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

M6: per-piece collage crop, Proof Composer grid/resize/tweet-fit, ontology doc (#5)

OsintMeThatca321f6ae582
diff --git a/docs/ONTOLOGY.md b/docs/ONTOLOGY.md
new file mode 100644
index 0000000..40bd6f8
--- /dev/null
+++ b/docs/ONTOLOGY.md
@@ -0,0 +1,138 @@
+# Ozimut ontology (case data model)
+
+> The contract every tool files against. Companion to [SPEC.md §5](SPEC.md); the
+> spec stays a summary, this is the precise vocabulary. Keep it small, coherent,
+> extensible, **versioned** — grown from real tool needs, never a whiteboard
+> taxonomy. Nothing enters a case without a human click (SPEC principle 5).
+
+**Schema version: `0`** (draft, 2026-07-10, aligns with spec v0.2). Bump on any
+breaking change to entity/link shape; ship a migration when you do.
+
+Legend: ✅ implemented in code · 🔶 machinery exists, unused · ⬜ proposed.
+
+---
+
+## 1. Where it lives
+
+`case.json` is the single source of truth for the graph:
+
+```jsonc
+{ "entities": [ … ], "links": [ … ], "folders": [ … ] }
+```
+
+- **Entities** = the nodes (files, points, proofs, people…). ✅
+- **Links** = typed directed edges between nodes. 🔶 (shape + CRUD exist in
+ `workspace.py`; **no tool emits any yet** — every derivation is currently
+ implicit in entity `attrs` paths. Closing this is the #1 ontology task.)
+- **Folders** = the analyst's own `/`-nested buckets (`attrs.folder`), an
+ organisational overlay, **not** semantic links. ✅
+- Rich per-media metadata (kind, size, uploader, duration, thumbnail…) lives in a
+ **media sidecar**, not on the entity — the entity carries only what the graph
+ needs to point and dedupe.
+
+## 2. Entity
+
+```jsonc
+{ "id": "e_ab12cd34", // _new_id("e")
+ "type": "capture", // from the registry below (free strings allowed)
+ "label": "48.8584, 2.2945", // human-readable, editable
+ "attrs": { … }, // per-type, see registry
+ "provenance": { "by": "satellite", "at": "2026-07-10T…Z",
+ "status": "confirmed", "source": "https://…" } }
+```
+
+Rules: `type` is extensible — unknown strings are accepted and stored; the UI
+just doesn't get a custom renderer for them (SPEC §5 escape hatch, keep it).
+`label` is always editable and never load-bearing for identity.
+
+### Entity type registry
+
+| Type | State | Produced by | Key `attrs` | File-backed |
+|---|---|---|---|---|
+| `media` | ✅ | media-library | `path`, `sha256`, `source_url?` | yes (+ sidecar) |
+| `capture` | ✅ | satellite | `coords`, `lat`, `lon`, `plus_code`, `zoom`, `bearing`, `path` | yes (image) |
+| `place` | ✅ | satellite | `coords`, `lat`, `lon`, `plus_code`, `dms`, `zoom`, `bearing`, `notes?` | no (a point) |
+| `proof` | ✅ | proof-composer | `spec` (json), `path` (png) | yes |
+| `post` | ✅ | post-composer | `draft` (json) | yes |
+| `inspect-session` | ✅ | inspect | `spec` (json) | yes |
+| `note` | ✅ | (manual) | free | no |
+| `person` | ⬜ | manual / future | name attrs | no |
+| `organization` | ⬜ | manual / future | | no |
+| `alias` / `account` | ⬜ | future orchestrator | `platform`, `handle`, `url` | no |
+| `email` `phone` `domain` `ip` | ⬜ | future | the identifier | no |
+| `vehicle` | ⬜ | future (OCR plate) | `plate`, `make` | no |
+| `event` | ⬜ | future (EXIF, timeline) | `when`, `where` | no |
+
+New types coming from the roadmap (declare here when built): `panorama`,
+`ground-image`, `map-board`, `report`.
+
+Per-type **attribute schemas** are the main open work: fix a controlled vocab of
+attr keys per type so tools read each other's output reliably. Today attrs are
+convention, not contract.
+
+## 3. Link (the gap)
+
+```jsonc
+{ "id": "l_…", "from": "e_proof", "to": "e_capture",
+ "type": "derived-from",
+ "provenance": { "by": "proof-composer", "at": "…", "status": "confirmed" } }
+```
+
+Directed: read as **`from` → `type` → `to`**. Removing an entity cascades to
+drop every link touching it (`remove_entity`, ✅).
+
+### Link type registry (proposed core)
+
+| Type | from → to | Meaning | Priority |
+|---|---|---|---|
+| `derived-from` | artifact → source | provenance chain: this was made from that | ⬜ **#1** |
+| `located-at` | media/proof/event → place | happened / shot at this point | ⬜ |
+| `depicts` / `appears-in` | media → place/vehicle/person | subject shown in the media | ⬜ |
+| `same-as` | entity → entity | two records, one real thing (merge) | ⬜ |
+| `owns` | person/org → account/asset | ownership | ⬜ |
+| `posted` | account → media/post | authorship | ⬜ |
+| `mentions` | media/note → any | referenced, weaker than depicts | ⬜ |
+
+Free-typed labels stay allowed (SPEC §5) — the registry is the well-known set the
+UI understands, not a closed list.
+
+### The derivation chain (why `derived-from` is #1)
+
+The chain you want to walk — `post ← proof ← {capture, frame} ← video ← download`
+— exists today only as file paths inside `attrs`, so nothing can traverse it.
+Emitting `derived-from` edges at save time turns on the derivation breadcrumbs,
+the cross-tool "relations", and the Case Board graph, all at once:
+
+```
+post ──derived-from──▶ proof ──derived-from──▶ capture ──(provenance: provider,zoom,bearing)
+ └────derived-from──▶ media(frame) ──derived-from──▶ media(video)
+```
+
+Each tool that already writes a source pointer in `attrs` should *also* call
+`add_link(..., "derived-from", ...)` — same click, no new ceremony (principle 3).
+
+## 4. Provenance, confidence, identity
+
+- **Provenance** (on every entity *and* link): `by` (tool id — `media-library`,
+ `satellite`, `proof-composer`, `post-composer`, `inspect`, or `manual`), `at`
+ (UTC), `status`, optional `source` (a URL). Borrow the *shape* of W3C PROV
+ (entity/activity/agent) conceptually — don't adopt the standard wholesale.
+- **Confidence** = `status`: `confirmed` (analyst-made or analyst-accepted) vs
+ `suggested` (a tool proposed it, awaiting a click). ✅ Binary on purpose —
+ honest and simple; resist finer grading until a tool truly needs it.
+- **`same-as` / merge** (⬜ open, SPEC §9): when two entities are one real thing,
+ link `same-as` rather than destructively merging; a resolver treats a `same-as`
+ cluster as one node in views and unions their attrs/links. Keeps it reversible
+ and auditable. Decide the collapse rules before the first orchestrator tool
+ produces duplicate accounts.
+
+## 5. Design rules
+
+1. **Extensible core, not complete taxonomy.** Small well-known set + free-string
+ escape hatch. Grow from real tool needs.
+2. **Nothing without a click.** Tools emit `suggested`; the analyst confirms
+ (principle 5). Auto-created links are `suggested` too.
+3. **Two-way delete.** An artifact and its entity are one thing; deleting either
+ drops the other and its links (SPEC §6 delete/edit sync).
+4. **Version the schema.** This file's version travels with `case.json`; a bump
+ ships a migration. Do the formalisation now, while the corpus is tiny.
diff --git a/docs/SPEC.md b/docs/SPEC.md
index 9bb6b1c..2c95b52 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -96,6 +96,10 @@ The entity model is the backbone of the workbench, so the **schema exists from
v1** even though the rich UI (graph, map, timeline views) arrives later. This
avoids painful migrations and lets early tools file their outputs correctly.
+> Full vocabulary — entity types, per-type attribute schemas, the link registry
+> (incl. the `derived-from` chain), provenance/confidence/`same-as` rules — lives
+> in the versioned [**ONTOLOGY.md**](ONTOLOGY.md). This section stays a summary.
+
**Entity types** (extensible): `person`, `organization`, `alias/username`,
`account` (X, Telegram, VK, …), `email`, `phone`, `domain`, `ip`, `vehicle`,
`place`, `event`, `media` (photo/video/audio/document), `proof`.
@@ -146,9 +150,9 @@ 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**, live-previewed, with a fold-out **Analyze** (histogram, EXIF, ELA *hint*). **Collage**: drag/scale and **corner-warp** tray frames (thumbnails show each frame's current adjustments) on a canvas into a hand-made panorama; the canvas fill is a color or **transparent** (RGBA PNG export of just the pieces). Auto-stitch = later. **Save**: tick which of {enhanced video, adjusted frames, collage} to file — each re-derived full-res on the backend with provenance back to its source, into an optional folder; the collage shows a live miniature 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 intact; re-saving a reopened session **overwrites it in place** (even after a rename). Adjust/analysis controls come from self-describing filter/analysis registries. |
+| **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 side by side (frames, photos, satellite crops, imported screenshots); 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**. Palette presets **+ custom color picker**. Legend **annotations are written per color** (one note per feature), while a separate **element list** (id + kind) selects/deletes individual shapes. Per-panel captions; numbered feature legend; export `proof.png` + re-editable JSON spec (`notes` per color) saved in `proofs/`. |
+| **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/`. |
| **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 — Ozimut 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. |
@@ -190,15 +194,17 @@ v1 notes:
| **Coordinates** | Convert DMS/decimal/MGRS/plus code/geohash; reverse geocode (Nominatim); quick-open links to Google Maps/Yandex/Bing/OSM. |
| **EXIF & Metadata** | Photos and videos: GPS, timestamps, device, codecs — parsed locally, with a "what was stripped" hint. Suggests `place`/`event` entities. |
| **Shadow Clock** | Mark a shadow on a photo, get possible capture times for given coordinates and date range (sun-position math, local). |
-| **Reverse Search Launcher** | Any image/frame → search links for Google/Yandex/Bing/TinEye (opens browser tabs; no scraping). First orchestrator-pattern tool. |
+| **Reverse Search Launcher** | *Entry point in **Media Library**.* Any image/frame → reverse-search links for Google/Yandex/Bing/TinEye (opens browser tabs; no scraping). First orchestrator-pattern tool. Twist beyond plain links: an **age/origin hint** — surface the *oldest* dates the engines expose for a match so the analyst can spot recycled/old imagery and trace toward the original source. Analyst files what they pick as entities with provenance; no automated verdict. |
| **OCR** | Read signs/plates on a frame (tesseract), detect script/language. Suggests entities. |
-| **Panorama** | Stitch a video time window into one wide view (cv2.Stitcher with fallbacks). |
+| **Ground Imagery** | See ground-level photos around a coordinate. **Key-less open sources first** — Panoramax, Mapillary, KartaView — so it works for everyone (principle 7). **Street View**: a zero-config **easy link** (`google.com/maps?layer=c`) ships first; an optional user-keyed in-app view is gated by the settings usage counter. Picked shots file as sourced `media`/`capture` entities with provenance. |
+| **Panorama** | Stitch a video time window (or a set of frames) into one wide view — `cv2.Stitcher` with fallbacks. **Pulled early into Inspect** (like Frame Extractor): an **auto-stitch** button on the collage that complements the existing hand-made warp collage — machine stitch first, hand-tune after. |
### v3 — the investigation layer (entities take the front seat)
| Tab | What it does |
|-----|--------------|
| **Case Board / Relations** | The entity UI: browse, create, merge entities; typed links; **graph, timeline and map views** over the schema that has been filling up since v1. Select a person → see their accounts, media, places, connections. |
+| **Map Board (MyMaps-style)** | An interactive, editable case map: drop **custom pins** (icon/color) with **notes + links**, draw shapes, group into layers; save/reopen as a case artifact; **import & export KML/KMZ/GeoJSON** to round-trip with Google Earth/MyMaps. Pins bind to `place` entities — the case's map view, exportable and handable to someone else. |
| **Evidence Locker** | Every piece of evidence: sha256, timestamps, source URL, notes; one-click Wayback Machine archiving; exportable chain-of-custody log (`evidence.jsonl`). |
| **Timeline Builder** | Timestamped events from mixed sources aligned on an interactive timeline + map. |
| **Report Builder** | Assemble proofs, maps, timeline extracts, entity summaries and notes into a publishable HTML/PDF report. |
@@ -215,6 +221,29 @@ v1 notes:
| **Manipulation Hints** | ELA (*shipped in Inspect*), JPEG quantization, noise inconsistencies — first-pass tampering indicators, honestly labeled as *hints*. |
| **Channel Monitor** | Watch Telegram channels/accounts, auto-archive media into the case, queue items for geolocation. (Needs care: rate limits, ToS.) |
+### Idea backlog (unscheduled)
+
+Loose ideas, not yet slotted into a version. Promote into a table above when a
+workflow forms; delete if it stops making sense. One line each.
+
+- **Auto-panorama in collage** — auto-stitch button in Inspect (see v2 Panorama).
+- **Reverse-search + age/origin hint** in Media Library (see v2 Reverse Search).
+- **Audio analyzer** — local transcription (Whisper) + sound-pattern *hint* (gunfire/engine signatures).
+- **More satellite basemaps** — Sentinel-2 (date slider), OSM context, user-keyed Bing/Google (grows v2 Satellite Compare).
+- **Sat-vs-screen compare** — overlay/swipe/pixel-diff alignment aid; assist, never an auto-verdict (principle 5). Grows v2 Image Compare.
+- **AI-generated media detector** — a v4 Manipulation *hint*, loudly labeled, never a judgment.
+- **Weather / METAR history** — corroborate a claimed date+coords (snow/clear/rain) from free archives; pairs with Shadow Clock into a chronolocation panel.
+- **Measure-on-imagery** — draw a scale/distance line on a satellite capture to match feature sizes in-frame (focused v4 Map Measures slice).
+- **Archive-on-download** — optional Wayback push on URL import, archive URL into provenance (early Evidence Locker slice).
+- **3D satellite capture** — after MapLibre 2D parity: pitch/terrain + oblique capture (see §7).
+- **A gif maker** — To visualize before / after with annotations.
+- **Tools links page** — A page with many OSINT tools links.
+- **Copernicus view or easy link** — A Copernicus easy links or viewer (https://browser.dataspace.copernicus.eu/).
+- **Free-form montage editor** — only if a crisp boundary vs Proof Composer + Inspect collage is drawn first (else grow Inspect's collage); risk = scope-creep into a paint app.
+- **Case bundle export/import** — one-click **.zip** of the whole case a recipient opens in their own Ozimut. A zip, not a hosted link (principle 1: no server).
+- **Auto-translation → English** — local/offline (Whisper translate for audio; Argos/OpusMT for text): translate media titles/descriptions and audio, stored beside the original (never overwriting it). Pairs with the audio analyzer.
+- _(add ideas here — keep them one-liners)_
+
### Explicit non-goals
- No cloud, no accounts, no hosted service, no telemetry.
@@ -235,6 +264,22 @@ v1 notes:
(pywebview window revisited later). Tabs on the left, tool canvas on the right,
case sidebar. **Svelte** + Leaflet (maps) + Konva/canvas (annotation) — decided,
the composer's interaction state is too rich for vanilla JS.
+ - **Planned map migration: Leaflet → MapLibre GL.** Phase 1 = **2D
+ iso-functional parity** (same providers, same captures, zero 3D) proven by
+ the existing capture tests staying green — parity asserts the *captured
+ pixels*, not just that the map renders (vector-tile compositing replaces
+ 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
+ (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);
+ key-less providers are always the default.
+- **Tool navigation & derivation chain**: cleaner switching between tools, with
+ linked tools surfacing their **derivation chain** (this proof ← this frame ←
+ this video ← this download) as breadcrumbs — the case's connections made
+ visible, an early slice of the v3 Relations view.
- **Distribution**: `pip install ozimut` + `ozimut` command for technical users;
PyInstaller single-file executables (Windows/Linux/macOS) for everyone else.
- **Storage**: plain files as described in §4. No database server; SQLite only for
@@ -252,8 +297,14 @@ v1 notes:
4. **M3 — Proof Composer**: panels, mouse annotation, colors, comments, legend,
export PNG + re-editable spec. *The demo video (media → satellite → proof) is
the community launch.*
-5. **M4 — Post Composer + polish**, first public release (GitHub + X post).
-6. **M5+**: v2 GEOINT suite by community demand, then the investigation layer.
+5. **M4 — Post Composer**, v1 Proof Studio complete + deep-linkable tools.
+6. **M5 — Inspect** (Frame Extractor pulled early): scratch workspace, frame
+ extraction/adjustments, warp collage, reopenable sessions (M5.1 rework).
+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+**: v2 GEOINT suite (auto-panorama, reverse-search — see backlog) by
+ community demand, then the investigation layer.
## 9. Open questions
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index e802666..967db63 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -16,7 +16,8 @@
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^7.2.0",
"svelte": "^5.0.0",
- "vite": "^8.1.4"
+ "vite": "^8.1.4",
+ "vitest": "^4.1.10"
}
},
"node_modules/@emnapi/core": {
@@ -405,6 +406,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@standard-schema/spec": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@sveltejs/acorn-typescript": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.11.tgz",
@@ -446,6 +454,24 @@
"tslib": "^2.4.0"
}
},
+ "node_modules/@types/chai": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/deep-eql": "*",
+ "assertion-error": "^2.0.1"
+ }
+ },
+ "node_modules/@types/deep-eql": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/estree": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
@@ -460,6 +486,119 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@vitest/expect": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.10.tgz",
+ "integrity": "sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@standard-schema/spec": "^1.1.0",
+ "@types/chai": "^5.2.2",
+ "@vitest/spy": "4.1.10",
+ "@vitest/utils": "4.1.10",
+ "chai": "^6.2.2",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/mocker": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.10.tgz",
+ "integrity": "sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "4.1.10",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^0.30.21"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/pretty-format": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.10.tgz",
+ "integrity": "sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/runner": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.10.tgz",
+ "integrity": "sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/utils": "4.1.10",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/snapshot": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.10.tgz",
+ "integrity": "sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.10",
+ "@vitest/utils": "4.1.10",
+ "magic-string": "^0.30.21",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/spy": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.10.tgz",
+ "integrity": "sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/utils": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.10.tgz",
+ "integrity": "sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.10",
+ "convert-source-map": "^2.0.0",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
"node_modules/acorn": {
"version": "8.17.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz",
@@ -483,6 +622,16 @@
"node": ">= 0.4"
}
},
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/axobject-query": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
@@ -493,6 +642,16 @@
"node": ">= 0.4"
}
},
+ "node_modules/chai": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
+ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/clsx": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
@@ -503,6 +662,13 @@
"node": ">=6"
}
},
+ "node_modules/convert-source-map": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/deepmerge": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
@@ -530,6 +696,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/es-module-lexer": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.0.tgz",
+ "integrity": "sha512-KLdwQm2NvGLDkQDCGvmiQrhkd0JbMzXthwQAUgWjQuQdBLFa3eiBP5arXZyA+f8x+x7OXgud6bq2rxjGtHV2tw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/esm-env": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz",
@@ -555,6 +728,26 @@
}
}
},
+ "node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/expect-type": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
@@ -944,6 +1137,13 @@
"node": ">=12.20.0"
}
},
+ "node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -1027,6 +1227,13 @@
"@rolldown/binding-win32-x64-msvc": "1.1.5"
}
},
+ "node_modules/siginfo": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
+ "dev": true,
+ "license": "ISC"
+ },
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -1037,6 +1244,20 @@
"node": ">=0.10.0"
}
},
+ "node_modules/stackback": {
+ "version": "0.0.2",
+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/std-env": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz",
+ "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/svelte": {
"version": "5.56.4",
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.56.4.tgz",
@@ -1065,6 +1286,23 @@
"node": ">=18"
}
},
+ "node_modules/tinybench": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinyexec": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.4.tgz",
+ "integrity": "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -1082,6 +1320,16 @@
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
+ "node_modules/tinyrainbow": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz",
+ "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
@@ -1188,6 +1436,113 @@
}
}
},
+ "node_modules/vitest": {
+ "version": "4.1.10",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.10.tgz",
+ "integrity": "sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/expect": "4.1.10",
+ "@vitest/mocker": "4.1.10",
+ "@vitest/pretty-format": "4.1.10",
+ "@vitest/runner": "4.1.10",
+ "@vitest/snapshot": "4.1.10",
+ "@vitest/spy": "4.1.10",
+ "@vitest/utils": "4.1.10",
+ "es-module-lexer": "^2.0.0",
+ "expect-type": "^1.3.0",
+ "magic-string": "^0.30.21",
+ "obug": "^2.1.1",
+ "pathe": "^2.0.3",
+ "picomatch": "^4.0.3",
+ "std-env": "^4.0.0-rc.1",
+ "tinybench": "^2.9.0",
+ "tinyexec": "^1.0.2",
+ "tinyglobby": "^0.2.15",
+ "tinyrainbow": "^3.1.0",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
+ "why-is-node-running": "^2.3.0"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@opentelemetry/api": "^1.9.0",
+ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "4.1.10",
+ "@vitest/browser-preview": "4.1.10",
+ "@vitest/browser-webdriverio": "4.1.10",
+ "@vitest/coverage-istanbul": "4.1.10",
+ "@vitest/coverage-v8": "4.1.10",
+ "@vitest/ui": "4.1.10",
+ "happy-dom": "*",
+ "jsdom": "*",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser-playwright": {
+ "optional": true
+ },
+ "@vitest/browser-preview": {
+ "optional": true
+ },
+ "@vitest/browser-webdriverio": {
+ "optional": true
+ },
+ "@vitest/coverage-istanbul": {
+ "optional": true
+ },
+ "@vitest/coverage-v8": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ },
+ "vite": {
+ "optional": false
+ }
+ }
+ },
+ "node_modules/why-is-node-running": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "siginfo": "^2.0.0",
+ "stackback": "0.0.2"
+ },
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/zimmerframe": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index f073ae2..6aa4e6d 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -6,12 +6,14 @@
"scripts": {
"dev": "vite",
"build": "vite build",
- "preview": "vite preview"
+ "preview": "vite preview",
+ "test": "vitest run"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^7.2.0",
"svelte": "^5.0.0",
- "vite": "^8.1.4"
+ "vite": "^8.1.4",
+ "vitest": "^4.1.10"
},
"dependencies": {
"@fontsource/oxanium": "^5.2.8",
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index 2de5413..c476fa8 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -40,8 +40,8 @@
</div>
<CaseSwitcher />
<div class="spacer"></div>
- <span class="local-badge" title="Server bound to 127.0.0.1 — nothing leaves this machine">
- <span class="dot"></span> local only
+ <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"
diff --git a/frontend/src/components/CaseSidebar.svelte b/frontend/src/components/CaseSidebar.svelte
index bbf1e25..691ce80 100644
--- a/frontend/src/components/CaseSidebar.svelte
+++ b/frontend/src/components/CaseSidebar.svelte
@@ -135,6 +135,12 @@
uiState.tool = 'satellite';
return;
}
+ if (entity.type === 'media') {
+ // switch to the Media Library and flag the item so it's highlighted there
+ if (entity.attrs?.path) uiState.focusMedia = entity.attrs.path;
+ uiState.tool = 'media';
+ return;
+ }
const tool = ENTITY_TOOL[entity.type];
if (tool) uiState.tool = tool;
}
@@ -151,11 +157,19 @@
['user', 'Notes & manual', 'note'],
];
const KNOWN_TOOLS = new Set(TOOL_GROUPS.map(([k]) => k).filter((k) => k !== 'user'));
- const groupKey = (by) => (KNOWN_TOOLS.has(by) ? by : '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';
+ };
const savedGroups = $derived.by(() => {
const buckets = new Map(TOOL_GROUPS.map(([k]) => [k, []]));
- for (const e of confirmed) buckets.get(groupKey(e.provenance?.by)).push(e);
+ for (const e of confirmed) buckets.get(groupKey(e)).push(e);
return TOOL_GROUPS.map(([key, label, icon]) => ({
key,
label,
diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelte
index 1fdd5af..d3b2bf0 100644
--- a/frontend/src/components/Icon.svelte
+++ b/frontend/src/components/Icon.svelte
@@ -57,6 +57,7 @@
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',
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',
};
</script>
diff --git a/frontend/src/lib/composer.js b/frontend/src/lib/composer.js
index 188b320..37fc62a 100644
--- a/frontend/src/lib/composer.js
+++ b/frontend/src/lib/composer.js
@@ -1,19 +1,33 @@
/**
* Proof composer document logic — pure functions, no Konva/DOM here.
*
- * Document space: panels share a common height (PANEL_H doc units) and sit in
- * one row. Shape coordinates are stored in each panel's *natural image pixels*
- * so the spec stays valid regardless of layout or zoom (re-editable forever).
+ * Document space: panels share a common height (PANEL_H doc units) within a
+ * row, and rows stack vertically. Each panel carries a `row` index (default 0);
+ * panels of the same row sit side by side (array order = left→right), rows are
+ * centered and stacked top→bottom. A single-row document (all row 0) is exactly
+ * the classic side-by-side strip. Stacking rows keeps the composite closer to a
+ * square so it survives a tweet's centre-crop instead of being a wide bandeau.
+ *
+ * Shape coordinates are stored in each panel's *natural image pixels* so the
+ * spec stays valid regardless of layout or zoom (re-editable forever).
*/
export const PANEL_H = 720;
export const PAD = 20;
export const GAP = 16;
-export const CAPTION_H = 34;
+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;
-export const ANNO_COLORS = ['#ff5252', '#40c4ff', '#ffd740', '#69f0ae', '#e040fb', '#ff9e40'];
+// 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.
+export const TWEET_GUIDES = {
+ '16:9': 16 / 9,
+ '4:5': 4 / 5,
+};
+
+export const ANNO_COLORS = ['#ff5252', '#40c4ff', '#ffd740', '#69f0ae', '#e040fb', '#ff9e40', '#ffffff'];
export const BG = '#0d1117';
export const TEXT_MAIN = '#e8edf6';
@@ -25,18 +39,100 @@ export function newId(prefix) {
return `${prefix}${Date.now().toString(36)}${(idSeq++).toString(36)}`;
}
-/** Panel layout boxes in doc space: [{x, y, w, h, scale}] aligned with panels. */
-export function layoutPanels(panels) {
- let x = PAD;
+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
+
+/** Height of the caption band under a row for a given caption font size. */
+export function captionBand(captionSize = CAPTION_SIZE) {
+ return Math.round(captionSize + 17);
+}
+
+/** Height of one legend line for a given legend font size. */
+export function legendLineHeight(legendSize = LEGEND_SIZE) {
+ return Math.round(legendSize + 13);
+}
+
+/** Height of the footer band for a given footer font size. */
+export function footerBand(footerSize = FOOTER_SIZE) {
+ return Math.round(footerSize + 13);
+}
+
+/** 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);
+}
+
+/** Per-panel height in doc units: base PANEL_H times the panel's own scale. */
+export function panelHeight(p) {
+ return PANEL_H * (p.scale ?? 1);
+}
+
+/**
+ * Panel layout boxes in doc space: [{x, y, w, h, scale, baseScale, row}] aligned
+ * with the input `panels`. Panels are grouped by `row` and centred; rows stack
+ * top→bottom with a caption band + ROW_GAP between them. Each panel is laid out
+ * at PANEL_H × its own `scale`, so a row's height is its tallest panel and the
+ * shorter panels are bottom-aligned so their captions share one baseline.
+ *
+ * `scale` maps a panel's natural pixels → doc pixels (grows/shrinks with the
+ * user scale); `baseScale` is that mapping at scale 1, used to keep stroke and
+ * arrow-head sizes normalised while still letting them grow with the panel.
+ */
+export function layoutPanels(panels, captionSize = CAPTION_SIZE) {
+ const rows = rowOrder(panels);
+ const band = captionBand(captionSize);
+ // width + height of each row, to centre narrower rows and stack by height
+ const rowWidth = new Map();
+ const rowHeight = new Map();
+ for (const r of rows) {
+ let w = 0;
+ let h = 0;
+ const inRow = panels.filter((p) => (p.row ?? 0) === r);
+ inRow.forEach((p, k) => {
+ const ph = panelHeight(p);
+ h = Math.max(h, ph);
+ w += p.natural[0] * (ph / p.natural[1]) + (k ? GAP : 0);
+ });
+ rowWidth.set(r, w);
+ rowHeight.set(r, h);
+ }
+ const contentW = rows.length ? Math.max(...rowWidth.values()) : 0;
+ // cumulative top of each row (rows differ in height once panels are scaled)
+ const rowTop = new Map();
+ let cy = PAD;
+ for (const r of rows) {
+ rowTop.set(r, cy);
+ cy += rowHeight.get(r) + band + ROW_GAP;
+ }
+ // running x cursor per row so array order stays left→right within a row
+ const cursor = new Map(rows.map((r) => [r, PAD + (contentW - rowWidth.get(r)) / 2]));
return panels.map((p) => {
- const scale = PANEL_H / p.natural[1];
+ const r = p.row ?? 0;
+ const ph = panelHeight(p);
+ const scale = ph / p.natural[1];
+ const baseScale = PANEL_H / p.natural[1];
const w = p.natural[0] * scale;
- const box = { x, y: PAD, w, h: PANEL_H, scale };
- x += w + GAP;
+ const y = rowTop.get(r) + (rowHeight.get(r) - ph); // bottom-align within row
+ const box = { x: cursor.get(r), y, w, h: ph, scale, baseScale, row: r };
+ cursor.set(r, cursor.get(r) + w + GAP);
return box;
});
}
+/** Height of the stacked panel block (rows + their caption bands), no legend. */
+export function panelsBlockHeight(panels, captionSize = CAPTION_SIZE) {
+ const rows = rowOrder(panels);
+ if (!rows.length) return 0;
+ const band = captionBand(captionSize);
+ let total = 0;
+ for (const r of rows) {
+ const inRow = panels.filter((p) => (p.row ?? 0) === r);
+ total += Math.max(...inRow.map(panelHeight)) + band;
+ }
+ return total + (rows.length - 1) * ROW_GAP;
+}
+
/**
* Distinct colors in order of first use → feature numbering (same color = same
* feature). Text labels are excluded — they annotate, they aren't features.
@@ -84,22 +180,124 @@ export function attributionLine(panels) {
const parts = new Set();
for (const p of panels) {
if (p.meta?.attribution) parts.add(`Imagery: ${p.meta.attribution}`);
- else if (p.meta?.source_url) parts.add(`Source: ${p.meta.source_url}`);
+ else {
+ for (const u of panelSourceUrls(p)) parts.add(`Source: ${u}`);
+ }
}
parts.add('Composed with Ozimut');
return [...parts].join(' · ');
}
-/** Full document size given panels + shapes (legend grows with features). */
-export function docSize(panels, shapes, notes = {}) {
- const boxes = layoutPanels(panels);
+// ---- coordinates + source (auto-derived from panels, user-overridable) ------
+
+/** First panel (add order) that carries geo → {lat, lon}, else null. */
+export function autoCoords(panels) {
+ for (const p of panels ?? []) {
+ const lat = p.meta?.lat;
+ const lon = p.meta?.lon;
+ if (lat != null && lon != null) return { lat: Number(lat), lon: Number(lon) };
+ }
+ return null;
+}
+
+/** Decimal "lat, lon" (6 dp) for a {lat, lon}, or '' when null. */
+export function formatCoords(c) {
+ return c && c.lat != null && c.lon != null
+ ? `${Number(c.lat).toFixed(6)}, ${Number(c.lon).toFixed(6)}`
+ : '';
+}
+
+/**
+ * Trace a media item back to its original *source link(s)*. A source is always a
+ * URL (a downloaded webpage): a file uploaded from disk is NOT a source. Inspect
+ * derivatives (frames, adjustments, collages) don't carry a URL themselves —
+ * their `source` records the case paths they were derived from (`from` and, for
+ * collages, `sources`), so we follow those through `mediaByPath` until we reach
+ * the download that owns a `webpage_url`. Returns de-duplicated URLs.
+ */
+export function resolveSourceUrls(item, mediaByPath, seen = new Set()) {
+ if (!item) return [];
+ const s = item.source ?? {};
+ const direct = s.webpage_url || (typeof s.url === 'string' && /^https?:\/\//i.test(s.url) ? s.url : null);
+ if (direct) return [direct];
+ const parents = [];
+ if (s.from) parents.push(s.from);
+ if (Array.isArray(s.sources)) parents.push(...s.sources);
+ const urls = [];
+ for (const path of parents) {
+ if (!path || seen.has(path)) continue;
+ seen.add(path);
+ urls.push(...resolveSourceUrls(mediaByPath?.get?.(path), mediaByPath, seen));
+ }
+ return [...new Set(urls)];
+}
+
+/** Source URLs already resolved onto a panel's meta (array, first-mirrored). */
+function panelSourceUrls(p) {
+ if (Array.isArray(p.meta?.source_urls)) return p.meta.source_urls.filter(Boolean);
+ return p.meta?.source_url ? [p.meta.source_url] : [];
+}
+
+/** Distinct source URLs across all panels (satellite imagery has none). */
+export function autoSourceUrls(panels) {
+ const set = new Set();
+ for (const p of panels ?? []) for (const u of panelSourceUrls(p)) set.add(u);
+ return [...set];
+}
+
+/** Auto source line: distinct panel source links joined, or '' when none. */
+export function autoSource(panels) {
+ return autoSourceUrls(panels).join(' · ');
+}
+
+/** Effective coordinates text for a proof/spec: manual override else auto. */
+export function proofCoordsText(p) {
+ const manual = p.coordsText?.trim();
+ if (manual) return manual;
+ return formatCoords(autoCoords(p.panels ?? []));
+}
+
+/** Effective source line for a proof/spec: manual override else auto. */
+export function proofSource(p) {
+ const manual = p.source?.trim();
+ if (manual) return manual;
+ return autoSource(p.panels ?? []);
+}
+
+/** How many columns the legend splits into for a given content width + count. */
+export function legendColumns(width, count) {
+ if (count <= 1) return 1;
+ const fit = Math.floor((width - PAD * 2 + GAP) / (LEGEND_COL_MIN + GAP));
+ return Math.max(1, Math.min(3, count, fit));
+}
+
+/** Number of stacked legend rows once split into columns. */
+export function legendRowCount(count, columns) {
+ return columns > 0 ? Math.ceil(count / columns) : 0;
+}
+
+/**
+ * Full document size given panels + shapes. Legend grows with the feature
+ * 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 = {}) {
+ const {
+ captionSize = CAPTION_SIZE, legendSize = LEGEND_SIZE, footerSize = FOOTER_SIZE,
+ } = text;
+ const boxes = layoutPanels(panels, captionSize);
const width = boxes.length
- ? boxes[boxes.length - 1].x + boxes[boxes.length - 1].w + PAD
+ ? 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 cols = legendColumns(contentW, legend.length);
+ const legendRows = legendRowCount(legend.length, cols);
const height =
- PAD + PANEL_H + CAPTION_H + (legend.length ? 10 + legend.length * LEGEND_LINE_H : 0) + FOOTER_H + PAD;
- return { width: Math.max(width, 640), height, legend };
+ PAD + panelsBlockHeight(panels, captionSize) +
+ (legend.length ? 10 + legendRows * legendLineHeight(legendSize) : 0) +
+ footerBand(footerSize) + PAD;
+ return { width: contentW, height, legend, cols };
}
/** Serializable spec from runtime state (drops live image objects). */
@@ -107,12 +305,20 @@ export function toSpec(proof) {
return {
ozimut_proof: 1,
title: proof.title,
- coords: proof.coords ?? null,
+ coords: autoCoords(proof.panels), // auto geo (first geo panel), for reference
+ coordsText: proof.coordsText?.trim() ? proof.coordsText.trim() : null, // null → auto
+ source: proof.source?.trim() ? proof.source.trim() : null, // null → auto (link only)
+ captionSize: proof.captionSize ?? CAPTION_SIZE,
+ legendSize: proof.legendSize ?? LEGEND_SIZE,
+ footerSize: proof.footerSize ?? FOOTER_SIZE,
+ footer: proof.footer?.trim() ? proof.footer.trim() : null, // null → default attribution line
notes: { ...(proof.notes ?? {}) },
panels: proof.panels.map((p) => ({
id: p.id, // kept so shapes stay bound to their panel on reload
src: p.src,
caption: p.caption ?? '',
+ row: p.row ?? 0, // vertical row (0 = top); missing → single-row layout
+ scale: p.scale ?? 1, // per-panel size multiplier (1 = default PANEL_H)
natural: p.natural,
meta: p.meta ?? {},
})),
@@ -120,6 +326,69 @@ export function toSpec(proof) {
};
}
+/**
+ * Detached, plain deep copy of a shape spec (id stripped) for the clipboard.
+ * A shape is pure JSON data, so a JSON round-trip both unwraps any reactive
+ * proxy — `structuredClone` of a live proxy throws in the browser, and a shallow
+ * spread leaves points-based line/arrow/curve with a proxied `points` array,
+ * which silently broke copy for those kinds — and fully detaches the copy.
+ */
+export function copyShapeSpec(shape) {
+ const clone = JSON.parse(JSON.stringify(shape));
+ delete clone.id;
+ return clone;
+}
+
+/**
+ * Copy of a shape spec nudged by `d` doc-pixels down-right, for paste/duplicate.
+ * Points-based kinds (line/arrow/curve) shift every vertex; box/ellipse/text
+ * shift their x/y. The returned spec carries no id — the caller assigns one.
+ */
+export function offsetShape(shape, d) {
+ const s = structuredClone(shape);
+ delete s.id;
+ if (Array.isArray(s.points)) {
+ s.points = s.points.map((v) => v + d);
+ } else {
+ s.x = (s.x ?? 0) + d;
+ s.y = (s.y ?? 0) + d;
+ }
+ return s;
+}
+
+/**
+ * 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
+ * uncropped in the X timeline, 4:5 fills the feed). Array order is preserved —
+ * we only choose where to break the sequence into rows — so the caller keeps
+ * left→right ordering. Returns one row index per panel (aligned with `panels`).
+ *
+ * The composite includes the legend + footer bands (they're part of the image
+ * that gets cropped), so `shapes`/`notes`/`text` are folded into the measure.
+ * Brute-forces the 2^(n-1) row-break combinations; n is tiny for real proofs.
+ */
+export function autoLayoutRows(
+ panels, shapes = [], notes = {}, text = {}, target = TWEET_GUIDES['16:9'],
+) {
+ const n = panels.length;
+ if (n <= 1) return panels.map(() => 0);
+ let best = null;
+ const combos = 1 << (n - 1); // one break-or-not bit between each adjacent pair
+ for (let mask = 0; mask < combos; mask++) {
+ let row = 0;
+ const rows = [0];
+ for (let i = 1; i < n; i++) {
+ if (mask & (1 << (i - 1))) row += 1;
+ rows.push(row);
+ }
+ const candidate = panels.map((p, i) => ({ ...p, row: rows[i], scale: 1 }));
+ const { width, height } = docSize(candidate, shapes, notes, text);
+ const score = Math.abs(width / height - target);
+ if (!best || score < best.score) best = { score, rows };
+ }
+ return best.rows;
+}
+
export function loadImage(url) {
return new Promise((resolve, reject) => {
const img = new Image();
diff --git a/frontend/src/lib/composer.test.js b/frontend/src/lib/composer.test.js
new file mode 100644
index 0000000..8e47c65
--- /dev/null
+++ b/frontend/src/lib/composer.test.js
@@ -0,0 +1,418 @@
+import { describe, it, expect } from 'vitest';
+import {
+ PAD, PANEL_H, GAP, ROW_GAP, FOOTER_H, LEGEND_LINE_H,
+ layoutPanels, panelsBlockHeight, panelHeight, captionBand, legendLineHeight, footerBand,
+ docSize, legendColumns, legendRowCount, toSpec, offsetShape, copyShapeSpec, autoLayoutRows, TWEET_GUIDES,
+ autoCoords, formatCoords, resolveSourceUrls, autoSource, autoSourceUrls,
+ proofCoordsText, proofSource,
+} from './composer.js';
+
+// natural is [width, height]; PANEL_H drives the per-row scale.
+const landscape = (w = 1000, h = 500, extra = {}) => ({ natural: [w, h], ...extra });
+
+describe('layoutPanels — single row (backward compatible)', () => {
+ it('lays panels left→right at PANEL_H on row 0 when no row is set', () => {
+ const panels = [landscape(1000, 500), landscape(500, 500)];
+ const boxes = layoutPanels(panels);
+ // first panel: scale 720/500 = 1.44, width 1440
+ expect(boxes[0]).toMatchObject({ x: PAD, y: PAD, h: PANEL_H, row: 0 });
+ expect(boxes[0].w).toBeCloseTo(1440);
+ // second panel sits a GAP to the right, same row/height
+ expect(boxes[1].x).toBeCloseTo(PAD + 1440 + GAP);
+ expect(boxes[1].y).toBe(PAD);
+ expect(boxes[1].w).toBeCloseTo(720);
+ });
+
+ it('treats an explicit row:0 identically to a missing row', () => {
+ const a = layoutPanels([landscape(1000, 500), landscape(500, 500)]);
+ const b = layoutPanels([landscape(1000, 500, { row: 0 }), landscape(500, 500, { row: 0 })]);
+ expect(b).toEqual(a);
+ });
+});
+
+describe('layoutPanels — stacked rows', () => {
+ it('stacks a second row below the first with a caption band + ROW_GAP', () => {
+ const panels = [landscape(1000, 500, { row: 0 }), landscape(1000, 500, { row: 1 })];
+ const boxes = layoutPanels(panels);
+ expect(boxes[0].y).toBe(PAD);
+ expect(boxes[1].y).toBe(PAD + (PANEL_H + captionBand() + ROW_GAP));
+ expect(boxes[1].row).toBe(1);
+ });
+
+ it('centres a narrower row under a wider one', () => {
+ // row 0: two 1000x500 panels; row 1: one 500x500 panel
+ const panels = [
+ landscape(1000, 500, { row: 0 }),
+ landscape(1000, 500, { row: 0 }),
+ landscape(500, 500, { row: 1 }),
+ ];
+ const boxes = layoutPanels(panels);
+ const contentW = 1440 + GAP + 1440; // widest row
+ const narrowW = 720;
+ expect(boxes[2].x).toBeCloseTo(PAD + (contentW - narrowW) / 2);
+ });
+
+ it('normalises sparse row indices by ascending order', () => {
+ // rows 0 and 5 → two stacked rows, not six
+ const panels = [landscape(1000, 500, { row: 0 }), landscape(1000, 500, { row: 5 })];
+ const boxes = layoutPanels(panels);
+ expect(boxes[1].y).toBe(PAD + (PANEL_H + captionBand() + ROW_GAP));
+ });
+});
+
+describe('layoutPanels — per-panel scale', () => {
+ it('panelHeight is PANEL_H times the panel scale (default 1)', () => {
+ expect(panelHeight({ natural: [1, 1] })).toBe(PANEL_H);
+ expect(panelHeight({ natural: [1, 1], scale: 0.5 })).toBe(PANEL_H * 0.5);
+ expect(panelHeight({ natural: [1, 1], scale: 2 })).toBe(PANEL_H * 2);
+ });
+
+ it('scales a panel height/width by its scale and keeps baseScale at scale 1', () => {
+ const boxes = layoutPanels([landscape(1000, 500, { scale: 2 })]);
+ expect(boxes[0].h).toBe(PANEL_H * 2);
+ expect(boxes[0].w).toBeCloseTo(1000 * ((PANEL_H * 2) / 500)); // 2880
+ expect(boxes[0].scale).toBeCloseTo((PANEL_H * 2) / 500);
+ expect(boxes[0].baseScale).toBeCloseTo(PANEL_H / 500);
+ });
+
+ it('bottom-aligns shorter panels within a row (shared caption baseline)', () => {
+ const panels = [
+ landscape(1000, 500, { row: 0, scale: 1 }),
+ landscape(1000, 500, { row: 0, scale: 0.5 }),
+ ];
+ const boxes = layoutPanels(panels);
+ expect(boxes[0].y).toBe(PAD);
+ expect(boxes[1].h).toBe(PANEL_H * 0.5);
+ expect(boxes[1].y).toBe(PAD + PANEL_H * 0.5); // pushed down to align bottoms
+ expect(boxes[0].y + boxes[0].h).toBe(boxes[1].y + boxes[1].h);
+ });
+
+ it('stacks the next row below the tallest panel of the previous row', () => {
+ const panels = [
+ landscape(1000, 500, { row: 0, scale: 2 }),
+ landscape(1000, 500, { row: 1, scale: 1 }),
+ ];
+ const boxes = layoutPanels(panels);
+ expect(boxes[1].y).toBe(PAD + (PANEL_H * 2 + captionBand() + ROW_GAP));
+ });
+});
+
+describe('captionBand + panelsBlockHeight', () => {
+ it('grows the caption band with the font size', () => {
+ expect(captionBand(17)).toBe(34);
+ expect(captionBand(40)).toBe(57);
+ });
+
+ it('measures the stacked panel block including caption bands and gaps', () => {
+ const oneRow = [landscape()];
+ const twoRows = [landscape(1000, 500, { row: 0 }), landscape(1000, 500, { row: 1 })];
+ expect(panelsBlockHeight(oneRow)).toBe(PANEL_H + captionBand());
+ expect(panelsBlockHeight(twoRows)).toBe(2 * (PANEL_H + captionBand()) + ROW_GAP);
+ });
+
+ it('reflects a custom caption size in the block height', () => {
+ const rows = [landscape(1000, 500, { row: 0 }), landscape(1000, 500, { row: 1 })];
+ expect(panelsBlockHeight(rows, 30)).toBe(2 * (PANEL_H + captionBand(30)) + ROW_GAP);
+ });
+
+ it('uses the tallest panel of each row when panels are scaled', () => {
+ const panels = [
+ landscape(1000, 500, { row: 0, scale: 2 }),
+ landscape(1000, 500, { row: 0, scale: 1 }),
+ landscape(1000, 500, { row: 1, scale: 0.5 }),
+ ];
+ const expected =
+ (PANEL_H * 2 + captionBand()) + (PANEL_H * 0.5 + captionBand()) + ROW_GAP;
+ expect(panelsBlockHeight(panels)).toBe(expected);
+ });
+});
+
+describe('text band sizes', () => {
+ it('grows the legend line height with the legend font size', () => {
+ expect(legendLineHeight(17)).toBe(30);
+ expect(legendLineHeight(30)).toBe(43);
+ });
+
+ it('grows the footer band with the footer font size', () => {
+ expect(footerBand(13)).toBe(26);
+ expect(footerBand(24)).toBe(37);
+ });
+});
+
+describe('docSize', () => {
+ it('sizes a single panel with no legend', () => {
+ const { width, height } = docSize([landscape(1000, 500)], [], {});
+ expect(width).toBe(PAD + 1440 + PAD);
+ expect(height).toBe(PAD + (PANEL_H + captionBand()) + FOOTER_H + PAD);
+ });
+
+ it('accounts for custom caption / legend / footer sizes', () => {
+ const panels = [landscape(1000, 500)];
+ const shapes = [{ kind: 'rect', color: '#ff5252', panel: 'p1' }];
+ const notes = { '#ff5252': 'road' };
+ const text = { captionSize: 30, legendSize: 24, footerSize: 20 };
+ const { height } = docSize(panels, shapes, notes, text);
+ const expected =
+ PAD + (PANEL_H + captionBand(30)) + (10 + legendLineHeight(24)) + footerBand(20) + PAD;
+ expect(height).toBe(expected);
+ });
+
+ it('adds height for legend rows and grows taller with stacked panels', () => {
+ const panels = [landscape(1000, 500, { row: 0 }), landscape(1000, 500, { row: 1 })];
+ const shapes = [{ kind: 'rect', color: '#ff5252', panel: 'p1' }];
+ const notes = { '#ff5252': 'road junction' };
+ const { height } = docSize(panels, shapes, notes);
+ const legendH = 10 + 1 * LEGEND_LINE_H;
+ expect(height).toBe(PAD + panelsBlockHeight(panels) + legendH + FOOTER_H + PAD);
+ });
+});
+
+describe('legend columns', () => {
+ it('keeps one column for narrow docs or a single feature', () => {
+ expect(legendColumns(400, 3)).toBe(1);
+ expect(legendColumns(2000, 1)).toBe(1);
+ });
+
+ it('splits into more columns as width and feature count allow, capped at 3', () => {
+ expect(legendColumns(800, 3)).toBe(2);
+ expect(legendColumns(3000, 8)).toBe(3);
+ });
+
+ it('never exceeds the feature count', () => {
+ expect(legendColumns(3000, 2)).toBe(2);
+ });
+
+ it('computes stacked legend rows from the column count', () => {
+ expect(legendRowCount(5, 2)).toBe(3);
+ expect(legendRowCount(3, 3)).toBe(1);
+ expect(legendRowCount(0, 2)).toBe(0);
+ });
+});
+
+describe('toSpec — persistence of layout', () => {
+ it('serialises the row index and caption size', () => {
+ const proof = {
+ title: 'T', coords: null, captionSize: 24, legendSize: 22, footerSize: 18,
+ footer: ' Custom footer ', notes: {},
+ panels: [
+ { id: 'p1', src: 'a.png', caption: '', row: 0, natural: [100, 100], meta: {} },
+ { id: 'p2', src: 'b.png', caption: 'x', row: 1, natural: [100, 100], meta: {} },
+ ],
+ shapes: [],
+ };
+ const spec = toSpec(proof);
+ expect(spec.captionSize).toBe(24);
+ expect(spec.legendSize).toBe(22);
+ expect(spec.footerSize).toBe(18);
+ expect(spec.footer).toBe('Custom footer'); // trimmed
+ expect(spec.panels.map((p) => p.row)).toEqual([0, 1]);
+ });
+
+ it('stores a blank footer as null so the automatic attribution shows', () => {
+ const proof = { title: 'T', footer: ' ', panels: [], shapes: [] };
+ expect(toSpec(proof).footer).toBeNull();
+ });
+
+ it('defaults a missing row to 0 and caption size to the base', () => {
+ const proof = {
+ title: 'T', panels: [{ id: 'p1', src: 'a.png', natural: [10, 10] }], shapes: [],
+ };
+ const spec = toSpec(proof);
+ expect(spec.panels[0].row).toBe(0);
+ expect(spec.captionSize).toBeGreaterThan(0);
+ });
+
+ it('serialises per-panel scale, defaulting a missing scale to 1', () => {
+ const proof = {
+ title: 'T',
+ panels: [
+ { id: 'p1', src: 'a.png', natural: [10, 10], scale: 1.5 },
+ { id: 'p2', src: 'b.png', natural: [10, 10] },
+ ],
+ shapes: [],
+ };
+ expect(toSpec(proof).panels.map((p) => p.scale)).toEqual([1.5, 1]);
+ });
+});
+
+describe('autoLayoutRows — magic tweet fit', () => {
+ const sq = (extra) => landscape(500, 500, extra);
+
+ it('leaves 0 or 1 panels in a single row', () => {
+ expect(autoLayoutRows([])).toEqual([]);
+ expect(autoLayoutRows([sq()])).toEqual([0]);
+ });
+
+ it('returns one contiguous, non-decreasing row index per panel', () => {
+ const rows = autoLayoutRows([sq(), sq(), sq(), sq()]);
+ expect(rows).toHaveLength(4);
+ for (let i = 1; i < rows.length; i++) {
+ const step = rows[i] - rows[i - 1];
+ expect(step).toBeGreaterThanOrEqual(0);
+ expect(step).toBeLessThanOrEqual(1); // rows only ever advance by one
+ }
+ });
+
+ it('breaks a wide strip of square panels into multiple rows for 16:9', () => {
+ const rows = autoLayoutRows([sq(), sq(), sq(), sq()], [], {}, {}, TWEET_GUIDES['16:9']);
+ expect(Math.max(...rows)).toBeGreaterThan(0);
+ });
+
+ it('packs at least as tall for a 4:5 target as for a 16:9 target', () => {
+ const panels = [sq(), sq(), sq(), sq(), sq(), sq()];
+ const wide = autoLayoutRows(panels, [], {}, {}, TWEET_GUIDES['16:9']);
+ const tall = autoLayoutRows(panels, [], {}, {}, TWEET_GUIDES['4:5']);
+ expect(Math.max(...tall)).toBeGreaterThanOrEqual(Math.max(...wide));
+ });
+});
+
+describe('copyShapeSpec — clipboard copy of any shape kind', () => {
+ it('strips the id from the copy', () => {
+ const out = copyShapeSpec({ id: 's1', kind: 'rect', panel: 'p1', color: '#fff', x: 1, y: 2, w: 3, h: 4 });
+ expect(out).not.toHaveProperty('id');
+ expect(out).toEqual({ kind: 'rect', panel: 'p1', color: '#fff', x: 1, y: 2, w: 3, h: 4 });
+ });
+
+ // The regression: line/arrow/curve keep their geometry in a `points` array, so
+ // the copy must carry the full array (a shallow spread once left it proxied and
+ // the browser refused to clone it, silently breaking copy for those kinds).
+ it('copies the whole points array of line / arrow / curve kinds', () => {
+ for (const kind of ['line', 'arrow', 'curve']) {
+ const out = copyShapeSpec({ id: 's', kind, panel: 'p1', color: '#fff', points: [0, 0, 10, 20, 30, 40] });
+ expect(out).toEqual({ kind, panel: 'p1', color: '#fff', points: [0, 0, 10, 20, 30, 40] });
+ }
+ });
+
+ it('detaches deeply — mutating the source leaves the copy untouched', () => {
+ const src = { id: 's', kind: 'arrow', panel: 'p1', color: '#fff', points: [0, 0, 5, 5] };
+ const out = copyShapeSpec(src);
+ src.points[0] = 999;
+ src.color = '#000';
+ expect(out.points[0]).toBe(0);
+ expect(out.color).toBe('#fff');
+ });
+});
+
+describe('offsetShape — copy / paste / duplicate', () => {
+ it('nudges x/y kinds (box, ellipse, text) down-right and drops the id', () => {
+ const rect = { id: 's1', kind: 'rect', panel: 'p1', color: '#fff', x: 10, y: 20, w: 5, h: 5 };
+ const out = offsetShape(rect, 26);
+ expect(out).not.toHaveProperty('id');
+ expect(out).toMatchObject({ x: 36, y: 46, w: 5, h: 5, panel: 'p1' });
+ });
+
+ it('shifts every vertex of points-based kinds (line/arrow/curve)', () => {
+ const line = { id: 's2', kind: 'line', panel: 'p1', color: '#fff', points: [0, 0, 100, 40] };
+ const out = offsetShape(line, 10);
+ expect(out.points).toEqual([10, 10, 110, 50]);
+ });
+
+ it('deep-clones so the source is untouched', () => {
+ const src = { id: 's3', kind: 'curve', panel: 'p1', points: [1, 2, 3, 4] };
+ const out = offsetShape(src, 5);
+ out.points[0] = 999;
+ expect(src.points[0]).toBe(1);
+ });
+});
+
+describe('coordinates — auto-derive + fallback', () => {
+ const geo = (lat, lon) => ({ meta: { kind: 'satellite', lat, lon } });
+ const plain = () => ({ meta: { kind: 'media' } });
+
+ it('takes the first panel that carries geo (add order)', () => {
+ expect(autoCoords([plain(), geo(1.5, 2.5), geo(9, 9)])).toEqual({ lat: 1.5, lon: 2.5 });
+ });
+
+ it('falls back to the next geo panel when the first is removed', () => {
+ const panels = [geo(1, 1), geo(2, 2)];
+ expect(autoCoords(panels)).toEqual({ lat: 1, lon: 1 });
+ expect(autoCoords(panels.slice(1))).toEqual({ lat: 2, lon: 2 }); // first deleted
+ });
+
+ it('is null with no geo panel, and formats to 6 decimals', () => {
+ expect(autoCoords([plain()])).toBeNull();
+ expect(formatCoords(null)).toBe('');
+ expect(formatCoords({ lat: 12.3, lon: -4 })).toBe('12.300000, -4.000000');
+ });
+
+ it('prefers a manual override over the auto value', () => {
+ expect(proofCoordsText({ panels: [geo(1, 1)] })).toBe('1.000000, 1.000000');
+ expect(proofCoordsText({ panels: [geo(1, 1)], coordsText: ' 48.8, 2.3 ' })).toBe('48.8, 2.3');
+ });
+});
+
+describe('source — always a link, traced through the derivation chain', () => {
+ const downloaded = (path, url) => ({ path, source: { type: 'download', url, webpage_url: url } });
+ const uploaded = (path) => ({ path, source: { type: 'upload', original_name: 'clip.mp4' } });
+ const frameOf = (path, from) => ({ path, source: { type: 'inspect', op: 'frame', from } });
+ const collageOf = (path, sources) => ({ path, source: { type: 'inspect', op: 'collage', from: '', sources } });
+ const byPath = (...items) => new Map(items.map((i) => [i.path, i]));
+
+ it('returns the URL of a directly downloaded item', () => {
+ const item = downloaded('media/v.mp4', 'https://x.com/a/1');
+ expect(resolveSourceUrls(item, byPath(item))).toEqual(['https://x.com/a/1']);
+ });
+
+ it('treats a disk upload (no URL) as having no source', () => {
+ const item = uploaded('media/u.mp4');
+ expect(resolveSourceUrls(item, byPath(item))).toEqual([]);
+ });
+
+ it('follows a frame back to the downloaded video it came from', () => {
+ const video = downloaded('media/v.mp4', 'https://x.com/a/1');
+ const frame = frameOf('media/f.png', 'media/v.mp4');
+ expect(resolveSourceUrls(frame, byPath(video, frame))).toEqual(['https://x.com/a/1']);
+ });
+
+ it('unions the distinct sources of a collage built from two videos', () => {
+ const v1 = downloaded('media/v1.mp4', 'https://x.com/a/1');
+ const v2 = downloaded('media/v2.mp4', 'https://t.me/b/2');
+ const collage = collageOf('media/c.png', ['media/v1.mp4', 'media/v2.mp4']);
+ expect(resolveSourceUrls(collage, byPath(v1, v2, collage)))
+ .toEqual(['https://x.com/a/1', 'https://t.me/b/2']);
+ });
+
+ it('aggregates distinct panel source links, ignoring satellite imagery', () => {
+ const panels = [
+ { meta: { kind: 'satellite', attribution: '© Provider' } },
+ { meta: { kind: 'media', source_urls: ['https://x.com/a/1'] } },
+ { meta: { kind: 'media', source_urls: ['https://x.com/a/1'] } }, // duplicate collapses
+ { meta: { kind: 'media', source_url: 'https://t.me/b/2' } },
+ ];
+ expect(autoSourceUrls(panels)).toEqual(['https://x.com/a/1', 'https://t.me/b/2']);
+ expect(autoSource(panels)).toBe('https://x.com/a/1 · https://t.me/b/2');
+ });
+
+ it('prefers a manual source override over the auto value', () => {
+ const panels = [{ meta: { kind: 'media', source_urls: ['https://x.com/a/1'] } }];
+ expect(proofSource({ panels })).toBe('https://x.com/a/1');
+ expect(proofSource({ panels, source: ' https://manual ' })).toBe('https://manual');
+ });
+});
+
+describe('toSpec — coordinates + source persistence', () => {
+ it('stores auto coords and null overrides when nothing is manual', () => {
+ const proof = {
+ title: 'T',
+ panels: [{ id: 'p1', src: 'a.png', natural: [10, 10], meta: { lat: 3, lon: 4 } }],
+ shapes: [],
+ };
+ const spec = toSpec(proof);
+ expect(spec.coords).toEqual({ lat: 3, lon: 4 });
+ expect(spec.coordsText).toBeNull();
+ expect(spec.source).toBeNull();
+ });
+
+ it('persists manual coordinate + source overrides (trimmed)', () => {
+ const spec = toSpec({ title: 'T', panels: [], shapes: [], coordsText: ' 1, 2 ', source: ' http://s ' });
+ expect(spec.coordsText).toBe('1, 2');
+ expect(spec.source).toBe('http://s');
+ });
+});
+
+describe('tweet guides', () => {
+ it('exposes landscape and portrait crop aspects', () => {
+ expect(TWEET_GUIDES['16:9']).toBeCloseTo(16 / 9);
+ expect(TWEET_GUIDES['4:5']).toBeCloseTo(0.8);
+ });
+});
diff --git a/frontend/src/lib/inspect.js b/frontend/src/lib/inspect.js
index b5c9722..700cf36 100644
--- a/frontend/src/lib/inspect.js
+++ b/frontend/src/lib/inspect.js
@@ -123,6 +123,119 @@ export function quadMatrix3d(w, h, quad) {
return `matrix3d(${t.join(',')})`;
}
+const _UNIT = [[0, 0], [1, 0], [1, 1], [0, 1]];
+
+/**
+ * Map points given in the piece's own unit square (u,v in 0..1, TL origin)
+ * to canvas points, through the projective transform defined by `quad`
+ * (TL, TR, BR, BL). Lets us reshape a piece's quad when a crop changes which
+ * sub-rectangle of the source it shows.
+ */
+export function quadMapUnit(quad, pts) {
+ const H = mul(basisToPoints(quad), adj(basisToPoints(_UNIT)));
+ return pts.map(([u, v]) => {
+ const p = mulV(H, [u, v, 1]);
+ return [p[0] / p[2], p[1] / p[2]];
+ });
+}
+
+/**
+ * New quad for a piece that now shows only the fractional sub-rectangle
+ * `rect` ({x,y,w,h} in 0..1) of what `quad` currently shows. Preserves the
+ * warp and keeps the piece in place, with the right proportions for the region.
+ */
+export function quadFromCropRect(quad, rect) {
+ const { x, y, w, h } = rect;
+ return quadMapUnit(quad, [[x, y], [x + w, y], [x + w, y + h], [x, y + h]]);
+}
+
+/**
+ * Non-destructive CSS crop: inline styles for an absolutely-positioned <img>
+ * inside an `overflow:hidden` wrapper, so the crop rect fills the wrapper. Lets
+ * the live blob preview + thumbnails *show* a fractional crop with no re-render.
+ */
+export function cropImgStyle(crop) {
+ if (!crop) return {};
+ return {
+ position: 'absolute',
+ width: `${100 / crop.w}%`,
+ height: `${100 / crop.h}%`,
+ left: `${(-crop.x / crop.w) * 100}%`,
+ top: `${(-crop.y / crop.h) * 100}%`,
+ 'max-width': 'none',
+ 'max-height': 'none',
+ };
+}
+
+/** Join a `{prop: value}` style object into an inline `style=""` string. */
+export function styleText(obj) {
+ return Object.entries(obj ?? {})
+ .filter(([, v]) => v != null && v !== '')
+ .map(([k, v]) => `${k}:${v}`)
+ .join(';');
+}
+
+/** Aspect ratio (w/h) of a crop rect over an image of natural size natW×natH. */
+export function cropAspect(crop, natW, natH) {
+ if (!crop || !natW || !natH) return null;
+ return (crop.w * natW) / (crop.h * natH);
+}
+
+/** 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;
+ const cy = (quad[0][1] + quad[1][1] + quad[2][1] + quad[3][1]) / 4;
+ return [cx, cy];
+}
+
+/**
+ * Uniformly scale a quad by `k` around a fixed point (its centroid by default).
+ * Warp shape is preserved — this is the collage "resize" that composes with the
+ * per-corner warp, since both just move the same 4 points.
+ */
+export function scaleQuad(quad, k, center = null) {
+ const [cx, cy] = center ?? quadCentroid(quad);
+ return quad.map(([x, y]) => [cx + (x - cx) * k, cy + (y - cy) * k]);
+}
+
+/**
+ * Tight bounding box over every node's quad (+ optional padding). Used to trim
+ * a transparent-PNG collage to just its pieces on export, so the canvas size
+ * follows the layout instead of being set by hand.
+ */
+export function collageBounds(nodes, pad = 0) {
+ const xs = [];
+ const ys = [];
+ for (const n of nodes) for (const [x, y] of n.quad) { xs.push(x); ys.push(y); }
+ const minX = Math.min(...xs) - pad;
+ const minY = Math.min(...ys) - pad;
+ return {
+ minX,
+ minY,
+ width: Math.max(1, Math.round(Math.max(...xs) + pad - minX)),
+ height: Math.max(1, Math.round(Math.max(...ys) + pad - minY)),
+ };
+}
+
+/** Mean distance from the centroid to the corners — the quad's "radius". */
+export function quadRadius(quad) {
+ const [cx, cy] = quadCentroid(quad);
+ const d = quad.reduce((s, [x, y]) => s + Math.hypot(x - cx, y - cy), 0);
+ return d / quad.length || 1;
+}
+
+/** Rotate a quad by `rad` radians around a fixed point (its centroid by default). */
+export function rotateQuad(quad, rad, center = null) {
+ const [cx, cy] = center ?? quadCentroid(quad);
+ const cos = Math.cos(rad);
+ const sin = Math.sin(rad);
+ return quad.map(([x, y]) => {
+ const dx = x - cx;
+ const dy = y - cy;
+ return [cx + dx * cos - dy * sin, cy + dx * sin + dy * cos];
+ });
+}
+
/** A sensible starting quad: the image scaled to fit `maxW`, placed at (ox, oy). */
export function initialQuad(natW, natH, maxW, ox, oy) {
const scale = Math.min(1, maxW / (natW || maxW));
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index 80b0a34..f7a3f28 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -24,6 +24,7 @@ export const uiState = $state({
openProof: null, // proof name to load in the Proof Composer
openDraft: null, // draft name to load in the Post Composer
inspectPath: null, // media path to open in the Inspect tool
+ 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
});
diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelte
index 4e2038f..c6cf72b 100644
--- a/frontend/src/tools/Inspector.svelte
+++ b/frontend/src/tools/Inspector.svelte
@@ -3,6 +3,7 @@
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,
} from '../lib/inspect.js';
import Icon from '../components/Icon.svelte';
import SelectionMenu from './inspect/SelectionMenu.svelte';
@@ -11,6 +12,7 @@
import CollageMenu from './inspect/CollageMenu.svelte';
import SaveGallery from './inspect/SaveGallery.svelte';
import SaveMenu from './inspect/SaveMenu.svelte';
+ import PieceCropModal from './inspect/PieceCropModal.svelte';
// The Inspect tool is a *scratch workspace*. Opening a photo/video starts a
// session; captured frames, per-frame adjustments, video tuning and a collage
@@ -31,6 +33,10 @@
let activeTab = $state('selection');
let collageSelectedId = $state(null);
+ let cropPieceNode = $state(null);
+ // Real (backend-composited) Save-tab thumbnails, keyed by collage id:
+ // { sig, url } — regenerated only when a collage's layout actually changes.
+ let collagePreviews = $state({});
let saving = $state(false);
const saveUi = $state({ selected: {}, folder: '' });
// the saved session this workspace came from (if any) — re-saving overwrites it
@@ -38,16 +44,28 @@
let openedSession = $state(null);
const sessionModal = $state({ open: false, mode: 'save', name: null, title: '', list: [], busy: 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.
+ function makeCollage(name) {
+ return { id: uid('cl'), name, width: 1600, height: 800, background: '#12141c', transparent: true, nodes: [] };
+ }
+
// the live session (reset on source / case change)
+ const _firstCollage = makeCollage('Collage 1');
const session = $state({
source: null,
videoAdjust: {},
frames: [],
activeFrameId: null,
- collage: { width: 1600, height: 800, background: '#12141c', transparent: false, nodes: [] },
+ collages: [_firstCollage],
+ activeCollageId: _firstCollage.id,
saved: {},
});
+ const activeCollage = $derived(
+ session.collages.find((c) => c.id === session.activeCollageId) ?? session.collages[0] ?? null
+ );
+
// viewer bridge (video seek + crop overlay), mirrors the old shared object
const shared = $state({ currentTime: 0, seekTo: null, cropMode: false });
let videoEl = $state();
@@ -77,10 +95,14 @@
saved: !!session.saved[`frame:${fr.id}`],
});
}
- if (session.collage.nodes.length) {
+ let colN = 0;
+ for (const cl of session.collages) {
+ colN += 1;
+ if (!cl.nodes.length) continue;
out.push({
- key: 'collage', kind: 'collage', label: 'Collage 1',
- thumb: null, collage: session.collage, saved: !!session.saved.collage,
+ key: `collage:${cl.id}`, kind: 'collage', label: cl.name || `Collage ${colN}`,
+ thumb: null, collage: cl, preview: collagePreviews[cl.id]?.url ?? null,
+ saved: !!session.saved[`collage:${cl.id}`],
});
}
return out;
@@ -139,7 +161,11 @@
session.videoAdjust = {};
session.frames = [];
session.activeFrameId = null;
- session.collage = { width: 1600, height: 800, background: '#12141c', transparent: false, nodes: [] };
+ const c0 = makeCollage('Collage 1');
+ session.collages = [c0];
+ session.activeCollageId = c0.id;
+ for (const p of Object.values(collagePreviews)) if (p?.url) URL.revokeObjectURL(p.url);
+ collagePreviews = {};
session.saved = {};
saveUi.selected = {};
saveUi.folder = '';
@@ -208,6 +234,45 @@
});
}
+ // -- true-to-export collage thumbnails (Save tab) -------------------------
+ // The Save picker shows the *actual* composited PNG (backend warp), not the
+ // CSS approximation. Signature = the pieces' recipes+quads, so we only re-render
+ // when a layout really changed.
+ const collageSig = (cl) => JSON.stringify(cl.nodes.map((n) => [n.save, n.quad]));
+
+ async function buildCollagePreview(cl, sig, cid) {
+ try {
+ const b = collageBounds(cl.nodes);
+ const nodes = cl.nodes.map((n) => ({
+ src: n.save, quad: n.quad.map(([x, y]) => [x - b.minX, y - b.minY]),
+ }));
+ const res = await fetch(`/api/cases/${cid}/inspect/compose-preview`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ width: b.width, height: b.height, background: null, nodes }),
+ });
+ if (!res.ok) return;
+ const url = URL.createObjectURL(await res.blob());
+ const prev = collagePreviews[cl.id];
+ if (prev?.url) URL.revokeObjectURL(prev.url);
+ collagePreviews[cl.id] = { sig, url };
+ } catch {
+ /* leave the CSS fallback in place */
+ }
+ }
+
+ $effect(() => {
+ if (activeTab !== 'save') return;
+ const cid = caseState.current?.id;
+ if (!cid) return;
+ for (const cl of session.collages) {
+ if (!cl.nodes.length) continue;
+ const sig = collageSig(cl);
+ if (collagePreviews[cl.id]?.sig === sig) continue;
+ buildCollagePreview(cl, sig, cid);
+ }
+ });
+
// -- frame capture (Selection) -------------------------------------------
async function capture(time) {
try {
@@ -226,24 +291,66 @@
// Collage pieces are snapshots frozen at add-time: the modified image is baked
// now and later frame edits never change it (deliberate — see SPEC).
async function addToCollage(frame) {
+ const cl = activeCollage;
+ if (!cl) return;
try {
const ops = buildOps(filters, frame.adjust, frame.crop);
const url = await renderUrl(frame.path, frame.time, ops);
const dim = await imageSize(url);
- const count = session.collage.nodes.length;
+ const count = cl.nodes.length;
const off = 30 + (count % 4) * 40;
- const quad = initialQuad(dim.w, dim.h, session.collage.width * 0.5, off, off);
+ const quad = initialQuad(dim.w, dim.h, cl.width * 0.5, off, off);
const node = {
- id: uid('nd'), frameId: frame.id, url, w: dim.w, h: dim.h,
+ id: uid('nd'), frameId: frame.id, url, baseUrl: url, w: dim.w, h: dim.h,
+ frameOps: ops, crop: null,
save: { path: frame.path, time: frame.time ?? null, ops }, quad,
};
- session.collage.nodes.push(node);
+ cl.nodes.push(node);
collageSelectedId = node.id;
} catch (e) {
toast(e.message, 'danger');
}
}
+ // Re-render a collage piece with (or without) its crop, applied before the
+ // warp. Keeps baseUrl (uncropped snapshot) so the crop editor never compounds.
+ async function applyNodeCrop(node, crop) {
+ try {
+ const frameOps = node.frameOps ?? node.save?.ops ?? [];
+ const ops = crop ? [...frameOps, { op: 'crop', params: crop }] : [...frameOps];
+ const url = await renderUrl(node.save.path, node.save.time, ops);
+ const dim = await imageSize(url);
+ // Reshape the quad so the cropped image keeps correct proportions and
+ // stays in place. Derive the *full-image* quad from the current one (a
+ // crop stored on the node is relative to the base image, so re-cropping
+ // never compounds), then re-project the new crop rectangle onto it.
+ const prev = node.crop;
+ const baseQuad = prev
+ ? 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);
+ }
+ node.url = url;
+ node.w = dim.w;
+ node.h = dim.h;
+ node.crop = crop;
+ node.save = { ...node.save, ops };
+ } catch (e) {
+ toast(e.message, 'danger');
+ }
+ }
+
+ // Open the piece crop editor, or clear the crop directly (clear=true).
+ function requestCrop(node, clear = false) {
+ if (clear) {
+ applyNodeCrop(node, null);
+ } else {
+ cropPieceNode = node;
+ }
+ }
+
function removeFrame(id) {
const fr = session.frames.find((f) => f.id === id);
if (fr?.url?.startsWith('blob:')) URL.revokeObjectURL(fr.url);
@@ -311,16 +418,22 @@
});
session.saved.video = true;
}
- if (chosen.some((it) => it.kind === 'collage')) {
- // each node carries its frozen snapshot recipe (path/time/ops)
- const nodes = session.collage.nodes.map((n) => ({ src: n.save, quad: n.quad }));
+ for (const it of chosen.filter((c) => c.kind === 'collage')) {
+ // A collage is always a transparent PNG of just the pieces, trimmed to
+ // their bounds — the export size follows the layout, not a manual value.
+ const cl = it.collage;
+ const b = collageBounds(cl.nodes);
+ const nodes = cl.nodes.map((n) => ({
+ src: n.save, // frozen snapshot recipe (path/time/ops)
+ quad: n.quad.map(([x, y]) => [x - b.minX, y - b.minY]),
+ }));
await api.post(`/api/cases/${cid}/inspect/compose`, {
- width: Math.round(session.collage.width),
- height: Math.round(session.collage.height),
- background: session.collage.transparent ? null : session.collage.background,
+ width: b.width,
+ height: b.height,
+ background: null,
nodes, folder,
});
- session.saved.collage = true;
+ session.saved[it.key] = true;
}
await reloadCase();
await refresh();
@@ -342,13 +455,15 @@
frames: session.frames.map((f) => ({
id: f.id, path: f.path, time: f.time, adjust: { ...f.adjust }, crop: f.crop, w: f.w, h: f.h,
})),
- collage: {
- width: session.collage.width, height: session.collage.height,
- background: session.collage.background, transparent: session.collage.transparent,
- nodes: session.collage.nodes.map((n) => ({
+ activeCollageId: session.activeCollageId,
+ collages: session.collages.map((cl) => ({
+ id: cl.id, name: cl.name, width: cl.width, height: cl.height,
+ background: cl.background, transparent: cl.transparent,
+ nodes: cl.nodes.map((n) => ({
id: n.id, frameId: n.frameId, save: n.save, w: n.w, h: n.h, quad: n.quad,
+ frameOps: n.frameOps ?? n.save.ops, crop: n.crop ?? null,
})),
- },
+ })),
};
}
@@ -421,21 +536,38 @@
}
}
session.activeFrameId = spec.activeFrameId ?? session.frames[0]?.id ?? null;
- const nodes = [];
- for (const n of spec.collage?.nodes ?? []) {
- try {
- nodes.push({ ...n, url: await renderUrl(n.save.path, n.save.time, n.save.ops) });
- } catch {
- /* skip a node whose source is gone */
+ // Back-compat: older sessions stored a single `collage`; newer ones an array.
+ const specCollages = spec.collages ?? (spec.collage ? [spec.collage] : []);
+ const collages = [];
+ for (const sc of specCollages) {
+ const nodes = [];
+ for (const n of sc.nodes ?? []) {
+ try {
+ // frameOps = the snapshot without the collage crop; baseUrl feeds the
+ // crop editor, url is the (possibly cropped) piece shown on the canvas.
+ const frameOps = n.frameOps ?? n.save.ops ?? [];
+ const crop = n.crop ?? null;
+ const baseUrl = await renderUrl(n.save.path, n.save.time, frameOps);
+ const url = crop ? await renderUrl(n.save.path, n.save.time, n.save.ops) : baseUrl;
+ nodes.push({ ...n, frameOps, crop, baseUrl, url });
+ } catch {
+ /* skip a node whose source is gone */
+ }
}
+ collages.push({
+ id: sc.id ?? uid('cl'),
+ name: sc.name ?? `Collage ${collages.length + 1}`,
+ width: sc.width ?? 1600,
+ height: sc.height ?? 800,
+ background: sc.background ?? '#12141c',
+ transparent: sc.transparent ?? false,
+ nodes,
+ });
}
- session.collage = {
- width: spec.collage?.width ?? 1600,
- height: spec.collage?.height ?? 800,
- background: spec.collage?.background ?? '#12141c',
- transparent: spec.collage?.transparent ?? false,
- nodes,
- };
+ if (!collages.length) collages.push(makeCollage('Collage 1'));
+ session.collages = collages;
+ session.activeCollageId =
+ collages.find((c) => c.id === spec.activeCollageId)?.id ?? collages[0].id;
openedSession = { name, title: spec.title || name };
activeTab = src.kind === 'video' ? 'selection' : 'frame';
sessionModal.open = false;
@@ -528,15 +660,31 @@
onpointermove={cropMove}
onpointerup={cropUp}
>
- <img src={activeFrame.url} alt="frame" style:filter={framePreview.filter} style:transform={framePreview.transform} />
- {#if cropBox}
+ {#if activeFrame.crop && !shared.cropMode}
+ <!-- committed crop: show the cropped region filling the box -->
<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>
+ class="crop-view"
+ style:--ar={cropAspect(activeFrame.crop, activeFrame.w, activeFrame.h) ?? 1}
+ >
+ <img
+ src={activeFrame.url}
+ alt="frame"
+ style={styleText(cropImgStyle(activeFrame.crop))}
+ style:filter={framePreview.filter}
+ style:transform={framePreview.transform}
+ />
+ </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>
{:else}
@@ -546,7 +694,7 @@
</div>
{/if}
{:else if activeTab === 'collage'}
- <CollageCanvas {session} bind:selectedId={collageSelectedId} />
+ <CollageCanvas collage={activeCollage} bind:selectedId={collageSelectedId} />
{:else if activeTab === 'save'}
<SaveGallery {savables} {saveUi} />
{/if}
@@ -558,7 +706,7 @@
{:else if activeTab === 'frame'}
<FrameMenu {session} {filters} {analyses} {activeFrame} {shared} {removeFrame} setActive={(id) => (session.activeFrameId = id)} />
{:else if activeTab === 'collage'}
- <CollageMenu {session} {filters} bind:selectedId={collageSelectedId} {addToCollage} />
+ <CollageMenu {session} {filters} bind:selectedId={collageSelectedId} {addToCollage} {requestCrop} />
{:else if activeTab === 'save'}
<SaveMenu {savables} {saveUi} {saving} save={saveSelected} />
{/if}
@@ -566,6 +714,14 @@
</div>
{/if}
+ {#if cropPieceNode}
+ <PieceCropModal
+ node={cropPieceNode}
+ onapply={(crop) => { applyNodeCrop(cropPieceNode, crop); cropPieceNode = null; }}
+ onclose={() => (cropPieceNode = null)}
+ />
+ {/if}
+
{#if sessionModal.open}
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
@@ -727,6 +883,17 @@
box-shadow: 0 0 0 9999px rgba(6, 9, 14, 0.55);
pointer-events: none;
}
+ .crop-view {
+ position: relative;
+ overflow: hidden;
+ aspect-ratio: var(--ar);
+ height: calc(100vh - var(--topbar-h) - 200px);
+ max-width: 100%;
+ line-height: 0;
+ }
+ .crop-view img {
+ display: block;
+ }
.panel {
width: 320px;
flex-shrink: 0;
diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelte
index 57f285c..6451f65 100644
--- a/frontend/src/tools/MediaLibrary.svelte
+++ b/frontend/src/tools/MediaLibrary.svelte
@@ -55,6 +55,11 @@
// --- lightbox ---
let lightboxItem = $state(null);
+ // --- focus/highlight (a media clicked from the case sidebar) ---
+ let focusedPath = $state(null);
+ let focusScrolledFor = null;
+ let focusTimer;
+
$effect(() => {
const id = caseState.current?.id;
caseState.rev; // also refetch when the case is reloaded elsewhere (e.g. sidebar edit)
@@ -65,6 +70,35 @@
if (id) refresh(id);
});
+ // Pick up a "focus this media" handoff from the sidebar: clear filters that
+ // might hide it, flag it for the highlight ring, then let it fade on its own.
+ $effect(() => {
+ if (!uiState.focusMedia) return;
+ catFilter = null;
+ folderFilter = null;
+ focusedPath = uiState.focusMedia;
+ uiState.focusMedia = null;
+ clearTimeout(focusTimer);
+ focusTimer = setTimeout(() => (focusedPath = null), 3000);
+ });
+
+ // Scroll the focused card into view once it's actually in the rendered grid
+ // (items may still be loading when the handoff arrives).
+ $effect(() => {
+ const p = focusedPath;
+ if (!p) {
+ focusScrolledFor = null;
+ return;
+ }
+ if (focusScrolledFor === p || !filteredItems.some((i) => i.path === p)) return;
+ focusScrolledFor = p;
+ requestAnimationFrame(() => {
+ document
+ .querySelector(`.media-card[data-path="${CSS.escape(p)}"]`)
+ ?.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ });
+ });
+
async function refresh(id = caseState.current?.id) {
if (id) items = await api.get(`/api/cases/${id}/media`);
}
@@ -325,7 +359,11 @@
{:else}
<div class="grid">
{#each filteredItems as item (item.path)}
- <div class="media-card card fade-up">
+ <div
+ class="media-card card fade-up"
+ class:focused={item.path === focusedPath}
+ data-path={item.path}
+ >
<!-- thumbnail — click to lightbox for images -->
<div
class="thumb"
@@ -496,6 +534,12 @@
>{editItem.source.webpage_url ?? editItem.source.url}</a>
</div>
{/if}
+ {#if editItem.source.description}
+ <div class="info-row">
+ <span class="info-label">Description</span>
+ <span class="description">{editItem.source.description}</span>
+ </div>
+ {/if}
{/if}
</div>
@@ -672,6 +716,15 @@
border-color: var(--border-strong);
transform: translateY(-1px);
}
+ .media-card.focused {
+ border-color: var(--accent);
+ box-shadow: 0 0 0 2px var(--accent-soft);
+ animation: focus-flash 0.9s var(--ease) 2;
+ }
+ @keyframes focus-flash {
+ 0%, 100% { box-shadow: 0 0 0 2px var(--accent-soft); }
+ 50% { box-shadow: 0 0 0 4px var(--accent-soft); }
+ }
.thumb {
position: relative;
aspect-ratio: 16 / 10;
@@ -816,6 +869,16 @@
text-overflow: ellipsis;
white-space: nowrap;
}
+ .description {
+ flex: 1;
+ min-width: 0;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ white-space: pre-wrap;
+ word-break: break-word;
+ max-height: 8.5em;
+ overflow-y: auto;
+ }
.divider {
border: none;
border-top: 1px solid var(--border);
diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelte
index 1cb17db..752d3e9 100644
--- a/frontend/src/tools/PostComposer.svelte
+++ b/frontend/src/tools/PostComposer.svelte
@@ -1,6 +1,7 @@
<script>
import { api } from '../lib/api.js';
import { caseState, uiState, toast, reloadCase } from '../lib/state.svelte.js';
+ import { proofCoordsText, proofSource } from '../lib/composer.js';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
@@ -47,15 +48,13 @@
if (!p) return;
uiState.postProof = null;
description = p.title === 'Untitled proof' ? '' : (p.title ?? '');
- source = p.sources?.[0] ?? '';
+ source = p.source ?? p.sources?.[0] ?? '';
setProof(p.png ?? null);
tweet1Edited = false;
- if (p.coords) {
- coordsText = `${p.coords.lat.toFixed(6)}, ${p.coords.lon.toFixed(6)}`;
- resolveCoords();
- } else {
- regenerate();
- }
+ coordsText = p.coordsText
+ ?? (p.coords ? `${p.coords.lat.toFixed(6)}, ${p.coords.lon.toFixed(6)}` : '');
+ if (coordsText.trim()) resolveCoords();
+ else regenerate();
});
// Consume an "open this draft" handoff from the sidebar
@@ -229,13 +228,23 @@
}
}
- function pickProof(item) {
+ async function pickProof(item) {
setProof(item.png);
+ proofPickerOpen = false;
if (!description.trim() && item.title && item.title !== 'Untitled proof') {
description = item.title;
- regenerate();
}
- proofPickerOpen = false;
+ // Pull the proof's coordinates + source into the post so the fields fill in.
+ try {
+ const spec = await api.get(`/api/cases/${caseState.current.id}/proofs/${item.name}`);
+ const src = proofSource(spec);
+ if (src) source = src;
+ const ct = proofCoordsText(spec);
+ if (ct) { coordsText = ct; await resolveCoords(); return; }
+ } catch {
+ /* fall through to a plain regenerate */
+ }
+ regenerate();
}
function clearProof() {
diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelte
index 45b6035..5c8b96d 100644
--- a/frontend/src/tools/ProofComposer.svelte
+++ b/frontend/src/tools/ProofComposer.svelte
@@ -6,12 +6,20 @@
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
import {
- ANNO_COLORS, PAD, CAPTION_H, LEGEND_LINE_H, FOOTER_H,
+ ANNO_COLORS, PAD, TWEET_GUIDES,
+ CAPTION_SIZE, LEGEND_SIZE, FOOTER_SIZE,
BG, TEXT_MAIN, TEXT_DIM, TEXT_FAINT,
- layoutPanels, attributionLine, docSize, toSpec, newId, loadImage,
- featureColors, notesFromShapes,
+ layoutPanels, panelsBlockHeight, legendLineHeight, footerBand,
+ attributionLine, docSize, offsetShape, autoLayoutRows,
+ autoCoords, formatCoords, autoSource, resolveSourceUrls,
+ toSpec, newId, loadImage, featureColors, notesFromShapes,
+ copyShapeSpec,
} from '../lib/composer.js';
+ const SCALE_MIN = 0.4;
+ const SCALE_MAX = 2.5;
+ const SCALE_STEP = 0.1;
+
const DRAW_TOOLS = [
{ id: 'select', icon: 'hand', label: 'Select / move' },
{ id: 'rect', icon: 'square', label: 'Box' },
@@ -25,12 +33,19 @@
// ---- document state -------------------------------------------------------
// `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: {}, coords: null });
+ const proof = $state({
+ title: 'Untitled proof', panels: [], shapes: [], notes: {},
+ coordsText: '', source: '', // '' → auto-derived from panels; non-empty → manual override
+ captionSize: CAPTION_SIZE, legendSize: LEGEND_SIZE, footerSize: FOOTER_SIZE, footer: '',
+ });
+ let advancedOpen = $state(false);
+ let collapsed = $state({ panels: false, annotations: false, elements: false });
let savedName = $state(null);
let dirty = $state(false);
let tool = $state('select');
let color = $state(ANNO_COLORS[0]);
let strokeW = $state(4);
+ let guide = $state(null); // null | '16:9' | '4:5' — tweet centre-crop overlay
let selectedId = $state(null);
let picker = $state(false);
let pickerItems = $state([]);
@@ -40,7 +55,7 @@
// ---- konva ------------------------------------------------------------------
let containerEl;
- let stage, docLayer, uiLayer, transformer, endHandles;
+ 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
@@ -60,6 +75,8 @@
borderDash: [4, 3],
ignoreStroke: true,
});
+ guideGroup = new Konva.Group({ listening: false });
+ uiLayer.add(guideGroup);
uiLayer.add(transformer);
endHandles = new Konva.Group();
uiLayer.add(endHandles);
@@ -118,20 +135,34 @@
// rebuild canvas whenever the document changes
$effect(() => {
JSON.stringify([
- proof.panels.map((p) => [p.src, p.caption]),
+ proof.panels.map((p) => [p.src, p.caption, p.row, p.scale]),
proof.shapes,
proof.notes,
+ proof.captionSize, proof.legendSize, proof.footerSize, proof.footer,
selectedId,
+ guide,
]);
if (stage) rebuild();
});
+ // Text-size options threaded into every layout/size computation.
+ const textOpts = () => ({
+ captionSize: proof.captionSize,
+ legendSize: proof.legendSize,
+ footerSize: proof.footerSize,
+ });
+
function resetDoc() {
proof.title = 'Untitled proof';
proof.panels = [];
proof.shapes = [];
proof.notes = {};
- proof.coords = null;
+ proof.coordsText = '';
+ proof.source = '';
+ proof.captionSize = CAPTION_SIZE;
+ proof.legendSize = LEGEND_SIZE;
+ proof.footerSize = FOOTER_SIZE;
+ proof.footer = '';
savedName = null;
selectedId = null;
dirty = false;
@@ -150,11 +181,16 @@
};
}
- function mediaPanelInput(m) {
+ function mediaPanelInput(m, mediaList = []) {
+ // Trace the real source link through the derivation chain (a collage/frame
+ // carries no URL of its own — follow it back to the downloaded original).
+ // A file uploaded from disk has no URL, so it contributes no source.
+ const byPath = new Map(mediaList.map((x) => [x.path, x]));
+ const urls = resolveSourceUrls(m, byPath);
return {
src: m.path,
- meta: { kind: 'media', source_url: m.source?.webpage_url ?? m.source?.url },
- caption: m.source?.title ?? m.filename,
+ meta: { kind: 'media', source_url: urls[0], source_urls: urls },
+ caption: '',
};
}
@@ -178,7 +214,7 @@
...media
.filter((m) => m.kind === 'image')
.map((m) => ({
- ...mediaPanelInput(m),
+ ...mediaPanelInput(m, media),
label: m.filename,
thumb: m.thumbnail ?? m.path,
kind: 'media',
@@ -190,17 +226,20 @@
async function addPanel(item) {
try {
const img = await loadImage(`/files/${caseState.current.id}/${item.src}`);
+ // 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))
+ : 0;
proof.panels.push({
id: newId('p'),
src: item.src,
caption: item.caption ?? '',
+ row,
+ scale: 1,
natural: [img.naturalWidth, img.naturalHeight],
meta: item.meta ?? {},
img,
});
- if (item.meta?.lat != null && !proof.coords) {
- proof.coords = { lat: item.meta.lat, lon: item.meta.lon };
- }
dirty = true;
requestAnimationFrame(fit);
} catch (e) {
@@ -221,22 +260,78 @@
continue;
}
const m = media.find((x) => x.path === path);
- if (m) await addPanel(mediaPanelInput(m));
+ if (m) await addPanel(mediaPanelInput(m, media));
}
}
+ // Renumber rows to a dense 0..n-1 range after a move may have emptied one.
+ function normalizeRows() {
+ const order = [...new Set(proof.panels.map((p) => p.row ?? 0))].sort((a, b) => a - b);
+ const remap = new Map(order.map((r, i) => [r, i]));
+ for (const p of proof.panels) p.row = remap.get(p.row ?? 0);
+ }
+
+ // Swap a panel with its left/right neighbour *within the same row*.
function movePanel(index, delta) {
- const target = index + delta;
- if (target < 0 || target >= proof.panels.length) return;
+ const row = proof.panels[index].row ?? 0;
+ let target = index + delta;
+ while (target >= 0 && target < proof.panels.length && (proof.panels[target].row ?? 0) !== row) {
+ target += delta;
+ }
+ if (target < 0 || target >= proof.panels.length || (proof.panels[target].row ?? 0) !== row) return;
const [panel] = proof.panels.splice(index, 1);
proof.panels.splice(target, 0, panel);
dirty = true;
}
+ // Move a panel up/down a row; going past the last row starts a fresh row.
+ function movePanelRow(index, delta) {
+ const panel = proof.panels[index];
+ const maxRow = Math.max(...proof.panels.map((p) => p.row ?? 0));
+ const next = (panel.row ?? 0) + delta;
+ if (next < 0 || next > maxRow + 1) return;
+ panel.row = next;
+ normalizeRows();
+ selectedId = null;
+ dirty = true;
+ requestAnimationFrame(fit);
+ }
+
+ const rowOf = (i) => proof.panels[i]?.row ?? 0;
+ const canMoveLeft = (i) => proof.panels.slice(0, i).some((p) => (p.row ?? 0) === rowOf(i));
+ const canMoveRight = (i) => proof.panels.slice(i + 1).some((p) => (p.row ?? 0) === rowOf(i));
+
+ // Grow / shrink a single panel (its drawn elements scale with it, since they
+ // live in the panel's natural pixel space and render at the panel box scale).
+ function scalePanel(index, delta) {
+ const p = proof.panels[index];
+ const cur = p.scale ?? 1;
+ const next = Math.round(Math.min(SCALE_MAX, Math.max(SCALE_MIN, cur + delta)) * 10) / 10;
+ if (next === cur) return;
+ p.scale = next;
+ dirty = true;
+ requestAnimationFrame(fit);
+ }
+
+ // "Magic" tweet fit: re-pack panels into rows so the composite lands closest
+ // to the active tweet aspect (the toggled 16:9 / 4:5 guide, else 16:9) and
+ // reset every panel to its default size.
+ function applyMagic() {
+ if (!proof.panels.length) return;
+ const target = guide ? TWEET_GUIDES[guide] : TWEET_GUIDES['16:9'];
+ const rows = autoLayoutRows(proof.panels, proof.shapes, proof.notes, textOpts(), target);
+ proof.panels.forEach((p, i) => { p.row = rows[i]; p.scale = 1; });
+ normalizeRows();
+ selectedId = null;
+ dirty = true;
+ requestAnimationFrame(fit);
+ }
+
function removePanel(index) {
const panel = proof.panels[index];
proof.shapes = proof.shapes.filter((s) => s.panel !== panel.id);
proof.panels.splice(index, 1);
+ normalizeRows();
selectedId = null;
dirty = true;
requestAnimationFrame(fit);
@@ -246,7 +341,7 @@
function fit() {
if (!stage || !containerEl || !containerEl.clientWidth) return;
- const { width, height } = docSize(proof.panels, proof.shapes, proof.notes);
+ const { width, height } = docSize(proof.panels, proof.shapes, proof.notes, textOpts());
const k = Math.min(
(containerEl.clientWidth - 24) / width,
(containerEl.clientHeight - 24) / height,
@@ -271,6 +366,10 @@
x: pointer.x - ((pointer.x - stage.x()) / old) * k,
y: pointer.y - ((pointer.y - stage.y()) / old) * k,
});
+ if (guide) {
+ const { width, height } = docSize(proof.panels, proof.shapes, proof.notes, textOpts());
+ drawGuide(width, height);
+ }
stage.batchDraw();
}
@@ -282,7 +381,7 @@
}
function panelAt(doc) {
- const boxes = layoutPanels(proof.panels);
+ const boxes = layoutPanels(proof.panels, proof.captionSize);
for (let i = 0; i < boxes.length; i++) {
const b = boxes[i];
if (doc.x >= b.x && doc.x <= b.x + b.w && doc.y >= b.y && doc.y <= b.y + b.h) {
@@ -323,7 +422,7 @@
if (!pathDraft) {
const node = new Konva.Line({
points: [hit.nx, hit.ny], tension: 0.5, stroke: color,
- strokeWidth: strokeW / hit.box.scale, lineCap: 'round', lineJoin: 'round',
+ strokeWidth: strokeW / hit.box.baseScale, lineCap: 'round', lineJoin: 'round',
listening: false,
});
group.add(node);
@@ -335,7 +434,7 @@
}
return;
}
- const sw = strokeW / hit.box.scale;
+ const sw = strokeW / hit.box.baseScale;
const common = { stroke: color, strokeWidth: sw, listening: false };
let node;
if (tool === 'rect') {
@@ -345,8 +444,8 @@
} else {
node = new Konva.Arrow({
points: [hit.nx, hit.ny, hit.nx, hit.ny],
- pointerLength: tool === 'arrow' ? 14 / hit.box.scale : 0,
- pointerWidth: tool === 'arrow' ? 14 / hit.box.scale : 0,
+ pointerLength: tool === 'arrow' ? 14 / hit.box.baseScale : 0,
+ pointerWidth: tool === 'arrow' ? 14 / hit.box.baseScale : 0,
fill: color,
...common,
});
@@ -449,8 +548,9 @@
function rebuild() {
docLayer.destroyChildren();
- const { width, height, legend } = docSize(proof.panels, proof.shapes, proof.notes);
- const boxes = layoutPanels(proof.panels);
+ const { width, height, legend, cols } = docSize(proof.panels, proof.shapes, proof.notes, textOpts());
+ const boxes = layoutPanels(proof.panels, proof.captionSize);
+ const capSize = proof.captionSize ?? CAPTION_SIZE;
docLayer.add(
new Konva.Rect({ name: 'bg', x: 0, y: 0, width, height, fill: BG })
@@ -458,55 +558,73 @@
proof.panels.forEach((panel, i) => {
const box = boxes[i];
+ // Outer group is NOT clipped so an element can be dragged across panels;
+ // only the image itself is clipped to the panel box (inner group).
const group = new Konva.Group({
id: `pg-${panel.id}`,
x: box.x, y: box.y,
scaleX: box.scale, scaleY: box.scale,
- clip: { x: 0, y: 0, width: panel.natural[0], height: panel.natural[1] },
});
if (panel.img) {
- group.add(new Konva.Image({
+ const imgClip = new Konva.Group({
+ clip: { x: 0, y: 0, width: panel.natural[0], height: panel.natural[1] },
+ listening: false,
+ });
+ imgClip.add(new Konva.Image({
image: panel.img, width: panel.natural[0], height: panel.natural[1], listening: false,
}));
+ group.add(imgClip);
}
for (const s of proof.shapes.filter((x) => x.panel === panel.id)) {
- group.add(makeShapeNode(s, box.scale));
+ group.add(makeShapeNode(s, box));
}
docLayer.add(group);
if (panel.caption?.trim()) {
docLayer.add(new Konva.Text({
x: box.x + 2, y: box.y + box.h + 9,
width: box.w - 4, text: panel.caption,
- fontSize: 17, fontFamily: 'system-ui, sans-serif',
+ fontSize: capSize, fontFamily: 'system-ui, sans-serif',
fill: TEXT_DIM, ellipsis: true, wrap: 'none', listening: false,
}));
}
});
- // legend (numbered colored chips) + attribution footer
- let y = PAD + (proof.panels.length ? boxes[0].h : 0) + CAPTION_H + 8;
- for (const line of legend.filter((l) => l.text)) {
+ // legend (numbered colored chips) laid out in `cols` columns, then footer.
+ // Chip + 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) => {
+ const col = i % cols;
+ const rowN = Math.floor(i / cols);
+ const cx = PAD + col * (colW + PAD);
+ const cy = legendTop + rowN * lineH + lineH / 2;
docLayer.add(new Konva.Circle({
- x: PAD + 11, y: y + 11, radius: 10, fill: line.color, listening: false,
+ x: cx + r, y: cy, radius: r, fill: line.color, listening: false,
}));
docLayer.add(new Konva.Text({
- x: PAD + 4, y: y + 5, width: 14, align: 'center',
- text: String(line.n), fontSize: 13, fontStyle: 'bold',
+ 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: PAD + 30, y: y + 3, width: width - PAD * 2 - 30,
- text: line.text, fontSize: 17, fill: TEXT_MAIN,
+ x: cx + r * 2 + 8, y: cy - legendSize * 0.62, width: colW - (r * 2 + 8),
+ text: line.text, fontSize: legendSize, fill: TEXT_MAIN,
fontFamily: 'system-ui, sans-serif', ellipsis: true, wrap: 'none', listening: false,
}));
- y += LEGEND_LINE_H;
- }
+ });
if (proof.panels.length) {
+ const footerSize = proof.footerSize ?? 13;
+ const footerText = proof.footer?.trim() || attributionLine(proof.panels);
docLayer.add(new Konva.Text({
- x: PAD, y: height - FOOTER_H - PAD + 8,
+ x: PAD,
+ y: height - PAD - footerBand(footerSize) + Math.round((footerBand(footerSize) - footerSize) / 2),
width: width - PAD * 2,
- text: attributionLine(proof.panels),
- fontSize: 12.5, fill: TEXT_FAINT,
+ text: footerText,
+ fontSize: footerSize, fill: TEXT_FAINT,
fontFamily: 'system-ui, sans-serif', ellipsis: true, wrap: 'none', listening: false,
}));
}
@@ -524,10 +642,47 @@
: []
);
drawEndHandles(boxes);
+ drawGuide(width, height);
docLayer.batchDraw();
uiLayer.batchDraw();
}
+ // Tweet centre-crop preview: X displays a single image with object-fit: cover
+ // into a box of the chosen aspect, so it crops whatever falls outside the
+ // largest centred rect of that aspect. We dim that outside region and outline
+ // the safe area. Screen-only (drawn on uiLayer, never exported).
+ function drawGuide(width, height) {
+ guideGroup.destroyChildren();
+ const aspect = guide ? TWEET_GUIDES[guide] : null;
+ if (!aspect || !proof.panels.length) return;
+ let w = width, h = width / aspect;
+ if (h > height) { h = height; w = height * aspect; }
+ const gx = (width - w) / 2;
+ const gy = (height - h) / 2;
+ const dim = 'rgba(9, 12, 20, 0.62)';
+ const masks = [
+ { x: 0, y: 0, width, height: gy },
+ { x: 0, y: gy + h, width, height: height - gy - h },
+ { x: 0, y: gy, width: gx, height: h },
+ { x: gx + w, y: gy, width: width - gx - w, height: h },
+ ];
+ for (const m of masks) {
+ if (m.width > 0.5 && m.height > 0.5) {
+ guideGroup.add(new Konva.Rect({ ...m, fill: dim, listening: false }));
+ }
+ }
+ guideGroup.add(new Konva.Rect({
+ x: gx, y: gy, width: w, height: h,
+ stroke: '#e8a33d', strokeWidth: 2 / stage.scaleX(), dash: [10 / stage.scaleX(), 6 / stage.scaleX()],
+ listening: false,
+ }));
+ guideGroup.add(new Konva.Text({
+ x: gx + 8, y: gy + 6, text: `${guide} · visible in tweet`,
+ fontSize: 15 / stage.scaleX(), fontStyle: 'bold', fill: '#e8a33d',
+ fontFamily: 'system-ui, sans-serif', listening: false,
+ }));
+ }
+
// Draggable per-vertex handles for the selected line / arrow / curve, so any
// point can be re-placed after drawing (rects/ellipses/text use the transformer).
const POINT_KINDS = new Set(['line', 'arrow', 'curve']);
@@ -571,7 +726,50 @@
}
}
- function makeShapeNode(s, panelScale) {
+ // On drop, re-bind a shape to whichever panel its anchor now sits over and
+ // convert its coordinates into that panel's natural pixel space. Returns the
+ // source/destination layout boxes so the caller can remap x/y or points.
+ function rebindOnDrop(s, node) {
+ const boxes = layoutPanels(proof.panels, proof.captionSize);
+ const fromIdx = proof.panels.findIndex((p) => p.id === s.panel);
+ if (fromIdx < 0) return { fromBox: null, toBox: null };
+ const fromBox = boxes[fromIdx];
+ let anchor;
+ if (s.kind === 'rect') {
+ anchor = { x: node.x() + (s.w ?? 0) / 2, y: node.y() + (s.h ?? 0) / 2 };
+ } else if (s.kind === 'ellipse' || s.kind === 'text') {
+ anchor = { x: node.x(), y: node.y() };
+ } else {
+ const pts = s.points.map((v, i) => v + (i % 2 === 0 ? node.x() : node.y()));
+ let sx = 0, sy = 0;
+ for (let i = 0; i < pts.length; i += 2) { sx += pts[i]; sy += pts[i + 1]; }
+ anchor = { x: sx / (pts.length / 2), y: sy / (pts.length / 2) };
+ }
+ const dx = fromBox.x + anchor.x * fromBox.scale;
+ const dy = fromBox.y + anchor.y * fromBox.scale;
+ let toIdx = fromIdx;
+ for (let i = 0; i < boxes.length; i++) {
+ const b = boxes[i];
+ if (dx >= b.x && dx <= b.x + b.w && dy >= b.y && dy <= b.y + b.h) { toIdx = i; break; }
+ }
+ s.panel = proof.panels[toIdx].id;
+ return { fromBox, toBox: boxes[toIdx] };
+ }
+
+ // Doc→panel remap of a single x/y origin between two layout boxes.
+ function remapXY(x, y, fromBox, toBox) {
+ return {
+ x: (fromBox.x + x * fromBox.scale - toBox.x) / toBox.scale,
+ y: (fromBox.y + y * fromBox.scale - toBox.y) / toBox.scale,
+ };
+ }
+
+ // `box` carries `scale` (natural→doc, grows with the panel) and `baseScale`
+ // (that mapping at scale 1). Stroke width and arrow heads are normalised by
+ // baseScale so they read the same across image resolutions yet still grow
+ // proportionally when the panel is scaled up.
+ 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 || ' ',
@@ -584,9 +782,12 @@
selectedId = s.id;
}
});
+ node.on('dragstart', () => node.getParent()?.moveToTop());
node.on('dragend', () => {
- s.x = node.x();
- s.y = node.y();
+ const { fromBox, toBox } = rebindOnDrop(s, node);
+ const p = toBox ? remapXY(node.x(), node.y(), fromBox, toBox) : { x: node.x(), y: node.y() };
+ s.x = p.x;
+ s.y = p.y;
dirty = true;
});
node.on('transformend', () => {
@@ -630,14 +831,25 @@
selectedId = s.id;
}
});
+ node.on('dragstart', () => node.getParent()?.moveToTop());
node.on('dragend', () => {
if (s.kind === 'rect' || s.kind === 'ellipse') {
- s.x = node.x();
- s.y = node.y();
+ const { fromBox, toBox } = rebindOnDrop(s, node);
+ const p = toBox ? remapXY(node.x(), node.y(), fromBox, toBox) : { x: node.x(), y: node.y() };
+ s.x = p.x;
+ s.y = p.y;
} else {
- // arrow / line / curve: fold the drag offset back into every vertex
+ // arrow / line / curve: fold the drag offset into every vertex, then
+ // remap the whole polyline into the panel it was dropped onto
const dx = node.x(), dy = node.y();
- s.points = s.points.map((v, i) => (i % 2 === 0 ? v + dx : v + dy));
+ const folded = s.points.map((v, i) => (i % 2 === 0 ? v + dx : v + dy));
+ const { fromBox, toBox } = rebindOnDrop(s, node);
+ s.points = toBox
+ ? folded.map((v, i) => {
+ const doc = (i % 2 === 0 ? fromBox.x : fromBox.y) + v * (fromBox?.scale ?? 1);
+ return (doc - (i % 2 === 0 ? toBox.x : toBox.y)) / toBox.scale;
+ })
+ : folded;
node.position({ x: 0, y: 0 });
}
dirty = true;
@@ -661,6 +873,36 @@
// ---- shape ops from the side panel -----------------------------------------------------
+ // ---- clipboard (copy / paste / duplicate of a single element) ---------------
+ let clipboard = null; // detached deep copy of a shape spec (no id)
+
+ function copyShape(id = selectedId) {
+ const s = proof.shapes.find((x) => x.id === id);
+ if (!s) return;
+ clipboard = copyShapeSpec(s);
+ }
+
+ // Paste the clipboard as a fresh element, nudged down-right so it doesn't hide
+ // the original. Points-based kinds (line/arrow/curve) shift every vertex.
+ function pasteShape() {
+ if (!clipboard) return;
+ const target = proof.panels.some((p) => p.id === clipboard.panel)
+ ? clipboard.panel
+ : proof.panels[0]?.id;
+ if (!target) return;
+ const s = { ...offsetShape(clipboard, 26), id: newId('s'), panel: target };
+ proof.shapes.push(s);
+ selectedId = s.id;
+ // cascade further pastes so repeated Ctrl+V steps down-right
+ clipboard = offsetShape(s, 0);
+ dirty = true;
+ }
+
+ function duplicateShape(id = selectedId) {
+ copyShape(id);
+ pasteShape();
+ }
+
function deleteShape(id) {
const gone = proof.shapes.find((s) => s.id === id);
proof.shapes = proof.shapes.filter((s) => s.id !== id);
@@ -712,6 +954,14 @@
finishPath(e.key === 'Enter');
return;
}
+ // clipboard: copy / paste / duplicate the selected element
+ 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(); }
+ return; // don't fall through to the single-letter tool shortcuts
+ }
if ((e.key === 'Delete' || e.key === 'Backspace') && selectedId) {
deleteShape(selectedId);
} else if (e.key === 'Escape') {
@@ -730,7 +980,7 @@
// ---- persistence -------------------------------------------------------------------------
function exportPng() {
- const { width, height } = docSize(proof.panels, proof.shapes, proof.notes);
+ const { width, height } = docSize(proof.panels, proof.shapes, proof.notes, textOpts());
const prevScale = stage.scale();
const prevPos = stage.position();
const prevSize = { w: stage.width(), h: stage.height() };
@@ -768,10 +1018,10 @@
if (andPost) {
uiState.postProof = {
title: proof.title,
- coords: proof.coords,
+ coordsText: displayedCoords,
+ source: displayedSource,
attribution: attributionLine(proof.panels),
png: result.png,
- sources: proof.panels.map((p) => p.meta?.source_url).filter(Boolean),
};
uiState.tool = 'post';
}
@@ -790,11 +1040,16 @@
const spec = await api.get(`/api/cases/${caseState.current.id}/proofs/${entry.name}`);
resetDoc();
proof.title = spec.title;
- proof.coords = spec.coords ?? null;
+ 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 ?? '';
for (const p of spec.panels) {
try {
const img = await loadImage(`/files/${caseState.current.id}/${p.src}`);
- proof.panels.push({ ...p, id: p.id ?? newId('p'), img });
+ proof.panels.push({ ...p, id: p.id ?? newId('p'), row: p.row ?? 0, img });
} catch {
toast(`Missing panel image: ${p.src}`, 'warn');
}
@@ -812,6 +1067,12 @@
const selectedShape = $derived(proof.shapes.find((s) => s.id === selectedId));
const activeColor = $derived(selectedShape?.color ?? color);
const featureList = $derived(featureColors(proof.shapes));
+
+ // Coordinates + source shown above the panels: a manual override wins, else
+ // the value auto-derived from the panels (reactive — deleting the first
+ // satellite panel falls back to the next, adding media fills the source).
+ const displayedCoords = $derived(proof.coordsText.trim() || formatCoords(autoCoords(proof.panels)));
+ const displayedSource = $derived(proof.source.trim() || autoSource(proof.panels));
</script>
<svelte:window onkeydown={onKeydown} />
@@ -887,6 +1148,23 @@
/>
<div class="tb-sep"></div>
<button class="tb-btn" title="Fit view (f)" onclick={fit}><Icon name="eye" size={18} /></button>
+ <div class="tb-sep"></div>
+ {#each Object.keys(TWEET_GUIDES) as g (g)}
+ <button
+ class="tb-btn tb-guide"
+ class:active={guide === g}
+ title={`Preview the ${g} tweet crop — everything outside is cut off`}
+ onclick={() => (guide = guide === g ? null : g)}
+ >{g}</button>
+ {/each}
+ <button
+ class="tb-btn tb-magic"
+ title={`Auto-fit for a tweet — re-pack panels toward ${guide ?? '16:9'} and reset panel sizes`}
+ disabled={!proof.panels.length}
+ onclick={applyMagic}
+ >
+ <Icon name="wand" size={18} />
+ </button>
</div>
<!-- canvas -->
@@ -910,10 +1188,65 @@
<!-- right: panels & annotations -->
<aside class="side">
<div class="side-scroll">
- <div class="side-title">Panels <span class="count">{proof.panels.length}</span></div>
+ <!-- Proof context: coordinates + source, auto-filled from the panels,
+ overridable. A ! flags a value the analyst still needs to supply. -->
+ <div class="meta-field">
+ <div class="meta-head">
+ <Icon name="crosshair" size={13} />
+ <span>Coordinates</span>
+ {#if !displayedCoords}
+ <span class="meta-warn" title="No satellite panel yet — add one or type the coordinates">
+ <Icon name="alert" size={13} />
+ </span>
+ {/if}
+ {#if proof.coordsText.trim()}
+ <button class="meta-reset" title="Reset to the coordinates from the imagery" onclick={() => { proof.coordsText = ''; dirty = true; }}>
+ <Icon name="reset" size={12} />
+ </button>
+ {/if}
+ </div>
+ <input
+ class="input meta-input"
+ class:warn={!displayedCoords}
+ placeholder="lat, lon"
+ value={displayedCoords}
+ oninput={(e) => { proof.coordsText = e.target.value; dirty = true; }}
+ />
+ </div>
+ <div class="meta-field">
+ <div class="meta-head">
+ <Icon name="link" size={13} />
+ <span>Source</span>
+ {#if !displayedSource}
+ <span class="meta-warn" title="A source is a link — add media downloaded from a URL, or paste one">
+ <Icon name="alert" size={13} />
+ </span>
+ {/if}
+ {#if proof.source.trim()}
+ <button class="meta-reset" title="Reset to the source traced from the media" onclick={() => { proof.source = ''; dirty = true; }}>
+ <Icon name="reset" size={12} />
+ </button>
+ {/if}
+ </div>
+ <input
+ class="input meta-input"
+ class:warn={!displayedSource}
+ placeholder="https://…"
+ value={displayedSource}
+ oninput={(e) => { proof.source = e.target.value; dirty = true; }}
+ />
+ </div>
+
+ <button class="side-title collapsible" style="margin-top: 14px" onclick={() => (collapsed.panels = !collapsed.panels)}>
+ <span><Icon name={collapsed.panels ? 'chevronRight' : 'chevronDown'} size={13} /> Panels <span class="count">{proof.panels.length}</span></span>
+ </button>
+ {#if !collapsed.panels}
{#each proof.panels as panel, i (panel.id)}
<div class="panel-row card">
- <img src={`/files/${caseState.current?.id}/${panel.src}`} alt="" />
+ <div class="panel-thumb">
+ <img src={`/files/${caseState.current?.id}/${panel.src}`} alt="" />
+ <span class="row-badge" title="Row (top→bottom)">R{(panel.row ?? 0) + 1}</span>
+ </div>
<input
class="input cap-input"
placeholder="Caption…"
@@ -921,19 +1254,38 @@
onchange={() => (dirty = true)}
/>
<div class="panel-actions">
- <button class="btn btn-ghost btn-sm" disabled={i === 0} title="Move left" onclick={() => movePanel(i, -1)}>←</button>
- <button class="btn btn-ghost btn-sm" disabled={i === proof.panels.length - 1} title="Move right" onclick={() => movePanel(i, 1)}>→</button>
+ <button class="btn btn-ghost btn-sm" disabled={!canMoveLeft(i)} title="Move left in row" onclick={() => movePanel(i, -1)}>←</button>
+ <button class="btn btn-ghost btn-sm" disabled={!canMoveRight(i)} title="Move right in row" onclick={() => movePanel(i, 1)}>→</button>
+ <button class="btn btn-ghost btn-sm" disabled={(panel.row ?? 0) === 0} title="Move up a row" onclick={() => movePanelRow(i, -1)}>↑</button>
+ <button class="btn btn-ghost btn-sm" title="Move down a row" onclick={() => movePanelRow(i, 1)}>↓</button>
<button class="btn btn-ghost btn-sm" style="margin-left:auto" title="Remove panel" onclick={() => removePanel(i)}>
<Icon name="trash" size={13} />
</button>
</div>
+ <div class="panel-scale" title="Panel size — elements scale with it">
+ <button
+ class="btn btn-ghost btn-sm"
+ disabled={(panel.scale ?? 1) <= SCALE_MIN}
+ title="Shrink panel"
+ onclick={() => scalePanel(i, -SCALE_STEP)}
+ >−</button>
+ <span class="scale-val">{Math.round((panel.scale ?? 1) * 100)}%</span>
+ <button
+ class="btn btn-ghost btn-sm"
+ disabled={(panel.scale ?? 1) >= SCALE_MAX}
+ title="Enlarge panel"
+ onclick={() => scalePanel(i, SCALE_STEP)}
+ >+</button>
+ </div>
</div>
{/each}
+ {/if}
<!-- Annotations: one legend note per color (feature), not per element -->
- <div class="side-title" style="margin-top: 14px">
- Annotations <span class="count">{featureList.length}</span>
- </div>
+ <button class="side-title collapsible" style="margin-top: 14px" onclick={() => (collapsed.annotations = !collapsed.annotations)}>
+ <span><Icon name={collapsed.annotations ? 'chevronRight' : 'chevronDown'} size={13} /> Annotations <span class="count">{featureList.length}</span></span>
+ </button>
+ {#if !collapsed.annotations}
{#if !featureList.length}
<div class="none">Draw on the panels with the box, ellipse, arrow or line tools. Same color = same feature.</div>
{/if}
@@ -953,11 +1305,13 @@
/>
</div>
{/each}
+ {/if}
<!-- Elements: every drawn shape, for quick select / delete -->
- <div class="side-title" style="margin-top: 14px">
- Elements <span class="count">{proof.shapes.length}</span>
- </div>
+ <button class="side-title collapsible" style="margin-top: 14px" onclick={() => (collapsed.elements = !collapsed.elements)}>
+ <span><Icon name={collapsed.elements ? 'chevronRight' : 'chevronDown'} size={13} /> Elements <span class="count">{proof.shapes.length}</span></span>
+ </button>
+ {#if !collapsed.elements}
{#each proof.shapes as s, i (s.id)}
<div
class="shape-row"
@@ -980,11 +1334,53 @@
{:else}
<span class="el-label">{KIND_LABEL[s.kind]} <span class="el-id">#{i + 1}</span></span>
{/if}
+ <button class="btn btn-ghost btn-sm" title="Duplicate (Ctrl+D)" onclick={(e) => { e.stopPropagation(); duplicateShape(s.id); }}>
+ <Icon name="copy" size={13} />
+ </button>
<button class="btn btn-ghost btn-sm" title="Delete" onclick={(e) => { e.stopPropagation(); deleteShape(s.id); }}>
<Icon name="trash" size={13} />
</button>
</div>
{/each}
+ {/if}
+
+ <!-- Advanced: text sizes + editable footer (the trickier knobs) -->
+ <button class="adv-toggle" onclick={() => (advancedOpen = !advancedOpen)} style="margin-top: 14px">
+ <Icon name={advancedOpen ? 'chevronDown' : 'chevronRight'} size={13} />
+ Advanced — text &amp; footer
+ </button>
+ {#if advancedOpen}
+ <div class="adv-body">
+ <div class="size-row">
+ <span>Caption size</span>
+ <input class="size-slider" type="range" min="10" max="40" step="1"
+ bind:value={proof.captionSize} oninput={() => (dirty = true)} />
+ <span class="size-val">{proof.captionSize}</span>
+ </div>
+ <div class="size-row">
+ <span>Legend size</span>
+ <input class="size-slider" type="range" min="11" max="40" step="1"
+ bind:value={proof.legendSize} oninput={() => (dirty = true)} />
+ <span class="size-val">{proof.legendSize}</span>
+ </div>
+ <div class="size-row">
+ <span>Footer size</span>
+ <input class="size-slider" type="range" min="10" max="32" step="1"
+ bind:value={proof.footerSize} oninput={() => (dirty = true)} />
+ <span class="size-val">{proof.footerSize}</span>
+ </div>
+ <label class="adv-label" for="footer-text">Footer text</label>
+ <textarea
+ id="footer-text"
+ class="input footer-input"
+ rows="2"
+ placeholder={attributionLine(proof.panels)}
+ bind:value={proof.footer}
+ oninput={() => (dirty = true)}
+ ></textarea>
+ <div class="adv-hint">Leave empty to keep the automatic imagery / source attribution.</div>
+ </div>
+ {/if}
</div>
</aside>
</div>
@@ -1073,6 +1469,10 @@
}
.tb-btn:hover { color: var(--text-1); background: var(--bg-2); }
.tb-btn.active { color: var(--accent); background: var(--accent-soft); }
+ .tb-guide { font-size: 11px; font-weight: 700; }
+ .tb-magic:not(:disabled) { color: var(--accent); }
+ .tb-magic:not(:disabled):hover { background: var(--accent-soft); }
+ .tb-magic:disabled { opacity: 0.4; cursor: default; }
.tb-sep {
width: 26px;
height: 1px;
@@ -1152,7 +1552,45 @@
display: flex;
justify-content: space-between;
}
+ .side-title.collapsible {
+ width: 100%;
+ background: none;
+ border: none;
+ padding: 0;
+ cursor: pointer;
+ text-align: left;
+ font: inherit;
+ color: inherit;
+ }
+ .side-title.collapsible span {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ }
.count { color: var(--text-3); }
+ .meta-field { margin-bottom: 10px; }
+ .meta-head {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-bottom: 5px;
+ font-size: var(--fs-xs);
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.07em;
+ color: var(--text-2);
+ }
+ .meta-warn { color: var(--warn, #e8a33d); display: inline-flex; }
+ .meta-reset {
+ margin-left: auto;
+ display: inline-flex;
+ color: var(--text-3);
+ padding: 1px;
+ border-radius: var(--r-sm);
+ }
+ .meta-reset:hover { color: var(--text-1); background: var(--bg-2); }
+ .meta-input { width: 100%; font-size: var(--fs-xs); padding: 5px 8px; }
+ .meta-input.warn { border-color: color-mix(in srgb, var(--warn, #e8a33d) 55%, transparent); }
.panel-row {
padding: 8px;
margin-bottom: 8px;
@@ -1160,15 +1598,80 @@
flex-direction: column;
gap: 6px;
}
+ .panel-thumb { position: relative; }
.panel-row img {
width: 100%;
max-height: 90px;
object-fit: cover;
border-radius: var(--r-sm);
background: var(--bg-2);
+ display: block;
+ }
+ .row-badge {
+ position: absolute;
+ top: 5px;
+ left: 5px;
+ padding: 1px 6px;
+ border-radius: 999px;
+ font-size: 10px;
+ font-weight: 700;
+ color: var(--text-1);
+ background: rgba(9, 12, 20, 0.72);
+ }
+ .adv-toggle {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ width: 100%;
+ padding: 6px 2px;
+ font-size: var(--fs-xs);
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.07em;
+ color: var(--text-2);
+ }
+ .adv-toggle:hover { color: var(--text-1); }
+ .adv-body { padding: 4px 2px 2px; }
+ .size-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-bottom: 8px;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .size-row span:first-child { min-width: 78px; }
+ .size-slider { flex: 1; accent-color: var(--accent); }
+ .size-val { min-width: 18px; text-align: right; color: var(--text-2); }
+ .adv-label {
+ display: block;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ margin: 8px 0 4px;
+ }
+ .footer-input {
+ width: 100%;
+ font-size: var(--fs-xs);
+ resize: vertical;
+ font-family: inherit;
}
+ .adv-hint { font-size: 11px; color: var(--text-3); margin-top: 5px; }
.cap-input { font-size: var(--fs-xs); padding: 5px 8px; }
.panel-actions { display: flex; gap: 2px; }
+ .panel-scale {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ }
+ .scale-val {
+ min-width: 42px;
+ text-align: center;
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ color: var(--text-2);
+ font-variant-numeric: tabular-nums;
+ }
.none {
font-size: var(--fs-xs);
color: var(--text-3);
diff --git a/frontend/src/tools/inspect/CollageCanvas.svelte b/frontend/src/tools/inspect/CollageCanvas.svelte
index 3f92545..225a3fb 100644
--- a/frontend/src/tools/inspect/CollageCanvas.svelte
+++ b/frontend/src/tools/inspect/CollageCanvas.svelte
@@ -1,19 +1,20 @@
<script>
- import { quadMatrix3d } from '../../lib/inspect.js';
+ import { quadMatrix3d, quadCentroid, scaleQuad, rotateQuad, quadRadius } from '../../lib/inspect.js';
import Icon from '../../components/Icon.svelte';
// Interactive collage surface. Each node is a tray frame placed as a 4-point
// quad (canvas pixels). Drag the body to move all four corners together; drag a
// 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).
- let { session, selectedId = $bindable() } = $props();
+ // `collage` is the session's *active* collage (a session may hold several).
+ let { collage, selectedId = $bindable() } = $props();
let wrapEl = $state();
let availW = $state(800);
let availH = $state(600);
- const cw = $derived(session.collage.width);
- const ch = $derived(session.collage.height);
+ const cw = $derived(collage.width);
+ const ch = $derived(collage.height);
const scale = $derived(Math.min(availW / cw, availH / ch, 1) || 1);
function boxOf(node) {
@@ -61,25 +62,90 @@
window.addEventListener('pointermove', move);
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) {
+ 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 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)));
+ node.quad = scaleQuad(base, k, c);
+ };
+ const up = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ };
+ window.addEventListener('pointermove', move);
+ 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.
+ function onKey(e) {
+ if (selectedId == null) return;
+ if (e.key !== 'Delete' && e.key !== 'Backspace') return;
+ const t = e.target;
+ if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;
+ if (document.querySelector('.overlay')) return;
+ e.preventDefault();
+ collage.nodes = collage.nodes.filter((n) => n.id !== selectedId);
+ selectedId = null;
+ }
+
+ // Rotate the piece around its centroid by dragging the rotate handle around
+ // the centre — the angle tracks the pointer. Pure quad math (composes w/ warp).
+ function startRotate(e, node) {
+ e.preventDefault();
+ e.stopPropagation();
+ selectedId = node.id;
+ const c = quadCentroid(node.quad);
+ const base = node.quad.map(([x, y]) => [x, y]);
+ const [sx, sy] = toCanvas(e);
+ const startAng = Math.atan2(sy - c[1], sx - c[0]);
+ const move = (ev) => {
+ const [mx, my] = toCanvas(ev);
+ const ang = Math.atan2(my - c[1], mx - c[0]);
+ node.quad = rotateQuad(base, ang - startAng, c);
+ };
+ const up = () => {
+ window.removeEventListener('pointermove', move);
+ window.removeEventListener('pointerup', up);
+ };
+ window.addEventListener('pointermove', move);
+ window.addEventListener('pointerup', up);
+ }
</script>
+<svelte:window onkeydown={onKey} />
+
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="wrap"
+ class:checker={collage.transparent}
bind:this={wrapEl}
bind:clientWidth={availW}
bind:clientHeight={availH}
+ style:background={collage.transparent ? null : collage.background}
onpointerdown={() => (selectedId = null)}
>
<div
class="surface"
- class:checker={session.collage.transparent}
style:width={`${cw}px`}
style:height={`${ch}px`}
style:transform={`scale(${scale})`}
- style:background={session.collage.transparent ? null : session.collage.background}
>
- {#each session.collage.nodes as node (node.id)}
+ {#each collage.nodes as node (node.id)}
{@const box = boxOf(node)}
<img
class="node"
@@ -104,11 +170,45 @@
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. -->
+ <div
+ class="toolbar"
+ style:left={`${(bx0 + bx1) / 2}px`}
+ style:top={`${by0 - 12 / scale}px`}
+ style:gap={`${5 / scale}px`}
+ style:padding={`${4 / scale}px ${5 / scale}px`}
+ >
+ <button
+ class="tbtn rot"
+ style:width={`${28 / scale}px`}
+ style:height={`${28 / scale}px`}
+ onpointerdown={(e) => startRotate(e, node)}
+ aria-label="Rotate piece"
+ title="Drag to rotate"
+ >
+ <Icon name="reset" size={15 / scale} />
+ </button>
+ <button
+ class="tbtn scl"
+ 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"
+ >
+ <Icon name="grip" size={15 / scale} />
+ </button>
+ </div>
{/if}
{/each}
</div>
- {#if session.collage.nodes.length === 0}
+ {#if collage.nodes.length === 0}
<div class="empty">
<Icon name="layers" size={34} />
<p>Add frames from the menu, then drag to move and pull the corners to warp.</p>
@@ -130,11 +230,11 @@
.surface {
position: relative;
transform-origin: 0 0;
- box-shadow: var(--shadow-2);
flex-shrink: 0;
}
- /* transparent canvas: a checkerboard shows what alpha will be exported */
- .surface.checker {
+ /* The working area fills the whole pane (no boxed canvas): a checkerboard
+ across it signals the transparent alpha that will be exported. */
+ .wrap.checker {
background-color: #2a2f3a;
background-image:
linear-gradient(45deg, rgba(255, 255, 255, 0.07) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.07) 75%),
@@ -168,6 +268,37 @@
padding: 0;
touch-action: none;
}
+ .toolbar {
+ position: absolute;
+ transform: translate(-50%, -100%);
+ display: flex;
+ align-items: center;
+ border-radius: 999px;
+ background: rgba(16, 20, 28, 0.92);
+ border: 1px solid var(--accent);
+ box-shadow: var(--shadow-2);
+ touch-action: none;
+ }
+ .tbtn {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 50%;
+ background: transparent;
+ color: var(--accent);
+ border: none;
+ padding: 0;
+ touch-action: none;
+ }
+ .tbtn:hover {
+ background: rgba(255, 255, 255, 0.09);
+ }
+ .tbtn.rot {
+ cursor: grab;
+ }
+ .tbtn.scl {
+ cursor: ns-resize;
+ }
.empty {
position: absolute;
inset: 0;
diff --git a/frontend/src/tools/inspect/CollageMenu.svelte b/frontend/src/tools/inspect/CollageMenu.svelte
index a80e3ea..1926cbd 100644
--- a/frontend/src/tools/inspect/CollageMenu.svelte
+++ b/frontend/src/tools/inspect/CollageMenu.svelte
@@ -1,24 +1,54 @@
<script>
- import { previewStyle } from '../../lib/inspect.js';
+ import { previewStyle, scaleQuad, rotateQuad, quadCentroid, cropImgStyle, styleText, uid } from '../../lib/inspect.js';
import Icon from '../../components/Icon.svelte';
- // Right-panel menu for the Collage tab: add tray frames to the canvas, set the
- // canvas size/background, and act on the selected piece. The layout stays in
- // session.collage until the Save tab commits it to a single flattened image.
- // Each added piece is a frozen snapshot of the frame's current look (addToCollage).
- let { session, filters, selectedId = $bindable(), addToCollage } = $props();
+ // Right-panel menu for the Collage tab: switch/create collages, add tray frames
+ // to the active one, and act on the selected piece. A session holds several
+ // collages (session.collages / session.activeCollageId); each is saved as its
+ // own PNG. Each added piece is a frozen snapshot of the frame (addToCollage).
+ let { session, filters, selectedId = $bindable(), addToCollage, requestCrop } = $props();
- const onCanvas = (id) => session.collage.nodes.some((n) => n.frameId === id);
- const selected = $derived(session.collage.nodes.find((n) => n.id === selectedId) ?? null);
+ const active = $derived(
+ session.collages.find((c) => c.id === session.activeCollageId) ?? session.collages[0]
+ );
+
+ const onCanvas = (id) => active?.nodes.some((n) => n.frameId === id);
+ const selected = $derived(active?.nodes.find((n) => n.id === selectedId) ?? null);
+
+ function switchCollage(id) {
+ session.activeCollageId = id;
+ selectedId = null;
+ }
+
+ function addCollage() {
+ const nums = session.collages.map((c) => parseInt((c.name?.match(/\d+/) ?? [])[0]) || 0);
+ const next = Math.max(0, ...nums) + 1;
+ const c = { id: uid('cl'), name: `Collage ${next}`, width: 1600, height: 800, background: '#12141c', transparent: true, nodes: [] };
+ session.collages.push(c);
+ session.activeCollageId = c.id;
+ selectedId = null;
+ }
+
+ function removeCollage(id) {
+ if (session.collages.length <= 1) return; // always keep at least one
+ session.collages = session.collages.filter((c) => c.id !== id);
+ if (session.activeCollageId === id) session.activeCollageId = session.collages[0].id;
+ selectedId = null;
+ }
function removeNode(id) {
- session.collage.nodes = session.collage.nodes.filter((n) => n.id !== id);
+ active.nodes = active.nodes.filter((n) => n.id !== id);
if (selectedId === id) selectedId = null;
}
function bringFront(id) {
- const i = session.collage.nodes.findIndex((n) => n.id === id);
- if (i !== -1) session.collage.nodes.push(session.collage.nodes.splice(i, 1)[0]);
+ const i = active.nodes.findIndex((n) => n.id === id);
+ if (i !== -1) active.nodes.push(active.nodes.splice(i, 1)[0]);
+ }
+
+ function sendBack(id) {
+ const i = active.nodes.findIndex((n) => n.id === id);
+ if (i > 0) active.nodes.unshift(active.nodes.splice(i, 1)[0]);
}
function resetWarp(node) {
@@ -30,9 +60,38 @@
const y1 = Math.max(...ys);
node.quad = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
}
+
+ // Uniform resize around the centroid — precise counterpart to the on-canvas
+ // scale handle (both just move the quad, so they compose with the warp).
+ function scaleBy(node, k) {
+ node.quad = scaleQuad(node.quad, k, quadCentroid(node.quad));
+ }
+
+ // Rotate around the centroid by a fixed step (degrees) — precise counterpart
+ // to the on-canvas rotate handle.
+ function rotateByDeg(node, deg) {
+ node.quad = rotateQuad(node.quad, (deg * Math.PI) / 180, quadCentroid(node.quad));
+ }
</script>
<div class="module">
+ <div class="section">
+ <div class="section-head"><span>Collages</span></div>
+ <div class="collage-tabs">
+ {#each session.collages as cl (cl.id)}
+ <div class="ctab" class:active={cl.id === session.activeCollageId}>
+ <button class="ctab-name" onclick={() => switchCollage(cl.id)} title="Switch to this collage">
+ {cl.name}{#if cl.nodes.length}<span class="count">{cl.nodes.length}</span>{/if}
+ </button>
+ {#if session.collages.length > 1}
+ <button class="ctab-x" onclick={() => removeCollage(cl.id)} aria-label="Delete collage"><Icon name="x" size={11} /></button>
+ {/if}
+ </div>
+ {/each}
+ <button class="ctab add" onclick={addCollage} title="New collage"><Icon name="plus" size={13} /></button>
+ </div>
+ </div>
+
<p class="hint">Pieces are the frames you captured. Add them, drag to arrange, pull corners to warp into a panorama.</p>
<div class="section">
@@ -41,7 +100,14 @@
{#each session.frames as fr (fr.id)}
{@const look = previewStyle(filters, fr.adjust)}
<button class="tile" class:used={onCanvas(fr.id)} onclick={() => addToCollage(fr)} title={onCanvas(fr.id) ? 'Add again (fresh snapshot)' : 'Add to canvas'}>
- <img src={fr.url} alt="frame" style:filter={look.filter} style:transform={look.transform} />
+ <img
+ class:cropped={fr.crop}
+ src={fr.url}
+ alt="frame"
+ style={styleText(cropImgStyle(fr.crop))}
+ style:filter={look.filter}
+ style:transform={look.transform}
+ />
<span class="add"><Icon name="plus" size={12} /></span>
</button>
{/each}
@@ -49,27 +115,33 @@
{#if session.frames.length === 0}<p class="empty">No frames captured yet.</p>{/if}
</div>
- <div class="section">
- <div class="section-head"><span>Canvas</span></div>
- <div class="controls">
- <label>Width <input type="number" min="16" max="8192" step="20" bind:value={session.collage.width} /></label>
- <label>Height <input type="number" min="16" max="8192" step="20" bind:value={session.collage.height} /></label>
- <label class="bg">Fill <input type="color" bind:value={session.collage.background} disabled={session.collage.transparent} /></label>
- </div>
- <label class="check">
- <input type="checkbox" bind:checked={session.collage.transparent} />
- Transparent canvas <span class="sub">— export only the pieces (PNG alpha)</span>
- </label>
- </div>
+ <p class="hint">Exported as a <strong>transparent PNG</strong> — only the pieces, trimmed to their bounds on save.</p>
{#if selected}
<div class="section">
<div class="section-head"><span>Selected piece</span></div>
+ <div class="scale-row">
+ <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>
+ </div>
+ <div class="scale-row">
+ <span class="lbl">Rotate</span>
+ <button class="btn btn-sm sq" onclick={() => rotateByDeg(selected, -15)} aria-label="Rotate left">↺</button>
+ <button class="btn btn-sm sq" onclick={() => rotateByDeg(selected, 15)} aria-label="Rotate right">↻</button>
+ <span class="sub">or drag the ↻ handle above the piece</span>
+ </div>
<div class="actions">
+ <button class="btn btn-sm" onclick={() => requestCrop?.(selected)}><Icon name="crop" size={13} /> Crop</button>
<button class="btn btn-sm" onclick={() => bringFront(selected.id)}><Icon name="layers" size={13} /> Front</button>
+ <button class="btn btn-sm" onclick={() => sendBack(selected.id)}><Icon name="layers" size={13} /> Back</button>
<button class="btn btn-sm" onclick={() => resetWarp(selected)}><Icon name="reset" size={13} /> Unwarp</button>
- <button class="btn btn-sm danger" onclick={() => removeNode(selected.id)}><Icon name="trash" size={13} /> Remove</button>
+ <button class="btn btn-sm danger" onclick={() => removeNode(selected.id)} title="or press Delete"><Icon name="trash" size={13} /> Remove</button>
</div>
+ {#if selected.crop}
+ <button class="btn btn-ghost btn-xs" onclick={() => requestCrop?.(selected, true)}><Icon name="reset" size={12} /> Clear crop</button>
+ {/if}
</div>
{/if}
@@ -95,7 +167,7 @@
flex-direction: column;
gap: 8px;
}
- .section + .section {
+ .hint + .section {
border-top: 1px solid var(--border);
padding-top: 12px;
}
@@ -103,6 +175,60 @@
font-weight: 600;
font-size: var(--fs-sm);
}
+ .collage-tabs {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ }
+ .ctab {
+ display: flex;
+ align-items: center;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ overflow: hidden;
+ background: var(--bg-1);
+ }
+ .ctab.active {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ }
+ .ctab-name {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ padding: 4px 8px;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ background: transparent;
+ border: none;
+ }
+ .ctab.active .ctab-name {
+ color: var(--accent);
+ }
+ .ctab-name .count {
+ font-size: 9px;
+ padding: 0 4px;
+ border-radius: 8px;
+ background: var(--bg-2);
+ color: var(--text-3);
+ }
+ .ctab-x {
+ display: flex;
+ align-items: center;
+ padding: 4px 5px;
+ color: var(--text-3);
+ background: transparent;
+ border: none;
+ border-left: 1px solid var(--border);
+ }
+ .ctab-x:hover {
+ color: var(--danger, #d86a6a);
+ }
+ .ctab.add {
+ padding: 4px 8px;
+ color: var(--text-2);
+ cursor: pointer;
+ }
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
@@ -137,48 +263,25 @@
display: flex;
padding: 1px;
}
- .controls {
- display: flex;
- gap: 8px;
- }
- .controls label {
- display: flex;
- flex-direction: column;
- gap: 3px;
- font-size: var(--fs-xs);
- color: var(--text-3);
- flex: 1;
- }
- .controls input[type='number'] {
- width: 100%;
- background: var(--bg-2);
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- padding: 4px 6px;
- color: var(--text-1);
- font-size: var(--fs-sm);
- }
- .controls .bg input {
- height: 28px;
- padding: 0;
- background: none;
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- }
- .controls .bg input:disabled {
- opacity: 0.4;
- }
- .check {
+ .scale-row {
display: flex;
align-items: center;
gap: 6px;
- font-size: var(--fs-xs);
+ }
+ .scale-row .lbl {
+ font-size: var(--fs-sm);
color: var(--text-2);
- cursor: pointer;
}
- .check .sub {
+ .scale-row .sub {
+ font-size: var(--fs-xs);
color: var(--text-3);
}
+ .btn.sq {
+ min-width: 30px;
+ justify-content: center;
+ font-size: var(--fs-md);
+ line-height: 1;
+ }
.actions {
display: flex;
gap: 6px;
diff --git a/frontend/src/tools/inspect/CollagePreview.svelte b/frontend/src/tools/inspect/CollagePreview.svelte
index 97e8445..6b6a3e1 100644
--- a/frontend/src/tools/inspect/CollagePreview.svelte
+++ b/frontend/src/tools/inspect/CollagePreview.svelte
@@ -1,17 +1,17 @@
<script>
- import { quadMatrix3d } from '../../lib/inspect.js';
+ import { quadMatrix3d, collageBounds } from '../../lib/inspect.js';
// Read-only miniature of a collage layout — the same node quads/urls the Save
- // tab will composite, scaled to fit its container. Used for the Save gallery
- // thumbnail so a collage no longer shows an empty placeholder.
+ // tab will composite. Framed to the pieces' trimmed bounds (not the full
+ // canvas), so the thumbnail matches the exported PNG instead of showing the
+ // empty working area around the pieces.
let { collage } = $props();
let availW = $state(150);
let availH = $state(112);
- const cw = $derived(collage.width || 1);
- const ch = $derived(collage.height || 1);
- const scale = $derived(Math.min(availW / cw, availH / ch) || 0);
+ const bounds = $derived(collageBounds(collage.nodes));
+ const scale = $derived(Math.min(availW / bounds.width, availH / bounds.height) || 0);
const boxOf = (n) => ({ w: n.w || 320, h: n.h || 240, url: n.url });
</script>
@@ -19,23 +19,25 @@
<div
class="surface"
class:checker={collage.transparent}
- style:width={`${cw}px`}
- style:height={`${ch}px`}
+ style:width={`${bounds.width}px`}
+ style:height={`${bounds.height}px`}
style:transform={`scale(${scale})`}
style:background={collage.transparent ? null : collage.background}
>
- {#each collage.nodes as node (node.id)}
- {@const box = boxOf(node)}
- <img
- class="node"
- src={box.url}
- alt="collage piece"
- style:width={`${box.w}px`}
- style:height={`${box.h}px`}
- style:transform={quadMatrix3d(box.w, box.h, node.quad)}
- draggable="false"
- />
- {/each}
+ <div class="layer" style:transform={`translate(${-bounds.minX}px, ${-bounds.minY}px)`}>
+ {#each collage.nodes as node (node.id)}
+ {@const box = boxOf(node)}
+ <img
+ class="node"
+ src={box.url}
+ alt="collage piece"
+ style:width={`${box.w}px`}
+ style:height={`${box.h}px`}
+ style:transform={quadMatrix3d(box.w, box.h, node.quad)}
+ draggable="false"
+ />
+ {/each}
+ </div>
</div>
</div>
@@ -61,6 +63,12 @@
background-size: 16px 16px;
background-position: 0 0, 8px 8px;
}
+ .layer {
+ position: absolute;
+ top: 0;
+ left: 0;
+ transform-origin: 0 0;
+ }
.node {
position: absolute;
top: 0;
diff --git a/frontend/src/tools/inspect/FrameMenu.svelte b/frontend/src/tools/inspect/FrameMenu.svelte
index be363ed..ff119df 100644
--- a/frontend/src/tools/inspect/FrameMenu.svelte
+++ b/frontend/src/tools/inspect/FrameMenu.svelte
@@ -1,7 +1,7 @@
<script>
import { api } from '../../lib/api.js';
import { caseState, toast } from '../../lib/state.svelte.js';
- import { adjustDefaults, buildOps, previewStyle } from '../../lib/inspect.js';
+ import { adjustDefaults, buildOps, previewStyle, cropImgStyle, styleText } from '../../lib/inspect.js';
import Icon from '../../components/Icon.svelte';
import AdjustSliders from './AdjustSliders.svelte';
@@ -80,7 +80,13 @@
{#each session.frames as fr, i (fr.id)}
<div class="thumb" class:active={fr.id === session.activeFrameId}>
<button class="pick" onclick={() => setActive(fr.id)} title={fr.time != null ? `Image ${i + 1} · t=${fr.time.toFixed(2)}s` : `Image ${i + 1}`}>
- <img src={fr.url} alt={`Image ${i + 1}`} style:filter={previewStyle(filters, fr.adjust).filter} />
+ <img
+ class:cropped={fr.crop}
+ src={fr.url}
+ alt={`Image ${i + 1}`}
+ style={styleText(cropImgStyle(fr.crop))}
+ style:filter={previewStyle(filters, fr.adjust).filter}
+ />
<span class="num">{i + 1}</span>
{#if session.saved[`frame:${fr.id}`]}<span class="saved" title="Saved"><Icon name="check" size={11} /></span>{/if}
</button>
@@ -158,6 +164,7 @@
height: 60px;
}
.thumb .pick {
+ position: relative;
width: 100%;
height: 100%;
border-radius: var(--r-sm);
diff --git a/frontend/src/tools/inspect/PieceCropModal.svelte b/frontend/src/tools/inspect/PieceCropModal.svelte
new file mode 100644
index 0000000..d40774f
--- /dev/null
+++ b/frontend/src/tools/inspect/PieceCropModal.svelte
@@ -0,0 +1,130 @@
+<script>
+ import Modal from '../../components/Modal.svelte';
+ import Icon from '../../components/Icon.svelte';
+
+ // Crop editor for a collage piece. Draws a fractional (0..1) box 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).
+ 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);
+
+ 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 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 apply() {
+ const c = box && box.w > 0.02 && box.h > 0.02
+ ? { x: box.x, y: box.y, w: box.w, h: box.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}>
+ <img
+ bind:this={imgEl}
+ src={node.baseUrl || node.url}
+ alt="piece"
+ draggable="false"
+ 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}
+ </div>
+ <div class="foot">
+ <button class="btn btn-sm" onclick={() => (draw = null)} disabled={!box}><Icon name="reset" size={13} /> Full frame</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>
+ </div>
+</Modal>
+
+<style>
+ .hint {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ margin: 0 0 10px;
+ }
+ .stage {
+ position: relative;
+ line-height: 0;
+ touch-action: none;
+ cursor: crosshair;
+ display: block;
+ width: fit-content;
+ max-width: 100%;
+ margin: 0 auto;
+ background: var(--bg-0);
+ border-radius: var(--r-sm);
+ overflow: hidden;
+ }
+ .stage img {
+ max-width: 100%;
+ max-height: 60vh;
+ 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;
+ }
+ .foot {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 12px;
+ }
+ .spacer {
+ flex: 1;
+ }
+ .primary {
+ color: var(--accent);
+ border-color: var(--accent);
+ }
+</style>
diff --git a/frontend/src/tools/inspect/SaveGallery.svelte b/frontend/src/tools/inspect/SaveGallery.svelte
index 5d9a32b..09e49c9 100644
--- a/frontend/src/tools/inspect/SaveGallery.svelte
+++ b/frontend/src/tools/inspect/SaveGallery.svelte
@@ -23,7 +23,12 @@
<button class="card" class:sel={saveUi.selected[it.key]} class:saved={it.saved} onclick={() => toggle(it.key)}>
<div class="thumb">
{#if it.kind === 'collage' && it.collage?.nodes.length}
- <CollagePreview collage={it.collage} />
+ {#if it.preview}
+ <!-- the actual composited PNG (backend warp), on a checker so alpha reads -->
+ <div class="collage-real checker"><img src={it.preview} alt={it.label} /></div>
+ {:else}
+ <CollagePreview collage={it.collage} />
+ {/if}
{:else if it.thumb}
<img src={it.thumb} alt={it.label} style:filter={it.filter} />
{:else}
@@ -95,6 +100,26 @@
height: 100%;
object-fit: cover;
}
+ .collage-real {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .collage-real img {
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ }
+ .checker {
+ background-color: #2a2f3a;
+ background-image:
+ linear-gradient(45deg, rgba(255, 255, 255, 0.07) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.07) 75%),
+ linear-gradient(45deg, rgba(255, 255, 255, 0.07) 25%, transparent 25%, transparent 75%, rgba(255, 255, 255, 0.07) 75%);
+ background-size: 16px 16px;
+ background-position: 0 0, 8px 8px;
+ }
.kind {
position: absolute;
top: 4px;
diff --git a/src/ozimut/api/cases.py b/src/ozimut/api/cases.py
index 4fae95d..7517f78 100644
--- a/src/ozimut/api/cases.py
+++ b/src/ozimut/api/cases.py
@@ -187,6 +187,8 @@ def remove_entity(case_id: str, entity_id: str) -> dict[str, str]:
_unlink_inside(case, attrs["spec"].removesuffix(".json") + ".png")
elif etype == "post" and attrs.get("draft"):
_unlink_inside(case, attrs["draft"])
+ elif etype == "inspect-session" and attrs.get("spec"):
+ _unlink_inside(case, attrs["spec"])
try:
case.remove_entity(entity_id)
diff --git a/src/ozimut/api/inspect.py b/src/ozimut/api/inspect.py
index ccb407d..afbe654 100644
--- a/src/ozimut/api/inspect.py
+++ b/src/ozimut/api/inspect.py
@@ -273,6 +273,27 @@ def compose(case_id: str, body: ComposeIn) -> dict[str, Any]:
raise HTTPException(status_code=422, detail=str(exc)) from exc
[email protected]("/cases/{case_id}/inspect/compose-preview")
+def compose_preview(case_id: str, body: ComposeIn) -> Response:
+ """Render the composited collage to a PNG for the Save tab — nothing is filed."""
+ case = get_case(case_id)
+ nodes = [
+ {"src": {**n.src.model_dump(exclude={"ops"}),
+ "ops": [op.model_dump() for op in n.src.ops]},
+ "quad": [list(pt) for pt in n.quad]}
+ for n in body.nodes
+ ]
+ try:
+ png = inspect_engine.compose_preview_png(
+ case, width=body.width, height=body.height, nodes=nodes, background=body.background,
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except (ValueError, RuntimeError, OSError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ return Response(content=png, media_type="image/png")
+
+
@router.post("/cases/{case_id}/inspect/enhance-video")
def enhance_video(case_id: str, body: EnhanceVideoIn) -> dict[str, Any]:
"""Re-encode a video with the gear's adjustments and file it as new media."""
diff --git a/src/ozimut/engine/inspect.py b/src/ozimut/engine/inspect.py
index b7dc139..7aa3e1d 100644
--- a/src/ozimut/engine/inspect.py
+++ b/src/ozimut/engine/inspect.py
@@ -574,27 +574,24 @@ def _perspective_coeffs(dst_quad: list[list[float]], src_quad: list[list[float]]
return _solve_linear(matrix, rhs)
-def compose_perspective(
+def _compose_canvas(
case: Case,
*,
width: int,
height: int,
nodes: list[dict[str, Any]],
- background: str | None = "#12141c",
- label: str | None = None,
- folder: str | None = None,
-) -> dict[str, Any]:
- """Composite tray/case images, each warped into a 4-point quad, onto a canvas.
+ background: str | None,
+ scale: float = 1.0,
+) -> tuple[Image.Image, list[str]]:
+ """Warp each node's source into its quad and paint onto one canvas.
- ``nodes`` are painted in order (later = on top); each is
- ``{"src": {path, time?, ops[]}, "quad": [[x,y]×4]}`` with the quad in canvas
- pixels (top-left, top-right, bottom-right, bottom-left). A falsy ``background``
- yields a transparent (RGBA) canvas so the saved PNG carries only the pieces.
+ Shared by the filed export and the (unsaved) Save-tab preview. ``scale``
+ shrinks the whole layout (canvas + quads) for a cheaper preview render.
"""
if not nodes:
raise ValueError("collage needs at least one image")
- width = max(16, min(int(width), 8192))
- height = max(16, min(int(height), 8192))
+ width = max(16, min(int(round(width * scale)), 8192))
+ height = max(16, min(int(round(height * scale)), 8192))
canvas = (
Image.new("RGB", (width, height), background)
if background
@@ -610,7 +607,7 @@ def compose_perspective(
img = _source_image(case, rel, spec.get("time"), spec.get("ops")).convert("RGB")
w, h = img.size
src_corners = [[0, 0], [w, 0], [w, h], [0, h]]
- quad = [[float(x), float(y)] for x, y in node["quad"]]
+ quad = [[float(x) * scale, float(y) * scale] for x, y in node["quad"]]
coeffs = _perspective_coeffs(quad, src_corners)
warped = img.transform((width, height), Image.PERSPECTIVE, coeffs, Image.BICUBIC)
mask = Image.new("L", (w, h), 255).transform(
@@ -618,7 +615,52 @@ def compose_perspective(
)
canvas.paste(warped, (0, 0), mask)
sources.append(rel)
+ return canvas, sources
+
+
+def compose_preview_png(
+ case: Case,
+ *,
+ width: int,
+ height: int,
+ nodes: list[dict[str, Any]],
+ background: str | None = None,
+ max_dim: int = 640,
+) -> bytes:
+ """Render the exact composited collage to PNG bytes — nothing is filed.
+
+ Same warp as :func:`compose_perspective`, downscaled to ``max_dim`` so the
+ Save tab can show a true-to-export thumbnail cheaply.
+ """
+ scale = min(1.0, max_dim / max(1, max(int(width), int(height))))
+ canvas, _ = _compose_canvas(
+ case, width=width, height=height, nodes=nodes, background=background, scale=scale
+ )
+ buf = io.BytesIO()
+ canvas.save(buf, "PNG")
+ return buf.getvalue()
+
+def compose_perspective(
+ case: Case,
+ *,
+ width: int,
+ height: int,
+ nodes: list[dict[str, Any]],
+ background: str | None = "#12141c",
+ label: str | None = None,
+ folder: str | None = None,
+) -> dict[str, Any]:
+ """Composite tray/case images, each warped into a 4-point quad, onto a canvas.
+
+ ``nodes`` are painted in order (later = on top); each is
+ ``{"src": {path, time?, ops[]}, "quad": [[x,y]×4]}`` with the quad in canvas
+ pixels (top-left, top-right, bottom-right, bottom-left). A falsy ``background``
+ yields a transparent (RGBA) canvas so the saved PNG carries only the pieces.
+ """
+ canvas, sources = _compose_canvas(
+ case, width=width, height=height, nodes=nodes, background=background
+ )
source = _derivation("", None, op="collage", sources=sources, perspective=True)
name = f"collage_{_stamp()}.png"
result = media_engine.import_image(case, canvas, name, source, by="inspect")
diff --git a/src/ozimut/engine/media.py b/src/ozimut/engine/media.py
index 7165cb7..f22fb59 100644
--- a/src/ozimut/engine/media.py
+++ b/src/ozimut/engine/media.py
@@ -230,6 +230,7 @@ def download_url(case: Case, url: str, progress_hook=None) -> dict[str, Any]:
"url": url,
"downloader": f"yt-dlp",
"title": info.get("title"),
+ "description": info.get("description"),
"uploader": info.get("uploader") or info.get("channel"),
"upload_date": info.get("upload_date"),
"webpage_url": info.get("webpage_url", url),
diff --git a/tests/test_inspect_api.py b/tests/test_inspect_api.py
index 9051be3..2106b13 100644
--- a/tests/test_inspect_api.py
+++ b/tests/test_inspect_api.py
@@ -245,6 +245,39 @@ def test_compose_transparent_background_keeps_alpha(client):
assert img.getpixel((60, 60))[3] == 255
+def test_compose_node_crop_is_applied_before_warp(client):
+ cid = client.post("/api/cases", json={"name": "CropWarp"}).json()["id"]
+ # left half white, right half black — crop keeps the white half only
+ two_tone = Image.new("RGB", (80, 60), (0, 0, 0))
+ two_tone.paste((255, 255, 255), (0, 0, 40, 60))
+ buf = io.BytesIO()
+ two_tone.save(buf, "PNG")
+ a = _upload(client, cid, "two.png", buf.getvalue())
+
+ res = client.post(
+ f"/api/cases/{cid}/inspect/compose",
+ json={
+ "width": 100, "height": 100, "background": None,
+ "nodes": [
+ {
+ "src": {"path": a["path"], "ops": [
+ {"op": "crop", "params": {"x": 0.0, "y": 0.0, "w": 0.5, "h": 1.0}},
+ ]},
+ "quad": [[0, 0], [100, 0], [100, 100], [0, 100]],
+ },
+ ],
+ },
+ ).json()
+ assert res["duplicate"] is False
+
+ png = client.get(f"/files/{cid}/{res['item']['path']}").content
+ img = Image.open(io.BytesIO(png))
+ # the whole canvas is filled by the (cropped) white half, so the interior is white
+ r, g, b, alpha = img.getpixel((50, 50))
+ assert alpha == 255
+ assert r > 200 and g > 200 and b > 200
+
+
def test_compose_requires_nodes(client):
cid = client.post("/api/cases", json={"name": "NoNodes"}).json()["id"]
res = client.post(
@@ -253,6 +286,32 @@ def test_compose_requires_nodes(client):
assert res.status_code == 422
+def test_compose_preview_returns_png_without_filing(client):
+ cid = client.post("/api/cases", json={"name": "Preview"}).json()["id"]
+ a = _upload(client, cid, "a.png", _png_bytes(color=(10, 20, 30), size=(80, 60)))
+ before = len(client.get(f"/api/cases/{cid}/media").json())
+
+ res = client.post(
+ f"/api/cases/{cid}/inspect/compose-preview",
+ json={
+ "width": 400, "height": 300, "background": None,
+ "nodes": [
+ {"src": {"path": a["path"]},
+ "quad": [[20, 20], [120, 20], [120, 100], [20, 100]]},
+ ],
+ },
+ )
+ assert res.status_code == 200
+ assert res.headers["content-type"] == "image/png"
+ img = Image.open(io.BytesIO(res.content))
+ # downscaled to max_dim=640 (so <= the 400x300 request) and transparent alpha
+ assert img.mode == "RGBA"
+ assert max(img.size) <= 640
+ assert img.getpixel((0, 0))[3] == 0
+ # nothing was filed to the case
+ assert len(client.get(f"/api/cases/{cid}/media").json()) == before
+
+
def test_analyze_accepts_transient_ops_without_filing(client):
cid = client.post("/api/cases", json={"name": "AnalyzeOps"}).json()["id"]
item = _upload(client, cid, "img.png", _png_bytes(color=(255, 0, 0), size=(20, 20)))
@@ -384,6 +443,25 @@ def test_session_save_list_load_delete_roundtrip(client):
assert not any(e["type"] == "inspect-session" for e in entities)
+def test_session_delete_via_sidebar_entity_removes_spec(client):
+ # Deleting the inspect-session row from the sidebar (the generic entity
+ # delete) must also drop the spec file, or the session keeps showing up in
+ # the Inspect "Open" dialog and can be reloaded.
+ cid = client.post("/api/cases", json={"name": "Sidebar delete"}).json()["id"]
+ item = _upload(client, cid, "clip.png")
+ spec = {"source": {"path": item["path"], "kind": "image"}, "frames": [], "collage": {"nodes": []}}
+ client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "Doomed", "spec": spec})
+
+ entities = client.get(f"/api/cases/{cid}").json()["entities"]
+ ent = next(e for e in entities if e["type"] == "inspect-session")
+
+ client.delete(f"/api/cases/{cid}/entities/{ent['id']}")
+
+ # gone from the Open list (spec file unlinked) and not reloadable
+ assert client.get(f"/api/cases/{cid}/inspect/sessions").json() == []
+ assert client.get(f"/api/cases/{cid}/inspect/sessions/doomed").status_code == 404
+
+
def test_session_resave_by_name_overwrites_after_rename(client):
# Reopening a session then saving it re-uses its slug (name), so a title
# change updates the same session in place instead of forking a new one.
diff --git a/tests/test_media_api.py b/tests/test_media_api.py
index 39d623b..63f28b9 100644
--- a/tests/test_media_api.py
+++ b/tests/test_media_api.py
@@ -149,6 +149,59 @@ def test_update_media_bad_path(client):
assert res.status_code == 400
+def test_download_captures_description(client, monkeypatch):
+ """yt-dlp's info dict already carries the video description — it must land
+ in the media item's source sidecar so we can show it on the source panel."""
+ import sys
+ import types
+
+ from ozimut.engine import media as media_engine
+ from ozimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "Desc"}).json()["id"]
+ case = Case.open(cid)
+
+ info = {
+ "id": "abc123",
+ "title": "A clip",
+ "description": "Line one\nLine two with a link https://example.com",
+ "uploader": "Some Channel",
+ "upload_date": "20260701",
+ "webpage_url": "https://example.com/watch?v=abc123",
+ "extractor": "generic",
+ "duration": 12,
+ }
+
+ class FakeYDL:
+ def __init__(self, opts):
+ self._tmpl = opts["outtmpl"]
+
+ 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._tmpl), f"{info['title']} [{info['id']}].png")
+ with open(path, "wb") as fh:
+ fh.write(_png_bytes())
+ return path
+
+ def extract_info(self, url, download=True):
+ return info
+
+ fake = types.ModuleType("yt_dlp")
+ fake.YoutubeDL = FakeYDL
+ monkeypatch.setitem(sys.modules, "yt_dlp", fake)
+
+ result = media_engine.download_url(case, "https://example.com/watch?v=abc123")
+ assert result["item"]["source"]["description"] == info["description"]
+ assert result["item"]["source"]["title"] == "A clip"
+
+
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_proofs_api.py b/tests/test_proofs_api.py
index 3bf08df..0cf05bb 100644
--- a/tests/test_proofs_api.py
+++ b/tests/test_proofs_api.py
@@ -13,9 +13,13 @@ def _png_b64() -> str:
SPEC = {
+ "captionSize": 24,
+ "legendSize": 22,
+ "footerSize": 18,
+ "footer": "Custom footer line",
"panels": [
- {"id": "p1", "src": "media/frame.png", "caption": "Frame", "natural": [1280, 720], "meta": {}},
- {"id": "p2", "src": "satellite/sat.png", "caption": "Esri", "natural": [1000, 700],
+ {"id": "p1", "src": "media/frame.png", "caption": "Frame", "row": 0, "natural": [1280, 720], "meta": {}},
+ {"id": "p2", "src": "satellite/sat.png", "caption": "Esri", "row": 1, "natural": [1000, 700],
"meta": {"kind": "satellite", "attribution": "Esri", "lat": 1.0, "lon": 2.0}},
],
"shapes": [
@@ -46,6 +50,12 @@ def test_save_load_roundtrip(client):
assert spec["shapes"][0]["comment"] == "blue roof"
assert spec["notes"] == {"#ff5252": "blue roof matches"} # legend text is per color
assert spec["panels"][0]["id"] == "p1" # panel ids survive → shapes stay bound
+ # multi-row layout + text sizes + custom footer survive the round-trip
+ assert [p["row"] for p in spec["panels"]] == [0, 1]
+ assert spec["captionSize"] == 24
+ assert spec["legendSize"] == 22
+ assert spec["footerSize"] == 18
+ assert spec["footer"] == "Custom footer line"
# PNG served
assert client.get(f"/files/{cid}/{saved['png']}").status_code == 200