The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
M3: Proof Composer — Konva annotation canvas, legend, re-editable specs
OsintMeThatd044de765304
diff --git a/frontend/src/lib/composer.js b/frontend/src/lib/composer.jsnew file mode 100644index 0000000..c769051--- /dev/null+++ b/frontend/src/lib/composer.js@@ -0,0 +1,107 @@+/**+ * 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).+ */++export const PANEL_H = 720;+export const PAD = 20;+export const GAP = 16;+export const CAPTION_H = 34;+export const LEGEND_LINE_H = 30;+export const FOOTER_H = 26;++export const ANNO_COLORS = ['#ff5252', '#40c4ff', '#ffd740', '#69f0ae', '#e040fb', '#ff9e40'];++export const BG = '#0d1117';+export const TEXT_MAIN = '#e8edf6';+export const TEXT_DIM = '#94a3b8';+export const TEXT_FAINT = '#64748b';++let idSeq = 0;+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;+ return panels.map((p) => {+ const scale = PANEL_H / p.natural[1];+ const w = p.natural[0] * scale;+ const box = { x, y: PAD, w, h: PANEL_H, scale };+ x += w + GAP;+ return box;+ });+}++/** Distinct colors in order of first use → feature numbering (same color = same feature). */+export function featureColors(shapes) {+ const seen = [];+ for (const s of shapes) {+ if (!seen.includes(s.color)) seen.push(s.color);+ }+ return seen;+}++/** Legend lines: one per used color, comments joined. */+export function legendLines(shapes) {+ const colors = featureColors(shapes);+ return colors.map((color, i) => {+ const comments = shapes+ .filter((s) => s.color === color && s.comment?.trim())+ .map((s) => s.comment.trim());+ return { color, n: i + 1, text: [...new Set(comments)].join(' · ') };+ });+}++/** Unique attribution strings from panel metadata. */+export function attributionLine(panels) {+ const parts = new Set();+ for (const p of panels) {+ if (p.meta?.attribution) parts.add(`Imagery: ${p.meta.attribution}`);+ else if (p.meta?.source_url) parts.add(`Source: ${p.meta.source_url}`);+ }+ parts.add('Composed with Ozimut');+ return [...parts].join(' · ');+}++/** Full document size given panels + shapes (legend grows with features). */+export function docSize(panels, shapes) {+ const boxes = layoutPanels(panels);+ const width = boxes.length+ ? boxes[boxes.length - 1].x + boxes[boxes.length - 1].w + PAD+ : 640;+ const legend = legendLines(shapes).filter((l) => l.text);+ 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 };+}++/** Serializable spec from runtime state (drops live image objects). */+export function toSpec(proof) {+ return {+ ozimut_proof: 1,+ title: proof.title,+ coords: proof.coords ?? null,+ panels: proof.panels.map((p) => ({+ id: p.id, // kept so shapes stay bound to their panel on reload+ src: p.src,+ caption: p.caption ?? '',+ natural: p.natural,+ meta: p.meta ?? {},+ })),+ shapes: proof.shapes.map((s) => ({ ...s })),+ };+}++export function loadImage(url) {+ return new Promise((resolve, reject) => {+ const img = new Image();+ img.onload = () => resolve(img);+ img.onerror = () => reject(new Error(`could not load ${url}`));+ img.src = url;+ });+}diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelteindex f261e7f..7bc16e7 100644--- a/frontend/src/tools/ProofComposer.svelte+++ b/frontend/src/tools/ProofComposer.svelte@@ -1,13 +1,980 @@<script>+ import { onMount } from 'svelte';+ import Konva from 'konva';+ import { api } from '../lib/api.js';+ import { caseState, uiState, ensureCase, reloadCase, toast } from '../lib/state.svelte.js';import Icon from '../components/Icon.svelte';+ import Modal from '../components/Modal.svelte';+ import {+ ANNO_COLORS, PAD, CAPTION_H, LEGEND_LINE_H, FOOTER_H,+ BG, TEXT_MAIN, TEXT_DIM, TEXT_FAINT,+ layoutPanels, attributionLine, docSize, toSpec, newId, loadImage,+ } from '../lib/composer.js';++ const DRAW_TOOLS = [+ { id: 'select', icon: 'hand', label: 'Select / move' },+ { id: 'rect', icon: 'square', label: 'Box' },+ { id: 'ellipse', icon: 'circle', label: 'Ellipse' },+ { id: 'arrow', icon: 'arrow', label: 'Arrow' },+ { id: 'line', icon: 'line', label: 'Line' },+ ];++ // ---- document state -------------------------------------------------------+ const proof = $state({ title: 'Untitled proof', panels: [], shapes: [], coords: null });+ let savedName = $state(null);+ let dirty = $state(false);+ let tool = $state('select');+ let color = $state(ANNO_COLORS[0]);+ let strokeW = $state(4);+ let selectedId = $state(null);+ let picker = $state(false);+ let pickerItems = $state([]);+ let openList = $state(null); // list of saved proofs, null = closed+ let saving = $state(false);+ let proofFor = $state(undefined);++ // ---- konva ------------------------------------------------------------------+ let containerEl;+ let stage, docLayer, uiLayer, transformer;+ let drawing = null; // {panel, node, start, box, kind}++ onMount(() => {+ stage = new Konva.Stage({ container: containerEl, width: 100, height: 100 });+ docLayer = new Konva.Layer();+ uiLayer = new Konva.Layer();+ stage.add(docLayer, uiLayer);+ transformer = new Konva.Transformer({+ rotateEnabled: false,+ flipEnabled: false,+ anchorSize: 9,+ anchorCornerRadius: 3,+ anchorStroke: '#e8a33d',+ anchorFill: '#161e2e',+ borderStroke: '#e8a33d',+ borderDash: [4, 3],+ ignoreStroke: true,+ });+ uiLayer.add(transformer);++ const resize = new ResizeObserver(() => {+ stage.width(containerEl.clientWidth);+ stage.height(containerEl.clientHeight);+ fit();+ });+ resize.observe(containerEl);++ stage.on('wheel', onWheel);+ stage.on('pointerdown', onPointerDown);+ stage.on('pointermove', onPointerMove);+ stage.on('pointerup', onPointerUp);++ return () => {+ resize.disconnect();+ stage.destroy();+ };+ });++ // reset the document when the case changes+ $effect(() => {+ const id = caseState.current?.id;+ if (id !== proofFor) {+ proofFor = id;+ resetDoc();+ }+ });++ // consume the cross-tool queue (media/satellite “send to composer”)+ $effect(() => {+ if (uiState.tool === 'proof' && uiState.composeQueue.length && caseState.current) {+ const queue = [...uiState.composeQueue];+ uiState.composeQueue.length = 0;+ addPanelsFromPaths(queue);+ }+ });++ // rebuild canvas whenever the document changes+ $effect(() => {+ JSON.stringify([+ proof.panels.map((p) => [p.src, p.caption]),+ proof.shapes,+ selectedId,+ ]);+ if (stage) rebuild();+ });++ function resetDoc() {+ proof.title = 'Untitled proof';+ proof.panels = [];+ proof.shapes = [];+ proof.coords = null;+ savedName = null;+ selectedId = null;+ dirty = false;+ }++ // ---- panels ------------------------------------------------------------------++ function satPanelInput(s) {+ return {+ src: s.path,+ meta: {+ kind: 'satellite', attribution: s.attribution, lat: s.lat, lon: s.lon,+ zoom: s.zoom, provider: s.provider_label, date: s.fetched_at?.slice(0, 10),+ },+ caption: `${s.provider_label} · ${s.lat.toFixed(5)}, ${s.lon.toFixed(5)} · ${s.fetched_at?.slice(0, 10) ?? ''}`,+ };+ }++ function mediaPanelInput(m) {+ return {+ src: m.path,+ meta: { kind: 'media', source_url: m.source?.webpage_url ?? m.source?.url },+ caption: m.source?.title ?? m.filename,+ };+ }++ async function openPicker() {+ if (!caseState.current) {+ toast('Add media first — the composer works on case images', 'info');+ uiState.tool = 'media';+ return;+ }+ const [media, sats] = await Promise.all([+ api.get(`/api/cases/${caseState.current.id}/media`),+ api.get(`/api/cases/${caseState.current.id}/satellite`),+ ]);+ pickerItems = [+ ...sats.map((s) => ({+ ...satPanelInput(s),+ label: `${s.lat.toFixed(4)}, ${s.lon.toFixed(4)} · z${s.zoom}`,+ thumb: s.path,+ kind: 'satellite',+ })),+ ...media+ .filter((m) => m.kind === 'image')+ .map((m) => ({+ ...mediaPanelInput(m),+ label: m.filename,+ thumb: m.thumbnail ?? m.path,+ kind: 'media',+ })),+ ];+ picker = true;+ }++ async function addPanel(item) {+ try {+ const img = await loadImage(`/files/${caseState.current.id}/${item.src}`);+ proof.panels.push({+ id: newId('p'),+ src: item.src,+ caption: item.caption ?? '',+ 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) {+ toast(e.message, 'danger');+ }+ }++ async function addPanelsFromPaths(paths) {+ const [media, sats] = await Promise.all([+ api.get(`/api/cases/${caseState.current.id}/media`),+ api.get(`/api/cases/${caseState.current.id}/satellite`),+ ]);+ for (const path of paths) {+ if (proof.panels.some((p) => p.src === path)) continue;+ const sat = sats.find((s) => s.path === path);+ if (sat) {+ await addPanel(satPanelInput(sat));+ continue;+ }+ const m = media.find((x) => x.path === path);+ if (m) await addPanel(mediaPanelInput(m));+ }+ }++ function movePanel(index, delta) {+ const target = index + delta;+ if (target < 0 || target >= proof.panels.length) return;+ const [panel] = proof.panels.splice(index, 1);+ proof.panels.splice(target, 0, panel);+ dirty = true;+ }++ function removePanel(index) {+ const panel = proof.panels[index];+ proof.shapes = proof.shapes.filter((s) => s.panel !== panel.id);+ proof.panels.splice(index, 1);+ selectedId = null;+ dirty = true;+ requestAnimationFrame(fit);+ }++ // ---- view (zoom / pan / fit) ----------------------------------------------------++ function fit() {+ if (!stage || !containerEl || !containerEl.clientWidth) return;+ const { width, height } = docSize(proof.panels, proof.shapes);+ const k = Math.min(+ (containerEl.clientWidth - 24) / width,+ (containerEl.clientHeight - 24) / height,+ 1.2+ );+ stage.scale({ x: k, y: k });+ stage.position({+ x: (containerEl.clientWidth - width * k) / 2,+ y: (containerEl.clientHeight - height * k) / 2,+ });+ stage.batchDraw();+ }++ function onWheel(e) {+ e.evt.preventDefault();+ const old = stage.scaleX();+ const pointer = stage.getPointerPosition();+ const factor = e.evt.deltaY > 0 ? 0.9 : 1.1;+ const k = Math.min(Math.max(old * factor, 0.08), 4);+ stage.scale({ x: k, y: k });+ stage.position({+ x: pointer.x - ((pointer.x - stage.x()) / old) * k,+ y: pointer.y - ((pointer.y - stage.y()) / old) * k,+ });+ stage.batchDraw();+ }++ // ---- drawing ----------------------------------------------------------------------++ function docPoint() {+ const p = stage.getPointerPosition();+ return { x: (p.x - stage.x()) / stage.scaleX(), y: (p.y - stage.y()) / stage.scaleY() };+ }++ function panelAt(doc) {+ const boxes = layoutPanels(proof.panels);+ 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) {+ return { index: i, box: b, nx: (doc.x - b.x) / b.scale, ny: (doc.y - b.y) / b.scale };+ }+ }+ return null;+ }++ function onPointerDown(e) {+ if (tool === 'select') {+ const onEmpty = e.target === stage || e.target.name() === 'bg';+ stage.draggable(onEmpty);+ if (onEmpty) selectedId = null;+ return;+ }+ stage.draggable(false);+ const hit = panelAt(docPoint());+ if (!hit) return;+ const panel = proof.panels[hit.index];+ const group = docLayer.findOne(`#pg-${panel.id}`);+ if (!group) return;+ const sw = strokeW / hit.box.scale;+ const common = { stroke: color, strokeWidth: sw, listening: false };+ let node;+ if (tool === 'rect') {+ node = new Konva.Rect({ x: hit.nx, y: hit.ny, width: 1, height: 1, cornerRadius: 2, ...common });+ } else if (tool === 'ellipse') {+ node = new Konva.Ellipse({ x: hit.nx, y: hit.ny, radiusX: 1, radiusY: 1, ...common });+ } 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,+ fill: color,+ ...common,+ });+ }+ group.add(node);+ drawing = { panel, node, start: { x: hit.nx, y: hit.ny }, box: hit.box, kind: tool };+ }++ function onPointerMove() {+ if (!drawing) return;+ const box = drawing.box;+ const doc = docPoint();+ // clamp to the panel even if the pointer leaves it+ const nx = Math.min(Math.max((doc.x - box.x) / box.scale, 0), drawing.panel.natural[0]);+ const ny = Math.min(Math.max((doc.y - box.y) / box.scale, 0), drawing.panel.natural[1]);+ const { start, node, kind } = drawing;+ if (kind === 'rect') {+ node.setAttrs({+ x: Math.min(start.x, nx), y: Math.min(start.y, ny),+ width: Math.abs(nx - start.x), height: Math.abs(ny - start.y),+ });+ } else if (kind === 'ellipse') {+ node.setAttrs({+ x: (start.x + nx) / 2, y: (start.y + ny) / 2,+ radiusX: Math.abs(nx - start.x) / 2, radiusY: Math.abs(ny - start.y) / 2,+ });+ } else {+ node.points([start.x, start.y, nx, ny]);+ }+ docLayer.batchDraw();+ }++ function onPointerUp() {+ if (tool === 'select') {+ stage.draggable(false);+ return;+ }+ if (!drawing) return;+ const { node, kind, panel } = drawing;+ const box = drawing.box;+ drawing = null;+ const minSize = 5 / box.scale;+ let shape = null;+ if (kind === 'rect' && node.width() > minSize && node.height() > minSize) {+ shape = { kind, x: node.x(), y: node.y(), w: node.width(), h: node.height() };+ } else if (kind === 'ellipse' && node.radiusX() * 2 > minSize && node.radiusY() * 2 > minSize) {+ shape = { kind, x: node.x(), y: node.y(), w: node.radiusX() * 2, h: node.radiusY() * 2 };+ } else if (kind === 'arrow' || kind === 'line') {+ const pts = node.points();+ if (Math.hypot(pts[2] - pts[0], pts[3] - pts[1]) > minSize) {+ shape = { kind, points: pts };+ }+ }+ node.destroy();+ if (shape) {+ const s = {+ id: newId('s'), panel: panel.id, color,+ strokeWidth: strokeW, comment: '', ...shape,+ };+ proof.shapes.push(s);+ selectedId = s.id;+ dirty = true;+ }+ }++ // ---- rebuild canvas from state ------------------------------------------------------++ function rebuild() {+ docLayer.destroyChildren();+ const { width, height, legend } = docSize(proof.panels, proof.shapes);+ const boxes = layoutPanels(proof.panels);++ docLayer.add(+ new Konva.Rect({ name: 'bg', x: 0, y: 0, width, height, fill: BG })+ );++ proof.panels.forEach((panel, i) => {+ const box = boxes[i];+ 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({+ image: panel.img, width: panel.natural[0], height: panel.natural[1], listening: false,+ }));+ }+ for (const s of proof.shapes.filter((x) => x.panel === panel.id)) {+ group.add(makeShapeNode(s, box.scale));+ }+ 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',+ 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)) {+ docLayer.add(new Konva.Circle({+ x: PAD + 11, y: y + 11, radius: 10, 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',+ 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,+ fontFamily: 'system-ui, sans-serif', ellipsis: true, wrap: 'none', listening: false,+ }));+ y += LEGEND_LINE_H;+ }+ if (proof.panels.length) {+ docLayer.add(new Konva.Text({+ x: PAD, y: height - FOOTER_H - PAD + 8,+ width: width - PAD * 2,+ text: attributionLine(proof.panels),+ fontSize: 12.5, fill: TEXT_FAINT,+ fontFamily: 'system-ui, sans-serif', ellipsis: true, wrap: 'none', listening: false,+ }));+ }++ // selection+ const selectedNode = selectedId ? docLayer.findOne(`#${selectedId}`) : null;+ transformer.nodes(selectedNode ? [selectedNode] : []);+ transformer.enabledAnchors(+ selectedNode && (selectedNode.className === 'Rect' || selectedNode.className === 'Ellipse')+ ? ['top-left', 'top-right', 'bottom-left', 'bottom-right', 'middle-left', 'middle-right', 'top-center', 'bottom-center']+ : []+ );+ docLayer.batchDraw();+ uiLayer.batchDraw();+ }++ function makeShapeNode(s, panelScale) {+ const sw = (s.strokeWidth ?? 4) / panelScale;+ const common = {+ id: s.id, stroke: s.color, strokeWidth: sw,+ draggable: true, hitStrokeWidth: Math.max(sw * 3, 14 / panelScale),+ };+ let node;+ if (s.kind === 'rect') {+ node = new Konva.Rect({ x: s.x, y: s.y, width: s.w, height: s.h, cornerRadius: 2, ...common });+ } else if (s.kind === 'ellipse') {+ node = new Konva.Ellipse({ x: s.x, y: s.y, radiusX: s.w / 2, radiusY: s.h / 2, ...common });+ } else {+ node = new Konva.Arrow({+ points: s.points,+ pointerLength: s.kind === 'arrow' ? 14 / panelScale : 0,+ pointerWidth: s.kind === 'arrow' ? 14 / panelScale : 0,+ fill: s.color,+ ...common,+ });+ }+ node.on('pointerdown', (e) => {+ if (tool === 'select') {+ e.cancelBubble = true;+ selectedId = s.id;+ }+ });+ node.on('dragend', () => {+ if (s.kind === 'rect' || s.kind === 'ellipse') {+ s.x = node.x();+ s.y = node.y();+ } else {+ const dx = node.x(), dy = node.y();+ s.points = [s.points[0] + dx, s.points[1] + dy, s.points[2] + dx, s.points[3] + dy];+ node.position({ x: 0, y: 0 });+ }+ dirty = true;+ });+ node.on('transformend', () => {+ if (s.kind === 'rect') {+ s.x = node.x(); s.y = node.y();+ s.w = Math.abs(node.width() * node.scaleX());+ s.h = Math.abs(node.height() * node.scaleY());+ } else if (s.kind === 'ellipse') {+ s.x = node.x(); s.y = node.y();+ s.w = Math.abs(node.radiusX() * 2 * node.scaleX());+ s.h = Math.abs(node.radiusY() * 2 * node.scaleY());+ }+ node.scale({ x: 1, y: 1 });+ dirty = true;+ });+ return node;+ }++ // ---- shape ops from the side panel -----------------------------------------------------++ function deleteShape(id) {+ proof.shapes = proof.shapes.filter((s) => s.id !== id);+ if (selectedId === id) selectedId = null;+ dirty = true;+ }++ function setShapeColor(s, c) {+ s.color = c;+ dirty = true;+ }++ function onKeydown(e) {+ if (uiState.tool !== 'proof') return;+ if (['INPUT', 'TEXTAREA', 'SELECT'].includes(e.target.tagName)) return;+ if ((e.key === 'Delete' || e.key === 'Backspace') && selectedId) {+ deleteShape(selectedId);+ } else if (e.key === 'Escape') {+ selectedId = null;+ tool = 'select';+ } else if (e.key === 'v') tool = 'select';+ else if (e.key === 'r') tool = 'rect';+ else if (e.key === 'e') tool = 'ellipse';+ else if (e.key === 'a') tool = 'arrow';+ else if (e.key === 'l') tool = 'line';+ else if (e.key === 'f') fit();+ }++ // ---- persistence -------------------------------------------------------------------------++ function exportPng() {+ const { width, height } = docSize(proof.panels, proof.shapes);+ const prevScale = stage.scale();+ const prevPos = stage.position();+ const prevSize = { w: stage.width(), h: stage.height() };+ transformer.nodes([]);+ stage.scale({ x: 1, y: 1 });+ stage.position({ x: 0, y: 0 });+ stage.width(width);+ stage.height(height);+ const pixelRatio = Math.min(Math.max(1800 / width, 0.75), 2);+ const dataUrl = docLayer.toDataURL({ x: 0, y: 0, width, height, pixelRatio });+ stage.scale(prevScale);+ stage.position(prevPos);+ stage.width(prevSize.w);+ stage.height(prevSize.h);+ rebuild();+ return dataUrl;+ }++ async function save({ andPost = false } = {}) {+ if (!proof.panels.length || saving) return;+ saving = true;+ try {+ const c = await ensureCase();+ const dataUrl = exportPng();+ const result = await api.post(`/api/cases/${c.id}/proofs`, {+ name: savedName,+ title: proof.title,+ spec: toSpec(proof),+ png_base64: dataUrl.split(',')[1],+ });+ savedName = result.name;+ dirty = false;+ await reloadCase();+ toast(`Proof saved — ${result.png}`, 'ok');+ if (andPost) {+ uiState.postProof = {+ title: proof.title,+ coords: proof.coords,+ attribution: attributionLine(proof.panels),+ png: result.png,+ sources: proof.panels.map((p) => p.meta?.source_url).filter(Boolean),+ };+ uiState.tool = 'post';+ }+ } catch (e) {+ toast(`Save failed: ${e.message}`, 'danger', 6000);+ } finally {+ saving = false;+ }+ }++ async function openProofList() {+ openList = await api.get(`/api/cases/${caseState.current.id}/proofs`);+ }++ async function openProof(entry) {+ const spec = await api.get(`/api/cases/${caseState.current.id}/proofs/${entry.name}`);+ resetDoc();+ proof.title = spec.title;+ proof.coords = spec.coords ?? null;+ 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 });+ } catch {+ toast(`Missing panel image: ${p.src}`, 'warn');+ }+ }+ const validPanels = new Set(proof.panels.map((p) => p.id));+ proof.shapes = (spec.shapes ?? []).filter((s) => validPanels.has(s.panel));+ savedName = entry.name;+ openList = null;+ dirty = false;+ requestAnimationFrame(fit);+ }++ const selectedShape = $derived(proof.shapes.find((s) => s.id === selectedId));</script>+<svelte:window onkeydown={onKeydown} />+<div class="tool">- <div class="tool-body">- <div class="empty" style="height: 100%">- <div class="empty-icon"><Icon name="proof" size={40} /></div>- <h3>Proof Composer</h3>- <p>Coming in the next milestone.</p>+ <div class="tool-header">+ <h2>Proof Composer</h2>+ <input class="input title-input" bind:value={proof.title} onchange={() => (dirty = true)} />+ {#if dirty}<span class="badge">unsaved</span>{/if}+ <div class="spacer"></div>+ {#if caseState.current}+ <button class="btn" onclick={openProofList}><Icon name="folderOpen" size={15} /> Open</button>+ {/if}+ <button class="btn" onclick={openPicker}><Icon name="plus" size={15} /> Add panel</button>+ <button class="btn btn-primary" onclick={() => save()} disabled={!proof.panels.length || saving}>+ <Icon name="check" size={15} /> {saving ? 'Saving…' : 'Save + export'}+ </button>+ <button class="btn" onclick={() => save({ andPost: true })} disabled={!proof.panels.length || saving}>+ <Icon name="post" size={15} /> To Post+ </button>+ </div>++ <div class="body">+ <!-- left: drawing toolbar -->+ <div class="toolbar">+ {#each DRAW_TOOLS as t (t.id)}+ <button+ class="tb-btn"+ class:active={tool === t.id}+ title="{t.label} ({t.id === 'select' ? 'v' : t.id[0]})"+ onclick={() => (tool = t.id)}+ >+ <Icon name={t.icon} size={18} />+ </button>+ {/each}+ <div class="tb-sep"></div>+ {#each ANNO_COLORS as c (c)}+ <button+ class="color-btn"+ class:active={(selectedShape?.color ?? color) === c}+ style:background={c}+ title="Same color = same feature"+ onclick={() => (selectedShape ? setShapeColor(selectedShape, c) : (color = c))}+ aria-label={`color ${c}`}+ ></button>+ {/each}+ <div class="tb-sep"></div>+ <input+ class="stroke-slider"+ type="range" min="2" max="10" step="1"+ bind:value={strokeW}+ title="Stroke width"+ />+ <div class="tb-sep"></div>+ <button class="tb-btn" title="Fit view (f)" onclick={fit}><Icon name="eye" size={18} /></button></div>++ <!-- canvas -->+ <div class="canvas-wrap" class:drawing={tool !== 'select'}>+ <div class="konva" bind:this={containerEl}></div>+ {#if !proof.panels.length}+ <div class="empty overlay-empty">+ <div class="empty-icon"><Icon name="proof" size={42} /></div>+ <h3>Compose a proof</h3>+ <p>+ Add panels — frames, photos, satellite crops — then draw colored shapes to match+ features. <strong>Same color = same feature</strong> across panels.+ </p>+ <button class="btn btn-primary" onclick={openPicker}>+ <Icon name="plus" size={15} /> Add your first panel+ </button>+ </div>+ {/if}+ </div>++ <!-- right: panels & annotations -->+ <aside class="side">+ <div class="side-scroll">+ <div class="side-title">Panels <span class="count">{proof.panels.length}</span></div>+ {#each proof.panels as panel, i (panel.id)}+ <div class="panel-row card">+ <img src={`/files/${caseState.current?.id}/${panel.src}`} alt="" />+ <input+ class="input cap-input"+ placeholder="Caption…"+ bind:value={panel.caption}+ 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" style="margin-left:auto" title="Remove panel" onclick={() => removePanel(i)}>+ <Icon name="trash" size={13} />+ </button>+ </div>+ </div>+ {/each}++ <div class="side-title" style="margin-top: 14px">+ Annotations <span class="count">{proof.shapes.length}</span>+ </div>+ {#if !proof.shapes.length}+ <div class="none">Draw on the panels with the box, ellipse, arrow or line tools.</div>+ {/if}+ {#each proof.shapes as s (s.id)}+ <div+ class="shape-row"+ class:selected={selectedId === s.id}+ onclick={() => (selectedId = s.id)}+ role="button"+ tabindex="0"+ onkeydown={(e) => e.key === 'Enter' && (selectedId = s.id)}+ >+ <span class="chip" style:background={s.color}></span>+ <Icon name={s.kind === 'rect' ? 'square' : s.kind === 'ellipse' ? 'circle' : s.kind} size={13} />+ <input+ class="input comment-input"+ placeholder="Feature comment (legend)…"+ bind:value={s.comment}+ onchange={() => (dirty = true)}+ onclick={(e) => e.stopPropagation()}+ />+ <button class="btn btn-ghost btn-sm" title="Delete" onclick={(e) => { e.stopPropagation(); deleteShape(s.id); }}>+ <Icon name="x" size={13} />+ </button>+ </div>+ {/each}+ </div>+ </aside></div></div>++{#if picker}+ <Modal title="Add a panel" onclose={() => (picker = false)} width="720px">+ {#if !pickerItems.length}+ <div class="empty">+ <p>No images in this case yet — import media or capture satellite imagery first.</p>+ </div>+ {:else}+ <div class="pick-grid">+ {#each pickerItems as item (item.src)}+ <button+ class="pick card"+ onclick={() => {+ addPanel(item);+ picker = false;+ }}+ >+ <img src={`/files/${caseState.current.id}/${item.thumb}`} alt="" loading="lazy" />+ <span class="pick-label">+ <Icon name={item.kind === 'satellite' ? 'satellite' : 'image'} size={12} />+ {item.label}+ </span>+ </button>+ {/each}+ </div>+ {/if}+ </Modal>+{/if}++{#if openList}+ <Modal title="Open a saved proof" onclose={() => (openList = null)} width="560px">+ {#if !openList.length}+ <div class="empty"><p>No saved proofs in this case yet.</p></div>+ {:else}+ <div class="open-list">+ {#each openList as entry (entry.name)}+ <button class="open-row" onclick={() => openProof(entry)}>+ {#if entry.png}+ <img src={`/files/${caseState.current.id}/${entry.png}`} alt="" loading="lazy" />+ {/if}+ <div class="open-meta">+ <span class="open-title">{entry.title}</span>+ <span class="open-sub">{entry.panels} panels · {entry.shapes} annotations · {entry.updated_at?.slice(0, 10)}</span>+ </div>+ </button>+ {/each}+ </div>+ {/if}+ </Modal>+{/if}++<style>+ .spacer { flex: 1; }+ .title-input {+ width: min(320px, 26vw);+ font-weight: 600;+ }+ .body {+ flex: 1;+ display: flex;+ min-height: 0;+ }+ .toolbar {+ width: 52px;+ flex-shrink: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 6px;+ padding: 12px 0;+ border-right: 1px solid var(--border);+ background: var(--bg-1);+ }+ .tb-btn {+ width: 38px;+ height: 38px;+ display: flex;+ align-items: center;+ justify-content: center;+ border-radius: var(--r-sm);+ color: var(--text-3);+ }+ .tb-btn:hover { color: var(--text-1); background: var(--bg-2); }+ .tb-btn.active { color: var(--accent); background: var(--accent-soft); }+ .tb-sep {+ width: 26px;+ height: 1px;+ background: var(--border);+ margin: 4px 0;+ }+ .color-btn {+ width: 22px;+ height: 22px;+ border-radius: 50%;+ border: 2px solid transparent;+ transition: transform 0.12s var(--ease);+ flex-shrink: 0;+ }+ .color-btn:hover { transform: scale(1.15); }+ .color-btn.active {+ border-color: var(--text-1);+ box-shadow: 0 0 0 2px var(--bg-1), 0 0 0 3.5px var(--text-3);+ }+ .stroke-slider {+ width: 80px;+ transform: rotate(-90deg);+ margin: 34px 0;+ accent-color: var(--accent);+ }+ .canvas-wrap {+ position: relative;+ flex: 1;+ min-width: 0;+ background:+ radial-gradient(circle at 1px 1px, rgba(148, 163, 196, 0.07) 1px, transparent 0) 0 0 / 22px 22px,+ var(--bg-0);+ }+ .canvas-wrap.drawing { cursor: crosshair; }+ .konva { position: absolute; inset: 0; }+ .overlay-empty {+ position: absolute;+ inset: 0;+ pointer-events: none;+ }+ .overlay-empty .btn { pointer-events: auto; }+ .side {+ width: 300px;+ flex-shrink: 0;+ border-left: 1px solid var(--border);+ background: var(--bg-1);+ display: flex;+ min-height: 0;+ }+ .side-scroll {+ flex: 1;+ overflow-y: auto;+ padding: 12px;+ }+ .side-title {+ font-size: var(--fs-xs);+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.07em;+ color: var(--text-2);+ margin-bottom: 8px;+ display: flex;+ justify-content: space-between;+ }+ .count { color: var(--text-3); }+ .panel-row {+ padding: 8px;+ margin-bottom: 8px;+ display: flex;+ flex-direction: column;+ gap: 6px;+ }+ .panel-row img {+ width: 100%;+ max-height: 90px;+ object-fit: cover;+ border-radius: var(--r-sm);+ background: var(--bg-2);+ }+ .cap-input { font-size: var(--fs-xs); padding: 5px 8px; }+ .panel-actions { display: flex; gap: 2px; }+ .none {+ font-size: var(--fs-xs);+ color: var(--text-3);+ padding: 2px 2px 8px;+ }+ .shape-row {+ display: flex;+ align-items: center;+ gap: 7px;+ padding: 5px 6px;+ border-radius: var(--r-sm);+ margin-bottom: 3px;+ border: 1px solid transparent;+ color: var(--text-3);+ cursor: pointer;+ }+ .shape-row:hover { background: var(--bg-2); }+ .shape-row.selected { border-color: var(--accent); background: var(--accent-soft); }+ .chip {+ width: 12px;+ height: 12px;+ border-radius: 50%;+ flex-shrink: 0;+ }+ .comment-input {+ flex: 1;+ font-size: var(--fs-xs);+ padding: 4px 8px;+ background: transparent;+ border-color: transparent;+ min-width: 0;+ }+ .comment-input:hover, .comment-input:focus { background: var(--bg-2); border-color: var(--border); }+ .pick-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));+ gap: 10px;+ }+ .pick {+ overflow: hidden;+ text-align: left;+ transition: border-color 0.15s var(--ease);+ }+ .pick:hover { border-color: var(--accent); }+ .pick img {+ width: 100%;+ aspect-ratio: 16 / 11;+ object-fit: cover;+ background: var(--bg-2);+ }+ .pick-label {+ display: flex;+ align-items: center;+ gap: 5px;+ padding: 6px 8px;+ font-size: var(--fs-xs);+ color: var(--text-2);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .open-list { display: flex; flex-direction: column; gap: 8px; }+ .open-row {+ display: flex;+ gap: 12px;+ align-items: center;+ padding: 8px;+ border: 1px solid var(--border);+ border-radius: var(--r-md);+ background: var(--bg-2);+ text-align: left;+ }+ .open-row:hover { border-color: var(--accent); }+ .open-row img {+ width: 110px;+ aspect-ratio: 16 / 10;+ object-fit: cover;+ border-radius: var(--r-sm);+ background: var(--bg-3);+ }+ .open-meta { display: flex; flex-direction: column; gap: 2px; }+ .open-title { font-weight: 600; font-size: var(--fs-sm); }+ .open-sub { font-size: var(--fs-xs); color: var(--text-3); }+</style>diff --git a/src/ozimut/api/proofs.py b/src/ozimut/api/proofs.pynew file mode 100644index 0000000..80c62b2--- /dev/null+++ b/src/ozimut/api/proofs.py@@ -0,0 +1,134 @@+"""REST API for proofs: save (PNG + re-editable JSON spec), list, load, delete.++The spec is the source of truth — a proof saved once reopens for re-editing+(spec §6 v1). The PNG is the publishable export of that spec.+"""++from __future__ import annotations++import base64+import binascii+import json+import re+from datetime import datetime, timezone+from typing import Any++from fastapi import APIRouter, HTTPException+from pydantic import BaseModel, Field++from ..workspace import CaseError+from .cases import get_case++router = APIRouter(prefix="/api", tags=["proofs"])+++class ProofIn(BaseModel):+ name: str | None = None # slug; None → derived from title+ title: str = Field(min_length=1, max_length=200)+ spec: dict[str, Any]+ png_base64: str | None = None # rendered export, data URL body+++def _slug(text: str) -> str:+ slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")+ return slug[:80] or "proof"+++def _now() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")++[email protected]("/cases/{case_id}/proofs")+def list_proofs(case_id: str) -> list[dict[str, Any]]:+ case = get_case(case_id)+ proofs = []+ for spec_path in sorted(case.subdir("proofs").glob("*.json")):+ try:+ spec = json.loads(spec_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ continue+ if spec.get("ozimut_proof") != 1:+ continue+ name = spec_path.stem+ png = spec_path.with_suffix(".png")+ proofs.append(+ {+ "name": name,+ "title": spec.get("title", name),+ "updated_at": spec.get("updated_at"),+ "panels": len(spec.get("panels", [])),+ "shapes": len(spec.get("shapes", [])),+ "png": f"proofs/{png.name}" if png.exists() else None,+ "spec_path": f"proofs/{spec_path.name}",+ }+ )+ proofs.sort(key=lambda p: p.get("updated_at") or "", reverse=True)+ return proofs++[email protected]("/cases/{case_id}/proofs/{name}")+def load_proof(case_id: str, name: str) -> dict[str, Any]:+ case = get_case(case_id)+ try:+ spec_path = case.resolve_inside(f"proofs/{name}.json")+ except CaseError as exc:+ raise HTTPException(status_code=403, detail=str(exc)) from exc+ if not spec_path.exists():+ raise HTTPException(status_code=404, detail="proof not found")+ return json.loads(spec_path.read_text(encoding="utf-8"))++[email protected]("/cases/{case_id}/proofs")+def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:+ case = get_case(case_id)+ name = _slug(body.name or body.title)+ proofs_dir = case.subdir("proofs")++ spec = dict(body.spec)+ spec["ozimut_proof"] = 1+ spec["title"] = body.title+ spec.setdefault("created_at", _now())+ spec["updated_at"] = _now()++ spec_path = proofs_dir / f"{name}.json"+ spec_path.write_text(+ json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"+ )++ png_rel = None+ if body.png_base64:+ try:+ png_bytes = base64.b64decode(body.png_base64, validate=True)+ except (binascii.Error, ValueError) as exc:+ raise HTTPException(status_code=422, detail="invalid PNG payload") from exc+ (proofs_dir / f"{name}.png").write_bytes(png_bytes)+ png_rel = f"proofs/{name}.png"++ # upsert the proof entity (analyst action → confirmed)+ existing = case.find_entity(attr="spec", value=f"proofs/{name}.json")+ if existing:+ case.update_entity(existing["id"], {"label": body.title})+ else:+ case.add_entity(+ "proof",+ body.title,+ attrs={"spec": f"proofs/{name}.json", **({"path": png_rel} if png_rel else {})},+ by="proof-composer",+ )++ return {"name": name, "png": png_rel, "spec_path": f"proofs/{name}.json"}++[email protected]("/cases/{case_id}/proofs/{name}")+def delete_proof(case_id: str, name: str) -> dict[str, str]:+ case = get_case(case_id)+ try:+ spec_path = case.resolve_inside(f"proofs/{name}.json")+ except CaseError as exc:+ raise HTTPException(status_code=403, detail=str(exc)) from exc+ spec_path.unlink(missing_ok=True)+ spec_path.with_suffix(".png").unlink(missing_ok=True)+ entity = case.find_entity(attr="spec", value=f"proofs/{name}.json")+ if entity:+ case.remove_entity(entity["id"])+ return {"status": "deleted"}diff --git a/src/ozimut/server.py b/src/ozimut/server.pyindex f283e66..5bdc358 100644--- a/src/ozimut/server.py+++ b/src/ozimut/server.py@@ -18,11 +18,12 @@ def create_app() -> FastAPI:app = FastAPI(title="Ozimut", version=__version__, docs_url="/api/docs")- from .api import cases, files, media, satellite+ from .api import cases, files, media, proofs, satelliteapp.include_router(cases.router)app.include_router(media.router)app.include_router(satellite.router)+ app.include_router(proofs.router)app.include_router(files.router)@app.get("/api/health")diff --git a/tests/test_proofs_api.py b/tests/test_proofs_api.pynew file mode 100644index 0000000..93bd519--- /dev/null+++ b/tests/test_proofs_api.py@@ -0,0 +1,79 @@+"""Proofs: save spec+PNG, list, reload, entity upsert, delete."""++import base64+import io++from PIL import Image+++def _png_b64() -> str:+ buf = io.BytesIO()+ Image.new("RGB", (80, 50), (40, 40, 60)).save(buf, "PNG")+ return base64.b64encode(buf.getvalue()).decode()+++SPEC = {+ "panels": [+ {"id": "p1", "src": "media/frame.png", "caption": "Frame", "natural": [1280, 720], "meta": {}},+ {"id": "p2", "src": "satellite/sat.png", "caption": "Esri", "natural": [1000, 700],+ "meta": {"kind": "satellite", "attribution": "Esri", "lat": 1.0, "lon": 2.0}},+ ],+ "shapes": [+ {"id": "s1", "panel": "p1", "kind": "rect", "x": 10, "y": 10, "w": 100, "h": 50,+ "color": "#ff5252", "strokeWidth": 4, "comment": "blue roof"},+ ],+ "coords": {"lat": 1.0, "lon": 2.0},+}+++def test_save_load_roundtrip(client):+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]++ saved = client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Kharkiv strike proof", "spec": SPEC, "png_base64": _png_b64()},+ ).json()+ assert saved["name"] == "kharkiv-strike-proof"+ assert saved["png"] == "proofs/kharkiv-strike-proof.png"++ listed = client.get(f"/api/cases/{cid}/proofs").json()+ assert len(listed) == 1+ assert listed[0]["panels"] == 2 and listed[0]["shapes"] == 1++ spec = client.get(f"/api/cases/{cid}/proofs/kharkiv-strike-proof").json()+ assert spec["title"] == "Kharkiv strike proof"+ assert spec["shapes"][0]["comment"] == "blue roof"+ assert spec["panels"][0]["id"] == "p1" # panel ids survive → shapes stay bound++ # PNG served+ assert client.get(f"/files/{cid}/{saved['png']}").status_code == 200++ # proof entity filed once, updated on resave+ client.post(+ f"/api/cases/{cid}/proofs",+ json={"name": saved["name"], "title": "Renamed proof", "spec": SPEC},+ )+ entities = [e for e in client.get(f"/api/cases/{cid}").json()["entities"] if e["type"] == "proof"]+ assert len(entities) == 1+ assert entities[0]["label"] == "Renamed proof"+++def test_invalid_png_rejected(client):+ cid = client.post("/api/cases", json={"name": "Bad"}).json()["id"]+ res = client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "x", "spec": SPEC, "png_base64": "not-base64!!!"},+ )+ assert res.status_code == 422+++def test_delete_proof(client):+ cid = client.post("/api/cases", json={"name": "DelProof"}).json()["id"]+ saved = client.post(+ f"/api/cases/{cid}/proofs",+ json={"title": "Temp", "spec": SPEC, "png_base64": _png_b64()},+ ).json()+ client.delete(f"/api/cases/{cid}/proofs/{saved['name']}")+ assert client.get(f"/api/cases/{cid}/proofs").json() == []+ assert client.get(f"/api/cases/{cid}/proofs/{saved['name']}").status_code == 404+ assert [e for e in client.get(f"/api/cases/{cid}").json()["entities"] if e["type"] == "proof"] == []