Skip to content

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

JavaScript

v0.1.1: Media/Satellite/Inspect/Proof polish + Settings tab (#8)

OsintMeThat56938ffe2313
diff --git a/.gitignore b/.gitignore
index d8b9bdb..f1c9dd1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -78,6 +78,7 @@ src/azimut/static/
# Local tooling / assistant configs
CLAUDE.md
.claude/
+.cheatsheet
# PyInstaller local output
dist-bin/
diff --git a/README.md b/README.md
index 073a724..66c1fed 100644
--- a/README.md
+++ b/README.md
@@ -14,14 +14,15 @@ journalists, researchers.
fix a point on the map (English *azimuth*). A fitting namesake for a geolocation
workbench: fix a direction, fix a location.*
-## v1 — Proof Studio
+## v0.1.1 — Proof Studio
| Tool | What it does |
|------|--------------|
-| **Media Library** | Import local files or download by URL (X, Telegram, TikTok, YouTube… via yt-dlp) → clean local file + metadata + SHA-256. |
-| **Satellite** | Coordinates → imagery crop with crosshair and recorded provenance (provider, zoom, date, attribution). Esri World Imagery by default, bring-your-own-key providers supported. |
-| **Proof Composer** | Compose panels side by side, annotate with colored shapes (same color = same feature), comments, legend → export `proof.png` + a re-editable spec. |
-| **Post Composer** | Turn a proof into a publishable post: coordinates in all formats, plus code, attribution, character count. Copy-paste ready — Azimut never posts for you. |
+| **Media Library** | Import local files or download by URL (X, Telegram, TikTok, YouTube, Instagram… via yt-dlp, with a gallery-dl fallback for image-only posts) → clean local file + metadata + SHA-256. Multi-photo posts open a picker. |
+| **Inspect** | Scratch workspace over any photo/video: frame adjustments, editable crop, sharpest-frame capture, hand-made collage with per-piece warp/scale/rotate — nothing enters the case until you save. |
+| **Satellite** | Coordinates or place name → imagery crop, with select-area capture, map rotation, measurement tools, and reference-image overlays. Esri/OSM by default; add your own Mapbox/Google key for more basemaps (stored locally, never shared). |
+| **Proof Composer** | Compose panels side by side, annotate with colored shapes and text (same color = same feature), reorderable legend → export `proof.png` + a re-editable spec. |
+| **Post Composer** | Turn a proof into a publishable thread: coordinates in all formats, plus code, attribution, character count, RTL-safe text. Copy-paste ready — Azimut never posts for you. |
Every tool works **one-shot** (no setup, scratch session) or inside a **case**
— a plain directory holding the whole investigation.
diff --git a/docs/KEYED_PROVIDERS.md b/docs/KEYED_PROVIDERS.md
new file mode 100644
index 0000000..15e75d7
--- /dev/null
+++ b/docs/KEYED_PROVIDERS.md
@@ -0,0 +1,174 @@
+# Keyed imagery providers — Mapbox & Google (implementation brief)
+
+> Build spec for a future agent. Goal: let a user add their **own** Mapbox and
+> Google Maps Platform API keys in-app, then select **Mapbox Satellite** and
+> **Google Satellite** as basemaps in the Satellite tab — with every existing tool
+> (rotate, measure, capture, reference windows) working over them exactly like Esri.
+>
+> Read alongside SPEC.md §6 "v1 notes → Tile providers" (legal-only policy) and the
+> tile engine [`src/azimut/engine/tiles.py`](../src/azimut/engine/tiles.py).
+
+## 0. Non-negotiable legal rules (decided — do not relax)
+
+These come from Google's and Mapbox's terms; they drive the whole design.
+
+| Rule | Why |
+|------|-----|
+| Keys are **user-supplied**, stored **locally**, **never** bundled into a shared case/zip. | Principle 7; keys are the user's own billing identity. |
+| Core features never require a key. Key-less providers (Esri, OSM) stay the default. | Principle 7. |
+| **Never** ship/suggest/document unofficial endpoints (`mt1.google.com`, `khms*`, …). Only official APIs. | Existing legal-only policy. |
+| **Google tiles must NOT be cached to disk.** Google's Map Tiles API forbids pre-fetch/store/cache/offline use of tiles. | [Map Tiles API Policies](https://developers.google.com/maps/documentation/tile/policies). |
+| A Google **capture** is allowed only as a **flattened, attributed screenshot** (single PNG, attribution burned in). It must never be a store of raw tiles. | Google Geo Guidelines permit screenshots in reports/periodicals ≤5,000 copies **with attribution**; the anti-cache clause forbids tile hoarding. The two are different acts. |
+| Every capture keeps provider **attribution** (Google/Mapbox + data providers, e.g. Maxar) unmodified. For Google it is **burned into the image footer** (non-optional). | Attribution is a condition of the allowed use, not a courtesy. |
+
+### Per-provider capability matrix (the model to encode)
+
+| Provider | `needs_key` | auth style | `capturable` | `cacheable` (tile disk cache) | attribution source |
+|----------|:-----------:|------------|:------------:|:-----------------------------:|--------------------|
+| Esri World Imagery | no | — | yes | yes | static string (current) |
+| OpenStreetMap | no | — | yes | yes | static string (current) |
+| **Mapbox Satellite** | yes | access token in URL | yes | yes¹ | `© Mapbox © OpenStreetMap` (+ Maxar) |
+| **Google Satellite** | yes | **session token** | yes (flattened+attributed only) | **NO** | dynamic copyright from viewport endpoint |
+
+¹ Mapbox: display + static-image capture with attribution is permitted; verify the
+user's plan-level caching/redistribution limits before enabling an aggressive
+persistent cache. Default to a modest cache, attribution always on.
+
+## 1. Data model — `settings.json`
+
+Extend `DEFAULT_SETTINGS` in [`src/azimut/config.py`](../src/azimut/config.py). `api_keys`
+already exists; add first-class keyed providers and usage counters so the user
+doesn't hand-write XYZ templates.
+
+```jsonc
+{
+ "api_keys": {
+ "mapbox": "pk.....", // Mapbox public access token
+ "google": "AIza...." // Google Maps Platform API key
+ },
+ "tile_providers": [ /* still supported for custom/self-hosted XYZ */ ],
+ "usage": { // per-provider monthly counters (§6)
+ "google": { "2026-07": 1234 },
+ "mapbox": { "2026-07": 87 }
+ }
+}
+```
+
+Keep back-compat: a user with only `api_keys.mapbox`/`google` set gets the built-in
+keyed providers below automatically — no `tile_providers` entry needed.
+
+## 2. Provider model — `tiles.py`
+
+Extend the `Provider` dataclass with the capability flags and an optional
+session-token hook:
+
+```python
+@dataclass(frozen=True)
+class Provider:
+ # ...existing fields...
+ capturable: bool = True # may a saved capture be filed from it?
+ cacheable: bool = True # may its tiles be written to a disk cache?
+ attribution_burn: bool = False # force attribution stamped into the image
+ session: str | None = None # provider kind needing a token: "google"
+```
+
+`all_providers()` gains the built-in keyed providers when the matching key is
+present in `api_keys`:
+
+- **Mapbox Satellite** — `capturable=True, cacheable=True`
+ URL: `https://api.mapbox.com/styles/v1/mapbox/satellite-v9/tiles/512/{z}/{x}/{y}?access_token={key}`
+ (`satellite-streets-v12` for a labelled variant; `max_zoom=22`, `imagery=True`).
+ **512px tiles, not 256**: Mapbox bills 256px tiles 4× vs 512px for the same
+ ground area at the same m/px (one 512 tile at z-1 = four 256 tiles at z).
+- **Google Satellite** — `capturable=True, cacheable=False, attribution_burn=True, session="google"`, `imagery=True`, `max_zoom=22`. URL template resolved at fetch time (needs a live session token, see §3).
+
+`fetch_crop` / the frontend tile layer must:
+- refuse to build a saved capture when `provider.capturable is False` (none today, but the flag must gate the code path);
+- skip the disk cache entirely when `provider.cacheable is False`;
+- stamp attribution into the footer when `attribution_burn is True` (route it into the existing Proof Composer/capture footer, and ensure the Satellite capture PNG itself carries it).
+
+## 3. Google Map Tiles API — session-token adapter
+
+Google is **not** a static `{key}` URL. Add a small adapter (e.g.
+`src/azimut/engine/google_tiles.py`) that mints and caches a session token, then
+hands the rest of the pipeline a normal XYZ template.
+
+1. **Create session** (once, cache it):
+ `POST https://tile.googleapis.com/v1/createSession?key={API_KEY}`
+ body: `{"mapType":"satellite","language":"en-US","region":"US"}`
+ → `{"session":"<token>","expiry":"<unix>","tileWidth":256,"tileHeight":256,"imageFormat":"jpeg"}`
+2. **Tiles** (standard slippy XYZ):
+ `GET https://tile.googleapis.com/v1/2dtiles/{z}/{x}/{y}?session={token}&key={API_KEY}`
+3. **Refresh** the token when `expiry` passes (or on 401/403), transparently.
+4. **Attribution**: fetch the viewport copyright string and display/burn it:
+ `GET https://tile.googleapis.com/tile/v1/viewport?session={token}&key={API_KEY}&zoom={z}&north=&south=&east=&west=`
+ → `copyright` field (e.g. `"Map data ©2026 Google, Maxar Technologies"`). Do not
+ reduce it to just "Google".
+5. Cache the token in memory (and optionally a short-lived on-disk token file — the
+ **token**, never tiles). Session params (mapType) are part of the token identity.
+
+Both the live Leaflet layer and backend `fetch_crop` consume the resolved URL from
+step 2 — so once the token exists, Google behaves like any XYZ provider and all
+tools work unchanged.
+
+## 4. Frontend — API keys settings tab
+
+New settings/options page (SPEC §7 "Settings & secrets"). Minimal:
+
+- Fields: **Mapbox token**, **Google Maps Platform key** — saved to `api_keys`.
+ Password-style inputs, "how to get one" help links, per-key **test** button
+ (Mapbox: fetch one tile; Google: `createSession`).
+- Keys are app-wide (not per-case). Never written into a case folder or export bundle.
+- On save, the keyed providers appear in the Satellite basemap selector automatically.
+
+### Basemap selector behaviour (Satellite tab)
+
+- The bottom-of-map basemap picker lists all `all_providers()`, keyed ones included.
+- When the selected provider has `capturable=False`, **disable the capture button**
+ with a tooltip ("view-only basemap"). (No built-in provider is view-only today,
+ but wire the gate now.)
+- Google + Mapbox render in the live Leaflet map via `L.tileLayer(resolvedUrl)`;
+ keep the existing rotate/measure/reference-window behaviour untouched.
+
+## 5. Tile disk cache (respect `cacheable`)
+
+If/when a disk tile cache lands (SPEC §9 open question):
+- Cache tiles **only** for `cacheable=True` providers (Esri, OSM, Mapbox).
+- **Never** cache Google tiles — re-fetch each time; lean on the monthly counter to
+ stay in free tier. Honour any `Cache-Control` headers Google returns.
+
+## 6. Monthly usage counter
+
+SPEC §7 already promises per-provider monthly counters. Implement here because
+keyed providers are billed:
+
+- Increment `usage.<provider>.<YYYY-MM>` per outbound tile request (Google, Mapbox).
+- Surface a small readout in the settings tab and near the basemap selector
+ ("Google: 12,430 tiles this month").
+- Optional soft cap: warn / block new fetches when a user-set monthly limit is hit
+ (protects the free tier; for Google it also limits exposure).
+- Counting is local bookkeeping only — no telemetry (principle 1).
+- Billing units verified (2026-07): both bill **per tile served** — Google 2D Map
+ Tiles SKU = "Request that returns a 2D map tile" (sessions are free), Mapbox
+ Static Tiles = per tile request when used with Leaflet. Free tiers: Google
+ 100k/month, Mapbox 200k/month. Metered tiles are proxied through the backend
+ so the counter matches billing exactly (browser cache hits never re-count).
+
+## 7. Tests (required — repo rule)
+
+- `tiles.py`: keyed providers appear in `all_providers()` only when their key is
+ present; `capturable`/`cacheable` flags parsed and defaulted correctly.
+- `google_tiles.py`: session token minted, cached, and refreshed on expiry
+ (mock the HTTP calls — no real network); viewport copyright parsed.
+- Capture path: `capturable=False` blocks a saved capture; `attribution_burn=True`
+ stamps the footer; `cacheable=False` bypasses the cache.
+- Usage counter increments per month key and rolls over correctly.
+- Back-compat: existing Esri/OSM capture tests stay green.
+
+## 8. Out of scope (future, separate specs)
+
+- **Street View** (Google Street View Static API) — a distinct ground-imagery tool,
+ not a basemap; already sketched in SPEC §v2 "Ground Imagery".
+- **Google Photorealistic 3D Tiles** — needs a WebGL engine (MapLibre/Cesium), lands
+ only after the MapLibre migration (SPEC §7); a 3D scene, not a flat capture.
+- **Mapillary**
\ No newline at end of file
diff --git a/docs/SPEC.md b/docs/SPEC.md
index 1eacdc9..4736622 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -149,10 +149,10 @@ get media in, annotate the match, publish the proof.
| Tab | What it does |
|-----|--------------|
-| ✅ **Media Library** | The case's media shelf. Import local files (drag & drop) or download by URL (X, Telegram, TikTok, YouTube, … via yt-dlp) → clean local file + metadata JSON + sha256. Every media becomes a `media` entity. A **facet bar** groups the shelf on the fly — auto **type/source facets** (Images, Videos, Collages, Imports, Downloads, Other, derived from `kind` + `source`) alongside the user's **virtual folders**. Items can be assigned a **virtual folder** (stored in sidecar) and annotated with **notes**; an info modal surfaces full provenance (source URL, title, uploader, duration) + editable notes + folder; images show a **lightbox** on click. |
-| ✅ **Inspect** | A scratch workspace over any photo/video — **nothing enters the case until Save**. **Selection** (video): scrub, step, scan *sharpest* frames, capture into a transient tray; a gear tunes the whole clip (brightness…) for an optional enhanced-video export. **Frame**: per-frame brightness/contrast/saturation/gamma/sharpness/grayscale/invert/rotate + interactive **crop** (applied live in the preview + tray thumbnails, still re-croppable), with a fold-out **Analyze** (histogram, EXIF, ELA *hint*). **Collage**: **multiple collages per session** (tab strip to add/switch/delete). Per piece: drag, **uniform-scale**/**rotate** (a compact toolbar floats above the piece, off the image, or panel ±/↺↻), **corner-warp**, **Front/Back** ordering, **Delete** key, and **per-piece crop** (editor over the piece's snapshot, baked before the warp — the piece's quad is re-projected to the crop so proportions stay correct and it stays in place). Tray frames (thumbnails show each frame's current adjustments) compose on a full-bleed scratch surface into a hand-made panorama. Each collage exports as a **transparent PNG of just its pieces, auto-trimmed to their bounds** — no manual canvas size. Auto-stitch = later. **Save**: tick which of {enhanced video, adjusted frames, each collage} to file — each re-derived full-res on the backend with provenance back to its source, into an optional folder; every collage shows a **true-to-export composited miniature** (the real backend warp, on a transparency checker) in the picker. Frames captured from a tuned clip inherit its look; collage pieces are **frozen snapshots** taken when added. The whole workspace can be **saved as a reopenable session** (`inspect-session` entity, spec in `inspect/`) — reload it later from the sidebar with every frame/adjustment/collage (all of them) intact; re-saving a reopened session **overwrites it in place** (even after a rename). Adjust/analysis controls come from self-describing filter/analysis registries. |
-| ✅ **Satellite** | Enter/click coordinates, then **Save place** (a navigable `place` — coordinates only, no image, clickable to fly back) **or Capture** (a sourced imagery crop → `capture` image entity). Capture options: **marker style** (crosshair / Google-Maps pin / none) baked in, crop-size + **capture-frame outline** (previewed on hover, capture-only), **map rotation** (off-north; capture matches the on-screen heading, bearing in provenance). **Move-pin mode** decouples the marker from center — drag it anywhere in frame (e.g. bottom of shot) and the **recorded coordinates follow the pin** for both actions. Captures are images (open to view, not map-navigable); places are the clickable points. The tool's side panel lists both in **collapsible** sections — **Places** (fly the map back) and **Captures** (open the full image) — each with an inline **title + note editor**; the case sidebar's info panel is the same editor for any capture/place/media. Provenance (provider, zoom, date, bearing, marker, center) recorded — feeds the composer. XYZ tile-provider abstraction (see note below). Editable title + notes per capture. |
-| ✅ **Proof Composer** | The heart of v1. Compose panels in a **multi-row grid** (frames, photos, satellite crops, imported screenshots) — arrange side by side *and* stack rows (↑↓ per panel) so the composite stays near-square instead of a wide bandeau. Each panel can be **resized** (± per panel, 40–250%) — its drawn elements scale with it, and shorter panels bottom-align in their row. A toggleable **tweet-crop guide** (16:9 / 4:5) dims whatever X would centre-crop; a **magic tweet-fit** button auto-repacks the panels into rows to land closest to the active guide's aspect (16:9 default) and resets panel sizes. Draw colored boxes/ellipses/lines/arrows, multi-point **curves** (rounded, click points + double-click to finish) and **text labels** with the mouse — same color = same feature across panels. Every element stays **editable after placing**: boxes/ellipses/text via transformer handles (text corner-drag = font size), lines/arrows/curves via draggable per-vertex handles; selecting an element lets you change its **color and stroke/font size live**, **copy/paste/duplicate** it (Ctrl+C/V/D, cascading offset), and **drag it onto any panel** (it re-binds to whatever panel it's dropped over). Palette presets **+ custom color picker**. Legend **annotations are written per color** (one note per feature) and auto-flow into up to 3 columns; a separate **element list** (id + kind) selects/copies/deletes individual shapes. Optional per-panel captions (**off by default** except satellite crops). A **Coordinates + Source** header (above the panels) auto-fills from them: coordinates from the first satellite panel (falls back to the next if it's deleted), source **traced through the derivation chain** back to the downloaded original (a collage/frame from a video resolves to that video's link) — a source is **always a link**, so a disk-uploaded file counts as none; both are editable and flag a **!** while empty. These carry into the **Post Composer** (on *To Post* export or when attaching the proof there). An **Advanced** panel exposes the trickier knobs: independent **caption / legend / footer font sizes** and an **editable footer** (blank = automatic imagery/source attribution). Numbered feature legend; export `proof.png` + re-editable JSON spec (`notes` per color, panel `row`/`scale`, `coords`/`coordsText`, `source`, `caption/legend/footerSize`, `footer`) saved in `proofs/`. |
+| ✅ **Media Library** | The case's media shelf. Import local files (drag & drop) or download by URL (X, Telegram, TikTok, YouTube, … via yt-dlp, with a **gallery-dl fallback** for image-only posts yt-dlp's video-first extractors drop — photo tweets, direct image links, Instagram, Facebook photos; a small **Telegram photo scraper** additionally fills in photos on mixed video+photo albums, which yt-dlp's Telegram extractor silently ignores) → clean local file + metadata JSON + sha256, with a **Title** field auto-filled from the extracted title. A link with several attachments (e.g. a tweet with multiple photos/a video) opens a **picker** to choose which ones to fetch, each with its own editable Title before download; a single-item link downloads straight away as before. Every media becomes a `media` entity. A **facet bar** groups the shelf on the fly — auto **type/source facets** (Images, Videos, Collages, Imports, Downloads, Other, derived from `kind` + `source`) alongside the user's **virtual folders**. Items can be assigned a **virtual folder** (stored in sidecar) and annotated with **notes**; an info modal surfaces full provenance (source URL, title, uploader, duration) + editable notes + folder; images show a **lightbox** on click. |
+| ✅ **Inspect** | A scratch workspace over any photo/video — **nothing enters the case until Save**. **Selection** (video): scrub, step, scan *sharpest* frames, capture into a transient tray; a gear tunes the whole clip (brightness…) for an optional enhanced-video export. **Frame**: per-frame brightness/contrast/saturation/gamma/sharpness/grayscale/invert, a **view-only zoom/pan/rotate** viewer (never saved — middle-drag turns the image around the grabbed point, marked by a "target", Google-Earth style; composes over any prior zoom/pan/rotate), and an **editable crop** — draw or nudge its 8 handles, **aspect-lock presets + numeric px entry**, **Enter/Apply** commits to a cropped preview, re-open (button or **double-click**) to edit the original — with a fold-out **Analyze** (histogram, EXIF, ELA *hint*). **Collage**: **multiple collages per session** (tab strip to add/switch/delete). Per piece: drag, **round corner handles warp**, **square side handles uniform-scale** (composes with the warp, holds up on an already-warped piece), a **rotate knob** on a stem that **follows the piece**; a small top bar carries only the **ghost** preview + **±1 stacking**, while the right panel keeps precise scale/rotate (±/↺↻) and all-the-way **Front/Back**; **Delete** removes it. **Per-piece crop** is the same editable box (handles, aspect lock, numeric) over the piece's snapshot, baked before the warp — the quad is re-projected to the crop so proportions stay correct and it stays in place. Tray frames (thumbnails show each frame's current adjustments) compose on a full-bleed scratch surface into a hand-made panorama. Each collage exports as a **transparent PNG of just its pieces, auto-trimmed to their bounds** — no manual canvas size. Auto-stitch = later. **Save**: tick which of {enhanced video, adjusted frames, each collage} to file — each re-derived full-res on the backend with provenance back to its source, into an optional folder; every collage shows a **true-to-export composited miniature** (the real backend warp, on a transparency checker) in the picker. Frames captured from a tuned clip inherit its look; collage pieces are **frozen snapshots** taken when added. The whole workspace can be **saved as a reopenable session** (`inspect-session` entity, spec in `inspect/`) — reload it later from the sidebar with every frame/adjustment/collage (all of them) intact; re-saving a reopened session **overwrites it in place** (even after a rename). Adjust/analysis controls come from self-describing filter/analysis registries. |
+| ✅ **Satellite** | Enter/click coordinates, then **Save place** (a navigable `place` — coordinates only, no image, clickable to fly back) **or Capture** (a sourced imagery crop → `capture` image entity, **filed in `media/`** so it also lists in the Media Library and opens in Inspect). A single **split capture button** re-runs whichever mode was used last — **Capture** for a centred **standard size** (Tweet 16:9 / Square / OG card / Wide / custom), or **Select area**, which arms a **mouse marquee** to drag a rectangle (live px/dimension readout) for an optional **ratio lock** (16:9 / 4:3 / 1:1 / free) — with its arrow opening a compact **mode/size/ratio/resolution popover** (closes on outside click) and a **resolution** control (1× / 2× / provider max-zoom, sized so 2×/max always yield a sharper file on every built-in preset) that captures a deeper zoom. **Marker style** (crosshair / Google-Maps pin / none) baked in; centred-Capture **frame outline** previewed on hover. **Map rotation** — **middle-drag turns the map around the grabbed point** (sober target marker, Google-Earth style), click the bearing to **type an exact angle**, click the compass rose to reset north (capture matches the on-screen heading, bearing in provenance). **Move-pin mode** decouples the marker from center — drag it anywhere in frame (e.g. bottom of shot) and the **recorded coordinates follow the pin** for both actions. **Two dates per capture**: the **capture timestamp** and the **imagery acquisition date** (Esri best-effort, if known) — both recorded and shown. **Map workspace**: toggle an **OSM labels overlay** (roads / place names over the imagery — disabled over a street base map, where it'd only double the labels), read the imagery acquisition date under the crosshair (shown as an unobtrusive corner pill), go **true browser fullscreen**, **measure** distance / area / **angle** (reported as the acute + obtuse pair), and float **reference windows** over the map (pick any case **image or video**; drag / roll-up / resize — images wheel-zoom & pan, videos get a native player) to eyeball the shot you're geolocating against the imagery — a **session-only scratch aid, never captured or saved**. The tool's side panel lists both in **collapsible** sections — **Places** (fly the map back) and **Captures** (open the full image, or **go to** their coordinates — also from the case sidebar) — each with an inline **title + note editor**; the case sidebar's info panel is the same editor for any capture/place/media. A collapsible **Open in…** list jumps to external maps we can't embed (Google/Earth, Apple, Bing, Yandex, Satellites.pro, Copernicus, Zoom Earth) at the current target. Provenance (provider, zoom, both dates, bearing, marker, center) recorded — feeds the composer. XYZ tile-provider abstraction (see note below). Editable title + notes per capture. |
+| ✅ **Proof Composer** | The heart of v1. Compose panels in a **multi-row grid** (frames, photos, satellite crops, imported screenshots) — arrange side by side *and* stack rows (↑↓ per panel) so the composite stays near-square instead of a wide bandeau. Each panel can be **resized** (± per panel, 40–250%) — its drawn elements scale with it, and shorter panels bottom-align in their row. A toggleable **tweet-crop guide** (16:9 / 4:5) dims whatever X would centre-crop; a **magic tweet-fit** button auto-repacks the panels into rows to land closest to the active guide's aspect (16:9 default) and resets panel sizes. Draw colored boxes/ellipses/lines/arrows, multi-point **curves** (rounded, click points + double-click to finish) and **text labels** (optional **frame and/or background box**, from the Elements tab) with the mouse — same color = same feature across panels. Every element stays **editable after placing**: boxes/ellipses/text via transformer handles (text corner-drag = font size), lines/arrows/curves via draggable per-vertex handles; selecting an element lets you change its **color and stroke/font size live**, **copy/paste/duplicate** it (Ctrl+C/V/D, cascading offset), and **drag it onto any panel** (it re-binds to whatever panel it's dropped over). Palette presets **+ custom color picker**. Legend **annotations are written per color** (one note per feature), **manually reorderable** from the Annotations tab, and auto-flow into up to 3 columns; a separate **element list** (id + kind) selects/copies/deletes/**reorders** individual shapes (order = z-order within their panel). Optional per-panel captions (**off by default** except satellite crops). A **Coordinates + Source** header (above the panels) auto-fills from them: coordinates from the first satellite panel (falls back to the next if it's deleted), source **traced through the derivation chain** back to the downloaded original (a collage/frame from a video resolves to that video's link) — a source is **always a link**, so a disk-uploaded file counts as none; both are editable and flag a **!** while empty. These carry into the **Post Composer** (on *To Post* export or when attaching the proof there). An **Advanced** panel exposes the trickier knobs: independent **caption / legend / footer font sizes** and an **editable footer** (blank = automatic imagery/source attribution). Feature legend (color dot only, numbered in the Annotations tab for reference); export `proof.png` + re-editable JSON spec (`notes`/`legendOrder` per color, panel `row`/`scale`, `coords`/`coordsText`, `source`, `caption/legend/footerSize`, `footer`) saved in `proofs/`. |
| ✅ **Post Composer** | Build a GeoConfirmed-style thread from a proof. Tweet 1 = `Place - Plus code`, description, decimal coordinates (6 digits), `@GeoConfirmed` mention, source. Tweet 2 = optional media (Video / Image(s), removable), with media picked from the case library. Add extra context tweets; per-tweet character count; copy-per-tweet or copy-all. **Save drafts** (in `exports/`, reopenable from the sidebar as `post` entities) and **Publish** (copies the thread and opens X compose prefilled). Copy-paste ready — Azimut never posts on your behalf. |
| ✅ **Case sidebar** | Always visible, three sections. **Case Notes** (`notes.md`). **Saved work** — every artifact, auto-grouped by the tool that produced it (Media Library / Inspect / Satellite / Proof Composer / Post Composer, from `provenance.by`); suggested entities pinned on top to confirm/dismiss; deleting here removes the item **everywhere** (drops its file — danger confirm). **My work** — the analyst's own **nested folders** (`/`-separated, e.g. `Sources/Telegram`), empty until you **drag** items in from Saved work; an item filed here stays in Saved work too (lives in both); deleting here only **unfiles** it (light confirm), and removing a folder cascades its subtree back to Saved work. Styled confirm dialogs, not browser popups. Create/open/promote/**rename**/**delete** cases from the switcher — names must be **unique** (case-insensitive, enforced on create/rename/promote); delete wipes the **whole case folder** and everything in it, gated behind typing `DELETE` in uppercase. |
@@ -177,8 +177,13 @@ v1 notes:
thing. Deleting a media / satellite capture / proof / post in its tool removes
the matching entity, and deleting the entity in the sidebar removes the
underlying file(s). One satellite capture ⇄ one `capture` entity (tied by file
- path): the entity title defaults to the coordinates but is editable, and
- deleting either side removes the other. A `place` is coordinates only — no file.
+ path): a capture is filed through the **media pipeline** (lives in `media/`,
+ hashed + thumbnailed, shown in the Media Library, openable in Inspect) but under
+ a `capture` entity — not `media` — carrying its coordinates; its media sidecar's
+ `source.type == "satellite"` is what tells the two apart. Captures never dedupe
+ (1:1 with their entity). The entity title defaults to the coordinates but is
+ editable, and deleting either side removes the other. A `place` is coordinates
+ only — no file.
- The previous frame-geolocator engine is **not** reused; v1 is a fresh,
minimal implementation. Frame extraction and image adjustments ship in the
**Inspect** tab (above); v1 also lets you bring images (screenshots/exports)
@@ -228,7 +233,7 @@ not a commitment. Promote into a table above when a workflow firms up; delete if
it stops making sense. One line each.
**Toward v2 (GEOINT suite) — mostly grow existing v2 tools:**
-- **More satellite basemaps** — Sentinel-2 (date slider), OSM context, user-keyed Bing/Google (grows Satellite Compare).
+- **More satellite basemaps** — Sentinel-2 (date slider), OSM context, user-keyed Bing (grows Satellite Compare). ✅ User-keyed **Mapbox & Google** basemaps + API-keys settings tab + monthly usage counters are speced in [KEYED_PROVIDERS.md](KEYED_PROVIDERS.md) (with the per-provider capture/cache legal rules).
- **Copernicus easy link / viewer** — quick link into `browser.dataspace.copernicus.eu` (grows Satellite Compare).
- **Sat-vs-screen compare** — overlay/swipe/pixel-diff alignment aid; assist, never an auto-verdict (principle 5). Grows Image Compare.
- **Weather / METAR history** — corroborate a claimed date+coords from free archives; pairs with Shadow Clock into a chronolocation panel.
@@ -261,15 +266,15 @@ it stops making sense. One line each.
facts; the analyst reasons and decides.
- No rebuilding of specialized OSINT services (email finders, people search, …) —
orchestrate them instead (principle 4).
-- No scraping features designed to evade platform blocks; the downloader uses
- yt-dlp as-is and inherits its capabilities.
+- No scraping features designed to evade platform blocks; downloads use
+ yt-dlp and gallery-dl as-is and inherit their capabilities.
- No auto-posting to any platform — Azimut prepares posts, the human publishes.
- No paid API dependencies, ever, for core features.
## 7. Architecture
- **Backend**: Python 3.11+, FastAPI serving on `localhost`. All processing
- (ffmpeg, yt-dlp, OpenCV, pytesseract, …) runs in the backend.
+ (ffmpeg, yt-dlp, gallery-dl, OpenCV, pytesseract, …) runs in the backend.
- **Frontend**: web UI served by the backend, opened in the default browser
(pywebview window revisited later). Tabs on the left, tool canvas on the right,
case sidebar. **Svelte** + Leaflet (maps) + Konva/canvas (annotation) — decided,
@@ -281,7 +286,7 @@ it stops making sense. One line each.
raster XYZ stitching). Phase 2 = pitch + terrain + oblique **3D capture**,
with **pitch recorded in provenance** alongside bearing so a tilted crop
stays auditable.
-- **Settings & secrets**: an in-app options page manages optional API keys/secrets
+- ✅ **Settings & secrets**: an in-app options page manages optional API keys/secrets
(stored locally, **never** bundled into a shared case) plus per-provider
**monthly usage counters** so a user tracks a keyed quota (Street View, Google
imagery, …) before hitting it. Core features never require a key (principle 7);
@@ -312,7 +317,7 @@ it stops making sense. One line each.
7. ✅ **M6 — polish pass** across all five tools: Media facet bar, Satellite
places/captures split + move-pin, Proof Composer curves/text/live-editable
elements, Post Composer proof picker, case rename/delete + unique names.
-8. **M7 — Launch v1**: pip-installable package (frontend bundled in the wheel),
+8. ✅ **M7 — Launch v1**: pip-installable package (frontend bundled in the wheel),
AGPL-3.0 `LICENSE`, cross-platform binaries via CI (Windows/Linux/macOS),
PyPI publish, `v0.1.0` GitHub release, demo video (media → satellite → proof).
9. **M8+**: v2 GEOINT suite (auto-panorama, reverse-search — see backlog) by
@@ -320,7 +325,7 @@ it stops making sense. One line each.
## 9. Open questions
-- ~~License: MIT vs AGPL.~~ **Decided: AGPL-3.0-only** ✅ (root `LICENSE` in place).
+- **Decided: AGPL-3.0-only** ✅ (root `LICENSE` in place).
- Entity schema details: attribute vocabularies per type, `same-as` merge
semantics, confidence levels — draft during M0, freeze at v1 release.
- Proof spec JSON format: design fresh at M3 (the old compose_proof format is a
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index 5e26560..9509a56 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -10,7 +10,10 @@
import ProofComposer from './tools/ProofComposer.svelte';
import PostComposer from './tools/PostComposer.svelte';
import Inspector from './tools/Inspector.svelte';
+ import Settings from './tools/Settings.svelte';
+ // the left rail carries the investigation tools; Settings lives behind the
+ // topbar gear instead — app plumbing, not part of the working flow
const TOOLS = [
{ id: 'media', label: 'Media', icon: 'media', component: MediaLibrary },
{ id: 'inspect', label: 'Inspect', icon: 'inspect', component: Inspector },
@@ -18,16 +21,26 @@
{ id: 'proof', label: 'Proof', icon: 'proof', component: ProofComposer },
{ id: 'post', label: 'Post', icon: 'post', component: PostComposer },
];
+ const ALL_TOOLS = [
+ ...TOOLS,
+ { id: 'settings', label: 'Settings', icon: 'settings', component: Settings },
+ ];
- const ActiveTool = $derived(TOOLS.find((t) => t.id === uiState.tool)?.component ?? MediaLibrary);
-
- // deep-linkable tools: #media #satellite #proof #post
+ // deep-linkable tools: #media #satellite #proof #post #settings
const fromHash = location.hash.slice(1);
- if (TOOLS.some((t) => t.id === fromHash)) uiState.tool = fromHash;
+ if (ALL_TOOLS.some((t) => t.id === fromHash)) uiState.tool = fromHash;
$effect(() => {
history.replaceState(null, '', `#${uiState.tool}`);
});
+ // Tools mount lazily on first visit, then stay mounted (hidden via CSS) so
+ // unsaved editor state — a half-composed proof, a collage in progress —
+ // survives switching tabs to grab another capture or media.
+ const visited = $state({ [uiState.tool]: true });
+ $effect(() => {
+ visited[uiState.tool] = true;
+ });
+
// Load the case list and reopen the last-used case (survives reloads).
initSession().catch(() => {});
</script>
@@ -43,6 +56,14 @@
<span class="local-badge" title="Everything stays on your machine — no accounts, no telemetry, no servers">
Your investigation. Your machine.
</span>
+ <button
+ class="btn btn-ghost btn-sm"
+ class:gear-active={uiState.tool === 'settings'}
+ title="Settings — API keys & usage"
+ onclick={() => (uiState.tool = 'settings')}
+ >
+ <Icon name="settings" size={16} />
+ </button>
<button
class="btn btn-ghost btn-sm"
title="Toggle case sidebar"
@@ -68,7 +89,13 @@
</nav>
<main class="canvas">
- <ActiveTool />
+ {#each ALL_TOOLS as tool (tool.id)}
+ {#if visited[tool.id]}
+ <div class="tool-host" class:hidden={uiState.tool !== tool.id}>
+ <tool.component />
+ </div>
+ {/if}
+ {/each}
</main>
{#if uiState.sidebarOpen}
@@ -130,6 +157,10 @@
background: var(--ok);
box-shadow: 0 0 6px var(--ok);
}
+ .gear-active {
+ color: var(--accent);
+ background: var(--accent-soft);
+ }
.main {
flex: 1;
display: flex;
@@ -170,4 +201,11 @@
min-width: 0;
background: var(--bg-0);
}
+ .tool-host {
+ width: 100%;
+ height: 100%;
+ }
+ .tool-host.hidden {
+ display: none;
+ }
</style>
diff --git a/frontend/src/components/CaseSidebar.svelte b/frontend/src/components/CaseSidebar.svelte
index 691ce80..eac9d82 100644
--- a/frontend/src/components/CaseSidebar.svelte
+++ b/frontend/src/components/CaseSidebar.svelte
@@ -1,6 +1,7 @@
<script>
import { api } from '../lib/api.js';
import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';
+ import { TOOL_GROUPS, groupKey } from '../lib/savedGrouping.js';
import Icon from './Icon.svelte';
import Modal from './Modal.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
@@ -33,6 +34,17 @@
// Entity types backed by a file on disk — deleting them everywhere drops the file.
const FILE_BACKED = new Set(['media', 'capture', 'proof', 'post', 'inspect-session']);
+ const VIDEO_EXTS = new Set(['mp4', 'mov', 'webm', 'mkv', 'avi', 'm4v']);
+ // Media entities normally carry the same `kind` the Media Library uses to tell
+ // video from image; fall back to the file extension for entities filed before
+ // that attr existed.
+ function isVideo(e) {
+ if (e.attrs?.kind) return e.attrs.kind === 'video';
+ const ext = e.attrs?.path?.split('.').pop()?.toLowerCase();
+ return !!ext && VIDEO_EXTS.has(ext);
+ }
+ const entityIcon = (e) => (e.type === 'media' && isVideo(e) ? 'video' : ENTITY_ICONS[e.type] ?? 'note');
+
// ── case notes (single notes.md) ─────────────────────────────────────────
let caseNotes = $state('');
let caseNotesLoadedFor = $state(null);
@@ -145,28 +157,27 @@
if (tool) uiState.tool = tool;
}
+ // Fly the Satellite map to a capture's recorded coordinates (its marker),
+ // matching its own zoom/bearing — the capture stays an image, this just
+ // navigates. Mirrors the "Go to" button in the Satellite panel.
+ function gotoCapture(entity) {
+ const lat = Number(entity.attrs?.lat);
+ const lon = Number(entity.attrs?.lon);
+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) return;
+ uiState.gotoCoords = {
+ lat,
+ lon,
+ zoom: Number(entity.attrs?.zoom),
+ bearing: Number(entity.attrs?.bearing),
+ };
+ uiState.tool = 'satellite';
+ }
+
// ── Saved work: every artifact, grouped by the tool that produced it ──────
// The grouping is derived from provenance.by — the honest record of origin —
- // so it fills itself as you work and needs no manual upkeep.
- const TOOL_GROUPS = [
- ['media-library', 'Media Library', 'image'],
- ['inspect', 'Inspect', 'inspect'],
- ['satellite', 'Satellite', 'satellite'],
- ['proof-composer', 'Proof Composer', 'proof'],
- ['post-composer', 'Post Composer', 'post'],
- ['user', 'Notes & manual', 'note'],
- ];
- const KNOWN_TOOLS = new Set(TOOL_GROUPS.map(([k]) => k).filter((k) => k !== 'user'));
- // Any filed image/video is media first — it belongs under Media Library no
- // matter which tool produced it (e.g. a frame saved from Inspect). Everything
- // else groups by the tool that made it. Reopenable Inspect *sessions* stay
- // under Inspect, since they're workspaces, not media.
- const groupKey = (e) => {
- if (e.type === 'media') return 'media-library';
- const by = e.provenance?.by;
- return KNOWN_TOOLS.has(by) ? by : 'user';
- };
-
+ // so it fills itself as you work and needs no manual upkeep. See
+ // lib/savedGrouping.js for the actual bucketing rule (media/captures always
+ // go under Media Library, regardless of which tool filed them).
const savedGroups = $derived.by(() => {
const buckets = new Map(TOOL_GROUPS.map(([k]) => [k, []]));
for (const e of confirmed) buckets.get(groupKey(e)).push(e);
@@ -550,7 +561,7 @@
<div class="suggest-note">Suggested — confirm or dismiss:</div>
{#each suggested as e (e.id)}
<div class="entity suggested">
- <Icon name={ENTITY_ICONS[e.type] ?? 'note'} size={14} />
+ <Icon name={entityIcon(e)} size={14} />
<div class="e-body">
<span class="e-label">{e.label}</span>
<span class="e-meta">{e.type} · {e.provenance?.by}</span>
@@ -706,11 +717,32 @@
onkeydown={(ev) => ev.key === 'Enter' && onEntityActivate(e)}
>
<Icon name="grip" size={13} />
- <Icon name={ENTITY_ICONS[e.type] ?? 'note'} size={14} />
+ <Icon name={entityIcon(e)} size={14} />
<div class="e-body">
<span class="e-label">{e.label}</span>
<span class="e-meta">{e.type}</span>
</div>
+ {#if e.type === 'capture' && e.attrs?.lat != null}
+ <button
+ class="btn btn-ghost btn-sm act"
+ title="Go to these coordinates on the map"
+ onclick={(ev) => { ev.stopPropagation(); gotoCapture(e); }}
+ >
+ <Icon name="crosshair" size={13} />
+ </button>
+ {/if}
+ {#if e.type === 'media' && e.attrs?.path}
+ <a
+ class="btn btn-ghost btn-sm act"
+ title="Open in new tab"
+ href={`/files/${caseState.current.id}/${e.attrs.path}`}
+ target="_blank"
+ rel="noreferrer"
+ onclick={(ev) => ev.stopPropagation()}
+ >
+ <Icon name="external" size={13} />
+ </a>
+ {/if}
<button
class="btn btn-ghost btn-sm act"
title="Info"
@@ -867,7 +899,10 @@
<div class="info-row"><span class="info-k">Zoom</span><span>z{infoEntity.attrs.zoom}</span></div>
{/if}
{#if infoData?.fetched_at}
- <div class="info-row"><span class="info-k">Date</span><span class="mono">{infoData.fetched_at.slice(0, 10)}</span></div>
+ <div class="info-row"><span class="info-k">Captured</span><span class="mono">{infoData.fetched_at.slice(0, 10)}</span></div>
+ {/if}
+ {#if infoData?.imagery_date}
+ <div class="info-row"><span class="info-k">Imagery</span><span class="mono">{infoData.imagery_date}</span></div>
{/if}
{:else if infoEntity.attrs?.content}
<div class="info-note-body">{infoEntity.attrs.content}</div>
@@ -900,6 +935,11 @@
<Icon name="arrowRight" size={13} /> Open in tool
</button>
{/if}
+ {#if infoEntity.type === 'capture' && infoEntity.attrs?.lat != null}
+ <button class="btn btn-ghost btn-sm" onclick={() => { gotoCapture(infoEntity); infoEntity = null; }}>
+ <Icon name="crosshair" size={13} /> Go to coords
+ </button>
+ {/if}
<div style="flex:1"></div>
<button class="btn" onclick={() => (infoEntity = null)}>Close</button>
{#if EDITABLE.has(infoEntity.type)}
diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelte
index d3b2bf0..d4cbf5a 100644
--- a/frontend/src/components/Icon.svelte
+++ b/frontend/src/components/Icon.svelte
@@ -17,6 +17,7 @@
chevronRight: 'm9 6 6 6-6 6',
chevronLeft: 'm15 6-6 6 6 6',
chevronDown: 'm6 9 6 6 6-6',
+ chevronUp: 'm6 15 6-6 6 6',
panelRight: 'M4 4h16a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1Zm11 0v16',
search: 'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm9 16-4.35-4.35',
trash: 'M4 7h16m-2 0-1 13H7L6 7m3 0V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m-6 4v6m4-6v6',
@@ -46,6 +47,10 @@
alert: 'M12 3 2.5 19.5h19L12 3Zm0 7v4m0 3.5h.01',
clock: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm0 4v5l3.5 2',
eye: 'M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Zm9.5-3a3 3 0 1 1 0 6 3 3 0 0 1 0-6Z',
+ eyeOff: 'M9.9 9.9a3 3 0 1 0 4.2 4.2M10.7 5.7A9.8 9.8 0 0 1 12 5.5c6 0 9.5 6.5 9.5 6.5a17.8 17.8 0 0 1-2.2 3M6.6 6.6C4 8.4 2.5 12 2.5 12S6 18.5 12 18.5c1.5 0 2.9-.4 4.1-1.1M3 3l18 18',
+ key: 'm21 2-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777Zm0 0L15.5 7.5m0 0 3 3L22 7l-3-3m-3.5 3.5L19 4',
+ shield: 'M12 21.5s7.5-3.7 7.5-9.3V5.4L12 2.5 4.5 5.4v6.8c0 5.6 7.5 9.3 7.5 9.3Z',
+ chart: 'M3.5 3.5v17h17m-4-5v-6m-5 6V8m-5 8.5v-3',
square: 'M5 5h14a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Z',
circle: 'M12 4a8 8 0 1 1 0 16 8 8 0 0 1 0-16Z',
line: 'M5 19 19 5',
@@ -56,8 +61,16 @@
inspect: 'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm9 16-4.35-4.35M8 11h6m-3-3v6',
crop: 'M6 2v14a2 2 0 0 0 2 2h14M2 6h14a2 2 0 0 1 2 2v14',
reset: 'M4 9a8 8 0 1 1-1.6 4.7M4 9H1m3 0V6',
+ undo: 'M8 5 4 9l4 4M4 9h10a6 6 0 0 1 0 12h-4',
+ redo: 'm16 5 4 4-4 4m4-4H10a6 6 0 0 0 0 12h4',
+ ghost: 'M5 20V10a7 7 0 0 1 14 0v10l-2.3-2-2.4 2-2.3-2-2.3 2-2.4-2-2.3 2ZM10 10h.01M14 10h.01',
sliders: 'M4 6h9m4 0h3M4 12h3m4 0h9M4 18h13m4 0h3M13 4v4m0 6v4m4-12v4',
wand: 'M4 20 13 11M15 3l1.1 3 3 1.1-3 1.1L15 11.3l-1.1-3-3-1.1 3-1.1L15 3ZM19.5 11.5l.6 1.8 1.8.6-1.8.6-.6 1.8-.6-1.8-1.8-.6 1.8-.6.6-1.8Z',
+ maximize: 'M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3M3 16v3a2 2 0 0 0 2 2h3m8 0h3a2 2 0 0 0 2-2v-3',
+ minimize: 'M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3M3 16h3a2 2 0 0 1 2 2v3m8 0v-3a2 2 0 0 1 2-2h3',
+ ruler: 'M4 15.5 15.5 4l4.5 4.5L8.5 20 4 15.5Zm3.5-.5 1.5 1.5m1-4.5 1.5 1.5m1-4.5L14 11',
+ polygon: 'M12 3.5 20 9.5l-3 9.5H7L4 9.5l8-6Z',
+ angle: 'M5 4v15h15M5 19 20 6',
};
</script>
diff --git a/frontend/src/lib/bidi.js b/frontend/src/lib/bidi.js
new file mode 100644
index 0000000..ac21149
--- /dev/null
+++ b/frontend/src/lib/bidi.js
@@ -0,0 +1,31 @@
+/**
+ * RTL-safe tweet text. A GeoConfirmed post often mixes RTL prose (Arabic,
+ * Hebrew) with LTR runs — decimal coordinates, plus codes, @mentions, URLs.
+ * Without direction control the Unicode bidi algorithm visually reorders
+ * those runs on X: the comma swaps around, punctuation jumps ends, the URL
+ * lands mid-sentence. Wrapping each LTR run in a Left-to-Right Isolate
+ * (U+2066 … U+2069) pins it in place; text without RTL passes through
+ * untouched, so LTR-only users never see a difference.
+ */
+
+// Hebrew, Arabic (incl. supplements/extended), and presentation forms.
+const RTL_CHARS = /[\u0590-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF]/;
+
+export const LRI = '\u2066'; // LEFT-TO-RIGHT ISOLATE
+export const PDI = '\u2069'; // POP DIRECTIONAL ISOLATE
+
+// LTR runs worth isolating: URLs, @mentions, plus codes, coordinate pairs.
+const LTR_RUN =
+ /https?:\/\/\S+|@\w+|\b[A-Z0-9]{4,8}\+[A-Z0-9]{2,3}\b|[-+]?\d{1,3}\.\d+\s*,\s*[-+]?\d{1,3}\.\d+/g;
+
+export function hasRtl(text) {
+ return RTL_CHARS.test(text ?? '');
+}
+
+/** Isolate direction-sensitive LTR runs when the text contains RTL script. */
+export function bidiSafe(text) {
+ if (!text || !hasRtl(text)) return text ?? '';
+ return text.replace(LTR_RUN, (run, offset, str) =>
+ str[offset - 1] === LRI ? run : LRI + run + PDI
+ );
+}
diff --git a/frontend/src/lib/bidi.test.js b/frontend/src/lib/bidi.test.js
new file mode 100644
index 0000000..fd6f345
--- /dev/null
+++ b/frontend/src/lib/bidi.test.js
@@ -0,0 +1,48 @@
+import { describe, it, expect } from 'vitest';
+import { bidiSafe, hasRtl, LRI, PDI } from './bidi.js';
+
+const ARABIC = 'قصف على المدينة';
+
+describe('hasRtl', () => {
+ it('detects Arabic and Hebrew, not Latin', () => {
+ expect(hasRtl(ARABIC)).toBe(true);
+ expect(hasRtl('עיר עתיקה')).toBe(true);
+ expect(hasRtl('Strike on the city, 48.8584, 2.2945')).toBe(false);
+ expect(hasRtl('')).toBe(false);
+ expect(hasRtl(null)).toBe(false);
+ });
+});
+
+describe('bidiSafe — isolates LTR runs inside RTL text', () => {
+ it('leaves LTR-only text completely untouched', () => {
+ const text = 'Kyiv - 8GXG+Q8\n50.450100, 30.523400\n@GeoConfirmed\nhttps://x.com/a/1';
+ expect(bidiSafe(text)).toBe(text);
+ });
+
+ it('wraps a coordinate pair so the comma cannot flip', () => {
+ const out = bidiSafe(`${ARABIC}\n50.450100, 30.523400`);
+ expect(out).toContain(`${LRI}50.450100, 30.523400${PDI}`);
+ });
+
+ it('wraps URLs, mentions and plus codes', () => {
+ const out = bidiSafe(`${ARABIC} @GeoConfirmed 8GXG+Q8 https://t.me/chan/42`);
+ expect(out).toContain(`${LRI}@GeoConfirmed${PDI}`);
+ expect(out).toContain(`${LRI}8GXG+Q8${PDI}`);
+ expect(out).toContain(`${LRI}https://t.me/chan/42${PDI}`);
+ });
+
+ it('keeps the RTL prose itself unwrapped', () => {
+ const out = bidiSafe(`${ARABIC}\nhttps://x.com/a/1`);
+ expect(out.startsWith(ARABIC)).toBe(true);
+ });
+
+ it('is idempotent — re-applying never double-wraps', () => {
+ const once = bidiSafe(`${ARABIC} 50.450100, 30.523400`);
+ expect(bidiSafe(once)).toBe(once);
+ });
+
+ it('handles empty/nullish input', () => {
+ expect(bidiSafe('')).toBe('');
+ expect(bidiSafe(null)).toBe('');
+ });
+});
diff --git a/frontend/src/lib/captureSize.js b/frontend/src/lib/captureSize.js
new file mode 100644
index 0000000..d62ffca
--- /dev/null
+++ b/frontend/src/lib/captureSize.js
@@ -0,0 +1,33 @@
+/**
+ * Satellite capture sizing: clamp a requested px size to what the backend
+ * accepts, and scale a base (view-zoom) crop up to a chosen output
+ * resolution (1×, 2×, "max") by capturing deeper zoom levels.
+ */
+
+export const SIZE_MIN = 256;
+export const SIZE_MAX = 4096;
+
+export function clampSize(v) {
+ return Math.min(Math.max(Math.round(Number(v) || 0), SIZE_MIN), SIZE_MAX);
+}
+
+/**
+ * Scale a base (view-zoom) crop to the chosen output resolution: capture `k`
+ * zoom levels deeper and multiply the pixel size by 2^k so the same ground
+ * footprint comes out sharper. `k` is walked back down (never below 0) until
+ * the scaled size fits SIZE_MAX — with SIZE_MAX sized generously enough that
+ * every built-in preset still gets a real multiplier at 2×/max, rather than
+ * being clamped straight back down to 1×.
+ */
+export function scaledCapture(baseW, baseH, resolution, viewZoom, providerMaxZoom) {
+ let k =
+ resolution === 'max' ? Math.max(0, providerMaxZoom - viewZoom) : Math.log2(resolution);
+ while (k > 0 && (baseW * 2 ** k > SIZE_MAX || baseH * 2 ** k > SIZE_MAX)) k -= 1;
+ const mult = 2 ** k;
+ return {
+ zoom: Math.min(viewZoom + k, providerMaxZoom),
+ width: clampSize(baseW * mult),
+ height: clampSize(baseH * mult),
+ mult,
+ };
+}
diff --git a/frontend/src/lib/captureSize.test.js b/frontend/src/lib/captureSize.test.js
new file mode 100644
index 0000000..aeec315
--- /dev/null
+++ b/frontend/src/lib/captureSize.test.js
@@ -0,0 +1,63 @@
+import { describe, it, expect } from 'vitest';
+import { clampSize, scaledCapture, SIZE_MIN, SIZE_MAX } from './captureSize.js';
+
+describe('clampSize', () => {
+ it('clamps to the min/max bounds', () => {
+ expect(clampSize(10)).toBe(SIZE_MIN);
+ expect(clampSize(999999)).toBe(SIZE_MAX);
+ });
+
+ it('rounds and falls back to the minimum for junk input', () => {
+ expect(clampSize(300.6)).toBe(301);
+ expect(clampSize(NaN)).toBe(SIZE_MIN);
+ });
+});
+
+describe('scaledCapture', () => {
+ // every built-in preset must show a real difference between 1x and 2x —
+ // this is the exact regression a user hit: presets exceeding SIZE_MAX at 2x
+ // were silently clamped straight back down to 1x, so the resolution picker
+ // appeared to do nothing.
+ const presets = [
+ { w: 1200, h: 675 }, // Tweet 16:9
+ { w: 1080, h: 1080 }, // Square
+ { w: 1200, h: 630 }, // OG card
+ { w: 1280, h: 800 }, // Wide
+ ];
+
+ for (const { w, h } of presets) {
+ it(`doubles the pixel size at 2x for a ${w}x${h} preset`, () => {
+ const base = scaledCapture(w, h, 1, 16, 19);
+ const doubled = scaledCapture(w, h, 2, 16, 19);
+ expect(doubled.mult).toBe(2);
+ expect(doubled.width).toBe(w * 2);
+ expect(doubled.height).toBe(h * 2);
+ expect(doubled.zoom).toBe(base.zoom + 1);
+ expect(doubled.width).not.toBe(base.width);
+ });
+ }
+
+ it('1x keeps the base size and zoom unchanged', () => {
+ const r = scaledCapture(1200, 675, 1, 16, 19);
+ expect(r).toEqual({ zoom: 16, width: 1200, height: 675, mult: 1 });
+ });
+
+ it('max resolution captures as many zoom levels as the provider allows', () => {
+ const r = scaledCapture(600, 400, 'max', 16, 18);
+ expect(r.mult).toBe(4); // 2 zoom levels deeper, still under SIZE_MAX
+ expect(r.zoom).toBe(18);
+ expect(r.width).toBe(2400);
+ expect(r.height).toBe(1600);
+ });
+
+ it('walks the multiplier back down when it would exceed SIZE_MAX', () => {
+ const r = scaledCapture(2200, 2200, 2, 16, 19);
+ expect(r.mult).toBe(1); // 2x would be 4400px, over SIZE_MAX
+ expect(r.width).toBe(2200);
+ });
+
+ it('never captures past the provider max zoom', () => {
+ const r = scaledCapture(500, 500, 'max', 18, 19);
+ expect(r.zoom).toBeLessThanOrEqual(19);
+ });
+});
diff --git a/frontend/src/lib/composer.js b/frontend/src/lib/composer.js
index 5bb514c..be7e524 100644
--- a/frontend/src/lib/composer.js
+++ b/frontend/src/lib/composer.js
@@ -16,9 +16,7 @@ export const PANEL_H = 720;
export const PAD = 20;
export const GAP = 16;
export const ROW_GAP = 18;
-export const LEGEND_LINE_H = 30;
export const LEGEND_COL_MIN = 340; // min px width before the legend splits columns
-export const FOOTER_H = 26;
// Tweet centre-crop aspect guides (width / height): X shows a single image with
// object-fit: cover into a box of this aspect, cropping whatever overflows.
@@ -39,9 +37,9 @@ export function newId(prefix) {
return `${prefix}${Date.now().toString(36)}${(idSeq++).toString(36)}`;
}
-export const CAPTION_SIZE = 17; // default caption font size (px, editable per proof)
-export const LEGEND_SIZE = 17; // default legend text size
-export const FOOTER_SIZE = 13; // default footer / attribution text size
+export const CAPTION_SIZE = 20; // default caption font size (px, editable per proof)
+export const LEGEND_SIZE = 20; // default legend text size
+export const FOOTER_SIZE = 15; // default footer / attribution text size
/** Height of the caption band under a row for a given caption font size. */
export function captionBand(captionSize = CAPTION_SIZE) {
@@ -58,6 +56,11 @@ export function footerBand(footerSize = FOOTER_SIZE) {
return Math.round(footerSize + 13);
}
+// Default band heights, derived from the size defaults so they can't drift out
+// of sync when those change (they mirror legendLineHeight()/footerBand()).
+export const LEGEND_LINE_H = legendLineHeight();
+export const FOOTER_H = footerBand();
+
/** Distinct row indices in ascending order (default row 0). */
function rowOrder(panels) {
return [...new Set(panels.map((p) => p.row ?? 0))].sort((a, b) => a - b);
@@ -146,12 +149,26 @@ export function featureColors(shapes) {
return seen;
}
+/**
+ * `featureColors` order (first use), overridden by an explicit `legendOrder`
+ * (array of colors) where one is given: known colors keep that order, colors
+ * no longer in use are dropped, newly-used colors not yet in `legendOrder`
+ * are appended after the known ones (first-use order among themselves).
+ */
+export function orderedFeatureColors(shapes, legendOrder = []) {
+ const used = featureColors(shapes);
+ const known = legendOrder.filter((c) => used.includes(c));
+ const extra = used.filter((c) => !known.includes(c));
+ return [...known, ...extra];
+}
+
/**
* Legend lines: one per used color (feature), text taken from the per-color
- * `notes` map. Annotations are written by color, not per element.
+ * `notes` map, ordered by `legendOrder` (falls back to first-use order).
+ * Annotations are written by color, not per element.
*/
-export function legendLines(shapes, notes = {}) {
- const colors = featureColors(shapes);
+export function legendLines(shapes, notes = {}, legendOrder = []) {
+ const colors = orderedFeatureColors(shapes, legendOrder);
return colors.map((color, i) => ({
color,
n: i + 1,
@@ -177,15 +194,7 @@ export function notesFromShapes(shapes) {
/** Unique attribution strings from panel metadata. */
export function attributionLine(panels) {
- const parts = new Set();
- for (const p of panels) {
- if (p.meta?.attribution) parts.add(`Imagery: ${p.meta.attribution}`);
- else {
- for (const u of panelSourceUrls(p)) parts.add(`Source: ${u}`);
- }
- }
- parts.add('Composed with Azimut');
- return [...parts].join(' · ');
+ return 'Composed with Azimut';
}
// ---- coordinates + source (auto-derived from panels, user-overridable) ------
@@ -281,7 +290,7 @@ export function legendRowCount(count, columns) {
* count and every text band grows with its own font size (all editable per
* proof via `text = { captionSize, legendSize, footerSize }`).
*/
-export function docSize(panels, shapes, notes = {}, text = {}) {
+export function docSize(panels, shapes, notes = {}, text = {}, legendOrder = []) {
const {
captionSize = CAPTION_SIZE, legendSize = LEGEND_SIZE, footerSize = FOOTER_SIZE,
} = text;
@@ -290,7 +299,7 @@ export function docSize(panels, shapes, notes = {}, text = {}) {
? Math.max(...boxes.map((b) => b.x + b.w)) + PAD
: 640;
const contentW = Math.max(width, 640);
- const legend = legendLines(shapes, notes).filter((l) => l.text);
+ const legend = legendLines(shapes, notes, legendOrder).filter((l) => l.text);
const cols = legendColumns(contentW, legend.length);
const legendRows = legendRowCount(legend.length, cols);
const height =
@@ -313,6 +322,7 @@ export function toSpec(proof) {
footerSize: proof.footerSize ?? FOOTER_SIZE,
footer: proof.footer?.trim() ? proof.footer.trim() : null, // null → default attribution line
notes: { ...(proof.notes ?? {}) },
+ legendOrder: [...(proof.legendOrder ?? [])],
panels: proof.panels.map((p) => ({
id: p.id, // kept so shapes stay bound to their panel on reload
src: p.src,
@@ -356,6 +366,32 @@ export function offsetShape(shape, d) {
return s;
}
+/**
+ * True when a media listing item is a satellite capture — mirrors the backend's
+ * `satellite.is_capture`. A capture *is* a media image (one file in `media/`),
+ * flagged by its sidecar `source.type`, so it surfaces in both the /media and
+ * /satellite listings; callers use this to avoid listing it under both.
+ */
+export function isSatelliteCapture(item) {
+ return (item?.source ?? {}).type === 'satellite';
+}
+
+/**
+ * Collapse picker items that share a `src` down to their first occurrence.
+ * The picker builds its list so no `src` repeats, but a duplicate key would
+ * throw Svelte's `each_key_duplicate` and blank the whole modal — so this is a
+ * cheap last-line guard around that keyed `{#each … (item.src)}`. Callers list
+ * the richer satellite entry first, so the kept one carries coords/attribution.
+ */
+export function dedupeBySrc(items) {
+ const seen = new Set();
+ return items.filter((it) => {
+ if (seen.has(it.src)) return false;
+ seen.add(it.src);
+ return true;
+ });
+}
+
/**
* Auto-arrange panels into stacked rows so the whole composite's aspect ratio
* lands as close as possible to `target` (a tweet-friendly aspect: 16:9 shows
diff --git a/frontend/src/lib/composer.test.js b/frontend/src/lib/composer.test.js
index 8e47c65..0e98bca 100644
--- a/frontend/src/lib/composer.test.js
+++ b/frontend/src/lib/composer.test.js
@@ -4,7 +4,8 @@ import {
layoutPanels, panelsBlockHeight, panelHeight, captionBand, legendLineHeight, footerBand,
docSize, legendColumns, legendRowCount, toSpec, offsetShape, copyShapeSpec, autoLayoutRows, TWEET_GUIDES,
autoCoords, formatCoords, resolveSourceUrls, autoSource, autoSourceUrls,
- proofCoordsText, proofSource,
+ proofCoordsText, proofSource, orderedFeatureColors, legendLines,
+ dedupeBySrc, isSatelliteCapture,
} from './composer.js';
// natural is [width, height]; PANEL_H drives the per-row scale.
@@ -167,6 +168,53 @@ describe('docSize', () => {
});
});
+describe('orderedFeatureColors + legendLines — manual legend order', () => {
+ const shapes = [
+ { kind: 'rect', color: '#ff5252', panel: 'p1' },
+ { kind: 'rect', color: '#40c4ff', panel: 'p1' },
+ { kind: 'rect', color: '#ffd740', panel: 'p1' },
+ ];
+
+ it('falls back to first-use order when no legendOrder is given', () => {
+ expect(orderedFeatureColors(shapes)).toEqual(['#ff5252', '#40c4ff', '#ffd740']);
+ });
+
+ it('respects an explicit legendOrder', () => {
+ const order = ['#ffd740', '#ff5252', '#40c4ff'];
+ expect(orderedFeatureColors(shapes, order)).toEqual(order);
+ });
+
+ it('drops colors no longer used and appends newly-used ones after the known order', () => {
+ const order = ['#40c4ff', '#gone000']; // '#gone000' has no shape anymore
+ const twoColors = shapes.slice(0, 2); // no '#ffd740' shape
+ expect(orderedFeatureColors(twoColors, order)).toEqual(['#40c4ff', '#ff5252']);
+ });
+
+ it('legendLines follows legendOrder and numbers accordingly', () => {
+ const notes = { '#ff5252': 'road', '#40c4ff': 'river', '#ffd740': 'bridge' };
+ const order = ['#ffd740', '#40c4ff', '#ff5252'];
+ const lines = legendLines(shapes, notes, order);
+ expect(lines.map((l) => l.color)).toEqual(order);
+ expect(lines.map((l) => l.n)).toEqual([1, 2, 3]);
+ expect(lines.map((l) => l.text)).toEqual(['bridge', 'river', 'road']);
+ });
+});
+
+describe('docSize — legendOrder does not affect sizing', () => {
+ it('produces the same height regardless of legend order', () => {
+ const panels = [landscape(1000, 500)];
+ const shapes = [
+ { kind: 'rect', color: '#ff5252', panel: 'p1' },
+ { kind: 'rect', color: '#40c4ff', panel: 'p1' },
+ ];
+ const notes = { '#ff5252': 'road', '#40c4ff': 'river' };
+ const a = docSize(panels, shapes, notes, {}, []);
+ const b = docSize(panels, shapes, notes, {}, ['#40c4ff', '#ff5252']);
+ expect(b.height).toBe(a.height);
+ expect(b.legend.map((l) => l.color)).toEqual(['#40c4ff', '#ff5252']);
+ });
+});
+
describe('legend columns', () => {
it('keeps one column for narrow docs or a single feature', () => {
expect(legendColumns(400, 3)).toBe(1);
@@ -416,3 +464,63 @@ describe('tweet guides', () => {
expect(TWEET_GUIDES['4:5']).toBeCloseTo(0.8);
});
});
+
+describe('dedupeBySrc — picker items collapse on shared src', () => {
+ // A satellite capture is registered as a media image too, so /satellite and
+ // /media surface the same path. Without this collapse the keyed picker each
+ // block throws `each_key_duplicate` and "Add panel" silently does nothing.
+ it('drops later items that repeat an earlier src', () => {
+ const items = [
+ { src: 'media/sat_1.png', kind: 'satellite' },
+ { src: 'media/photo.jpg', kind: 'media' },
+ { src: 'media/sat_1.png', kind: 'media' }, // same file, from the media list
+ ];
+ const out = dedupeBySrc(items);
+ expect(out.map((i) => i.src)).toEqual(['media/sat_1.png', 'media/photo.jpg']);
+ });
+
+ it('keeps the first occurrence, so the richer satellite entry wins over media', () => {
+ const items = [
+ { src: 'media/sat_1.png', kind: 'satellite', meta: { lat: 1 } },
+ { src: 'media/sat_1.png', kind: 'media', meta: {} },
+ ];
+ const out = dedupeBySrc(items);
+ expect(out).toHaveLength(1);
+ expect(out[0].kind).toBe('satellite');
+ });
+
+ it('produces a duplicate-free set of keys (the picker each-key invariant)', () => {
+ const items = [
+ { src: 'a' }, { src: 'b' }, { src: 'a' }, { src: 'c' }, { src: 'b' },
+ ];
+ const keys = dedupeBySrc(items).map((i) => i.src);
+ expect(new Set(keys).size).toBe(keys.length);
+ expect(keys).toEqual(['a', 'b', 'c']);
+ });
+
+ it('leaves an already-unique list untouched', () => {
+ const items = [{ src: 'x' }, { src: 'y' }, { src: 'z' }];
+ expect(dedupeBySrc(items)).toEqual(items);
+ });
+});
+
+describe('isSatelliteCapture — a capture is a media image flagged by its source', () => {
+ it('is true for a media item whose source.type is satellite', () => {
+ expect(isSatelliteCapture({ kind: 'image', source: { type: 'satellite' } })).toBe(true);
+ });
+
+ it('is false for an ordinary image, and tolerates a missing source', () => {
+ expect(isSatelliteCapture({ kind: 'image', source: { type: 'download' } })).toBe(false);
+ expect(isSatelliteCapture({ kind: 'image' })).toBe(false);
+ expect(isSatelliteCapture({})).toBe(false);
+ });
+
+ it('lets the picker drop captures from the media half so nothing double-lists', () => {
+ const media = [
+ { path: 'media/sat_1.png', kind: 'image', source: { type: 'satellite' } },
+ { path: 'media/photo.jpg', kind: 'image', source: { type: 'download' } },
+ ];
+ const kept = media.filter((m) => m.kind === 'image' && !isSatelliteCapture(m));
+ expect(kept.map((m) => m.path)).toEqual(['media/photo.jpg']);
+ });
+});
diff --git a/frontend/src/lib/frameRotate.js b/frontend/src/lib/frameRotate.js
new file mode 100644
index 0000000..781e104
--- /dev/null
+++ b/frontend/src/lib/frameRotate.js
@@ -0,0 +1,80 @@
+/**
+ * View-only rotation for the Frame viewer — a Google-Earth-style "grab & turn".
+ *
+ * The image's accumulated rotation is kept as a 2D affine matrix in the CSS
+ * `matrix(a,b,c,d,e,f)` layout, expressed in the stage's own (transform-origin
+ * 0 0) coordinate space. Each middle-drag gesture rotates the *current* matrix
+ * about a fresh pivot, so any prior zoom / pan / rotate is preserved and every
+ * new grab turns the image around exactly the point you clicked.
+ *
+ * matrix(a,b,c,d,e,f) maps (x,y) → (a*x + c*y + e, b*x + d*y + f)
+ */
+
+export const IDENTITY = [1, 0, 0, 1, 0, 0];
+
+const DEG = Math.PI / 180;
+
+/** Compose two affine matrices: returns `m ∘ n` (n applied first, then m). */
+export function matMul(m, n) {
+ const [a1, b1, c1, d1, e1, f1] = m;
+ const [a2, b2, c2, d2, e2, f2] = n;
+ return [
+ a1 * a2 + c1 * b2,
+ b1 * a2 + d1 * b2,
+ a1 * c2 + c1 * d2,
+ b1 * c2 + d1 * d2,
+ a1 * e2 + c1 * f2 + e1,
+ b1 * e2 + d1 * f2 + f1,
+ ];
+}
+
+/** CSS-convention rotation matrix (positive = clockwise, since Y points down). */
+export function rotation(deg) {
+ const r = deg * DEG;
+ const cos = Math.cos(r);
+ const sin = Math.sin(r);
+ return [cos, sin, -sin, cos, 0, 0];
+}
+
+/** Pure translation matrix. */
+export function translation(tx, ty) {
+ return [1, 0, 0, 1, tx, ty];
+}
+
+/** Map a point through a matrix. */
+export function apply(m, x, y) {
+ return [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
+}
+
+/**
+ * Rotate `base` by `deg` around the pivot (px, py): `T(p)·R(deg)·T(-p)·base`.
+ * The pivot is a fixed point of the added rotation, so it stays put while the
+ * already-accumulated image turns around it — and because we pre-multiply, the
+ * new turn composes on top of `base` instead of replacing it.
+ */
+export function rotateAbout(base, px, py, deg) {
+ return matMul(
+ translation(px, py),
+ matMul(rotation(deg), matMul(translation(-px, -py), base))
+ );
+}
+
+/** `matrix(...)` string for a CSS `transform`. */
+export function matrixCss(m) {
+ return `matrix(${m.join(', ')})`;
+}
+
+/** Signed rotation the matrix encodes, in degrees (read from its first column). */
+export function matrixAngleDeg(m) {
+ return Math.atan2(m[1], m[0]) / DEG;
+}
+
+/** Is the matrix (within eps) the identity — i.e. no rotation applied? */
+export function isIdentity(m, eps = 1e-6) {
+ return IDENTITY.every((v, i) => Math.abs(m[i] - v) < eps);
+}
+
+/** Angle (deg) of the spoke from a pivot to a point, in screen space (Y down). */
+export function pointerAngleDeg(pivotX, pivotY, x, y) {
+ return Math.atan2(y - pivotY, x - pivotX) / DEG;
+}
diff --git a/frontend/src/lib/frameRotate.test.js b/frontend/src/lib/frameRotate.test.js
new file mode 100644
index 0000000..9ee85bc
--- /dev/null
+++ b/frontend/src/lib/frameRotate.test.js
@@ -0,0 +1,100 @@
+import { describe, it, expect } from 'vitest';
+import {
+ IDENTITY, matMul, rotation, translation, apply,
+ rotateAbout, matrixCss, matrixAngleDeg, isIdentity, pointerAngleDeg,
+} from './frameRotate.js';
+
+const near = (a, b, eps = 1e-9) => Math.abs(a - b) < eps;
+const pointNear = (p, x, y, eps = 1e-9) => near(p[0], x, eps) && near(p[1], y, eps);
+
+describe('matMul', () => {
+ it('is a no-op against the identity', () => {
+ const m = rotation(30);
+ expect(matMul(IDENTITY, m)).toEqual(m);
+ expect(matMul(m, IDENTITY)).toEqual(m);
+ });
+ it('applies the right-hand matrix first', () => {
+ // translate-then-scale vs scale-then-translate differ
+ const t = translation(10, 0);
+ const s = [2, 0, 0, 2, 0, 0];
+ // matMul(s, t): translate first, then scale → the offset gets scaled
+ expect(matMul(s, t)).toEqual([2, 0, 0, 2, 20, 0]);
+ // matMul(t, s): scale first, then translate → offset unscaled
+ expect(matMul(t, s)).toEqual([2, 0, 0, 2, 10, 0]);
+ });
+});
+
+describe('rotation', () => {
+ it('turns +x toward +y (clockwise, Y down) at 90°', () => {
+ expect(pointNear(apply(rotation(90), 1, 0), 0, 1)).toBe(true);
+ });
+ it('is the identity at 0° and 360°', () => {
+ expect(isIdentity(rotation(0))).toBe(true);
+ expect(isIdentity(rotation(360))).toBe(true);
+ });
+});
+
+describe('rotateAbout', () => {
+ it('leaves the pivot itself fixed', () => {
+ const m = rotateAbout(IDENTITY, 50, 30, 37);
+ expect(pointNear(apply(m, 50, 30), 50, 30, 1e-6)).toBe(true);
+ });
+
+ it('rotates a point around the pivot, not the origin', () => {
+ // pivot (10,10); the point (20,10) is 10px to its right → +90° puts it below
+ const m = rotateAbout(IDENTITY, 10, 10, 90);
+ expect(pointNear(apply(m, 20, 10), 10, 20, 1e-6)).toBe(true);
+ });
+
+ it('accumulates: two turns about one pivot equal their sum', () => {
+ const pivotX = 12, pivotY = -7;
+ const step = rotateAbout(rotateAbout(IDENTITY, pivotX, pivotY, 30), pivotX, pivotY, 60);
+ const once = rotateAbout(IDENTITY, pivotX, pivotY, 90);
+ step.forEach((v, i) => expect(near(v, once[i], 1e-6)).toBe(true));
+ });
+
+ it('composes on top of a prior rotation, pivoting in the output space', () => {
+ // Grab a fresh pivot after the image already carries a rotation: the new
+ // turn must (a) keep the grabbed point — a point in the matrix's *output*
+ // space — fixed, and (b) leave the prior rotation intact (pre-multiplied).
+ const base = rotation(25);
+ const turned = rotateAbout(base, 40, 60, 50);
+ const addedOnly = rotateAbout(IDENTITY, 40, 60, 50);
+ // the grabbed pivot is a fixed point of the freshly-added rotation
+ expect(pointNear(apply(addedOnly, 40, 60), 40, 60, 1e-6)).toBe(true);
+ // and the accumulated matrix is exactly "added ∘ base" — base preserved
+ matMul(addedOnly, base).forEach((v, i) => expect(near(v, turned[i], 1e-6)).toBe(true));
+ });
+});
+
+describe('matrixAngleDeg', () => {
+ it('reads back the encoded rotation', () => {
+ expect(near(matrixAngleDeg(rotation(45)), 45, 1e-6)).toBe(true);
+ expect(near(matrixAngleDeg(rotation(-120)), -120, 1e-6)).toBe(true);
+ });
+ it('is unaffected by the pivot translation', () => {
+ expect(near(matrixAngleDeg(rotateAbout(IDENTITY, 99, 33, 15)), 15, 1e-6)).toBe(true);
+ });
+});
+
+describe('isIdentity', () => {
+ it('is true only for the (near) identity', () => {
+ expect(isIdentity(IDENTITY)).toBe(true);
+ expect(isIdentity(rotation(0.0000001))).toBe(true);
+ expect(isIdentity(rotation(5))).toBe(false);
+ });
+});
+
+describe('pointerAngleDeg', () => {
+ it('measures the spoke angle in screen space (Y down)', () => {
+ expect(near(pointerAngleDeg(0, 0, 1, 0), 0)).toBe(true);
+ expect(near(pointerAngleDeg(0, 0, 0, 1), 90)).toBe(true);
+ expect(near(Math.abs(pointerAngleDeg(0, 0, -1, 0)), 180)).toBe(true);
+ });
+});
+
+describe('matrixCss', () => {
+ it('serialises to a CSS matrix() string', () => {
+ expect(matrixCss(IDENTITY)).toBe('matrix(1, 0, 0, 1, 0, 0)');
+ });
+});
diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.js
new file mode 100644
index 0000000..cebda99
--- /dev/null
+++ b/frontend/src/lib/history.js
@@ -0,0 +1,44 @@
+/**
+ * Bounded snapshot history for undo/redo. Snapshots are JSON strings (cheap
+ * equality checks); the caller decides what to serialize and how to restore.
+ * `push` drops the redo tail — a new edit after an undo forks the timeline —
+ * and evicts the oldest entry past `limit`.
+ */
+export function createHistory(limit = 60) {
+ let stack = [];
+ let index = -1;
+ return {
+ get canUndo() {
+ return index > 0;
+ },
+ get canRedo() {
+ return index >= 0 && index < stack.length - 1;
+ },
+ /** Start a fresh timeline anchored at `snapshot` (undo stops here). */
+ reset(snapshot) {
+ stack = [snapshot];
+ index = 0;
+ },
+ /** Record `snapshot` unless it equals the current entry. */
+ push(snapshot) {
+ if (index >= 0 && stack[index] === snapshot) return false;
+ stack = stack.slice(0, index + 1);
+ stack.push(snapshot);
+ if (stack.length > limit) stack.shift();
+ index = stack.length - 1;
+ return true;
+ },
+ /** Step back; returns the snapshot to restore, or null at the anchor. */
+ undo() {
+ if (index <= 0) return null;
+ index -= 1;
+ return stack[index];
+ },
+ /** Step forward; returns the snapshot to restore, or null at the tip. */
+ redo() {
+ if (index < 0 || index >= stack.length - 1) return null;
+ index += 1;
+ return stack[index];
+ },
+ };
+}
diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.js
new file mode 100644
index 0000000..03740a0
--- /dev/null
+++ b/frontend/src/lib/history.test.js
@@ -0,0 +1,78 @@
+import { describe, it, expect } from 'vitest';
+import { createHistory } from './history.js';
+
+describe('createHistory — undo/redo timeline', () => {
+ it('starts unable to undo or redo', () => {
+ const h = createHistory();
+ h.reset('a');
+ expect(h.canUndo).toBe(false);
+ expect(h.canRedo).toBe(false);
+ expect(h.undo()).toBeNull();
+ expect(h.redo()).toBeNull();
+ });
+
+ it('pushes distinct snapshots and walks back through them', () => {
+ const h = createHistory();
+ h.reset('a');
+ expect(h.push('b')).toBe(true);
+ expect(h.push('c')).toBe(true);
+ expect(h.canUndo).toBe(true);
+ expect(h.undo()).toBe('b');
+ expect(h.undo()).toBe('a');
+ expect(h.undo()).toBeNull(); // anchor reached
+ });
+
+ it('skips a push equal to the current entry (debounce echoes)', () => {
+ const h = createHistory();
+ h.reset('a');
+ h.push('b');
+ expect(h.push('b')).toBe(false);
+ expect(h.undo()).toBe('a');
+ });
+
+ it('redoes forward after an undo', () => {
+ const h = createHistory();
+ h.reset('a');
+ h.push('b');
+ h.push('c');
+ h.undo();
+ h.undo();
+ expect(h.canRedo).toBe(true);
+ expect(h.redo()).toBe('b');
+ expect(h.redo()).toBe('c');
+ expect(h.redo()).toBeNull(); // tip reached
+ });
+
+ it('forks the timeline: a push after undo drops the redo tail', () => {
+ const h = createHistory();
+ h.reset('a');
+ h.push('b');
+ h.push('c');
+ h.undo(); // at b
+ h.push('d'); // c is gone
+ expect(h.canRedo).toBe(false);
+ expect(h.undo()).toBe('b');
+ expect(h.redo()).toBe('d');
+ });
+
+ it('reset drops everything and re-anchors', () => {
+ const h = createHistory();
+ h.reset('a');
+ h.push('b');
+ h.reset('z');
+ expect(h.canUndo).toBe(false);
+ expect(h.canRedo).toBe(false);
+ expect(h.push('z')).toBe(false); // same as the anchor
+ });
+
+ it('evicts the oldest entry past the limit', () => {
+ const h = createHistory(3);
+ h.reset('a');
+ h.push('b');
+ h.push('c');
+ h.push('d'); // 'a' evicted
+ expect(h.undo()).toBe('c');
+ expect(h.undo()).toBe('b');
+ expect(h.undo()).toBeNull(); // 'a' is gone
+ });
+});
diff --git a/frontend/src/lib/inspect.js b/frontend/src/lib/inspect.js
index 700cf36..9040ba7 100644
--- a/frontend/src/lib/inspect.js
+++ b/frontend/src/lib/inspect.js
@@ -181,6 +181,129 @@ export function cropAspect(crop, natW, natH) {
return (crop.w * natW) / (crop.h * natH);
}
+// ---------------------------------------------------------------------------
+// Editable crop box: a fractional {x,y,w,h} (0..1) resized by dragging its 8
+// handles (4 corners + 4 edges) or moved by its body, with an optional aspect
+// lock. All pure so the same math backs the Frame overlay and the piece modal.
+// ---------------------------------------------------------------------------
+
+/** Clamp a fractional crop so it stays inside [0,1] and never smaller than `min`. */
+export function clampCrop(c, min = 0.02) {
+ const w = Math.max(min, Math.min(1, c.w));
+ const h = Math.max(min, Math.min(1, c.h));
+ const x = Math.min(Math.max(0, c.x), 1 - w);
+ const y = Math.min(Math.max(0, c.y), 1 - h);
+ return { x, y, w, h };
+}
+
+/** Translate a crop by a fractional delta, clamped inside the image. */
+export function moveCrop(c, dx, dy) {
+ const w = c.w;
+ const h = c.h;
+ return {
+ x: Math.min(Math.max(0, c.x + dx), 1 - w),
+ y: Math.min(Math.max(0, c.y + dy), 1 - h),
+ w,
+ h,
+ };
+}
+
+// Handle → which edges it drives. l/r/t/b flags mean that edge follows the pointer.
+const HANDLE_EDGES = {
+ nw: { l: true, t: true }, n: { t: true }, ne: { r: true, t: true },
+ e: { r: true }, se: { r: true, b: true }, s: { b: true },
+ sw: { l: true, b: true }, w: { l: true },
+};
+
+/**
+ * New crop after dragging `handle` (one of nw/n/ne/e/se/s/sw/w) to the pointer
+ * fraction (px, py). With `fracAspect` (w/h in *fractional* units) the box keeps
+ * that ratio: corners grow from the opposite corner, edges grow about the centre
+ * of the fixed edge. Result is clamped inside the image.
+ */
+export function resizeCropByHandle(crop, handle, px, py, fracAspect = null, min = 0.02) {
+ const e = HANDLE_EDGES[handle];
+ if (!e) return clampCrop(crop, min);
+ let left = crop.x;
+ let top = crop.y;
+ let right = crop.x + crop.w;
+ let bottom = crop.y + crop.h;
+ if (e.l) left = Math.min(px, right - min);
+ if (e.r) right = Math.max(px, left + min);
+ if (e.t) top = Math.min(py, bottom - min);
+ if (e.b) bottom = Math.max(py, top + min);
+
+ let x = left;
+ let y = top;
+ let w = right - left;
+ let h = bottom - top;
+
+ if (fracAspect) {
+ const corner = (e.l || e.r) && (e.t || e.b);
+ if (corner) {
+ // corner: drive by width, derive height, keep the opposite corner fixed
+ h = w / fracAspect;
+ if (e.t) y = bottom - h;
+ } else if (e.l || e.r) {
+ // vertical edge: width drives, expand height about the fixed edge's centre
+ const cy = crop.y + crop.h / 2;
+ h = w / fracAspect;
+ y = cy - h / 2;
+ } else {
+ // horizontal edge: height drives, expand width about the fixed edge's centre
+ const cx = crop.x + crop.w / 2;
+ w = h * fracAspect;
+ x = cx - w / 2;
+ }
+ }
+ return clampCrop({ x, y, w, h }, min);
+}
+
+// ---------------------------------------------------------------------------
+// Collage piece edges: side handles that resize a (possibly warped) quad by
+// sliding one edge along its outward normal, leaving the opposite edge fixed.
+// Corners stay free-warp handles; sides are a pure, warp-preserving resize.
+// ---------------------------------------------------------------------------
+
+/** Corner index pairs for the four quad edges: top, right, bottom, left. */
+export const QUAD_SIDES = [[0, 1], [1, 2], [2, 3], [3, 0]];
+
+/** Midpoints of the four quad edges, tagged with their side index. */
+export function quadEdgeMidpoints(quad) {
+ return QUAD_SIDES.map(([a, b], side) => ({
+ side,
+ x: (quad[a][0] + quad[b][0]) / 2,
+ y: (quad[a][1] + quad[b][1]) / 2,
+ }));
+}
+
+/**
+ * Move one edge of `quad` by the drag (dx, dy) *projected onto that edge's
+ * outward normal* — a resize that keeps the edge parallel and the opposite edge
+ * fixed. Works on a warped quad (both endpoints shift together) and composes
+ * with the per-corner warp, since it only moves two of the four points.
+ */
+export function moveQuadEdge(quad, side, dx, dy) {
+ const [a, b] = QUAD_SIDES[side];
+ const ex = quad[b][0] - quad[a][0];
+ const ey = quad[b][1] - quad[a][1];
+ const len = Math.hypot(ex, ey) || 1;
+ let nx = -ey / len;
+ let ny = ex / len;
+ const [cx, cy] = quadCentroid(quad);
+ const mx = (quad[a][0] + quad[b][0]) / 2;
+ const my = (quad[a][1] + quad[b][1]) / 2;
+ if ((mx - cx) * nx + (my - cy) * ny < 0) {
+ nx = -nx;
+ ny = -ny;
+ }
+ const t = dx * nx + dy * ny; // drag projected onto the outward normal
+ const out = quad.map(([x, y]) => [x, y]);
+ out[a] = [quad[a][0] + nx * t, quad[a][1] + ny * t];
+ out[b] = [quad[b][0] + nx * t, quad[b][1] + ny * t];
+ return out;
+}
+
/** Centroid (mean of the 4 corners) of a quad. */
export function quadCentroid(quad) {
const cx = (quad[0][0] + quad[1][0] + quad[2][0] + quad[3][0]) / 4;
diff --git a/frontend/src/lib/inspect.test.js b/frontend/src/lib/inspect.test.js
new file mode 100644
index 0000000..66b447f
--- /dev/null
+++ b/frontend/src/lib/inspect.test.js
@@ -0,0 +1,126 @@
+import { describe, it, expect } from 'vitest';
+import {
+ clampCrop, moveCrop, resizeCropByHandle,
+ QUAD_SIDES, quadEdgeMidpoints, moveQuadEdge, quadCentroid,
+} from './inspect.js';
+
+const near = (a, b, eps = 1e-6) => Math.abs(a - b) < eps;
+
+describe('clampCrop', () => {
+ it('keeps a valid crop untouched', () => {
+ expect(clampCrop({ x: 0.1, y: 0.2, w: 0.5, h: 0.4 })).toEqual({ x: 0.1, y: 0.2, w: 0.5, h: 0.4 });
+ });
+ it('clamps size and pushes the box back inside the image', () => {
+ const c = clampCrop({ x: 0.8, y: 0.9, w: 0.5, h: 0.4 });
+ expect(c.x + c.w).toBeLessThanOrEqual(1 + 1e-9);
+ expect(c.y + c.h).toBeLessThanOrEqual(1 + 1e-9);
+ });
+ it('enforces a minimum size', () => {
+ expect(clampCrop({ x: 0, y: 0, w: 0.001, h: 0.001 }, 0.02)).toMatchObject({ w: 0.02, h: 0.02 });
+ });
+});
+
+describe('moveCrop', () => {
+ it('translates within bounds', () => {
+ const c = moveCrop({ x: 0.2, y: 0.2, w: 0.3, h: 0.3 }, 0.1, -0.1);
+ expect(near(c.x, 0.3)).toBe(true);
+ expect(near(c.y, 0.1)).toBe(true);
+ expect(c.w).toBe(0.3);
+ expect(c.h).toBe(0.3);
+ });
+ it('stops the box at the image edge instead of overflowing', () => {
+ const c = moveCrop({ x: 0.6, y: 0.6, w: 0.3, h: 0.3 }, 0.5, 0.5);
+ expect(near(c.x, 0.7)).toBe(true);
+ expect(near(c.y, 0.7)).toBe(true);
+ });
+});
+
+describe('resizeCropByHandle', () => {
+ const base = { x: 0.2, y: 0.2, w: 0.4, h: 0.4 }; // corners at 0.2 and 0.6
+
+ it('drags the SE corner, keeping the NW corner fixed', () => {
+ const c = resizeCropByHandle(base, 'se', 0.8, 0.9);
+ expect(c.x).toBe(0.2);
+ expect(c.y).toBe(0.2);
+ expect(near(c.w, 0.6)).toBe(true);
+ expect(near(c.h, 0.7)).toBe(true);
+ });
+
+ it('drags the N edge, moving only the top', () => {
+ const c = resizeCropByHandle(base, 'n', 0.5, 0.1);
+ expect(near(c.y, 0.1)).toBe(true);
+ expect(near(c.h, 0.5)).toBe(true);
+ expect(c.x).toBe(0.2);
+ expect(near(c.w, 0.4)).toBe(true);
+ });
+
+ it('drags the W edge, moving only the left', () => {
+ const c = resizeCropByHandle(base, 'w', 0.35, 0.5);
+ expect(near(c.x, 0.35)).toBe(true);
+ expect(near(c.w, 0.25)).toBe(true);
+ });
+
+ it('never lets an edge cross past the opposite one', () => {
+ const c = resizeCropByHandle(base, 'e', 0.0, 0.5, null, 0.05);
+ expect(c.w).toBeGreaterThanOrEqual(0.05 - 1e-9);
+ expect(c.x).toBe(0.2);
+ });
+
+ it('keeps the aspect ratio on a corner drag', () => {
+ // fracAspect 2 → width twice the height
+ const c = resizeCropByHandle(base, 'se', 0.8, 0.65, 2);
+ expect(near(c.w / c.h, 2)).toBe(true);
+ expect(c.x).toBe(0.2);
+ expect(c.y).toBe(0.2);
+ });
+
+ it('keeps aspect on a vertical edge by growing height about the centre', () => {
+ const c = resizeCropByHandle(base, 'e', 0.7, 0.5, 1); // square lock
+ // width becomes 0.5, height follows to 0.5, recentred on old centre (0.4)
+ expect(near(c.w, c.h)).toBe(true);
+ expect(near(c.y + c.h / 2, 0.4, 1e-6)).toBe(true);
+ });
+});
+
+describe('quad side resize', () => {
+ const rect = [[0, 0], [100, 0], [100, 80], [0, 80]]; // TL,TR,BR,BL
+
+ it('exposes an edge midpoint per side', () => {
+ expect(QUAD_SIDES.length).toBe(4);
+ const mids = quadEdgeMidpoints(rect);
+ expect(mids[0]).toMatchObject({ side: 0, x: 50, y: 0 }); // top
+ expect(mids[2]).toMatchObject({ side: 2, x: 50, y: 80 }); // bottom
+ });
+
+ it('grows the rect by dragging the right edge outward', () => {
+ const out = moveQuadEdge(rect, 1, 40, 0); // right edge, drag +x
+ expect(out[1][0]).toBe(140); // TR moved out
+ expect(out[2][0]).toBe(140); // BR moved out
+ expect(out[0]).toEqual([0, 0]); // left edge fixed
+ expect(out[3]).toEqual([0, 80]);
+ });
+
+ it('ignores drag parallel to the edge (projects onto the normal)', () => {
+ const out = moveQuadEdge(rect, 1, 0, 30); // right edge, drag along the edge
+ expect(out[1][0]).toBe(100);
+ expect(out[2][0]).toBe(100);
+ });
+
+ it('keeps the opposite edge fixed on a warped quad', () => {
+ const warped = [[10, 5], [110, 0], [120, 90], [0, 85]];
+ const out = moveQuadEdge(warped, 0, 0, -20); // top edge outward (up)
+ // bottom corners unchanged
+ expect(out[2]).toEqual(warped[2]);
+ expect(out[3]).toEqual(warped[3]);
+ // top corners moved
+ expect(out[0]).not.toEqual(warped[0]);
+ expect(out[1]).not.toEqual(warped[1]);
+ });
+
+ it('moving an edge out then back returns near the start', () => {
+ const c0 = quadCentroid(rect);
+ const out = moveQuadEdge(moveQuadEdge(rect, 1, 40, 0), 1, -40, 0);
+ const c1 = quadCentroid(out);
+ expect(near(c0[0], c1[0], 1e-9)).toBe(true);
+ });
+});
diff --git a/frontend/src/lib/maplinks.js b/frontend/src/lib/maplinks.js
new file mode 100644
index 0000000..71ccf84
--- /dev/null
+++ b/frontend/src/lib/maplinks.js
@@ -0,0 +1,43 @@
+// Quick-jump links to external maps we can't embed in-tool, for a coordinate.
+// Used by the Satellite "Open in…" panel: the point is to reach the maps that
+// aren't reachable from inside Azimut (Esri/OSM are already in-tool tile
+// providers, so they're deliberately left out). Pure URL construction.
+export function mapLinks(lat, lon, zoom = 17) {
+ const z = Math.round(zoom);
+ return [
+ { id: 'google', label: 'Google Maps', url: `https://www.google.com/maps/@${lat},${lon},${z}z` },
+ {
+ id: 'google_sat',
+ label: 'Google Satellite',
+ url: `https://www.google.com/maps/@${lat},${lon},2000m/data=!3m1!1e3`,
+ },
+ {
+ id: 'google_earth',
+ label: 'Google Earth',
+ url: `https://earth.google.com/web/@${lat},${lon},0a,1000d,35y,0h,0t,0r`,
+ },
+ {
+ id: 'apple',
+ label: 'Apple Maps',
+ // t=k selects the satellite/hybrid basemap
+ url: `https://maps.apple.com/?ll=${lat},${lon}&z=${z}&t=k`,
+ },
+ { id: 'bing', label: 'Bing Maps', url: `https://www.bing.com/maps?cp=${lat}~${lon}&lvl=${z}&style=h` },
+ {
+ id: 'yandex',
+ label: 'Yandex Satellite',
+ url: `https://yandex.com/maps/?ll=${lon},${lat}&z=${z}&l=sat`,
+ },
+ {
+ id: 'satellites_pro',
+ label: 'Satellites.pro',
+ url: `https://satellites.pro/#${lat},${lon},${z}`,
+ },
+ {
+ id: 'sentinel',
+ label: 'Copernicus Browser',
+ url: `https://browser.dataspace.copernicus.eu/?zoom=${z}&lat=${lat}&lng=${lon}`,
+ },
+ { id: 'zoom_earth', label: 'Zoom Earth', url: `https://zoom.earth/#view=${lat},${lon},${z}z` },
+ ];
+}
diff --git a/frontend/src/lib/maplinks.test.js b/frontend/src/lib/maplinks.test.js
new file mode 100644
index 0000000..639f1ed
--- /dev/null
+++ b/frontend/src/lib/maplinks.test.js
@@ -0,0 +1,47 @@
+import { describe, it, expect } from 'vitest';
+import { mapLinks } from './maplinks.js';
+
+describe('mapLinks', () => {
+ const links = mapLinks(48.8584, 2.2945, 16);
+ const byId = Object.fromEntries(links.map((l) => [l.id, l]));
+
+ it('covers the external maps not embeddable in-tool', () => {
+ expect(links.map((l) => l.id).sort()).toEqual(
+ [
+ 'apple',
+ 'bing',
+ 'google',
+ 'google_earth',
+ 'google_sat',
+ 'satellites_pro',
+ 'sentinel',
+ 'yandex',
+ 'zoom_earth',
+ ].sort()
+ );
+ });
+
+ it('deliberately excludes the in-tool tile providers (Esri, OSM)', () => {
+ expect(byId.esri).toBeUndefined();
+ expect(byId.osm).toBeUndefined();
+ });
+
+ it('embeds the coordinates in each URL', () => {
+ for (const { url } of links) {
+ expect(url).toContain('48.8584');
+ expect(url).toContain('2.2945');
+ }
+ });
+
+ it('rounds zoom and uses lon,lat order for Yandex', () => {
+ expect(byId.google.url).toContain(',16z');
+ expect(byId.yandex.url).toContain('ll=2.2945,48.8584');
+ });
+
+ it('every entry has a label and an https url', () => {
+ for (const { label, url } of links) {
+ expect(label).toBeTruthy();
+ expect(url.startsWith('https://')).toBe(true);
+ }
+ });
+});
diff --git a/frontend/src/lib/measure.js b/frontend/src/lib/measure.js
new file mode 100644
index 0000000..d8b7488
--- /dev/null
+++ b/frontend/src/lib/measure.js
@@ -0,0 +1,71 @@
+// Pure geodesic geometry for the Satellite measure tools (distance / area /
+// angle). Points are { lat, lon } in degrees. Kept free of Leaflet so it can be
+// unit-tested; the component only handles drawing and interaction.
+
+const R = 6378137; // Earth radius (m), WGS84 equatorial — matches Web Mercator
+const rad = (deg) => (deg * Math.PI) / 180;
+
+/** Great-circle distance between two points, in metres (haversine). */
+export function haversine(a, b) {
+ const dLat = rad(b.lat - a.lat);
+ const dLon = rad(b.lon - a.lon);
+ const s =
+ Math.sin(dLat / 2) ** 2 +
+ Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;
+ return 2 * R * Math.asin(Math.min(1, Math.sqrt(s)));
+}
+
+/** Total length of a polyline through the points, in metres. */
+export function pathLength(points) {
+ let total = 0;
+ for (let i = 1; i < points.length; i++) total += haversine(points[i - 1], points[i]);
+ return total;
+}
+
+/** Area of the polygon (spherical excess approximation), in square metres. */
+export function polygonArea(points) {
+ const n = points.length;
+ if (n < 3) return 0;
+ let sum = 0;
+ for (let i = 0; i < n; i++) {
+ const p = points[i];
+ const q = points[(i + 1) % n];
+ sum += rad(q.lon - p.lon) * (2 + Math.sin(rad(p.lat)) + Math.sin(rad(q.lat)));
+ }
+ return Math.abs((sum * R * R) / 2);
+}
+
+/** Interior angle at `vertex` between the rays to `a` and `b`, in degrees. */
+export function angleAt(a, vertex, b) {
+ const cosLat = Math.cos(rad(vertex.lat));
+ const ax = rad(a.lon - vertex.lon) * cosLat;
+ const ay = rad(a.lat - vertex.lat);
+ const bx = rad(b.lon - vertex.lon) * cosLat;
+ const by = rad(b.lat - vertex.lat);
+ const magA = Math.hypot(ax, ay);
+ const magB = Math.hypot(bx, by);
+ if (!magA || !magB) return 0;
+ const cos = Math.min(1, Math.max(-1, (ax * bx + ay * by) / (magA * magB)));
+ return (Math.acos(cos) * 180) / Math.PI;
+}
+
+export function formatDistance(m) {
+ if (m < 1000) return `${m < 10 ? m.toFixed(1) : Math.round(m)} m`;
+ return `${(m / 1000).toFixed(m < 10000 ? 2 : 1)} km`;
+}
+
+export function formatArea(m2) {
+ if (m2 < 10000) return `${Math.round(m2)} m²`;
+ if (m2 < 1e6) return `${(m2 / 10000).toFixed(2)} ha`;
+ return `${(m2 / 1e6).toFixed(2)} km²`;
+}
+
+// Two straight rays meeting at a vertex form a pair of supplementary angles
+// (they sum to 180°). Report both the acute and the obtuse one so the reader
+// doesn't have to work out the complement themselves (Satellite item 7).
+export function formatAngle(deg) {
+ const other = 180 - deg;
+ const acute = Math.min(deg, other);
+ const obtuse = Math.max(deg, other);
+ return `${acute.toFixed(1)}° · ${obtuse.toFixed(1)}°`;
+}
diff --git a/frontend/src/lib/measure.test.js b/frontend/src/lib/measure.test.js
new file mode 100644
index 0000000..e24a3cd
--- /dev/null
+++ b/frontend/src/lib/measure.test.js
@@ -0,0 +1,100 @@
+import { describe, it, expect } from 'vitest';
+import {
+ haversine,
+ pathLength,
+ polygonArea,
+ angleAt,
+ formatDistance,
+ formatArea,
+ formatAngle,
+} from './measure.js';
+
+describe('haversine', () => {
+ it('measures a known one-degree of latitude (~111 km)', () => {
+ const d = haversine({ lat: 0, lon: 0 }, { lat: 1, lon: 0 });
+ expect(d).toBeGreaterThan(110000);
+ expect(d).toBeLessThan(112000);
+ });
+
+ it('is zero for identical points', () => {
+ expect(haversine({ lat: 48.8, lon: 2.3 }, { lat: 48.8, lon: 2.3 })).toBe(0);
+ });
+});
+
+describe('pathLength', () => {
+ it('sums consecutive legs', () => {
+ const pts = [
+ { lat: 0, lon: 0 },
+ { lat: 0, lon: 1 },
+ { lat: 0, lon: 2 },
+ ];
+ expect(pathLength(pts)).toBeCloseTo(2 * haversine(pts[0], pts[1]), 0);
+ });
+
+ it('is zero for a single point', () => {
+ expect(pathLength([{ lat: 1, lon: 1 }])).toBe(0);
+ });
+});
+
+describe('polygonArea', () => {
+ it('needs at least three points', () => {
+ expect(polygonArea([{ lat: 0, lon: 0 }, { lat: 0, lon: 1 }])).toBe(0);
+ });
+
+ it('approximates a 1°×1° cell near the equator (~12,300 km²)', () => {
+ const km2 =
+ polygonArea([
+ { lat: 0, lon: 0 },
+ { lat: 0, lon: 1 },
+ { lat: 1, lon: 1 },
+ { lat: 1, lon: 0 },
+ ]) / 1e6;
+ expect(km2).toBeGreaterThan(12000);
+ expect(km2).toBeLessThan(12500);
+ });
+
+ it('is orientation-independent (always positive)', () => {
+ const cw = [
+ { lat: 0, lon: 0 },
+ { lat: 1, lon: 0 },
+ { lat: 1, lon: 1 },
+ { lat: 0, lon: 1 },
+ ];
+ expect(polygonArea(cw)).toBeGreaterThan(0);
+ });
+});
+
+describe('angleAt', () => {
+ it('is 90° for a right angle', () => {
+ const a = { lat: 1, lon: 0 };
+ const v = { lat: 0, lon: 0 };
+ const b = { lat: 0, lon: 1 };
+ expect(angleAt(a, v, b)).toBeCloseTo(90, 1);
+ });
+
+ it('is 180° for a straight line', () => {
+ expect(angleAt({ lat: 0, lon: -1 }, { lat: 0, lon: 0 }, { lat: 0, lon: 1 })).toBeCloseTo(
+ 180,
+ 1
+ );
+ });
+});
+
+describe('formatting', () => {
+ it('switches metres → km', () => {
+ expect(formatDistance(250)).toBe('250 m');
+ expect(formatDistance(1500)).toBe('1.50 km');
+ });
+
+ it('switches m² → ha → km²', () => {
+ expect(formatArea(500)).toBe('500 m²');
+ expect(formatArea(50000)).toBe('5.00 ha');
+ expect(formatArea(5e6)).toBe('5.00 km²');
+ });
+
+ it('reports the acute and obtuse angle pair', () => {
+ expect(formatAngle(90)).toBe('90.0° · 90.0°');
+ expect(formatAngle(65)).toBe('65.0° · 115.0°');
+ expect(formatAngle(150)).toBe('30.0° · 150.0°');
+ });
+});
diff --git a/frontend/src/lib/mediaFilter.js b/frontend/src/lib/mediaFilter.js
new file mode 100644
index 0000000..2015c9f
--- /dev/null
+++ b/frontend/src/lib/mediaFilter.js
@@ -0,0 +1,80 @@
+/**
+ * Free-text search + sorting for the Media Library grid. Pure functions so a
+ * case with hundreds of items stays navigable and the behavior stays testable.
+ */
+
+/** Case-insensitive match against everything the analyst might remember:
+ * filename, title, notes, folder, and the download's title/uploader/URL. */
+export function matchesQuery(item, query) {
+ const q = (query ?? '').trim().toLowerCase();
+ if (!q) return true;
+ const haystack = [
+ item.filename,
+ item.title,
+ item.notes,
+ item.folder,
+ item.source?.title,
+ item.source?.uploader,
+ item.source?.webpage_url ?? item.source?.url,
+ ]
+ .filter(Boolean)
+ .join('\n')
+ .toLowerCase();
+ return q.split(/\s+/).every((term) => haystack.includes(term));
+}
+
+export const SORTS = [
+ { id: 'newest', label: 'Newest first' },
+ { id: 'oldest', label: 'Oldest first' },
+ { id: 'name', label: 'Name A–Z' },
+ { id: 'size', label: 'Largest first' },
+];
+
+/**
+ * The media rows the grid should render: filtered by category/folder/query and
+ * sorted. Returns nothing when no case is open — the cards read
+ * `caseState.current.id` for their file URLs, so rendering a stale list while
+ * the case is being closed (a brief window where `current` is null but `items`
+ * hasn't been cleared yet) would throw and abort the whole reactive flush,
+ * leaving *other* tools un-reset. Gating on `hasCase` makes that impossible
+ * regardless of effect ordering.
+ */
+export function visibleMedia(
+ items,
+ { hasCase = true, catMatch = null, folderFilter = null, query = '', sort = 'newest' } = {}
+) {
+ if (!hasCase) return [];
+ return sortItems(
+ items.filter(
+ (i) =>
+ (!catMatch || catMatch(i)) &&
+ (!folderFilter || i.folder === folderFilter) &&
+ matchesQuery(i, query)
+ ),
+ sort
+ );
+}
+
+const displayName = (i) => (i.title ?? i.filename ?? '').toLowerCase();
+
+/** Stable-sorted copy of `items` (the API's order is newest-first on disk scan,
+ * but sorting explicitly keeps the toggle honest whatever the backend does). */
+export function sortItems(items, sort) {
+ const out = [...items];
+ switch (sort) {
+ case 'oldest':
+ out.sort((a, b) => (a.added_at ?? '').localeCompare(b.added_at ?? ''));
+ break;
+ case 'name':
+ out.sort((a, b) => displayName(a).localeCompare(displayName(b)));
+ break;
+ case 'size':
+ out.sort((a, b) => (b.size ?? 0) - (a.size ?? 0));
+ break;
+ case 'newest':
+ default:
+ out.sort((a, b) => (b.added_at ?? '').localeCompare(a.added_at ?? ''));
+ break;
+ }
+ return out;
+}
diff --git a/frontend/src/lib/mediaFilter.test.js b/frontend/src/lib/mediaFilter.test.js
new file mode 100644
index 0000000..7ba6931
--- /dev/null
+++ b/frontend/src/lib/mediaFilter.test.js
@@ -0,0 +1,120 @@
+import { describe, it, expect } from 'vitest';
+import { matchesQuery, sortItems, visibleMedia } from './mediaFilter.js';
+
+const item = (extra = {}) => ({
+ filename: 'strike_video.mp4',
+ title: null,
+ notes: null,
+ folder: null,
+ source: null,
+ size: 100,
+ added_at: '2026-07-01T10:00:00Z',
+ ...extra,
+});
+
+describe('matchesQuery', () => {
+ it('matches on filename, case-insensitively', () => {
+ expect(matchesQuery(item(), 'STRIKE')).toBe(true);
+ expect(matchesQuery(item(), 'mosque')).toBe(false);
+ });
+
+ it('matches on title, notes and folder', () => {
+ expect(matchesQuery(item({ title: 'Mosque strike' }), 'mosque')).toBe(true);
+ expect(matchesQuery(item({ notes: 'seen near the bridge' }), 'bridge')).toBe(true);
+ expect(matchesQuery(item({ folder: 'Sources/Telegram' }), 'telegram')).toBe(true);
+ });
+
+ it('matches on the download source title, uploader and URL', () => {
+ const it_ = item({
+ source: { type: 'download', title: 'Artillery hit', uploader: 'chan42', webpage_url: 'https://t.me/chan42/7' },
+ });
+ expect(matchesQuery(it_, 'artillery')).toBe(true);
+ expect(matchesQuery(it_, 'chan42')).toBe(true);
+ expect(matchesQuery(it_, 't.me')).toBe(true);
+ });
+
+ it('requires every term (AND), in any field', () => {
+ const it_ = item({ title: 'Mosque strike', notes: 'northern district' });
+ expect(matchesQuery(it_, 'mosque northern')).toBe(true);
+ expect(matchesQuery(it_, 'mosque southern')).toBe(false);
+ });
+
+ it('empty or blank query matches everything', () => {
+ expect(matchesQuery(item(), '')).toBe(true);
+ expect(matchesQuery(item(), ' ')).toBe(true);
+ expect(matchesQuery(item(), null)).toBe(true);
+ });
+});
+
+describe('sortItems', () => {
+ const a = item({ filename: 'b.mp4', title: 'Bravo', size: 10, added_at: '2026-07-01T00:00:00Z' });
+ const b = item({ filename: 'a.jpg', title: null, size: 30, added_at: '2026-07-03T00:00:00Z' });
+ const c = item({ filename: 'c.png', title: 'alpha', size: 20, added_at: '2026-07-02T00:00:00Z' });
+
+ it('newest first (default)', () => {
+ expect(sortItems([a, b, c], 'newest').map((i) => i.filename)).toEqual(['a.jpg', 'c.png', 'b.mp4']);
+ });
+
+ it('oldest first', () => {
+ expect(sortItems([a, b, c], 'oldest').map((i) => i.filename)).toEqual(['b.mp4', 'c.png', 'a.jpg']);
+ });
+
+ it('name A–Z uses the display name (title over filename)', () => {
+ expect(sortItems([a, b, c], 'name').map((i) => i.filename)).toEqual(['a.jpg', 'c.png', 'b.mp4']);
+ });
+
+ it('largest first', () => {
+ expect(sortItems([a, b, c], 'size').map((i) => i.filename)).toEqual(['a.jpg', 'c.png', 'b.mp4']);
+ });
+
+ it('does not mutate the input', () => {
+ const input = [a, b, c];
+ sortItems(input, 'name');
+ expect(input.map((i) => i.filename)).toEqual(['b.mp4', 'a.jpg', 'c.png']);
+ });
+});
+
+describe('visibleMedia — case gating', () => {
+ const img = (extra = {}) => item({ filename: 'a.jpg', kind: 'image', ...extra });
+
+ it('returns nothing when no case is open, even with items still in memory', () => {
+ // Regression: closing a case leaves `items` populated for one reactive flush
+ // while caseState.current is null. The grid cards read caseState.current.id,
+ // so rendering that stale list threw and aborted the whole flush — which left
+ // *other* tools (e.g. the Proof Composer) un-reset. Gating on hasCase makes
+ // the grid empty regardless of effect ordering, so nothing dereferences null.
+ const items = [img(), img({ filename: 'b.png' })];
+ expect(visibleMedia(items, { hasCase: false })).toEqual([]);
+ });
+
+ it('returns the filtered+sorted list when a case is open (hasCase defaults true)', () => {
+ const items = [
+ img({ filename: 'b.jpg', added_at: '2026-07-02T00:00:00Z' }),
+ img({ filename: 'a.jpg', added_at: '2026-07-01T00:00:00Z' }),
+ ];
+ const out = visibleMedia(items, { sort: 'name' });
+ expect(out.map((i) => i.filename)).toEqual(['a.jpg', 'b.jpg']);
+ });
+
+ it('applies the category matcher, folder filter and query together', () => {
+ const items = [
+ img({ filename: 'road.jpg', folder: 'north', kind: 'image' }),
+ img({ filename: 'road.mp4', folder: 'north', kind: 'video' }),
+ img({ filename: 'river.jpg', folder: 'south', kind: 'image' }),
+ ];
+ const out = visibleMedia(items, {
+ hasCase: true,
+ catMatch: (i) => i.kind === 'image',
+ folderFilter: 'north',
+ query: 'road',
+ });
+ expect(out.map((i) => i.filename)).toEqual(['road.jpg']);
+ });
+
+ it('does not mutate the input list', () => {
+ const items = [img({ filename: 'b.jpg' }), img({ filename: 'a.jpg' })];
+ const snapshot = items.map((i) => i.filename);
+ visibleMedia(items, { sort: 'name' });
+ expect(items.map((i) => i.filename)).toEqual(snapshot);
+ });
+});
diff --git a/frontend/src/lib/refViewers.js b/frontend/src/lib/refViewers.js
new file mode 100644
index 0000000..03422a8
--- /dev/null
+++ b/frontend/src/lib/refViewers.js
@@ -0,0 +1,101 @@
+/**
+ * Reference viewers for the Satellite tab — small floating windows that hold a
+ * media image (the shot you're trying to geolocate) over the map, so you can
+ * eyeball it against the imagery while you pan. Pure, framework-free helpers for
+ * the fiddly bits: window placement/clamping, z-ordering, and cursor-anchored
+ * image zoom/pan. The Svelte glue (pointer events, DOM) lives in RefViewer.svelte.
+ *
+ * These viewers are session-only scratch aids: never captured, never saved.
+ */
+
+export const MIN_SCALE = 1; // 1 = image fits the window; can't zoom out past fit
+export const MAX_SCALE = 8;
+export const DEFAULT_W = 320;
+export const DEFAULT_H = 260;
+export const MIN_W = 200;
+export const MIN_H = 150;
+
+export function clamp(v, lo, hi) {
+ return Math.min(hi, Math.max(lo, v));
+}
+
+/**
+ * A fresh viewer for `media` ({ path, title }). `spawn` seeds the initial
+ * position/size/z so the caller can stagger new windows and stack them on top.
+ */
+export function createViewer(id, media, spawn = {}) {
+ return {
+ id,
+ path: media.path,
+ kind: media.kind === 'video' ? 'video' : 'image',
+ title: media.title || media.filename || '',
+ x: spawn.x ?? 60,
+ y: spawn.y ?? 60,
+ w: spawn.w ?? DEFAULT_W,
+ h: spawn.h ?? DEFAULT_H,
+ z: spawn.z ?? 1,
+ collapsed: false,
+ scale: 1, // image zoom (1 = fit)
+ ox: 0, // image pan offset in content px
+ oy: 0,
+ };
+}
+
+/** One more than the top-most viewer's z — the z to give a newly focused window. */
+export function nextZ(viewers) {
+ return viewers.reduce((m, v) => Math.max(m, v.z), 0) + 1;
+}
+
+/**
+ * Re-number z so `id` sits on top, keeping the values small and gap-free
+ * (1..n) instead of letting them climb without bound. Returns a Map of
+ * viewer id → new z for the caller to apply.
+ */
+export function restack(viewers, id) {
+ const others = viewers.filter((v) => v.id !== id).sort((a, b) => a.z - b.z);
+ const z = new Map();
+ others.forEach((v, i) => z.set(v.id, i + 1));
+ z.set(id, others.length + 1);
+ return z;
+}
+
+/** Keep a window of size `w`×`h` fully inside `bounds` ({ w, h }). */
+export function clampWindow(x, y, w, h, bounds) {
+ return {
+ x: clamp(x, 0, Math.max(0, bounds.w - w)),
+ y: clamp(y, 0, Math.max(0, bounds.h - h)),
+ };
+}
+
+/** Clamp a resize to the min size and to what fits between (x,y) and `bounds`. */
+export function clampSize(w, h, x, y, bounds) {
+ return {
+ w: clamp(w, MIN_W, Math.max(MIN_W, bounds.w - x)),
+ h: clamp(h, MIN_H, Math.max(MIN_H, bounds.h - y)),
+ };
+}
+
+/**
+ * Keep the scaled image covering its `w`×`h` viewport — no gap can open at an
+ * edge. At scale 1 this pins the offset to 0; deeper in it allows panning up to
+ * the amount the image overflows.
+ */
+export function clampPan(ox, oy, scale, w, h) {
+ return {
+ ox: clamp(ox, Math.min(0, w - scale * w), 0),
+ oy: clamp(oy, Math.min(0, h - scale * h), 0),
+ };
+}
+
+/**
+ * Zoom `view` by `factor` about `cursor` (content-px, relative to the viewport
+ * top-left), keeping the image point under the cursor fixed. `size` is the
+ * viewport ({ w, h }). Returns the new { scale, ox, oy }, pan re-clamped.
+ */
+export function zoomAt(view, factor, cursor, size) {
+ const scale = clamp(view.scale * factor, MIN_SCALE, MAX_SCALE);
+ const f = scale / view.scale; // actual ratio after clamping
+ const ox = cursor.x - f * (cursor.x - view.ox);
+ const oy = cursor.y - f * (cursor.y - view.oy);
+ return { scale, ...clampPan(ox, oy, scale, size.w, size.h) };
+}
diff --git a/frontend/src/lib/refViewers.test.js b/frontend/src/lib/refViewers.test.js
new file mode 100644
index 0000000..d2c85ed
--- /dev/null
+++ b/frontend/src/lib/refViewers.test.js
@@ -0,0 +1,134 @@
+import { describe, it, expect } from 'vitest';
+import {
+ createViewer,
+ nextZ,
+ restack,
+ clampWindow,
+ clampSize,
+ clampPan,
+ zoomAt,
+ MIN_SCALE,
+ MAX_SCALE,
+ MIN_W,
+ MIN_H,
+} from './refViewers.js';
+
+describe('createViewer', () => {
+ it('seeds sane defaults and prefers title over filename', () => {
+ const v = createViewer('a', { path: 'm/x.jpg', title: 'Shot', filename: 'x.jpg' });
+ expect(v.id).toBe('a');
+ expect(v.path).toBe('m/x.jpg');
+ expect(v.kind).toBe('image');
+ expect(v.title).toBe('Shot');
+ expect(v.scale).toBe(1);
+ expect(v.ox).toBe(0);
+ expect(v.collapsed).toBe(false);
+ });
+
+ it('falls back to filename, then empty title', () => {
+ expect(createViewer('a', { path: 'p', filename: 'x.jpg' }).title).toBe('x.jpg');
+ expect(createViewer('a', { path: 'p' }).title).toBe('');
+ });
+
+ it('marks videos, defaulting anything else to image', () => {
+ expect(createViewer('a', { path: 'p', kind: 'video' }).kind).toBe('video');
+ expect(createViewer('a', { path: 'p', kind: 'image' }).kind).toBe('image');
+ expect(createViewer('a', { path: 'p' }).kind).toBe('image');
+ });
+
+ it('honours spawn overrides', () => {
+ const v = createViewer('a', { path: 'p' }, { x: 10, y: 20, z: 4 });
+ expect([v.x, v.y, v.z]).toEqual([10, 20, 4]);
+ });
+});
+
+describe('nextZ', () => {
+ it('is one above the top-most window (1 for an empty set)', () => {
+ expect(nextZ([])).toBe(1);
+ expect(nextZ([{ z: 1 }, { z: 5 }, { z: 3 }])).toBe(6);
+ });
+});
+
+describe('restack', () => {
+ it('puts the focused window on top and re-numbers 1..n gap-free', () => {
+ const vs = [
+ { id: 'a', z: 2 },
+ { id: 'b', z: 5 },
+ { id: 'c', z: 9 },
+ ];
+ const z = restack(vs, 'a');
+ expect(z.get('b')).toBe(1);
+ expect(z.get('c')).toBe(2);
+ expect(z.get('a')).toBe(3); // focused → highest
+ });
+
+ it('handles a single window', () => {
+ expect(restack([{ id: 'a', z: 7 }], 'a').get('a')).toBe(1);
+ });
+});
+
+describe('clampWindow', () => {
+ const bounds = { w: 1000, h: 600 };
+ it('keeps the window inside the bounds', () => {
+ expect(clampWindow(-20, -10, 320, 260, bounds)).toEqual({ x: 0, y: 0 });
+ expect(clampWindow(9999, 9999, 320, 260, bounds)).toEqual({ x: 680, y: 340 });
+ });
+ it('pins to 0 when the window is larger than the bounds', () => {
+ expect(clampWindow(50, 50, 1200, 800, bounds)).toEqual({ x: 0, y: 0 });
+ });
+});
+
+describe('clampSize', () => {
+ const bounds = { w: 1000, h: 600 };
+ it('enforces the minimum size', () => {
+ expect(clampSize(10, 10, 0, 0, bounds)).toEqual({ w: MIN_W, h: MIN_H });
+ });
+ it('caps growth to what fits from (x, y)', () => {
+ expect(clampSize(9999, 9999, 700, 400, bounds)).toEqual({ w: 300, h: 200 });
+ });
+});
+
+describe('clampPan', () => {
+ it('pins offset to 0 at fit scale', () => {
+ expect(clampPan(-50, -50, 1, 300, 200)).toEqual({ ox: 0, oy: 0 });
+ expect(clampPan(50, 50, 1, 300, 200)).toEqual({ ox: 0, oy: 0 });
+ });
+ it('allows panning up to the overflow when zoomed in', () => {
+ // scale 2 over a 300px width overflows by 300px → offset ∈ [-300, 0]
+ expect(clampPan(-500, 0, 2, 300, 200).ox).toBe(-300);
+ expect(clampPan(100, 0, 2, 300, 200).ox).toBe(0);
+ expect(clampPan(-120, -80, 2, 300, 200)).toEqual({ ox: -120, oy: -80 });
+ });
+});
+
+describe('zoomAt', () => {
+ const size = { w: 300, h: 200 };
+
+ it('keeps the point under the cursor fixed while zooming in', () => {
+ const view = { scale: 1, ox: 0, oy: 0 };
+ const cursor = { x: 150, y: 100 }; // centre
+ const r = zoomAt(view, 2, cursor, size);
+ expect(r.scale).toBe(2);
+ // image point under a centred cursor stays centred: c - f*(c-ox) = 150-2*150=-150
+ expect(r.ox).toBe(-150);
+ expect(r.oy).toBe(-100);
+ });
+
+ it('clamps to the max scale', () => {
+ const r = zoomAt({ scale: MAX_SCALE, ox: 0, oy: 0 }, 2, { x: 0, y: 0 }, size);
+ expect(r.scale).toBe(MAX_SCALE);
+ });
+
+ it('clamps to the min scale and re-pins the offset to 0', () => {
+ const r = zoomAt({ scale: 1, ox: 0, oy: 0 }, 0.5, { x: 150, y: 100 }, size);
+ expect(r.scale).toBe(MIN_SCALE);
+ expect(r).toMatchObject({ ox: 0, oy: 0 });
+ });
+
+ it('never opens a gap at the edge (offset stays clamped)', () => {
+ // zoom about the top-left corner would push the image right (ox > 0) — clamp to 0
+ const r = zoomAt({ scale: 1, ox: 0, oy: 0 }, 2, { x: 0, y: 0 }, size);
+ expect(r.ox).toBe(0);
+ expect(r.oy).toBe(0);
+ });
+});
diff --git a/frontend/src/lib/satRotate.js b/frontend/src/lib/satRotate.js
new file mode 100644
index 0000000..5b735f7
--- /dev/null
+++ b/frontend/src/lib/satRotate.js
@@ -0,0 +1,34 @@
+/**
+ * Middle-drag map rotation for the Satellite tab — the same Google-Earth
+ * "grab & turn" as the Frame viewer, but driving a Leaflet map bearing.
+ *
+ * Leaflet's `setBearing` always rotates about the map centre, so to turn around
+ * an arbitrary grabbed point we set the bearing and then pan the map so the
+ * grabbed location slides back under the cursor. These two pure helpers hold the
+ * bits that are easy to get subtly wrong (the swept-angle bearing and, above
+ * all, the *sign* of the compensating pan); the Leaflet glue lives in the tool.
+ */
+
+import { pointerAngleDeg } from './frameRotate.js';
+
+/**
+ * New map bearing after sweeping the pointer around a fixed screen `pivot`,
+ * from `start` to `cur` (all `{x, y}` in screen px). The turn tracks the angle
+ * the cursor sweeps about the pivot — grab, then circle to rotate.
+ */
+export function dragBearing(startBearing, pivot, start, cur) {
+ const delta =
+ pointerAngleDeg(pivot.x, pivot.y, cur.x, cur.y) -
+ pointerAngleDeg(pivot.x, pivot.y, start.x, start.y);
+ return startBearing + delta;
+}
+
+/**
+ * The `[dx, dy]` to `map.panBy` so a pivot that a bearing change pushed from
+ * `grab` to `now` (both container-pixel points) returns exactly under `grab`.
+ * Leaflet's `panBy(offset)` shifts every container point by `-offset`, so to
+ * move the pivot by `grab - now` we pan by `now - grab`.
+ */
+export function pivotPanOffset(grab, now) {
+ return [now.x - grab.x, now.y - grab.y];
+}
diff --git a/frontend/src/lib/satRotate.test.js b/frontend/src/lib/satRotate.test.js
new file mode 100644
index 0000000..8cc5e17
--- /dev/null
+++ b/frontend/src/lib/satRotate.test.js
@@ -0,0 +1,43 @@
+import { describe, it, expect } from 'vitest';
+import { dragBearing, pivotPanOffset } from './satRotate.js';
+
+const near = (a, b, eps = 1e-9) => Math.abs(a - b) < eps;
+
+describe('dragBearing', () => {
+ const pivot = { x: 100, y: 100 };
+
+ it('adds the swept angle to the starting bearing', () => {
+ // start due east of the pivot, sweep to due south → +90° (screen, Y down)
+ const b = dragBearing(30, pivot, { x: 200, y: 100 }, { x: 100, y: 200 });
+ expect(near(b, 120)).toBe(true);
+ });
+
+ it('turns the other way when the sweep reverses', () => {
+ // east → north is -90°
+ const b = dragBearing(0, pivot, { x: 200, y: 100 }, { x: 100, y: 0 });
+ expect(near(b, -90)).toBe(true);
+ });
+
+ it('is a no-op when the cursor has not moved off the reference spoke', () => {
+ const b = dragBearing(42, pivot, { x: 160, y: 100 }, { x: 160, y: 100 });
+ expect(near(b, 42)).toBe(true);
+ });
+});
+
+describe('pivotPanOffset', () => {
+ it('cancels the drift so panBy re-pins the pivot under the grab point', () => {
+ // Leaflet shifts container points by -offset; panning by (now-grab) moves
+ // the drifted pivot (now) back onto grab.
+ const grab = { x: 120, y: 80 };
+ const now = { x: 135, y: 60 };
+ const [dx, dy] = pivotPanOffset(grab, now);
+ expect([dx, dy]).toEqual([15, -20]);
+ // apply the -offset shift Leaflet performs → pivot lands back on grab
+ expect(now.x - dx).toBe(grab.x);
+ expect(now.y - dy).toBe(grab.y);
+ });
+
+ it('is zero when the pivot did not drift', () => {
+ expect(pivotPanOffset({ x: 10, y: 10 }, { x: 10, y: 10 })).toEqual([0, 0]);
+ });
+});
diff --git a/frontend/src/lib/savedGrouping.js b/frontend/src/lib/savedGrouping.js
new file mode 100644
index 0000000..7575e3e
--- /dev/null
+++ b/frontend/src/lib/savedGrouping.js
@@ -0,0 +1,28 @@
+/**
+ * "Saved work" grouping for the case sidebar: every filed entity, bucketed by
+ * the tool that produced it — except filed images/videos, which are media
+ * first and belong under Media Library no matter which tool produced them
+ * (e.g. a frame saved from Inspect, or a satellite capture).
+ */
+
+export const TOOL_GROUPS = [
+ ['media-library', 'Media Library', 'image'],
+ ['inspect', 'Inspect', 'inspect'],
+ ['satellite', 'Satellite', 'satellite'],
+ ['proof-composer', 'Proof Composer', 'proof'],
+ ['post-composer', 'Post Composer', 'post'],
+ ['user', 'Notes & manual', 'note'],
+];
+
+export const KNOWN_TOOLS = new Set(TOOL_GROUPS.map(([k]) => k).filter((k) => k !== 'user'));
+
+// Entity types that are filed images/videos living in media/, whatever tool
+// produced them: plain uploads/derivatives ('media') and satellite captures
+// ('capture', which additionally carry lat/lon/zoom).
+const MEDIA_ENTITY_TYPES = new Set(['media', 'capture']);
+
+export function groupKey(entity) {
+ if (MEDIA_ENTITY_TYPES.has(entity.type)) return 'media-library';
+ const by = entity.provenance?.by;
+ return KNOWN_TOOLS.has(by) ? by : 'user';
+}
diff --git a/frontend/src/lib/savedGrouping.test.js b/frontend/src/lib/savedGrouping.test.js
new file mode 100644
index 0000000..0831e61
--- /dev/null
+++ b/frontend/src/lib/savedGrouping.test.js
@@ -0,0 +1,25 @@
+import { describe, it, expect } from 'vitest';
+import { groupKey } from './savedGrouping.js';
+
+describe('groupKey', () => {
+ it('buckets plain media entities under Media Library', () => {
+ expect(groupKey({ type: 'media', provenance: { by: 'media-library' } })).toBe('media-library');
+ });
+
+ it('buckets satellite captures under Media Library, not Satellite', () => {
+ // a capture is a filed image first — the fact that the satellite tool
+ // produced it (provenance.by === 'satellite') shouldn't override that
+ expect(groupKey({ type: 'capture', provenance: { by: 'satellite' } })).toBe('media-library');
+ });
+
+ it('buckets a non-image entity by its producing tool', () => {
+ expect(groupKey({ type: 'place', provenance: { by: 'satellite' } })).toBe('satellite');
+ expect(groupKey({ type: 'proof', provenance: { by: 'proof-composer' } })).toBe('proof-composer');
+ });
+
+ it('falls back to "user" for an unknown or missing producing tool', () => {
+ expect(groupKey({ type: 'note', provenance: { by: 'user' } })).toBe('user');
+ expect(groupKey({ type: 'note' })).toBe('user');
+ expect(groupKey({ type: 'place', provenance: { by: 'some-future-tool' } })).toBe('user');
+ });
+});
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index 0615521..86e440b 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -27,6 +27,10 @@ export const uiState = $state({
focusMedia: null, // media path to highlight & scroll to in the Media Library
openInspect: null, // inspect-session name to reopen in the Inspect tool
gotoCoords: null, // { lat, lon } to fly to in the Satellite tool
+ // Satellite reference viewers: floating scratch windows holding a media image
+ // over the map to eyeball against the imagery. Session-only — never captured
+ // or saved, and dropped when the open case changes (they point at its media).
+ refViewers: [],
});
let toastSeq = 0;
@@ -59,6 +63,8 @@ function rememberCase(id) {
export async function openCase(id) {
caseState.loading = true;
try {
+ // reference viewers point at the previous case's media — drop them
+ if (caseState.current?.id !== id) uiState.refViewers = [];
caseState.current = await api.get(`/api/cases/${id}`);
rememberCase(id);
} finally {
@@ -132,9 +138,24 @@ export async function promoteCase(name) {
toast(`Promoted to case “${name}”`, 'ok');
}
+/**
+ * Close the open case (dropping back to one-shot mode). Also clears every
+ * cross-tool handoff — otherwise a queued handoff meant for the closed case
+ * (e.g. "open this proof") could get consumed against whatever case comes
+ * next, since the consuming effects only check that *some* case is open.
+ */
export function closeCase() {
caseState.current = null;
rememberCase(null);
+ uiState.composeQueue = [];
+ uiState.postProof = null;
+ uiState.openProof = null;
+ uiState.openDraft = null;
+ uiState.inspectPath = null;
+ uiState.focusMedia = null;
+ uiState.openInspect = null;
+ uiState.gotoCoords = null;
+ uiState.refViewers = [];
}
/**
diff --git a/frontend/src/lib/state.test.js b/frontend/src/lib/state.test.js
new file mode 100644
index 0000000..fd74a05
--- /dev/null
+++ b/frontend/src/lib/state.test.js
@@ -0,0 +1,33 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { caseState, uiState, closeCase } from './state.svelte.js';
+
+describe('closeCase', () => {
+ beforeEach(() => {
+ caseState.current = { id: 'case-a', name: 'Case A' };
+ uiState.composeQueue = ['media/a.jpg'];
+ uiState.postProof = { title: 'x' };
+ uiState.openProof = 'proof-a';
+ uiState.openDraft = 'draft-a';
+ uiState.inspectPath = 'media/a.jpg';
+ uiState.focusMedia = 'media/a.jpg';
+ uiState.openInspect = 'session-a';
+ uiState.gotoCoords = { lat: 1, lon: 2 };
+ });
+
+ it('drops the open case', () => {
+ closeCase();
+ expect(caseState.current).toBeNull();
+ });
+
+ it('clears every cross-tool handoff, so nothing meant for the closed case leaks into whatever opens next', () => {
+ closeCase();
+ expect(uiState.composeQueue).toEqual([]);
+ expect(uiState.postProof).toBeNull();
+ expect(uiState.openProof).toBeNull();
+ expect(uiState.openDraft).toBeNull();
+ expect(uiState.inspectPath).toBeNull();
+ expect(uiState.focusMedia).toBeNull();
+ expect(uiState.openInspect).toBeNull();
+ expect(uiState.gotoCoords).toBeNull();
+ });
+});
diff --git a/frontend/src/lib/usage.js b/frontend/src/lib/usage.js
new file mode 100644
index 0000000..c6d1674
--- /dev/null
+++ b/frontend/src/lib/usage.js
@@ -0,0 +1,46 @@
+/**
+ * Keyed-provider usage bookkeeping (docs/KEYED_PROVIDERS.md §6).
+ *
+ * Billed providers (Mapbox, Google) get a per-month tile counter in
+ * settings.json, maintained entirely by the backend: captures count the tiles
+ * they stitch, and the live map's tiles flow through the backend proxy which
+ * counts each one it serves. The frontend only reads the tally.
+ */
+
+/**
+ * Documented monthly free allowances, in tile requests — a yardstick for the
+ * counter, not a guarantee (providers change their pricing; verify on their
+ * pricing pages). Mapbox Static Tiles: 200k/month, then pay-as-you-go per
+ * extra 1,000 (billed to the card on the account). Google 2D Map Tiles:
+ * 100k/month, then billed per extra 1,000 against the Cloud project —
+ * a quota cap set in the Cloud Console makes it stop instead of bill.
+ */
+export const FREE_TIER = { mapbox: 200_000, google: 100_000 };
+
+/** The usage bucket for a moment in time: "YYYY-MM" (UTC, matches backend). */
+export function monthKey(date = new Date()) {
+ return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}`;
+}
+
+/** This month's tally for a meter out of the settings `usage` map. */
+export function monthCount(usage, meter, month = monthKey()) {
+ return Number(usage?.[meter]?.[month] ?? 0);
+}
+
+/** Compact readout for the map pill: "767 tiles". */
+export function tilesShort(count) {
+ return `${count.toLocaleString('en-US')} tile${count === 1 ? '' : 's'}`;
+}
+
+/** Settings readout against the free allowance: "767 / 200,000 free tiles". */
+export function tilesOfFree(count, meter) {
+ const free = FREE_TIER[meter];
+ if (!free) return tilesShort(count);
+ return `${count.toLocaleString('en-US')} / ${free.toLocaleString('en-US')} free tiles`;
+}
+
+/** Share of the free allowance used this month, 0–1 (can exceed 1). */
+export function freeTierShare(count, meter) {
+ const free = FREE_TIER[meter];
+ return free ? count / free : 0;
+}
diff --git a/frontend/src/lib/usage.test.js b/frontend/src/lib/usage.test.js
new file mode 100644
index 0000000..add07b7
--- /dev/null
+++ b/frontend/src/lib/usage.test.js
@@ -0,0 +1,62 @@
+import { describe, it, expect } from 'vitest';
+import {
+ monthKey,
+ monthCount,
+ tilesShort,
+ tilesOfFree,
+ freeTierShare,
+ FREE_TIER,
+} from './usage.js';
+
+describe('monthKey', () => {
+ it('formats a UTC year-month bucket', () => {
+ expect(monthKey(new Date(Date.UTC(2026, 6, 14)))).toBe('2026-07');
+ expect(monthKey(new Date(Date.UTC(2026, 11, 31)))).toBe('2026-12');
+ });
+});
+
+describe('monthCount', () => {
+ const usage = { google: { '2026-07': 1234 }, mapbox: { '2026-07': 87 } };
+
+ it('reads the month bucket for a meter', () => {
+ expect(monthCount(usage, 'google', '2026-07')).toBe(1234);
+ });
+
+ it('is zero for unknown meters or empty usage', () => {
+ expect(monthCount(usage, 'bing', '2026-07')).toBe(0);
+ expect(monthCount(undefined, 'google', '2026-07')).toBe(0);
+ expect(monthCount(usage, 'google', '2026-01')).toBe(0);
+ });
+});
+
+describe('tilesShort', () => {
+ it('is a compact map-pill readout', () => {
+ expect(tilesShort(767)).toBe('767 tiles');
+ expect(tilesShort(12430)).toBe('12,430 tiles');
+ expect(tilesShort(1)).toBe('1 tile');
+ });
+});
+
+describe('tilesOfFree', () => {
+ it('shows the count against the documented free allowance', () => {
+ expect(tilesOfFree(767, 'mapbox')).toBe('767 / 200,000 free tiles');
+ expect(tilesOfFree(12430, 'google')).toBe('12,430 / 100,000 free tiles');
+ });
+
+ it('falls back to the plain count for meters without a known allowance', () => {
+ expect(tilesOfFree(42, 'bing')).toBe('42 tiles');
+ });
+});
+
+describe('freeTierShare', () => {
+ it('is the fraction of the free allowance used', () => {
+ expect(freeTierShare(100_000, 'mapbox')).toBe(0.5);
+ expect(freeTierShare(150_000, 'google')).toBe(1.5); // over — UI can warn
+ expect(freeTierShare(500, 'unknown')).toBe(0);
+ });
+
+ it('free tiers stay in sync with the label helper', () => {
+ expect(FREE_TIER.mapbox).toBe(200_000);
+ expect(FREE_TIER.google).toBe(100_000);
+ });
+});
diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelte
index c6cf72b..a02553d 100644
--- a/frontend/src/tools/Inspector.svelte
+++ b/frontend/src/tools/Inspector.svelte
@@ -3,9 +3,13 @@
import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';
import {
adjustDefaults, buildOps, previewStyle, isNeutral, uid, videoSeed, initialQuad, VIDEO_ADJUST_IDS,
- cropImgStyle, cropAspect, styleText, collageBounds, quadFromCropRect,
+ collageBounds, quadFromCropRect, cropImgStyle, cropAspect, styleText,
} from '../lib/inspect.js';
+ import { createHistory } from '../lib/history.js';
+ import { IDENTITY, matrixCss, rotateAbout, isIdentity, matrixAngleDeg, pointerAngleDeg } from '../lib/frameRotate.js';
import Icon from '../components/Icon.svelte';
+ import ConfirmDialog from '../components/ConfirmDialog.svelte';
+ import CropBox from './inspect/CropBox.svelte';
import SelectionMenu from './inspect/SelectionMenu.svelte';
import FrameMenu from './inspect/FrameMenu.svelte';
import CollageCanvas from './inspect/CollageCanvas.svelte';
@@ -43,6 +47,7 @@
// in place instead of forking a new named session.
let openedSession = $state(null);
const sessionModal = $state({ open: false, mode: 'save', name: null, title: '', list: [], busy: false });
+ let discardConfirm = $state(false);
// A fresh, empty collage. A session can hold several — the Collage tab edits
// one at a time (session.activeCollageId) and each is saved as its own PNG.
@@ -66,10 +71,119 @@
session.collages.find((c) => c.id === session.activeCollageId) ?? session.collages[0] ?? null
);
+ // ---- collage undo / redo --------------------------------------------------
+ // Snapshot history over the collages (quads, pieces, crops). A drag mutates
+ // node.quad continuously; the debounced capture collapses it into one entry.
+ const collageHistory = createHistory();
+ let collageCanUndo = $state(false);
+ let collageCanRedo = $state(false);
+ let collageHistBusy = false; // plain (untracked): suppresses capture while restoring
+ let collageHistTimer = null;
+
+ const collageSnapshot = () => JSON.stringify(session.collages);
+
+ function syncCollageHist() {
+ collageCanUndo = collageHistory.canUndo;
+ collageCanRedo = collageHistory.canRedo;
+ }
+
+ function anchorCollageHistory() {
+ clearTimeout(collageHistTimer);
+ collageHistory.reset(collageSnapshot());
+ syncCollageHist();
+ }
+
+ $effect(() => {
+ const json = collageSnapshot(); // reads every collage field → tracked
+ if (collageHistBusy) return;
+ clearTimeout(collageHistTimer);
+ collageHistTimer = setTimeout(() => {
+ collageHistory.push(json);
+ syncCollageHist();
+ }, 350);
+ });
+
+ function applyCollageSnapshot(json) {
+ collageHistBusy = true;
+ session.collages = JSON.parse(json);
+ if (!session.collages.some((c) => c.id === session.activeCollageId)) {
+ session.activeCollageId = session.collages[0]?.id ?? null;
+ }
+ collageSelectedId = null;
+ // outlast the capture debounce so the restore itself is not re-recorded
+ setTimeout(() => (collageHistBusy = false), 400);
+ }
+
+ function undoCollage() {
+ const json = collageHistory.undo();
+ if (json != null) applyCollageSnapshot(json);
+ syncCollageHist();
+ }
+
+ function redoCollage() {
+ const json = collageHistory.redo();
+ if (json != null) applyCollageSnapshot(json);
+ syncCollageHist();
+ }
+
+ // ---- keyboard: collage undo + frame-accurate video stepping ----------------
+ const frameDur = $derived(probeInfo?.fps ? 1 / probeInfo.fps : 1 / 30);
+
+ function stepVideo(delta) {
+ const duration = probeInfo?.duration ?? Infinity;
+ shared.seekTo = Math.min(Math.max((shared.currentTime ?? 0) + delta, 0), duration);
+ }
+
+ function onWindowKeydown(e) {
+ if (uiState.tool !== 'inspect') return;
+ const t = e.target;
+ if (['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName) || t.isContentEditable) return;
+ if (e.ctrlKey || e.metaKey) {
+ if (activeTab !== 'collage') return;
+ const k = e.key.toLowerCase();
+ if (k === 'z') { e.preventDefault(); e.shiftKey ? redoCollage() : undoCollage(); }
+ else if (k === 'y') { e.preventDefault(); redoCollage(); }
+ return;
+ }
+ // Frame tab: Enter applies the crop (→ committed preview), Esc leaves editing.
+ if (activeTab === 'frame' && cropEditing) {
+ if (e.key === 'Enter' || e.key === 'Escape') { e.preventDefault(); commitCrop(); }
+ return;
+ }
+ // Selection tab: ←/→ step one frame (Shift = 1s), ,/. mpv-style aliases
+ if (activeTab !== 'selection' || session.source?.kind !== 'video') return;
+ if (e.key === 'ArrowLeft') { e.preventDefault(); stepVideo(e.shiftKey ? -1 : -frameDur); }
+ else if (e.key === 'ArrowRight') { e.preventDefault(); stepVideo(e.shiftKey ? 1 : frameDur); }
+ else if (e.key === ',') { e.preventDefault(); stepVideo(-frameDur); }
+ else if (e.key === '.') { e.preventDefault(); stepVideo(frameDur); }
+ }
+
+ // keep-alive: tools stay mounted when another tab is shown — silence the video
+ $effect(() => {
+ if (uiState.tool !== 'inspect') videoEl?.pause();
+ });
+
// viewer bridge (video seek + crop overlay), mirrors the old shared object
const shared = $state({ currentTime: 0, seekTo: null, cropMode: false });
let videoEl = $state();
- let cropDraw = $state(null);
+ // Frame-tab viewer: wheel-zoom toward the pointer, left-drag pans, middle-drag
+ // turns the view (Google-Earth style, around the grabbed point). Zoom/pan/
+ // rotate are *view only* — never saved — so turning just helps read the frame.
+ // The rotation is an affine matrix in the stage's own space (see frameRotate.js);
+ // `frameAspect` is the crop aspect lock, shared with the right-panel controls.
+ let frameZoom = $state(1);
+ let framePan = $state({ x: 0, y: 0 });
+ let frameRotMatrix = $state(IDENTITY); // accumulated view rotation (stage-local)
+ let rotating = $state(false); // a middle-drag turn is in progress
+ let rotatePivot = $state({ x: 0, y: 0 }); // target indicator, viewport-local px
+ let frameStageEl = $state(); // rotated stage (image + crop overlay)
+ let frameZoomEl = $state(); // zoom/pan layer — reference box for screen→local
+ let frameViewportEl = $state(); // outer viewport — reference box for the indicator
+ let frameAspect = $state(null);
+ // Crop has two modes: *editing* (original image + draggable box) and, once
+ // applied (Enter / Apply), a committed *preview* showing the cropped result.
+ // Re-opening crop (button or double-click) goes back to editing the original.
+ let cropEditing = $state(false);
const videoFilters = $derived(filters.filter((f) => VIDEO_ADJUST_IDS.includes(f.id)));
const tabs = $derived(
@@ -111,11 +225,14 @@
// -- lifecycle ------------------------------------------------------------
$effect(() => {
const id = caseState.current?.id;
+ caseState.rev; // refetch when media changes elsewhere (e.g. Media Library upload/delete)
if (id !== loadedFor) {
loadedFor = id;
mediaList = [];
resetSession();
if (id) refresh(id);
+ } else if (id) {
+ refresh(id);
}
});
@@ -146,7 +263,9 @@
async function ensureOps() {
if (filters.length) return;
const ops = await api.get('/api/inspect/ops');
- filters = ops.filters.filter((f) => f.id !== 'crop');
+ // `crop` is driven by the interactive box; `rotate` is a view-only tilt in
+ // the Frame tab (never baked) — neither belongs in the slider pipeline.
+ filters = ops.filters.filter((f) => f.id !== 'crop' && f.id !== 'rotate');
analyses = ops.analyses;
}
@@ -173,7 +292,13 @@
collageSelectedId = null;
shared.currentTime = 0;
shared.cropMode = false;
- cropDraw = null;
+ frameZoom = 1;
+ framePan = { x: 0, y: 0 };
+ frameRotMatrix = IDENTITY;
+ rotating = false;
+ frameAspect = null;
+ cropEditing = false;
+ anchorCollageHistory();
}
async function select(item) {
@@ -329,9 +454,8 @@
? quadFromCropRect(node.quad, { x: -prev.x / prev.w, y: -prev.y / prev.h, w: 1 / prev.w, h: 1 / prev.h })
: node.quad;
node.quad = crop ? quadFromCropRect(baseQuad, crop) : baseQuad.map(([x, y]) => [x, y]);
- if (node.url && node.url !== node.baseUrl && node.url.startsWith('blob:')) {
- URL.revokeObjectURL(node.url);
- }
+ // the previous blob URL stays alive: an undo may restore a snapshot that
+ // still points at it (bounded leak, reclaimed on session reset/reload)
node.url = url;
node.w = dim.w;
node.h = dim.h;
@@ -360,38 +484,140 @@
if (session.activeFrameId === id) session.activeFrameId = session.frames[0]?.id ?? null;
}
- // -- crop overlay (Frame tab) --------------------------------------------
- function frac(e, el) {
- const r = el.getBoundingClientRect();
- return {
- x: Math.min(Math.max((e.clientX - r.left) / r.width, 0), 1),
- y: Math.min(Math.max((e.clientY - r.top) / r.height, 0), 1),
- };
+ // -- frame viewer: zoom / pan / straighten (Frame tab) -------------------
+ // Reset the view whenever the active frame changes.
+ $effect(() => {
+ session.activeFrameId; // track
+ frameZoom = 1;
+ framePan = { x: 0, y: 0 };
+ frameRotMatrix = IDENTITY;
+ frameAspect = null;
+ cropEditing = false;
+ shared.cropMode = false;
+ });
+
+ // Enter crop editing (original + box); arm a fresh draw if there's no box yet.
+ function beginCrop() {
+ if (!activeFrame) return;
+ cropEditing = true;
+ if (!activeFrame.crop) shared.cropMode = true;
+ }
+ // Apply the crop → drop back to the committed preview of the cropped result.
+ function commitCrop() {
+ cropEditing = false;
+ shared.cropMode = false;
}
- function cropDown(e) {
- if (!shared.cropMode || !activeFrame) return;
+
+ // Wheel zooms toward the pointer (never below the fitted size); at 1× the pan
+ // snaps back to centre so the image can't drift off.
+ function frameWheel(e) {
+ if (!activeFrame) return;
e.preventDefault();
- const p = frac(e, e.currentTarget);
- cropDraw = { sx: p.x, sy: p.y, x: p.x, y: p.y, w: 0, h: 0 };
- e.currentTarget.setPointerCapture(e.pointerId);
- }
- function cropMove(e) {
- if (!cropDraw) return;
- const p = frac(e, e.currentTarget);
- cropDraw = {
- sx: cropDraw.sx, sy: cropDraw.sy,
- x: Math.min(cropDraw.sx, p.x), y: Math.min(cropDraw.sy, p.y),
- w: Math.abs(p.x - cropDraw.sx), h: Math.abs(p.y - cropDraw.sy),
+ const r = e.currentTarget.getBoundingClientRect();
+ const px = e.clientX - r.left;
+ const py = e.clientY - r.top;
+ const cX = r.width / 2;
+ const cY = r.height / 2;
+ const old = frameZoom;
+ const next = Math.min(Math.max(old * (e.deltaY > 0 ? 0.9 : 1.1), 1), 8);
+ if (next === 1) {
+ frameZoom = 1;
+ framePan = { x: 0, y: 0 };
+ return;
+ }
+ // keep the point under the pointer fixed (transform-origin is the centre)
+ const ratio = next / old;
+ framePan = {
+ x: px - (px - (cX + framePan.x)) * ratio - cX,
+ y: py - (py - (cY + framePan.y)) * ratio - cY,
+ };
+ frameZoom = next;
+ }
+
+ function resetFrameView() {
+ frameZoom = 1;
+ framePan = { x: 0, y: 0 };
+ frameRotMatrix = IDENTITY;
+ }
+
+ const frameViewDirty = $derived(
+ frameZoom !== 1 || framePan.x !== 0 || framePan.y !== 0 || !isIdentity(frameRotMatrix)
+ );
+ const frameAngle = $derived(Math.round(matrixAngleDeg(frameRotMatrix)));
+
+ // Middle-drag turns the *view* (never saved), Google-Earth style: a stylised
+ // target marks the exact point you grabbed and the image spins around it as you
+ // move the mouse — the turn follows the angle the cursor sweeps about that
+ // pivot. The rotation is kept as a matrix in the stage's own space, so it
+ // composes on top of any prior zoom / pan / rotate: every new grab pivots from
+ // wherever you click, with no jump, no matter what the view already looks like.
+ const ROTATE_DEADZONE = 8; // px to move off the pivot before a spoke is fixed
+ function frameRotateStart(e) {
+ if (!activeFrame || !frameStageEl || !frameZoomEl || !frameViewportEl) return;
+ // The zoom/pan layer carries only translate + scale (no rotation), so its
+ // on-screen box gives a clean screen→local map — read it live so the pivot is
+ // correct whatever the current zoom/pan is. offsetLeft/Top place the stage's
+ // origin (its transform-origin, 0 0) within that layer, unaffected by rotation.
+ const layer = frameZoomEl.getBoundingClientRect();
+ const vp = frameViewportEl.getBoundingClientRect();
+ const px = (e.clientX - layer.left) / frameZoom - frameStageEl.offsetLeft;
+ const py = (e.clientY - layer.top) / frameZoom - frameStageEl.offsetTop;
+ const base = frameRotMatrix; // freeze the accumulated rotation for this gesture
+ const pivotX = e.clientX;
+ const pivotY = e.clientY;
+ rotatePivot = { x: e.clientX - vp.left, y: e.clientY - vp.top };
+ rotating = true;
+ let startAngle = null; // the reference spoke, fixed once the cursor leaves the deadzone
+ const move = (ev) => {
+ if (startAngle === null) {
+ if (Math.hypot(ev.clientX - pivotX, ev.clientY - pivotY) < ROTATE_DEADZONE) return;
+ startAngle = pointerAngleDeg(pivotX, pivotY, ev.clientX, ev.clientY);
+ return;
+ }
+ const delta = pointerAngleDeg(pivotX, pivotY, ev.clientX, ev.clientY) - startAngle;
+ frameRotMatrix = rotateAbout(base, px, py, delta);
};
+ const up = () => {
+ rotating = false;
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ }
+
+ // Kill the browser's middle-click auto-scroll so a turn doesn't also pan-scroll.
+ function frameMouseDown(e) {
+ if (e.button === 1) e.preventDefault();
}
- function cropUp() {
- if (cropDraw && cropDraw.w > 0.02 && cropDraw.h > 0.02 && activeFrame) {
- activeFrame.crop = { x: cropDraw.x, y: cropDraw.y, w: cropDraw.w, h: cropDraw.h };
- shared.cropMode = false;
+
+ // Left-drag on the image pans the view.
+ function framePanStart(e) {
+ const sx = e.clientX;
+ const sy = e.clientY;
+ const ox = framePan.x;
+ const oy = framePan.y;
+ const move = (ev) => {
+ framePan = { x: ox + ev.clientX - sx, y: oy + ev.clientY - sy };
+ };
+ const up = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ }
+
+ function frameViewportDown(e) {
+ if (e.button === 1) {
+ e.preventDefault();
+ if (!cropEditing) frameRotateStart(e); // keep the crop box un-rotated
+ return;
}
- cropDraw = null;
+ if (e.button !== 0 || shared.cropMode || cropEditing) return; // crop box owns drags
+ e.preventDefault(); // stop the browser's native image-drag ghost
+ framePanStart(e);
}
- const cropBox = $derived(cropDraw ?? activeFrame?.crop ?? null);
// -- save (the only gate that files entities) ----------------------------
async function saveSelected() {
@@ -571,6 +797,12 @@
openedSession = { name, title: spec.title || name };
activeTab = src.kind === 'video' ? 'selection' : 'frame';
sessionModal.open = false;
+ anchorCollageHistory();
+ }
+
+ function discardSession() {
+ resetSession();
+ discardConfirm = false;
}
async function deleteSession(name) {
@@ -585,6 +817,8 @@
}
</script>
+<svelte:window onkeydown={onWindowKeydown} />
+
<div class="tool">
<div class="tool-header">
<h2>Inspect</h2>
@@ -594,6 +828,11 @@
<button class="btn btn-sm" onclick={openLoadDialog} title="Reopen a saved session">
<Icon name="folderOpen" size={14} /> Open
</button>
+ {#if session.source}
+ <button class="btn btn-sm" onclick={() => (discardConfirm = true)} title="Clear this workspace">
+ <Icon name="reset" size={14} /> Discard
+ </button>
+ {/if}
<button class="btn btn-sm" disabled={!session.source} onclick={openSaveDialog} title="Save this workspace">
<Icon name="save" size={14} /> Save session
</button>
@@ -634,6 +873,15 @@
<Icon name={TAB_META[t].icon} size={15} /> {TAB_META[t].label}
</button>
{/each}
+ {#if activeTab === 'collage'}
+ <div class="tab-spacer"></div>
+ <button class="btn btn-ghost btn-sm" title="Undo (Ctrl+Z)" disabled={!collageCanUndo} onclick={undoCollage}>
+ <Icon name="undo" size={15} />
+ </button>
+ <button class="btn btn-ghost btn-sm" title="Redo (Ctrl+Shift+Z / Ctrl+Y)" disabled={!collageCanRedo} onclick={redoCollage}>
+ <Icon name="redo" size={15} />
+ </button>
+ {/if}
</div>
<div class="workspace">
@@ -643,7 +891,7 @@
<!-- svelte-ignore a11y_media_has_caption -->
<video
bind:this={videoEl}
- src={`/files/${caseState.current.id}/${session.source.path}`}
+ src={`/files/${caseState.current?.id}/${session.source.path}`}
controls
ontimeupdate={() => (shared.currentTime = videoEl?.currentTime ?? 0)}
style:filter={videoPreview.filter}
@@ -654,38 +902,79 @@
{#if activeFrame}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
- class="frame"
+ class="frame-viewport"
class:cropping={shared.cropMode}
- onpointerdown={cropDown}
- onpointermove={cropMove}
- onpointerup={cropUp}
+ class:pannable={!shared.cropMode && !cropEditing}
+ class:rotating
+ bind:this={frameViewportEl}
+ onwheel={frameWheel}
+ onmousedown={frameMouseDown}
+ onpointerdown={frameViewportDown}
+ onauxclick={(e) => e.preventDefault()}
+ ondblclick={beginCrop}
>
- {#if activeFrame.crop && !shared.cropMode}
- <!-- committed crop: show the cropped region filling the box -->
+ <div
+ class="zoom-layer"
+ bind:this={frameZoomEl}
+ style:transform={`translate(${framePan.x}px, ${framePan.y}px) scale(${frameZoom})`}
+ >
+ <!-- View-only rotation pivots around the grabbed point; never saved. -->
<div
- class="crop-view"
- style:--ar={cropAspect(activeFrame.crop, activeFrame.w, activeFrame.h) ?? 1}
+ class="img-stage"
+ bind:this={frameStageEl}
+ style:transform={matrixCss(frameRotMatrix)}
+ style:transform-origin="0 0"
>
- <img
- src={activeFrame.url}
- alt="frame"
- style={styleText(cropImgStyle(activeFrame.crop))}
- style:filter={framePreview.filter}
- style:transform={framePreview.transform}
- />
+ {#if activeFrame.crop && !cropEditing}
+ <!-- committed crop: show the cropped region -->
+ <div class="crop-view" style:--ar={cropAspect(activeFrame.crop, activeFrame.w, activeFrame.h) ?? 1}>
+ <img
+ src={activeFrame.url}
+ alt="frame"
+ draggable="false"
+ style={styleText(cropImgStyle(activeFrame.crop))}
+ style:filter={framePreview.filter}
+ style:transform={framePreview.transform}
+ />
+ </div>
+ {:else}
+ <img src={activeFrame.url} alt="frame" draggable="false" style:filter={framePreview.filter} style:transform={framePreview.transform} />
+ <CropBox
+ bind:crop={activeFrame.crop}
+ bind:draw={shared.cropMode}
+ aspect={frameAspect}
+ natW={activeFrame.w}
+ natH={activeFrame.h}
+ />
+ {/if}
+ </div>
+ </div>
+ {#if rotating}
+ <!-- "target" pivot marker: sits at the grabbed point, fixed on
+ screen while the image turns around it -->
+ <div class="rotate-pivot" style:left={`${rotatePivot.x}px`} style:top={`${rotatePivot.y}px`} aria-hidden="true">
+ <svg width="40" height="40" viewBox="0 0 40 40">
+ <circle class="ring" cx="20" cy="20" r="15" />
+ <circle class="dot" cx="20" cy="20" r="1.5" />
+ </svg>
</div>
- {:else}
- <img src={activeFrame.url} alt="frame" style:filter={framePreview.filter} style:transform={framePreview.transform} />
- {#if cropBox}
- <div
- class="crop-box"
- style:left={`${cropBox.x * 100}%`}
- style:top={`${cropBox.y * 100}%`}
- style:width={`${cropBox.w * 100}%`}
- style:height={`${cropBox.h * 100}%`}
- ></div>
- {/if}
{/if}
+ <div class="view-ctl">
+ {#if cropEditing}
+ <span class="zoom-hint">drag to crop · Enter applies · Esc cancels</span>
+ <button class="btn btn-sm" onclick={commitCrop} title="Apply the crop (Enter)">
+ <Icon name="check" size={14} /> Apply
+ </button>
+ {:else if frameViewDirty}
+ {#if frameZoom !== 1}<span class="zoom-val">{Math.round(frameZoom * 100)}%</span>{/if}
+ {#if frameAngle !== 0}<span class="zoom-val">{frameAngle}°</span>{/if}
+ <button class="btn btn-ghost btn-sm" onclick={resetFrameView} title="Reset zoom / pan / rotation">
+ <Icon name="eye" size={14} /> Fit
+ </button>
+ {:else}
+ <span class="zoom-hint">scroll zoom · drag pan · middle-drag turns · double-click crop</span>
+ {/if}
+ </div>
</div>
{:else}
<div class="hint-mid">
@@ -694,7 +983,7 @@
</div>
{/if}
{:else if activeTab === 'collage'}
- <CollageCanvas collage={activeCollage} bind:selectedId={collageSelectedId} />
+ <CollageCanvas collage={activeCollage} bind:selectedId={collageSelectedId} {requestCrop} />
{:else if activeTab === 'save'}
<SaveGallery {savables} {saveUi} />
{/if}
@@ -704,7 +993,7 @@
{#if activeTab === 'selection'}
<SelectionMenu {probeInfo} {shared} {videoFilters} {session} {capture} />
{:else if activeTab === 'frame'}
- <FrameMenu {session} {filters} {analyses} {activeFrame} {shared} {removeFrame} setActive={(id) => (session.activeFrameId = id)} />
+ <FrameMenu {session} {filters} {analyses} {activeFrame} {shared} {removeFrame} bind:cropAspect={frameAspect} bind:cropEditing {beginCrop} {commitCrop} setActive={(id) => (session.activeFrameId = id)} />
{:else if activeTab === 'collage'}
<CollageMenu {session} {filters} bind:selectedId={collageSelectedId} {addToCollage} {requestCrop} />
{:else if activeTab === 'save'}
@@ -722,6 +1011,19 @@
/>
{/if}
+ {#if discardConfirm}
+ <ConfirmDialog
+ title="Discard this session?"
+ message="The current workspace — captured frames, adjustments and collage layout — will be cleared."
+ detail={openedSession ? 'This does not delete the saved session, only the unsaved changes in this workspace.' : 'Anything not saved yet will be lost.'}
+ confirmLabel="Discard"
+ tone="danger"
+ icon="reset"
+ onconfirm={discardSession}
+ oncancel={() => (discardConfirm = false)}
+ />
+ {/if}
+
{#if sessionModal.open}
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
@@ -821,11 +1123,15 @@
}
.tabbar {
display: flex;
+ align-items: center;
gap: 4px;
padding: 8px 12px;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
+ .tab-spacer {
+ flex: 1;
+ }
.tab {
display: flex;
align-items: center;
@@ -868,32 +1174,104 @@
touch-action: none;
box-shadow: var(--shadow-2);
}
- .frame.cropping {
- cursor: crosshair;
- }
- .frame img,
.frame video {
max-width: 100%;
max-height: calc(100vh - var(--topbar-h) - 160px);
display: block;
}
- .crop-box {
+ /* Frame tab: a zoom/pan/rotate surface with the crop overlay on top. */
+ .frame-viewport {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+ touch-action: none;
+ }
+ .frame-viewport.pannable {
+ cursor: grab;
+ }
+ .frame-viewport.cropping {
+ cursor: crosshair;
+ }
+ .frame-viewport.rotating {
+ cursor: grabbing;
+ }
+ /* Sober pivot mark (Google-Earth style): a faint translucent ring + dot. */
+ .rotate-pivot {
position: absolute;
- border: 1.5px solid var(--accent);
- box-shadow: 0 0 0 9999px rgba(6, 9, 14, 0.55);
+ transform: translate(-50%, -50%);
pointer-events: none;
+ z-index: 5;
+ color: #fff;
+ }
+ .rotate-pivot svg {
+ display: block;
+ overflow: visible;
+ filter: drop-shadow(0 0 1.5px rgba(0, 0, 0, 0.55));
+ }
+ .rotate-pivot .ring {
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1;
+ opacity: 0.5;
+ }
+ .rotate-pivot .dot {
+ fill: currentColor;
+ opacity: 0.8;
+ }
+ .zoom-layer {
+ position: relative;
+ transform-origin: center center;
+ display: inline-block;
+ line-height: 0;
+ }
+ .img-stage {
+ position: relative;
+ display: inline-block;
+ line-height: 0;
+ }
+ .img-stage > img {
+ max-width: 100%;
+ max-height: calc(100vh - var(--topbar-h) - 200px);
+ display: block;
}
.crop-view {
position: relative;
overflow: hidden;
aspect-ratio: var(--ar);
- height: calc(100vh - var(--topbar-h) - 200px);
+ height: calc(100vh - var(--topbar-h) - 220px);
max-width: 100%;
line-height: 0;
}
.crop-view img {
display: block;
}
+ .view-ctl {
+ position: absolute;
+ right: 10px;
+ bottom: 10px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 3px 6px;
+ border-radius: var(--r-md);
+ background: rgba(16, 20, 28, 0.85);
+ border: 1px solid var(--border);
+ }
+ .zoom-val {
+ font-size: var(--fs-xs);
+ font-weight: 700;
+ color: var(--text-2);
+ font-variant-numeric: tabular-nums;
+ }
+ .zoom-hint {
+ font-size: 11px;
+ color: var(--text-3);
+ user-select: none;
+ }
.panel {
width: 320px;
flex-shrink: 0;
diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelte
index 6451f65..bfb643c 100644
--- a/frontend/src/tools/MediaLibrary.svelte
+++ b/frontend/src/tools/MediaLibrary.svelte
@@ -1,16 +1,19 @@
<script>
import { api } from '../lib/api.js';
import { caseState, uiState, ensureCase, reloadCase, toast } from '../lib/state.svelte.js';
+ import { visibleMedia, SORTS } from '../lib/mediaFilter.js';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
+ import ConfirmDialog from '../components/ConfirmDialog.svelte';
const KIND_ICONS = { image: 'image', video: 'video', audio: 'audio', file: 'file' };
let items = $state([]);
let loadedFor = $state(null);
let url = $state('');
+ let picker = $state(null); // multi-item picker: {url, items: [{index, title, thumbnail, kind, selected}]}
let dragOver = $state(false);
- let jobs = $state([]); // active download jobs: {id, url, progress}
+ let jobs = $state([]); // active download jobs: {id, url, label, progress}
let fileInput;
// --- category facets (auto-derived from kind + source) ---
@@ -20,6 +23,7 @@
{ key: 'image', label: 'Images', icon: 'image', match: (i) => i.kind === 'image' },
{ key: 'video', label: 'Videos', icon: 'video', match: (i) => i.kind === 'video' },
{ key: 'collage', label: 'Collages', icon: 'layers', match: (i) => i.source?.op === 'collage' },
+ { key: 'satellite', label: 'Satellite', icon: 'satellite', match: (i) => i.source?.type === 'satellite' },
{ key: 'upload', label: 'Imports', icon: 'upload', match: (i) => i.source?.type === 'upload' },
{ key: 'download', label: 'Downloads', icon: 'download', match: (i) => i.source?.type === 'download' },
{ key: 'other', label: 'Other files', icon: 'file', match: (i) => i.kind !== 'image' && i.kind !== 'video' },
@@ -37,13 +41,24 @@
// --- folder filter (user-defined folders) ---
let folderFilter = $state(null); // null = All
+ // --- free-text search + sort ---
+ let query = $state('');
+ let sort = $state('newest');
+
const folders = $derived(
[...new Set(items.filter((i) => i.folder).map((i) => i.folder))].sort()
);
+ // Empty when no case is open — the grid cards build file URLs from
+ // `caseState.current.id`, so a stale render during case-close (current is
+ // briefly null before `items` clears) must not reach them. See visibleMedia.
const filteredItems = $derived(
- items.filter(
- (i) => (!catMatch || catMatch(i)) && (!folderFilter || i.folder === folderFilter)
- )
+ visibleMedia(items, {
+ hasCase: !!caseState.current,
+ catMatch,
+ folderFilter,
+ query,
+ sort,
+ })
);
// --- info/edit modal ---
@@ -52,8 +67,23 @@
let editTitle = $state('');
let editSaving = $state(false);
- // --- lightbox ---
+ // --- lightbox (←/→ flips through the filtered images) ---
let lightboxItem = $state(null);
+ const lightboxImages = $derived(filteredItems.filter((i) => i.kind === 'image'));
+
+ function lightboxStep(delta) {
+ if (!lightboxItem || !lightboxImages.length) return;
+ const idx = lightboxImages.findIndex((i) => i.path === lightboxItem.path);
+ const next = ((idx < 0 ? 0 : idx) + delta + lightboxImages.length) % lightboxImages.length;
+ lightboxItem = lightboxImages[next];
+ }
+
+ function onLightboxKey(e) {
+ if (!lightboxItem || uiState.tool !== 'media') return;
+ if (e.key === 'Escape') lightboxItem = null;
+ else if (e.key === 'ArrowLeft') lightboxStep(-1);
+ else if (e.key === 'ArrowRight') lightboxStep(1);
+ }
// --- focus/highlight (a media clicked from the case sidebar) ---
let focusedPath = $state(null);
@@ -128,16 +158,36 @@
const target = url.trim();
if (!target) return;
url = '';
- const c = await ensureCase();
+ startDownload(target);
+ }
+
+ async function startDownload(target, index = null, title = null) {
try {
- const { job_id } = await api.post(`/api/cases/${c.id}/media/download`, { url: target });
- jobs.push({ id: job_id, url: target, progress: {} });
+ const c = await ensureCase();
+ const { job_id } = await api.post(`/api/cases/${c.id}/media/download`, {
+ url: target,
+ index,
+ title,
+ });
+ jobs.push({ id: job_id, url: target, label: title || target, progress: {} });
poll(job_id);
} catch (e) {
toast(e.message, 'danger');
}
}
+ function selectAllPicker(value) {
+ picker.items.forEach((i) => (i.selected = value));
+ }
+
+ function confirmPicker() {
+ const chosen = picker.items.filter((i) => i.selected);
+ for (const item of chosen) {
+ startDownload(picker.url, item.index, item.title.trim() || undefined);
+ }
+ picker = null;
+ }
+
async function poll(jobId) {
const job = jobs.find((j) => j.id === jobId);
if (!job) return;
@@ -149,7 +199,10 @@
return;
}
jobs = jobs.filter((j) => j.id !== jobId);
- if (status.status === 'done') {
+ if (status.status === 'done' && status.result?.multi) {
+ // several attachments — nothing was downloaded yet, let the analyst pick
+ picker = { url: job.url, items: status.result.items.map((i) => ({ ...i, selected: true })) };
+ } else if (status.status === 'done') {
toast(
status.result?.duplicate
? 'Already in the case (same SHA-256)'
@@ -166,12 +219,25 @@
}
}
- async function remove(item) {
- await api.del(
- `/api/cases/${caseState.current.id}/media?path=${encodeURIComponent(item.path)}`
- );
- await Promise.all([refresh(), reloadCase()]);
- toast(`Removed ${item.filename}`, 'info');
+ // Deleting media drops the file (evidence!) — always behind a confirm.
+ let deleteTarget = $state(null);
+ let deleteBusy = $state(false);
+
+ async function confirmDelete() {
+ if (!deleteTarget || deleteBusy) return;
+ deleteBusy = true;
+ try {
+ await api.del(
+ `/api/cases/${caseState.current.id}/media?path=${encodeURIComponent(deleteTarget.path)}`
+ );
+ await Promise.all([refresh(), reloadCase()]);
+ toast(`Removed ${deleteTarget.filename}`, 'info');
+ deleteTarget = null;
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ deleteBusy = false;
+ }
}
function sendToComposer(item) {
@@ -282,9 +348,28 @@
/>
</div>
- <!-- category + folder filter bar -->
+ <!-- search + sort + category + folder filter bar -->
{#if items.length > 0}
<div class="folder-bar">
+ <div class="search-box">
+ <Icon name="search" size={13} />
+ <input
+ class="search-input"
+ placeholder="Search name, notes, source…"
+ bind:value={query}
+ />
+ {#if query}
+ <button class="search-clear" onclick={() => (query = '')} aria-label="Clear search">
+ <Icon name="x" size={12} />
+ </button>
+ {/if}
+ </div>
+ <select class="select sort-select" bind:value={sort} title="Sort order">
+ {#each SORTS as s (s.id)}
+ <option value={s.id}>{s.label}</option>
+ {/each}
+ </select>
+ <span class="bar-sep"></span>
<!-- type / source facets -->
<button
class="folder-chip"
@@ -326,7 +411,7 @@
{#each jobs as job (job.id)}
<div class="job card fade-up">
<Icon name="download" size={15} />
- <span class="job-url mono">{job.url}</span>
+ <span class="job-url mono" title={job.url}>{job.label ?? job.url}</span>
<div class="bar">
<div
class="fill"
@@ -438,7 +523,7 @@
<Icon name="proof" size={14} />
</button>
{/if}
- <button class="btn btn-ghost btn-sm del" title="Delete" onclick={() => remove(item)}>
+ <button class="btn btn-ghost btn-sm del" title="Delete" onclick={() => (deleteTarget = item)}>
<Icon name="trash" size={14} />
</button>
</div>
@@ -458,9 +543,48 @@
{/if}
</div>
+<!-- multi-item picker: shown when a URL has several attachments (e.g. a tweet
+ with several photos) — pick which ones to download, before anything is fetched -->
+{#if picker}
+ <Modal title="Choose media to download" onclose={() => (picker = null)} width="560px">
+ <p class="picker-hint">This link has {picker.items.length} attachments — pick which to fetch.</p>
+ <div class="picker-toolbar">
+ <button class="btn btn-ghost btn-sm" onclick={() => selectAllPicker(true)}>Select all</button>
+ <button class="btn btn-ghost btn-sm" onclick={() => selectAllPicker(false)}>Select none</button>
+ </div>
+ <div class="picker-list">
+ {#each picker.items as item (item.index)}
+ <label class="picker-row" class:selected={item.selected}>
+ <input type="checkbox" bind:checked={item.selected} />
+ <div class="picker-thumb">
+ {#if item.thumbnail}
+ <img src={item.thumbnail} alt="" loading="lazy" />
+ {:else}
+ <Icon name={KIND_ICONS[item.kind] ?? 'file'} size={20} />
+ {/if}
+ </div>
+ <input class="input picker-title" placeholder="Title" bind:value={item.title} />
+ </label>
+ {/each}
+ </div>
+ <div class="modal-actions">
+ <div style="flex:1"></div>
+ <button class="btn" onclick={() => (picker = null)}>Cancel</button>
+ <button
+ class="btn btn-primary"
+ disabled={!picker.items.some((i) => i.selected)}
+ onclick={confirmPicker}
+ >
+ <Icon name="download" size={14} />
+ Download {picker.items.filter((i) => i.selected).length} selected
+ </button>
+ </div>
+ </Modal>
+{/if}
+
<!-- info / edit modal -->
{#if editItem}
- <Modal title={editItem.filename} onclose={() => (editItem = null)} width="520px">
+ <Modal title={editTitle.trim() || editItem.filename} onclose={() => (editItem = null)} width="520px">
<!-- preview -->
{#if editItem.kind === 'image' && editItem.thumbnail}
<div class="modal-preview">
@@ -579,11 +703,11 @@
{/if}
<!-- lightbox -->
+<svelte:window onkeydown={onLightboxKey} />
{#if lightboxItem}
<div
class="lightbox"
onclick={() => (lightboxItem = null)}
- onkeydown={(e) => e.key === 'Escape' && (lightboxItem = null)}
role="dialog"
aria-label="Image preview"
tabindex="-1"
@@ -591,15 +715,52 @@
<button class="lb-close btn btn-ghost" onclick={() => (lightboxItem = null)} aria-label="Close">
<Icon name="x" size={20} />
</button>
+ {#if lightboxImages.length > 1}
+ <button
+ class="lb-nav prev btn btn-ghost"
+ onclick={(e) => (e.stopPropagation(), lightboxStep(-1))}
+ aria-label="Previous image"
+ title="Previous (←)"
+ >
+ <Icon name="chevronLeft" size={26} />
+ </button>
+ <button
+ class="lb-nav next btn btn-ghost"
+ onclick={(e) => (e.stopPropagation(), lightboxStep(1))}
+ aria-label="Next image"
+ title="Next (→)"
+ >
+ <Icon name="chevronRight" size={26} />
+ </button>
+ {/if}
<img
src={`/files/${caseState.current.id}/${lightboxItem.path}`}
alt={lightboxItem.filename}
onclick={(e) => e.stopPropagation()}
/>
- <span class="lb-caption">{lightboxItem.filename}</span>
+ <span class="lb-caption">
+ {lightboxItem.title ?? lightboxItem.filename}
+ {#if lightboxImages.length > 1}
+ · {lightboxImages.findIndex((i) => i.path === lightboxItem.path) + 1}/{lightboxImages.length}
+ {/if}
+ </span>
</div>
{/if}
+<!-- delete confirm: the file on disk goes with the entity -->
+{#if deleteTarget}
+ <ConfirmDialog
+ title="Delete this media?"
+ message={`“${deleteTarget.title ?? deleteTarget.filename}” and its entity will be removed from the case.`}
+ detail="This permanently deletes the file on disk — it cannot be undone."
+ confirmLabel="Delete"
+ tone="danger"
+ busy={deleteBusy}
+ onconfirm={confirmDelete}
+ oncancel={() => (deleteTarget = null)}
+ />
+{/if}
+
<style>
.tool {
position: relative;
@@ -658,6 +819,44 @@
background: var(--border);
flex-shrink: 0;
}
+ .search-box {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 8px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ background: var(--bg-2);
+ color: var(--text-3);
+ flex-shrink: 0;
+ }
+ .search-box:focus-within {
+ border-color: var(--accent);
+ }
+ .search-input {
+ width: 180px;
+ border: none;
+ background: none;
+ outline: none;
+ color: var(--text-1);
+ font-size: var(--fs-xs);
+ }
+ .search-clear {
+ display: inline-flex;
+ color: var(--text-3);
+ padding: 1px;
+ border-radius: 50%;
+ }
+ .search-clear:hover {
+ color: var(--text-1);
+ background: var(--bg-3);
+ }
+ .sort-select {
+ width: auto;
+ font-size: var(--fs-xs);
+ padding: 4px 8px;
+ flex-shrink: 0;
+ }
.job {
display: flex;
@@ -902,6 +1101,59 @@
margin-top: 14px;
}
+ /* multi-item picker */
+ .picker-hint {
+ font-size: var(--fs-sm);
+ color: var(--text-2);
+ margin: 0 0 10px;
+ }
+ .picker-toolbar {
+ display: flex;
+ gap: 6px;
+ margin-bottom: 8px;
+ }
+ .picker-list {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ max-height: 46vh;
+ overflow-y: auto;
+ }
+ .picker-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 6px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r);
+ cursor: pointer;
+ }
+ .picker-row.selected {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ }
+ .picker-thumb {
+ width: 44px;
+ height: 44px;
+ flex-shrink: 0;
+ border-radius: var(--r-sm, 6px);
+ overflow: hidden;
+ background: var(--bg-2);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--text-3);
+ }
+ .picker-thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .picker-title {
+ flex: 1;
+ min-width: 0;
+ }
+
/* lightbox */
.lightbox {
position: fixed;
@@ -927,6 +1179,24 @@
top: 14px;
right: 14px;
}
+ .lb-nav {
+ position: absolute;
+ top: 50%;
+ transform: translateY(-50%);
+ padding: 14px 8px;
+ color: var(--text-1);
+ background: rgba(11, 15, 23, 0.55);
+ border-radius: var(--r-md);
+ }
+ .lb-nav:hover {
+ background: rgba(11, 15, 23, 0.85);
+ }
+ .lb-nav.prev {
+ left: 14px;
+ }
+ .lb-nav.next {
+ right: 14px;
+ }
.lb-caption {
position: absolute;
bottom: 18px;
diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelte
index 6ee8487..5ee98a8 100644
--- a/frontend/src/tools/PostComposer.svelte
+++ b/frontend/src/tools/PostComposer.svelte
@@ -2,8 +2,10 @@
import { api } from '../lib/api.js';
import { caseState, uiState, toast, reloadCase } from '../lib/state.svelte.js';
import { proofCoordsText, proofSource } from '../lib/composer.js';
+ import { bidiSafe } from '../lib/bidi.js';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
+ import ConfirmDialog from '../components/ConfirmDialog.svelte';
const X_LIMIT = 280;
const URL_WEIGHT = 23; // X counts every URL as 23 chars
@@ -33,6 +35,8 @@
// Draft persistence
let draftName = $state(null); // slug of the saved draft (null until first save)
let saving = $state(false);
+ let discardConfirm = $state(false);
+ let openList = $state(null); // list of saved drafts, null = closed
// Media picker modal
let pickerOpen = $state(false);
@@ -42,6 +46,17 @@
let proofPickerOpen = $state(false);
let proofLibrary = $state([]);
+ let postFor = $state(undefined); // id of the case the form's content belongs to
+
+ // reset the draft form when the case changes (close/switch/one-shot)
+ $effect(() => {
+ const id = caseState.current?.id;
+ if (id !== postFor) {
+ postFor = id;
+ resetDraft();
+ }
+ });
+
// Ingest a proof handed over by the Proof Composer
$effect(() => {
const p = uiState.postProof;
@@ -140,9 +155,12 @@
}
function weightedLength(t) {
+ // count the bidi-safe text that actually gets copied, so the counter
+ // stays honest for Arabic/Hebrew threads (isolates counted, worst case)
+ const safe = bidiSafe(t);
const urlRe = /https?:\/\/\S+/g;
- const stripped = t.replace(urlRe, '');
- const urls = t.match(urlRe)?.length ?? 0;
+ const stripped = safe.replace(urlRe, '');
+ const urls = safe.match(urlRe)?.length ?? 0;
return [...stripped].length + urls * URL_WEIGHT;
}
@@ -163,8 +181,10 @@
if (i !== -1) extraTweets.splice(i, 1);
}
+ // Copies go through bidiSafe: Arabic/Hebrew threads keep coordinates,
+ // plus codes, @mentions and URLs reading left-to-right on X (see lib/bidi).
async function copy(value) {
- await navigator.clipboard.writeText(value);
+ await navigator.clipboard.writeText(bidiSafe(value));
toast('Copied to clipboard', 'ok', 1600);
}
@@ -174,7 +194,7 @@
for (const t of extraTweets) {
if (t.text.trim()) parts.push(t.text.trim());
}
- await navigator.clipboard.writeText(parts.join('\n\n---\n\n'));
+ await navigator.clipboard.writeText(parts.map(bidiSafe).join('\n\n---\n\n'));
toast('All tweets copied', 'ok', 1800);
}
@@ -353,6 +373,15 @@
}
}
+ async function openDraftList() {
+ if (!caseState.current) return;
+ try {
+ openList = await api.get(`/api/cases/${caseState.current.id}/drafts`);
+ } catch (e) {
+ toast(e.message, 'danger');
+ }
+ }
+
async function loadDraft(name) {
if (!caseState.current) return;
try {
@@ -382,19 +411,44 @@
}
tweet1 = s.tweet1 ?? buildTweet1();
tweet1Edited = s.tweet1Edited ?? false;
+ openList = null;
toast('Draft loaded', 'ok', 1400);
} catch (e) {
toast(`Could not load draft: ${e.message}`, 'danger');
}
}
+ function resetDraft() {
+ description = '';
+ coordsText = '';
+ geo = null;
+ place = '';
+ mention = '@GeoConfirmed';
+ source = '';
+ setProof(null);
+ tweet1 = '';
+ tweet1Edited = false;
+ mediaEnabled = true;
+ mediaType = 'none';
+ mediaText = '';
+ mediaPath = null;
+ extraTweets = [];
+ draftName = null;
+ discardConfirm = false;
+ }
+
+ const hasContent = $derived(
+ !!(draftName || description.trim() || coordsText.trim() || mediaPath || proofPng ||
+ extraTweets.length || tweet1.trim())
+ );
+
// ---- publish (prefill X compose — Azimut never posts on your behalf) -----
async function publish() {
// X's web intent only prefills the first post; copy the whole thread so the
// rest can be pasted as replies, then open the compose window.
await copyAll();
- const url = `https://x.com/intent/post?text=${encodeURIComponent(tweet1)}`;
+ const url = `https://x.com/intent/post?text=${encodeURIComponent(bidiSafe(tweet1))}`;
window.open(url, '_blank', 'noopener,noreferrer');
toast('Opened X — thread copied for the replies', 'info', 3200);
}
@@ -407,6 +461,16 @@
<span class="sub">publishable post from your proof — you copy, you publish, Azimut never posts</span>
</div>
<div class="head-actions">
+ {#if caseState.current}
+ <button class="btn btn-ghost btn-sm" onclick={openDraftList} title="Reopen a saved draft">
+ <Icon name="folderOpen" size={14} /> Open
+ </button>
+ {/if}
+ {#if hasContent}
+ <button class="btn btn-ghost btn-sm" onclick={() => (discardConfirm = true)} title="Clear this draft">
+ <Icon name="reset" size={14} /> Discard
+ </button>
+ {/if}
<button class="btn btn-ghost btn-sm" onclick={saveDraft} disabled={saving}>
<Icon name="save" size={14} /> {draftName ? 'Save draft' : 'Save as draft'}
</button>
@@ -544,6 +608,7 @@
</div>
<textarea
class="textarea post-text mono"
+ dir="auto"
bind:value={tweet1}
oninput={() => (tweet1Edited = true)}
rows="11"
@@ -584,6 +649,7 @@
<div class="media-prefix">{mediaType === 'video' ? '2/ Video:' : '2/ Image(s):'}</div>
<textarea
class="textarea post-text mono"
+ dir="auto"
placeholder="Paste URL or describe the media…"
bind:value={mediaText}
rows="3"
@@ -640,6 +706,7 @@
</div>
<textarea
class="textarea post-text mono"
+ dir="auto"
placeholder="Additional context…"
bind:value={tweet.text}
rows="4"
@@ -666,13 +733,45 @@
</div>
</div>
+{#if openList}
+ <Modal title="Open a saved draft" onclose={() => (openList = null)} width="560px">
+ {#if !openList.length}
+ <div class="empty"><p>No saved drafts in this case yet.</p></div>
+ {:else}
+ <div class="open-list">
+ {#each openList as entry (entry.name)}
+ <button class="open-row" onclick={() => loadDraft(entry.name)}>
+ <div class="open-meta">
+ <span class="open-title">{entry.title}</span>
+ <span class="open-sub">{entry.updated_at?.slice(0, 10)}</span>
+ </div>
+ </button>
+ {/each}
+ </div>
+ {/if}
+ </Modal>
+{/if}
+
+{#if discardConfirm}
+ <ConfirmDialog
+ title="Discard this draft?"
+ message="The current post — description, coordinates, media and extra tweets — will be cleared."
+ detail={draftName ? 'This does not delete the saved draft, only the unsaved changes here.' : 'Anything not saved yet will be lost.'}
+ confirmLabel="Discard"
+ tone="danger"
+ icon="reset"
+ onconfirm={resetDraft}
+ oncancel={() => (discardConfirm = false)}
+ />
+{/if}
+
{#if pickerOpen}
<Modal title="Choose a media" width="640px" onclose={() => (pickerOpen = false)}>
{#if mediaLibrary.length === 0}
<p class="picker-empty">No media in this case yet — import or download some in the Media tab.</p>
{:else}
<div class="picker-grid">
- {#each mediaLibrary as item (item.path)}
+ {#each (caseState.current ? mediaLibrary : []) as item (item.path)}
<button class="picker-item" onclick={() => pickMedia(item)} title={item.path}>
<div class="picker-thumb">
{#if item.thumbnail}
@@ -696,7 +795,7 @@
<p class="picker-empty">No proofs in this case yet — build one in the Proof tab.</p>
{:else}
<div class="picker-grid">
- {#each proofLibrary as item (item.name)}
+ {#each (caseState.current ? proofLibrary : []) as item (item.name)}
<button class="picker-item" onclick={() => pickProof(item)} title={item.title} disabled={!item.png}>
<div class="picker-thumb">
{#if item.png}
@@ -941,4 +1040,20 @@
text-overflow: ellipsis;
white-space: nowrap;
}
+ .open-list { display: flex; flex-direction: column; gap: 8px; }
+ .open-row {
+ display: flex;
+ gap: 12px;
+ align-items: center;
+ padding: 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-2);
+ cursor: pointer;
+ text-align: left;
+ }
+ .open-row:hover { border-color: var(--accent); }
+ .open-meta { display: flex; flex-direction: column; gap: 2px; }
+ .open-title { font-weight: 600; font-size: var(--fs-sm); }
+ .open-sub { font-size: var(--fs-xs); color: var(--text-3); }
</style>
diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelte
index 5c8b96d..df77c41 100644
--- a/frontend/src/tools/ProofComposer.svelte
+++ b/frontend/src/tools/ProofComposer.svelte
@@ -5,6 +5,7 @@
import { caseState, uiState, ensureCase, reloadCase, toast } from '../lib/state.svelte.js';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
+ import ConfirmDialog from '../components/ConfirmDialog.svelte';
import {
ANNO_COLORS, PAD, TWEET_GUIDES,
CAPTION_SIZE, LEGEND_SIZE, FOOTER_SIZE,
@@ -12,9 +13,10 @@
layoutPanels, panelsBlockHeight, legendLineHeight, footerBand,
attributionLine, docSize, offsetShape, autoLayoutRows,
autoCoords, formatCoords, autoSource, resolveSourceUrls,
- toSpec, newId, loadImage, featureColors, notesFromShapes,
- copyShapeSpec,
+ toSpec, newId, loadImage, orderedFeatureColors, notesFromShapes,
+ copyShapeSpec, dedupeBySrc, isSatelliteCapture,
} from '../lib/composer.js';
+ import { createHistory } from '../lib/history.js';
const SCALE_MIN = 0.4;
const SCALE_MAX = 2.5;
@@ -34,7 +36,7 @@
// `notes` holds the legend text per color (annotations are written by color,
// not per element); `shapes` are the drawn geometry bound to a panel.
const proof = $state({
- title: 'Untitled proof', panels: [], shapes: [], notes: {},
+ title: 'Untitled proof', panels: [], shapes: [], notes: {}, legendOrder: [],
coordsText: '', source: '', // '' → auto-derived from panels; non-empty → manual override
captionSize: CAPTION_SIZE, legendSize: LEGEND_SIZE, footerSize: FOOTER_SIZE, footer: '',
});
@@ -52,12 +54,92 @@
let openList = $state(null); // list of saved proofs, null = closed
let saving = $state(false);
let proofFor = $state(undefined);
+ let discardConfirm = $state(false);
+
+ // ---- undo / redo -------------------------------------------------------------
+ // Snapshot-based history over the serializable document (toSpec). Mutations
+ // are captured by a debounced effect, so a slider drag collapses into one
+ // entry; panel images are re-attached from a cache on restore.
+ const history = createHistory();
+ const imgCache = new Map(); // src → HTMLImageElement, survives undo/redo
+ let canUndo = $state(false);
+ let canRedo = $state(false);
+ let histBusy = false; // plain (untracked): suppresses capture while restoring
+ let histTimer = null;
+
+ const docSnapshot = () => JSON.stringify(toSpec(proof));
+
+ function syncHist() {
+ canUndo = history.canUndo;
+ canRedo = history.canRedo;
+ }
+
+ function anchorHistory() {
+ clearTimeout(histTimer);
+ history.reset(docSnapshot());
+ syncHist();
+ }
+
+ $effect(() => {
+ const json = docSnapshot(); // reads every document field → tracked
+ if (histBusy) return;
+ clearTimeout(histTimer);
+ histTimer = setTimeout(() => {
+ history.push(json);
+ syncHist();
+ }, 350);
+ });
+
+ function applySnapshot(json) {
+ const spec = JSON.parse(json);
+ histBusy = true;
+ if (pathDraft) finishPath(false);
+ proof.title = spec.title ?? 'Untitled proof';
+ proof.coordsText = spec.coordsText ?? '';
+ proof.source = spec.source ?? '';
+ proof.captionSize = spec.captionSize ?? CAPTION_SIZE;
+ proof.legendSize = spec.legendSize ?? LEGEND_SIZE;
+ proof.footerSize = spec.footerSize ?? FOOTER_SIZE;
+ proof.footer = spec.footer ?? '';
+ proof.notes = spec.notes ?? {};
+ proof.panels = spec.panels.map((p) => ({ ...p, img: imgCache.get(p.src) ?? null }));
+ proof.shapes = spec.shapes ?? [];
+ // a panel image missing from the cache (shouldn't happen) reloads async
+ for (const p of proof.panels.filter((x) => !x.img)) {
+ loadImage(`/files/${caseState.current?.id}/${p.src}`)
+ .then((img) => {
+ imgCache.set(p.src, img);
+ p.img = img;
+ })
+ .catch(() => {});
+ }
+ selectedId = null;
+ dirty = true;
+ requestAnimationFrame(fit);
+ // outlast the capture debounce so the restore itself is not re-recorded
+ setTimeout(() => (histBusy = false), 400);
+ }
+
+ function undo() {
+ const json = history.undo();
+ if (json != null) applySnapshot(json);
+ syncHist();
+ }
+
+ function redo() {
+ const json = history.redo();
+ if (json != null) applySnapshot(json);
+ syncHist();
+ }
// ---- konva ------------------------------------------------------------------
let containerEl;
let stage, docLayer, uiLayer, transformer, endHandles, guideGroup;
let drawing = null; // {panel, node, start, box, kind}
let pathDraft = null; // {panel, box, node, points:[]} — multi-click curve in progress
+ let spacePan = false; // hold-space panning (manual, so it wins over shape drags)
+ let panDrag = null; // {sx, sy, ox, oy} — space/middle-drag pan in progress
+ let textEdit = $state(null); // {id, value, left, top, size} — inline text editor
onMount(() => {
stage = new Konva.Stage({ container: containerEl, width: 100, height: 100 });
@@ -138,6 +220,7 @@
proof.panels.map((p) => [p.src, p.caption, p.row, p.scale]),
proof.shapes,
proof.notes,
+ proof.legendOrder,
proof.captionSize, proof.legendSize, proof.footerSize, proof.footer,
selectedId,
guide,
@@ -157,6 +240,7 @@
proof.panels = [];
proof.shapes = [];
proof.notes = {};
+ proof.legendOrder = [];
proof.coordsText = '';
proof.source = '';
proof.captionSize = CAPTION_SIZE;
@@ -166,6 +250,13 @@
savedName = null;
selectedId = null;
dirty = false;
+ imgCache.clear();
+ anchorHistory();
+ }
+
+ function discardProof() {
+ resetDoc();
+ discardConfirm = false;
}
// ---- panels ------------------------------------------------------------------
@@ -204,7 +295,11 @@
api.get(`/api/cases/${caseState.current.id}/media`),
api.get(`/api/cases/${caseState.current.id}/satellite`),
]);
- pickerItems = [
+ // A satellite capture *is* a media image, so it shows up in both lists. List
+ // it once, via its richer satellite entry (coordinates/attribution), and drop
+ // it from the media half. dedupeBySrc is a belt-and-braces guard so a stray
+ // overlap can never throw the keyed picker's `each_key_duplicate`.
+ pickerItems = dedupeBySrc([
...sats.map((s) => ({
...satPanelInput(s),
label: `${s.lat.toFixed(6)}, ${s.lon.toFixed(6)} · z${s.zoom}`,
@@ -212,20 +307,21 @@
kind: 'satellite',
})),
...media
- .filter((m) => m.kind === 'image')
+ .filter((m) => m.kind === 'image' && !isSatelliteCapture(m))
.map((m) => ({
...mediaPanelInput(m, media),
label: m.filename,
thumb: m.thumbnail ?? m.path,
kind: 'media',
})),
- ];
+ ]);
picker = true;
}
async function addPanel(item) {
try {
const img = await loadImage(`/files/${caseState.current.id}/${item.src}`);
+ imgCache.set(item.src, img);
// append to the current bottom row so new panels join the strip
const row = proof.panels.length
? Math.max(...proof.panels.map((p) => p.row ?? 0))
@@ -392,6 +488,13 @@
}
function onPointerDown(e) {
+ // space-drag / middle-drag pans regardless of the active tool
+ if (spacePan || e.evt.button === 1) {
+ e.evt.preventDefault();
+ const p = stage.getPointerPosition();
+ panDrag = { sx: p.x, sy: p.y, ox: stage.x(), oy: stage.y() };
+ return;
+ }
if (tool === 'select') {
const onEmpty = e.target === stage || e.target.name() === 'bg';
stage.draggable(onEmpty);
@@ -455,6 +558,12 @@
}
function onPointerMove() {
+ if (panDrag) {
+ const p = stage.getPointerPosition();
+ stage.position({ x: panDrag.ox + p.x - panDrag.sx, y: panDrag.oy + p.y - panDrag.sy });
+ stage.batchDraw();
+ return;
+ }
if (pathDraft) {
const box = pathDraft.box;
const doc = docPoint();
@@ -488,6 +597,10 @@
}
function onPointerUp() {
+ if (panDrag) {
+ panDrag = null;
+ return;
+ }
if (tool === 'select') {
stage.draggable(false);
return;
@@ -548,7 +661,7 @@
function rebuild() {
docLayer.destroyChildren();
- const { width, height, legend, cols } = docSize(proof.panels, proof.shapes, proof.notes, textOpts());
+ const { width, height, legend, cols } = docSize(proof.panels, proof.shapes, proof.notes, textOpts(), proof.legendOrder);
const boxes = layoutPanels(proof.panels, proof.captionSize);
const capSize = proof.captionSize ?? CAPTION_SIZE;
@@ -589,12 +702,11 @@
}
});
- // legend (numbered colored chips) laid out in `cols` columns, then footer.
- // Chip + text scale with the legend font size and stay vertically centred.
+ // legend (colored dots) laid out in `cols` columns, then footer.
+ // Dot + text scale with the legend font size and stay vertically centred.
const legendSize = proof.legendSize ?? 17;
const lineH = legendLineHeight(legendSize);
const r = Math.round(legendSize * 0.62);
- const numSize = Math.round(legendSize * 0.72);
const legendTop = PAD + panelsBlockHeight(proof.panels, proof.captionSize) + 8;
const colW = (width - PAD * 2 - (cols - 1) * PAD) / cols;
legend.filter((l) => l.text).forEach((line, i) => {
@@ -605,11 +717,6 @@
docLayer.add(new Konva.Circle({
x: cx + r, y: cy, radius: r, fill: line.color, listening: false,
}));
- docLayer.add(new Konva.Text({
- x: cx, y: cy - numSize * 0.62, width: r * 2, align: 'center',
- text: String(line.n), fontSize: numSize, fontStyle: 'bold',
- fill: '#0b0f17', listening: false,
- }));
docLayer.add(new Konva.Text({
x: cx + r * 2 + 8, y: cy - legendSize * 0.62, width: colW - (r * 2 + 8),
text: line.text, fontSize: legendSize, fill: TEXT_MAIN,
@@ -629,15 +736,16 @@
}));
}
- // selection
+ // selection — keyed on the shape's kind, not the Konva node's class name,
+ // since a framed/backgrounded text renders as a Group rather than a Text
const selectedNode = selectedId ? docLayer.findOne(`#${selectedId}`) : null;
transformer.nodes(selectedNode ? [selectedNode] : []);
- const cls = selectedNode?.className;
- transformer.rotateEnabled(cls === 'Text' || cls === 'Rect' || cls === 'Ellipse');
+ const selKind = selectedShape?.kind;
+ transformer.rotateEnabled(selKind === 'text' || selKind === 'rect' || selKind === 'ellipse');
transformer.enabledAnchors(
- cls === 'Rect' || cls === 'Ellipse'
+ selKind === 'rect' || selKind === 'ellipse'
? ['top-left', 'top-right', 'bottom-left', 'bottom-right', 'middle-left', 'middle-right', 'top-center', 'bottom-center']
- : cls === 'Text'
+ : selKind === 'text'
? ['top-left', 'top-right', 'bottom-left', 'bottom-right']
: []
);
@@ -771,17 +879,53 @@
function makeShapeNode(s, box) {
const panelScale = box.baseScale;
if (s.kind === 'text') {
- const node = new Konva.Text({
- id: s.id, x: s.x, y: s.y, text: s.text || ' ',
+ // The glyph itself: always built first so its measured size drives the
+ // optional frame/background box. Unboxed, it's also the interactive node.
+ const textNode = new Konva.Text({
+ x: 0, y: 0, text: s.text || ' ',
fontSize: s.fontSize ?? 28, fontFamily: 'system-ui, sans-serif',
- fontStyle: 'bold', fill: s.color, rotation: s.rotation ?? 0, draggable: true,
+ fontStyle: 'bold', fill: s.color,
});
+ const boxed = s.frame || s.bg;
+ let node; // the draggable/transformable/selectable node (group when boxed)
+ if (boxed) {
+ const pad = Math.round((s.fontSize ?? 28) * 0.28);
+ const w = textNode.width() + pad * 2;
+ const h = textNode.height() + pad * 2;
+ const frameSW = Math.max(2, Math.round((s.fontSize ?? 28) * 0.07));
+ node = new Konva.Group({ id: s.id, x: s.x, y: s.y, rotation: s.rotation ?? 0, draggable: true });
+ // invisible full-box hit target — clicking/dragging the padding (not
+ // just the glyph or the frame stroke) must still select this element
+ node.add(new Konva.Rect({ x: 0, y: 0, width: w, height: h, fill: 'transparent', listening: true }));
+ if (s.bg) {
+ node.add(new Konva.Rect({ x: 0, y: 0, width: w, height: h, fill: s.bg, cornerRadius: 4, listening: false }));
+ }
+ if (s.frame) {
+ node.add(new Konva.Rect({
+ x: 0, y: 0, width: w, height: h, stroke: s.color, strokeWidth: frameSW,
+ cornerRadius: 4, listening: false,
+ }));
+ }
+ textNode.position({ x: pad, y: pad });
+ textNode.listening(false);
+ node.add(textNode);
+ } else {
+ textNode.id(s.id);
+ textNode.position({ x: s.x, y: s.y });
+ textNode.rotation(s.rotation ?? 0);
+ textNode.draggable(true);
+ node = textNode;
+ }
node.on('pointerdown', (e) => {
if (tool === 'select') {
e.cancelBubble = true;
selectedId = s.id;
}
});
+ node.on('dblclick dbltap', (e) => {
+ e.cancelBubble = true;
+ startTextEdit(s, textNode);
+ });
node.on('dragstart', () => node.getParent()?.moveToTop());
node.on('dragend', () => {
const { fromBox, toBox } = rebindOnDrop(s, node);
@@ -871,6 +1015,40 @@
return node;
}
+ // ---- inline text editing (double-click a label on the canvas) ---------------
+ function startTextEdit(s, node) {
+ const boxes = layoutPanels(proof.panels, proof.captionSize);
+ const idx = proof.panels.findIndex((p) => p.id === s.panel);
+ const panelScale = idx >= 0 ? boxes[idx].scale : 1;
+ const abs = node.getAbsolutePosition(); // container px, stage transform included
+ selectedId = s.id;
+ textEdit = {
+ id: s.id,
+ value: s.text ?? '',
+ left: abs.x,
+ top: abs.y,
+ size: (s.fontSize ?? 28) * panelScale * stage.scaleX(),
+ color: s.color,
+ };
+ }
+
+ function commitTextEdit(keep = true) {
+ if (!textEdit) return;
+ if (keep) {
+ const s = proof.shapes.find((x) => x.id === textEdit.id);
+ if (s && s.text !== textEdit.value) {
+ s.text = textEdit.value;
+ dirty = true;
+ }
+ }
+ textEdit = null;
+ }
+
+ const focusSelect = (el) => {
+ el.focus();
+ el.select();
+ };
+
// ---- shape ops from the side panel -----------------------------------------------------
// ---- clipboard (copy / paste / duplicate of a single element) ---------------
@@ -914,6 +1092,23 @@
dirty = true;
}
+ // Reorder a shape among same-panel siblings only — order doubles as z-order
+ // (rebuild() adds shapes to their panel group in array order), so moving
+ // past a shape bound to a different panel would silently no-op visually.
+ function moveShape(index, delta) {
+ const panelId = proof.shapes[index].panel;
+ let target = index + delta;
+ while (target >= 0 && target < proof.shapes.length && proof.shapes[target].panel !== panelId) {
+ target += delta;
+ }
+ if (target < 0 || target >= proof.shapes.length || proof.shapes[target].panel !== panelId) return;
+ const [s] = proof.shapes.splice(index, 1);
+ proof.shapes.splice(target, 0, s);
+ dirty = true;
+ }
+ const canMoveShapeUp = (i) => proof.shapes.slice(0, i).some((s) => s.panel === proof.shapes[i].panel);
+ const canMoveShapeDown = (i) => proof.shapes.slice(i + 1).some((s) => s.panel === proof.shapes[i].panel);
+
const KIND_ICON = { rect: 'square', ellipse: 'circle', arrow: 'arrow', line: 'line', curve: 'curve', text: 'text' };
const KIND_LABEL = { rect: 'Box', ellipse: 'Ellipse', arrow: 'Arrow', line: 'Line', curve: 'Curve', text: 'Text' };
@@ -947,6 +1142,22 @@
}
}
+ // Arrow-key nudge of the selected element, in panel-natural pixels.
+ const NUDGE = {
+ ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1],
+ };
+ function nudgeSelected(dx, dy) {
+ const s = selectedShape;
+ if (!s) return;
+ if (Array.isArray(s.points)) {
+ s.points = s.points.map((v, i) => v + (i % 2 === 0 ? dx : dy));
+ } else {
+ s.x = (s.x ?? 0) + dx;
+ s.y = (s.y ?? 0) + dy;
+ }
+ dirty = true;
+ }
+
function onKeydown(e) {
if (uiState.tool !== 'proof') return;
if (['INPUT', 'TEXTAREA', 'SELECT'].includes(e.target.tagName)) return;
@@ -954,14 +1165,31 @@
finishPath(e.key === 'Enter');
return;
}
- // clipboard: copy / paste / duplicate the selected element
+ // clipboard / undo / save chords
if (e.ctrlKey || e.metaKey) {
const k = e.key.toLowerCase();
if (k === 'c' && selectedId) { e.preventDefault(); copyShape(); }
else if (k === 'v' && clipboard) { e.preventDefault(); pasteShape(); }
else if (k === 'd' && selectedId) { e.preventDefault(); duplicateShape(); }
+ else if (k === 'z') { e.preventDefault(); e.shiftKey ? redo() : undo(); }
+ else if (k === 'y') { e.preventDefault(); redo(); }
+ else if (k === 's') { e.preventDefault(); save(); }
return; // don't fall through to the single-letter tool shortcuts
}
+ if (NUDGE[e.key] && selectedId) {
+ e.preventDefault();
+ const step = e.shiftKey ? 10 : 1;
+ nudgeSelected(NUDGE[e.key][0] * step, NUDGE[e.key][1] * step);
+ return;
+ }
+ if (e.key === ' ' && !e.repeat) {
+ // hold space to pan, whatever the active tool — even over an element
+ e.preventDefault();
+ spacePan = true;
+ docLayer.listening(false);
+ containerEl.style.cursor = 'grab';
+ return;
+ }
if ((e.key === 'Delete' || e.key === 'Backspace') && selectedId) {
deleteShape(selectedId);
} else if (e.key === 'Escape') {
@@ -977,6 +1205,15 @@
else if (e.key === 'f') fit();
}
+ function onKeyup(e) {
+ if (e.key === ' ' && spacePan) {
+ spacePan = false;
+ panDrag = null;
+ docLayer?.listening(true);
+ if (containerEl) containerEl.style.cursor = '';
+ }
+ }
+
// ---- persistence -------------------------------------------------------------------------
function exportPng() {
@@ -999,6 +1236,23 @@
return dataUrl;
}
+ // Copy the composed PNG straight to the clipboard — for peer review in a
+ // chat before publishing, without hunting the file in the case folder.
+ let copying = $state(false);
+ async function copyPng() {
+ if (!proof.panels.length || copying) return;
+ copying = true;
+ try {
+ const blob = await (await fetch(exportPng())).blob();
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
+ toast('Proof image copied — paste it anywhere', 'ok');
+ } catch (e) {
+ toast(`Could not copy image: ${e.message}`, 'danger');
+ } finally {
+ copying = false;
+ }
+ }
+
async function save({ andPost = false } = {}) {
if (!proof.panels.length || saving) return;
saving = true;
@@ -1049,6 +1303,7 @@
for (const p of spec.panels) {
try {
const img = await loadImage(`/files/${caseState.current.id}/${p.src}`);
+ imgCache.set(p.src, img);
proof.panels.push({ ...p, id: p.id ?? newId('p'), row: p.row ?? 0, img });
} catch {
toast(`Missing panel image: ${p.src}`, 'warn');
@@ -1058,15 +1313,29 @@
proof.shapes = (spec.shapes ?? []).filter((s) => validPanels.has(s.panel));
// legend text lives in `notes` (per color); migrate old per-shape comments
proof.notes = spec.notes ?? notesFromShapes(proof.shapes);
+ proof.legendOrder = spec.legendOrder ?? [];
savedName = entry.name;
openList = null;
dirty = false;
+ anchorHistory();
requestAnimationFrame(fit);
}
const selectedShape = $derived(proof.shapes.find((s) => s.id === selectedId));
const activeColor = $derived(selectedShape?.color ?? color);
- const featureList = $derived(featureColors(proof.shapes));
+ const featureList = $derived(orderedFeatureColors(proof.shapes, proof.legendOrder));
+
+ // Swap a legend entry with its neighbour, persisting the whole resulting
+ // order — this also promotes any color that was only implicitly ordered
+ // (first-use) into an explicit, saved position.
+ function moveLegendColor(i, delta) {
+ const j = i + delta;
+ if (j < 0 || j >= featureList.length) return;
+ const order = [...featureList];
+ [order[i], order[j]] = [order[j], order[i]];
+ proof.legendOrder = order;
+ dirty = true;
+ }
// Coordinates + source shown above the panels: a manual override wins, else
// the value auto-derived from the panels (reactive — deleting the first
@@ -1075,7 +1344,7 @@
const displayedSource = $derived(proof.source.trim() || autoSource(proof.panels));
</script>
-<svelte:window onkeydown={onKeydown} />
+<svelte:window onkeydown={onKeydown} onkeyup={onKeyup} />
<div class="tool">
<div class="tool-header">
@@ -1086,7 +1355,20 @@
{#if caseState.current}
<button class="btn" onclick={openProofList}><Icon name="folderOpen" size={15} /> Open</button>
{/if}
+ {#if proof.panels.length}
+ <button class="btn" onclick={() => (discardConfirm = true)} title="Clear this proof">
+ <Icon name="reset" size={15} /> Discard
+ </button>
+ {/if}
<button class="btn" onclick={openPicker}><Icon name="plus" size={15} /> Add panel</button>
+ <button
+ class="btn"
+ onclick={copyPng}
+ disabled={!proof.panels.length || copying}
+ title="Copy the composed PNG to the clipboard — paste it in a chat or a tweet"
+ >
+ <Icon name="copy" size={15} /> {copying ? 'Copying…' : 'Copy PNG'}
+ </button>
<button class="btn btn-primary" onclick={() => save()} disabled={!proof.panels.length || saving}>
<Icon name="check" size={15} /> {saving ? 'Saving…' : 'Save'}
</button>
@@ -1098,6 +1380,13 @@
<div class="body">
<!-- left: drawing toolbar -->
<div class="toolbar">
+ <button class="tb-btn" title="Undo (Ctrl+Z)" disabled={!canUndo} onclick={undo}>
+ <Icon name="undo" size={18} />
+ </button>
+ <button class="tb-btn" title="Redo (Ctrl+Shift+Z / Ctrl+Y)" disabled={!canRedo} onclick={redo}>
+ <Icon name="redo" size={18} />
+ </button>
+ <div class="tb-sep"></div>
{#each DRAW_TOOLS as t (t.id)}
<button
class="tb-btn"
@@ -1170,6 +1459,23 @@
<!-- canvas -->
<div class="canvas-wrap" class:drawing={tool !== 'select'}>
<div class="konva" bind:this={containerEl}></div>
+ {#if textEdit}
+ <input
+ class="text-edit"
+ style:left={`${textEdit.left}px`}
+ style:top={`${textEdit.top}px`}
+ style:font-size={`${textEdit.size}px`}
+ style:color={textEdit.color}
+ bind:value={textEdit.value}
+ use:focusSelect
+ onblur={() => commitTextEdit(true)}
+ onkeydown={(e) => {
+ e.stopPropagation();
+ if (e.key === 'Enter') commitTextEdit(true);
+ else if (e.key === 'Escape') commitTextEdit(false);
+ }}
+ />
+ {/if}
{#if !proof.panels.length}
<div class="empty overlay-empty">
<div class="empty-icon"><Icon name="proof" size={42} /></div>
@@ -1291,6 +1597,14 @@
{/if}
{#each featureList as c, i (c)}
<div class="anno-row" class:active={activeColor === c}>
+ <div class="reorder">
+ <button class="btn btn-ghost reorder-btn" disabled={i === 0} title="Move up" onclick={() => moveLegendColor(i, -1)}>
+ <Icon name="chevronUp" size={11} />
+ </button>
+ <button class="btn btn-ghost reorder-btn" disabled={i === featureList.length - 1} title="Move down" onclick={() => moveLegendColor(i, 1)}>
+ <Icon name="chevronDown" size={11} />
+ </button>
+ </div>
<button
class="chip-num"
style:background={c}
@@ -1321,6 +1635,14 @@
tabindex="0"
onkeydown={(e) => e.key === 'Enter' && (selectedId = s.id)}
>
+ <div class="reorder">
+ <button class="btn btn-ghost reorder-btn" disabled={!canMoveShapeUp(i)} title="Move up (z-order within its panel)" onclick={(e) => { e.stopPropagation(); moveShape(i, -1); }}>
+ <Icon name="chevronUp" size={11} />
+ </button>
+ <button class="btn btn-ghost reorder-btn" disabled={!canMoveShapeDown(i)} title="Move down (z-order within its panel)" onclick={(e) => { e.stopPropagation(); moveShape(i, 1); }}>
+ <Icon name="chevronDown" size={11} />
+ </button>
+ </div>
<span class="chip" style:background={s.color}></span>
<Icon name={KIND_ICON[s.kind]} size={13} />
{#if s.kind === 'text'}
@@ -1331,6 +1653,34 @@
onchange={() => (dirty = true)}
onclick={(e) => e.stopPropagation()}
/>
+ <button
+ class="btn btn-ghost btn-sm"
+ class:active={s.frame}
+ title="Frame (border in the text's color)"
+ onclick={(e) => { e.stopPropagation(); s.frame = !s.frame; dirty = true; }}
+ >
+ <Icon name="square" size={13} />
+ </button>
+ <label
+ class="color-btn color-pick bg-pick"
+ class:active={!!s.bg}
+ style:background={s.bg || 'transparent'}
+ title="Background color"
+ onclick={(e) => e.stopPropagation()}
+ >
+ <Icon name="plus" size={11} />
+ <input
+ type="color"
+ value={s.bg || '#000000'}
+ oninput={(e) => { s.bg = e.target.value; dirty = true; }}
+ aria-label="text background color"
+ />
+ </label>
+ {#if s.bg}
+ <button class="btn btn-ghost btn-sm" title="Remove background" onclick={(e) => { e.stopPropagation(); s.bg = null; dirty = true; }}>
+ <Icon name="x" size={11} />
+ </button>
+ {/if}
{:else}
<span class="el-label">{KIND_LABEL[s.kind]} <span class="el-id">#{i + 1}</span></span>
{/if}
@@ -1386,6 +1736,19 @@
</div>
</div>
+{#if discardConfirm}
+ <ConfirmDialog
+ title="Discard this proof?"
+ message="The current document — panels, annotations and layout — will be cleared."
+ detail={savedName ? 'This does not delete the saved proof, only the unsaved changes here.' : 'Anything not saved yet will be lost.'}
+ confirmLabel="Discard"
+ tone="danger"
+ icon="reset"
+ onconfirm={discardProof}
+ oncancel={() => (discardConfirm = false)}
+ />
+{/if}
+
{#if picker}
<Modal title="Add a panel" onclose={() => (picker = false)} width="720px">
{#if !pickerItems.length}
@@ -1523,6 +1886,20 @@
}
.canvas-wrap.drawing { cursor: crosshair; }
.konva { position: absolute; inset: 0; }
+ .tb-btn:disabled { opacity: 0.35; cursor: default; }
+ .tb-btn:disabled:hover { color: var(--text-3); background: none; }
+ .text-edit {
+ position: absolute;
+ transform: translateY(-2px);
+ min-width: 60px;
+ padding: 0 2px;
+ font-family: system-ui, sans-serif;
+ font-weight: 700;
+ background: rgba(9, 12, 20, 0.85);
+ border: 1px dashed var(--accent);
+ border-radius: 2px;
+ outline: none;
+ }
.overlay-empty {
position: absolute;
inset: 0;
@@ -1687,6 +2064,26 @@
border: 1px solid transparent;
}
.anno-row.active { border-color: var(--accent); background: var(--accent-soft); }
+ .reorder {
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ flex-shrink: 0;
+ }
+ .reorder-btn {
+ padding: 0 2px;
+ line-height: 1;
+ color: var(--text-3);
+ }
+ .reorder-btn:disabled { opacity: 0.25; cursor: default; }
+ .bg-pick {
+ width: 20px;
+ height: 20px;
+ flex-shrink: 0;
+ border: 1px dashed var(--border);
+ }
+ .bg-pick.active { border-style: solid; }
+ .bg-pick:not(.active) { color: var(--text-3); }
.chip-num {
width: 20px;
height: 20px;
diff --git a/frontend/src/tools/RefViewer.svelte b/frontend/src/tools/RefViewer.svelte
new file mode 100644
index 0000000..e98b840
--- /dev/null
+++ b/frontend/src/tools/RefViewer.svelte
@@ -0,0 +1,333 @@
+<script>
+ // One floating reference-image window over the Satellite map. Drag the header
+ // to move it, roll it up, resize from the corner, fade it with the opacity
+ // slider, and wheel/drag to zoom & pan the image. Pure geometry lives in
+ // lib/refViewers.js; this file is the pointer/DOM glue. Session-only: nothing
+ // here is captured or saved.
+ import Icon from '../components/Icon.svelte';
+ import {
+ clamp,
+ clampWindow,
+ clampSize,
+ clampPan,
+ zoomAt,
+ MIN_SCALE,
+ MAX_SCALE,
+ } from '../lib/refViewers.js';
+
+ let { viewer, caseId, zBase = 630, onfocus, onclose } = $props();
+
+ let el; // the window root
+ let headEl;
+ let bodyEl;
+
+ // the map-wrap we're positioned in — the box drags/resizes are clamped to
+ const bounds = () => {
+ const r = el.parentElement.getBoundingClientRect();
+ return { w: r.width, h: r.height };
+ };
+
+ function focus() {
+ onfocus?.(viewer.id);
+ }
+
+ // run `move` on pointer drags until release; shared by the three gestures
+ function drag(move) {
+ const up = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ }
+
+ function startWindowDrag(e) {
+ if (e.button !== 0 || e.target.closest('button')) return;
+ focus();
+ e.preventDefault();
+ const sx = e.clientX;
+ const sy = e.clientY;
+ const x0 = viewer.x;
+ const y0 = viewer.y;
+ drag((ev) => {
+ const h = viewer.collapsed ? headEl.offsetHeight : viewer.h;
+ const c = clampWindow(x0 + (ev.clientX - sx), y0 + (ev.clientY - sy), viewer.w, h, bounds());
+ viewer.x = c.x;
+ viewer.y = c.y;
+ });
+ }
+
+ function startResize(e) {
+ if (e.button !== 0) return;
+ focus();
+ e.preventDefault();
+ e.stopPropagation();
+ const sx = e.clientX;
+ const sy = e.clientY;
+ const w0 = viewer.w;
+ const h0 = viewer.h;
+ drag((ev) => {
+ const s = clampSize(w0 + (ev.clientX - sx), h0 + (ev.clientY - sy), viewer.x, viewer.y, bounds());
+ viewer.w = s.w;
+ viewer.h = s.h;
+ reclampPan();
+ });
+ }
+
+ function startPan(e) {
+ // videos keep their native controls; only the zoomed-in image pans, and at
+ // fit scale a drag does nothing
+ if (isVideo || e.button !== 0 || viewer.scale <= MIN_SCALE) return;
+ focus();
+ e.preventDefault();
+ const sx = e.clientX;
+ const sy = e.clientY;
+ const ox0 = viewer.ox;
+ const oy0 = viewer.oy;
+ drag((ev) => {
+ const p = clampPan(
+ ox0 + (ev.clientX - sx),
+ oy0 + (ev.clientY - sy),
+ viewer.scale,
+ bodyEl.clientWidth,
+ bodyEl.clientHeight
+ );
+ viewer.ox = p.ox;
+ viewer.oy = p.oy;
+ });
+ }
+
+ function onWheel(e) {
+ if (isVideo) return; // let the page scroll / video controls behave normally
+ e.preventDefault();
+ const rect = bodyEl.getBoundingClientRect();
+ const cursor = { x: e.clientX - rect.left, y: e.clientY - rect.top };
+ const factor = e.deltaY < 0 ? 1.15 : 1 / 1.15;
+ apply(zoomAt(viewer, factor, cursor, { w: rect.width, h: rect.height }));
+ }
+
+ function zoomBy(factor) {
+ const size = { w: bodyEl.clientWidth, h: bodyEl.clientHeight };
+ apply(zoomAt(viewer, factor, { x: size.w / 2, y: size.h / 2 }, size));
+ }
+
+ function resetZoom() {
+ viewer.scale = 1;
+ viewer.ox = 0;
+ viewer.oy = 0;
+ }
+
+ function apply({ scale, ox, oy }) {
+ viewer.scale = scale;
+ viewer.ox = ox;
+ viewer.oy = oy;
+ }
+
+ // keep the pan legal after the window (and so the viewport) resizes
+ function reclampPan() {
+ if (!bodyEl) return;
+ const p = clampPan(viewer.ox, viewer.oy, viewer.scale, bodyEl.clientWidth, bodyEl.clientHeight);
+ viewer.ox = p.ox;
+ viewer.oy = p.oy;
+ }
+
+ const isVideo = $derived(viewer.kind === 'video');
+ const pct = $derived(Math.round(viewer.scale * 100));
+</script>
+
+<div
+ bind:this={el}
+ class="ref-viewer card"
+ class:collapsed={viewer.collapsed}
+ style:left={`${viewer.x}px`}
+ style:top={`${viewer.y}px`}
+ style:width={`${viewer.w}px`}
+ style:height={viewer.collapsed ? 'auto' : `${viewer.h}px`}
+ style:z-index={zBase + viewer.z}
+ onpointerdown={focus}
+>
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div bind:this={headEl} class="rv-head" onpointerdown={startWindowDrag} title="Drag to move">
+ <Icon name="grip" size={14} />
+ <span class="rv-title" title={viewer.title}>{viewer.title || 'Reference'}</span>
+ <button
+ class="rv-btn"
+ onclick={() => (viewer.collapsed = !viewer.collapsed)}
+ title={viewer.collapsed ? 'Expand' : 'Collapse'}
+ aria-label={viewer.collapsed ? 'Expand' : 'Collapse'}
+ >
+ <Icon name={viewer.collapsed ? 'chevronDown' : 'chevronUp'} size={13} />
+ </button>
+ <button class="rv-btn" onclick={() => onclose?.(viewer.id)} title="Close" aria-label="Close">
+ <Icon name="x" size={13} />
+ </button>
+ </div>
+
+ {#if !viewer.collapsed}
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div
+ bind:this={bodyEl}
+ class="rv-body"
+ class:pannable={!isVideo && viewer.scale > MIN_SCALE}
+ onpointerdown={startPan}
+ onwheel={onWheel}
+ >
+ {#if caseId}
+ {#if isVideo}
+ <!-- svelte-ignore a11y_media_has_caption -->
+ <video src={`/files/${caseId}/${viewer.path}`} controls preload="metadata"></video>
+ {:else}
+ <img
+ src={`/files/${caseId}/${viewer.path}`}
+ alt={viewer.title}
+ draggable="false"
+ style:transform={`translate(${viewer.ox}px, ${viewer.oy}px) scale(${viewer.scale})`}
+ />
+ {/if}
+ {/if}
+ </div>
+
+ {#if !isVideo}
+ <div class="rv-foot">
+ <span class="rv-gap"></span>
+ <button class="rv-btn" onclick={() => zoomBy(1 / 1.25)} title="Zoom out" aria-label="Zoom out">
+ <Icon name="minimize" size={12} />
+ </button>
+ <button class="rv-zoom" onclick={resetZoom} title="Reset zoom">{pct}%</button>
+ <button class="rv-btn" onclick={() => zoomBy(1.25)} title="Zoom in" aria-label="Zoom in">
+ <Icon name="plus" size={13} />
+ </button>
+ </div>
+ {/if}
+
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div class="rv-resize" onpointerdown={startResize} title="Resize"></div>
+ {/if}
+</div>
+
+<style>
+ .ref-viewer {
+ position: absolute;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ background: rgba(16, 22, 35, 0.92);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-2);
+ user-select: none;
+ }
+ .rv-head {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 6px 5px 8px;
+ color: var(--text-2);
+ cursor: grab;
+ flex-shrink: 0;
+ }
+ .rv-head:active {
+ cursor: grabbing;
+ }
+ .rv-title {
+ flex: 1;
+ min-width: 0;
+ font-size: var(--fs-xs);
+ color: var(--text-1);
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .rv-btn {
+ display: grid;
+ place-items: center;
+ width: 22px;
+ height: 22px;
+ border-radius: var(--radius-1);
+ color: var(--text-2);
+ cursor: pointer;
+ flex-shrink: 0;
+ }
+ .rv-btn:hover {
+ color: var(--text-1);
+ background: var(--bg-3);
+ }
+ .rv-body {
+ flex: 1;
+ min-height: 0;
+ position: relative;
+ overflow: hidden;
+ background:
+ linear-gradient(45deg, rgba(255, 255, 255, 0.03) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.03) 75%),
+ linear-gradient(45deg, rgba(255, 255, 255, 0.03) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.03) 75%);
+ background-size: 16px 16px;
+ background-position: 0 0, 8px 8px;
+ }
+ .rv-body.pannable {
+ cursor: grab;
+ }
+ .rv-body.pannable:active {
+ cursor: grabbing;
+ }
+ .rv-body img {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ transform-origin: 0 0;
+ pointer-events: none;
+ }
+ .rv-body video {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ background: #000;
+ }
+ .rv-foot {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 8px;
+ color: var(--text-3);
+ border-top: 1px solid var(--border);
+ flex-shrink: 0;
+ }
+ .rv-gap {
+ flex: 1;
+ }
+ .rv-zoom {
+ min-width: 42px;
+ text-align: center;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ cursor: pointer;
+ padding: 2px 4px;
+ border-radius: var(--radius-1);
+ }
+ .rv-zoom:hover {
+ color: var(--accent);
+ background: var(--bg-3);
+ }
+ .rv-resize {
+ position: absolute;
+ right: 0;
+ bottom: 0;
+ width: 16px;
+ height: 16px;
+ cursor: nwse-resize;
+ background: linear-gradient(
+ 135deg,
+ transparent 50%,
+ var(--border-strong) 50%,
+ var(--border-strong) 60%,
+ transparent 60%,
+ transparent 72%,
+ var(--border-strong) 72%,
+ var(--border-strong) 82%,
+ transparent 82%
+ );
+ }
+</style>
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index c462e63..4770a73 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -4,22 +4,34 @@
import 'leaflet/dist/leaflet.css';
import { api } from '../lib/api.js';
import { caseState, uiState, ensureCase, reloadCase, toast } from '../lib/state.svelte.js';
+ import { mapLinks } from '../lib/maplinks.js';
+ import * as measure from '../lib/measure.js';
+ import { dragBearing, pivotPanOffset } from '../lib/satRotate.js';
+ import { SIZE_MIN, SIZE_MAX, clampSize, scaledCapture } from '../lib/captureSize.js';
+ import { monthCount, tilesShort } from '../lib/usage.js';
+ import { createViewer, nextZ, restack } from '../lib/refViewers.js';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
+ import ConfirmDialog from '../components/ConfirmDialog.svelte';
+ import RefViewer from './RefViewer.svelte';
let mapEl;
+ let toolEl; // tool root — target of the real (browser) fullscreen (item 5)
let map;
let tileLayer;
let providers = $state([]);
let providerId = $state('esri-world-imagery');
let coordsText = $state('');
let center = $state({ lat: 48.8584, lon: 2.2945, zoom: 16 });
- let size = $state('1000x700');
- let markerStyle = $state('crosshair'); // 'crosshair' | 'pin' | 'none'
+ let markerStyle = $state('none'); // 'crosshair' | 'pin' | 'none' — clean view by default (item 4)
let moveMode = $state(false); // pin decoupled from center, draggable
let marker = null; // Leaflet marker instance while in move mode
let markerLatLng = $state(null); // {lat, lon} of the moved pin
let bearing = $state(0);
+ // Middle-drag rotation: a sober "target" marks the grabbed point and the map
+ // turns around it (Google-Earth style, mirrors the Frame viewer).
+ let rotating = $state(false);
+ let rotatePivot = $state({ x: 0, y: 0 }); // grabbed point, map-wrap-local px
let capturing = $state(false);
let captureHover = $state(false); // previewing the crop frame (capture group hover)
let captures = $state([]);
@@ -27,6 +39,109 @@
let capturesCollapsed = $state(false);
let mapReady = $state(false);
+ // OSM labels overlay: a transparent labels-only layer laid over the imagery so
+ // roads / place names are readable without hiding the satellite view (item 1).
+ let osmOverlay = $state(false);
+ let labelsLayer = null;
+ const LABELS_URL =
+ 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager_only_labels/{z}/{x}/{y}.png';
+ // The labels overlay only makes sense over satellite imagery — over a street
+ // base map (OSM) it just doubles the road/place labels, so it's disabled then
+ // and force-off if the provider changes to a non-imagery one (item 1).
+ const currentProvider = $derived(providers.find((p) => p.id === providerId));
+ const baseIsImagery = $derived(currentProvider?.imagery ?? true);
+ // view-only basemaps (capturable=false) keep the map but not the capture
+ // button (KEYED_PROVIDERS.md §4) — none built-in today, gate wired anyway
+ const captureBlocked = $derived(currentProvider?.capturable === false);
+
+ // --- keyed-provider usage (KEYED_PROVIDERS.md §6) ---
+ // Metered tiles are proxied through the backend, which counts each one it
+ // actually serves — this readout just mirrors settings.json.
+ let usageTotals = $state({});
+ let usageMonth = $state('');
+ async function refreshUsage() {
+ try {
+ const s = await api.get('/api/settings');
+ usageTotals = s.usage;
+ usageMonth = s.month;
+ } catch {
+ /* readout only — never blocks the map */
+ }
+ }
+ // small readout near the basemap selector, billed providers only
+ const usagePill = $derived(
+ currentProvider?.meter
+ ? tilesShort(monthCount(usageTotals, currentProvider.meter, usageMonth))
+ : null
+ );
+
+ // Acquisition date of the imagery under the crosshair — Esri only (item 2).
+ let imageryDate = $state(null); // { supported, date, source } | null
+ let dateReqId = 0;
+ let dateTimer;
+
+ // Fullscreen: the tool covers the whole viewport; SAVED stays collapsible (item 4).
+ let fullscreen = $state(false);
+
+ // Editable bearing readout (item 3): click the number to type an angle.
+ let editingBearing = $state(false);
+ let bearingInput = $state('');
+
+ // Measure tools (item 5): distance / area / angle drawn on the map.
+ let measureMode = $state(null); // null | 'distance' | 'area' | 'angle'
+ let measurePoints = $state([]);
+ let measureLayer = null;
+ let toolsOpen = $state(false);
+
+ // External-maps quick links, in the SAVED panel (item 6).
+ let linksOpen = $state(false);
+
+ // --- reference viewers: floating scratch windows over the map that hold a
+ // media image (the shot to geolocate) so you can eyeball it against the
+ // imagery while panning. Session-only (uiState.refViewers) — never captured,
+ // never saved, dropped when the case changes (see openCase).
+ let refPicker = $state(false); // the "pick an image" modal
+ let refMedia = $state([]); // case images available to reference
+ let refLoading = $state(false);
+ let refSeq = 0; // id source for spawned windows
+
+ async function openRefPicker() {
+ refPicker = true;
+ refLoading = true;
+ try {
+ const id = caseState.current?.id;
+ const media = id ? await api.get(`/api/cases/${id}/media`) : [];
+ refMedia = media.filter((m) => m.kind === 'image' || m.kind === 'video');
+ } catch (e) {
+ toast(`Could not load media: ${e.message}`, 'danger');
+ refMedia = [];
+ } finally {
+ refLoading = false;
+ }
+ }
+
+ function addRef(item) {
+ const vs = uiState.refViewers;
+ const n = vs.length;
+ vs.push(
+ createViewer(`ref-${++refSeq}`, item, {
+ x: 60 + (n % 6) * 26,
+ y: 60 + (n % 6) * 26,
+ z: nextZ(vs),
+ })
+ );
+ refPicker = false;
+ }
+
+ function focusRef(id) {
+ const z = restack(uiState.refViewers, id);
+ for (const v of uiState.refViewers) v.z = z.get(v.id);
+ }
+
+ function closeRef(id) {
+ uiState.refViewers = uiState.refViewers.filter((v) => v.id !== id);
+ }
+
onMount(async () => {
providers = await api.get('/api/satellite/providers');
// leaflet-rotate patches the global L, so expose it before importing.
@@ -35,7 +150,7 @@
map = L.map(mapEl, {
center: [center.lat, center.lon],
zoom: center.zoom,
- zoomControl: true,
+ zoomControl: false,
attributionControl: true,
rotate: true,
rotateControl: false,
@@ -43,6 +158,12 @@
shiftKeyRotate: true,
});
setLayer();
+ setOverlay();
+ // stacked below the top-left tool cluster (fullscreen/labels/measure) via
+ // CSS offset below, instead of Leaflet's default corner margin
+ L.control.zoom({ position: 'topleft' }).addTo(map);
+ // judging feature sizes (buildings, roads) needs a scale reference
+ L.control.scale({ imperial: false, position: 'bottomright' }).addTo(map);
map.on('moveend zoomend', () => {
const c = map.getCenter();
center = { lat: c.lat, lon: c.lng, zoom: map.getZoom() };
@@ -50,18 +171,313 @@
map.on('rotate', () => {
bearing = Math.round(map.getBearing());
});
+ map.on('click', onMapClick);
+ // keep tiles seam-free (see deSeamTiles): re-flatten after any reposition,
+ // and un-flatten right before a zoom so the reposition doesn't double-offset
+ map.on('moveend zoomend viewreset rotateend', scheduleDeSeam);
+ map.on('zoomstart', reSeamTiles);
+ // middle-mouse drag rotates the view (item 3). Capture-phase so we can stop
+ // the event before Leaflet's own container drag handler (which treats the
+ // middle button as a pan) ever sees it — otherwise a turn also pans.
+ mapEl.addEventListener('mousedown', onMiddleRotateStart, true);
+ // left-drag draws the capture marquee when that mode is armed (capture-phase
+ // so Leaflet's pan handler never sees the gesture)
+ mapEl.addEventListener('mousedown', onSelectStart, true);
+ window.addEventListener('keydown', onKeydown);
+ document.addEventListener('fullscreenchange', onFullscreenChange);
mapReady = true;
- return () => map.remove();
+ return () => {
+ window.removeEventListener('keydown', onKeydown);
+ document.removeEventListener('fullscreenchange', onFullscreenChange);
+ map.remove();
+ };
+ });
+
+ function onKeydown(e) {
+ if (uiState.tool !== 'satellite' || e.key !== 'Escape') return;
+ if (selectArmed) toggleSelect();
+ else if (sizeMenuOpen) sizeMenuOpen = false;
+ else if (measureMode) setMeasureMode(null);
+ // native fullscreen already exits on Esc (handled by onFullscreenChange);
+ // only the CSS fallback needs an explicit toggle here
+ else if (fullscreen && !document.fullscreenElement) toggleFullscreen();
+ }
+
+ // --- OSM labels overlay (item 1) ---
+ function setOverlay() {
+ if (!map) return;
+ if (osmOverlay && !labelsLayer) {
+ labelsLayer = L.tileLayer(LABELS_URL, {
+ subdomains: 'abcd',
+ maxZoom: 20,
+ pane: 'overlayPane', // above the imagery tiles, below markers/controls
+ attribution: '© OpenStreetMap contributors © CARTO',
+ }).addTo(map);
+ labelsLayer.on('load tileload', scheduleDeSeam); // keep overlay seam-free too
+ } else if (!osmOverlay && labelsLayer) {
+ labelsLayer.remove();
+ labelsLayer = null;
+ }
+ }
+
+ // force the labels overlay off whenever the base isn't imagery (item 1)
+ $effect(() => {
+ if (!baseIsImagery && osmOverlay) osmOverlay = false;
+ });
+
+ $effect(() => {
+ osmOverlay; // toggle the labels overlay
+ setOverlay();
+ });
+
+ // --- imagery date under the crosshair (item 2) ---
+ async function refreshImageryDate() {
+ const id = ++dateReqId;
+ try {
+ const r = await api.get(
+ `/api/satellite/imagery-date?lat=${center.lat}&lon=${center.lon}` +
+ `&zoom=${center.zoom}&provider=${providerId}`
+ );
+ if (id === dateReqId) imageryDate = r;
+ } catch {
+ if (id === dateReqId) imageryDate = { supported: true, date: null, source: null };
+ }
+ }
+
+ // debounce: the target moves a lot while panning — only query once it settles
+ $effect(() => {
+ center.lat;
+ center.lon;
+ center.zoom;
+ providerId;
+ if (!mapReady) return;
+ clearTimeout(dateTimer);
+ dateTimer = setTimeout(refreshImageryDate, 500);
+ });
+
+ // --- middle-drag rotate (item 3), Google-Earth style ---
+ // Grab a point → the map turns around *that* point (not the centre) as the
+ // cursor sweeps, with a sober target marking the pivot. Leaflet only rotates
+ // about the centre, so after each bearing change we pan the grabbed geographic
+ // point back under the cursor — keeping it pinned exactly where you grabbed.
+ const ROTATE_DEADZONE = 8; // px to leave the pivot before the spoke is fixed
+ function onMiddleRotateStart(e) {
+ if (e.button !== 1 || !map) return;
+ // own the gesture: no Leaflet pan, no browser middle-click autoscroll
+ e.stopPropagation();
+ e.preventDefault();
+ const rect = mapEl.getBoundingClientRect();
+ const grab = L.point(e.clientX - rect.left, e.clientY - rect.top);
+ const pivotLatLng = map.containerPointToLatLng(grab); // the pinned location
+ const startBearing = map.getBearing();
+ const startScreen = { x: e.clientX, y: e.clientY };
+ rotatePivot = { x: grab.x, y: grab.y };
+ rotating = true;
+ let startAngle = null; // reference spoke, fixed once out of the deadzone
+ const move = (ev) => {
+ if (startAngle === null) {
+ if (Math.hypot(ev.clientX - startScreen.x, ev.clientY - startScreen.y) < ROTATE_DEADZONE) return;
+ startAngle = { x: ev.clientX, y: ev.clientY };
+ return;
+ }
+ setBearing(dragBearing(startBearing, startScreen, startAngle, { x: ev.clientX, y: ev.clientY }));
+ // re-pin: pan the grabbed location back under the grab point
+ const now = map.latLngToContainerPoint(pivotLatLng);
+ const [dx, dy] = pivotPanOffset(grab, now);
+ if (dx || dy) map.panBy([dx, dy], { animate: false });
+ };
+ const up = () => {
+ rotating = false;
+ window.removeEventListener('mousemove', move);
+ window.removeEventListener('mouseup', up);
+ };
+ window.addEventListener('mousemove', move);
+ window.addEventListener('mouseup', up);
+ }
+
+ function startEditBearing() {
+ bearingInput = String(bearing);
+ editingBearing = true;
+ }
+
+ function commitBearing() {
+ const v = parseFloat(bearingInput);
+ if (Number.isFinite(v)) setBearing(v);
+ editingBearing = false;
+ }
+
+ // --- fullscreen (item 5) ---
+ // Prefer the real Fullscreen API — it covers the OS/browser chrome too, unlike
+ // the old fixed-overlay hack. Fall back to a CSS overlay where it's blocked
+ // (e.g. an iframe without allow="fullscreen"). onFullscreenChange keeps the
+ // `fullscreen` flag in sync when the browser enters/exits (Esc, F11, etc.).
+ async function toggleFullscreen() {
+ if (document.fullscreenElement) {
+ await document.exitFullscreen().catch(() => {});
+ return;
+ }
+ if (toolEl?.requestFullscreen) {
+ try {
+ await toolEl.requestFullscreen();
+ return; // state + resize handled by onFullscreenChange
+ } catch {
+ /* blocked — fall through to the CSS fallback */
+ }
+ }
+ fullscreen = !fullscreen;
+ await tick();
+ map?.invalidateSize();
+ }
+
+ function onFullscreenChange() {
+ if (document.fullscreenElement === toolEl) fullscreen = true;
+ else if (!document.fullscreenElement) fullscreen = false;
+ tick().then(() => map?.invalidateSize());
+ }
+
+ // --- measure tools (item 5) ---
+ function onMapClick(e) {
+ if (!measureMode) return;
+ const pt = { lat: e.latlng.lat, lon: e.latlng.lng };
+ // an angle is exactly three points; a fourth click starts a fresh angle
+ if (measureMode === 'angle' && measurePoints.length >= 3) measurePoints = [];
+ measurePoints = [...measurePoints, pt];
+ redrawMeasure();
+ }
+
+ function setMeasureMode(m) {
+ measureMode = measureMode === m ? null : m;
+ if (measureMode) selectArmed = false; // measuring and marquee can't both be armed
+ measurePoints = [];
+ measureLayer?.clearLayers();
+ }
+
+ // toggling the panel shut also drops any active measure tool — otherwise the
+ // ruler button stays lit (and the tool stays armed) with the panel gone
+ function toggleTools() {
+ toolsOpen = !toolsOpen;
+ if (!toolsOpen && measureMode) setMeasureMode(null);
+ }
+
+ function clearMeasure() {
+ measurePoints = [];
+ measureLayer?.clearLayers();
+ }
+
+ function redrawMeasure() {
+ if (!map) return;
+ if (!measureLayer) measureLayer = L.layerGroup().addTo(map);
+ measureLayer.clearLayers();
+ const latlngs = measurePoints.map((p) => [p.lat, p.lon]);
+ const stroke = { color: '#f5a623', weight: 2.5, opacity: 0.95 };
+ if (measureMode === 'area' && latlngs.length >= 2) {
+ L.polygon(latlngs, { ...stroke, fillColor: '#f5a623', fillOpacity: 0.15 }).addTo(
+ measureLayer
+ );
+ } else if (latlngs.length >= 2) {
+ L.polyline(latlngs, stroke).addTo(measureLayer);
+ }
+ for (const p of measurePoints) {
+ L.circleMarker([p.lat, p.lon], {
+ radius: 4,
+ color: '#fff',
+ weight: 2,
+ fillColor: '#f5a623',
+ fillOpacity: 1,
+ }).addTo(measureLayer);
+ }
+ }
+
+ const measureReadout = $derived.by(() => {
+ if (!measureMode || measurePoints.length < 2) return null;
+ if (measureMode === 'distance')
+ return measure.formatDistance(measure.pathLength(measurePoints));
+ if (measureMode === 'area')
+ return measurePoints.length >= 3
+ ? measure.formatArea(measure.polygonArea(measurePoints))
+ : '…';
+ // angle needs a middle vertex
+ return measurePoints.length >= 3
+ ? measure.formatAngle(measure.angleAt(measurePoints[0], measurePoints[1], measurePoints[2]))
+ : '…';
});
+ const MEASURE_HINT = {
+ distance: 'Click points along the path',
+ area: 'Click the polygon corners',
+ angle: 'Click three points — vertex second',
+ };
+
+ // --- external map links (item 6) ---
+ const externalLinks = $derived(mapLinks(displayCoords.lat, displayCoords.lon, center.zoom));
+
+ // fly the map to a capture's recorded point (item 7)
+ function flyToCapture(item) {
+ if (!map) return;
+ map.setView([item.lat, item.lon], item.zoom || map.getZoom());
+ setBearing(item.bearing || 0);
+ }
+
+ // --- tile seam fix ---
+ // Leaflet positions each tile with a `translate3d(...)` transform, which
+ // promotes it to its own GPU layer. At fractional OS display scaling (e.g.
+ // 125/150%) an integer CSS position lands on a half physical pixel, so every
+ // tile edge is antialiased independently and bleeds the map background as a
+ // faint white grid — browser- and zoom-independent. Painting tiles with plain
+ // left/top (no transform, no backface-visibility promotion — see CSS) keeps
+ // them in the shared pane layer, where neighbouring edges meet on whole
+ // pixels. Rotation/zoom still use their own pane transforms, so both keep
+ // working. We convert after Leaflet positions the tiles, and revert to
+ // transform positioning just before a zoom so the reposition is glitch-free.
+ let deSeamRaf = 0;
+ function deSeamTiles() {
+ deSeamRaf = 0;
+ if (!mapEl) return;
+ for (const t of mapEl.querySelectorAll('.leaflet-tile')) {
+ const m = /translate3d\((-?[\d.]+)px,\s*(-?[\d.]+)px/.exec(t.style.transform);
+ if (!m) continue; // already flat, or a rotated matrix we shouldn't touch
+ t.style.left = m[1] + 'px';
+ t.style.top = m[2] + 'px';
+ t.style.transform = 'none';
+ }
+ }
+ function scheduleDeSeam() {
+ if (!deSeamRaf) deSeamRaf = requestAnimationFrame(deSeamTiles);
+ }
+ // put the translate transform back before Leaflet repositions tiles for a new
+ // zoom, so a tile is never briefly offset by both left/top and translate3d
+ function reSeamTiles() {
+ if (!mapEl) return;
+ for (const t of mapEl.querySelectorAll('.leaflet-tile')) {
+ if (t.style.transform === 'none' && t.style.left) {
+ t.style.transform = `translate3d(${t.style.left}, ${t.style.top}, 0)`;
+ t.style.left = '';
+ t.style.top = '';
+ }
+ }
+ }
+
function setLayer() {
const p = providers.find((x) => x.id === providerId);
if (!p || !map) return;
+ // metered/keyed providers go through the backend tile proxy: the key and
+ // any session token stay server-side, and every billed tile is counted
+ // exactly once (browser cache hits never reach the proxy)
+ const url = p.meter ? `/api/tiles/${p.id}/{z}/{x}/{y}` : p.url;
+ const opts = { attribution: p.attribution, maxZoom: p.max_zoom };
+ if (p.tile_size === 512) {
+ // 512px tiles: same m/px at z-1, a quarter of the billed requests
+ opts.tileSize = 512;
+ opts.zoomOffset = -1;
+ }
if (tileLayer) tileLayer.remove();
- tileLayer = L.tileLayer(p.url, {
- attribution: p.attribution,
- maxZoom: p.max_zoom,
- }).addTo(map);
+ tileLayer = L.tileLayer(url, opts).addTo(map);
+ tileLayer.on('load tileload', scheduleDeSeam);
+ if (p.meter) {
+ refreshUsage();
+ // 'load' fires once all visible tiles are in — keep the pill current
+ tileLayer.on('load', refreshUsage);
+ }
}
$effect(() => {
@@ -81,11 +497,12 @@
api.get(`/api/cases/${id}/satellite`).then((r) => (captures = r));
});
- // the case sidebar mounts/unmounts outside this component — when it does,
- // the map container resizes, so redraw tiles for the newly exposed area
+ // the map container resizes when the sidebar toggles, and reappears from
+ // display:none when the tool tab is re-selected (tools stay mounted) — both
+ // need Leaflet to re-measure and redraw tiles for the exposed area
$effect(() => {
uiState.sidebarOpen; // track the global sidebar toggle
- if (!mapReady) return;
+ if (!mapReady || uiState.tool !== 'satellite') return;
tick().then(() => map?.invalidateSize());
});
@@ -101,14 +518,27 @@
}
});
+ let searching = $state(false);
async function goTo() {
const text = coordsText.trim();
- if (!text) return;
+ if (!text || searching) return;
+ searching = true;
try {
- const parsed = await api.post('/api/geo/parse', { text });
- map.setView([parsed.lat, parsed.lon], Math.max(map.getZoom(), 16));
+ // coordinates first (decimal or DMS); anything else is a place name
+ try {
+ const parsed = await api.post('/api/geo/parse', { text });
+ map.setView([parsed.lat, parsed.lon], Math.max(map.getZoom(), 16));
+ return;
+ } catch {
+ /* not coordinates — fall through to geocoding */
+ }
+ const place = await api.get(`/api/geo/geocode?q=${encodeURIComponent(text)}`);
+ map.setView([place.lat, place.lon], Math.max(map.getZoom(), 13));
+ if (place.display_name) toast(place.display_name, 'info', 5000);
} catch {
- toast('Could not parse coordinates — try "50.4501, 30.5234" or DMS', 'danger');
+ toast('No match — try coordinates ("50.4501, 30.5234"), DMS, or a place name', 'danger');
+ } finally {
+ searching = false;
}
}
@@ -117,10 +547,6 @@
map.setBearing(((deg % 360) + 360) % 360);
}
- function nudgeBearing(delta) {
- setBearing(bearing + delta);
- }
-
function resetNorth() {
setBearing(0);
}
@@ -132,8 +558,48 @@
moveMode && markerLatLng ? markerLatLng : { lat: center.lat, lon: center.lon }
);
- // crop dimensions in px — drawn as the capture-frame outline
- const frameSize = $derived(size.split('x').map(Number));
+ // --- capture sizing (backend validates 256–4096 px per side; see lib/captureSize.js) ---
+
+ // Standard output sizes for the centred Capture button, named by intent.
+ const PRESETS = [
+ { id: '1200x675', label: 'Tweet 16:9', w: 1200, h: 675 },
+ { id: '1080x1080', label: 'Square', w: 1080, h: 1080 },
+ { id: '1200x630', label: 'OG card', w: 1200, h: 630 },
+ { id: '1280x800', label: 'Wide', w: 1280, h: 800 },
+ { id: 'custom', label: 'Custom', w: 0, h: 0 },
+ ];
+ let preset = $state('1200x675');
+ let customW = $state(1200);
+ let customH = $state(675);
+ // preset dimensions in px — the centred Capture frame + its hover preview
+ const presetSize = $derived.by(() => {
+ if (preset === 'custom') return [clampSize(customW), clampSize(customH)];
+ const p = PRESETS.find((x) => x.id === preset);
+ return [p.w, p.h];
+ });
+
+ // Marquee ratio lock (width/height); null = free-form drag.
+ const RATIOS = [
+ { id: 'free', label: 'Free', r: null },
+ { id: '16:9', label: '16:9', r: 16 / 9 },
+ { id: '4:3', label: '4:3', r: 4 / 3 },
+ { id: '1:1', label: '1:1', r: 1 },
+ ];
+ let ratio = $state('free');
+ const ratioValue = $derived(RATIOS.find((x) => x.id === ratio)?.r ?? null);
+
+ // Output resolution: 1 = view zoom, 2 = one zoom deeper (2×), 'max' = provider max.
+ let resolution = $state(1);
+ const providerMaxZoom = $derived(providers.find((p) => p.id === providerId)?.max_zoom ?? 19);
+
+ // Single capture button, split-style: the main part re-runs whichever mode
+ // was used last (remembered here); the arrow opens mode + size/ratio/
+ // resolution settings.
+ let captureMode = $state('center'); // 'center' | 'select'
+ let sizeMenuOpen = $state(false); // the mode/size/ratio/resolution popover
+ let sizeMenuEl; // bound to the popover's wrapper — used to detect outside clicks
+ let selectArmed = $state(false); // marquee mode: drag a box on the map to capture
+ let selRect = $state(null); // live marquee { x0, y0, x1, y1 } in map-container px
function markerIcon(style) {
if (style === 'pin') {
@@ -203,29 +669,34 @@
}
});
- async function captureCrop() {
+ // The single capture path. `centerLL` frames the crop (a Leaflet LatLng);
+ // `baseW`/`baseH` are the crop size at the current view zoom, then scaled to
+ // the chosen output resolution. The recorded point is the moved pin (if any),
+ // else the crop centre.
+ async function doCapture(centerLL, baseW, baseH) {
if (capturing) return;
capturing = true;
- const [width, height] = size.split('x').map(Number);
- // marker offset (px from crop center) + its coordinates; when the pin has
- // been moved, its container offset already accounts for map rotation
- let marker_x = 0, marker_y = 0;
- let marker_lat = center.lat, marker_lon = center.lon;
+ const { zoom, width, height, mult } = scaledCapture(
+ baseW, baseH, resolution, center.zoom, providerMaxZoom
+ );
+ let marker_x = 0, marker_y = 0, marker_lat = centerLL.lat, marker_lon = centerLL.lng;
if (moveMode && marker) {
const ll = marker.getLatLng();
marker_lat = ll.lat;
marker_lon = ll.lng;
- const mapSize = map.getSize();
- const p = map.latLngToContainerPoint(ll);
- marker_x = Math.round(p.x - mapSize.x / 2);
- marker_y = Math.round(p.y - mapSize.y / 2);
+ // pin offset from the crop centre in container px (already accounts for
+ // rotation), scaled up to the output pixel size
+ const c0 = map.latLngToContainerPoint(centerLL);
+ const cp = map.latLngToContainerPoint(ll);
+ marker_x = Math.round((cp.x - c0.x) * mult);
+ marker_y = Math.round((cp.y - c0.y) * mult);
}
try {
const c = await ensureCase();
const result = await api.post(`/api/cases/${c.id}/satellite/capture`, {
- lat: center.lat,
- lon: center.lon,
- zoom: center.zoom,
+ lat: centerLL.lat,
+ lon: centerLL.lng,
+ zoom,
width,
height,
provider: providerId,
@@ -235,6 +706,8 @@
marker_y,
marker_lat,
marker_lon,
+ // second date on the capture: the imagery's acquisition date, if known
+ imagery_date: imageryDate?.date ?? null,
});
captures = [result, ...captures];
await reloadCase();
@@ -251,6 +724,89 @@
}
}
+ // Centred Capture button: the standard preset size, framed on the map centre.
+ function captureCentered() {
+ const [w, h] = presetSize;
+ doCapture(map.getCenter(), w, h);
+ }
+
+ // The main capture button runs whichever mode is currently selected —
+ // captureMode itself *is* the "last used mode" memory, so nothing else
+ // needs to track it.
+ function runCapture() {
+ if (captureBlocked) return; // view-only basemap
+ if (captureMode === 'select') toggleSelect();
+ else captureCentered();
+ }
+
+ // clicking outside the open size/ratio/resolution popover closes it
+ $effect(() => {
+ if (!sizeMenuOpen) return;
+ const onDocMousedown = (e) => {
+ if (sizeMenuEl && !sizeMenuEl.contains(e.target)) sizeMenuOpen = false;
+ };
+ document.addEventListener('mousedown', onDocMousedown, true);
+ return () => document.removeEventListener('mousedown', onDocMousedown, true);
+ });
+
+ // --- marquee: drag a rectangle on the map to capture exactly that area ---
+ function toggleSelect() {
+ selectArmed = !selectArmed;
+ if (selectArmed) {
+ sizeMenuOpen = false;
+ if (measureMode) setMeasureMode(null);
+ } else {
+ selRect = null;
+ }
+ }
+
+ function onSelectStart(e) {
+ if (!selectArmed || e.button !== 0 || !map) return;
+ // own the gesture so Leaflet doesn't pan while we draw the box
+ e.stopPropagation();
+ e.preventDefault();
+ const rect = mapEl.getBoundingClientRect();
+ const start = { x: e.clientX - rect.left, y: e.clientY - rect.top };
+ selRect = { x0: start.x, y0: start.y, x1: start.x, y1: start.y };
+ const move = (ev) => {
+ let x1 = ev.clientX - rect.left;
+ let y1 = ev.clientY - rect.top;
+ if (ratioValue) {
+ // lock the box to the chosen aspect ratio, sized from the larger delta
+ const dx = x1 - start.x;
+ const dy = y1 - start.y;
+ let w = Math.abs(dx);
+ let h = Math.abs(dy);
+ if (w / h > ratioValue) h = w / ratioValue;
+ else w = h * ratioValue;
+ x1 = start.x + (dx < 0 ? -w : w);
+ y1 = start.y + (dy < 0 ? -h : h);
+ }
+ selRect = { x0: start.x, y0: start.y, x1, y1 };
+ };
+ const up = () => {
+ window.removeEventListener('mousemove', move);
+ window.removeEventListener('mouseup', up);
+ finishSelect();
+ };
+ window.addEventListener('mousemove', move);
+ window.addEventListener('mouseup', up);
+ }
+
+ function finishSelect() {
+ const r = selRect;
+ selRect = null;
+ if (!r) return;
+ const w = Math.abs(r.x1 - r.x0);
+ const h = Math.abs(r.y1 - r.y0);
+ if (w < 12 || h < 12) return; // an accidental click / tiny drag: ignore
+ const centerLL = map.containerPointToLatLng(
+ L.point((r.x0 + r.x1) / 2, (r.y0 + r.y1) / 2)
+ );
+ selectArmed = false; // one box per arm — re-arm to draw another
+ doCapture(centerLL, Math.round(w), Math.round(h));
+ }
+
// save just the point (pin if moved, else center) as a navigable place — no image
let savingPlace = $state(false);
async function savePlace() {
@@ -273,6 +829,11 @@
}
}
+ // Deletions drop a file / an entity — always behind a confirm.
+ // { kind: 'capture', item } | { kind: 'place', item }
+ let deleteTarget = $state(null);
+ let deleteBusy = $state(false);
+
async function removeCapture(item) {
await api.del(
`/api/cases/${caseState.current.id}/satellite?path=${encodeURIComponent(item.path)}`
@@ -282,6 +843,20 @@
await reloadCase();
}
+ async function confirmDelete() {
+ if (!deleteTarget || deleteBusy) return;
+ deleteBusy = true;
+ try {
+ if (deleteTarget.kind === 'capture') await removeCapture(deleteTarget.item);
+ else await removePlace(deleteTarget.item);
+ deleteTarget = null;
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ deleteBusy = false;
+ }
+ }
+
// --- details modal (title + notes) ---
let notesItem = $state(null);
let notesText = $state('');
@@ -429,7 +1004,7 @@
}
</script>
-<div class="tool">
+<div class="tool" class:fullscreen bind:this={toolEl}>
<div class="tool-header">
<h2>Satellite</h2>
<span class="sub">pan to a point, capture a sourced imagery crop</span>
@@ -443,29 +1018,129 @@
>
<input
class="input"
- placeholder={'50.4501, 30.5234 · 48°51\'29"N 2°17\'40"E'}
+ placeholder={'50.4501, 30.5234 · 48°51\'29"N 2°17\'40"E · a place name'}
bind:value={coordsText}
+ title="Coordinates (decimal or DMS) or a place name (geocoded via Nominatim)"
/>
- <button type="submit" class="btn" disabled={!coordsText.trim()}>
- <Icon name="search" size={15} /> Go
+ <button type="submit" class="btn" disabled={!coordsText.trim() || searching}>
+ <Icon name="search" size={15} /> {searching ? '…' : 'Go'}
</button>
</form>
</div>
<div class="body">
- <div class="map-wrap">
+ <div class="map-wrap" class:measuring={measureMode} class:selecting={selectArmed}>
<div class="map" bind:this={mapEl}></div>
- <!-- capture-frame outline: what the crop will cover — only while a capture
- is the intent (hovering the capture group, or mid-capture) -->
- {#if captureHover || capturing}
+ <!-- top-left control cluster: fullscreen, OSM labels overlay, measure tools -->
+ <div class="map-tools">
+ <div class="tool-cluster card">
+ <button
+ class="mtbtn"
+ class:on={fullscreen}
+ onclick={toggleFullscreen}
+ title={fullscreen ? 'Exit fullscreen (Esc)' : 'Fullscreen map'}
+ aria-label="Toggle fullscreen"
+ >
+ <Icon name={fullscreen ? 'minimize' : 'maximize'} size={16} />
+ </button>
+ <button
+ class="mtbtn"
+ class:on={osmOverlay}
+ onclick={() => (osmOverlay = !osmOverlay)}
+ disabled={!baseIsImagery}
+ title={baseIsImagery
+ ? 'Overlay OSM labels (roads, place names) on the imagery'
+ : 'Labels overlay is only useful over satellite imagery'}
+ aria-label="Toggle OSM labels overlay"
+ >
+ <Icon name="layers" size={16} />
+ </button>
+ <button
+ class="mtbtn"
+ class:on={toolsOpen || measureMode}
+ onclick={toggleTools}
+ title="Measure tools"
+ aria-label="Measure tools"
+ >
+ <Icon name="ruler" size={16} />
+ </button>
+ <button
+ class="mtbtn"
+ class:on={uiState.refViewers.length}
+ onclick={openRefPicker}
+ title="Add a reference image or video over the map (scratch only — never captured or saved)"
+ aria-label="Add reference"
+ >
+ <Icon name="image" size={16} />
+ </button>
+ </div>
+
+ {#if toolsOpen}
+ <div class="measure-panel card">
+ <div class="measure-btns">
+ <button
+ class="btn btn-sm"
+ class:on={measureMode === 'distance'}
+ onclick={() => setMeasureMode('distance')}
+ >
+ <Icon name="ruler" size={14} /> Distance
+ </button>
+ <button
+ class="btn btn-sm"
+ class:on={measureMode === 'area'}
+ onclick={() => setMeasureMode('area')}
+ >
+ <Icon name="polygon" size={14} /> Area
+ </button>
+ <button
+ class="btn btn-sm"
+ class:on={measureMode === 'angle'}
+ onclick={() => setMeasureMode('angle')}
+ >
+ <Icon name="angle" size={14} /> Angle
+ </button>
+ </div>
+ {#if measureMode}
+ <div class="measure-readout">
+ {#if measureReadout}
+ <span class="measure-value mono">{measureReadout}</span>
+ {:else}
+ <span class="measure-hint">{MEASURE_HINT[measureMode]}</span>
+ {/if}
+ <button class="btn btn-ghost btn-sm" onclick={clearMeasure} title="Clear points">
+ <Icon name="reset" size={13} />
+ </button>
+ </div>
+ {/if}
+ </div>
+ {/if}
+ </div>
+
+ <!-- capture-frame outline: what the centred Capture will cover — only when
+ a centred capture is the intent (hovering the capture button, or
+ mid-capture) and not while drawing a marquee -->
+ {#if captureMode === 'center' && (captureHover || capturing) && !selectArmed && !selRect}
<div
class="frame-overlay"
- style="width:{frameSize[0]}px;height:{frameSize[1]}px"
+ style="width:{presetSize[0]}px;height:{presetSize[1]}px"
aria-hidden="true"
></div>
{/if}
+ <!-- live marquee: the rectangle being dragged to define a custom crop -->
+ {#if selRect}
+ <div
+ class="sel-rect"
+ style="left:{Math.min(selRect.x0, selRect.x1)}px;top:{Math.min(selRect.y0, selRect.y1)}px;width:{Math.abs(selRect.x1 - selRect.x0)}px;height:{Math.abs(selRect.y1 - selRect.y0)}px"
+ aria-hidden="true"
+ >
+ <span class="sel-dim mono">
+ {Math.round(Math.abs(selRect.x1 - selRect.x0))} × {Math.round(Math.abs(selRect.y1 - selRect.y0))}
+ </span>
+ </div>
+ {/if}
+
<!-- fixed center marker; a draggable Leaflet marker takes over in move mode -->
{#if markerStyle !== 'none' && !moveMode}
<div class="marker-overlay marker-{markerStyle}" aria-hidden="true">
@@ -493,6 +1168,17 @@
</div>
{/if}
+ <!-- middle-drag rotation pivot: sober target at the grabbed point, pinned
+ on screen while the map turns around it -->
+ {#if rotating}
+ <div class="rotate-pivot" style:left={`${rotatePivot.x}px`} style:top={`${rotatePivot.y}px`} aria-hidden="true">
+ <svg width="40" height="40" viewBox="0 0 40 40">
+ <circle class="ring" cx="20" cy="20" r="15" />
+ <circle class="dot" cx="20" cy="20" r="1.5" />
+ </svg>
+ </div>
+ {/if}
+
<div class="hud card">
<button class="hud-coords mono" onclick={copyCoords} title="Copy coordinates">
<Icon name="crosshair" size={13} />
@@ -503,39 +1189,56 @@
</button>
</div>
- <div class="rotate-ctl card">
+ <!-- imagery acquisition date: a compact, unobtrusive pill in the corner so
+ it doesn't crowd the coordinates readout (item 2) -->
+ {#if imageryDate?.supported}
+ <span
+ class="date-pill mono"
+ title={imageryDate.source
+ ? `Imagery acquired around this date (source: ${imageryDate.source})`
+ : 'Approximate acquisition date of the imagery here'}
+ >
+ <Icon name="clock" size={11} />
+ {imageryDate.date ?? '—'}
+ </span>
+ {/if}
+
+ <!-- lightweight compass: click the rose to reset north; middle-drag the map
+ to rotate; click the number to type an exact bearing (item 3) -->
+ <div class="rotate-ctl">
<button
class="compass"
onclick={resetNorth}
- title={bearing ? 'Reset to north' : 'North up'}
+ title={bearing ? 'Reset to north' : 'North up · middle-drag the map to rotate'}
aria-label="Reset to north"
>
- <svg width="34" height="34" viewBox="0 0 34 34" style="transform: rotate({-bearing}deg)">
- <circle cx="17" cy="17" r="15" fill="none" stroke="currentColor" stroke-width="1" opacity="0.4" />
+ <svg width="30" height="30" viewBox="0 0 34 34" style="transform: rotate({-bearing}deg)">
<polygon points="17,4 13,18 17,15 21,18" fill="#e5484d" />
<polygon points="17,30 13,16 17,19 21,16" fill="#8a93a5" />
</svg>
<span class="n">N</span>
</button>
- <div class="rotate-actions">
- <button class="rbtn" onclick={() => nudgeBearing(-15)} title="Rotate left 15°" aria-label="Rotate left">
- <Icon name="chevronLeft" size={15} />
- </button>
- <span class="deg mono">{bearing}°</span>
- <button class="rbtn" onclick={() => nudgeBearing(15)} title="Rotate right 15°" aria-label="Rotate right">
- <Icon name="chevronRight" size={15} />
+ {#if editingBearing}
+ <!-- svelte-ignore a11y_autofocus -->
+ <input
+ class="input deg-input mono"
+ type="number"
+ min="0"
+ max="359"
+ bind:value={bearingInput}
+ autofocus
+ onblur={commitBearing}
+ onkeydown={(e) => {
+ if (e.key === 'Enter') commitBearing();
+ else if (e.key === 'Escape') editingBearing = false;
+ }}
+ aria-label="Set bearing in degrees"
+ />
+ {:else}
+ <button class="deg mono" onclick={startEditBearing} title="Click to type an exact angle">
+ {bearing}°
</button>
- </div>
- <input
- class="rotate-slider"
- type="range"
- min="0"
- max="359"
- value={bearing}
- oninput={(e) => setBearing(+e.target.value)}
- title="Drag to rotate the view"
- aria-label="Map rotation"
- />
+ {/if}
</div>
<div class="capture-bar card">
@@ -546,6 +1249,12 @@
</option>
{/each}
</select>
+ {#if usagePill}
+ <span
+ class="usage-pill mono"
+ title="Tiles requested from this billed provider this month — local counter, see Settings"
+ >{usagePill}</span>
+ {/if}
<select class="select" bind:value={markerStyle} title="Marker style">
<option value="crosshair">✛ crosshair</option>
<option value="pin">📍 pin</option>
@@ -579,31 +1288,137 @@
<Icon name="note" size={14} />
</button>
</div>
- <!-- crop size only concerns a capture, so it lives with the Capture button;
- hovering this group previews the crop frame on the map -->
- <div
- class="capture-group"
- onmouseenter={() => (captureHover = true)}
- onmouseleave={() => (captureHover = false)}
- onfocusin={() => (captureHover = true)}
- onfocusout={() => (captureHover = false)}
- role="group"
- >
- <select class="select" bind:value={size} title="Crop size">
- <option value="800x600">800 × 600</option>
- <option value="1000x700">1000 × 700</option>
- <option value="1280x800">1280 × 800</option>
- <option value="1000x1000">1000 × 1000</option>
- </select>
- <button class="btn btn-primary" onclick={captureCrop} disabled={capturing}>
+ <!-- capture controls: one split button. The main part re-runs whichever
+ mode was used last — a centred capture at the chosen size, or
+ arming a marquee to drag a custom area — and the arrow opens the
+ mode + size/ratio/resolution settings. Hovering/focusing the main
+ button previews the centred crop frame, only while that's the
+ active mode. -->
+ <div class="capture-split" role="group">
+ <button
+ class="btn btn-primary capture-main"
+ class:on={captureMode === 'select' && selectArmed}
+ onmouseenter={() => (captureHover = captureMode === 'center')}
+ onmouseleave={() => (captureHover = false)}
+ onfocusin={() => (captureHover = captureMode === 'center')}
+ onfocusout={() => (captureHover = false)}
+ onclick={runCapture}
+ disabled={capturing || captureBlocked}
+ title={captureBlocked
+ ? 'View-only basemap — this provider cannot be captured'
+ : captureMode === 'select'
+ ? 'Draw a rectangle on the map to capture exactly that area'
+ : 'Capture the centred preset size'}
+ >
{#if capturing}
<span class="spinner"></span> Capturing…
+ {:else if captureMode === 'select'}
+ <Icon name="crop" size={14} /> {selectArmed ? 'Draw box…' : 'Select area'}
{:else}
<Icon name="satellite" size={15} /> Capture
{/if}
</button>
+
+ <div class="size-menu-wrap" bind:this={sizeMenuEl}>
+ <button
+ class="btn btn-icon capture-arrow"
+ class:on={sizeMenuOpen}
+ onclick={() => (sizeMenuOpen = !sizeMenuOpen)}
+ title="Capture mode, size, ratio & resolution"
+ aria-label="Capture options"
+ >
+ <Icon name="chevronDown" size={13} />
+ </button>
+ {#if sizeMenuOpen}
+ <div class="size-menu card">
+ <div class="menu-row">
+ <span class="menu-label">Mode</span>
+ <div class="chips">
+ <button class="chip" class:on={captureMode === 'center'} onclick={() => (captureMode = 'center')}>
+ Capture
+ </button>
+ <button class="chip" class:on={captureMode === 'select'} onclick={() => (captureMode = 'select')}>
+ Select area
+ </button>
+ </div>
+ </div>
+ <div class="menu-hint">
+ {captureMode === 'center'
+ ? 'Captures the centred size below.'
+ : 'Drag a box on the map to capture exactly it.'}
+ </div>
+
+ {#if captureMode === 'select'}
+ <div class="menu-row">
+ <span class="menu-label">Ratio</span>
+ <div class="chips">
+ {#each RATIOS as r (r.id)}
+ <button class="chip" class:on={ratio === r.id} onclick={() => (ratio = r.id)}>
+ {r.label}
+ </button>
+ {/each}
+ </div>
+ </div>
+ <div class="menu-hint">Locks the dragged box's shape.</div>
+ {:else}
+ <div class="menu-row">
+ <span class="menu-label">Size</span>
+ <div class="chips">
+ {#each PRESETS as p (p.id)}
+ <button class="chip" class:on={preset === p.id} onclick={() => (preset = p.id)}>
+ {p.label}
+ </button>
+ {/each}
+ </div>
+ </div>
+ {#if preset === 'custom'}
+ <div class="custom-size" title="Custom crop size ({SIZE_MIN}–{SIZE_MAX} px)">
+ <input
+ class="input size-input"
+ type="number"
+ min={SIZE_MIN}
+ max={SIZE_MAX}
+ bind:value={customW}
+ onblur={() => (customW = clampSize(customW))}
+ aria-label="Crop width"
+ />
+ <span>×</span>
+ <input
+ class="input size-input"
+ type="number"
+ min={SIZE_MIN}
+ max={SIZE_MAX}
+ bind:value={customH}
+ onblur={() => (customH = clampSize(customH))}
+ aria-label="Crop height"
+ />
+ </div>
+ {/if}
+ {/if}
+
+ <div class="menu-row">
+ <span class="menu-label">Resolution</span>
+ <div class="chips">
+ <button class="chip" class:on={resolution === 1} onclick={() => (resolution = 1)}>1×</button>
+ <button class="chip" class:on={resolution === 2} onclick={() => (resolution = 2)}>2×</button>
+ <button class="chip" class:on={resolution === 'max'} onclick={() => (resolution = 'max')}>Max</button>
+ </div>
+ </div>
+ <div class="menu-hint">Captures a deeper zoom for a sharper file.</div>
+ </div>
+ {/if}
+ </div>
</div>
</div>
+ <!-- floating reference-image windows (scratch aids over the map) -->
+ {#each uiState.refViewers as v (v.id)}
+ <RefViewer
+ viewer={v}
+ caseId={caseState.current?.id}
+ onfocus={focusRef}
+ onclose={closeRef}
+ />
+ {/each}
</div>
<aside class="captures" class:collapsed={capturesCollapsed}>
@@ -621,6 +1436,27 @@
<!-- collapsed: header acts as the toggle back to the list -->
{:else}
<div class="panel-scroll">
+ <!-- External maps: quick jumps to maps we can't embed in-tool, at the
+ current target coordinates (item 6) -->
+ <button type="button" class="sub-head" onclick={() => (linksOpen = !linksOpen)}>
+ <Icon name={linksOpen ? 'chevronDown' : 'chevronRight'} size={12} />
+ <Icon name="external" size={13} />
+ <span>Open in…</span>
+ <span class="count">{externalLinks.length}</span>
+ </button>
+ {#if linksOpen}
+ <div class="links-grid">
+ {#each externalLinks as l (l.id)}
+ <a class="ext-link" href={l.url} target="_blank" rel="noreferrer" title={l.url}>
+ <Icon name="globe" size={13} />
+ <span>{l.label}</span>
+ <Icon name="external" size={12} />
+ </a>
+ {/each}
+ </div>
+ <div class="links-note mono">{fmt(displayCoords.lat)}, {fmt(displayCoords.lon)}</div>
+ {/if}
+
<!-- Places: navigable points (no image) -->
<button
type="button"
@@ -664,7 +1500,7 @@
<button
class="btn btn-ghost btn-sm"
title="Delete place"
- onclick={() => removePlace(p)}
+ onclick={() => (deleteTarget = { kind: 'place', item: p })}
>
<Icon name="trash" size={14} />
</button>
@@ -697,7 +1533,7 @@
</div>
{:else}
<div class="cap-list">
- {#each captures as item (item.path)}
+ {#each (caseState.current ? captures : []) as item (item.path)}
<div class="cap card fade-up">
<a
class="cap-goto"
@@ -714,10 +1550,21 @@
<div class="cap-meta">
<span class="title">{item.title ?? coordsLabel(item)}</span>
<span class="mono coords">{coordsLabel(item)}</span>
- <span class="prov">z{item.zoom}{item.bearing ? ` · ${Math.round(item.bearing)}°` : ''} · {item.provider_label} · {item.fetched_at?.slice(0, 10)}</span>
+ <span class="prov">z{item.zoom}{item.bearing ? ` · ${Math.round(item.bearing)}°` : ''} · {item.provider_label}</span>
+ <span class="prov dates" title="Capture date · imagery acquisition date">
+ <Icon name="crosshair" size={10} /> {item.fetched_at?.slice(0, 10)}
+ {#if item.imagery_date}<span class="img-date"><Icon name="satellite" size={10} /> {item.imagery_date}</span>{/if}
+ </span>
</div>
</a>
<div class="cap-actions">
+ <button
+ class="btn btn-ghost btn-sm"
+ title="Go to these coordinates on the map"
+ onclick={() => flyToCapture(item)}
+ >
+ <Icon name="crosshair" size={14} />
+ </button>
<button
class="btn btn-ghost btn-sm"
title="Edit title & note"
@@ -744,7 +1591,7 @@
<button
class="btn btn-ghost btn-sm"
title="Delete"
- onclick={() => removeCapture(item)}
+ onclick={() => (deleteTarget = { kind: 'capture', item })}
>
<Icon name="trash" size={14} />
</button>
@@ -763,6 +1610,24 @@
</div>
</div>
+<!-- delete confirm: a capture drops its image file, a place its entity -->
+{#if deleteTarget}
+ <ConfirmDialog
+ title={deleteTarget.kind === 'capture' ? 'Delete this capture?' : 'Delete this place?'}
+ message={deleteTarget.kind === 'capture'
+ ? `“${deleteTarget.item.title ?? coordsLabel(deleteTarget.item)}” will be removed from the case.`
+ : `“${deleteTarget.item.label}” will be removed from the case.`}
+ detail={deleteTarget.kind === 'capture'
+ ? 'This permanently deletes the image file on disk — it cannot be undone.'
+ : 'This permanently removes the saved point — it cannot be undone.'}
+ confirmLabel="Delete"
+ tone="danger"
+ busy={deleteBusy}
+ onconfirm={confirmDelete}
+ oncancel={() => (deleteTarget = null)}
+ />
+{/if}
+
<!-- satellite notes modal -->
{#if notesItem}
<Modal title="Capture details" onclose={() => (notesItem = null)} width="420px">
@@ -787,9 +1652,13 @@
<span>{notesItem.zoom}</span>
</div>
<div class="sat-info-row">
- <span class="sat-info-label">Date</span>
+ <span class="sat-info-label">Captured</span>
<span class="mono">{notesItem.fetched_at?.slice(0, 10)}</span>
</div>
+ <div class="sat-info-row">
+ <span class="sat-info-label">Imagery date</span>
+ <span class="mono">{notesItem.imagery_date ?? '—'}</span>
+ </div>
</div>
<hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />
<label style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Notes</label>
@@ -849,6 +1718,42 @@
</Modal>
{/if}
+<!-- reference-image picker: choose a case image to float over the map. Pure
+ scratch aid — the window is never captured or saved. -->
+{#if refPicker}
+ <Modal title="Add reference" onclose={() => (refPicker = false)} width="560px">
+ <p class="ref-hint">
+ Float one of the case's images or videos over the map to eyeball against the imagery.
+ It's a scratch aid — never captured or saved.
+ </p>
+ {#if refLoading}
+ <div class="ref-empty">Loading…</div>
+ {:else if !refMedia.length}
+ <div class="ref-empty">
+ No images or videos in this case yet — import one in the Media Library first.
+ </div>
+ {:else}
+ <div class="ref-grid">
+ {#each (caseState.current ? refMedia : []) as m (m.path)}
+ <button class="ref-pick" onclick={() => addRef(m)} title={m.title ?? m.filename}>
+ <div class="ref-thumb">
+ {#if m.thumbnail}
+ <img src={`/files/${caseState.current.id}/${m.thumbnail}`} alt={m.filename} loading="lazy" />
+ {:else}
+ <Icon name={m.kind === 'video' ? 'video' : 'image'} size={26} />
+ {/if}
+ {#if m.kind === 'video'}
+ <span class="ref-kind"><Icon name="video" size={11} /></span>
+ {/if}
+ </div>
+ <span class="ref-name">{m.title ?? m.filename}</span>
+ </button>
+ {/each}
+ </div>
+ {/if}
+ </Modal>
+{/if}
+
<style>
.spacer {
flex: 1;
@@ -902,6 +1807,29 @@
:global(.sat-marker) {
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.5));
}
+ /* Sober rotation pivot (Google-Earth style): faint translucent ring + dot. */
+ .rotate-pivot {
+ position: absolute;
+ transform: translate(-50%, -50%);
+ pointer-events: none;
+ z-index: 650;
+ color: #fff;
+ }
+ .rotate-pivot svg {
+ display: block;
+ overflow: visible;
+ filter: drop-shadow(0 0 1.5px rgba(0, 0, 0, 0.55));
+ }
+ .rotate-pivot .ring {
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1;
+ opacity: 0.5;
+ }
+ .rotate-pivot .dot {
+ fill: currentColor;
+ opacity: 0.8;
+ }
.pin-tag {
font-size: 9px;
font-weight: 700;
@@ -918,6 +1846,7 @@
left: 50%;
transform: translateX(-50%);
z-index: 600;
+ display: flex;
background: rgba(16, 22, 35, 0.88);
backdrop-filter: blur(6px);
}
@@ -936,79 +1865,211 @@
color: var(--text-3);
font-size: var(--fs-xs);
}
- .rotate-ctl {
+ /* imagery date: small, low-contrast pill tucked into the bottom-left corner */
+ .date-pill {
position: absolute;
- top: 12px;
- right: 12px;
+ bottom: 12px;
+ left: 12px;
z-index: 600;
display: flex;
- flex-direction: column;
align-items: center;
+ gap: 5px;
+ padding: 3px 8px;
+ border-radius: 999px;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ background: rgba(16, 22, 35, 0.7);
+ backdrop-filter: blur(6px);
+ pointer-events: none;
+ }
+
+ /* fullscreen: the whole tool covers the viewport, above the app chrome */
+ .tool.fullscreen {
+ position: fixed;
+ inset: 0;
+ z-index: 2000;
+ background: var(--bg-0);
+ }
+
+ /* top-left control cluster (fullscreen · OSM labels · measure) */
+ .map-tools {
+ position: absolute;
+ top: 12px;
+ left: 12px;
+ /* above Leaflet's own control corners (z-index 1000) so the measure panel
+ is never hidden behind the zoom +/- buttons (item 7) */
+ z-index: 1100;
+ display: flex;
+ flex-direction: column;
gap: 8px;
- padding: 10px;
+ align-items: flex-start;
+ }
+ .tool-cluster {
+ display: flex;
+ gap: 2px;
+ padding: 4px;
background: rgba(16, 22, 35, 0.88);
backdrop-filter: blur(6px);
- box-shadow: var(--shadow-2);
}
- .compass {
- position: relative;
+ .mtbtn {
display: grid;
place-items: center;
- width: 34px;
- height: 34px;
+ width: 30px;
+ height: 30px;
+ border-radius: var(--radius-1);
color: var(--text-2);
cursor: pointer;
}
- .compass:hover {
- color: var(--accent);
+ .mtbtn:hover {
+ color: var(--text-1);
+ background: var(--bg-3);
}
- .compass svg {
- transition: transform 0.1s linear;
+ .mtbtn.on {
+ color: var(--accent-text);
+ background: var(--accent);
}
- .compass .n {
+ .mtbtn:disabled {
+ opacity: 0.35;
+ cursor: not-allowed;
+ }
+ .mtbtn:disabled:hover {
+ color: var(--text-2);
+ background: none;
+ }
+ /* float to the right of the tool cluster instead of below it, where the
+ Leaflet zoom control sits — otherwise the two overlap (item 7) */
+ .measure-panel {
position: absolute;
- top: -3px;
- left: 50%;
- transform: translateX(-50%);
- font-size: 9px;
+ top: 0;
+ left: calc(100% + 8px);
+ width: max-content;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 10px;
+ background: rgba(16, 22, 35, 0.92);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-2);
+ }
+ .measure-btns {
+ display: flex;
+ gap: 4px;
+ }
+ .measure-btns .btn.on {
+ background: var(--accent);
+ color: var(--accent-text);
+ border-color: var(--accent);
+ }
+ .measure-readout {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding-top: 6px;
+ border-top: 1px solid var(--border);
+ }
+ .measure-value {
+ font-size: var(--fs-md);
font-weight: 700;
+ color: var(--accent);
+ }
+ .measure-hint {
+ font-size: var(--fs-xs);
color: var(--text-3);
+ }
+ .map-wrap.measuring :global(.leaflet-container),
+ .map-wrap.selecting :global(.leaflet-container) {
+ cursor: crosshair;
+ }
+
+ /* live capture marquee: a dashed box with a dark scrim over the rest of the
+ map, mirroring the centred frame-overlay look */
+ .sel-rect {
+ position: absolute;
+ border: 1.5px dashed var(--accent);
+ box-shadow: 0 0 0 100vmax rgba(8, 11, 18, 0.28);
pointer-events: none;
+ z-index: 460;
}
- .rotate-actions {
+ .sel-dim {
+ position: absolute;
+ top: -22px;
+ left: 0;
+ padding: 2px 6px;
+ border-radius: var(--radius-1);
+ font-size: var(--fs-xs);
+ color: var(--text-1);
+ background: var(--accent);
+ color: var(--accent-text);
+ white-space: nowrap;
+ }
+
+ /* lightweight compass — no heavy card, just the rose + an editable readout */
+ .rotate-ctl {
+ position: absolute;
+ top: 12px;
+ right: 12px;
+ z-index: 600;
display: flex;
+ flex-direction: column;
align-items: center;
gap: 4px;
}
- .rbtn {
+ .compass {
+ position: relative;
display: grid;
place-items: center;
- width: 24px;
- height: 24px;
- border: 1px solid var(--border);
- border-radius: var(--radius-1);
- background: var(--bg-2);
+ width: 38px;
+ height: 38px;
color: var(--text-2);
cursor: pointer;
+ /* round translucent backing disc so the rose reads clearly over any
+ imagery — same fill as the degree readout below (item 3) */
+ border-radius: 50%;
+ background: rgba(16, 22, 35, 0.88);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-1);
}
- .rbtn:hover {
+ .compass:hover {
color: var(--accent);
- border-color: var(--accent);
+ }
+ .compass svg {
+ transition: transform 0.1s linear;
+ }
+ .compass .n {
+ position: absolute;
+ top: 1px;
+ left: 50%;
+ transform: translateX(-50%);
+ font-size: 9px;
+ font-weight: 700;
+ color: var(--text-1);
+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);
+ pointer-events: none;
}
.deg {
- min-width: 36px;
+ min-width: 40px;
text-align: center;
+ padding: 2px 6px;
+ border-radius: var(--radius-1);
font-size: var(--fs-xs);
color: var(--text-1);
+ background: rgba(16, 22, 35, 0.88);
+ backdrop-filter: blur(6px);
+ cursor: text;
}
- .rotate-slider {
- width: 108px;
- accent-color: var(--accent);
- cursor: pointer;
+ .deg:hover {
+ color: var(--accent);
+ }
+ .deg-input {
+ width: 52px;
+ padding: 2px 4px;
+ text-align: center;
+ font-size: var(--fs-xs);
}
.capture-bar {
position: absolute;
- bottom: 16px;
+ bottom: 34px;
left: 50%;
transform: translateX(-50%);
z-index: 600;
@@ -1023,16 +2084,151 @@
.capture-bar .select {
width: auto;
}
+ /* billed-provider tile counter (KEYED_PROVIDERS.md §6) — full readout in Settings */
+ .usage-pill {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ background: var(--bg-2);
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ padding: 3px 9px;
+ white-space: nowrap;
+ }
.bar-sep {
width: 1px;
align-self: stretch;
background: var(--border);
margin: 0 2px;
}
- .capture-group {
+ /* the capture split-button: main action + arrow fused into one pill,
+ mirroring .place-save's main/edit split */
+ .capture-split {
+ display: flex;
+ align-items: stretch;
+ }
+ .capture-main {
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+ }
+ .capture-arrow {
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+ background: var(--accent);
+ border-color: transparent;
+ border-left: 1px solid rgba(0, 0, 0, 0.2);
+ color: var(--accent-text);
+ }
+ .capture-arrow:hover:not(:disabled) {
+ background: var(--accent-hover);
+ }
+ .size-menu-wrap .capture-arrow.on {
+ background: var(--accent-hover);
+ }
+ .capture-main.on {
+ box-shadow: inset 0 0 0 2px rgba(255, 255, 255, 0.5);
+ }
+ .custom-size {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .size-input {
+ width: 64px;
+ padding: 5px 6px;
+ font-size: var(--fs-xs);
+ text-align: center;
+ }
+
+ /* square icon button (the size/ratio/resolution popover trigger) */
+ .btn-icon {
+ padding: 6px 8px;
+ }
+ .btn-icon.on {
+ background: var(--accent);
+ color: var(--accent-text);
+ border-color: var(--accent);
+ }
+ .size-menu-wrap {
+ position: relative;
+ display: flex;
+ }
+ .size-menu {
+ position: absolute;
+ bottom: calc(100% + 8px);
+ right: 0;
+ width: max-content;
+ max-width: 280px;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 12px;
+ background: rgba(16, 22, 35, 0.96);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-2);
+ z-index: 700;
+ }
+ .menu-row {
display: flex;
align-items: center;
gap: 10px;
+ justify-content: space-between;
+ }
+ .menu-label {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ font-weight: 600;
+ }
+ .chips {
+ display: flex;
+ gap: 4px;
+ flex-wrap: wrap;
+ justify-content: flex-end;
+ }
+ .chip {
+ padding: 4px 9px;
+ border-radius: 999px;
+ border: 1px solid var(--border);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ white-space: nowrap;
+ cursor: pointer;
+ transition: border-color 0.12s, color 0.12s, background 0.12s;
+ }
+ .chip:hover {
+ border-color: var(--border-strong);
+ color: var(--text-1);
+ }
+ .chip.on {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ color: var(--accent);
+ }
+ .menu-hint {
+ font-size: 10px;
+ color: var(--text-3);
+ margin: -1px 0 5px;
+ }
+ .menu-row + .custom-size {
+ justify-content: flex-end;
+ padding: 2px 0;
+ }
+ .prov.dates {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 1px;
+ }
+ .prov.dates :global(svg) {
+ vertical-align: -1px;
+ opacity: 0.8;
+ }
+ .img-date {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
}
.place-save {
display: flex;
@@ -1150,6 +2346,44 @@
margin-left: auto;
text-transform: none;
}
+ .links-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 4px;
+ padding: 4px 2px 6px;
+ }
+ .ext-link {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-1);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ text-decoration: none;
+ overflow: hidden;
+ }
+ .ext-link span {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .ext-link:hover {
+ color: var(--accent);
+ border-color: var(--accent);
+ }
+ .ext-link :global(svg:last-child) {
+ color: var(--text-3);
+ flex-shrink: 0;
+ }
+ .links-note {
+ padding: 0 4px 6px;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
.place-notes {
padding: 0 10px 8px 30px;
font-size: var(--fs-xs);
@@ -1288,7 +2522,11 @@
:global(.leaflet-container) {
font-family: var(--font-sans);
background: var(--bg-2);
+ image-rendering: smooth;
}
+ /* NB: no backface-visibility / transform promotion on tiles — that forces
+ each tile onto its own GPU layer and reintroduces the white seams the
+ deSeamTiles() left/top positioning removes (see script). */
:global(.leaflet-control-attribution) {
background: rgba(16, 22, 35, 0.85) !important;
color: var(--text-3) !important;
@@ -1305,4 +2543,110 @@
:global(.leaflet-bar a:hover) {
background: var(--bg-3) !important;
}
+ /* zoom +/- (topleft) sits directly under the fullscreen/labels/measure
+ cluster instead of Leaflet's default corner margin, which used to land
+ it right on top of that cluster */
+ :global(.leaflet-top.leaflet-left) {
+ top: 58px !important;
+ left: 12px !important;
+ }
+ :global(.leaflet-top.leaflet-left .leaflet-control) {
+ margin: 0 0 8px !important;
+ }
+ :global(.leaflet-pane) {
+ will-change: transform;
+ }
+ /* Slim ruler-style scale: no boxed panel, just a light bracket + label
+ floating directly on the map so it stays readable over any imagery. */
+ :global(.leaflet-control-scale) {
+ background: transparent !important;
+ border: none !important;
+ box-shadow: none !important;
+ padding: 0 !important;
+ margin: 0 10px 10px 0 !important;
+ }
+ :global(.leaflet-control-scale-line) {
+ background: transparent !important;
+ border: none !important;
+ border-left: 1.5px solid rgba(255, 255, 255, 0.92) !important;
+ border-right: 1.5px solid rgba(255, 255, 255, 0.92) !important;
+ border-bottom: 1.5px solid rgba(255, 255, 255, 0.92) !important;
+ color: #fff !important;
+ font-size: 10px !important;
+ font-weight: 600 !important;
+ line-height: 1.3 !important;
+ padding: 0 4px 1px !important;
+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.85), 0 0 4px rgba(0, 0, 0, 0.5) !important;
+ }
+
+ /* reference-image picker */
+ .ref-hint {
+ font-size: var(--fs-sm);
+ color: var(--text-2);
+ margin: 0 0 12px;
+ }
+ .ref-empty {
+ padding: 24px 4px;
+ text-align: center;
+ font-size: var(--fs-sm);
+ color: var(--text-3);
+ }
+ .ref-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
+ gap: 10px;
+ max-height: 52vh;
+ overflow-y: auto;
+ }
+ .ref-pick {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ padding: 0;
+ background: none;
+ border: none;
+ color: var(--text-2);
+ cursor: pointer;
+ text-align: left;
+ }
+ .ref-thumb {
+ position: relative;
+ aspect-ratio: 4 / 3;
+ border-radius: var(--radius-1);
+ overflow: hidden;
+ background: var(--bg-2);
+ display: grid;
+ place-items: center;
+ color: var(--text-3);
+ border: 1px solid var(--border);
+ }
+ .ref-kind {
+ position: absolute;
+ bottom: 4px;
+ right: 4px;
+ display: grid;
+ place-items: center;
+ padding: 2px;
+ border-radius: var(--radius-1);
+ color: #fff;
+ background: rgba(11, 15, 23, 0.75);
+ backdrop-filter: blur(4px);
+ }
+ .ref-pick:hover .ref-thumb {
+ border-color: var(--accent);
+ }
+ .ref-thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .ref-name {
+ font-size: var(--fs-xs);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .ref-pick:hover .ref-name {
+ color: var(--accent);
+ }
</style>
diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelte
new file mode 100644
index 0000000..8cac517
--- /dev/null
+++ b/frontend/src/tools/Settings.svelte
@@ -0,0 +1,354 @@
+<script>
+ import { onMount } from 'svelte';
+ import { api } from '../lib/api.js';
+ import { toast } from '../lib/state.svelte.js';
+ import { monthCount, tilesOfFree, freeTierShare } from '../lib/usage.js';
+ import Icon from '../components/Icon.svelte';
+
+ // The keyed imagery providers the app knows how to light up (KEYED_PROVIDERS.md).
+ // Keys are app-wide, stored locally in settings.json, never written into a
+ // case folder or export bundle — they're the user's own billing identity.
+ const KEYED = [
+ {
+ id: 'mapbox',
+ label: 'Mapbox',
+ field: 'Mapbox public access token',
+ placeholder: 'pk.…',
+ help: 'https://account.mapbox.com/access-tokens/',
+ unlocks: 'Mapbox Satellite basemap',
+ overage:
+ 'Beyond the free tier, Mapbox bills extra tiles automatically (pay-as-you-go, per 1,000). Set a spending alert in your Mapbox account.',
+ },
+ {
+ id: 'google',
+ label: 'Google',
+ field: 'Google Maps Platform API key',
+ placeholder: 'AIza…',
+ help: 'https://developers.google.com/maps/documentation/tile/get-api-key',
+ unlocks: 'Google Satellite basemap (Map Tiles API)',
+ overage:
+ 'Beyond the free tier, Google bills extra tiles to your Cloud project (per 1,000). A quota cap in the Cloud Console makes it stop serving instead of billing.',
+ },
+ ];
+
+ let keys = $state({ mapbox: '', google: '' });
+ let shown = $state({ mapbox: false, google: false });
+ let usage = $state({});
+ let month = $state('');
+ let saving = $state(false);
+ let testing = $state({ mapbox: false, google: false });
+ let testResult = $state({ mapbox: null, google: null }); // { ok, detail } | null
+
+ async function load() {
+ const s = await api.get('/api/settings');
+ keys = { mapbox: s.api_keys.mapbox ?? '', google: s.api_keys.google ?? '' };
+ usage = s.usage;
+ month = s.month;
+ }
+
+ onMount(() => {
+ load().catch((e) => toast(`Could not load settings: ${e.message}`, 'danger'));
+ });
+
+ async function saveKeys() {
+ if (saving) return;
+ saving = true;
+ try {
+ await api.put('/api/settings/keys', { mapbox: keys.mapbox, google: keys.google });
+ testResult = { mapbox: null, google: null }; // stale verdicts for new keys
+ toast('Keys saved — keyed basemaps now appear in the Satellite tab', 'ok');
+ } catch (e) {
+ toast(`Could not save keys: ${e.message}`, 'danger');
+ } finally {
+ saving = false;
+ }
+ }
+
+ // exercise the *saved* key against the real service (Mapbox: one tile;
+ // Google: createSession) so a typo shows up here, not mid-investigation
+ async function testKey(id) {
+ if (testing[id]) return;
+ testing[id] = true;
+ testResult[id] = null;
+ try {
+ await api.put('/api/settings/keys', { [id]: keys[id] }); // test what's in the field
+ testResult[id] = await api.post(`/api/settings/keys/${id}/test`);
+ } catch (e) {
+ testResult[id] = { ok: false, detail: e.message };
+ } finally {
+ testing[id] = false;
+ }
+ }
+</script>
+
+<div class="tool">
+ <div class="tool-header">
+ <h2>Settings</h2>
+ <span class="sub">API keys & usage — stored locally, never in a case export</span>
+ </div>
+
+ <div class="body">
+ <section class="card block">
+ <h3><Icon name="key" size={15} /> Imagery API keys</h3>
+ <p class="hint">
+ Optional. Azimut's built-in basemaps (Esri, OSM) never need a key — your own
+ Mapbox / Google keys just unlock extra official basemaps in the Satellite tab.
+ Keys stay in <span class="mono">settings.json</span> on this machine.
+ </p>
+
+ {#each KEYED as k (k.id)}
+ <div class="key-row">
+ <label for="key-{k.id}">
+ {k.field}
+ <a href={k.help} target="_blank" rel="noreferrer" title="How to get one">
+ how to get one <Icon name="external" size={11} />
+ </a>
+ </label>
+ <div class="key-line">
+ <input
+ id="key-{k.id}"
+ class="input"
+ type={shown[k.id] ? 'text' : 'password'}
+ placeholder={k.placeholder}
+ bind:value={keys[k.id]}
+ autocomplete="off"
+ spellcheck="false"
+ />
+ <button
+ class="btn btn-ghost btn-sm"
+ onclick={() => (shown[k.id] = !shown[k.id])}
+ title={shown[k.id] ? 'Hide key' : 'Show key'}
+ aria-label={shown[k.id] ? 'Hide key' : 'Show key'}
+ >
+ <Icon name={shown[k.id] ? 'eyeOff' : 'eye'} size={14} />
+ </button>
+ <button
+ class="btn btn-sm"
+ onclick={() => testKey(k.id)}
+ disabled={testing[k.id] || !keys[k.id].trim()}
+ title="Save this key, then exercise it against the real service"
+ >
+ {testing[k.id] ? 'Testing…' : 'Test'}
+ </button>
+ </div>
+ <div class="key-foot">
+ <span class="unlocks">Unlocks: {k.unlocks}</span>
+ {#if testResult[k.id]}
+ <span class="verdict" class:ok={testResult[k.id].ok} class:bad={!testResult[k.id].ok}>
+ <Icon name={testResult[k.id].ok ? 'check' : 'alert'} size={12} />
+ {testResult[k.id].ok ? 'Key works' : testResult[k.id].detail}
+ </span>
+ {/if}
+ </div>
+ </div>
+ {/each}
+
+ <div class="actions">
+ <button class="btn btn-primary" onclick={saveKeys} disabled={saving}>
+ {saving ? 'Saving…' : 'Save keys'}
+ </button>
+ </div>
+ </section>
+
+ <section class="card block">
+ <h3><Icon name="chart" size={15} /> Tile usage — {month}</h3>
+ <p class="hint">
+ Keyed providers bill per tile served. Azimut counts exactly what goes out to
+ each provider (live map + captures, browser cache hits excluded), so this
+ matches their billing as closely as possible. Local bookkeeping only — the
+ counter never leaves this machine.
+ </p>
+ {#if KEYED.some((k) => keys[k.id] || monthCount(usage, k.id, month))}
+ <div class="usage">
+ {#each KEYED as k (k.id)}
+ {#if keys[k.id] || monthCount(usage, k.id, month)}
+ {@const count = monthCount(usage, k.id, month)}
+ {@const share = freeTierShare(count, k.id)}
+ <div class="usage-row">
+ <div class="usage-line">
+ <span class="usage-name">{k.label}</span>
+ <span class="mono">{tilesOfFree(count, k.id)}</span>
+ </div>
+ <div class="meter-track" aria-hidden="true">
+ <div
+ class="meter-fill"
+ class:hot={share >= 0.9}
+ style="width:{Math.min(share * 100, 100)}%"
+ ></div>
+ </div>
+ <p class="overage">{k.overage}</p>
+ </div>
+ {/if}
+ {/each}
+ </div>
+ {:else}
+ <p class="none">No keyed provider configured yet.</p>
+ {/if}
+ <button class="btn btn-ghost btn-sm" onclick={() => load()} title="Refresh counters">
+ <Icon name="reset" size={13} /> Refresh
+ </button>
+ </section>
+
+ <section class="card block">
+ <h3><Icon name="shield" size={15} /> Provider terms, encoded</h3>
+ <ul class="rules">
+ <li>Google tiles are never cached to disk, and a Google capture is a flattened screenshot with the copyright line burned into its footer — both are conditions of Google's Map Tiles API terms.</li>
+ <li>Mapbox captures keep the © Mapbox © OpenStreetMap attribution in their provenance.</li>
+ <li>Keys are never bundled into a shared case or export.</li>
+ </ul>
+ </section>
+ </div>
+</div>
+
+<style>
+ .tool {
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ }
+ .tool-header {
+ display: flex;
+ align-items: baseline;
+ gap: 12px;
+ padding: 14px 18px 10px;
+ }
+ .tool-header h2 {
+ font-size: var(--fs-lg);
+ }
+ .sub {
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ }
+ .body {
+ flex: 1;
+ overflow-y: auto;
+ padding: 6px 18px 24px;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ max-width: 720px;
+ }
+ .block {
+ padding: 16px;
+ }
+ h3 {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: var(--fs-md);
+ margin-bottom: 6px;
+ }
+ .hint {
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ margin-bottom: 14px;
+ line-height: 1.5;
+ }
+ .key-row {
+ margin-bottom: 14px;
+ }
+ .key-row label {
+ display: flex;
+ align-items: baseline;
+ gap: 10px;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ font-weight: 600;
+ margin-bottom: 5px;
+ }
+ .key-row label a {
+ color: var(--accent);
+ font-weight: 400;
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ }
+ .key-line {
+ display: flex;
+ gap: 6px;
+ align-items: center;
+ }
+ .key-line .input {
+ flex: 1;
+ font-family: var(--font-mono);
+ }
+ .key-foot {
+ display: flex;
+ gap: 12px;
+ align-items: center;
+ margin-top: 4px;
+ font-size: var(--fs-xs);
+ }
+ .unlocks {
+ color: var(--text-3);
+ }
+ .verdict {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ }
+ .verdict.ok {
+ color: var(--ok);
+ }
+ .verdict.bad {
+ color: var(--danger);
+ }
+ .actions {
+ margin-top: 4px;
+ }
+ .usage {
+ margin: 0 0 10px;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ font-size: var(--fs-sm);
+ }
+ .usage-line {
+ display: flex;
+ justify-content: space-between;
+ align-items: baseline;
+ gap: 10px;
+ margin-bottom: 5px;
+ }
+ .usage-name {
+ font-weight: 600;
+ color: var(--text-2);
+ }
+ .meter-track {
+ height: 5px;
+ border-radius: 999px;
+ background: var(--bg-2);
+ border: 1px solid var(--border);
+ overflow: hidden;
+ }
+ .meter-fill {
+ height: 100%;
+ background: var(--accent);
+ border-radius: inherit;
+ transition: width 0.3s var(--ease);
+ }
+ .meter-fill.hot {
+ background: var(--danger);
+ }
+ .overage {
+ margin-top: 5px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ line-height: 1.4;
+ }
+ .none {
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ margin-bottom: 10px;
+ }
+ .rules {
+ margin: 0;
+ padding-left: 18px;
+ color: var(--text-2);
+ font-size: var(--fs-sm);
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ line-height: 1.45;
+ }
+</style>
diff --git a/frontend/src/tools/inspect/CollageCanvas.svelte b/frontend/src/tools/inspect/CollageCanvas.svelte
index 225a3fb..c415b43 100644
--- a/frontend/src/tools/inspect/CollageCanvas.svelte
+++ b/frontend/src/tools/inspect/CollageCanvas.svelte
@@ -1,5 +1,6 @@
<script>
- import { quadMatrix3d, quadCentroid, scaleQuad, rotateQuad, quadRadius } from '../../lib/inspect.js';
+ import { quadMatrix3d, quadCentroid, rotateQuad, quadEdgeMidpoints, scaleQuad } from '../../lib/inspect.js';
+ import { uiState } from '../../lib/state.svelte.js';
import Icon from '../../components/Icon.svelte';
// Interactive collage surface. Each node is a tray frame placed as a 4-point
@@ -7,29 +8,75 @@
// corner handle to warp — a hand-made panorama. The same quads are sent to the
// backend, which renders the full-res warp with PIL (see compose_perspective).
// `collage` is the session's *active* collage (a session may hold several).
- let { collage, selectedId = $bindable() } = $props();
+ let { collage, selectedId = $bindable(), requestCrop } = $props();
let wrapEl = $state();
let availW = $state(800);
let availH = $state(600);
+ let zoom = $state(1); // 1 = fit; wheel zooms toward the pointer
+ let panX = $state(0);
+ let panY = $state(0);
+ let movingId = $state(null); // piece being dragged — semi-transparent to align
const cw = $derived(collage.width);
const ch = $derived(collage.height);
- const scale = $derived(Math.min(availW / cw, availH / ch, 1) || 1);
+ const fitScale = $derived(Math.min(availW / cw, availH / ch, 1) || 1);
+ const scale = $derived(fitScale * zoom);
function boxOf(node) {
return { w: node.w || 320, h: node.h || 240, url: node.url };
}
- // client px -> canvas px (the inner surface is scaled with transform-origin 0 0)
+ // client px -> canvas px (the inner surface is translated then scaled, origin 0 0)
function toCanvas(e) {
const r = wrapEl.getBoundingClientRect();
- return [(e.clientX - r.left) / scale, (e.clientY - r.top) / scale];
+ return [(e.clientX - r.left - panX) / scale, (e.clientY - r.top - panY) / scale];
+ }
+
+ // Wheel zooms toward the pointer so the feature under the cursor stays put —
+ // pixel-level alignment needs to get closer than the fitted view.
+ function onWheel(e) {
+ e.preventDefault();
+ const r = wrapEl.getBoundingClientRect();
+ const px = e.clientX - r.left;
+ const py = e.clientY - r.top;
+ const old = scale;
+ const next = Math.min(Math.max(zoom * (e.deltaY > 0 ? 0.9 : 1.1), 0.2), 8);
+ const k = fitScale * next;
+ panX = px - ((px - panX) / old) * k;
+ panY = py - ((py - panY) / old) * k;
+ zoom = next;
+ }
+
+ function resetView() {
+ zoom = 1;
+ panX = 0;
+ panY = 0;
+ }
+
+ // Drag on the empty background pans the view (a plain click still deselects).
+ function startPan(e) {
+ selectedId = null;
+ const sx = e.clientX;
+ const sy = e.clientY;
+ const ox = panX;
+ const oy = panY;
+ const move = (ev) => {
+ panX = ox + ev.clientX - sx;
+ panY = oy + ev.clientY - sy;
+ };
+ const up = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
}
function startMove(e, node) {
e.preventDefault();
selectedId = node.id;
+ movingId = node.id;
let [px, py] = toCanvas(e);
const move = (ev) => {
const [nx, ny] = toCanvas(ev);
@@ -40,6 +87,7 @@
py = ny;
};
const up = () => {
+ movingId = null;
window.removeEventListener('pointermove', move);
window.removeEventListener('pointerup', up);
};
@@ -63,22 +111,26 @@
window.addEventListener('pointerup', up);
}
- // Uniformly resize the piece with a *vertical* drag (up = bigger). The factor
- // is calibrated on the piece's own radius and eased exponentially, so it feels
- // the same for small and large pieces and never snaps. Pure quad math, so it
- // composes with the per-corner warp — both just move the same points.
- function startScale(e, node) {
+ // Square side handles: uniform scale of the whole piece about its centroid
+ // (not a one-axis stretch). Dragging a side out enlarges, in shrinks; the
+ // factor tracks the handle's distance from the centre, so it composes with the
+ // per-corner warp (round handles) and holds up on an already-warped piece.
+ function startEdgeResize(e, node, side) {
e.preventDefault();
e.stopPropagation();
selectedId = node.id;
const c = quadCentroid(node.quad);
const base = node.quad.map(([x, y]) => [x, y]);
- const R = quadRadius(node.quad);
- const [, sy] = toCanvas(e);
+ const mid = quadEdgeMidpoints(base)[side];
+ const dl = Math.hypot(mid.x - c[0], mid.y - c[1]) || 1;
+ const ux = (mid.x - c[0]) / dl;
+ const uy = (mid.y - c[1]) / dl;
+ const [sx, sy] = toCanvas(e);
+ const d0 = (sx - c[0]) * ux + (sy - c[1]) * uy || dl; // start projection
const move = (ev) => {
- const [, my] = toCanvas(ev);
- // drag one radius up ≈ ×2, one radius down ≈ ×0.5
- const k = Math.min(20, Math.max(0.05, Math.pow(2, (sy - my) / R)));
+ const [mx, my] = toCanvas(ev);
+ const d = (mx - c[0]) * ux + (my - c[1]) * uy;
+ const k = Math.min(20, Math.max(0.05, d / d0));
node.quad = scaleQuad(base, k, c);
};
const up = () => {
@@ -89,10 +141,22 @@
window.addEventListener('pointerup', up);
}
- // Delete / Backspace removes the selected piece. This canvas is only mounted
- // on the Collage tab, so the window listener is scoped to it — but still bail
- // when typing in a field or when a modal (e.g. the crop editor) is open.
+ // Nudge the piece one step up/down the stacking order (swap with its
+ // neighbour). The right panel keeps the all-the-way Front/Back buttons.
+ function stepZ(node, dir) {
+ const nodes = collage.nodes;
+ const i = nodes.findIndex((n) => n.id === node.id);
+ const j = i + dir;
+ if (i < 0 || j < 0 || j >= nodes.length) return;
+ [nodes[i], nodes[j]] = [nodes[j], nodes[i]];
+ collage.nodes = [...nodes];
+ }
+
+ // Delete / Backspace removes the selected piece. The Inspect tool stays
+ // mounted when another tab is shown, so bail unless it is the visible tool —
+ // and when typing in a field or when a modal (e.g. the crop editor) is open.
function onKey(e) {
+ if (uiState.tool !== 'inspect') return;
if (selectedId == null) return;
if (e.key !== 'Delete' && e.key !== 'Backspace') return;
const t = e.target;
@@ -137,19 +201,21 @@
bind:clientWidth={availW}
bind:clientHeight={availH}
style:background={collage.transparent ? null : collage.background}
- onpointerdown={() => (selectedId = null)}
+ onpointerdown={startPan}
+ onwheel={onWheel}
>
<div
class="surface"
style:width={`${cw}px`}
style:height={`${ch}px`}
- style:transform={`scale(${scale})`}
+ style:transform={`translate(${panX}px, ${panY}px) scale(${scale})`}
>
{#each collage.nodes as node (node.id)}
{@const box = boxOf(node)}
<img
class="node"
class:selected={node.id === selectedId}
+ class:ghost={node.ghost || node.id === movingId}
src={box.url}
alt="collage piece"
style:width={`${box.w}px`}
@@ -157,8 +223,10 @@
style:transform={quadMatrix3d(box.w, box.h, node.quad)}
draggable="false"
onpointerdown={(e) => (e.stopPropagation(), startMove(e, node))}
+ ondblclick={() => { selectedId = node.id; requestCrop?.(node); }}
/>
{#if node.id === selectedId}
+ <!-- round corner handles: free perspective warp -->
{#each node.quad as pt, i (i)}
<button
class="handle"
@@ -170,44 +238,114 @@
aria-label={`Warp corner ${i + 1}`}
></button>
{/each}
- {@const bx0 = Math.min(node.quad[0][0], node.quad[1][0], node.quad[2][0], node.quad[3][0])}
- {@const bx1 = Math.max(node.quad[0][0], node.quad[1][0], node.quad[2][0], node.quad[3][0])}
- {@const by0 = Math.min(node.quad[0][1], node.quad[1][1], node.quad[2][1], node.quad[3][1])}
- <!-- Controls float in a compact bar just above the piece so they never
- cover the image. Both are relative-drag gestures (see startScale /
- startRotate), so their fixed position doesn't matter. -->
+ <!-- square side handles: resize (slide that edge, opposite edge fixed) -->
+ {#each quadEdgeMidpoints(node.quad) as m (m.side)}
+ <button
+ class="side-handle"
+ style:left={`${m.x}px`}
+ style:top={`${m.y}px`}
+ style:width={`${14 / scale}px`}
+ style:height={`${14 / scale}px`}
+ onpointerdown={(e) => startEdgeResize(e, node, m.side)}
+ aria-label={`Resize side ${m.side + 1}`}
+ title="Drag to resize this side"
+ ></button>
+ {/each}
+ <!-- Anchor the knob/bar to the piece's *right edge* along its outward
+ normal, so they follow the piece as it rotates and warps. -->
+ {@const cen = quadCentroid(node.quad)}
+ {@const rmx = (node.quad[1][0] + node.quad[2][0]) / 2}
+ {@const rmy = (node.quad[1][1] + node.quad[2][1]) / 2}
+ {@const dl = Math.hypot(rmx - cen[0], rmy - cen[1]) || 1}
+ {@const ux = (rmx - cen[0]) / dl}
+ {@const uy = (rmy - cen[1]) / dl}
+ {@const stemAng = Math.atan2(uy, ux)}
+ <!-- rotate bar on a short stem off the right edge, pointing outward -->
+ <div
+ class="rot-stem"
+ style:left={`${rmx}px`}
+ style:top={`${rmy}px`}
+ style:width={`${24 / scale}px`}
+ style:height={`${1.5 / scale}px`}
+ style:transform={`translateX(${-0.75 / scale}px) rotate(${stemAng}rad)`}
+ ></div>
+ <button
+ class="rot-handle"
+ style:left={`${rmx + ux * (24 / scale)}px`}
+ style:top={`${rmy + uy * (24 / scale)}px`}
+ style:width={`${20 / scale}px`}
+ style:height={`${20 / scale}px`}
+ onpointerdown={(e) => startRotate(e, node)}
+ aria-label="Rotate piece"
+ title="Drag to rotate"
+ >
+ <Icon name="reset" size={13 / scale} />
+ </button>
+ <!-- ghost preview + one-step stacking order. Anchored off the *bottom*
+ edge (opposite the rotate knob) so the two never overlap however the
+ piece is turned. Front/Back-all live in the right panel. -->
+ {@const bmx = (node.quad[2][0] + node.quad[3][0]) / 2}
+ {@const bmy = (node.quad[2][1] + node.quad[3][1]) / 2}
+ {@const bdl = Math.hypot(bmx - cen[0], bmy - cen[1]) || 1}
+ {@const bux = (bmx - cen[0]) / bdl}
+ {@const buy = (bmy - cen[1]) / bdl}
<div
class="toolbar"
- style:left={`${(bx0 + bx1) / 2}px`}
- style:top={`${by0 - 12 / scale}px`}
+ style:left={`${bmx + bux * (34 / scale)}px`}
+ style:top={`${bmy + buy * (34 / scale)}px`}
style:gap={`${5 / scale}px`}
style:padding={`${4 / scale}px ${5 / scale}px`}
>
<button
- class="tbtn rot"
+ class="tbtn"
+ class:on={node.ghost}
style:width={`${28 / scale}px`}
style:height={`${28 / scale}px`}
- onpointerdown={(e) => startRotate(e, node)}
- aria-label="Rotate piece"
- title="Drag to rotate"
+ onpointerdown={(e) => e.stopPropagation()}
+ onclick={() => (node.ghost = !node.ghost)}
+ aria-label="Toggle piece transparency"
+ title="See through this piece to align features (view only, never exported)"
>
- <Icon name="reset" size={15 / scale} />
+ <Icon name="ghost" size={15 / scale} />
</button>
<button
- class="tbtn scl"
+ class="tbtn z-up"
style:width={`${28 / scale}px`}
style:height={`${28 / scale}px`}
- onpointerdown={(e) => startScale(e, node)}
- aria-label="Resize piece"
- title="Drag up/down to resize"
+ onpointerdown={(e) => e.stopPropagation()}
+ onclick={() => stepZ(node, 1)}
+ aria-label="Bring forward one step"
+ title="Bring forward (one step)"
>
- <Icon name="grip" size={15 / scale} />
+ <Icon name="chevronDown" size={15 / scale} />
+ </button>
+ <button
+ class="tbtn"
+ style:width={`${28 / scale}px`}
+ style:height={`${28 / scale}px`}
+ onpointerdown={(e) => e.stopPropagation()}
+ onclick={() => stepZ(node, -1)}
+ aria-label="Send back one step"
+ title="Send back (one step)"
+ >
+ <Icon name="chevronDown" size={15 / scale} />
</button>
</div>
{/if}
{/each}
</div>
+ <div class="view-ctl">
+ {#if zoom !== 1}
+ <span class="zoom-val">{Math.round(zoom * 100)}%</span>
+ <button class="btn btn-ghost btn-sm" onclick={resetView} title="Fit the collage back in view">
+ <Icon name="eye" size={14} /> Fit
+ </button>
+ {:else}
+ <span class="zoom-hint">scroll to zoom · drag background to pan</span>
+ {/if}
+ </div>
+
{#if collage.nodes.length === 0}
<div class="empty">
<Icon name="layers" size={34} />
@@ -258,6 +396,35 @@
.node.selected {
outline: 1px dashed var(--accent);
}
+ .node.ghost {
+ opacity: 0.55;
+ }
+ .tbtn.on {
+ background: var(--accent-soft);
+ }
+ .view-ctl {
+ position: absolute;
+ right: 10px;
+ bottom: 10px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 3px 6px;
+ border-radius: var(--r-md);
+ background: rgba(16, 20, 28, 0.85);
+ border: 1px solid var(--border);
+ }
+ .zoom-val {
+ font-size: var(--fs-xs);
+ font-weight: 700;
+ color: var(--text-2);
+ font-variant-numeric: tabular-nums;
+ }
+ .zoom-hint {
+ font-size: 11px;
+ color: var(--text-3);
+ user-select: none;
+ }
.handle {
position: absolute;
transform: translate(-50%, -50%);
@@ -270,7 +437,7 @@
}
.toolbar {
position: absolute;
- transform: translate(-50%, -100%);
+ transform: translate(-50%, -50%);
display: flex;
align-items: center;
border-radius: 999px;
@@ -293,11 +460,42 @@
.tbtn:hover {
background: rgba(255, 255, 255, 0.09);
}
- .tbtn.rot {
+ .tbtn.z-up :global(svg) {
+ transform: rotate(180deg);
+ }
+ /* Square side handles resize; round corner handles warp. */
+ .side-handle {
+ position: absolute;
+ transform: translate(-50%, -50%);
+ border-radius: 2px;
+ background: var(--accent);
+ border: 2px solid #10141c;
+ cursor: nesw-resize;
+ padding: 0;
+ touch-action: none;
+ }
+ .rot-stem {
+ position: absolute;
+ transform-origin: 0 0;
+ background: var(--accent);
+ pointer-events: none;
+ }
+ .rot-handle {
+ position: absolute;
+ transform: translate(-50%, -50%);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 50%;
+ background: rgba(16, 20, 28, 0.92);
+ color: var(--accent);
+ border: 1px solid var(--accent);
cursor: grab;
+ padding: 0;
+ touch-action: none;
}
- .tbtn.scl {
- cursor: ns-resize;
+ .rot-handle:hover {
+ background: rgba(255, 255, 255, 0.09);
}
.empty {
position: absolute;
diff --git a/frontend/src/tools/inspect/CollageMenu.svelte b/frontend/src/tools/inspect/CollageMenu.svelte
index 1926cbd..dd78caf 100644
--- a/frontend/src/tools/inspect/CollageMenu.svelte
+++ b/frontend/src/tools/inspect/CollageMenu.svelte
@@ -124,7 +124,7 @@
<span class="lbl">Scale</span>
<button class="btn btn-sm sq" onclick={() => scaleBy(selected, 1 / 1.1)} aria-label="Shrink piece">−</button>
<button class="btn btn-sm sq" onclick={() => scaleBy(selected, 1.1)} aria-label="Enlarge piece">+</button>
- <span class="sub">or drag the ⇕ grip above the piece</span>
+ <span class="sub">or drag a square side handle</span>
</div>
<div class="scale-row">
<span class="lbl">Rotate</span>
diff --git a/frontend/src/tools/inspect/CropBox.svelte b/frontend/src/tools/inspect/CropBox.svelte
new file mode 100644
index 0000000..b8e7e13
--- /dev/null
+++ b/frontend/src/tools/inspect/CropBox.svelte
@@ -0,0 +1,195 @@
+<script>
+ import { clampCrop, moveCrop, resizeCropByHandle } from '../../lib/inspect.js';
+
+ // Editable crop rectangle overlaid on an image. Emits a fractional (0..1)
+ // {x,y,w,h} via `bind:crop`. Eight handles resize (corners + edges), the body
+ // moves, and — while `draw` is armed — dragging empty space draws a fresh box.
+ // With `aspect` (pixel w/h) set the box keeps that ratio. All the geometry is
+ // pure (see inspect.js), so the Frame overlay and the piece modal share it.
+ let {
+ crop = $bindable(null),
+ draw = $bindable(false),
+ aspect = null,
+ natW = null,
+ natH = null,
+ min = 0.02,
+ } = $props();
+
+ let layerEl = $state();
+ let action = null; // { type:'draw'|'move'|'resize', ... }
+
+ // pixel aspect (w/h) → fractional aspect, since the box is stored in 0..1
+ const fracAspect = $derived(
+ aspect ? (natW && natH ? aspect * (natH / natW) : aspect) : null
+ );
+
+ const HANDLES = [
+ { h: 'nw', x: 0, y: 0 }, { h: 'n', x: 0.5, y: 0 }, { h: 'ne', x: 1, y: 0 },
+ { h: 'e', x: 1, y: 0.5 }, { h: 'se', x: 1, y: 1 }, { h: 's', x: 0.5, y: 1 },
+ { h: 'sw', x: 0, y: 1 }, { h: 'w', x: 0, y: 0.5 },
+ ];
+ const CURSORS = {
+ nw: 'nwse-resize', se: 'nwse-resize', ne: 'nesw-resize', sw: 'nesw-resize',
+ n: 'ns-resize', s: 'ns-resize', e: 'ew-resize', w: 'ew-resize',
+ };
+
+ function frac(e) {
+ const r = layerEl.getBoundingClientRect();
+ return {
+ x: Math.min(1, Math.max(0, (e.clientX - r.left) / r.width)),
+ y: Math.min(1, Math.max(0, (e.clientY - r.top) / r.height)),
+ };
+ }
+
+ function begin(a) {
+ action = a;
+ window.addEventListener('pointermove', onMove);
+ window.addEventListener('pointerup', onUp);
+ }
+
+ function onMove(e) {
+ if (!action) return;
+ const p = frac(e);
+ if (action.type === 'draw') {
+ let c = {
+ x: Math.min(action.sx, p.x), y: Math.min(action.sy, p.y),
+ w: Math.abs(p.x - action.sx), h: Math.abs(p.y - action.sy),
+ };
+ if (fracAspect) {
+ c.h = c.w / fracAspect;
+ if (p.y < action.sy) c.y = action.sy - c.h;
+ }
+ crop = c;
+ } else if (action.type === 'move') {
+ crop = moveCrop(action.orig, p.x - action.sx, p.y - action.sy);
+ } else if (action.type === 'resize') {
+ crop = resizeCropByHandle(action.orig, action.handle, p.x, p.y, fracAspect, min);
+ }
+ }
+
+ function onUp() {
+ if (action?.type === 'draw') {
+ crop = crop && crop.w >= min && crop.h >= min ? clampCrop(crop, min) : action.prev;
+ draw = false;
+ }
+ action = null;
+ window.removeEventListener('pointermove', onMove);
+ window.removeEventListener('pointerup', onUp);
+ }
+
+ function layerDown(e) {
+ if (!draw || e.button !== 0) return; // middle-drag falls through (rotate)
+ e.preventDefault();
+ const p = frac(e);
+ const prev = crop;
+ crop = { x: p.x, y: p.y, w: 0, h: 0 };
+ begin({ type: 'draw', sx: p.x, sy: p.y, prev });
+ }
+
+ function bodyDown(e) {
+ if (e.button !== 0) return;
+ e.preventDefault();
+ e.stopPropagation();
+ const p = frac(e);
+ begin({ type: 'move', sx: p.x, sy: p.y, orig: { ...crop } });
+ }
+
+ function handleDown(e, h) {
+ if (e.button !== 0) return;
+ e.preventDefault();
+ e.stopPropagation();
+ begin({ type: 'resize', handle: h, orig: { ...crop } });
+ }
+</script>
+
+<!-- svelte-ignore a11y_no_static_element_interactions -->
+<div
+ class="cropbox-layer"
+ class:drawing={draw}
+ bind:this={layerEl}
+ onpointerdown={layerDown}
+>
+ {#if crop}
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div
+ class="box"
+ style:left={`${crop.x * 100}%`}
+ style:top={`${crop.y * 100}%`}
+ style:width={`${crop.w * 100}%`}
+ style:height={`${crop.h * 100}%`}
+ onpointerdown={bodyDown}
+ >
+ <span class="edge v" style:left="33.33%"></span>
+ <span class="edge v" style:left="66.66%"></span>
+ <span class="edge h" style:top="33.33%"></span>
+ <span class="edge h" style:top="66.66%"></span>
+ {#each HANDLES as hd (hd.h)}
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <span
+ class="handle {hd.h}"
+ style:left={`${hd.x * 100}%`}
+ style:top={`${hd.y * 100}%`}
+ style:cursor={CURSORS[hd.h]}
+ onpointerdown={(e) => handleDown(e, hd.h)}
+ ></span>
+ {/each}
+ </div>
+ {/if}
+</div>
+
+<style>
+ .cropbox-layer {
+ position: absolute;
+ inset: 0;
+ pointer-events: none; /* empty area passes through (pan) unless drawing */
+ z-index: 3;
+ }
+ .cropbox-layer.drawing {
+ pointer-events: auto;
+ cursor: crosshair;
+ }
+ .box {
+ position: absolute;
+ box-sizing: border-box;
+ border: 1.5px solid var(--accent);
+ box-shadow: 0 0 0 9999px rgba(6, 9, 14, 0.55);
+ pointer-events: auto;
+ cursor: move;
+ }
+ .edge {
+ position: absolute;
+ background: rgba(232, 163, 61, 0.35);
+ pointer-events: none;
+ }
+ .edge.v {
+ top: 0;
+ bottom: 0;
+ width: 1px;
+ }
+ .edge.h {
+ left: 0;
+ right: 0;
+ height: 1px;
+ }
+ .handle {
+ position: absolute;
+ width: 12px;
+ height: 12px;
+ transform: translate(-50%, -50%);
+ background: var(--accent);
+ border: 2px solid #10141c;
+ border-radius: 2px;
+ pointer-events: auto;
+ touch-action: none;
+ }
+ .handle.n,
+ .handle.s {
+ border-radius: 6px;
+ width: 16px;
+ }
+ .handle.e,
+ .handle.w {
+ border-radius: 6px;
+ height: 16px;
+ }
+</style>
diff --git a/frontend/src/tools/inspect/CropControls.svelte b/frontend/src/tools/inspect/CropControls.svelte
new file mode 100644
index 0000000..30ec636
--- /dev/null
+++ b/frontend/src/tools/inspect/CropControls.svelte
@@ -0,0 +1,162 @@
+<script>
+ import { clampCrop } from '../../lib/inspect.js';
+
+ // Precise controls for an editable crop: aspect-ratio lock (presets) plus
+ // numeric entry. Operates on a bindable fractional crop + bindable aspect
+ // (pixel w/h, null = free). When natural pixel dims are known the numeric
+ // fields are pixels, otherwise percentages. Pairs with CropBox.
+ let {
+ crop = $bindable(null),
+ aspect = $bindable(null),
+ natW = null,
+ natH = null,
+ onclear = null,
+ } = $props();
+
+ const nat = $derived(!!(natW && natH));
+ const fracAspect = $derived(aspect ? (nat ? aspect * (natH / natW) : aspect) : null);
+
+ const PRESETS = [
+ { label: 'Free', a: null },
+ { label: '1:1', a: 1 },
+ { label: '4:3', a: 4 / 3 },
+ { label: '3:2', a: 3 / 2 },
+ { label: '16:9', a: 16 / 9 },
+ { label: '5:4', a: 5 / 4 },
+ { label: '4:5', a: 4 / 5 },
+ { label: '9:16', a: 9 / 16 },
+ ];
+
+ // Re-fit the current crop to a newly picked aspect, keeping its centre.
+ function fitAspect(fa) {
+ if (!crop || !fa) return;
+ const cx = crop.x + crop.w / 2;
+ const cy = crop.y + crop.h / 2;
+ let w = crop.w;
+ let h = w / fa;
+ if (h > 1) { h = 1; w = h * fa; }
+ if (w > 1) { w = 1; h = w / fa; }
+ crop = clampCrop({ x: cx - w / 2, y: cy - h / 2, w, h });
+ }
+
+ function pickAspect(a) {
+ aspect = a;
+ if (a) fitAspect(nat ? a * (natH / natW) : a);
+ }
+
+ const originalAspect = $derived(nat ? natW / natH : null);
+
+ // px (or %) → fraction, applied to one field with the aspect lock honoured.
+ function setField(field, raw) {
+ if (!crop) return;
+ const val = Number(raw);
+ if (!Number.isFinite(val)) return;
+ const denom = field === 'w' || field === 'x' ? (nat ? natW : 100) : (nat ? natH : 100);
+ const f = val / denom;
+ const c = { ...crop, [field]: f };
+ if (fracAspect && field === 'w') c.h = c.w / fracAspect;
+ if (fracAspect && field === 'h') c.w = c.h * fracAspect;
+ crop = clampCrop(c);
+ }
+
+ const disp = (f, denom) => (crop ? Math.round(f * (nat ? denom : 100)) : 0);
+</script>
+
+<div class="crop-controls">
+ <div class="chips">
+ {#each PRESETS as p (p.label)}
+ <button
+ class="chip"
+ class:on={aspect === p.a}
+ onclick={() => pickAspect(p.a)}
+ disabled={!crop && p.a != null}
+ title={`Lock ${p.label}`}
+ >{p.label}</button>
+ {/each}
+ {#if originalAspect}
+ <button
+ class="chip"
+ class:on={aspect === originalAspect}
+ onclick={() => pickAspect(originalAspect)}
+ disabled={!crop}
+ title="Lock the source aspect ratio"
+ >Orig</button>
+ {/if}
+ </div>
+
+ {#if crop}
+ <div class="fields">
+ <label>W<input type="number" min="1" value={disp(crop.w, natW)} onchange={(e) => setField('w', e.target.value)} /></label>
+ <label>H<input type="number" min="1" value={disp(crop.h, natH)} onchange={(e) => setField('h', e.target.value)} /></label>
+ <label>X<input type="number" min="0" value={disp(crop.x, natW)} onchange={(e) => setField('x', e.target.value)} /></label>
+ <label>Y<input type="number" min="0" value={disp(crop.y, natH)} onchange={(e) => setField('y', e.target.value)} /></label>
+ <span class="unit">{nat ? 'px' : '%'}</span>
+ {#if onclear}
+ <button class="chip clear" onclick={onclear} title="Remove the crop">Clear</button>
+ {/if}
+ </div>
+ {/if}
+</div>
+
+<style>
+ .crop-controls {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+ .chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ }
+ .chip {
+ padding: 3px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-1);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ }
+ .chip:hover:not(:disabled) {
+ border-color: var(--accent);
+ }
+ .chip.on {
+ border-color: var(--accent);
+ color: var(--accent);
+ background: var(--accent-soft);
+ }
+ .chip:disabled {
+ opacity: 0.4;
+ }
+ .chip.clear {
+ margin-left: auto;
+ color: var(--danger, #d86a6a);
+ }
+ .fields {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 6px;
+ }
+ .fields label {
+ display: flex;
+ align-items: center;
+ gap: 3px;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .fields input {
+ width: 56px;
+ padding: 3px 5px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-0);
+ color: var(--text-1);
+ font-size: var(--fs-xs);
+ font-variant-numeric: tabular-nums;
+ }
+ .unit {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+</style>
diff --git a/frontend/src/tools/inspect/FrameMenu.svelte b/frontend/src/tools/inspect/FrameMenu.svelte
index ff119df..fd753d2 100644
--- a/frontend/src/tools/inspect/FrameMenu.svelte
+++ b/frontend/src/tools/inspect/FrameMenu.svelte
@@ -4,11 +4,15 @@
import { adjustDefaults, buildOps, previewStyle, cropImgStyle, styleText } from '../../lib/inspect.js';
import Icon from '../../components/Icon.svelte';
import AdjustSliders from './AdjustSliders.svelte';
+ import CropControls from './CropControls.svelte';
// Right-panel menu for the Frame tab. Works on the *active* tray frame:
// pick it, adjust it (live-previewed), crop it, or analyse it — all without
// filing anything. The recipe is committed later from the Save tab.
- let { session, filters, analyses, activeFrame, shared, removeFrame, setActive } = $props();
+ let {
+ session, filters, analyses, activeFrame, shared, removeFrame, setActive,
+ cropAspect = $bindable(null), cropEditing = $bindable(false), beginCrop, commitCrop,
+ } = $props();
let showAnalyze = $state(false);
let analyzing = $state(null);
@@ -20,15 +24,15 @@
activeFrame.adjust = adjustDefaults(filters);
activeFrame.crop = null;
shared.cropMode = false;
- }
-
- function toggleCrop() {
- shared.cropMode = !shared.cropMode;
+ cropAspect = null;
+ cropEditing = false;
}
function clearCrop() {
if (activeFrame) activeFrame.crop = null;
shared.cropMode = false;
+ cropAspect = null;
+ cropEditing = false;
}
async function runAnalysis(name) {
@@ -101,15 +105,26 @@
{#if activeFrame}
<div class="section">
<AdjustSliders {filters} values={activeFrame.adjust} />
- <div class="crop-row">
- <button class="btn btn-sm" class:active={shared.cropMode} onclick={toggleCrop}>
- <Icon name="crop" size={14} /> {shared.cropMode ? 'Drag on image…' : 'Crop region'}
- </button>
- {#if activeFrame.crop}
- <span class="crop-info mono">
- {Math.round(activeFrame.crop.w * 100)}% × {Math.round(activeFrame.crop.h * 100)}%
- </span>
- <button class="btn btn-ghost btn-xs" onclick={clearCrop} aria-label="Clear crop"><Icon name="x" size={13} /></button>
+ <div class="crop-block">
+ <div class="crop-row">
+ {#if cropEditing}
+ <button class="btn btn-sm active" onclick={() => commitCrop?.()} title="Apply the crop (Enter)">
+ <Icon name="check" size={14} /> Apply crop
+ </button>
+ <button class="btn btn-ghost btn-xs" onclick={() => (shared.cropMode = true)} title="Draw a fresh region">
+ <Icon name="crop" size={13} /> Redraw
+ </button>
+ {:else}
+ <button class="btn btn-sm" onclick={() => beginCrop?.()}>
+ <Icon name="crop" size={14} /> {activeFrame.crop ? 'Edit crop' : 'Crop region'}
+ </button>
+ {#if activeFrame.crop}
+ <span class="crop-info">or double-click the image</span>
+ {/if}
+ {/if}
+ </div>
+ {#if cropEditing}
+ <CropControls bind:crop={activeFrame.crop} bind:aspect={cropAspect} natW={activeFrame.w} natH={activeFrame.h} onclear={clearCrop} />
{/if}
</div>
<button class="btn btn-ghost btn-sm reset" onclick={reset}><Icon name="reset" size={14} /> Reset frame</button>
@@ -232,6 +247,11 @@
flex-direction: column;
gap: 9px;
}
+ .crop-block {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
.crop-row {
display: flex;
align-items: center;
diff --git a/frontend/src/tools/inspect/PieceCropModal.svelte b/frontend/src/tools/inspect/PieceCropModal.svelte
index d40774f..7c76378 100644
--- a/frontend/src/tools/inspect/PieceCropModal.svelte
+++ b/frontend/src/tools/inspect/PieceCropModal.svelte
@@ -1,82 +1,59 @@
<script>
import Modal from '../../components/Modal.svelte';
import Icon from '../../components/Icon.svelte';
+ import CropBox from './CropBox.svelte';
+ import CropControls from './CropControls.svelte';
- // Crop editor for a collage piece. Draws a fractional (0..1) box over the
+ // Crop editor for a collage piece. The fractional (0..1) box is drawn over the
// piece's *base* image (its snapshot before any collage crop), so re-cropping
- // always replaces rather than compounds. On apply, the parent re-renders the
- // node through the backend crop op (applied before the perspective warp).
+ // always replaces rather than compounds. Corners/edges nudge it, an aspect lock
+ // and numeric fields make it precise. On apply the parent re-renders the node
+ // through the backend crop op (applied before the perspective warp).
let { node, onapply, onclose } = $props();
let imgEl = $state();
- let draw = $state(null);
- // A drag in progress. `draw` alone can't gate `move` because we keep the box
- // after release (so Apply can read it) — without this flag the box would keep
- // resizing every time the pointer moved after mouse-up.
- let dragging = false;
- const box = $derived(draw ?? node.crop ?? null);
+ let natW = $state(node.w ?? null);
+ let natH = $state(node.h ?? null);
+ let crop = $state(node.crop ? { ...node.crop } : null);
+ let aspect = $state(null);
+ let draw = $state(!node.crop);
- function frac(e) {
- const r = imgEl.getBoundingClientRect();
- return {
- x: Math.min(1, Math.max(0, (e.clientX - r.left) / r.width)),
- y: Math.min(1, Math.max(0, (e.clientY - r.top) / r.height)),
- };
+ function onImgLoad(e) {
+ natW = e.currentTarget.naturalWidth;
+ natH = e.currentTarget.naturalHeight;
}
- function down(e) {
- e.preventDefault();
- dragging = true;
- const p = frac(e);
- draw = { sx: p.x, sy: p.y, x: p.x, y: p.y, w: 0, h: 0 };
- e.currentTarget.setPointerCapture?.(e.pointerId);
- }
- function move(e) {
- if (!dragging) return;
- const p = frac(e);
- draw = {
- sx: draw.sx, sy: draw.sy,
- x: Math.min(draw.sx, p.x), y: Math.min(draw.sy, p.y),
- w: Math.abs(p.x - draw.sx), h: Math.abs(p.y - draw.sy),
- };
- }
- function up(e) {
- dragging = false;
- if (draw && (draw.w < 0.02 || draw.h < 0.02)) draw = null;
- try { e.currentTarget.releasePointerCapture?.(e.pointerId); } catch { /* not captured */ }
+ function redraw() {
+ crop = null;
+ draw = true;
}
function apply() {
- const c = box && box.w > 0.02 && box.h > 0.02
- ? { x: box.x, y: box.y, w: box.w, h: box.h }
+ const c = crop && crop.w > 0.02 && crop.h > 0.02
+ ? { x: crop.x, y: crop.y, w: crop.w, h: crop.h }
: null;
onapply?.(c);
}
</script>
<Modal title="Crop piece" width="560px" {onclose}>
- <p class="hint">Drag a rectangle over the region to keep. It's applied before the warp, so the collage updates in place.</p>
- <!-- svelte-ignore a11y_no_static_element_interactions -->
- <div class="stage" onpointerdown={down} onpointermove={move} onpointerup={up}>
+ <p class="hint">Drag to draw a region, then nudge the handles or type exact values. Lock an aspect ratio to match a panel. Applied before the warp, so the collage updates in place.</p>
+ <div class="stage">
<img
bind:this={imgEl}
src={node.baseUrl || node.url}
alt="piece"
draggable="false"
+ onload={onImgLoad}
onerror={(e) => { if (node.url && e.currentTarget.src !== node.url) e.currentTarget.src = node.url; }}
/>
- {#if box}
- <div
- class="box"
- style:left={`${box.x * 100}%`}
- style:top={`${box.y * 100}%`}
- style:width={`${box.w * 100}%`}
- style:height={`${box.h * 100}%`}
- ></div>
- {/if}
+ <CropBox bind:crop bind:draw {aspect} {natW} {natH} />
+ </div>
+ <div class="tools">
+ <CropControls bind:crop bind:aspect {natW} {natH} onclear={redraw} />
</div>
<div class="foot">
- <button class="btn btn-sm" onclick={() => (draw = null)} disabled={!box}><Icon name="reset" size={13} /> Full frame</button>
+ <button class="btn btn-sm" onclick={redraw}><Icon name="crop" size={13} /> Redraw</button>
<div class="spacer"></div>
<button class="btn btn-sm" onclick={onclose}>Cancel</button>
<button class="btn btn-sm primary" onclick={apply}><Icon name="check" size={13} /> Apply</button>
@@ -93,7 +70,6 @@
position: relative;
line-height: 0;
touch-action: none;
- cursor: crosshair;
display: block;
width: fit-content;
max-width: 100%;
@@ -101,6 +77,7 @@
background: var(--bg-0);
border-radius: var(--r-sm);
overflow: hidden;
+ user-select: none;
}
.stage img {
max-width: 100%;
@@ -108,11 +85,8 @@
display: block;
user-select: none;
}
- .box {
- position: absolute;
- border: 1.5px solid var(--accent);
- box-shadow: 0 0 0 9999px rgba(6, 9, 14, 0.55);
- pointer-events: none;
+ .tools {
+ margin-top: 12px;
}
.foot {
display: flex;
diff --git a/frontend/src/tools/inspect/SelectionMenu.svelte b/frontend/src/tools/inspect/SelectionMenu.svelte
index 0fb476d..e64679d 100644
--- a/frontend/src/tools/inspect/SelectionMenu.svelte
+++ b/frontend/src/tools/inspect/SelectionMenu.svelte
@@ -16,6 +16,9 @@
let showGear = $state(false);
const duration = $derived(probeInfo?.duration ?? 0);
+ // one frame at the clip's rate — the difference between a readable plate
+ // and a blurry one (falls back to 30 fps when ffprobe gave none)
+ const frameDur = $derived(probeInfo?.fps ? 1 / probeInfo.fps : 1 / 30);
function fmt(t) {
const m = Math.floor(t / 60);
@@ -73,10 +76,12 @@
</div>
<div class="stepper">
- <button class="btn btn-sm" onclick={() => step(-1)} title="Back 1s">-1s</button>
+ <button class="btn btn-sm" onclick={() => step(-1)} title="Back 1s (Shift+←)">-1s</button>
<button class="btn btn-sm" onclick={() => step(-0.1)} title="Back 0.1s">-0.1</button>
+ <button class="btn btn-sm" onclick={() => step(-frameDur)} title="Back 1 frame (← or ,)">-1f</button>
+ <button class="btn btn-sm" onclick={() => step(frameDur)} title="Forward 1 frame (→ or .)">+1f</button>
<button class="btn btn-sm" onclick={() => step(0.1)} title="Forward 0.1s">+0.1</button>
- <button class="btn btn-sm" onclick={() => step(1)} title="Forward 1s">+1s</button>
+ <button class="btn btn-sm" onclick={() => step(1)} title="Forward 1s (Shift+→)">+1s</button>
</div>
<button class="btn btn-primary w-full" disabled={capturing} onclick={() => grab()}>
@@ -144,7 +149,7 @@
}
.stepper {
display: grid;
- grid-template-columns: repeat(4, 1fr);
+ grid-template-columns: repeat(6, 1fr);
gap: 6px;
}
.w-full {
diff --git a/packaging/azimut.spec b/packaging/azimut.spec
index a27f2f3..bd8afde 100644
--- a/packaging/azimut.spec
+++ b/packaging/azimut.spec
@@ -5,8 +5,9 @@
# 2. Install the package so its data is discoverable: pip install .
# 3. Build: pyinstaller packaging/azimut.spec
#
-# The bundled UI (azimut/static/**) and uvicorn / yt-dlp submodules are collected
-# explicitly because they are loaded dynamically and PyInstaller can't see them.
+# The bundled UI (azimut/static/**) and uvicorn / yt-dlp / gallery-dl submodules
+# are collected explicitly because they are loaded dynamically and PyInstaller
+# can't see them.
from PyInstaller.utils.hooks import collect_data_files, collect_submodules
@@ -14,6 +15,7 @@ hiddenimports = (
collect_submodules("uvicorn")
+ collect_submodules("azimut")
+ collect_submodules("yt_dlp")
+ + collect_submodules("gallery_dl")
)
# Grabs azimut/static/** (index.html, assets, favicon) from the installed package.
diff --git a/pyproject.toml b/pyproject.toml
index ad09d42..38355df 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "azimut"
-version = "0.1.0"
+version = "0.1.1"
description = "The OSINT investigator's workbench — local-first media, geolocation proofs and case management."
readme = "README.md"
requires-python = ">=3.11"
@@ -26,6 +26,8 @@ dependencies = [
"httpx>=0.27",
"pillow>=10.3",
"yt-dlp>=2024.4.9",
+ "gallery-dl>=1.27",
+ "requests>=2.31",
"python-multipart>=0.0.9",
]
diff --git a/scripts/relaunch.sh b/scripts/relaunch.sh
new file mode 100755
index 0000000..c4f035e
--- /dev/null
+++ b/scripts/relaunch.sh
@@ -0,0 +1,23 @@
+#!/usr/bin/env bash
+# One-shot dev relaunch: kill anything running on the azimut ports, rebuild
+# the frontend, and start a single backend process that serves the fresh
+# build directly (no vite dev server, no proxy — just one process).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+
+echo "==> Killing any existing azimut / vite processes"
+pkill -f ".venv/bin/azimut" 2>/dev/null || true
+pkill -f "vite" 2>/dev/null || true
+for port in 8477 5173; do
+ pid=$(lsof -ti:"$port" 2>/dev/null || true)
+ if [ -n "$pid" ]; then
+ kill $pid 2>/dev/null || true
+ fi
+done
+sleep 1
+
+echo "==> Rebuilding frontend"
+(cd frontend && npm run build)
+
+echo "==> Starting azimut on http://127.0.0.1:8477"
+exec .venv/bin/azimut
diff --git a/src/azimut/api/cases.py b/src/azimut/api/cases.py
index 7517f78..c574d9d 100644
--- a/src/azimut/api/cases.py
+++ b/src/azimut/api/cases.py
@@ -8,7 +8,6 @@ from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
from ..engine import media as media_engine
-from ..engine import satellite as satellite_engine
from ..workspace import Case, CaseError
router = APIRouter(prefix="/api/cases", tags=["cases"])
@@ -170,8 +169,9 @@ def remove_entity(case_id: str, entity_id: str) -> dict[str, str]:
etype = entity.get("type")
attrs = entity.get("attrs", {})
- # media has its own delete that drops file + thumbnail + sidecar + entity
- if etype == "media" and attrs.get("path"):
+ # media and satellite captures both live in media/ and share the media
+ # delete: it drops the file + thumbnail + sidecar + entity in one go.
+ if etype in ("media", "capture") and attrs.get("path"):
try:
media_engine.delete_media(case, attrs["path"])
except CaseError as exc:
@@ -179,10 +179,8 @@ def remove_entity(case_id: str, entity_id: str) -> dict[str, str]:
return {"status": "deleted"}
# other artifact-backed types: drop the file(s) before removing the row.
- # captures carry the image; a bare place (no path) has nothing on disk.
- if etype in ("capture", "place") and attrs.get("path"):
- satellite_engine.unlink_capture(case, attrs["path"])
- elif etype == "proof" and attrs.get("spec"):
+ # a bare place (no path) has nothing on disk.
+ if etype == "proof" and attrs.get("spec"):
_unlink_inside(case, attrs["spec"])
_unlink_inside(case, attrs["spec"].removesuffix(".json") + ".png")
elif etype == "post" and attrs.get("draft"):
diff --git a/src/azimut/api/media.py b/src/azimut/api/media.py
index c733d4e..4d72685 100644
--- a/src/azimut/api/media.py
+++ b/src/azimut/api/media.py
@@ -17,6 +17,8 @@ router = APIRouter(prefix="/api", tags=["media"])
class DownloadIn(BaseModel):
url: HttpUrl
+ index: int | None = None
+ title: str | None = None
class DeleteIn(BaseModel):
@@ -46,6 +48,7 @@ async def upload(case_id: str, file: UploadFile) -> dict[str, Any]:
def download(case_id: str, body: DownloadIn) -> dict[str, str]:
case = get_case(case_id)
url = str(body.url)
+ index, title = body.index, body.title
def work(set_progress):
def hook(d):
@@ -61,7 +64,7 @@ def download(case_id: str, body: DownloadIn) -> dict[str, str]:
elif d.get("status") == "finished":
set_progress({"percent": 100, "stage": "processing"})
- return media_engine.download_url(case, url, progress_hook=hook)
+ return media_engine.download_url(case, url, progress_hook=hook, index=index, title=title)
job_id = jobs.start("download", work)
return {"job_id": job_id}
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index 72d7629..6783cd7 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -1,15 +1,18 @@
-"""REST API for the Satellite tool: providers, capture crops, list captures."""
+"""REST API for the Satellite tool: providers, tile proxy, capture crops."""
from __future__ import annotations
-import json
from datetime import datetime, timezone
from typing import Any
+import httpx
from fastapi import APIRouter, HTTPException
+from fastapi.responses import Response
from pydantic import BaseModel, Field
-from ..engine import geo, satellite as satellite_engine, tiles
+from .. import config
+from ..engine import geo, google_tiles, media as media_engine, satellite as satellite_engine, tiles
+from ..workspace import CaseError
from .cases import get_case
router = APIRouter(prefix="/api", tags=["satellite"])
@@ -19,14 +22,17 @@ class CaptureIn(BaseModel):
lat: float = Field(ge=-90, le=90) # crop frame center
lon: float = Field(ge=-180, le=180)
zoom: int = Field(ge=1, le=22)
- width: int = Field(default=1000, ge=256, le=2048)
- height: int = Field(default=700, ge=256, le=2048)
+ width: int = Field(default=1000, ge=256, le=tiles.SIZE_MAX)
+ height: int = Field(default=700, ge=256, le=tiles.SIZE_MAX)
provider: str = "esri-world-imagery"
bearing: float = Field(default=0.0, ge=0, le=360)
+ # acquisition date of the underlying imagery (Esri best-effort), resolved
+ # client-side and recorded next to the capture timestamp (fetched_at)
+ imagery_date: str | None = None
# marker (recorded point of interest): style + optional offset from center
marker_style: str = Field(default="crosshair", pattern="^(crosshair|pin|none)$")
- marker_x: int = Field(default=0, ge=-2048, le=2048)
- marker_y: int = Field(default=0, ge=-2048, le=2048)
+ marker_x: int = Field(default=0, ge=-tiles.SIZE_MAX, le=tiles.SIZE_MAX)
+ marker_y: int = Field(default=0, ge=-tiles.SIZE_MAX, le=tiles.SIZE_MAX)
marker_lat: float | None = Field(default=None, ge=-90, le=90)
marker_lon: float | None = Field(default=None, ge=-180, le=180)
@@ -60,11 +66,79 @@ def providers() -> list[dict[str, Any]]:
"attribution": p.attribution,
"max_zoom": p.max_zoom,
"needs_key": p.needs_key,
+ "imagery": p.imagery,
+ "capturable": p.capturable,
+ "cacheable": p.cacheable,
+ "session": p.session,
+ "meter": p.meter,
+ "tile_size": p.tile_size,
}
for p in tiles.all_providers()
]
[email protected]("/tiles/{provider_id}/{z}/{x}/{y}")
+def tile_proxy(provider_id: str, z: int, x: int, y: int) -> Response:
+ """Live-map tiles for keyed providers, proxied through the app.
+
+ Two reasons (docs/KEYED_PROVIDERS.md §3/§6): the API key and Google session
+ token never reach the browser, and the meter counts *exactly* what the
+ provider bills — one bump per tile actually served; a browser cache hit
+ never reaches this endpoint, so it never over-counts. Nothing is stored
+ server-side: the provider's own Cache-Control is passed through untouched.
+ """
+ try:
+ provider = tiles.get_provider(provider_id)
+ except KeyError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+
+ upstream: httpx.Response | None = None
+ for attempt in (1, 2):
+ try:
+ url = tiles.resolve_url(provider).format(x=x, y=y, z=z)
+ except tiles.TileFetchError as exc:
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
+ try:
+ upstream = httpx.get(
+ url, headers={"User-Agent": tiles.USER_AGENT}, timeout=20,
+ follow_redirects=True,
+ )
+ except httpx.HTTPError as exc:
+ raise HTTPException(status_code=502, detail=f"tile fetch failed: {exc}") from exc
+ # a stale Google session token answers 401/403 — re-mint once, transparently
+ if attempt == 1 and provider.session and upstream.status_code in (401, 403):
+ google_tiles.invalidate(google_tiles.key_from_url(provider.url))
+ continue
+ break
+
+ if provider.meter and upstream.status_code < 400:
+ config.record_usage(provider.meter, 1)
+ headers = {}
+ if upstream.headers.get("cache-control"):
+ headers["Cache-Control"] = upstream.headers["cache-control"]
+ return Response(
+ content=upstream.content,
+ status_code=upstream.status_code,
+ media_type=upstream.headers.get("content-type", "image/png"),
+ headers=headers,
+ )
+
+
[email protected]("/satellite/imagery-date")
+def imagery_date(lat: float, lon: float, zoom: int, provider: str = "esri-world-imagery") -> dict[str, Any]:
+ """Best-effort acquisition date of the imagery under a point.
+
+ Only Esri World Imagery exposes per-scene capture dates; for any other
+ provider we report ``supported: false`` so the UI can hide the readout.
+ """
+ if provider != "esri-world-imagery":
+ return {"supported": False, "date": None, "source": None}
+ result = tiles.esri_capture_date(lat, lon, int(zoom))
+ if result is None: # metadata service unreachable
+ return {"supported": True, "date": None, "source": None}
+ return {"supported": True, **result}
+
+
@router.post("/geo/parse")
def parse_coordinates(body: ParseIn) -> dict[str, Any]:
coords = geo.parse_coords(body.text)
@@ -80,6 +154,17 @@ def parse_coordinates(body: ParseIn) -> dict[str, Any]:
}
[email protected]("/geo/geocode")
+def geocode(q: str) -> dict[str, Any]:
+ query = q.strip()
+ if not query:
+ raise HTTPException(status_code=422, detail="empty query")
+ result = geo.geocode(query)
+ if not result:
+ raise HTTPException(status_code=404, detail="no match for that place name")
+ return result
+
+
@router.get("/geo/reverse")
def reverse(lat: float, lon: float) -> dict[str, Any]:
result = geo.reverse_geocode(lat, lon)
@@ -108,36 +193,39 @@ def capture(case_id: str, body: CaptureIn) -> dict[str, Any]:
except Exception as exc: # network / provider failure
raise HTTPException(status_code=502, detail=f"tile fetch failed: {exc}") from exc
- stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
- name = f"sat_{stamp}_z{provenance['zoom']}_{provider.id}.png"
- rel_path = f"satellite/{name}"
- sat_dir = case.subdir("satellite")
- image.save(sat_dir / name, "PNG")
# the recorded point is the marker (== center unless it was moved off-center)
marker_lat, marker_lon = provenance["lat"], provenance["lon"]
label = satellite_engine.coords_label(marker_lat, marker_lon)
- provenance["filename"] = name
- provenance["title"] = label
- provenance["plus_code"] = geo.plus_code(marker_lat, marker_lon)
+ plus_code = geo.plus_code(marker_lat, marker_lon)
+ provenance["plus_code"] = plus_code
provenance["dms"] = geo.to_dms(marker_lat, marker_lon)
- (sat_dir / f"{name}.json").write_text(
- json.dumps(provenance, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
- )
+ # two dates ride with a capture: fetched_at (when it was captured, set by
+ # fetch_crop) and imagery_date (when the satellite scene was shot, if known)
+ provenance["imagery_date"] = (body.imagery_date or "").strip() or None
- # a capture is an image artifact, mirrored by one ``capture`` entity tied by
- # its path (spec §3.5) — it carries the marker's coordinates as info but is
- # not a navigable point; saving a ``place`` (below) is the separate act for that
- case.add_entity(
- "capture",
- label,
- attrs={"coords": label, "lat": marker_lat, "lon": marker_lon,
- "plus_code": provenance["plus_code"], "path": rel_path,
- "zoom": provenance["zoom"], "bearing": body.bearing},
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
+ filename = f"sat_{stamp}_z{provenance['zoom']}_{provider.id}.png"
+
+ # A capture is filed through the media pipeline so it lands in media/ (hashed,
+ # thumbnailed, shown in the Media Library, openable in Inspect), but under a
+ # ``capture`` entity carrying its coordinates (spec §3.5). The full capture
+ # provenance rides on the media sidecar's ``source`` (type "satellite").
+ result = media_engine.import_image(
+ case,
+ image,
+ filename,
+ {"type": "satellite", **provenance},
by="satellite",
- status="confirmed",
+ entity_type="capture",
+ extra_attrs={
+ "coords": label, "lat": marker_lat, "lon": marker_lon,
+ "plus_code": plus_code, "zoom": provenance["zoom"], "bearing": body.bearing,
+ },
+ title=label,
+ dedupe=False, # a capture is 1:1 with its entity — never collapse re-captures
)
- return {"path": rel_path, **provenance}
+ return {"path": result["item"]["path"], "title": label, **provenance}
@router.post("/cases/{case_id}/satellite/place")
@@ -162,40 +250,34 @@ def list_captures(case_id: str) -> list[dict[str, Any]]:
@router.delete("/cases/{case_id}/satellite")
def delete_capture(case_id: str, path: str) -> dict[str, str]:
- # also drops the mirrored place entity when its last capture is gone
- satellite_engine.delete_capture(get_case(case_id), path)
+ # a capture is a media item: this drops the file + thumbnail + sidecar + entity
+ case = get_case(case_id)
+ try:
+ media_engine.delete_media(case, path)
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
return {"status": "deleted"}
@router.patch("/cases/{case_id}/satellite")
def update_capture(case_id: str, body: SatelliteUpdateIn) -> dict[str, Any]:
case = get_case(case_id)
- try:
- image_path = case.resolve_inside(body.path)
- except Exception as exc:
- raise HTTPException(status_code=400, detail=str(exc)) from exc
-
- sidecar_path = image_path.with_name(image_path.name + ".json")
- if not sidecar_path.exists():
+ item = media_engine.read_item(case, body.path)
+ if item is None:
raise HTTPException(status_code=404, detail="capture not found")
-
- data = json.loads(sidecar_path.read_text(encoding="utf-8"))
+ patch: dict[str, Any] = {}
if body.notes is not None:
- if body.notes == "":
- data.pop("notes", None)
- else:
- data["notes"] = body.notes
+ patch["notes"] = body.notes
+ # empty title falls back to the coordinates (mirrored onto the entity label)
if body.title is not None:
- # empty title falls back to the coordinates; keep entity label in sync
- title = body.title.strip() or satellite_engine.coords_label(
- data["lat"], data["lon"]
+ source = item.get("source") or {}
+ patch["title"] = body.title.strip() or satellite_engine.coords_label(
+ source.get("lat"), source.get("lon")
)
- data["title"] = title
- entity = case.find_entity(attr="path", value=body.path)
- if entity:
- case.update_entity(entity["id"], {"label": title})
- sidecar_path.write_text(
- json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
- )
- data["path"] = body.path
- return data
+ try:
+ updated = media_engine.update_media(case, body.path, patch)
+ except (ValueError, CaseError) as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ # flatten the capture provenance up, like the listing does, so the client
+ # gets the same shape back as GET /satellite
+ return {**(updated.get("source") or {}), **updated}
diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.py
new file mode 100644
index 0000000..dca2ff7
--- /dev/null
+++ b/src/azimut/api/settings.py
@@ -0,0 +1,81 @@
+"""REST API for app-wide settings: API keys and per-provider usage counters.
+
+Keys are the user's own billing identity (docs/KEYED_PROVIDERS.md §0): stored
+locally in settings.json, app-wide (never per-case), never written into a case
+folder or export bundle. Usage counters are local bookkeeping only.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import httpx
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel
+
+from .. import config
+from ..engine import google_tiles, tiles
+
+router = APIRouter(prefix="/api", tags=["settings"])
+
+# the keyed providers the settings tab manages — matching api_keys entries
+# light up the built-in basemaps (engine/tiles.py all_providers)
+KEYED_PROVIDERS = ("mapbox", "google")
+
+
+class KeysIn(BaseModel):
+ # None = leave untouched; "" (or whitespace) = remove the stored key
+ mapbox: str | None = None
+ google: str | None = None
+
+
[email protected]("/settings")
+def get_settings() -> dict[str, Any]:
+ settings = config.load_settings()
+ return {
+ "api_keys": settings.get("api_keys", {}),
+ "usage": settings.get("usage", {}),
+ "month": config.month_key(),
+ }
+
+
[email protected]("/settings/keys")
+def put_keys(body: KeysIn) -> dict[str, Any]:
+ settings = config.load_settings()
+ keys = settings.setdefault("api_keys", {})
+ for name in KEYED_PROVIDERS:
+ value = getattr(body, name)
+ if value is None:
+ continue
+ value = value.strip()
+ if value:
+ keys[name] = value
+ else:
+ keys.pop(name, None)
+ config.save_settings(settings)
+ return {"api_keys": keys}
+
+
[email protected]("/settings/keys/{provider}/test")
+def test_key(provider: str) -> dict[str, Any]:
+ """Exercise the saved key against the real service — never raises on a bad
+ key, so the settings tab can show the provider's error message inline."""
+ key = (config.load_settings().get("api_keys") or {}).get(provider)
+ if not key:
+ raise HTTPException(status_code=404, detail=f"no {provider} key saved")
+ if provider == "google":
+ try:
+ google_tiles.invalidate(key) # force a fresh mint — that's the test
+ google_tiles.session_token(key)
+ return {"ok": True, "detail": "session token created"}
+ except Exception as exc:
+ return {"ok": False, "detail": str(exc)}
+ if provider == "mapbox":
+ url = tiles.MAPBOX_SATELLITE_URL.replace("{key}", key).format(z=0, x=0, y=0)
+ try:
+ response = httpx.get(url, headers={"User-Agent": tiles.USER_AGENT}, timeout=10)
+ response.raise_for_status()
+ return {"ok": True, "detail": "tile fetched"}
+ except Exception as exc:
+ return {"ok": False, "detail": str(exc)}
+ raise HTTPException(status_code=404, detail=f"unknown keyed provider '{provider}'")
diff --git a/src/azimut/config.py b/src/azimut/config.py
index b678269..b6c8556 100644
--- a/src/azimut/config.py
+++ b/src/azimut/config.py
@@ -15,6 +15,8 @@ from __future__ import annotations
import json
import os
+import threading
+from datetime import datetime, timezone
from pathlib import Path
from typing import Any
@@ -23,7 +25,12 @@ DEFAULT_SETTINGS: dict[str, Any] = {
# Each: {"id", "label", "url" ({x}/{y}/{z} template), "attribution", "max_zoom"}
"tile_providers": [],
# Optional user-supplied API keys, keyed by provider id. Never required.
+ # Built-in keyed providers (Mapbox, Google) read their token from here:
+ # "mapbox": "pk....", "google": "AIza...".
"api_keys": {},
+ # Per-provider monthly tile-request counters: {"<provider_id>": {"YYYY-MM": count}}.
+ # Local bookkeeping only, for billed keyed providers (Mapbox, Google).
+ "usage": {},
}
@@ -67,3 +74,27 @@ def save_settings(settings: dict[str, Any]) -> None:
settings_path().write_text(
json.dumps(settings, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
)
+
+
+def month_key(when: datetime | None = None) -> str:
+ """The usage-counter bucket for a moment in time: "YYYY-MM" (UTC)."""
+ return (when or datetime.now(timezone.utc)).strftime("%Y-%m")
+
+
+_usage_lock = threading.Lock() # tile proxy bumps the counter from many threads
+
+
+def record_usage(meter: str, count: int = 1, when: datetime | None = None) -> int:
+ """Bump a provider's tile counter for the month; returns the new total.
+
+ Local bookkeeping only (docs/KEYED_PROVIDERS.md §6): billed keyed providers
+ (Mapbox, Google) get a per-month tally so the user can watch their quota.
+ No telemetry — the counter never leaves settings.json.
+ """
+ with _usage_lock:
+ settings = load_settings()
+ per_month = settings.setdefault("usage", {}).setdefault(meter, {})
+ bucket = month_key(when)
+ per_month[bucket] = int(per_month.get(bucket, 0)) + int(count)
+ save_settings(settings)
+ return per_month[bucket]
diff --git a/src/azimut/engine/geo.py b/src/azimut/engine/geo.py
index 41cf5e2..1a87b84 100644
--- a/src/azimut/engine/geo.py
+++ b/src/azimut/engine/geo.py
@@ -93,15 +93,42 @@ def map_links(lat: float, lon: float, zoom: int = 17) -> dict[str, str]:
return {
"google": f"https://www.google.com/maps/@{lat},{lon},{zoom}z",
"google_sat": f"https://www.google.com/maps/@{lat},{lon},2000m/data=!3m1!1e3",
+ "google_earth": f"https://earth.google.com/web/@{lat},{lon},0a,1000d,35y,0h,0t,0r",
"osm": f"https://www.openstreetmap.org/?mlat={lat}&mlon={lon}#map={zoom}/{lat}/{lon}",
"bing": f"https://www.bing.com/maps?cp={lat}~{lon}&lvl={zoom}&style=h",
"yandex": f"https://yandex.com/maps/?ll={lon},{lat}&z={zoom}&l=sat",
+ "sentinel": f"https://browser.dataspace.copernicus.eu/?zoom={zoom}&lat={lat}&lng={lon}",
+ "zoom_earth": f"https://zoom.earth/#view={lat},{lon},{zoom}z",
}
# -- reverse geocoding (Nominatim, polite) ------------------------------------------
+def geocode(query: str) -> dict[str, Any] | None:
+ """Best-effort forward geocoding via Nominatim. Returns None on any failure."""
+ try:
+ response = httpx.get(
+ "https://nominatim.openstreetmap.org/search",
+ params={"q": query, "format": "jsonv2", "limit": 1},
+ headers={"User-Agent": USER_AGENT},
+ timeout=8,
+ )
+ response.raise_for_status()
+ results = response.json()
+ if not results:
+ return None
+ top = results[0]
+ return {
+ "lat": float(top["lat"]),
+ "lon": float(top["lon"]),
+ "display_name": top.get("display_name"),
+ "attribution": "© OpenStreetMap contributors (Nominatim)",
+ }
+ except Exception:
+ return None
+
+
def reverse_geocode(lat: float, lon: float) -> dict[str, Any] | None:
"""Best-effort place name via Nominatim. Returns None on any failure."""
try:
diff --git a/src/azimut/engine/google_tiles.py b/src/azimut/engine/google_tiles.py
new file mode 100644
index 0000000..f81d437
--- /dev/null
+++ b/src/azimut/engine/google_tiles.py
@@ -0,0 +1,126 @@
+"""Google Map Tiles API session-token adapter (docs/KEYED_PROVIDERS.md §3).
+
+Google satellite tiles are not a static XYZ URL: a client first mints a
+short-lived *session token* (createSession), then requests standard slippy
+tiles with ``session`` + ``key`` query params. This module mints and caches
+that token in memory — the token only, never tiles: Google's Map Tiles API
+policies forbid caching/storing tiles — and hands the rest of the pipeline a
+plain XYZ template.
+
+Attribution is dynamic: the viewport endpoint returns the exact copyright line
+for the mapped area (e.g. "Map data ©2026 Google, Maxar Technologies"), which
+every capture must carry unmodified, burned into its footer.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from typing import Any, Callable
+from urllib.parse import parse_qs, urlsplit
+
+import httpx
+
+CREATE_SESSION_URL = "https://tile.googleapis.com/v1/createSession"
+VIEWPORT_URL = "https://tile.googleapis.com/tile/v1/viewport"
+# mapType is part of the token's identity — a satellite session only serves
+# satellite tiles. Only this one kind is minted today.
+SESSION_BODY = {"mapType": "satellite", "language": "en-US", "region": "US"}
+EXPIRY_SLACK = 60 # refresh this many seconds before the reported expiry
+
+_lock = threading.Lock()
+_sessions: dict[str, dict[str, Any]] = {} # api key → {"session", "expiry"}
+
+
+class GoogleSessionError(Exception):
+ pass
+
+
+def _mint(key: str, post: Callable[..., Any] | None) -> dict[str, Any]:
+ response = (post or httpx.post)(
+ CREATE_SESSION_URL, params={"key": key}, json=SESSION_BODY, timeout=15
+ )
+ response.raise_for_status()
+ data = response.json()
+ if not data.get("session"):
+ raise GoogleSessionError("createSession response carried no session token")
+ return {"session": data["session"], "expiry": int(data.get("expiry") or 0)}
+
+
+def session_token(
+ key: str,
+ *,
+ post: Callable[..., Any] | None = None,
+ now: Callable[[], float] | None = None,
+) -> str:
+ """Current session token for this key — minted once, refreshed near expiry."""
+ clock = now or time.time
+ with _lock:
+ cached = _sessions.get(key)
+ if cached and cached["expiry"] - EXPIRY_SLACK > clock():
+ return cached["session"]
+ fresh = _mint(key, post)
+ _sessions[key] = fresh
+ return fresh["session"]
+
+
+def invalidate(key: str) -> None:
+ """Drop the cached token (e.g. after a 401/403) so the next call re-mints."""
+ with _lock:
+ _sessions.pop(key, None)
+
+
+def key_from_url(url: str) -> str:
+ """The ``key=`` query param of a Google tile URL template."""
+ values = parse_qs(urlsplit(url).query).get("key")
+ if not values or not values[0]:
+ raise GoogleSessionError("no key= in Google tile URL template")
+ return values[0]
+
+
+def resolve_template(
+ url_template: str,
+ *,
+ post: Callable[..., Any] | None = None,
+ now: Callable[[], float] | None = None,
+) -> str:
+ """Replace ``{session}`` in a Google tile URL template with a live token."""
+ token = session_token(key_from_url(url_template), post=post, now=now)
+ return url_template.replace("{session}", token)
+
+
+def viewport_copyright(
+ key: str,
+ zoom: int,
+ north: float,
+ south: float,
+ east: float,
+ west: float,
+ *,
+ get: Callable[..., Any] | None = None,
+ post: Callable[..., Any] | None = None,
+) -> str | None:
+ """The exact copyright line for a viewport, or None if unavailable.
+
+ Never raises: attribution falls back to the provider's static string when
+ the endpoint can't be reached — the capture still carries attribution.
+ """
+ try:
+ token = session_token(key, post=post)
+ response = (get or httpx.get)(
+ VIEWPORT_URL,
+ params={
+ "session": token,
+ "key": key,
+ "zoom": int(zoom),
+ "north": north,
+ "south": south,
+ "east": east,
+ "west": west,
+ },
+ timeout=8,
+ )
+ response.raise_for_status()
+ return response.json().get("copyright") or None
+ except Exception:
+ return None
diff --git a/src/azimut/engine/media.py b/src/azimut/engine/media.py
index b888a4d..635f12d 100644
--- a/src/azimut/engine/media.py
+++ b/src/azimut/engine/media.py
@@ -13,6 +13,7 @@ import mimetypes
import re
import shutil
import subprocess
+import uuid
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, BinaryIO
@@ -24,6 +25,10 @@ from ..workspace import Case
THUMB_DIR = ".thumbs"
THUMB_MAX = 512
SIDECAR_SUFFIX = ".azimut.json"
+# a post's attachments (photos on a tweet, an album, …) fit comfortably under
+# this; above it, treat the link as a real playlist and just grab its first
+# item, same as the old noplaylist behavior — no picker with hundreds of rows
+MAX_PICKER_ITEMS = 20
def _now() -> str:
@@ -107,19 +112,35 @@ def _write_sidecar(media_path: Path, data: dict[str, Any]) -> None:
def _register(
- case: Case, media_path: Path, source: dict[str, Any], *, by: str = "media-library"
+ case: Case,
+ media_path: Path,
+ source: dict[str, Any],
+ *,
+ by: str = "media-library",
+ entity_type: str = "media",
+ extra_attrs: dict[str, Any] | None = None,
+ title: str | None = None,
+ dedupe: bool = True,
) -> dict[str, Any]:
- """Hash + sidecar + thumbnail + media entity. Dedupes on sha256.
+ """Hash + sidecar + thumbnail + entity. Dedupes on sha256 by default.
``by`` records which tool produced the item (media-library import, inspect
- derivative, …) on the media entity's provenance (spec §6 honest output).
+ derivative, satellite capture, …) on the entity's provenance (spec §6 honest
+ output). ``entity_type`` lets a producer file the item under a more specific
+ type than the generic ``media`` (e.g. a satellite ``capture``) while it still
+ lives in ``media/`` and shows up in the Media Library; ``extra_attrs`` are
+ merged onto that entity (coordinates, zoom, …) and ``title`` seeds the display
+ label/sidecar title. ``dedupe=False`` keeps every registration a distinct
+ item even when the bytes match an existing one — satellite captures are 1:1
+ with their entity (spec §3.5), so re-capturing the same view is two captures.
"""
digest = sha256_file(media_path)
- existing = case.find_entity(attr="sha256", value=digest)
- if existing:
- media_path.unlink() # identical bytes already in the case
- return {"duplicate": True, "entity": existing, "item": read_item(case, existing["attrs"]["path"])}
+ if dedupe:
+ existing = case.find_entity(attr="sha256", value=digest)
+ if existing:
+ media_path.unlink() # identical bytes already in the case
+ return {"duplicate": True, "entity": existing, "item": read_item(case, existing["attrs"]["path"])}
rel_path = f"media/{media_path.name}"
thumb = case.subdir("media") / THUMB_DIR / (media_path.name + ".jpg")
@@ -134,12 +155,20 @@ def _register(
"source": source,
"thumbnail": f"media/{THUMB_DIR}/{media_path.name}.jpg" if has_thumb else None,
}
+ if title:
+ sidecar["title"] = title
_write_sidecar(media_path, sidecar)
entity = case.add_entity(
- "media",
- media_path.name,
- attrs={"path": rel_path, "sha256": digest, **({"source_url": source["url"]} if source.get("url") else {})},
+ entity_type,
+ title or media_path.name,
+ attrs={
+ "path": rel_path,
+ "sha256": digest,
+ "kind": sidecar["kind"],
+ **({"source_url": source["url"]} if source.get("url") else {}),
+ **(extra_attrs or {}),
+ },
by=by,
source=source.get("url"),
)
@@ -156,13 +185,25 @@ def import_stream(case: Case, filename: str, stream: BinaryIO) -> dict[str, Any]
def import_image(
- case: Case, image: Image.Image, filename: str, source: dict[str, Any], *, by: str = "inspect"
+ case: Case,
+ image: Image.Image,
+ filename: str,
+ source: dict[str, Any],
+ *,
+ by: str = "inspect",
+ entity_type: str = "media",
+ extra_attrs: dict[str, Any] | None = None,
+ title: str | None = None,
+ dedupe: bool = True,
) -> dict[str, Any]:
"""File a freshly rendered PIL image into the case as a media derivative.
Used by tools that produce new imagery from existing media (frame capture,
- adjustments, collages). The ``source`` dict records the derivation so the
- output stays auditable back to its origin (spec §6).
+ adjustments, collages, satellite crops). The ``source`` dict records the
+ derivation so the output stays auditable back to its origin (spec §6).
+ ``entity_type``/``extra_attrs``/``title``/``dedupe`` are forwarded to
+ :func:`_register` so e.g. a satellite crop files under a ``capture`` entity
+ carrying its coordinates while still landing in ``media/``.
"""
media_dir = case.subdir("media")
name = safe_filename(filename)
@@ -172,7 +213,10 @@ def import_image(
# Preserve an alpha channel (e.g. a transparent collage canvas); everything
# else is flattened to RGB. The thumbnail stage composites alpha over black.
image.save(dest, "PNG") if image.mode == "RGBA" else image.convert("RGB").save(dest, "PNG")
- return _register(case, dest, source, by=by)
+ return _register(
+ case, dest, source, by=by, entity_type=entity_type,
+ extra_attrs=extra_attrs, title=title, dedupe=dedupe,
+ )
def import_produced_file(
@@ -190,21 +234,225 @@ def import_produced_file(
return _register(case, dest, source, by=by)
-def download_url(case: Case, url: str, progress_hook=None) -> dict[str, Any]:
- """Download a URL via yt-dlp into the case. Blocking — run in a worker."""
+def _picker_items(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ items = []
+ for i, entry in enumerate(entries, start=1):
+ thumb = entry.get("thumbnail")
+ if not thumb and entry.get("thumbnails"):
+ thumb = entry["thumbnails"][-1].get("url")
+ items.append(
+ {
+ "index": i,
+ "title": entry.get("title") or entry.get("id") or f"item {i}",
+ "thumbnail": thumb,
+ "kind": media_kind(f"file.{entry['ext']}") if entry.get("ext") else "file",
+ }
+ )
+ return items
+
+
+def _register_downloaded_item(
+ case: Case,
+ post_url: str,
+ filename: str,
+ content: bytes,
+ *,
+ title: str | None,
+ source_extra: dict[str, Any],
+) -> dict[str, Any]:
+ """Shared tail for the non-yt-dlp download paths (gallery-dl, the Telegram
+ photo scraper): write ``content`` into the case's media dir, register it,
+ and apply the display title — same bookkeeping ``download_url`` does for
+ its own yt-dlp path, minus the yt-dlp-specific extraction bits."""
+ media_dir = case.subdir("media")
+ tmp_dir = media_dir / ".dl" / uuid.uuid4().hex
+ tmp_dir.mkdir(parents=True, exist_ok=True)
+ try:
+ fname = safe_filename(filename)
+ tmp_path = tmp_dir / fname
+ tmp_path.write_bytes(content)
+ dest = unique_path(media_dir, fname)
+ shutil.move(str(tmp_path), str(dest))
+ finally:
+ shutil.rmtree(tmp_dir, ignore_errors=True)
+
+ source = {"type": "download", "url": post_url, "webpage_url": post_url, **source_extra}
+ result = _register(case, dest, source)
+ display_title = (title or "").strip() or source_extra.get("title")
+ if not result["duplicate"] and display_title:
+ result["item"] = update_media(case, result["item"]["path"], {"title": display_title})
+ result["multi"] = False
+ return result
+
+
+def _gallery_dl_item(file_url: str, kwdict: dict[str, Any]) -> dict[str, Any]:
+ content = (kwdict.get("content") or kwdict.get("description") or "").strip()
+ first_line = content.splitlines()[0][:120] if content else None
+ filename = kwdict.get("filename") or "file"
+ ext = kwdict.get("extension") or ""
+ date = kwdict.get("date")
+ author = kwdict.get("author") or kwdict.get("user") or {}
+ return {
+ "url": file_url,
+ "filename": filename,
+ "extension": ext,
+ "kind": media_kind(f"file.{ext}") if ext else "file",
+ "title": first_line or filename,
+ "description": content or None,
+ "uploader": author.get("nick") or author.get("name"),
+ "upload_date": date.strftime("%Y%m%d") if hasattr(date, "strftime") else None,
+ }
+
+
+def _register_gallery_dl_item(
+ case: Case, extractor, post_url: str, item: dict[str, Any], *, title: str | None = None
+) -> dict[str, Any]:
+ resp = extractor.request(item["url"])
+ fname = f"{item['filename']}.{item['extension']}" if item["extension"] else item["filename"]
+ return _register_downloaded_item(
+ case,
+ post_url,
+ fname,
+ resp.content,
+ title=title,
+ source_extra={
+ "downloader": "gallery-dl",
+ "title": item["title"],
+ "description": item.get("description"),
+ "uploader": item.get("uploader"),
+ "upload_date": item.get("upload_date"),
+ "extractor": "gallery-dl",
+ },
+ )
+
+
+def _download_via_gallery_dl(
+ case: Case, url: str, *, index: int | None = None, title: str | None = None
+) -> dict[str, Any]:
+ """Fallback for links yt-dlp can't extract at all.
+
+ yt-dlp's extractors are video-first — X/Twitter, for one, explicitly
+ drops photos from what it reports. gallery-dl covers standalone images
+ instead: photo tweets, direct image links, Instagram posts, Facebook
+ photos. Used when yt-dlp raises (e.g. "No video could be found").
+ """
+ import gallery_dl.extractor as gdl_extractor
+
+ extractor = gdl_extractor.find(url)
+ if extractor is None:
+ raise RuntimeError(f"no extractor (yt-dlp or gallery-dl) recognizes this link: {url}")
+
+ items = [_gallery_dl_item(msg[1], msg[2]) for msg in extractor if msg[0] == 3] # Message.Url
+ if not items:
+ raise RuntimeError("gallery-dl found no downloadable media at this link")
+
+ if index is None and 1 < len(items) <= MAX_PICKER_ITEMS:
+ return {
+ "multi": True,
+ "items": [
+ {"index": i, "title": it["title"], "thumbnail": it["url"], "kind": it["kind"]}
+ for i, it in enumerate(items, start=1)
+ ],
+ }
+
+ picked = items[(index or 1) - 1]
+ return _register_gallery_dl_item(case, extractor, url, picked, title=title)
+
+
+_TELEGRAM_POST_RE = re.compile(r"^https?://(www\.)?(t|telegram)\.me/[^/]+/\d+")
+
+
+def _telegram_extra_photos(url: str) -> list[dict[str, Any]]:
+ """yt-dlp's Telegram extractor only regex-matches ``<video>`` players in
+ the public embed page — it has no notion of photos at all, so a mixed
+ video+photo album silently loses its photos (verified against a real
+ post: 2 videos + 2 photos in the HTML, yt-dlp reports only the 2 videos).
+ gallery-dl has no Telegram extractor either. Scrape the same embed page
+ ourselves for photo attachments to fill that gap. Best-effort: any
+ failure (markup change, non-Telegram URL, network hiccup) yields ``[]``
+ rather than breaking the main download flow.
+ """
+ if not _TELEGRAM_POST_RE.match(url):
+ return []
+ import requests
+
+ try:
+ embed_url = url.split("?")[0] + "?embed=1&single"
+ resp = requests.get(embed_url, headers={"User-Agent": "Mozilla/5.0"}, timeout=15)
+ resp.raise_for_status()
+ html = resp.text
+ except Exception:
+ return []
+
+ urls = re.findall(
+ r"tgme_widget_message_photo_wrap[^\"]*\"[^>]*background-image:url\('([^']+)'\)", html
+ )
+ return [{"url": u} for u in dict.fromkeys(urls)] # de-dup, keep order
+
+
+def _register_telegram_photo(
+ case: Case, post_url: str, photo: dict[str, Any], *, title: str | None = None
+) -> dict[str, Any]:
+ import requests
+
+ resp = requests.get(photo["url"], headers={"User-Agent": "Mozilla/5.0"}, timeout=30)
+ resp.raise_for_status()
+ ext = mimetypes.guess_extension((resp.headers.get("content-type") or "").split(";")[0]) or ".jpg"
+ return _register_downloaded_item(
+ case,
+ post_url,
+ f"{uuid.uuid4().hex[:10]}{ext}",
+ resp.content,
+ title=title,
+ source_extra={
+ "downloader": "telegram-scrape",
+ "title": photo.get("title") or "Telegram photo",
+ "extractor": "telegram-scrape",
+ },
+ )
+
+
+def download_url(
+ case: Case, url: str, progress_hook=None, *, index: int | None = None, title: str | None = None
+) -> dict[str, Any]:
+ """Resolve and download a URL via yt-dlp. Blocking — run in a worker.
+
+ One extraction total (plus, for Telegram links, one lightweight extra
+ fetch — see ``_telegram_extra_photos``). Without ``index``, a post with
+ several attachments (a tweet with several photos, a mixed Telegram
+ album, …) is *not* downloaded — ``{"multi": True, "items": [...]}`` is
+ returned instead so the caller can show a picker and call back with the
+ chosen ``index`` (1-based, in picker order). ``title`` overrides the
+ sidecar's display title; it defaults to the extracted one.
+
+ Falls back to gallery-dl (see ``_download_via_gallery_dl``) for links
+ yt-dlp can't extract at all — most commonly image-only posts.
+ """
import yt_dlp
media_dir = case.subdir("media")
- tmp_dir = media_dir / ".dl"
- tmp_dir.mkdir(exist_ok=True)
+ # a unique subdir per call — concurrent downloads (the multi-item picker
+ # fires one per selected item) must not share a scratch dir, or the first
+ # one to finish rmtree()s it out from under the others still writing to it
+ tmp_dir = media_dir / ".dl" / uuid.uuid4().hex
+ tmp_dir.mkdir(parents=True, exist_ok=True)
+
+ extra_photos = _telegram_extra_photos(url) # [] — and free — for non-Telegram links
ydl_opts = {
"outtmpl": str(tmp_dir / "%(title).120B [%(id)s].%(ext)s"),
- "noplaylist": True,
"quiet": True,
"no_warnings": True,
"restrictfilenames": False,
}
+ # Narrow yt-dlp to the one picked entry, as an optimization, ONLY when
+ # we're sure the index refers to one of its own entries (i.e. there are
+ # no extra Telegram photos whose indices would otherwise collide with it).
+ # When narrowed, yt-dlp itself filters `entries` down to that one item, so
+ # it must be addressed as entries[0] below, not by the original index.
+ narrowed = index is not None and not extra_photos
+ if narrowed:
+ ydl_opts["playlist_items"] = str(index)
if not ffmpeg_available():
# without ffmpeg yt-dlp cannot merge separate audio+video streams
ydl_opts["format"] = "best[acodec!=none][vcodec!=none]/best"
@@ -212,7 +460,60 @@ def download_url(case: Case, url: str, progress_hook=None) -> dict[str, Any]:
ydl_opts["progress_hooks"] = [progress_hook]
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
- info = ydl.extract_info(url, download=True)
+ try:
+ info = ydl.extract_info(url, download=False)
+ entries = [e for e in (info.get("entries") or []) if e]
+ except yt_dlp.utils.DownloadError:
+ info = None
+ entries = []
+
+ if narrowed:
+ if info is None and not entries:
+ shutil.rmtree(tmp_dir, ignore_errors=True)
+ return _download_via_gallery_dl(case, url, index=index, title=title)
+ target_info = entries[0] if entries else info
+ else:
+ yt_count = len(entries) if entries else (1 if info is not None else 0)
+ total = yt_count + len(extra_photos)
+
+ if total == 0:
+ shutil.rmtree(tmp_dir, ignore_errors=True)
+ return _download_via_gallery_dl(case, url, index=index, title=title)
+
+ if index is None and 1 < total <= MAX_PICKER_ITEMS:
+ # several attachments and the caller hasn't picked one yet —
+ # report the candidates without downloading anything
+ shutil.rmtree(tmp_dir, ignore_errors=True)
+ if entries:
+ yt_items = _picker_items(entries)
+ elif info is not None:
+ yt_items = [
+ {
+ "index": 1,
+ "title": info.get("title") or info.get("id") or "item 1",
+ "thumbnail": info.get("thumbnail"),
+ "kind": "video",
+ }
+ ]
+ else:
+ yt_items = []
+ photo_items = [
+ {"index": yt_count + i, "title": "Telegram photo", "thumbnail": p["url"], "kind": "image"}
+ for i, p in enumerate(extra_photos, start=1)
+ ]
+ return {"multi": True, "items": yt_items + photo_items}
+
+ pick = index or 1
+ if pick > yt_count:
+ # not a yt-dlp entry — one of the extra Telegram photos
+ shutil.rmtree(tmp_dir, ignore_errors=True)
+ photo = extra_photos[pick - yt_count - 1]
+ return _register_telegram_photo(case, url, photo, title=title)
+
+ target_info = entries[pick - 1] if entries else info
+
+ # download from the info we already extracted — no second extraction
+ info = ydl.process_ie_result(target_info, download=True)
downloaded = Path(ydl.prepare_filename(info))
if not downloaded.exists(): # extension may differ after post-processing
@@ -225,11 +526,12 @@ def download_url(case: Case, url: str, progress_hook=None) -> dict[str, Any]:
shutil.move(str(downloaded), str(dest))
shutil.rmtree(tmp_dir, ignore_errors=True)
+ extracted_title = info.get("title")
source = {
"type": "download",
"url": url,
- "downloader": f"yt-dlp",
- "title": info.get("title"),
+ "downloader": "yt-dlp",
+ "title": extracted_title,
"description": info.get("description"),
"uploader": info.get("uploader") or info.get("channel"),
"upload_date": info.get("upload_date"),
@@ -237,7 +539,13 @@ def download_url(case: Case, url: str, progress_hook=None) -> dict[str, Any]:
"extractor": info.get("extractor"),
"duration": info.get("duration"),
}
- return _register(case, dest, source)
+ result = _register(case, dest, source)
+
+ display_title = (title or "").strip() or extracted_title
+ if not result["duplicate"] and display_title:
+ result["item"] = update_media(case, result["item"]["path"], {"title": display_title})
+ result["multi"] = False
+ return result
def read_item(case: Case, rel_path: str) -> dict[str, Any] | None:
diff --git a/src/azimut/engine/satellite.py b/src/azimut/engine/satellite.py
index ed988cb..4343833 100644
--- a/src/azimut/engine/satellite.py
+++ b/src/azimut/engine/satellite.py
@@ -1,31 +1,25 @@
-"""Satellite captures on disk and their one-to-one sync with ``place`` entities.
-
-A capture is an image plus a JSON sidecar under ``<case>/satellite/``:
-
- satellite/sat_<stamp>_z<zoom>_<provider>.png
- satellite/sat_<stamp>_z<zoom>_<provider>.png.json # provenance (lat/lon/…)
-
-Every capture is mirrored by exactly one ``capture`` entity in ``case.json``
-(spec §3.5): one capture == one entity on the right. They are tied by the
-capture's relative ``path``, stored on the entity as ``attrs.path`` — not by
-coordinates, so two captures of the same point stay two independent entities.
-The entity ``label`` is the capture title (coordinates by default, editable).
-A capture is an *image* (its marker coordinates are recorded as info); saving a
-bare ``place`` — a navigable point with no image — is a separate act.
-
-Deleting in one place must delete in the other, so all delete paths funnel here:
-
-* delete a capture → drop the one ``capture`` entity that points at it;
-* delete a ``capture`` row → drop the one capture file it points at (handled by
- the entities API via :func:`unlink_capture`).
+"""Satellite captures and their one-to-one ``capture`` entities.
+
+A capture is a satellite imagery crop. It is filed through the *media* pipeline
+(:mod:`azimut.engine.media`) so it lives in ``<case>/media/`` alongside every
+other image — hashed, thumbnailed, listed in the Media Library and openable in
+Inspect — but it is registered under a ``capture`` entity (not ``media``) that
+carries the crop's coordinates/zoom/bearing. Its media sidecar's ``source`` dict
+holds the full capture provenance (provider, attribution, acquisition, …) with
+``type == "satellite"``, which is how a capture is told apart from an ordinary
+media item both here and in the Media Library facet.
+
+Because a capture *is* a media item, all of its lifecycle (list/patch/delete)
+funnels through the media engine; this module only adds the satellite-flavoured
+listing view the Satellite tool's "Saved › Captures" panel consumes.
"""
from __future__ import annotations
-import json
from typing import Any
from ..workspace import Case
+from . import media as media_engine
def coords_label(lat: float, lon: float) -> str:
@@ -33,41 +27,29 @@ def coords_label(lat: float, lon: float) -> str:
return f"{lat:.6f}, {lon:.6f}"
-def _read_sidecar(case: Case, rel_path: str) -> dict[str, Any] | None:
- image = case.resolve_inside(rel_path)
- sidecar = image.with_name(image.name + ".json")
- if not sidecar.exists():
- return None
- return json.loads(sidecar.read_text(encoding="utf-8"))
+def is_capture(item: dict[str, Any]) -> bool:
+ """True if a media listing item is a satellite capture."""
+ return (item.get("source") or {}).get("type") == "satellite"
def list_captures(case: Case) -> list[dict[str, Any]]:
- sat_dir = case.subdir("satellite")
+ """The case's satellite captures, newest first, flattened for the UI.
+
+ Each item merges the capture provenance (from the media sidecar's
+ ``source``: provider, zoom, bearing, coordinates, acquisition date, …) with
+ the media item's own fields (path, title, notes, thumbnail), so the Satellite
+ panel keeps rendering exactly the fields it did when captures had their own
+ store.
+ """
captures: list[dict[str, Any]] = []
- for sidecar in sorted(sat_dir.glob("*.png.json")):
- image_name = sidecar.name[: -len(".json")]
- if not (sat_dir / image_name).exists():
+ for item in media_engine.list_media(case):
+ if not is_capture(item):
continue
- data = json.loads(sidecar.read_text(encoding="utf-8"))
- data["path"] = f"satellite/{image_name}"
- lat, lon = data.get("lat"), data.get("lon")
- if not data.get("title") and lat is not None and lon is not None:
- data["title"] = coords_label(lat, lon)
- captures.append(data)
- captures.sort(key=lambda d: d.get("fetched_at") or "", reverse=True)
+ source = item.get("source") or {}
+ merged = {**source, **item} # media fields (title/notes/path) win
+ lat, lon = merged.get("lat"), merged.get("lon")
+ if not merged.get("title") and lat is not None and lon is not None:
+ merged["title"] = coords_label(lat, lon)
+ captures.append(merged)
+ captures.sort(key=lambda d: d.get("fetched_at") or d.get("added_at") or "", reverse=True)
return captures
-
-
-def unlink_capture(case: Case, rel_path: str) -> None:
- """Remove a capture's image + sidecar from disk (leaves entities alone)."""
- image = case.resolve_inside(rel_path)
- image.unlink(missing_ok=True)
- image.with_name(image.name + ".json").unlink(missing_ok=True)
-
-
-def delete_capture(case: Case, rel_path: str) -> None:
- """Delete one capture and the single ``place`` entity mirroring it."""
- unlink_capture(case, rel_path)
- entity = case.find_entity(attr="path", value=rel_path)
- if entity:
- case.remove_entity(entity["id"])
diff --git a/src/azimut/engine/tiles.py b/src/azimut/engine/tiles.py
index 0150086..0d778bd 100644
--- a/src/azimut/engine/tiles.py
+++ b/src/azimut/engine/tiles.py
@@ -16,12 +16,18 @@ from datetime import datetime, timezone
from typing import Any, Callable
import httpx
-from PIL import Image, ImageDraw
+from PIL import Image, ImageDraw, ImageFont
from .. import config
+from . import google_tiles
TILE_SIZE = 256
-MAX_TILES_PER_CROP = 64 # hard cap: bounded requests per capture, polite to providers
+SIZE_MAX = 4096 # hard cap on a capture's width/height, in px
+# hard cap: bounded requests per capture, polite to providers. Kept at the
+# same ratio to SIZE_MAX as the original 2048px/64-tile cap, so an exact
+# SIZE_MAX×SIZE_MAX crop still gets rejected (as 2048×2048 did before) while
+# realistic preset/resolution combinations stay comfortably under it.
+MAX_TILES_PER_CROP = (SIZE_MAX // TILE_SIZE) ** 2
USER_AGENT = "Azimut/0.1 (+local OSINT workbench; single-user)"
@@ -34,7 +40,31 @@ class Provider:
max_zoom: int = 19
needs_key: bool = False
subdomains: tuple[str, ...] = field(default_factory=tuple) # for {s} templates
-
+ # True for satellite/aerial imagery, False for street/base maps. Drives the UI:
+ # the OSM labels overlay is only useful over imagery (§ Satellite item 1).
+ imagery: bool = True
+ capturable: bool = True # may a saved capture be filed from it?
+ cacheable: bool = True # may its tiles be written to a disk cache?
+ attribution_burn: bool = False # force attribution stamped into the image
+ session: str | None = None # provider kind needing a live token, e.g. "google"
+ # usage-counter bucket in settings.json (docs/KEYED_PROVIDERS.md §6);
+ # None = unmetered. Billed keyed providers count every tile request.
+ meter: str | None = None
+ # px per tile edge. Mapbox bills 256px tiles 4× vs 512px ones (same imagery
+ # resolution: one 512 tile at z-1 = four 256 tiles at z), so keyed Mapbox
+ # uses 512. The visual zoom stays the caller's; the URL z is offset down.
+ tile_size: int = 256
+
+
+# Built-in keyed providers (docs/KEYED_PROVIDERS.md §2): only surfaced from
+# all_providers() once the matching api_keys entry is set. Mapbox's token is a
+# static credential baked straight into the URL; Google needs a live session
+# token minted per docs/KEYED_PROVIDERS.md §3, so {session} stays unresolved
+# here and is substituted at fetch time (engine/google_tiles.py).
+MAPBOX_SATELLITE_URL = (
+ "https://api.mapbox.com/styles/v1/mapbox/satellite-v9/tiles/512/{z}/{x}/{y}?access_token={key}"
+)
+GOOGLE_SATELLITE_URL = "https://tile.googleapis.com/v1/2dtiles/{z}/{x}/{y}?session={session}&key={key}"
BUILTIN_PROVIDERS: tuple[Provider, ...] = (
Provider(
@@ -50,6 +80,7 @@ BUILTIN_PROVIDERS: tuple[Provider, ...] = (
url="https://tile.openstreetmap.org/{z}/{x}/{y}.png",
attribution="© OpenStreetMap contributors",
max_zoom=19,
+ imagery=False,
),
)
@@ -58,6 +89,44 @@ def all_providers() -> list[Provider]:
providers = list(BUILTIN_PROVIDERS)
settings = config.load_settings()
keys = settings.get("api_keys", {})
+
+ mapbox_key = keys.get("mapbox")
+ if mapbox_key:
+ providers.append(
+ Provider(
+ id="mapbox-satellite",
+ label="Mapbox Satellite",
+ url=MAPBOX_SATELLITE_URL.replace("{key}", mapbox_key),
+ attribution="© Mapbox © OpenStreetMap",
+ max_zoom=22,
+ imagery=True,
+ capturable=True,
+ cacheable=True,
+ meter="mapbox",
+ tile_size=512,
+ )
+ )
+
+ google_key = keys.get("google")
+ if google_key:
+ providers.append(
+ Provider(
+ id="google-satellite",
+ label="Google Satellite",
+ url=GOOGLE_SATELLITE_URL.replace("{key}", google_key),
+ # fallback only — captures resolve the real per-viewport
+ # copyright line at fetch time (engine/google_tiles.py)
+ attribution="Google",
+ max_zoom=22,
+ imagery=True,
+ capturable=True,
+ cacheable=False,
+ attribution_burn=True,
+ session="google",
+ meter="google",
+ )
+ )
+
for entry in settings.get("tile_providers", []):
try:
url = entry["url"]
@@ -73,6 +142,11 @@ def all_providers() -> list[Provider]:
attribution=entry.get("attribution", entry["id"]),
max_zoom=int(entry.get("max_zoom", 19)),
needs_key=needs_key,
+ imagery=bool(entry.get("imagery", True)),
+ # only the two real-world sizes; anything else falls back
+ tile_size=(
+ 512 if int(entry.get("tile_size", TILE_SIZE)) == 512 else TILE_SIZE
+ ),
)
)
except (KeyError, TypeError, ValueError):
@@ -120,6 +194,16 @@ class TileFetchError(Exception):
pass
+def resolve_url(provider: Provider) -> str:
+ """The provider's live XYZ template — session token substituted if needed."""
+ if provider.session != "google":
+ return provider.url
+ try:
+ return google_tiles.resolve_template(provider.url)
+ except Exception as exc:
+ raise TileFetchError(f"Google session token: {exc}") from exc
+
+
def _default_fetch(client: httpx.Client, url: str) -> Image.Image | None:
"""Fetch one tile; None for 'no imagery here' (404), raise on other errors."""
response = client.get(url)
@@ -163,61 +247,82 @@ def fetch_crop(
"""
if provider.needs_key:
raise TileFetchError(f"provider '{provider.id}' requires an API key (settings.json)")
- zoom = min(zoom, provider.max_zoom)
- width, height = min(width, 2048), min(height, 2048)
+ if not provider.capturable:
+ raise TileFetchError(f"provider '{provider.id}' is view-only and cannot be captured")
+ # Bigger tiles keep the caller's visual zoom (same m/px) but request a
+ # lower URL z: one 512px tile at z-1 covers four 256px tiles at z.
+ z_shift = int(math.log2(provider.tile_size // TILE_SIZE))
+ zoom = max(min(zoom, provider.max_zoom), z_shift)
+ tile_z = zoom - z_shift
+ ts = provider.tile_size
+ width, height = min(width, SIZE_MAX), min(height, SIZE_MAX)
bearing = bearing % 360.0
# A rotated crop needs a bigger north-up source so its corners stay covered
# after rotation; the diagonal is the smallest square that always fits.
if bearing:
- fetch_w = fetch_h = min(math.ceil(math.hypot(width, height)) + 2, 2048)
+ fetch_w = fetch_h = min(math.ceil(math.hypot(width, height)) + 2, SIZE_MAX)
else:
fetch_w, fetch_h = width, height
+ # world-pixel space at the visual zoom (256·2^zoom px across); the tile
+ # grid divides it in `ts`-px steps, with tile indices valid at `tile_z`
center_x, center_y = project(lat, lon, zoom)
center_px, center_py = center_x * TILE_SIZE, center_y * TILE_SIZE
left, top = center_px - fetch_w / 2, center_py - fetch_h / 2
- tile_x0, tile_y0 = int(left // TILE_SIZE), int(top // TILE_SIZE)
- tile_x1, tile_y1 = int((left + fetch_w) // TILE_SIZE), int((top + fetch_h) // TILE_SIZE)
+ tile_x0, tile_y0 = int(left // ts), int(top // ts)
+ tile_x1, tile_y1 = int((left + fetch_w) // ts), int((top + fetch_h) // ts)
n_tiles = (tile_x1 - tile_x0 + 1) * (tile_y1 - tile_y0 + 1)
if n_tiles > MAX_TILES_PER_CROP:
raise TileFetchError(
f"crop needs {n_tiles} tiles (max {MAX_TILES_PER_CROP}) — reduce size or zoom"
)
- max_index = (1 << zoom) - 1
+ max_index = (1 << tile_z) - 1
fetch = fetch_tile or _default_fetch
canvas = Image.new("RGB", (fetch_w, fetch_h), (24, 28, 38))
missing = 0
- def grab(tx: int, ty: int) -> tuple[int, int, Image.Image | None]:
- if not (0 <= tx <= max_index and 0 <= ty <= max_index):
- return tx, ty, None
- url = provider.url.format(x=tx, y=ty, z=zoom)
- return tx, ty, fetch(client, url)
-
- with httpx.Client(
- headers={"User-Agent": USER_AGENT}, timeout=20, follow_redirects=True
- ) as client:
- with ThreadPoolExecutor(max_workers=6) as pool:
- results = list(
- pool.map(
- lambda xy: grab(*xy),
- [
- (tx, ty)
- for ty in range(tile_y0, tile_y1 + 1)
- for tx in range(tile_x0, tile_x1 + 1)
- ],
- )
- )
-
+ coords = [
+ (tx, ty)
+ for ty in range(tile_y0, tile_y1 + 1)
+ for tx in range(tile_x0, tile_x1 + 1)
+ ]
+
+ def fetch_all(url_template: str) -> list[tuple[int, int, Image.Image | None]]:
+ def grab(tx: int, ty: int) -> tuple[int, int, Image.Image | None]:
+ if not (0 <= tx <= max_index and 0 <= ty <= max_index):
+ return tx, ty, None
+ return tx, ty, fetch(client, url_template.format(x=tx, y=ty, z=tile_z))
+
+ with httpx.Client(
+ headers={"User-Agent": USER_AGENT}, timeout=20, follow_redirects=True
+ ) as client:
+ with ThreadPoolExecutor(max_workers=6) as pool:
+ return list(pool.map(lambda xy: grab(*xy), coords))
+
+ for attempt in (1, 2):
+ try:
+ results = fetch_all(resolve_url(provider))
+ break
+ except httpx.HTTPStatusError as exc:
+ # a stale Google session token answers 401/403 — re-mint once, transparently
+ if attempt == 1 and provider.session and exc.response.status_code in (401, 403):
+ google_tiles.invalidate(google_tiles.key_from_url(provider.url))
+ else:
+ raise
+
+ served = 0 # tiles the provider actually returned — what a billed meter counts
for tx, ty, tile in results:
- px, py = int(tx * TILE_SIZE - left), int(ty * TILE_SIZE - top)
+ px, py = int(tx * ts - left), int(ty * ts - top)
if tile is None:
missing += 1
continue
+ served += 1
canvas.paste(tile, (px, py))
+ if provider.meter and served:
+ config.record_usage(provider.meter, served)
if bearing:
# CSS rotates the map clockwise; PIL rotates counter-clockwise, hence -bearing.
@@ -237,10 +342,27 @@ def fetch_crop(
marker_style = "crosshair"
_draw_crosshair(canvas, mx, my)
+ attribution = provider.attribution
+ if provider.session == "google":
+ # the exact copyright line for this viewport (e.g. "Map data ©2026
+ # Google, Maxar Technologies"); static fallback if unreachable
+ north, west = unproject(left / TILE_SIZE, top / TILE_SIZE, zoom)
+ south, east = unproject((left + fetch_w) / TILE_SIZE, (top + fetch_h) / TILE_SIZE, zoom)
+ attribution = (
+ google_tiles.viewport_copyright(
+ google_tiles.key_from_url(provider.url), zoom, north, south, east, west
+ )
+ or attribution
+ )
+
+ if provider.attribution_burn:
+ canvas = _burn_attribution(canvas, attribution)
+
provenance = {
"provider": provider.id,
"provider_label": provider.label,
- "attribution": provider.attribution,
+ "attribution": attribution,
+ "attribution_burned": bool(provider.attribution_burn),
# lat/lon are the marker (point of interest); center frames the crop
"lat": marker_lat,
"lon": marker_lon,
@@ -263,6 +385,101 @@ def fetch_crop(
return canvas, provenance
+# -- Esri imagery capture date (best-effort) ----------------------------------
+
+# Esri publishes per-scene acquisition metadata for World Imagery through the
+# MapServer "identify" endpoint. Only this provider exposes a capture date; for
+# everything else we simply have nothing to show.
+ESRI_METADATA_URL = (
+ "https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/identify"
+)
+
+
+def _extract_capture_date(attrs: dict[str, Any]) -> str | None:
+ """Pull a human date out of an Esri identify attribute bag.
+
+ Esri's date field varies by scene (``SRC_DATE2`` as YYYYMMDD, a plain year,
+ or an already-formatted string), so scan every date-ish attribute and take
+ the most precise value we can recognise.
+ """
+ best: str | None = None
+ for key, value in attrs.items():
+ if "DATE" not in key.upper() or value in (None, "", 0):
+ continue
+ text = str(value).strip()
+ digits = text.replace("-", "").replace("/", "")
+ if len(digits) == 8 and digits.isdigit(): # YYYYMMDD → full date wins outright
+ return f"{digits[:4]}-{digits[4:6]}-{digits[6:8]}"
+ if len(text) == 4 and text.isdigit(): # bare year — keep unless a full date turns up
+ best = best or text
+ elif len(text) >= 8: # already looks like a formatted date
+ best = best or text
+ return best
+
+
+def esri_capture_date(
+ lat: float,
+ lon: float,
+ zoom: int,
+ *,
+ get: Callable[..., Any] | None = None,
+) -> dict[str, Any] | None:
+ """Best-effort acquisition date of the Esri World Imagery scene at a point.
+
+ Returns ``{"date": str|None, "source": str|None}`` on a successful query
+ (``date`` may still be ``None`` if the scene carries no date), or ``None``
+ when the metadata service can't be reached. Never raises.
+ """
+ tx, ty = project(lat, lon, zoom)
+ tl_lat, tl_lon = unproject(int(tx), int(ty), zoom)
+ br_lat, br_lon = unproject(int(tx) + 1, int(ty) + 1, zoom)
+ params = {
+ "f": "json",
+ "geometry": f"{lon},{lat}",
+ "geometryType": "esriGeometryPoint",
+ "sr": "4326",
+ "layers": "all",
+ "tolerance": "0",
+ "returnGeometry": "false",
+ "mapExtent": f"{tl_lon},{br_lat},{br_lon},{tl_lat}",
+ "imageDisplay": "256,256,96",
+ }
+ fetch = get or httpx.get
+ try:
+ response = fetch(
+ ESRI_METADATA_URL, params=params, headers={"User-Agent": USER_AGENT}, timeout=8
+ )
+ response.raise_for_status()
+ results = response.json().get("results") or []
+ except Exception:
+ return None
+ if not results:
+ return {"date": None, "source": None}
+ attrs = results[0].get("attributes", {})
+ return {
+ "date": _extract_capture_date(attrs),
+ "source": attrs.get("NICE_NAME") or attrs.get("SRC_DESC") or None,
+ }
+
+
+ATTRIBUTION_BAND = 20 # px footer appended below the imagery
+
+
+def _burn_attribution(img: Image.Image, text: str) -> Image.Image:
+ """Append a footer band carrying the attribution line.
+
+ For providers whose terms make attribution a condition of the allowed use
+ (Google), the capture must never exist without it — burned in, not optional.
+ The band is added *below* the imagery so nothing is covered.
+ """
+ out = Image.new("RGB", (img.width, img.height + ATTRIBUTION_BAND), (16, 18, 24))
+ out.paste(img, (0, 0))
+ draw = ImageDraw.Draw(out)
+ font = ImageFont.load_default()
+ draw.text((6, img.height + 4), text, fill=(203, 208, 218), font=font)
+ return out
+
+
def _draw_crosshair(img: Image.Image, cx: int, cy: int) -> None:
"""Marker at (cx, cy): thin cross with an open middle, white with dark outline."""
draw = ImageDraw.Draw(img)
diff --git a/src/azimut/server.py b/src/azimut/server.py
index 91e0373..e8a355d 100644
--- a/src/azimut/server.py
+++ b/src/azimut/server.py
@@ -18,7 +18,7 @@ def create_app() -> FastAPI:
app = FastAPI(title="Azimut", version=__version__, docs_url="/api/docs")
- from .api import cases, drafts, files, inspect, media, proofs, satellite
+ from .api import cases, drafts, files, inspect, media, proofs, satellite, settings
app.include_router(cases.router)
app.include_router(media.router)
@@ -27,6 +27,7 @@ def create_app() -> FastAPI:
app.include_router(proofs.router)
app.include_router(drafts.router)
app.include_router(files.router)
+ app.include_router(settings.router)
@app.get("/api/health")
def health() -> dict[str, str]:
diff --git a/src/azimut/workspace.py b/src/azimut/workspace.py
index 8e8ec44..b097751 100644
--- a/src/azimut/workspace.py
+++ b/src/azimut/workspace.py
@@ -5,8 +5,7 @@ A case is a plain directory (spec §4):
<case>/
├── case.json # metadata + entities + links
├── notes.md # free-form case notes
- ├── media/ # imported/downloaded media + sidecar metadata
- ├── satellite/ # imagery crops + provenance
+ ├── media/ # imported/downloaded media + satellite crops + sidecars
├── proofs/ # composed proofs (PNG + editable JSON spec)
└── exports/ # post drafts, reports
@@ -19,6 +18,7 @@ from __future__ import annotations
import json
import re
import shutil
+import threading
import uuid
from datetime import datetime, timezone
from pathlib import Path
@@ -26,7 +26,25 @@ from typing import Any, Literal
from . import config
-CASE_SUBDIRS = ("media", "satellite", "proofs", "exports", "inspect")
+CASE_SUBDIRS = ("media", "proofs", "exports", "inspect")
+
+# One lock per case directory, shared across every Case instance that points
+# at it (a fresh instance is constructed per request). Without it, concurrent
+# read-modify-write of case.json — e.g. several media downloads from the
+# multi-item picker finishing at once — silently drop each other's entity or
+# crash on the tmp-file rename (spec §6 honest output requires none lost).
+_case_locks_guard = threading.Lock()
+_case_locks: dict[str, threading.Lock] = {}
+
+
+def _case_lock(path: Path) -> threading.Lock:
+ key = str(path)
+ with _case_locks_guard:
+ lock = _case_locks.get(key)
+ if lock is None:
+ lock = threading.Lock()
+ _case_locks[key] = lock
+ return lock
EntityStatus = Literal["confirmed", "suggested"]
@@ -60,6 +78,7 @@ class Case:
def __init__(self, path: Path):
self.path = path
+ self._lock = _case_lock(path)
# -- identity ---------------------------------------------------------
@@ -164,9 +183,10 @@ class Case:
# -- lifecycle -----------------------------------------------------------
def rename(self, name: str) -> None:
- data = self.read()
- data["name"] = name
- self._write_json(data)
+ with self._lock:
+ data = self.read()
+ data["name"] = name
+ self._write_json(data)
def promote(self, name: str) -> "Case":
"""Move a scratch case into cases/ under a proper name (spec §3.3)."""
@@ -197,45 +217,48 @@ class Case:
status: EntityStatus = "confirmed",
source: str | None = None,
) -> dict[str, Any]:
- data = self.read()
- entity = {
- "id": _new_id("e"),
- "type": type_,
- "label": label,
- "attrs": attrs or {},
- "provenance": {"by": by, "at": _now(), "status": status},
- }
- if source:
- entity["provenance"]["source"] = source
- data["entities"].append(entity)
- self._write_json(data)
- return entity
+ with self._lock:
+ data = self.read()
+ entity = {
+ "id": _new_id("e"),
+ "type": type_,
+ "label": label,
+ "attrs": attrs or {},
+ "provenance": {"by": by, "at": _now(), "status": status},
+ }
+ if source:
+ entity["provenance"]["source"] = source
+ data["entities"].append(entity)
+ self._write_json(data)
+ return entity
def update_entity(self, entity_id: str, patch: dict[str, Any]) -> dict[str, Any]:
- data = self.read()
- for entity in data["entities"]:
- if entity["id"] == entity_id:
- for key in ("type", "label"):
- if key in patch:
- entity[key] = patch[key]
- if "attrs" in patch:
- entity["attrs"].update(patch["attrs"])
- if patch.get("status") in ("confirmed", "suggested"):
- entity["provenance"]["status"] = patch["status"]
- self._write_json(data)
- return entity
- raise CaseError(f"entity '{entity_id}' not found")
+ with self._lock:
+ data = self.read()
+ for entity in data["entities"]:
+ if entity["id"] == entity_id:
+ for key in ("type", "label"):
+ if key in patch:
+ entity[key] = patch[key]
+ if "attrs" in patch:
+ entity["attrs"].update(patch["attrs"])
+ if patch.get("status") in ("confirmed", "suggested"):
+ entity["provenance"]["status"] = patch["status"]
+ self._write_json(data)
+ return entity
+ raise CaseError(f"entity '{entity_id}' not found")
def remove_entity(self, entity_id: str) -> None:
- data = self.read()
- before = len(data["entities"])
- data["entities"] = [e for e in data["entities"] if e["id"] != entity_id]
- if len(data["entities"]) == before:
- raise CaseError(f"entity '{entity_id}' not found")
- data["links"] = [
- l for l in data["links"] if entity_id not in (l["from"], l["to"])
- ]
- self._write_json(data)
+ with self._lock:
+ data = self.read()
+ before = len(data["entities"])
+ data["entities"] = [e for e in data["entities"] if e["id"] != entity_id]
+ if len(data["entities"]) == before:
+ raise CaseError(f"entity '{entity_id}' not found")
+ data["links"] = [
+ l for l in data["links"] if entity_id not in (l["from"], l["to"])
+ ]
+ self._write_json(data)
def find_entity(self, *, attr: str, value: Any) -> dict[str, Any] | None:
for entity in self.read()["entities"]:
@@ -252,29 +275,31 @@ class Case:
by: str,
status: EntityStatus = "confirmed",
) -> dict[str, Any]:
- data = self.read()
- ids = {e["id"] for e in data["entities"]}
- for eid in (from_id, to_id):
- if eid not in ids:
- raise CaseError(f"entity '{eid}' not found")
- link = {
- "id": _new_id("l"),
- "from": from_id,
- "to": to_id,
- "type": type_,
- "provenance": {"by": by, "at": _now(), "status": status},
- }
- data["links"].append(link)
- self._write_json(data)
- return link
+ with self._lock:
+ data = self.read()
+ ids = {e["id"] for e in data["entities"]}
+ for eid in (from_id, to_id):
+ if eid not in ids:
+ raise CaseError(f"entity '{eid}' not found")
+ link = {
+ "id": _new_id("l"),
+ "from": from_id,
+ "to": to_id,
+ "type": type_,
+ "provenance": {"by": by, "at": _now(), "status": status},
+ }
+ data["links"].append(link)
+ self._write_json(data)
+ return link
def remove_link(self, link_id: str) -> None:
- data = self.read()
- before = len(data["links"])
- data["links"] = [l for l in data["links"] if l["id"] != link_id]
- if len(data["links"]) == before:
- raise CaseError(f"link '{link_id}' not found")
- self._write_json(data)
+ with self._lock:
+ data = self.read()
+ before = len(data["links"])
+ data["links"] = [l for l in data["links"] if l["id"] != link_id]
+ if len(data["links"]) == before:
+ raise CaseError(f"link '{link_id}' not found")
+ self._write_json(data)
# -- folders (nested organisational buckets for entities) ----------------
#
@@ -296,35 +321,37 @@ class Case:
def add_folder(self, name: str) -> list[str]:
path = self._normalize_folder(name)
- data = self.read()
- folders = data.setdefault("folders", [])
- # materialise the leaf and every ancestor so the tree stays connected
- segments = path.split("/")
- changed = False
- for i in range(1, len(segments) + 1):
- ancestor = "/".join(segments[:i])
- if ancestor not in folders:
- folders.append(ancestor)
- changed = True
- if changed:
- folders.sort(key=str.lower)
- self._write_json(data)
- return data["folders"]
+ with self._lock:
+ data = self.read()
+ folders = data.setdefault("folders", [])
+ # materialise the leaf and every ancestor so the tree stays connected
+ segments = path.split("/")
+ changed = False
+ for i in range(1, len(segments) + 1):
+ ancestor = "/".join(segments[:i])
+ if ancestor not in folders:
+ folders.append(ancestor)
+ changed = True
+ if changed:
+ folders.sort(key=str.lower)
+ self._write_json(data)
+ return data["folders"]
def remove_folder(self, name: str) -> list[str]:
- data = self.read()
- folders = data.setdefault("folders", [])
- # a folder and its whole subtree go together
- prefix = name + "/"
- doomed = {f for f in folders if f == name or f.startswith(prefix)}
- data["folders"] = [f for f in folders if f not in doomed]
- # unassign any entity filed under a removed node (or its descendants)
- for entity in data.get("entities", []):
- folder = entity.get("attrs", {}).get("folder")
- if folder is not None and (folder == name or folder.startswith(prefix)):
- entity["attrs"].pop("folder", None)
- self._write_json(data)
- return data["folders"]
+ with self._lock:
+ data = self.read()
+ folders = data.setdefault("folders", [])
+ # a folder and its whole subtree go together
+ prefix = name + "/"
+ doomed = {f for f in folders if f == name or f.startswith(prefix)}
+ data["folders"] = [f for f in folders if f not in doomed]
+ # unassign any entity filed under a removed node (or its descendants)
+ for entity in data.get("entities", []):
+ folder = entity.get("attrs", {}).get("folder")
+ if folder is not None and (folder == name or folder.startswith(prefix)):
+ entity["attrs"].pop("folder", None)
+ self._write_json(data)
+ return data["folders"]
# -- helpers -------------------------------------------------------------
diff --git a/tests/test_cases_api.py b/tests/test_cases_api.py
index 70acda9..16590e5 100644
--- a/tests/test_cases_api.py
+++ b/tests/test_cases_api.py
@@ -134,32 +134,36 @@ import os
def _plant_capture(client, cid: str) -> dict:
- """Write a fake satellite PNG + sidecar directly into the case directory."""
- import azimut.config as cfg
- from pathlib import Path
+ """File a fake satellite capture through the media pipeline (its real store)."""
+ from PIL import Image
- case_dir = cfg.cases_dir() / cid
- sat_dir = case_dir / "satellite"
- sat_dir.mkdir(parents=True, exist_ok=True)
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
- fname = "sat_test_z16_esri.png"
- (sat_dir / fname).write_bytes(b"\x89PNG\r\n\x1a\n") # minimal PNG magic bytes
- sidecar = {
- "filename": fname,
+ prov = {
"provider": "esri-world-imagery",
"provider_label": "Esri World Imagery",
"zoom": 16,
"lat": 50.0,
"lon": 30.0,
+ "bearing": 0.0,
"fetched_at": "2026-07-08T12:00:00Z",
"tiles": 9,
"tiles_missing": 0,
}
- (sat_dir / (fname + ".json")).write_text(
- json.dumps(sidecar, indent=2) + "\n", encoding="utf-8"
+ result = media_engine.import_image(
+ Case.open(cid),
+ Image.new("RGB", (32, 32), (10, 120, 10)),
+ "sat_test_z16_esri.png",
+ {"type": "satellite", **prov},
+ by="satellite",
+ entity_type="capture",
+ extra_attrs={"coords": "50.000000, 30.000000", "lat": 50.0, "lon": 30.0,
+ "zoom": 16, "bearing": 0.0},
+ title="50.000000, 30.000000",
+ dedupe=False,
)
- sidecar["path"] = f"satellite/{fname}"
- return sidecar
+ return {"path": result["item"]["path"], **prov}
def test_satellite_patch_notes(client):
diff --git a/tests/test_config.py b/tests/test_config.py
new file mode 100644
index 0000000..6e5a08e
--- /dev/null
+++ b/tests/test_config.py
@@ -0,0 +1,52 @@
+"""Settings persistence and back-compat merging (spec: docs/KEYED_PROVIDERS.md §1)."""
+
+import json
+
+from azimut import config
+
+
+def test_default_settings_has_usage_and_api_keys():
+ assert config.DEFAULT_SETTINGS["usage"] == {}
+ assert config.DEFAULT_SETTINGS["api_keys"] == {}
+
+
+def test_ensure_workspace_writes_defaults(monkeypatch, tmp_path):
+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
+ config.ensure_workspace()
+ saved = json.loads(config.settings_path().read_text(encoding="utf-8"))
+ assert saved["usage"] == {}
+ assert saved["tile_providers"] == []
+
+
+def test_load_settings_roundtrips_usage_counters(monkeypatch, tmp_path):
+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
+ config.save_settings(
+ {
+ "tile_providers": [],
+ "api_keys": {"mapbox": "pk.test"},
+ "usage": {"mapbox": {"2026-07": 87}},
+ }
+ )
+ loaded = config.load_settings()
+ assert loaded["usage"] == {"mapbox": {"2026-07": 87}}
+ assert loaded["api_keys"] == {"mapbox": "pk.test"}
+
+
+def test_load_settings_back_compat_missing_usage_key(monkeypatch, tmp_path):
+ """A settings.json written before `usage` existed still loads cleanly."""
+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
+ config.settings_path().parent.mkdir(parents=True, exist_ok=True)
+ config.settings_path().write_text(
+ json.dumps({"tile_providers": [], "api_keys": {"google": "AIza.test"}}),
+ encoding="utf-8",
+ )
+ loaded = config.load_settings()
+ assert loaded["usage"] == {}
+ assert loaded["api_keys"] == {"google": "AIza.test"}
+
+
+def test_load_settings_missing_file_returns_defaults(monkeypatch, tmp_path):
+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
+ loaded = config.load_settings()
+ assert loaded == config.DEFAULT_SETTINGS
+ assert loaded is not config.DEFAULT_SETTINGS
diff --git a/tests/test_geo_api.py b/tests/test_geo_api.py
new file mode 100644
index 0000000..b8c1f99
--- /dev/null
+++ b/tests/test_geo_api.py
@@ -0,0 +1,65 @@
+"""Forward geocoding (/api/geo/geocode): Nominatim behind a mock, never the network."""
+
+from azimut.engine import geo
+
+
+class _FakeResponse:
+ def __init__(self, payload):
+ self._payload = payload
+
+ def raise_for_status(self):
+ pass
+
+ def json(self):
+ return self._payload
+
+
+def _fake_get(payload):
+ calls = {}
+
+ def fake(url, params=None, headers=None, timeout=None):
+ calls["url"] = url
+ calls["params"] = params
+ calls["headers"] = headers
+ return _FakeResponse(payload)
+
+ return fake, calls
+
+
+def test_geocode_returns_top_match(client, monkeypatch):
+ fake, calls = _fake_get(
+ [{"lat": "48.8584", "lon": "2.2945", "display_name": "Tour Eiffel, Paris, France"}]
+ )
+ monkeypatch.setattr(geo.httpx, "get", fake)
+
+ result = client.get("/api/geo/geocode", params={"q": "tour eiffel"}).json()
+ assert result["lat"] == 48.8584
+ assert result["lon"] == 2.2945
+ assert result["display_name"] == "Tour Eiffel, Paris, France"
+ assert "OpenStreetMap" in result["attribution"]
+ # polite Nominatim usage: identified UA, single result requested
+ assert calls["params"]["q"] == "tour eiffel"
+ assert calls["params"]["limit"] == 1
+ assert calls["headers"]["User-Agent"]
+
+
+def test_geocode_no_match_is_404(client, monkeypatch):
+ fake, _ = _fake_get([])
+ monkeypatch.setattr(geo.httpx, "get", fake)
+ response = client.get("/api/geo/geocode", params={"q": "zzzz nowhere zzzz"})
+ assert response.status_code == 404
+
+
+def test_geocode_empty_query_is_422(client):
+ response = client.get("/api/geo/geocode", params={"q": " "})
+ assert response.status_code == 422
+
+
+def test_geocode_network_failure_is_404(client, monkeypatch):
+ def boom(*args, **kwargs):
+ raise OSError("network down")
+
+ monkeypatch.setattr(geo.httpx, "get", boom)
+ # engine swallows the error (best-effort) → API reports no match
+ response = client.get("/api/geo/geocode", params={"q": "paris"})
+ assert response.status_code == 404
diff --git a/tests/test_google_tiles.py b/tests/test_google_tiles.py
new file mode 100644
index 0000000..f53ce63
--- /dev/null
+++ b/tests/test_google_tiles.py
@@ -0,0 +1,144 @@
+"""Google Map Tiles session adapter: mint, cache, refresh, viewport copyright.
+
+All HTTP is mocked — no real network, no real key ever touches these tests.
+"""
+
+import pytest
+
+from azimut.engine import google_tiles
+
+
+class FakeResponse:
+ def __init__(self, payload, status=200):
+ self._payload = payload
+ self.status_code = status
+
+ def raise_for_status(self):
+ if self.status_code >= 400:
+ raise RuntimeError(f"HTTP {self.status_code}")
+
+ def json(self):
+ return self._payload
+
+
[email protected](autouse=True)
+def clean_session_cache():
+ google_tiles._sessions.clear()
+ yield
+ google_tiles._sessions.clear()
+
+
+def test_session_token_minted_once_and_cached():
+ calls = []
+
+ def post(url, **kwargs):
+ calls.append(kwargs)
+ return FakeResponse({"session": "tok-1", "expiry": "9999999999"})
+
+ assert google_tiles.session_token("KEY", post=post) == "tok-1"
+ assert google_tiles.session_token("KEY", post=post) == "tok-1"
+ assert len(calls) == 1 # second call served from cache
+ assert calls[0]["params"] == {"key": "KEY"}
+ assert calls[0]["json"]["mapType"] == "satellite"
+
+
+def test_session_token_refreshed_on_expiry():
+ tokens = iter(["tok-1", "tok-2"])
+ minted = []
+
+ def post(url, **kwargs):
+ token = next(tokens)
+ minted.append(token)
+ return FakeResponse({"session": token, "expiry": "1000"})
+
+ now = [500.0]
+ clock = lambda: now[0] # noqa: E731
+ assert google_tiles.session_token("KEY", post=post, now=clock) == "tok-1"
+ now[0] = 2000.0 # past expiry — must re-mint
+ assert google_tiles.session_token("KEY", post=post, now=clock) == "tok-2"
+ assert minted == ["tok-1", "tok-2"]
+
+
+def test_session_token_refreshed_within_slack_window():
+ def post(url, **kwargs):
+ return FakeResponse({"session": "tok", "expiry": "1000"})
+
+ google_tiles.session_token("KEY", post=post, now=lambda: 0.0)
+ # 30s before expiry (inside the 60s slack): treated as stale
+ def post2(url, **kwargs):
+ return FakeResponse({"session": "tok-fresh", "expiry": "99999"})
+
+ assert google_tiles.session_token("KEY", post=post2, now=lambda: 970.0) == "tok-fresh"
+
+
+def test_invalidate_forces_a_fresh_mint():
+ tokens = iter(["tok-1", "tok-2"])
+
+ def post(url, **kwargs):
+ return FakeResponse({"session": next(tokens), "expiry": "9999999999"})
+
+ assert google_tiles.session_token("KEY", post=post) == "tok-1"
+ google_tiles.invalidate("KEY")
+ assert google_tiles.session_token("KEY", post=post) == "tok-2"
+
+
+def test_sessions_cached_per_key():
+ def post(url, **kwargs):
+ key = kwargs["params"]["key"]
+ return FakeResponse({"session": f"tok-{key}", "expiry": "9999999999"})
+
+ assert google_tiles.session_token("A", post=post) == "tok-A"
+ assert google_tiles.session_token("B", post=post) == "tok-B"
+
+
+def test_missing_session_in_response_raises():
+ def post(url, **kwargs):
+ return FakeResponse({"expiry": "9999999999"})
+
+ with pytest.raises(google_tiles.GoogleSessionError):
+ google_tiles.session_token("KEY", post=post)
+
+
+def test_key_from_url():
+ url = "https://tile.googleapis.com/v1/2dtiles/{z}/{x}/{y}?session={session}&key=AIza.test"
+ assert google_tiles.key_from_url(url) == "AIza.test"
+ with pytest.raises(google_tiles.GoogleSessionError):
+ google_tiles.key_from_url("https://example.com/{z}/{x}/{y}")
+
+
+def test_resolve_template_substitutes_session():
+ def post(url, **kwargs):
+ return FakeResponse({"session": "tok-xyz", "expiry": "9999999999"})
+
+ template = "https://tile.googleapis.com/v1/2dtiles/{z}/{x}/{y}?session={session}&key=K1"
+ resolved = google_tiles.resolve_template(template, post=post)
+ assert "{session}" not in resolved
+ assert "session=tok-xyz" in resolved
+ assert "key=K1" in resolved
+ assert "{z}" in resolved # still an XYZ template for the tile loop
+
+
+def test_viewport_copyright_parsed():
+ def post(url, **kwargs):
+ return FakeResponse({"session": "tok", "expiry": "9999999999"})
+
+ seen = {}
+
+ def get(url, **kwargs):
+ seen.update(kwargs["params"])
+ return FakeResponse({"copyright": "Map data ©2026 Google, Maxar Technologies"})
+
+ text = google_tiles.viewport_copyright(
+ "KEY", 15, 48.9, 48.8, 2.4, 2.2, get=get, post=post
+ )
+ assert text == "Map data ©2026 Google, Maxar Technologies"
+ assert seen["session"] == "tok"
+ assert seen["zoom"] == 15
+ assert seen["north"] == 48.9
+
+
+def test_viewport_copyright_never_raises():
+ def post(url, **kwargs):
+ raise RuntimeError("network down")
+
+ assert google_tiles.viewport_copyright("KEY", 15, 1, 0, 1, 0, post=post) is None
diff --git a/tests/test_media_api.py b/tests/test_media_api.py
index b77106f..38db49d 100644
--- a/tests/test_media_api.py
+++ b/tests/test_media_api.py
@@ -190,7 +190,10 @@ def test_download_captures_description(client, monkeypatch):
fh.write(_png_bytes())
return path
- def extract_info(self, url, download=True):
+ def process_ie_result(self, info, download=True):
+ return info
+
+ def extract_info(self, url, download=False):
return info
fake = types.ModuleType("yt_dlp")
@@ -202,6 +205,469 @@ def test_download_captures_description(client, monkeypatch):
assert result["item"]["source"]["title"] == "A clip"
+def _install_fake_ydl(monkeypatch, extract_info_fn, content_fn=None):
+ """Patch a fake ``yt_dlp`` module. ``extract_info_fn(ydl, url, download)``
+ returns the info dict from the (single) ``extract_info`` call; ``prepare_filename``
+ writes a placeholder PNG next to the resolved name so ``download_url`` finds it
+ — ``content_fn(info)`` picks its bytes (default: identical for every call;
+ pass a per-``info`` variant to avoid sha256-dedup collisions across items
+ that are supposed to be distinct, e.g. in a concurrency test).
+ ``process_ie_result`` is a passthrough, matching the real "download from
+ already-extracted info, no second extraction" call ``download_url`` makes."""
+ import sys
+ import types
+
+ content_fn = content_fn or (lambda info: _png_bytes())
+
+ class FakeYDL:
+ def __init__(self, opts):
+ self.opts = opts
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ def prepare_filename(self, info):
+ import os
+
+ path = os.path.join(
+ os.path.dirname(self.opts["outtmpl"]), f"{info['title']} [{info['id']}].png"
+ )
+ with open(path, "wb") as fh:
+ fh.write(content_fn(info))
+ return path
+
+ def process_ie_result(self, info, download=True):
+ return info
+
+ def extract_info(self, url, download=False):
+ return extract_info_fn(self, url, download)
+
+ fake = types.ModuleType("yt_dlp")
+ fake.YoutubeDL = FakeYDL
+ monkeypatch.setitem(sys.modules, "yt_dlp", fake)
+
+
+def test_download_reports_multi_without_downloading(client, monkeypatch):
+ """A post with several attachments (e.g. a tweet with photos) comes back
+ from yt-dlp as a playlist with ``entries``. Without an ``index``,
+ ``download_url`` must report each candidate (title/thumbnail/kind) for a
+ picker and download *nothing* — one extraction, no file, no case entity."""
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "Multi"}).json()["id"]
+ case = Case.open(cid)
+ entries = [
+ {"id": "p1", "title": "photo 1", "ext": "jpg", "thumbnail": "https://x.test/p1.jpg"},
+ {
+ "id": "p2",
+ "title": "photo 2",
+ "ext": "jpg",
+ "thumbnails": [{"url": "https://x.test/p2-small.jpg"}, {"url": "https://x.test/p2.jpg"}],
+ },
+ {"id": "p3", "title": None, "ext": "mp4"},
+ ]
+ _install_fake_ydl(
+ monkeypatch, lambda ydl, url, download: {"_type": "playlist", "entries": entries}
+ )
+
+ result = media_engine.download_url(case, "https://x.com/user/status/123")
+ assert result == {
+ "multi": True,
+ "items": [
+ {"index": 1, "title": "photo 1", "thumbnail": "https://x.test/p1.jpg", "kind": "image"},
+ {"index": 2, "title": "photo 2", "thumbnail": "https://x.test/p2.jpg", "kind": "image"},
+ {"index": 3, "title": "p3", "thumbnail": None, "kind": "video"},
+ ],
+ }
+ assert case.read()["entities"] == []
+ assert client.get(f"/api/cases/{cid}/media").json() == []
+
+
+def test_download_route_surfaces_multi_via_job(client, monkeypatch):
+ """Same as above, exercised through the actual HTTP route + job polling
+ (not just the engine function) to check the request/response wiring."""
+ from azimut.engine import media as media_engine
+
+ cid = client.post("/api/cases", json={"name": "MultiRoute"}).json()["id"]
+ entries = [{"id": "p1", "title": "a", "ext": "jpg"}, {"id": "p2", "title": "b", "ext": "jpg"}]
+ monkeypatch.setattr(
+ media_engine,
+ "download_url",
+ lambda case, url, progress_hook=None, index=None, title=None: {
+ "multi": True,
+ "items": media_engine._picker_items(entries),
+ },
+ )
+
+ job_id = client.post(
+ f"/api/cases/{cid}/media/download", json={"url": "https://x.com/u/status/1"}
+ ).json()["job_id"]
+
+ for _ in range(100):
+ job = client.get(f"/api/jobs/{job_id}").json()
+ if job["status"] != "running":
+ break
+ time.sleep(0.1)
+ assert job["status"] == "done"
+ assert job["result"]["multi"] is True
+ assert [i["title"] for i in job["result"]["items"]] == ["a", "b"]
+
+
+def test_download_with_index_picks_entry_and_keeps_custom_title(client, monkeypatch):
+ """Downloading item #2 of a multi-item post must fetch that specific entry
+ (via yt-dlp's ``playlist_items``) and let the caller override the display
+ title while keeping the originally-extracted title in the source record."""
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "MultiPick"}).json()["id"]
+ case = Case.open(cid)
+ entries = [{"id": "p1", "title": "photo one"}, {"id": "p2", "title": "photo two"}]
+
+ def extract_info(ydl, url, download):
+ assert ydl.opts["playlist_items"] == "2"
+ return {"_type": "playlist", "entries": [entries[int(ydl.opts["playlist_items"]) - 1]]}
+
+ _install_fake_ydl(monkeypatch, extract_info)
+
+ result = media_engine.download_url(
+ case, "https://x.com/user/status/123", index=2, title="My custom title"
+ )
+ assert result["item"]["title"] == "My custom title"
+ assert result["item"]["source"]["title"] == "photo two" # provenance stays honest
+
+
+def test_download_autofills_title_from_extraction(client, monkeypatch):
+ """No explicit title given — the display title should default to whatever
+ yt-dlp reported, instead of leaving the media card stuck on the raw
+ filename until the analyst manually renames it."""
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "AutoTitle"}).json()["id"]
+ case = Case.open(cid)
+
+ _install_fake_ydl(
+ monkeypatch, lambda ydl, url, download: {"id": "abc123", "title": "Strike footage"}
+ )
+
+ result = media_engine.download_url(case, "https://example.com/watch?v=abc123")
+ assert result["item"]["title"] == "Strike footage"
+
+
+def _install_failing_ydl(monkeypatch):
+ """A fake yt_dlp module whose extract_info always raises DownloadError —
+ used to exercise the gallery-dl fallback (yt-dlp's extractors are
+ video-first and hard-fail on e.g. a photo-only tweet)."""
+ import sys
+ import types
+
+ class DownloadError(Exception):
+ pass
+
+ class FakeYDL:
+ def __init__(self, opts):
+ self.opts = opts
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ def extract_info(self, url, download=False):
+ raise DownloadError("No video could be found in this tweet")
+
+ utils = types.ModuleType("yt_dlp.utils")
+ utils.DownloadError = DownloadError
+ fake = types.ModuleType("yt_dlp")
+ fake.YoutubeDL = FakeYDL
+ fake.utils = utils
+ monkeypatch.setitem(sys.modules, "yt_dlp", fake)
+ monkeypatch.setitem(sys.modules, "yt_dlp.utils", utils)
+
+
+class _FakeGalleryExtractor:
+ """Mimics a gallery-dl extractor: iterating yields (message_type, url,
+ kwdict) tuples, type 3 being ``Message.Url`` (a downloadable file)."""
+
+ def __init__(self, items):
+ self._items = items
+
+ def __iter__(self):
+ yield (2, "", {}) # Message.Directory — ignored by our code
+ for url, kw in self._items:
+ yield (3, url, kw)
+
+ def request(self, url):
+ class Resp:
+ content = _png_bytes()
+
+ return Resp()
+
+
+def test_gallery_dl_fallback_downloads_single_image(client, monkeypatch):
+ """A photo-only tweet: yt-dlp raises, gallery-dl finds one image — it
+ must still land in the case, with provenance naming gallery-dl."""
+ import gallery_dl.extractor as gdl_extractor
+
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "GalleryFallback"}).json()["id"]
+ case = Case.open(cid)
+
+ _install_failing_ydl(monkeypatch)
+ items = [
+ (
+ "https://pbs.twimg.com/media/abc.jpg",
+ {
+ "filename": "abc",
+ "extension": "jpg",
+ "content": "Impact on the substation\nsecond line",
+ "author": {"nick": "someone"},
+ },
+ )
+ ]
+ monkeypatch.setattr(gdl_extractor, "find", lambda url: _FakeGalleryExtractor(items))
+
+ result = media_engine.download_url(case, "https://x.com/u/status/1")
+ assert result["multi"] is False
+ assert result["item"]["source"]["downloader"] == "gallery-dl"
+ assert result["item"]["title"] == "Impact on the substation"
+ assert result["item"]["source"]["uploader"] == "someone"
+
+
+def test_gallery_dl_fallback_multi_images(client, monkeypatch):
+ """Two photos on the same post: reported as a picker like the yt-dlp
+ path, downloads nothing until an ``index`` is picked."""
+ import gallery_dl.extractor as gdl_extractor
+
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "GalleryMulti"}).json()["id"]
+ case = Case.open(cid)
+ items = [
+ ("https://pbs.twimg.com/media/a.jpg", {"filename": "a", "extension": "jpg"}),
+ ("https://pbs.twimg.com/media/b.png", {"filename": "b", "extension": "png"}),
+ ]
+
+ _install_failing_ydl(monkeypatch)
+ monkeypatch.setattr(gdl_extractor, "find", lambda url: _FakeGalleryExtractor(items))
+
+ result = media_engine.download_url(case, "https://x.com/u/status/2")
+ assert result == {
+ "multi": True,
+ "items": [
+ {"index": 1, "title": "a", "thumbnail": items[0][0], "kind": "image"},
+ {"index": 2, "title": "b", "thumbnail": items[1][0], "kind": "image"},
+ ],
+ }
+ assert case.read()["entities"] == []
+
+ picked = media_engine.download_url(case, "https://x.com/u/status/2", index=2)
+ assert picked["multi"] is False
+ assert picked["item"]["filename"].startswith("b")
+
+
+def test_gallery_dl_fallback_no_extractor_raises(client, monkeypatch):
+ """Neither yt-dlp nor gallery-dl recognizes the link — a clear error, not
+ a silent no-op."""
+ import gallery_dl.extractor as gdl_extractor
+
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "GalleryNone"}).json()["id"]
+ case = Case.open(cid)
+
+ _install_failing_ydl(monkeypatch)
+ monkeypatch.setattr(gdl_extractor, "find", lambda url: None)
+
+ try:
+ media_engine.download_url(case, "https://example.com/nope")
+ raise AssertionError("expected RuntimeError")
+ except RuntimeError as exc:
+ assert "no extractor" in str(exc)
+
+
+def test_telegram_extra_photos_parses_embed_html(monkeypatch):
+ """Unit test for the Telegram photo scraper itself: extracts photo CDN
+ URLs from the embed page's markup, and never makes a network call at all
+ for a non-Telegram URL (the domain check short-circuits first)."""
+ from azimut.engine import media as media_engine
+
+ html = """
+ <a class="tgme_widget_message_photo_wrap grouped_media_wrap blured js-message_photo"
+ style="background-image:url('https://cdn1.telesco.pe/file/AAA')"></a>
+ <a class="tgme_widget_message_photo_wrap grouped_media_wrap blured js-message_photo"
+ style="background-image:url('https://cdn1.telesco.pe/file/BBB')"></a>
+ """
+
+ class FakeResp:
+ text = html
+
+ def raise_for_status(self):
+ pass
+
+ import requests
+
+ monkeypatch.setattr(requests, "get", lambda *a, **kw: FakeResp())
+
+ photos = media_engine._telegram_extra_photos("https://t.me/exilenova_plus/24988")
+ assert [p["url"] for p in photos] == [
+ "https://cdn1.telesco.pe/file/AAA",
+ "https://cdn1.telesco.pe/file/BBB",
+ ]
+
+ def boom(*a, **kw):
+ raise AssertionError("must not be called for a non-Telegram URL")
+
+ monkeypatch.setattr(requests, "get", boom)
+ assert media_engine._telegram_extra_photos("https://x.com/u/status/1") == []
+
+
+def test_download_merges_telegram_video_and_photos(client, monkeypatch):
+ """A mixed Telegram album (2 videos yt-dlp finds + 2 photos it silently
+ drops) must surface all 4 in one picker, videos first then photos, not
+ just the videos yt-dlp itself reports."""
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "TelegramMixed"}).json()["id"]
+ case = Case.open(cid)
+
+ entries = [
+ {"id": "v1", "title": "clip one", "ext": "mp4"},
+ {"id": "v2", "title": "clip two", "ext": "mp4"},
+ ]
+ _install_fake_ydl(
+ monkeypatch, lambda ydl, url, download: {"_type": "playlist", "entries": entries}
+ )
+ monkeypatch.setattr(
+ media_engine,
+ "_telegram_extra_photos",
+ lambda url: [{"url": "https://cdn/a.jpg"}, {"url": "https://cdn/b.jpg"}],
+ )
+
+ result = media_engine.download_url(case, "https://t.me/exilenova_plus/24988")
+ assert result["multi"] is True
+ assert [(i["index"], i["kind"]) for i in result["items"]] == [
+ (1, "video"),
+ (2, "video"),
+ (3, "image"),
+ (4, "image"),
+ ]
+ assert case.read()["entities"] == [] # detection only — nothing downloaded
+
+
+def test_download_picks_telegram_photo_from_mixed_post(client, monkeypatch):
+ """Picking index 3 out of the merged 2-video + 2-photo post must resolve
+ to the *first* extra photo, not a yt-dlp entry."""
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "TelegramPickPhoto"}).json()["id"]
+ case = Case.open(cid)
+
+ entries = [{"id": "v1", "title": "clip one", "ext": "mp4"}, {"id": "v2", "title": "clip two", "ext": "mp4"}]
+ _install_fake_ydl(
+ monkeypatch, lambda ydl, url, download: {"_type": "playlist", "entries": entries}
+ )
+ monkeypatch.setattr(
+ media_engine,
+ "_telegram_extra_photos",
+ lambda url: [{"url": "https://cdn/a.jpg"}, {"url": "https://cdn/b.jpg"}],
+ )
+
+ captured = {}
+
+ def fake_register(case_, post_url, photo, *, title=None):
+ captured["photo"] = photo
+ return {"multi": False, "item": {"filename": "a.jpg"}}
+
+ monkeypatch.setattr(media_engine, "_register_telegram_photo", fake_register)
+
+ result = media_engine.download_url(case, "https://t.me/exilenova_plus/24988", index=3)
+ assert captured["photo"]["url"] == "https://cdn/a.jpg"
+ assert result["item"]["filename"] == "a.jpg"
+
+
+def test_download_picks_yt_dlp_video_from_mixed_post(client, monkeypatch):
+ """Picking index 2 out of the same merged post must still resolve to
+ yt-dlp's second video entry, not a photo."""
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "TelegramPickVideo"}).json()["id"]
+ case = Case.open(cid)
+
+ entries = [{"id": "v1", "title": "clip one", "ext": "mp4"}, {"id": "v2", "title": "clip two", "ext": "mp4"}]
+ _install_fake_ydl(
+ monkeypatch, lambda ydl, url, download: {"_type": "playlist", "entries": entries}
+ )
+ monkeypatch.setattr(
+ media_engine,
+ "_telegram_extra_photos",
+ lambda url: [{"url": "https://cdn/a.jpg"}, {"url": "https://cdn/b.jpg"}],
+ )
+
+ result = media_engine.download_url(case, "https://t.me/exilenova_plus/24988", index=2)
+ assert result["item"]["source"]["title"] == "clip two"
+
+
+def test_concurrent_downloads_dont_lose_entities(client, monkeypatch):
+ """The multi-item picker fires one download per selected attachment, and
+ those run concurrently (each on its own job thread). Every one of them
+ ends in ``_register`` -> ``case.add_entity``, a read-modify-write of
+ case.json — without a lock, whichever thread wins the write races drops
+ every entity added in between (regression: reported as attachments
+ silently vanishing / only one of several selected items ending up filed)."""
+ import threading
+
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "Concurrent"}).json()["id"]
+ case = Case.open(cid)
+ n = 8
+
+ def extract_info(ydl, url, download):
+ idx = int(ydl.opts["playlist_items"])
+ time.sleep(0.02) # widen the race window
+ return {"id": f"item{idx}", "title": f"clip {idx}"}
+
+ # distinct bytes per item — identical content would legitimately dedup
+ # via sha256 and mask what this test is actually checking (entity loss,
+ # not the separate dedup-check race)
+ _install_fake_ydl(
+ monkeypatch, extract_info, content_fn=lambda info: _png_bytes(color=(int(info["id"][4:]), 0, 0))
+ )
+
+ errors = []
+
+ def run(i):
+ try:
+ media_engine.download_url(case, "https://x.com/u/status/1", index=i, title=f"title {i}")
+ except Exception as exc: # pragma: no cover - assertion below reports it
+ errors.append(exc)
+
+ threads = [threading.Thread(target=run, args=(i,)) for i in range(1, n + 1)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ assert errors == []
+ assert len(case.read()["entities"]) == n
+ assert len(client.get(f"/api/cases/{cid}/media").json()) == n
+
+
def test_download_job_bad_url(client):
cid = client.post("/api/cases", json={"name": "Job"}).json()["id"]
job_id = client.post(
diff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.py
index f6641bb..e3250f1 100644
--- a/tests/test_satellite_api.py
+++ b/tests/test_satellite_api.py
@@ -9,6 +9,13 @@ def _fake_tile(client, url): # offline: every tile is a solid green square
return Image.new("RGB", (256, 256), (10, 120, 10))
+def test_providers_flag_imagery_vs_street(client):
+ # the UI uses `imagery` to disable the OSM labels overlay over street maps
+ providers = {p["id"]: p for p in client.get("/api/satellite/providers").json()}
+ assert providers["esri-world-imagery"]["imagery"] is True
+ assert providers["osm"]["imagery"] is False
+
+
def test_capture_persists_bearing(client, monkeypatch):
monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
@@ -74,6 +81,80 @@ def test_capture_creates_capture_entity_not_place(client, monkeypatch):
assert caps[0]["provenance"]["status"] == "confirmed"
+def test_capture_lands_in_media_library(client, monkeypatch):
+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+ cap = _capture(client, cid, 48.8584, 2.2945)
+ # a capture now lives in media/ so the Media Library lists it and Inspect can open it
+ assert cap["path"].startswith("media/")
+ media = client.get(f"/api/cases/{cid}/media").json()
+ entry = next(m for m in media if m["path"] == cap["path"])
+ assert entry["kind"] == "image"
+ assert entry["source"]["type"] == "satellite"
+ # it carries a thumbnail like any other media item
+ assert entry["thumbnail"]
+
+
+def test_capture_records_both_dates(client, monkeypatch):
+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+ result = client.post(
+ f"/api/cases/{cid}/satellite/capture",
+ json={"lat": 48.8584, "lon": 2.2945, "zoom": 16, "width": 512, "height": 512,
+ "imagery_date": "2021-06-01"},
+ ).json()
+ # capture timestamp (when clicked) and imagery acquisition date (the scene)
+ assert result["fetched_at"] # ISO capture timestamp
+ assert result["imagery_date"] == "2021-06-01"
+ listed = client.get(f"/api/cases/{cid}/satellite").json()[0]
+ assert listed["fetched_at"] == result["fetched_at"]
+ assert listed["imagery_date"] == "2021-06-01"
+
+
+def test_capture_imagery_date_optional(client, monkeypatch):
+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+ # no imagery date known → recorded as null, capture still succeeds
+ result = _capture(client, cid, 48.8584, 2.2945)
+ assert result["imagery_date"] is None
+
+
+def test_imagery_date_non_esri_is_unsupported(client):
+ out = client.get(
+ "/api/satellite/imagery-date",
+ params={"lat": 48.8584, "lon": 2.2945, "zoom": 16, "provider": "osm"},
+ ).json()
+ assert out == {"supported": False, "date": None, "source": None}
+
+
+def test_imagery_date_esri_best_effort(client, monkeypatch):
+ class _Resp:
+ def raise_for_status(self):
+ pass
+
+ def json(self):
+ return {"results": [{"attributes": {"NICE_NAME": "Maxar", "SRC_DATE2": "20200103"}}]}
+
+ monkeypatch.setattr(tiles.httpx, "get", lambda *a, **k: _Resp())
+ out = client.get(
+ "/api/satellite/imagery-date",
+ params={"lat": 48.8584, "lon": 2.2945, "zoom": 16},
+ ).json()
+ assert out == {"supported": True, "date": "2020-01-03", "source": "Maxar"}
+
+
+def test_imagery_date_service_down_is_graceful(client, monkeypatch):
+ def boom(*a, **k):
+ raise OSError("down")
+
+ monkeypatch.setattr(tiles.httpx, "get", boom)
+ out = client.get(
+ "/api/satellite/imagery-date",
+ params={"lat": 0, "lon": 0, "zoom": 10},
+ ).json()
+ assert out == {"supported": True, "date": None, "source": None}
+
+
def test_save_place_creates_place_without_image(client):
cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
place = client.post(
diff --git a/tests/test_settings_api.py b/tests/test_settings_api.py
new file mode 100644
index 0000000..254cf9e
--- /dev/null
+++ b/tests/test_settings_api.py
@@ -0,0 +1,176 @@
+"""Settings API: API keys management, key tests, usage counters (all offline)."""
+
+import httpx
+
+from azimut import config
+from azimut.engine import google_tiles
+
+
+def test_get_settings_defaults(client):
+ body = client.get("/api/settings").json()
+ assert body["api_keys"] == {}
+ assert body["usage"] == {}
+ assert body["month"] == config.month_key()
+
+
+def test_put_keys_lights_up_keyed_providers(client):
+ saved = client.put("/api/settings/keys", json={"mapbox": "pk.abc"}).json()
+ assert saved["api_keys"] == {"mapbox": "pk.abc"}
+ ids = {p["id"] for p in client.get("/api/satellite/providers").json()}
+ assert "mapbox-satellite" in ids
+ assert "google-satellite" not in ids # no google key yet
+
+ client.put("/api/settings/keys", json={"google": "AIza.x"})
+ providers = {p["id"]: p for p in client.get("/api/satellite/providers").json()}
+ assert "mapbox-satellite" in providers # untouched key survives a partial PUT
+ google = providers["google-satellite"]
+ assert google["capturable"] is True
+ assert google["cacheable"] is False
+ assert google["session"] == "google"
+ assert google["meter"] == "google"
+
+
+def test_put_empty_key_removes_it(client):
+ client.put("/api/settings/keys", json={"mapbox": "pk.abc"})
+ saved = client.put("/api/settings/keys", json={"mapbox": " "}).json()
+ assert saved["api_keys"] == {}
+ ids = {p["id"] for p in client.get("/api/satellite/providers").json()}
+ assert "mapbox-satellite" not in ids
+
+
+def test_keys_never_reach_a_case_folder(client, monkeypatch):
+ """Principle 7: keys live in settings.json only — nothing under cases/."""
+ from PIL import Image
+
+ from azimut.engine import tiles
+
+ monkeypatch.setattr(
+ tiles, "_default_fetch", lambda c, u: Image.new("RGB", (256, 256), (9, 9, 9))
+ )
+ client.put("/api/settings/keys", json={"mapbox": "pk.SECRET"})
+ cid = client.post("/api/cases", json={"name": "K"}).json()["id"]
+ client.post(
+ f"/api/cases/{cid}/satellite/capture",
+ json={"lat": 48.85, "lon": 2.29, "zoom": 15, "width": 512, "height": 512,
+ "provider": "mapbox-satellite"},
+ )
+ case_dir = config.cases_dir() / cid
+ hits = [
+ p for p in case_dir.rglob("*")
+ if p.is_file() and p.suffix in (".json", ".md") and "pk.SECRET" in p.read_text()
+ ]
+ assert hits == []
+
+
+def _upstream(status=200, content=b"JPEGDATA", headers=None):
+ def get(url, **kwargs):
+ get.urls.append(url)
+ return httpx.Response(
+ status, content=content,
+ headers={"content-type": "image/jpeg", **(headers or {})},
+ request=httpx.Request("GET", url),
+ )
+
+ get.urls = []
+ return get
+
+
+def test_tile_proxy_serves_and_counts_exactly(client, monkeypatch):
+ client.put("/api/settings/keys", json={"mapbox": "pk.abc"})
+ upstream = _upstream(headers={"cache-control": "max-age=43200"})
+ monkeypatch.setattr(httpx, "get", upstream)
+
+ r = client.get("/api/tiles/mapbox-satellite/14/8298/5639")
+ assert r.status_code == 200
+ assert r.content == b"JPEGDATA"
+ assert r.headers["content-type"] == "image/jpeg"
+ # provider cache policy passed through so the browser caches (and a cached
+ # tile never re-hits the proxy — the counter can't over-count)
+ assert r.headers["cache-control"] == "max-age=43200"
+ assert "access_token=pk.abc" in upstream.urls[0]
+ assert "/tiles/512/14/8298/5639" in upstream.urls[0]
+
+ client.get("/api/tiles/mapbox-satellite/14/8298/5640")
+ body = client.get("/api/settings").json()
+ assert body["usage"]["mapbox"][body["month"]] == 2 # one bump per served tile
+
+
+def test_tile_proxy_does_not_count_errors(client, monkeypatch):
+ client.put("/api/settings/keys", json={"mapbox": "pk.abc"})
+ monkeypatch.setattr(httpx, "get", _upstream(status=404, content=b""))
+ r = client.get("/api/tiles/mapbox-satellite/14/0/0")
+ assert r.status_code == 404
+ assert client.get("/api/settings").json()["usage"] == {}
+
+
+def test_tile_proxy_unknown_provider_404(client):
+ assert client.get("/api/tiles/nope/14/0/0").status_code == 404
+
+
+def test_tile_proxy_google_remints_session_on_403(client, monkeypatch):
+ client.put("/api/settings/keys", json={"google": "AIza.x"})
+ tokens = iter(["tok-stale", "tok-fresh"])
+ monkeypatch.setattr(
+ google_tiles, "resolve_template", lambda url, **kw: url.replace("{session}", next(tokens))
+ )
+ invalidated = []
+ monkeypatch.setattr(google_tiles, "invalidate", invalidated.append)
+
+ def get(url, **kwargs):
+ status = 403 if "session=tok-stale" in url else 200
+ return httpx.Response(
+ status, content=b"TILE", headers={"content-type": "image/jpeg"},
+ request=httpx.Request("GET", url),
+ )
+
+ monkeypatch.setattr(httpx, "get", get)
+ r = client.get("/api/tiles/google-satellite/15/16597/11278")
+ assert r.status_code == 200
+ assert r.content == b"TILE"
+ assert invalidated == ["AIza.x"]
+ body = client.get("/api/settings").json()
+ assert body["usage"]["google"][body["month"]] == 1 # the retry isn't double-counted
+
+
+def test_test_key_without_saved_key_is_404(client):
+ assert client.post("/api/settings/keys/mapbox/test").status_code == 404
+ assert client.post("/api/settings/keys/unknown/test").status_code == 404
+
+
+def test_test_key_mapbox_ok_and_failure(client, monkeypatch):
+ client.put("/api/settings/keys", json={"mapbox": "pk.abc"})
+
+ def ok(url, **kwargs):
+ assert "access_token=pk.abc" in url
+ return httpx.Response(200, request=httpx.Request("GET", url))
+
+ monkeypatch.setattr(httpx, "get", ok)
+ assert client.post("/api/settings/keys/mapbox/test").json()["ok"] is True
+
+ def unauthorized(url, **kwargs):
+ return httpx.Response(401, request=httpx.Request("GET", url))
+
+ monkeypatch.setattr(httpx, "get", unauthorized)
+ result = client.post("/api/settings/keys/mapbox/test").json()
+ assert result["ok"] is False
+ assert result["detail"]
+
+
+def test_test_key_google_mints_a_session(client, monkeypatch):
+ client.put("/api/settings/keys", json={"google": "AIza.x"})
+ minted = []
+
+ def fake_token(key, **kwargs):
+ minted.append(key)
+ return "tok"
+
+ monkeypatch.setattr(google_tiles, "session_token", fake_token)
+ assert client.post("/api/settings/keys/google/test").json()["ok"] is True
+ assert minted == ["AIza.x"]
+
+
+def test_providers_expose_tile_size(client):
+ client.put("/api/settings/keys", json={"mapbox": "pk.abc"})
+ providers = {p["id"]: p for p in client.get("/api/satellite/providers").json()}
+ assert providers["esri-world-imagery"]["tile_size"] == 256
+ assert providers["mapbox-satellite"]["tile_size"] == 512 # 4× cheaper, same m/px
diff --git a/tests/test_tiles.py b/tests/test_tiles.py
index 933f0f7..e6a4e70 100644
--- a/tests/test_tiles.py
+++ b/tests/test_tiles.py
@@ -1,9 +1,13 @@
"""Tile math and crop stitching (offline: injected fake tile fetcher)."""
+import dataclasses
import math
+import httpx
+import pytest
from PIL import Image
+from azimut import config
from azimut.engine import geo, tiles
@@ -136,13 +140,195 @@ def test_fetch_crop_bearing_zero_matches_unrotated():
def test_fetch_crop_tile_cap():
provider = tiles.BUILTIN_PROVIDERS[0]
try:
- tiles.fetch_crop(0, 0, 19, 2048, 2048, provider, fetch_tile=lambda c, u: None)
+ tiles.fetch_crop(
+ 0, 0, 19, tiles.SIZE_MAX, tiles.SIZE_MAX, provider,
+ fetch_tile=lambda c, u: None,
+ )
except tiles.TileFetchError as exc:
assert "tiles" in str(exc)
else: # pragma: no cover
raise AssertionError("expected TileFetchError for oversized crop")
+def test_all_providers_omits_keyed_providers_without_keys(monkeypatch, tmp_path):
+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
+ ids = {p.id for p in tiles.all_providers()}
+ assert "mapbox-satellite" not in ids
+ assert "google-satellite" not in ids
+
+
+def test_all_providers_adds_mapbox_when_keyed(monkeypatch, tmp_path):
+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
+ config.save_settings({**config.DEFAULT_SETTINGS, "api_keys": {"mapbox": "pk.test123"}})
+ mapbox = next(p for p in tiles.all_providers() if p.id == "mapbox-satellite")
+ assert "pk.test123" in mapbox.url
+ assert "{key}" not in mapbox.url
+ assert mapbox.capturable is True
+ assert mapbox.cacheable is True
+ assert mapbox.attribution_burn is False
+ assert mapbox.session is None
+ assert mapbox.max_zoom == 22
+
+
+def test_all_providers_adds_google_when_keyed(monkeypatch, tmp_path):
+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
+ config.save_settings({**config.DEFAULT_SETTINGS, "api_keys": {"google": "AIza.test123"}})
+ google = next(p for p in tiles.all_providers() if p.id == "google-satellite")
+ assert "AIza.test123" in google.url
+ assert "{session}" in google.url # resolved at fetch time (§3), not here
+ assert google.capturable is True
+ assert google.cacheable is False
+ assert google.attribution_burn is True
+ assert google.session == "google"
+
+
+def test_fetch_crop_rejects_non_capturable_provider():
+ provider = dataclasses.replace(tiles.BUILTIN_PROVIDERS[0], capturable=False)
+ with pytest.raises(tiles.TileFetchError, match="view-only"):
+ tiles.fetch_crop(0, 0, 10, 256, 256, provider, fetch_tile=lambda c, u: None)
+
+
+def _green_tile(client, url):
+ return Image.new("RGB", (256, 256), (10, 120, 10))
+
+
+def _keyed_provider(monkeypatch, tmp_path, name, key):
+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
+ config.save_settings({**config.DEFAULT_SETTINGS, "api_keys": {name: key}})
+ return next(p for p in tiles.all_providers() if p.id == f"{name}-satellite")
+
+
+def test_fetch_crop_mapbox_uses_512_tiles_and_meters_served(monkeypatch, tmp_path):
+ provider = _keyed_provider(monkeypatch, tmp_path, "mapbox", "pk.test")
+ assert provider.tile_size == 512
+ urls = []
+
+ def fetch(client, url):
+ urls.append(url)
+ return Image.new("RGB", (512, 512), (10, 120, 10))
+
+ img, prov = tiles.fetch_crop(48.8584, 2.2945, 15, 512, 512, provider, fetch_tile=fetch)
+ assert all("access_token=pk.test" in u for u in urls)
+ # 512px tiles: same m/px, but requested one zoom lower — 4× fewer billed tiles
+ assert all("/tiles/512/14/" in u for u in urls)
+ assert prov["zoom"] == 15 # provenance keeps the visual zoom
+ assert len(urls) <= 4 # a 512px crop needs at most 2×2 512px tiles, not 3×3 256s
+ assert prov["attribution"] == "© Mapbox © OpenStreetMap"
+ assert prov["attribution_burned"] is False
+ assert img.size == (512, 512) # no footer band for Mapbox
+ # exactly the tiles the provider served land in the monthly counter (§6)
+ assert config.load_settings()["usage"]["mapbox"][config.month_key()] == len(urls)
+
+
+def test_fetch_crop_512_grid_covers_the_canvas(monkeypatch, tmp_path):
+ provider = _keyed_provider(monkeypatch, tmp_path, "mapbox", "pk.test")
+
+ def fetch(client, url):
+ return Image.new("RGB", (512, 512), (10, 120, 10))
+
+ img, prov = tiles.fetch_crop(
+ 48.8584, 2.2945, 17, 900, 700, provider, marker_style="none", fetch_tile=fetch
+ )
+ assert prov["tiles_missing"] == 0
+ # no background showing through anywhere — the 512 grid must tile seamlessly
+ for xy in ((0, 0), (899, 0), (0, 699), (899, 699), (450, 350)):
+ assert img.getpixel(xy) == (10, 120, 10)
+
+
+def test_fetch_crop_missing_tiles_are_not_billed(monkeypatch, tmp_path):
+ provider = _keyed_provider(monkeypatch, tmp_path, "mapbox", "pk.test")
+ calls = {"n": 0}
+
+ def fetch(client, url):
+ calls["n"] += 1
+ return None if calls["n"] == 1 else Image.new("RGB", (512, 512), (10, 120, 10))
+
+ img, prov = tiles.fetch_crop(48.8584, 2.2945, 15, 900, 900, provider, fetch_tile=fetch)
+ assert prov["tiles_missing"] == 1
+ # only tiles the provider actually served count toward the meter
+ usage = config.load_settings()["usage"]["mapbox"][config.month_key()]
+ assert usage == prov["tiles"] - 1
+
+
+def test_fetch_crop_unmetered_provider_records_nothing(monkeypatch, tmp_path):
+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
+ tiles.fetch_crop(
+ 48.8584, 2.2945, 15, 512, 512, tiles.BUILTIN_PROVIDERS[0], fetch_tile=_green_tile
+ )
+ assert config.load_settings()["usage"] == {}
+
+
+def test_fetch_crop_google_resolves_session_and_burns_attribution(monkeypatch, tmp_path):
+ provider = _keyed_provider(monkeypatch, tmp_path, "google", "AIza.test")
+ monkeypatch.setattr(
+ tiles.google_tiles,
+ "resolve_template",
+ lambda url, **kw: url.replace("{session}", "tok-live"),
+ )
+ monkeypatch.setattr(
+ tiles.google_tiles,
+ "viewport_copyright",
+ lambda *a, **kw: "Map data ©2026 Google, Maxar Technologies",
+ )
+ urls = []
+
+ def fetch(client, url):
+ urls.append(url)
+ return _green_tile(client, url)
+
+ img, prov = tiles.fetch_crop(48.8584, 2.2945, 15, 512, 512, provider, fetch_tile=fetch)
+ assert all("session=tok-live" in u and "key=AIza.test" in u for u in urls)
+ # dynamic viewport copyright recorded, not just "Google"
+ assert prov["attribution"] == "Map data ©2026 Google, Maxar Technologies"
+ assert prov["attribution_burned"] is True
+ # the footer band is appended below the imagery, never covering it
+ assert img.size == (512, 512 + tiles.ATTRIBUTION_BAND)
+ assert img.getpixel((0, 512 + tiles.ATTRIBUTION_BAND - 1)) == (16, 18, 24)
+ assert img.getpixel((0, 511)) == (10, 120, 10) # imagery intact
+ assert config.load_settings()["usage"]["google"][config.month_key()] == prov["tiles"]
+
+
+def test_fetch_crop_google_remints_session_on_403(monkeypatch, tmp_path):
+ provider = _keyed_provider(monkeypatch, tmp_path, "google", "AIza.test")
+ tokens = iter(["tok-stale", "tok-fresh"])
+ monkeypatch.setattr(
+ tiles.google_tiles,
+ "resolve_template",
+ lambda url, **kw: url.replace("{session}", next(tokens)),
+ )
+ invalidated = []
+ monkeypatch.setattr(tiles.google_tiles, "invalidate", invalidated.append)
+ monkeypatch.setattr(tiles.google_tiles, "viewport_copyright", lambda *a, **kw: None)
+
+ def fetch(client, url):
+ if "session=tok-stale" in url:
+ request = httpx.Request("GET", url)
+ raise httpx.HTTPStatusError(
+ "expired", request=request, response=httpx.Response(403, request=request)
+ )
+ assert "session=tok-fresh" in url
+ return _green_tile(client, url)
+
+ img, prov = tiles.fetch_crop(48.8584, 2.2945, 15, 512, 512, provider, fetch_tile=fetch)
+ assert invalidated == ["AIza.test"]
+ assert prov["tiles_missing"] == 0
+ # no viewport copyright reachable — static fallback still carried & burned
+ assert prov["attribution"] == "Google"
+
+
+def test_record_usage_rolls_months(monkeypatch, tmp_path):
+ from datetime import datetime, timezone
+
+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
+ july = datetime(2026, 7, 20, tzinfo=timezone.utc)
+ august = datetime(2026, 8, 2, tzinfo=timezone.utc)
+ assert config.record_usage("google", 5, when=july) == 5
+ assert config.record_usage("google", 3, when=july) == 8
+ assert config.record_usage("google", 2, when=august) == 2 # fresh bucket
+ usage = config.load_settings()["usage"]["google"]
+ assert usage == {"2026-07": 8, "2026-08": 2}
+
+
def test_parse_coords():
assert geo.parse_coords("50.4501, 30.5234") == (50.4501, 30.5234)
assert geo.parse_coords("50.4501 30.5234") == (50.4501, 30.5234)
@@ -162,3 +348,46 @@ def test_plus_code_known_value():
def test_dms_format():
assert geo.to_dms(48.8584, 2.2945).endswith('E')
assert "N" in geo.to_dms(48.8584, 2.2945)
+
+
+def test_map_links_cover_external_maps():
+ links = geo.map_links(48.8584, 2.2945, 16)
+ for key in ("google", "google_earth", "bing", "yandex", "sentinel", "zoom_earth"):
+ assert key in links and links[key].startswith("https://")
+ # Yandex takes lon,lat order
+ assert "ll=2.2945,48.8584" in links["yandex"]
+
+
+class _FakeResp:
+ def __init__(self, payload):
+ self._payload = payload
+
+ def raise_for_status(self):
+ pass
+
+ def json(self):
+ return self._payload
+
+
+def test_esri_capture_date_parses_yyyymmdd():
+ payload = {"results": [{"attributes": {"NICE_NAME": "Maxar", "SRC_DATE2": "20210514"}}]}
+ out = tiles.esri_capture_date(48.8584, 2.2945, 17, get=lambda *a, **k: _FakeResp(payload))
+ assert out == {"date": "2021-05-14", "source": "Maxar"}
+
+
+def test_esri_capture_date_full_date_beats_year():
+ payload = {"results": [{"attributes": {"SRC_DATE": "2019", "SRC_DATE2": "20200103"}}]}
+ out = tiles.esri_capture_date(0, 0, 17, get=lambda *a, **k: _FakeResp(payload))
+ assert out["date"] == "2020-01-03"
+
+
+def test_esri_capture_date_empty_results():
+ out = tiles.esri_capture_date(0, 0, 17, get=lambda *a, **k: _FakeResp({"results": []}))
+ assert out == {"date": None, "source": None}
+
+
+def test_esri_capture_date_network_failure_returns_none():
+ def boom(*a, **k):
+ raise OSError("down")
+
+ assert tiles.esri_capture_date(0, 0, 17, get=boom) is None