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

Add reusable composer templates and post targets

OsintMeThateec2aab90e21
diff --git a/.gitignore b/.gitignore
index 824c2c3..8a06605 100644
--- a/.gitignore
+++ b/.gitignore
@@ -43,6 +43,8 @@ src/azimut/static/
# Local tooling / assistant configs
CLAUDE.md
.claude/
+AGENTS.md
+.codex/
.cheatsheet
# PyInstaller local output
diff --git a/docs/SPEC.md b/docs/SPEC.md
index 0d8e18e..f5f4e7f 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -94,7 +94,7 @@ the wheel, cross-platform binaries, tag-driven release CI).
| ✅ **Media Library** | Case media shelf. Import (drag & drop) or download by URL (yt-dlp + gallery-dl fallback + Telegram photo scraper) → clean file + metadata + sha256, each a `media` entity. Multi-attachment picker, facet bar (type/source + virtual folders), per-item notes, lightbox, provenance modal. |
| ✅ **Inspect** | Scratch workspace over any photo/video, nothing saved until Save. Sharpest-frame scan, per-frame adjustments, view-only zoom/pan/rotate, editable crop, multi-piece warp collage with auto-stitch (planar/cylindrical/spherical), ELA hint, reopenable sessions. |
| ✅ **Satellite** | Coordinate map over an XYZ tile abstraction. Save a `place` or capture a sourced crop (→ `capture`, filed in `media/`). Standard-size or marquee capture, resolution multiplier, marker styles, map rotation, move-pin, dual dates, measure, OSM overlay, reference windows, external-map links. |
-| ✅ **Proof Composer** | The v1 heart. Multi-row grid or free layout of panels; resize, tweet-crop guide, magic tweet-fit. Draw boxes/ellipses/lines/arrows/curves/text, all editable after placing; per-color legend; captions; a Coordinates + Source header traced through the derivation chain; signature. Export `proof.png` + re-editable JSON spec. |
+| ✅ **Proof Composer** | The v1 heart. Start a named proof with independent template and searchable case-panel selection. Multi-row grid or free layout; resize, tweet-crop guide, magic tweet-fit; editable shapes/freehand/text, per-color legend, captions, traced Coordinates + Source, signature. Export `proof.png` + re-editable JSON spec. |
| ✅ **Post Composer** | GeoConfirmed thread from a proof: place + plus code, decimal coords, mention, source, optional media tweet, extra tweets, char counts. Save drafts, publish (opens X prefilled — never posts for you). |
| ✅ **Case sidebar** | Resizable. Case notes, suggestions inbox, nested "My work" folders + Unfiled, a details/selection editor, two-way delete sync, and the case switcher (create/open/promote/rename/delete, unique names). |
@@ -112,6 +112,8 @@ server security hardening, and the two-regime dependency setup.
| ✅ **Coordinates** | Map-workspace tab: paste a point in any notation (decimal, DDM, DMS, UTM, MGRS, plus code, geohash) → read it back in every other with copy; the nine external-map links; opt-in Nominatim place name. |
| ✅ **Reverse Search** | Collect-workspace launcher: pick a case image (or scrub a video to a frame), tweak brightness/contrast/saturation/grayscale → copy to the clipboard for Google Lens or save the PNG to drag into Yandex/Bing/TinEye, each opened key-less. Orchestrates, never queries itself. |
| ✅ **Grid Search** | Satellite mode: overlay a custom metric grid on an area of interest — drag a box or draw a polygon, reshape either after the fact — and sweep it cell by cell. Fly-to-review with keyboard marks, cleared/flagged coverage; every action auto-saves. A case holds several named grids you switch between; promote a hit to a `place`. In-app only, no export. |
+| ✅ **Templates** | Reusable house styles, workspace-level: a proof style (background, panel margins, text sizes, footer, signature placement, preferred colours) and a post-thread skeleton (mention, which tweet-1 lines, media tweet, extra tweets). Built and edited in Settings → Templates, applied from the Proof/Post Composer. |
+| ✅ **Post outputs** | Prepare one thread for X, Bluesky or Mastodon, hand it to the selected composer, or copy a Markdown report. |
**Key constraints** (carried forward):
@@ -144,25 +146,18 @@ never as new rail entries. Releases ship as GitHub `v0.x` tags.
| **Audio Transcript** | Transcribe speech (Whisper) + acoustic context hints (bells/adhan/aircraft/language); auto-translate → English (offline). |
| **Ground Imagery** | Ground-level photos: Panoramax/Mapillary/KartaView key-less first; Street View easy link, optional keyed in-app view. |
| **Panorama** | Stitch a video window / frame set. Auto-stitch already in Inspect; still to do: sample a video window directly, seam blending. |
-| **Proof annotation** | Grow the Proof Composer toolbox: shape fill + dashed strokes, freehand, numbered markers, a redaction/blur box; a document-level free layer so shapes cross panels and reach the margins; callout / zoom insets. |
+| **Proof annotation** | Grow the Proof Composer toolbox: shape fill + dashed strokes, numbered markers, a redaction/blur box; a document-level free layer so shapes cross panels and reach the margins; callout / zoom insets. |
| **Case Notebook** | A full notes page, not just raw `notes.md`: write, paste screenshots and images, embed links to places/entities; a writer pane + a reader pane. |
-| **Proof Templates** | Save a proof's house style (layout, colors, legend, signature) as a reusable template/preset; new proofs start from one. |
Also toward v2: GIF maker, curated tools-links page, command palette (Ctrl+K),
full-text case search, timezone + local-time readout at coords, clipboard
capture (paste an image or a URL anywhere → filed as media with provenance),
scale bar + north arrow + optional graticule burned into captures
(preference-toggled auto-inclusion, extension/widget capture path included),
-read EXIF/GPS at media import → suggest place/time, Post Composer targets beyond
-X (Mastodon, Bluesky, generic report). Grow the two shipped GEOINT tools:
-Coordinates gains map-URL paste (reuse the extension's `parse_map_url`) and a
-Satellite hand-off; Reverse Search gains an optional TinEye-API-keyed
-oldest-date origin hint (Settings key, labeled a hint).
-
-Engineering (toward v2): split the monolith tool components (Satellite,
-ProofComposer) by extracting their logic into `lib/` modules like the other
-tools; add component/interaction tests (Playwright) for the canvas gestures the
-`lib` unit tests can't reach.
+read EXIF/GPS at media import → suggest place/time.
+
+Engineering toward v2: split Satellite and Proof Composer into focused modules;
+add Playwright coverage for canvas interactions that unit tests cannot exercise.
### v3 — investigation layer
diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelte
index 66c7e33..416ea30 100644
--- a/frontend/src/components/Icon.svelte
+++ b/frontend/src/components/Icon.svelte
@@ -57,6 +57,7 @@
circle: 'M12 4a8 8 0 1 1 0 16 8 8 0 0 1 0-16Z',
line: 'M5 19 19 5',
curve: 'M4 18c4 0 4-12 8-12s4 12 8 12',
+ freehand: 'M3 17c3-9 5 5 8-2s4-8 6-2 3-2 4-5',
arrow: 'M5 19 19 5m0 0h-8m8 0v8',
text: 'M5 6V4h14v2M12 4v16m-3 0h6',
hand: 'M8 12V6a1.5 1.5 0 0 1 3 0v5m0-6.5a1.5 1.5 0 0 1 3 0V11m0-5a1.5 1.5 0 0 1 3 0v9a6 6 0 0 1-6 6h-1a6 6 0 0 1-5-2.7L3.5 15A1.6 1.6 0 0 1 6 13.2l2 1.8',
diff --git a/frontend/src/components/PostTemplateEditor.svelte b/frontend/src/components/PostTemplateEditor.svelte
new file mode 100644
index 0000000..172a5c7
--- /dev/null
+++ b/frontend/src/components/PostTemplateEditor.svelte
@@ -0,0 +1,138 @@
+<script>
+ /**
+ * Editor for one post-thread template. The thread structure is a token body:
+ * the analyst arranges tokens (#place, #coordinates, …) in the order and line
+ * layout they want, mixes in literal text, and a live preview fills them with
+ * sample values. Plus the default mention, the media-tweet flag and any
+ * boilerplate extra tweets. Content-free.
+ *
+ * `data` is the template blob (bindable); the parent owns save/delete.
+ */
+ import { TWEET_TOKENS, DEFAULT_TWEET_BODY, buildTweet1 } from '../lib/post.js';
+ import Icon from './Icon.svelte';
+
+ let { data = $bindable() } = $props();
+
+ // guarantee the shape (a hand-edited or legacy blob may omit fields)
+ if (typeof data.body !== 'string' || !data.body) data.body = DEFAULT_TWEET_BODY;
+ if (!Array.isArray(data.extraTweets)) data.extraTweets = [];
+
+ let bodyEl = $state(null);
+
+ // Insert a token at the caret (or over the selection), keeping focus so the
+ // analyst can keep typing/inserting without reaching for the mouse.
+ function insertToken(tag) {
+ const el = bodyEl;
+ const text = data.body ?? '';
+ const start = el?.selectionStart ?? text.length;
+ const end = el?.selectionEnd ?? text.length;
+ data.body = text.slice(0, start) + tag + text.slice(end);
+ requestAnimationFrame(() => {
+ if (!el) return;
+ const caret = start + tag.length;
+ el.focus();
+ el.setSelectionRange(caret, caret);
+ });
+ }
+
+ function addExtra() {
+ data.extraTweets.push({ text: '' });
+ }
+ function removeExtra(i) {
+ data.extraTweets.splice(i, 1);
+ }
+
+ // Live preview of the first tweet with placeholder facts + the template's own
+ // mention, so the effect of the token layout reads without leaving Settings.
+ const SAMPLE = Object.fromEntries(TWEET_TOKENS.map((t) => [t.tag.slice(1), t.sample]));
+ const preview = $derived(
+ buildTweet1(data.body, {
+ place: SAMPLE.place,
+ plusCode: SAMPLE.pluscode,
+ description: SAMPLE.description,
+ lat: 48.85,
+ lon: 2.35,
+ mention: data.mention || SAMPLE.mention,
+ source: SAMPLE.source,
+ }) || '(empty post)'
+ );
+</script>
+
+<div class="post-editor">
+ <div class="pe-grid">
+ <div class="pe-fields">
+ <label class="fld">
+ <span>Mention</span>
+ <input type="text" placeholder="@GeoConfirmed" maxlength="64" bind:value={data.mention} />
+ </label>
+
+ <fieldset class="fld">
+ <span>First post layout</span>
+ <p class="hint">Arrange the tokens in the order you want, add line breaks and
+ your own text. A token with no value drops its line.</p>
+ <div class="tokens">
+ {#each TWEET_TOKENS as tok}
+ <button type="button" class="tok" title={`Insert ${tok.tag}`}
+ onclick={() => insertToken(tok.tag)}>{tok.tag}</button>
+ {/each}
+ </div>
+ <textarea class="body" rows="9" bind:this={bodyEl} bind:value={data.body}></textarea>
+ </fieldset>
+
+ <label class="chk">
+ <input type="checkbox" bind:checked={data.mediaEnabled} /> Include a media post
+ </label>
+
+ <fieldset class="fld">
+ <span>Boilerplate extra posts</span>
+ {#each data.extraTweets as tw, i (i)}
+ <div class="extra-row">
+ <textarea rows="2" placeholder="Extra post text" bind:value={tw.text}></textarea>
+ <button type="button" class="btn btn-ghost btn-sm" title="Remove"
+ onclick={() => removeExtra(i)}><Icon name="trash" /></button>
+ </div>
+ {/each}
+ <button type="button" class="btn btn-ghost btn-sm" onclick={addExtra}>
+ <Icon name="plus" /> Add post
+ </button>
+ </fieldset>
+ </div>
+
+ <div class="pe-preview">
+ <span class="pv-label">First post preview</span>
+ <pre>{preview}</pre>
+ </div>
+ </div>
+</div>
+
+<style>
+ .pe-grid { display: grid; grid-template-columns: 1fr 240px; gap: 16px; align-items: start; }
+ .pe-fields { display: flex; flex-direction: column; gap: 14px; min-width: 0; }
+ .fld { display: flex; flex-direction: column; gap: 6px; border: 0; margin: 0; padding: 0; }
+ .fld > span { font-size: 12px; color: var(--text-2); font-weight: 600; }
+ .hint { margin: 0; font-size: 11px; color: var(--text-3); line-height: 1.4; }
+ .fld input[type='text'], .extra-row textarea, .body {
+ background: var(--bg-2); border: 1px solid var(--border); border-radius: 6px;
+ color: var(--text-1); padding: 6px 8px; font: inherit; width: 100%; resize: vertical;
+ }
+ .body { font: 12px/1.5 var(--font-mono, monospace); }
+ .tokens { display: flex; flex-wrap: wrap; gap: 5px; }
+ .tok {
+ padding: 3px 8px; border: 1px solid var(--border); border-radius: 999px;
+ background: var(--bg-2); color: var(--accent); font: 11px var(--font-mono, monospace);
+ cursor: pointer;
+ }
+ .tok:hover { background: var(--bg-3); }
+ .chk { display: flex; gap: 6px; align-items: center; font-size: 13px; color: var(--text-2); }
+ .extra-row { display: grid; grid-template-columns: 1fr auto; gap: 8px; align-items: start; }
+ .pe-preview {
+ border: 1px solid var(--border); border-radius: 8px; padding: 10px;
+ display: flex; flex-direction: column; gap: 6px; background: var(--bg-1);
+ position: sticky; top: 0;
+ }
+ .pv-label { font-size: 11px; color: var(--text-3); font-weight: 600; }
+ .pe-preview pre {
+ margin: 0; white-space: pre-wrap; word-break: break-word;
+ font: 12px/1.4 system-ui, sans-serif; color: var(--text-1);
+ }
+</style>
diff --git a/frontend/src/components/ProofPreview.svelte b/frontend/src/components/ProofPreview.svelte
new file mode 100644
index 0000000..2b57820
--- /dev/null
+++ b/frontend/src/components/ProofPreview.svelte
@@ -0,0 +1,266 @@
+<script>
+ /**
+ * A faithful, interactive miniature of a proof drawn from a style template,
+ * with two average-screenshot stand-ins. It reuses the composer's real layout
+ * maths so the footer and signatures show at their true size *relative to
+ * the panels* — impossible to judge from number fields. The real signature
+ * logo is loaded; if none is saved the box says to add one in Settings. Click
+ * the logo or the @handle to select it, then drag to move or pull a corner to
+ * resize — the change is written back into the template.
+ *
+ * `style` is the template's style blob (bindable). `logoMissing` is set true
+ * when the signature is on but no logo file exists.
+ */
+ import { onMount } from 'svelte';
+ import Konva from 'konva';
+ import {
+ layoutPanels, docSize, footerBand,
+ signatureBox, signatureOffset, signaturePairPositions, anchoredPos, anchoredOffset,
+ normalizeProofStyle, textColors, attributionLine, loadImage,
+ BG, CAPTION_SIZE, FOOTER_SIZE, SIG_SCALE, SIG_TEXT_SIZE,
+ } from '../lib/composer.js';
+ import { prefs } from '../lib/state.svelte.js';
+
+ let { style = $bindable(), logoMissing = $bindable(false) } = $props();
+
+ // Equal-size stand-ins make spacing, orientation and signature scale easy to
+ // compare without one panel's aspect ratio distorting the preview.
+ const FAKE_PANELS = [
+ { id: 'a', natural: [1600, 900], row: 0, caption: 'Ground photo' },
+ { id: 'b', natural: [1600, 900], row: 0, caption: 'Satellite' },
+ ];
+
+ let host = $state(null);
+ let cw = $state(340);
+ let stage;
+ let layer;
+ let sigImg = null; // the real logo, loaded once; null → none saved
+ let selected = null; // 'logo' | 'text' | null — what the transformer holds
+
+ // The logo's true aspect, from the loaded file (fallback keeps the box sane).
+ function logoAspect() {
+ return sigImg ? [sigImg.naturalWidth, sigImg.naturalHeight] : [220, 88];
+ }
+
+ // Panels honour the template's caption default: off → no captions (and, the
+ // band collapsing with them, no empty strip under the panels).
+ function panels(safeStyle) {
+ const withCaptions = safeStyle.captionsEnabled;
+ const vertical = safeStyle.panelDirection === 'vertical';
+ return FAKE_PANELS.map((p, i) => ({
+ ...p,
+ row: vertical ? i : 0,
+ caption: withCaptions ? p.caption : '',
+ }));
+ }
+
+ function render() {
+ if (!stage || !cw) return;
+ layer.destroyChildren();
+ const safeStyle = normalizeProofStyle(style);
+ const space = safeStyle.space;
+ const bg = safeStyle.bg ?? BG;
+ const tc = textColors(bg);
+ const text = {
+ captionSize: safeStyle.captionSize ?? CAPTION_SIZE,
+ footerSize: safeStyle.footerSize ?? FOOTER_SIZE,
+ footerEnabled: safeStyle.footerEnabled,
+ };
+ const pnls = panels(safeStyle);
+ const { width, height } = docSize(pnls, [], {}, text, [], 'grid', space);
+ const boxes = layoutPanels(pnls, text.captionSize, 'grid', space);
+ const scale = cw / width;
+ stage.size({ width: Math.round(width * scale), height: Math.round(height * scale) });
+ stage.scale({ x: scale, y: scale });
+
+ layer.add(new Konva.Rect({ name: 'bg', x: 0, y: 0, width, height, fill: bg }));
+
+ boxes.forEach((box, i) => {
+ layer.add(new Konva.Rect({
+ x: box.x, y: box.y, width: box.w, height: box.h, name: 'bg',
+ fillLinearGradientStartPoint: { x: 0, y: 0 },
+ fillLinearGradientEndPoint: { x: box.w, y: box.h },
+ fillLinearGradientColorStops: [0, '#3b4a63', 1, '#1e2637'],
+ cornerRadius: 4,
+ }));
+ layer.add(new Konva.Text({
+ x: box.x, y: box.y + box.h / 2 - box.h * 0.05, width: box.w, align: 'center',
+ text: `${pnls[i].natural[0]} × ${pnls[i].natural[1]} px`,
+ fontSize: box.h * 0.065, fill: 'rgba(255,255,255,0.55)',
+ fontFamily: 'system-ui, sans-serif', listening: false,
+ }));
+ const cap = pnls[i].caption;
+ if (cap?.trim()) {
+ layer.add(new Konva.Text({
+ x: box.x + 2, y: box.y + box.h + 9, width: box.w - 4, text: cap,
+ fontSize: text.captionSize, fill: tc.dim,
+ fontFamily: 'system-ui, sans-serif', ellipsis: true, wrap: 'none', listening: false,
+ }));
+ }
+ });
+
+ // footer
+ if (text.footerEnabled) {
+ const fs = text.footerSize;
+ layer.add(new Konva.Text({
+ x: space.pad, y: height - space.pad - footerBand(fs) + Math.round((footerBand(fs) - fs) / 2),
+ width: width - space.pad * 2, text: safeStyle.footer?.trim() || attributionLine(pnls),
+ align: safeStyle.footerAlign === 'right' ? 'right' : 'left',
+ fontSize: fs, fill: safeStyle.footerColor || tc.faint,
+ fontFamily: 'system-ui, sans-serif', ellipsis: true, wrap: 'none', listening: false,
+ }));
+ }
+
+ let logoNode = null;
+ let textNode = null;
+ const st = safeStyle.signatureText && prefs.signatureHandle?.trim() ? safeStyle.signatureText : null;
+ const pendingTextNode = st ? new Konva.Text({
+ text: prefs.signatureHandle.trim(), fontSize: st.size ?? SIG_TEXT_SIZE, fontStyle: 'bold',
+ fontFamily: 'system-ui, sans-serif', fill: st.color ?? '#ffffff',
+ opacity: st.opacity ?? 1, draggable: true,
+ }) : null;
+ const baseLogoBox = safeStyle.signature
+ ? signatureBox(safeStyle.signature, width, height, logoAspect())
+ : null;
+ const pair = pendingTextNode
+ ? signaturePairPositions(
+ safeStyle.signature, st, width, height, baseLogoBox,
+ pendingTextNode.width(), pendingTextNode.height(),
+ )
+ : null;
+
+ // logo — the real file at its true signatureBox size, or an "add one" prompt
+ if (safeStyle.signature) {
+ const box = pair?.logo ?? baseLogoBox;
+ const g = new Konva.Group({ x: box.x, y: box.y, opacity: safeStyle.signature.opacity, draggable: true });
+ if (sigImg) {
+ g.add(new Konva.Image({ image: sigImg, width: box.w, height: box.h }));
+ } else {
+ g.add(new Konva.Rect({
+ width: box.w, height: box.h, cornerRadius: 6,
+ fill: 'rgba(255,255,255,0.9)', stroke: 'rgba(0,0,0,0.25)', strokeWidth: 1,
+ }));
+ g.add(new Konva.Text({
+ width: box.w, height: box.h, padding: box.h * 0.12, align: 'center', verticalAlign: 'middle',
+ text: 'Add a logo in\nSettings → Preferences', fontSize: box.h * 0.16, fill: '#111',
+ fontFamily: 'system-ui, sans-serif',
+ }));
+ }
+ g.on('click tap', () => selectEl('logo'));
+ g.on('dragend', () => {
+ const placement = signatureOffset(safeStyle.signature, width, height, logoAspect(), g.x(), g.y());
+ style.signature = { ...safeStyle.signature, ...placement };
+ });
+ g.on('transformend', () => {
+ const scale = (safeStyle.signature.scale ?? SIG_SCALE) * g.scaleX();
+ style.signature = { ...safeStyle.signature, scale: Math.max(0.03, Math.min(0.6, scale)) };
+ });
+ layer.add(g);
+ logoNode = g;
+ }
+
+ // Text handle — its value is app-wide in Settings, while the template
+ // supplies only the opt-in slot and its placement.
+ if (st && pendingTextNode) {
+ const node = pendingTextNode;
+ const tw = node.width();
+ const th = node.height();
+ node.position(pair?.handle ?? anchoredPos(st, width, height, tw, th));
+ node.on('click tap', () => selectEl('text'));
+ node.on('dragend', () => {
+ const placement = anchoredOffset(st, width, height, tw, th, node.x(), node.y());
+ style.signatureText = { ...st, ...placement };
+ });
+ node.on('transformend', () => {
+ const size = Math.round((st.size ?? SIG_TEXT_SIZE) * node.scaleX());
+ style.signatureText = { ...st, size: Math.max(12, Math.min(300, size)) };
+ });
+ layer.add(node);
+ textNode = node;
+ }
+
+ // transformer on the selected element — corner resize, no rotation
+ const picked = selected === 'logo' ? logoNode : selected === 'text' ? textNode : null;
+ if (picked) {
+ const tr = new Konva.Transformer({
+ rotateEnabled: false, keepRatio: true, ignoreStroke: true,
+ enabledAnchors: ['top-left', 'top-right', 'bottom-left', 'bottom-right'],
+ anchorSize: 9, borderStroke: '#4c9ffe', anchorStroke: '#4c9ffe',
+ });
+ layer.add(tr);
+ tr.nodes([picked]);
+ }
+
+ layer.draw();
+ }
+
+ function selectEl(which) {
+ selected = which;
+ render();
+ }
+
+ onMount(() => {
+ stage = new Konva.Stage({ container: host, width: cw, height: 120 });
+ layer = new Konva.Layer();
+ stage.add(layer);
+ // click empty space (a background rect or the stage) to deselect
+ stage.on('click tap', (e) => {
+ if (e.target === stage || e.target.name() === 'bg') {
+ if (selected) { selected = null; render(); }
+ }
+ });
+ const ro = new ResizeObserver(() => {
+ const w = host?.clientWidth;
+ if (w && Math.abs(w - cw) > 1) cw = w;
+ });
+ if (host) {
+ cw = host.clientWidth || cw;
+ ro.observe(host);
+ }
+ // load the real signature once; a missing file flips logoMissing for the editor
+ loadImage('/api/settings/signature.png')
+ .then((img) => { sigImg = img; logoMissing = false; render(); })
+ .catch(() => { sigImg = null; logoMissing = true; render(); });
+ render();
+ return () => {
+ ro.disconnect();
+ stage?.destroy();
+ };
+ });
+
+ // Re-render whenever the template style or the container width changes.
+ $effect(() => {
+ JSON.stringify([
+ style.bg, style.space, style.captionSize, style.footerSize,
+ style.footer, style.footerEnabled, style.footerColor, style.footerAlign, style.captionsEnabled,
+ style.panelDirection,
+ style.signature, style.signatureText,
+ ]);
+ prefs.signatureHandle;
+ cw;
+ if (stage) render();
+ });
+</script>
+
+<div class="preview-frame">
+ <div class="hint">Drag the logo or account handle to move or resize it; mock panels show their source dimensions.</div>
+ <div class="canvas" bind:this={host}></div>
+</div>
+
+<style>
+ .preview-frame {
+ position: sticky;
+ top: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+ .hint { font-size: 11px; color: var(--text-3); line-height: 1.3; }
+ .canvas {
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ overflow: hidden;
+ background: var(--bg-2);
+ line-height: 0;
+ }
+</style>
diff --git a/frontend/src/components/ProofTemplateEditor.svelte b/frontend/src/components/ProofTemplateEditor.svelte
new file mode 100644
index 0000000..4e164c2
--- /dev/null
+++ b/frontend/src/components/ProofTemplateEditor.svelte
@@ -0,0 +1,373 @@
+<script>
+ /**
+ * Editor for one proof-style template (a proof's "house style"): background,
+ * panel spacing, text sizes, footer line, signature placement and preferred
+ * colours. Content-free — it never touches panels, shapes or coordinates.
+ *
+ * `data` is the template's style blob (bindable); the parent owns save/delete.
+ * Remount it per template with {#key} so the local palette re-seeds.
+ */
+ import {
+ ANNO_COLORS, SIG_ANCHORS, PANEL_DIRECTIONS, BG, textColors, normSpace,
+ newSignature, newSignatureText, SIG_SCALE, SIG_TEXT_SIZE,
+ normalizePreferredColors, normalizeProofStyle, replacePreferredColor,
+ } from '../lib/composer.js';
+ import Icon from './Icon.svelte';
+ import Modal from './Modal.svelte';
+ import ProofPreview from './ProofPreview.svelte';
+
+ let { data = $bindable() } = $props();
+ Object.assign(data, normalizeProofStyle(data));
+
+ // A few one-click backgrounds; the colour input covers anything else.
+ const BG_PRESETS = ['#0d1117', '#000000', '#ffffff', '#f4f1ea', '#1b2a4a'];
+
+ // Templates always expose seven drawing slots. Older or partial palettes are
+ // completed from the shipped colours without disturbing their saved order.
+ let palette = $state(normalizePreferredColors([
+ ...(Array.isArray(data.palette) ? data.palette : []),
+ ...ANNO_COLORS,
+ ]));
+ let customColor = $state(ANNO_COLORS[0]);
+ let selectedColor = $state(null);
+
+ function commitPalette() {
+ data.palette = [...palette];
+ // Early template drafts stored legend content here. It belongs to proofs.
+ delete data.notes;
+ delete data.legendOrder;
+ }
+
+ function openColor(index) {
+ selectedColor = selectedColor === index ? null : index;
+ customColor = palette[index];
+ }
+
+ function replaceColor(color) {
+ if (selectedColor == null) return;
+ palette = replacePreferredColor(palette, selectedColor, color);
+ commitPalette();
+ selectedColor = null;
+ }
+ commitPalette();
+
+ const space = $derived(normSpace(data.space));
+ function setSpace(key, value) {
+ data.space = { ...space, [key]: Math.max(0, Math.min(200, Number(value) || 0)) };
+ }
+
+ function setTextSize(key, value, fallback) {
+ const number = Number(value);
+ data[key] = Number.isFinite(number) ? Math.max(8, Math.min(80, number)) : fallback;
+ }
+
+ const signed = $derived(!!data.signature);
+ function toggleSignature(on) {
+ data.signature = on
+ ? (data.signature ?? newSignature())
+ : null;
+ }
+ function setSig(key, value) {
+ data.signature = key === 'anchor'
+ ? { ...data.signature, anchor: value, dx: 0, dy: 0, xRatio: undefined, yRatio: undefined }
+ : { ...data.signature, [key]: value };
+ }
+
+ // Text signature — the Settings handle laid over the panels, positioned by drag.
+ const signedText = $derived(!!data.signatureText);
+ function toggleSignatureText(on) {
+ data.signatureText = on ? (data.signatureText ?? newSignatureText()) : null;
+ }
+ function setSigText(key, value) {
+ data.signatureText = key === 'anchor'
+ ? { ...data.signatureText, anchor: value, dx: 0, dy: 0, xRatio: undefined, yRatio: undefined }
+ : { ...data.signatureText, [key]: value };
+ }
+
+ // Footer switch + colour (null colour → auto from the background).
+ const footerOn = $derived(data.footerEnabled !== false);
+ const autoFooterColor = $derived(textColors(data.bg ?? BG).faint);
+
+ // Default caption for newly added panels.
+ const captionsOn = $derived(data.captionsEnabled !== false);
+
+ // Set by the preview when the signature is on but no logo file is saved.
+ let logoMissing = $state(false);
+ // The zoomed, roomier preview for precise drag/resize.
+ let expanded = $state(false);
+</script>
+
+<div class="pt-editor">
+ <div class="pt-grid">
+ <div class="pt-fields">
+ <label class="fld">
+ <span>Background</span>
+ <span class="bg-row">
+ <input type="color" value={data.bg ?? BG} oninput={(e) => (data.bg = e.target.value)} />
+ {#each BG_PRESETS as c}
+ <button
+ type="button"
+ class="sw"
+ class:active={(data.bg ?? BG).toLowerCase() === c}
+ style:background={c}
+ title={c}
+ aria-label={`Background ${c}`}
+ onclick={() => (data.bg = c)}
+ ></button>
+ {/each}
+ </span>
+ </label>
+
+ <fieldset class="fld">
+ <span>Margins (px)</span>
+ <div class="triple">
+ <label>Outer
+ <input type="number" min="0" max="200" value={space.pad}
+ oninput={(e) => setSpace('pad', e.target.value)} />
+ </label>
+ <label>Between panels
+ <input type="number" min="0" max="200" value={space.gap}
+ oninput={(e) => setSpace('gap', e.target.value)} />
+ </label>
+ <label>Between rows
+ <input type="number" min="0" max="200" value={space.rowGap}
+ oninput={(e) => setSpace('rowGap', e.target.value)} />
+ </label>
+ </div>
+ </fieldset>
+
+ <fieldset class="fld">
+ <span>Text sizes (px)</span>
+ <div class="triple">
+ <label>Captions
+ <input type="number" min="8" max="80" value={data.captionSize}
+ oninput={(e) => setTextSize('captionSize', e.target.value, 20)} />
+ </label>
+ <label>Legend
+ <input type="number" min="8" max="80" value={data.legendSize}
+ oninput={(e) => setTextSize('legendSize', e.target.value, 20)} />
+ </label>
+ <label>Footer
+ <input type="number" min="8" max="80" value={data.footerSize}
+ oninput={(e) => setTextSize('footerSize', e.target.value, 15)} />
+ </label>
+ </div>
+ </fieldset>
+
+ <fieldset class="fld">
+ <span>
+ <label class="chk"><input type="checkbox" checked={captionsOn}
+ onchange={(e) => (data.captionsEnabled = e.target.checked)} /> Caption new panels</label>
+ </span>
+ <p class="hint">Off: panels are added blank. A caption can still be typed on any panel.</p>
+ </fieldset>
+
+ <fieldset class="fld">
+ <span>
+ <label class="chk"><input type="checkbox" checked={footerOn}
+ onchange={(e) => (data.footerEnabled = e.target.checked)} /> Show footer</label>
+ </span>
+ {#if footerOn}
+ <input type="text" placeholder="Composed with Azimut" maxlength="200"
+ bind:value={data.footer} />
+ <div class="color-row">
+ <span>Colour</span>
+ <input type="color" value={data.footerColor ?? autoFooterColor}
+ oninput={(e) => (data.footerColor = e.target.value)} />
+ {#if data.footerColor}
+ <button type="button" class="btn btn-ghost btn-sm"
+ onclick={() => (data.footerColor = null)}>Auto</button>
+ {/if}
+ </div>
+ <div class="radio-row">
+ <span>Alignment</span>
+ <label><input type="radio" value="left" checked={(data.footerAlign ?? 'left') === 'left'}
+ onchange={() => (data.footerAlign = 'left')} /> Left</label>
+ <label><input type="radio" value="right" checked={data.footerAlign === 'right'}
+ onchange={() => (data.footerAlign = 'right')} /> Right</label>
+ </div>
+ {:else}
+ <p class="hint">No band under the panels. Drop all margins for panels-only output.</p>
+ {/if}
+ </fieldset>
+
+ <fieldset class="fld">
+ <span>Layout</span>
+ <div class="radio-row">
+ <label><input type="radio" value="grid" bind:group={data.layout} /> Grid rows</label>
+ <label><input type="radio" value="free" bind:group={data.layout} /> Free (overlap)</label>
+ </div>
+ {#if data.layout !== 'free'}
+ <div class="radio-row">
+ <span>First two panels</span>
+ {#each PANEL_DIRECTIONS as direction}
+ <label><input type="radio" value={direction.id}
+ checked={(data.panelDirection ?? 'horizontal') === direction.id}
+ onchange={() => (data.panelDirection = direction.id)} /> {direction.label}</label>
+ {/each}
+ </div>
+ {/if}
+ </fieldset>
+
+ <fieldset class="fld">
+ <span>
+ <label class="chk"><input type="checkbox" checked={signed}
+ onchange={(e) => toggleSignature(e.target.checked)} /> Stamp the logo</label>
+ </span>
+ {#if signed}
+ <div class="triple">
+ <label>Corner
+ <select value={data.signature.anchor} onchange={(e) => setSig('anchor', e.target.value)}>
+ {#each SIG_ANCHORS as a}<option value={a.id}>{a.label}</option>{/each}
+ </select>
+ </label>
+ <label>Size
+ <input type="range" min="0.03" max="0.3" step="0.01"
+ value={data.signature.scale ?? SIG_SCALE}
+ oninput={(e) => setSig('scale', Number(e.target.value))} />
+ </label>
+ <label>Opacity
+ <input type="range" min="0.2" max="1" step="0.05"
+ value={data.signature.opacity ?? 0.9}
+ oninput={(e) => setSig('opacity', Number(e.target.value))} />
+ </label>
+ </div>
+ {#if logoMissing}
+ <p class="warn"><Icon name="alert" /> No logo saved yet. Add one in Settings → Preferences.</p>
+ {:else}
+ <p class="hint">The logo comes from Settings → Preferences; drag it in the preview.</p>
+ {/if}
+ {/if}
+ </fieldset>
+
+ <fieldset class="fld">
+ <span>
+ <label class="chk"><input type="checkbox" checked={signedText}
+ onchange={(e) => toggleSignatureText(e.target.checked)} /> Add account handle</label>
+ </span>
+ {#if signedText}
+ <div class="triple">
+ <label>Corner
+ <select value={data.signatureText.anchor} onchange={(e) => setSigText('anchor', e.target.value)}>
+ {#each SIG_ANCHORS as a}<option value={a.id}>{a.label}</option>{/each}
+ </select>
+ </label>
+ <label>Size
+ <input type="number" min="12" max="160"
+ value={data.signatureText.size ?? SIG_TEXT_SIZE}
+ oninput={(e) => setSigText('size', Math.max(12, Math.min(160, Number(e.target.value) || SIG_TEXT_SIZE)))} />
+ </label>
+ <label>Colour
+ <input type="color" value={data.signatureText.color ?? '#ffffff'}
+ oninput={(e) => setSigText('color', e.target.value)} />
+ </label>
+ </div>
+ <p class="hint">The account handle comes from Settings → Preferences; drag it into place in the preview.</p>
+ {/if}
+ </fieldset>
+
+ <fieldset class="fld">
+ <span>Preferred colour palette</span>
+ <p class="hint">Select a colour to replace it.</p>
+ <div class="preferred-palette" aria-label="Preferred colours">
+ {#each palette as color, i (color)}
+ <button type="button" class="preferred-colour" class:active={selectedColor === i}
+ title={`Change ${color}`} aria-label={`Change colour ${i + 1}, currently ${color}`}
+ onclick={() => openColor(i)}>
+ <span>{i + 1}</span>
+ <span class="dot" style:background={color}></span>
+ <code>{color}</code>
+ </button>
+ {/each}
+ </div>
+ {#if selectedColor != null}
+ <div class="colour-picker">
+ <span>Replace with</span>
+ <div class="colour-choices">
+ {#each ANNO_COLORS as color (color)}
+ <button type="button" class="sw colour-choice" style:background={color}
+ title={color} aria-label={`Use colour ${color}`}
+ onclick={() => replaceColor(color)}></button>
+ {/each}
+ <label class="custom-choice" title="Choose another colour">
+ <input type="color" bind:value={customColor}
+ onchange={(e) => replaceColor(e.currentTarget.value)} aria-label="Choose another colour" />
+ </label>
+ </div>
+ </div>
+ {/if}
+ </fieldset>
+ </div>
+
+ <div class="pt-preview">
+ <ProofPreview bind:style={data} bind:logoMissing />
+ <button type="button" class="btn btn-ghost btn-sm zoom-btn" onclick={() => (expanded = true)}>
+ <Icon name="maximize" /> Zoom to edit
+ </button>
+ </div>
+ </div>
+</div>
+
+{#if expanded}
+ <Modal title="Proof preview" width="min(1100px, 92vw)" onclose={() => (expanded = false)}>
+ <div class="pt-zoom">
+ <ProofPreview bind:style={data} bind:logoMissing />
+ </div>
+ </Modal>
+{/if}
+
+<style>
+ .pt-editor { display: block; }
+ .pt-grid { display: grid; grid-template-columns: 1fr 320px; gap: 16px; align-items: start; }
+ .pt-fields { display: flex; flex-direction: column; gap: 14px; min-width: 0; }
+ .fld { display: flex; flex-direction: column; gap: 6px; border: 0; margin: 0; padding: 0; }
+ .fld > span { font-size: 12px; color: var(--text-2); font-weight: 600; }
+ .fld input[type='text'], .fld input[type='number'], .fld select {
+ background: var(--bg-2); border: 1px solid var(--border); border-radius: 6px;
+ color: var(--text-1); padding: 6px 8px; font: inherit; width: 100%;
+ }
+ .bg-row { display: flex; align-items: center; gap: 6px; }
+ .bg-row input[type='color'], .color-row input[type='color'], .triple input[type='color'] {
+ width: 34px; height: 28px; padding: 0; border: 1px solid var(--border); border-radius: 6px; background: none;
+ }
+ .color-row { display: flex; align-items: center; gap: 8px; font-size: 11px; color: var(--text-3); }
+ .sw { width: 22px; height: 22px; border-radius: 5px; border: 1px solid var(--border); cursor: pointer; }
+ .sw.active { outline: 2px solid var(--accent); outline-offset: 1px; }
+ .triple { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
+ .triple label { display: flex; flex-direction: column; gap: 3px; font-size: 11px; color: var(--text-3); }
+ .radio-row, .chk { display: flex; gap: 14px; align-items: center; font-size: 13px; color: var(--text-2); }
+ .chk { gap: 6px; }
+ .hint { margin: 0; font-size: 11px; color: var(--text-3); }
+ .warn {
+ margin: 0; font-size: 11px; color: var(--warn, #e0a33e);
+ display: flex; align-items: center; gap: 5px;
+ }
+ .pt-preview { display: flex; flex-direction: column; gap: 8px; position: sticky; top: 0; }
+ .zoom-btn { align-self: flex-start; }
+ .pt-zoom { width: min(1040px, 88vw); }
+ .preferred-palette { display: flex; flex-direction: column; gap: 4px; }
+ .preferred-colour {
+ display: grid; grid-template-columns: 18px 14px 1fr; gap: 7px; align-items: center;
+ min-height: 26px; width: 100%; padding: 2px 5px; font-size: 11px;
+ color: var(--text-3); text-align: left; background: transparent;
+ border: 1px solid transparent; border-radius: 5px; cursor: pointer;
+ }
+ .preferred-colour:hover { background: var(--bg-2); }
+ .preferred-colour.active { border-color: var(--accent); background: var(--bg-2); }
+ .preferred-colour code { color: var(--text-2); }
+ .colour-picker {
+ display: flex; flex-direction: column; gap: 6px; padding: 8px;
+ border: 1px solid var(--border); border-radius: 6px; background: var(--bg-2);
+ }
+ .colour-picker > span { font-size: 11px; color: var(--text-3); }
+ .colour-choices { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
+ .colour-choice { padding: 0; }
+ .custom-choice {
+ display: block; width: 28px; height: 24px; cursor: pointer;
+ }
+ .custom-choice input {
+ width: 28px; height: 24px; padding: 0; border: 1px solid var(--border);
+ border-radius: 5px; background: none; cursor: pointer;
+ }
+ .dot { width: 12px; height: 12px; border-radius: 50%; display: inline-block; }
+</style>
diff --git a/frontend/src/lib/composer.js b/frontend/src/lib/composer.js
index eec9402..6210444 100644
--- a/frontend/src/lib/composer.js
+++ b/frontend/src/lib/composer.js
@@ -28,12 +28,91 @@ export const TWEET_GUIDES = {
};
export const ANNO_COLORS = ['#ff5252', '#40c4ff', '#ffd740', '#69f0ae', '#e040fb', '#ff9e40', '#ffffff'];
+export const MAX_ANNO_COLORS = ANNO_COLORS.length;
+export const MAX_EXPORT_DIMENSION = 16_384;
+export const MAX_EXPORT_PIXELS = 64_000_000;
+
+/** Ordered drawing palette, with invalid/duplicate colours removed. */
+export function normalizePreferredColors(colors) {
+ const source = Array.isArray(colors) && colors.length ? colors : ANNO_COLORS;
+ const seen = new Set();
+ const palette = [];
+ for (const value of source) {
+ const color = String(value ?? '').trim().toLowerCase();
+ if (!/^#[0-9a-f]{6}$/.test(color) || seen.has(color)) continue;
+ seen.add(color);
+ palette.push(color);
+ if (palette.length === MAX_ANNO_COLORS) break;
+ }
+ return palette.length ? palette : [...ANNO_COLORS];
+}
+
+/** Replace one palette slot; choosing an existing colour swaps the two slots. */
+export function replacePreferredColor(colors, index, value) {
+ const color = String(value ?? '').trim().toLowerCase();
+ const palette = normalizePreferredColors(colors);
+ if (!Number.isInteger(index) || index < 0 || index >= palette.length) return palette;
+ if (!/^#[0-9a-f]{6}$/.test(color)) return palette;
+ const existing = palette.indexOf(color);
+ if (existing >= 0 && existing !== index) {
+ [palette[index], palette[existing]] = [palette[existing], palette[index]];
+ } else {
+ palette[index] = color;
+ }
+ return palette;
+}
export const BG = '#0d1117';
export const TEXT_MAIN = '#e8edf6';
export const TEXT_DIM = '#94a3b8';
export const TEXT_FAINT = '#64748b';
+// Text palette for a light proof background, so captions/legend/footer stay
+// legible when the analyst picks a pale backdrop. textColors() chooses between
+// this and the dark palette from the background's luminance — one `bg` field
+// drives both, no second colour to keep in sync.
+export const TEXT_MAIN_LIGHT = '#0d1117';
+export const TEXT_DIM_LIGHT = '#475569';
+export const TEXT_FAINT_LIGHT = '#64748b';
+
+/** True when `hex` (#rgb or #rrggbb) is light enough to want dark text on it. */
+export function isLightColor(hex) {
+ const c = String(hex || '').trim().replace('#', '');
+ const full = c.length === 3 ? c.split('').map((x) => x + x).join('') : c;
+ if (full.length !== 6) return false;
+ const r = parseInt(full.slice(0, 2), 16);
+ const g = parseInt(full.slice(2, 4), 16);
+ const b = parseInt(full.slice(4, 6), 16);
+ if ([r, g, b].some(Number.isNaN)) return false;
+ // relative luminance (sRGB weights); above ~0.6 reads as a light backdrop
+ return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255 > 0.6;
+}
+
+/** Caption/legend/footer colours for a proof background (auto dark-on-light). */
+export function textColors(bg = BG) {
+ return isLightColor(bg)
+ ? { main: TEXT_MAIN_LIGHT, dim: TEXT_DIM_LIGHT, faint: TEXT_FAINT_LIGHT }
+ : { main: TEXT_MAIN, dim: TEXT_DIM, faint: TEXT_FAINT };
+}
+
+function boundedNumber(value, fallback, min, max) {
+ return Number.isFinite(value) ? clamp(value, min, max) : fallback;
+}
+
+function normalizedColor(value, fallback) {
+ const color = typeof value === 'string' ? value.trim().toLowerCase() : '';
+ return /^#[0-9a-f]{6}$/.test(color) ? color : fallback;
+}
+
+/** Panel spacing in doc px; malformed fields fall back to shipped defaults. */
+export function normSpace(space) {
+ return {
+ pad: boundedNumber(space?.pad, PAD, 0, 200),
+ gap: boundedNumber(space?.gap, GAP, 0, 200),
+ rowGap: boundedNumber(space?.rowGap, ROW_GAP, 0, 200),
+ };
+}
+
let idSeq = 0;
export function newId(prefix) {
return `${prefix}${Date.now().toString(36)}${(idSeq++).toString(36)}`;
@@ -66,10 +145,55 @@ export function uniqueProofTitle(base, taken) {
return `${base} ${n}`;
}
+/** Prefill a new proof from its case name without colliding with a saved proof. */
+export function proofTitleFromCase(caseName, taken = []) {
+ const base = String(caseName ?? '').trim() || DEFAULT_PROOF_TITLE;
+ return uniqueProofTitle(base, taken);
+}
+
+/**
+ * Search and category filter for the proof panel picker. Satellite captures
+ * carry `kind: satellite`; every other case image carries `kind: media`.
+ */
+export function filterProofPanelItems(items, query = '', category = 'all') {
+ const needle = String(query).trim().toLocaleLowerCase();
+ return (items ?? []).filter((item) => {
+ if (category === 'satellite' && item.kind !== 'satellite') return false;
+ if (category === 'media' && item.kind !== 'media') return false;
+ if (!needle) return true;
+ const text = [
+ item.label,
+ item.src,
+ item.meta?.provider,
+ item.meta?.date,
+ item.meta?.imagery_date,
+ ].filter(Boolean).join(' ').toLocaleLowerCase();
+ return text.includes(needle);
+ });
+}
+
+/** A proof has nothing to render until it contains at least one panel. */
+export function hasProofCanvasContent(proof) {
+ return Array.isArray(proof?.panels) && proof.panels.length > 0;
+}
+
export const CAPTION_SIZE = 20; // default caption font size (px, editable per proof)
export const LEGEND_SIZE = 20; // default legend text size
export const FOOTER_SIZE = 15; // default footer / attribution text size
+export const PANEL_DIRECTIONS = [
+ { id: 'horizontal', label: 'Side by side' },
+ { id: 'vertical', label: 'Stacked' },
+];
+
+/** Apply a template's preferred arrangement to its first two panels. */
+export function orientFirstPanels(panels, direction = 'horizontal') {
+ if (!panels?.length) return panels;
+ panels[0].row = 0;
+ if (panels.length > 1) panels[1].row = direction === 'vertical' ? 1 : 0;
+ return panels;
+}
+
/** 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);
@@ -95,6 +219,11 @@ function rowOrder(panels) {
return [...new Set(panels.map((p) => p.row ?? 0))].sort((a, b) => a - b);
}
+/** Whether any panel in row `r` carries caption text — the band collapses when none does. */
+function rowHasCaption(panels, r) {
+ return panels.some((p) => (p.row ?? 0) === r && (p.caption ?? '').trim());
+}
+
/** 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);
@@ -112,10 +241,10 @@ export function panelHeight(p) {
* 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, layout = 'grid') {
+export function layoutPanels(panels, captionSize = CAPTION_SIZE, layout = 'grid', space) {
return layout === 'free'
- ? layoutPanelsFree(panels, captionSize)
- : layoutPanelsGrid(panels, captionSize);
+ ? layoutPanelsFree(panels, captionSize, space)
+ : layoutPanelsGrid(panels, captionSize, space);
}
/**
@@ -123,9 +252,13 @@ export function layoutPanels(panels, captionSize = CAPTION_SIZE, layout = 'grid'
* height is its tallest panel and the shorter panels are bottom-aligned so
* their captions share one baseline.
*/
-function layoutPanelsGrid(panels, captionSize = CAPTION_SIZE) {
+function layoutPanelsGrid(panels, captionSize = CAPTION_SIZE, space) {
+ const { pad, gap, rowGap } = normSpace(space);
const rows = rowOrder(panels);
- const band = captionBand(captionSize);
+ // A row reserves a caption band only when one of its panels is captioned, so a
+ // caption-less proof has no empty strip under the panels (and none below the
+ // last row — the bottom "bar" a footer-less, margin-less proof would show).
+ const bandOf = (r) => (rowHasCaption(panels, r) ? captionBand(captionSize) : 0);
// width + height of each row, to centre narrower rows and stack by height
const rowWidth = new Map();
const rowHeight = new Map();
@@ -136,7 +269,7 @@ function layoutPanelsGrid(panels, captionSize = CAPTION_SIZE) {
inRow.forEach((p, k) => {
const ph = panelHeight(p);
h = Math.max(h, ph);
- w += p.natural[0] * (ph / p.natural[1]) + (k ? GAP : 0);
+ w += p.natural[0] * (ph / p.natural[1]) + (k ? gap : 0);
});
rowWidth.set(r, w);
rowHeight.set(r, h);
@@ -144,13 +277,13 @@ function layoutPanelsGrid(panels, captionSize = CAPTION_SIZE) {
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;
+ let cy = pad;
for (const r of rows) {
rowTop.set(r, cy);
- cy += rowHeight.get(r) + band + ROW_GAP;
+ cy += rowHeight.get(r) + bandOf(r) + rowGap;
}
// 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]));
+ const cursor = new Map(rows.map((r) => [r, pad + (contentW - rowWidth.get(r)) / 2]));
return panels.map((p) => {
const r = p.row ?? 0;
const ph = panelHeight(p);
@@ -159,7 +292,7 @@ function layoutPanelsGrid(panels, captionSize = CAPTION_SIZE) {
const w = p.natural[0] * scale;
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);
+ cursor.set(r, cursor.get(r) + w + gap);
return box;
});
}
@@ -172,15 +305,16 @@ function layoutPanelsGrid(panels, captionSize = CAPTION_SIZE) {
* no position yet (just added, or a grid spec toggled to free) falls back to
* where the grid would have put it, so nothing jumps when entering the mode.
*/
-export function layoutPanelsFree(panels, captionSize = CAPTION_SIZE) {
+export function layoutPanelsFree(panels, captionSize = CAPTION_SIZE, space) {
if (!panels.length) return [];
- const grid = layoutPanelsGrid(panels, captionSize); // fallback positions
+ const { pad } = normSpace(space);
+ const grid = layoutPanelsGrid(panels, captionSize, space); // fallback positions
const pos = panels.map((p, i) => ({
x: p.x ?? grid[i].x,
y: p.y ?? grid[i].y,
}));
- const dx = PAD - Math.min(...pos.map((q) => q.x));
- const dy = PAD - Math.min(...pos.map((q) => q.y));
+ const dx = pad - Math.min(...pos.map((q) => q.x));
+ const dy = pad - Math.min(...pos.map((q) => q.y));
return panels.map((p, i) => {
const ph = panelHeight(p);
const scale = ph / p.natural[1];
@@ -202,25 +336,27 @@ export function layoutPanelsFree(panels, captionSize = CAPTION_SIZE) {
* stored x/y after a drag/resize so stored coordinates always equal rendered
* ones — and can offset the stage by the same amount so nothing jumps on screen.
*/
-export function freeNormalizeDelta(panels, captionSize = CAPTION_SIZE) {
+export function freeNormalizeDelta(panels, captionSize = CAPTION_SIZE, space) {
if (!panels.length) return { dx: 0, dy: 0 };
- const grid = layoutPanelsGrid(panels, captionSize);
+ const { pad } = normSpace(space);
+ const grid = layoutPanelsGrid(panels, captionSize, space);
const xs = panels.map((p, i) => p.x ?? grid[i].x);
const ys = panels.map((p, i) => p.y ?? grid[i].y);
- return { dx: PAD - Math.min(...xs), dy: PAD - Math.min(...ys) };
+ return { dx: pad - Math.min(...xs), dy: pad - Math.min(...ys) };
}
/** Height of the stacked panel block (rows + their caption bands), no legend. */
-export function panelsBlockHeight(panels, captionSize = CAPTION_SIZE) {
+export function panelsBlockHeight(panels, captionSize = CAPTION_SIZE, space) {
+ const { rowGap } = normSpace(space);
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);
+ const band = rowHasCaption(panels, r) ? captionBand(captionSize) : 0;
total += Math.max(...inRow.map(panelHeight)) + band;
}
- return total + (rows.length - 1) * ROW_GAP;
+ return total + (rows.length - 1) * rowGap;
}
/**
@@ -228,10 +364,11 @@ export function panelsBlockHeight(panels, captionSize = CAPTION_SIZE) {
* the stacked block (every row reserves its caption band). Free: the lowest
* panel bottom, plus a caption band only under panels that actually carry one.
*/
-export function panelsBottom(panels, captionSize = CAPTION_SIZE, layout = 'grid') {
- if (!panels.length) return PAD;
- if (layout !== 'free') return PAD + panelsBlockHeight(panels, captionSize);
- const boxes = layoutPanelsFree(panels, captionSize);
+export function panelsBottom(panels, captionSize = CAPTION_SIZE, layout = 'grid', space) {
+ const { pad } = normSpace(space);
+ if (!panels.length) return pad;
+ if (layout !== 'free') return pad + panelsBlockHeight(panels, captionSize, space);
+ const boxes = layoutPanelsFree(panels, captionSize, space);
const band = captionBand(captionSize);
return Math.max(
...boxes.map((b, i) => b.y + b.h + (panels[i].caption?.trim() ? band : 0))
@@ -378,9 +515,10 @@ export function proofSource(p) {
}
/** How many columns the legend splits into for a given content width + count. */
-export function legendColumns(width, count) {
+export function legendColumns(width, count, space) {
if (count <= 1) return 1;
- const fit = Math.floor((width - PAD * 2 + GAP) / (LEGEND_COL_MIN + GAP));
+ const { pad, gap } = normSpace(space);
+ const fit = Math.floor((width - pad * 2 + gap) / (LEGEND_COL_MIN + gap));
return Math.max(1, Math.min(3, count, fit));
}
@@ -394,22 +532,24 @@ export function legendRowCount(count, columns) {
* count and every text band grows with its own font size (all editable per
* proof via `text = { captionSize, legendSize, footerSize }`).
*/
-export function docSize(panels, shapes, notes = {}, text = {}, legendOrder = [], layout = 'grid') {
+export function docSize(panels, shapes, notes = {}, text = {}, legendOrder = [], layout = 'grid', space) {
const {
captionSize = CAPTION_SIZE, legendSize = LEGEND_SIZE, footerSize = FOOTER_SIZE,
+ footerEnabled = true,
} = text;
- const boxes = layoutPanels(panels, captionSize, layout);
+ const { pad } = normSpace(space);
+ const boxes = layoutPanels(panels, captionSize, layout, space);
const width = boxes.length
- ? Math.max(...boxes.map((b) => b.x + b.w)) + PAD
+ ? Math.max(...boxes.map((b) => b.x + b.w)) + pad
: 640;
const contentW = Math.max(width, 640);
const legend = legendLines(shapes, notes, legendOrder).filter((l) => l.text);
- const cols = legendColumns(contentW, legend.length);
+ const cols = legendColumns(contentW, legend.length, space);
const legendRows = legendRowCount(legend.length, cols);
const height =
- panelsBottom(panels, captionSize, layout) +
+ panelsBottom(panels, captionSize, layout, space) +
(legend.length ? 10 + legendRows * legendLineHeight(legendSize) : 0) +
- footerBand(footerSize) + PAD;
+ (footerEnabled ? footerBand(footerSize) : 0) + pad;
return { width: contentW, height, legend, cols };
}
@@ -424,7 +564,7 @@ export const SIG_ANCHORS = [
];
export const SIG_MARGIN = PAD; // inset from the doc edge at zero offset
-export const SIG_SCALE = 0.12; // default width, as a share of the doc width
+export const SIG_SCALE = 0.08; // default logo footprint, as a share of the proof
export const SIG_OPACITY = 0.9;
/** A fresh signature record — bottom right, the corner a byline usually takes. */
@@ -435,9 +575,9 @@ export function newSignature() {
/**
* Where the signature lands in doc space: {x, y, w, h}.
*
- * Size is a *share of the doc width* (`scale`) rather than fixed pixels, so a
- * logo keeps its visual weight whether it's stamped on a lone panel or a wide
- * three-up composite. Position is an `anchor` corner plus a user `dx`/`dy` nudge
+ * Size fits inside a `scale` share of both document dimensions, so wide, square
+ * and tall PNGs start with the same visual footprint. Position is an `anchor`
+ * corner plus a user `dx`/`dy` nudge
* — the document grows every time a panel or a font size changes, so a raw x/y
* would drift off the image; an anchored offset stays put.
*
@@ -446,13 +586,18 @@ export function newSignature() {
*/
export function signatureBox(sig, docW, docH, natural) {
const [nw, nh] = natural;
- const w = docW * (sig.scale ?? SIG_SCALE);
- const h = nw > 0 ? w * (nh / nw) : 0;
+ const scale = sig.scale ?? SIG_SCALE;
+ const maxW = docW * scale;
+ const maxH = docH * scale;
+ const aspect = nw > 0 && nh > 0 ? nw / nh : 1;
+ const w = aspect >= maxW / Math.max(maxH, 1) ? maxW : maxH * aspect;
+ const h = w / aspect;
const right = (sig.anchor ?? 'br').endsWith('r');
const bottom = (sig.anchor ?? 'br').startsWith('b');
const x = right ? docW - SIG_MARGIN - w : SIG_MARGIN;
const y = bottom ? docH - SIG_MARGIN - h : SIG_MARGIN;
- return {
+ const relative = relativePlacement(sig, docW, docH, w, h);
+ return relative ?? {
x: clamp(x + (sig.dx ?? 0), 0, Math.max(0, docW - w)),
y: clamp(y + (sig.dy ?? 0), 0, Math.max(0, docH - h)),
w,
@@ -460,17 +605,131 @@ export function signatureBox(sig, docW, docH, natural) {
};
}
+/** Whether an anchored item is still at its untouched corner position. */
+function hasDefaultPlacement(item) {
+ return item
+ && !Number.isFinite(item.xRatio)
+ && !Number.isFinite(item.yRatio)
+ && (item.dx ?? 0) === 0
+ && (item.dy ?? 0) === 0;
+}
+
+/**
+ * Default logo + account-handle stack. When both items still share an untouched
+ * corner, the logo sits above the centered handle. Once either item is moved or
+ * assigned another corner, callers use their independent positions instead.
+ */
+export function signaturePairPositions(
+ signature, signatureText, docW, docH, logoBox, handleW, handleH,
+) {
+ if (!logoBox || !hasDefaultPlacement(signature) || !hasDefaultPlacement(signatureText)) return null;
+ if ((signature.anchor ?? 'br') !== (signatureText.anchor ?? 'br')) return null;
+
+ const anchor = signature.anchor ?? 'br';
+ const right = anchor.endsWith('r');
+ const bottom = anchor.startsWith('b');
+ const gap = Math.max(8, Math.round(handleH * 0.3));
+ const groupW = Math.max(logoBox.w, handleW);
+ const groupH = logoBox.h + gap + handleH;
+ const groupX = right ? docW - SIG_MARGIN - groupW : SIG_MARGIN;
+ const groupY = bottom ? docH - SIG_MARGIN - groupH : SIG_MARGIN;
+ const x = clamp(groupX, 0, Math.max(0, docW - groupW));
+ const y = clamp(groupY, 0, Math.max(0, docH - groupH));
+
+ return {
+ logo: { ...logoBox, x: x + (groupW - logoBox.w) / 2, y },
+ handle: { x: x + (groupW - handleW) / 2, y: y + logoBox.h + gap },
+ };
+}
+
function clamp(v, lo, hi) {
return Math.max(lo, Math.min(hi, v));
}
+/** Resolve a dragged placement as a share of the available document area. */
+function relativePlacement(a, docW, docH, w, h) {
+ if (!Number.isFinite(a?.xRatio) || !Number.isFinite(a?.yRatio)) return null;
+ const maxX = Math.max(0, docW - w);
+ const maxY = Math.max(0, docH - h);
+ return {
+ x: clamp(a.xRatio, 0, 1) * maxX,
+ y: clamp(a.yRatio, 0, 1) * maxY,
+ w,
+ h,
+ };
+}
+
+/**
+ * {x, y} of a w×h box anchored to a document corner with a `dx`/`dy` nudge,
+ * clamped inside the document. The general form behind signatureBox — used by
+ * the text signature too, whose width is measured at render time.
+ */
+export function anchoredPos(a, docW, docH, w, h, margin = SIG_MARGIN) {
+ const relative = relativePlacement(a, docW, docH, w, h);
+ if (relative) return { x: relative.x, y: relative.y };
+ const right = (a?.anchor ?? 'br').endsWith('r');
+ const bottom = (a?.anchor ?? 'br').startsWith('b');
+ const x = right ? docW - margin - w : margin;
+ const y = bottom ? docH - margin - h : margin;
+ return {
+ x: clamp(x + (a?.dx ?? 0), 0, Math.max(0, docW - w)),
+ y: clamp(y + (a?.dy ?? 0), 0, Math.max(0, docH - h)),
+ };
+}
+
+/** The `dx`/`dy` placing an anchored box's top-left at (x, y) — inverse of anchoredPos. */
+export function anchoredOffset(a, docW, docH, w, h, x, y, margin = SIG_MARGIN) {
+ const base = anchoredPos({ ...a, dx: 0, dy: 0 }, docW, docH, w, h, margin);
+ const maxX = Math.max(0, docW - w);
+ const maxY = Math.max(0, docH - h);
+ return {
+ dx: x - base.x,
+ dy: y - base.y,
+ xRatio: maxX ? clamp(x / maxX, 0, 1) : 0,
+ yRatio: maxY ? clamp(y / maxY, 0, 1) : 0,
+ };
+}
+
+// Default doc-pixel height of a text signature (the Settings handle laid over
+// the panels). The text itself is deliberately not stored in a proof/template:
+// it is the analyst's app-wide identity, like the signature logo.
+export const SIG_TEXT_SIZE = 28;
+
+/** A fresh text-signature record — a handle in the bottom-right, over the panels. */
+export function newSignatureText() {
+ return { anchor: 'br', dx: 0, dy: 0, size: SIG_TEXT_SIZE, color: '#ffffff', opacity: 1 };
+}
+
+/** Copy a text-signature slot while dropping the legacy per-proof handle text. */
+export function textSignatureStyle(signatureText) {
+ if (!signatureText || typeof signatureText !== 'object' || Array.isArray(signatureText)) return null;
+ const style = {
+ anchor: ['tl', 'tr', 'bl', 'br'].includes(signatureText.anchor) ? signatureText.anchor : 'br',
+ dx: boundedNumber(signatureText.dx, 0, -100_000, 100_000),
+ dy: boundedNumber(signatureText.dy, 0, -100_000, 100_000),
+ size: boundedNumber(signatureText.size, SIG_TEXT_SIZE, 12, 300),
+ color: normalizedColor(signatureText.color, '#ffffff'),
+ opacity: boundedNumber(signatureText.opacity, 1, 0, 1),
+ };
+ if (Number.isFinite(signatureText.xRatio)) style.xRatio = clamp(signatureText.xRatio, 0, 1);
+ if (Number.isFinite(signatureText.yRatio)) style.yRatio = clamp(signatureText.yRatio, 0, 1);
+ return style;
+}
+
/**
* The `dx`/`dy` that puts the signature's top-left at doc point (x, y) — the
* inverse of signatureBox's anchoring, for writing a drag back to the spec.
*/
export function signatureOffset(sig, docW, docH, natural, x, y) {
const base = signatureBox({ ...sig, dx: 0, dy: 0 }, docW, docH, natural);
- return { dx: x - base.x, dy: y - base.y };
+ const maxX = Math.max(0, docW - base.w);
+ const maxY = Math.max(0, docH - base.h);
+ return {
+ dx: x - base.x,
+ dy: y - base.y,
+ xRatio: maxX ? clamp(x / maxX, 0, 1) : 0,
+ yRatio: maxY ? clamp(y / maxY, 0, 1) : 0,
+ };
}
/** Serializable spec from runtime state (drops live image objects). */
@@ -485,11 +744,23 @@ export function toSpec(proof) {
legendSize: proof.legendSize ?? LEGEND_SIZE,
footerSize: proof.footerSize ?? FOOTER_SIZE,
footer: proof.footer?.trim() ? proof.footer.trim() : null, // null → default attribution line
+ footerEnabled: proof.footerEnabled !== false, // false → no footer line at all
+ footerColor: proof.footerColor ?? null, // null → auto from the background
+ footerAlign: proof.footerAlign === 'right' ? 'right' : 'left',
+ captionsEnabled: proof.captionsEnabled !== false, // default caption for newly added panels
+ bg: proof.bg ?? BG, // proof background fill; text colours follow it (textColors)
+ space: normSpace(proof.space), // panel spacing {pad, gap, rowGap}
layout: proof.layout ?? 'grid', // 'grid' (rows) | 'free' (per-panel x/y, overlap allowed)
+ panelDirection: proof.layout !== 'free' && proof.panels?.length > 1
+ ? ((proof.panels[0].row ?? 0) === (proof.panels[1].row ?? 0) ? 'horizontal' : 'vertical')
+ : (proof.panelDirection === 'vertical' ? 'vertical' : 'horizontal'),
// null → unsigned. The logo itself lives in the workspace, never in the
// spec: a shared case reads the same, it just renders no signature without
// the file (see config.signature_path).
signature: proof.signature ? { ...proof.signature } : null,
+ // The handle value lives in Settings; this stores only its optional slot.
+ signatureText: textSignatureStyle(proof.signatureText),
+ palette: normalizePreferredColors(proof.palette),
notes: { ...(proof.notes ?? {}) },
legendOrder: [...(proof.legendOrder ?? [])],
panels: proof.panels.map((p) => ({
@@ -507,11 +778,110 @@ export function toSpec(proof) {
};
}
+// ---- reusable house-style templates -----------------------------------------
+
+/**
+ * A content-free house style extracted from a proof (or a loaded spec): the
+ * fields that make a proof look like "yours" — background, spacing, layout
+ * mode, text sizes, footer line, signature placement and preferred colours.
+ * Never the panels, shapes, legend text, title, coordinates or source.
+ */
+export function templateFromProof(proof) {
+ return normalizeProofStyle({
+ bg: proof.bg ?? BG,
+ space: normSpace(proof.space),
+ layout: proof.layout ?? 'grid',
+ captionSize: proof.captionSize ?? CAPTION_SIZE,
+ legendSize: proof.legendSize ?? LEGEND_SIZE,
+ footerSize: proof.footerSize ?? FOOTER_SIZE,
+ footer: proof.footer ?? '',
+ footerEnabled: proof.footerEnabled !== false,
+ footerColor: proof.footerColor ?? null,
+ footerAlign: proof.footerAlign === 'right' ? 'right' : 'left',
+ captionsEnabled: proof.captionsEnabled !== false,
+ panelDirection: proof.layout !== 'free' && proof.panels?.length > 1
+ ? ((proof.panels[0].row ?? 0) === (proof.panels[1].row ?? 0) ? 'horizontal' : 'vertical')
+ : (proof.panelDirection === 'vertical' ? 'vertical' : 'horizontal'),
+ signature: proof.signature ? { ...proof.signature } : null,
+ signatureText: textSignatureStyle(proof.signatureText),
+ palette: normalizePreferredColors(proof.palette),
+ });
+}
+
+function normalizedSignature(signature) {
+ if (!signature || typeof signature !== 'object' || Array.isArray(signature)) return null;
+ const style = {
+ anchor: ['tl', 'tr', 'bl', 'br'].includes(signature.anchor) ? signature.anchor : 'br',
+ dx: boundedNumber(signature.dx, 0, -100_000, 100_000),
+ dy: boundedNumber(signature.dy, 0, -100_000, 100_000),
+ scale: boundedNumber(signature.scale, SIG_SCALE, 0.03, 0.6),
+ opacity: boundedNumber(signature.opacity, SIG_OPACITY, 0, 1),
+ };
+ if (Number.isFinite(signature.xRatio)) style.xRatio = clamp(signature.xRatio, 0, 1);
+ if (Number.isFinite(signature.yRatio)) style.yRatio = clamp(signature.yRatio, 0, 1);
+ return style;
+}
+
+/** Canonical, content-free proof style safe to feed into preview/render code. */
+export function normalizeProofStyle(style = {}) {
+ const source = style && typeof style === 'object' && !Array.isArray(style) ? style : {};
+ return {
+ bg: normalizedColor(source.bg, BG),
+ space: normSpace(source.space),
+ layout: source.layout === 'free' ? 'free' : 'grid',
+ captionSize: boundedNumber(source.captionSize, CAPTION_SIZE, 8, 80),
+ legendSize: boundedNumber(source.legendSize, LEGEND_SIZE, 8, 80),
+ footerSize: boundedNumber(source.footerSize, FOOTER_SIZE, 8, 80),
+ footer: typeof source.footer === 'string' ? source.footer.slice(0, 200) : '',
+ footerEnabled: typeof source.footerEnabled === 'boolean' ? source.footerEnabled : true,
+ footerColor: source.footerColor == null ? null : normalizedColor(source.footerColor, null),
+ footerAlign: source.footerAlign === 'right' ? 'right' : 'left',
+ captionsEnabled: typeof source.captionsEnabled === 'boolean' ? source.captionsEnabled : true,
+ panelDirection: source.panelDirection === 'vertical' ? 'vertical' : 'horizontal',
+ signature: normalizedSignature(source.signature),
+ signatureText: textSignatureStyle(source.signatureText),
+ palette: normalizePreferredColors(source.palette),
+ };
+}
+
+/**
+ * Apply a house style onto a proof, mutating it in place. Panel content,
+ * shapes, title, coordinates and source stay untouched; the first pair's rows
+ * may change when the template specifies their direction. Legend text and its
+ * order are content, so templates leave both untouched.
+ */
+export function applyProofStyle(proof, style, available = {}) {
+ if (!style) return proof;
+ const source = typeof style === 'object' && !Array.isArray(style) ? style : {};
+ const normalized = normalizeProofStyle(source);
+ if ('bg' in source) proof.bg = normalized.bg;
+ if ('space' in source) proof.space = normalized.space;
+ if ('layout' in source) proof.layout = normalized.layout;
+ if ('captionSize' in source) proof.captionSize = normalized.captionSize;
+ if ('legendSize' in source) proof.legendSize = normalized.legendSize;
+ if ('footerSize' in source) proof.footerSize = normalized.footerSize;
+ if ('footer' in source) proof.footer = normalized.footer;
+ if ('footerEnabled' in source) proof.footerEnabled = normalized.footerEnabled;
+ if ('footerColor' in source) proof.footerColor = normalized.footerColor;
+ if ('footerAlign' in source) proof.footerAlign = normalized.footerAlign;
+ if ('captionsEnabled' in source) proof.captionsEnabled = normalized.captionsEnabled;
+ if ('panelDirection' in source) {
+ proof.panelDirection = normalized.panelDirection;
+ orientFirstPanels(proof.panels ?? [], proof.panelDirection);
+ }
+ proof.signature = normalized.signature && available.logo !== false ? normalized.signature : null;
+ proof.signatureText = normalized.signatureText && available.handle !== false
+ ? normalized.signatureText
+ : null;
+ if ('palette' in source) proof.palette = normalized.palette;
+ return 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,
+ * spread leaves points-based shapes with a proxied `points` array,
* which silently broke copy for those kinds — and fully detaches the copy.
*/
export function copyShapeSpec(shape) {
@@ -522,7 +892,7 @@ export function copyShapeSpec(shape) {
/**
* 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
+ * Points-based kinds 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) {
@@ -610,30 +980,257 @@ export function dedupeBySrc(items) {
*
* 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.
+ * Exhaustive search stays useful for small proofs. Larger documents use a
+ * deterministic balanced-row search so runtime remains bounded.
*/
export function autoLayoutRows(
- panels, shapes = [], notes = {}, text = {}, target = TWEET_GUIDES['16:9'],
+ panels, shapes = [], notes = {}, text = {}, target = TWEET_GUIDES['16:9'], space,
) {
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 measure = (rows) => {
const candidate = panels.map((p, i) => ({ ...p, row: rows[i], scale: 1 }));
- const { width, height } = docSize(candidate, shapes, notes, text);
+ const { width, height } = docSize(candidate, shapes, notes, text, [], 'grid', space);
const score = Math.abs(width / height - target);
if (!best || score < best.score) best = { score, rows };
+ };
+
+ const exhaustiveLimit = 12;
+ if (n <= exhaustiveLimit) {
+ const combos = 2 ** (n - 1);
+ for (let mask = 0; mask < combos; mask++) {
+ let row = 0;
+ const rows = [0];
+ for (let i = 1; i < n; i++) {
+ if (mask & (2 ** (i - 1))) row += 1;
+ rows.push(row);
+ }
+ measure(rows);
+ }
+ return best.rows;
+ }
+
+ const weights = panels.map((panel) => {
+ const width = panel?.natural?.[0];
+ const height = panel?.natural?.[1];
+ return Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0
+ ? width / height
+ : 1;
+ });
+ const total = weights.reduce((sum, weight) => sum + weight, 0);
+ const maxRows = Math.min(n, 64);
+ for (let rowCount = 1; rowCount <= maxRows; rowCount++) {
+ const rows = [];
+ let row = 0;
+ let cumulative = 0;
+ for (let i = 0; i < n; i++) {
+ rows.push(row);
+ cumulative += weights[i];
+ const remainingItems = n - i - 1;
+ const remainingRows = rowCount - row - 1;
+ if (
+ row < rowCount - 1
+ && (remainingItems === remainingRows || cumulative >= total * (row + 1) / rowCount)
+ ) {
+ row += 1;
+ }
+ }
+ measure(rows);
}
return best.rows;
}
+/** Safe canvas export settings for a measured proof document. */
+export function proofExportOptions(width, height) {
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
+ throw new RangeError('Proof dimensions are invalid.');
+ }
+ const pixelRatio = Math.min(Math.max(1800 / width, 0.75), 2);
+ const outputWidth = Math.ceil(width * pixelRatio);
+ const outputHeight = Math.ceil(height * pixelRatio);
+ if (
+ outputWidth > MAX_EXPORT_DIMENSION
+ || outputHeight > MAX_EXPORT_DIMENSION
+ || outputWidth * outputHeight > MAX_EXPORT_PIXELS
+ ) {
+ throw new RangeError('Proof is too large to export. Reduce its panel count or spacing.');
+ }
+ return { pixelRatio, outputWidth, outputHeight };
+}
+
+// ---- editor geometry & ordering (pure helpers behind the canvas gestures) ---
+
+/**
+ * Remap a point from one panel's natural-pixel space into another's, via doc
+ * space. `fromBox`/`toBox` are layout boxes ({x, y, scale}); used when a shape
+ * is dragged off its panel onto another so it keeps its on-screen position.
+ */
+export function remapPanelXY(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,
+ };
+}
+
+/**
+ * Topmost panel box under a doc-space point, or null. `boxes` is the layout in
+ * front→back order (array order = z-order), so the first hit wins. Returns the
+ * box, its index, and the point in that panel's natural pixels ({nx, ny}).
+ */
+export function panelHitTest(boxes, point) {
+ for (let i = 0; i < boxes.length; i++) {
+ const b = boxes[i];
+ if (point.x >= b.x && point.x <= b.x + b.w && point.y >= b.y && point.y <= b.y + b.h) {
+ return { index: i, box: b, nx: (point.x - b.x) / b.scale, ny: (point.y - b.y) / b.scale };
+ }
+ }
+ return null;
+}
+
+/**
+ * Index to swap `index` with when nudging it by `delta` (±1) while staying in
+ * its own group: the nearest item in that direction sharing its group key
+ * (`keyOf(item)` → a panel's row, a shape's panel). -1 when none (group edge).
+ */
+export function groupNeighborIndex(items, index, delta, keyOf) {
+ const key = keyOf(items[index]);
+ let target = index + delta;
+ while (target >= 0 && target < items.length && keyOf(items[target]) !== key) {
+ target += delta;
+ }
+ return target >= 0 && target < items.length && keyOf(items[target]) === key ? target : -1;
+}
+
+/** Whether `index` has a same-group item before it (delta<0) or after it (delta>0). */
+export function hasGroupNeighbor(items, index, delta, keyOf) {
+ const key = keyOf(items[index]);
+ const side = delta < 0 ? items.slice(0, index) : items.slice(index + 1);
+ return side.some((it) => keyOf(it) === key);
+}
+
+/**
+ * Dense 0..n-1 row numbers for panels whose `row` indices went sparse after a
+ * move emptied one. Ascending distinct rows map to 0,1,2,…; returns one value
+ * per panel (aligned with `panels`) for the caller to assign back in place.
+ */
+export function denseRowValues(panels) {
+ const order = [...new Set(panels.map((p) => p.row ?? 0))].sort((a, b) => a - b);
+ const remap = new Map(order.map((r, i) => [r, i]));
+ return panels.map((p) => remap.get(p.row ?? 0));
+}
+
+/** Clamp a panel scale after a `delta`, rounded to whole percent. */
+export function clampPanelScale(current, delta, min, max) {
+ return Math.round(Math.min(max, Math.max(min, (current ?? 1) + delta)) * 100) / 100;
+}
+
+/**
+ * Drop the duplicate final vertex a double-click leaves on a drawn curve: if
+ * the last point sits within `threshold` doc px of the previous one, trim it.
+ * `points` is a flat [x0,y0,x1,y1,…] array; returns a (possibly shorter) copy.
+ */
+export function trimClosingDuplicate(points, threshold = 3) {
+ const n = points.length;
+ if (n >= 4 && Math.hypot(points[n - 2] - points[n - 4], points[n - 1] - points[n - 3]) < threshold) {
+ return points.slice(0, n - 2);
+ }
+ return points.slice();
+}
+
+/**
+ * Lightly smooth a pointer-drawn polyline. Samples closer than `minDistance`
+ * are folded together first, then one weighted moving-average pass removes
+ * hand jitter while preserving both endpoints.
+ */
+export function smoothFreehandPoints(points, minDistance = 1) {
+ if (!Array.isArray(points) || points.length < 4) return [...(points ?? [])];
+ const threshold = Math.max(0, minDistance);
+ const sampled = [points[0], points[1]];
+ for (let i = 2; i < points.length - 2; i += 2) {
+ const lx = sampled[sampled.length - 2];
+ const ly = sampled[sampled.length - 1];
+ if (Math.hypot(points[i] - lx, points[i + 1] - ly) > threshold) {
+ sampled.push(points[i], points[i + 1]);
+ }
+ }
+
+ const endX = points[points.length - 2];
+ const endY = points[points.length - 1];
+ if (sampled.length === 2) sampled.push(endX, endY);
+ else {
+ const lx = sampled[sampled.length - 2];
+ const ly = sampled[sampled.length - 1];
+ if (Math.hypot(endX - lx, endY - ly) > threshold) sampled.push(endX, endY);
+ else {
+ sampled[sampled.length - 2] = endX;
+ sampled[sampled.length - 1] = endY;
+ }
+ }
+ if (sampled.length < 6) return sampled;
+
+ const smoothed = [sampled[0], sampled[1]];
+ for (let i = 2; i < sampled.length - 2; i += 2) {
+ smoothed.push(
+ (sampled[i - 2] + sampled[i] * 2 + sampled[i + 2]) / 4,
+ (sampled[i - 1] + sampled[i + 1] * 2 + sampled[i + 3]) / 4,
+ );
+ }
+ smoothed.push(sampled[sampled.length - 2], sampled[sampled.length - 1]);
+ return smoothed;
+}
+
+/** Build a persisted freehand shape, or reject a click/tiny accidental drag. */
+export function freehandShape(points, { minDistance = 1, minLength = 5 } = {}) {
+ const smoothed = smoothFreehandPoints(points, minDistance);
+ let length = 0;
+ for (let i = 2; i < smoothed.length; i += 2) {
+ length += Math.hypot(smoothed[i] - smoothed[i - 2], smoothed[i + 1] - smoothed[i - 1]);
+ }
+ return smoothed.length >= 4 && length > minLength
+ ? { kind: 'freehand', points: smoothed, tension: 0.25 }
+ : null;
+}
+
+/**
+ * Whether the legend note on `oldColor` should follow a shape recolored to
+ * `newColor`: only when `newColor` carries no note yet and no *other* shape
+ * still uses `oldColor`, so the note is neither stranded on an unused color nor
+ * stolen from shapes that keep it. `moving` is the shape being recolored.
+ */
+export function canReassignLegendNote(notes, oldColor, newColor, shapes, moving) {
+ return Boolean(
+ notes?.[oldColor] && !notes?.[newColor] &&
+ !shapes.some((s) => s !== moving && s.color === oldColor),
+ );
+}
+
+// ---- saved-proof case queries ----------------------------------------------
+
+/** Filed proof entities in a case (those whose `attrs.spec` is `proofs/*.json`). */
+export function savedProofEntities(entities) {
+ return (entities ?? []).filter((e) => {
+ const s = e.attrs?.spec;
+ return typeof s === 'string' && s.startsWith('proofs/') && s.endsWith('.json');
+ });
+}
+
+/** Slugs (filename without `proofs/….json`) of every saved proof — the collision set. */
+export function savedProofSlugs(entities) {
+ return new Set(savedProofEntities(entities).map((e) => e.attrs.spec.slice(7, -5)));
+}
+
+/** Titles of every saved proof, so a fresh title can read apart from them. */
+export function savedProofTitles(entities) {
+ return new Set(savedProofEntities(entities).map((e) => e.label ?? ''));
+}
+
+/** Title of the saved proof with slug `name`, for the overwrite prompt. */
+export function savedProofTitle(entities, name) {
+ const e = savedProofEntities(entities).find((x) => x.attrs.spec === `proofs/${name}.json`);
+ return e?.label ?? name;
+}
+
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
index d34a279..666363c 100644
--- a/frontend/src/lib/composer.test.js
+++ b/frontend/src/lib/composer.test.js
@@ -7,8 +7,18 @@ import {
autoCoords, formatCoords, resolveSourceUrls, autoSource, autoSourceUrls,
proofCoordsText, proofSource, orderedFeatureColors, legendLines,
dedupeBySrc, isSatelliteCapture, satPanelInput, mediaPanelInput,
- SIG_MARGIN, SIG_SCALE, newSignature, signatureBox, signatureOffset,
- proofSlug, uniqueProofTitle, DEFAULT_PROOF_TITLE,
+ SIG_MARGIN, SIG_SCALE, newSignature, signatureBox, signatureOffset, signaturePairPositions,
+ proofSlug, uniqueProofTitle, proofTitleFromCase, DEFAULT_PROOF_TITLE,
+ filterProofPanelItems, hasProofCanvasContent,
+ remapPanelXY, panelHitTest, groupNeighborIndex, hasGroupNeighbor,
+ denseRowValues, clampPanelScale, trimClosingDuplicate, smoothFreehandPoints,
+ freehandShape, canReassignLegendNote,
+ savedProofEntities, savedProofSlugs, savedProofTitles, savedProofTitle,
+ BG, ANNO_COLORS, MAX_ANNO_COLORS, normSpace, isLightColor, textColors,
+ normalizePreferredColors, replacePreferredColor,
+ TEXT_MAIN, TEXT_MAIN_LIGHT, templateFromProof, applyProofStyle, normalizeProofStyle,
+ anchoredPos, anchoredOffset, newSignatureText, SIG_TEXT_SIZE,
+ orientFirstPanels, proofExportOptions,
} from './composer.js';
// natural is [width, height]; PANEL_H drives the per-row scale.
@@ -36,7 +46,7 @@ describe('layoutPanels — single row (backward compatible)', () => {
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 panels = [landscape(1000, 500, { row: 0, caption: 'a' }), landscape(1000, 500, { row: 1, caption: 'b' })];
const boxes = layoutPanels(panels);
expect(boxes[0].y).toBe(PAD);
expect(boxes[1].y).toBe(PAD + (PANEL_H + captionBand() + ROW_GAP));
@@ -58,7 +68,7 @@ describe('layoutPanels — stacked rows', () => {
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 panels = [landscape(1000, 500, { row: 0, caption: 'a' }), landscape(1000, 500, { row: 5, caption: 'b' })];
const boxes = layoutPanels(panels);
expect(boxes[1].y).toBe(PAD + (PANEL_H + captionBand() + ROW_GAP));
});
@@ -93,8 +103,8 @@ describe('layoutPanels — per-panel scale', () => {
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 }),
+ landscape(1000, 500, { row: 0, scale: 2, caption: 'a' }),
+ landscape(1000, 500, { row: 1, scale: 1, caption: 'b' }),
];
const boxes = layoutPanels(panels);
expect(boxes[1].y).toBe(PAD + (PANEL_H * 2 + captionBand() + ROW_GAP));
@@ -195,27 +205,43 @@ describe('captionBand + panelsBlockHeight', () => {
});
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 })];
+ const oneRow = [landscape(1000, 500, { caption: 'c' })];
+ const twoRows = [landscape(1000, 500, { row: 0, caption: 'a' }), landscape(1000, 500, { row: 1, caption: 'b' })];
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 })];
+ const rows = [landscape(1000, 500, { row: 0, caption: 'a' }), landscape(1000, 500, { row: 1, caption: 'b' })];
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: 2, caption: 'a' }),
landscape(1000, 500, { row: 0, scale: 1 }),
- landscape(1000, 500, { row: 1, scale: 0.5 }),
+ landscape(1000, 500, { row: 1, scale: 0.5, caption: 'b' }),
];
const expected =
(PANEL_H * 2 + captionBand()) + (PANEL_H * 0.5 + captionBand()) + ROW_GAP;
expect(panelsBlockHeight(panels)).toBe(expected);
});
+
+ it('collapses the caption band on a row with no caption text', () => {
+ // caption-less panels leave no empty strip: the block is just the panels
+ expect(panelsBlockHeight([landscape()])).toBe(PANEL_H);
+ const twoRows = [landscape(1000, 500, { row: 0 }), landscape(1000, 500, { row: 1 })];
+ expect(panelsBlockHeight(twoRows)).toBe(2 * PANEL_H + ROW_GAP);
+ // only the captioned row keeps its band
+ const mixed = [landscape(1000, 500, { row: 0, caption: 'a' }), landscape(1000, 500, { row: 1 })];
+ expect(panelsBlockHeight(mixed)).toBe(2 * PANEL_H + captionBand() + ROW_GAP);
+ });
+
+ it('stacks caption-less rows tighter (no band between them)', () => {
+ const panels = [landscape(1000, 500, { row: 0 }), landscape(1000, 500, { row: 1 })];
+ const boxes = layoutPanels(panels);
+ expect(boxes[1].y).toBe(PAD + PANEL_H + ROW_GAP);
+ });
});
describe('text band sizes', () => {
@@ -232,13 +258,13 @@ describe('text band sizes', () => {
describe('docSize', () => {
it('sizes a single panel with no legend', () => {
- const { width, height } = docSize([landscape(1000, 500)], [], {});
+ const { width, height } = docSize([landscape(1000, 500, { caption: 'c' })], [], {});
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 panels = [landscape(1000, 500, { caption: 'c' })];
const shapes = [{ kind: 'rect', color: '#ff5252', panel: 'p1' }];
const notes = { '#ff5252': 'road' };
const text = { captionSize: 30, legendSize: 24, footerSize: 20 };
@@ -467,6 +493,28 @@ describe('autoLayoutRows — magic tweet fit', () => {
const tall = autoLayoutRows(panels, [], {}, {}, TWEET_GUIDES['4:5']);
expect(Math.max(...tall)).toBeGreaterThanOrEqual(Math.max(...wide));
});
+
+ it.each([18, 32])('keeps %i panels on the bounded layout path', (count) => {
+ const rows = autoLayoutRows(Array.from({ length: count }, () => sq()));
+ expect(rows).toHaveLength(count);
+ expect(rows[0]).toBe(0);
+ for (let i = 1; i < rows.length; i++) {
+ expect(rows[i] - rows[i - 1]).toBeGreaterThanOrEqual(0);
+ expect(rows[i] - rows[i - 1]).toBeLessThanOrEqual(1);
+ }
+ });
+
+ it('uses active spacing when choosing row breaks', () => {
+ const panels = [landscape(1658, 500), landscape(569, 500), landscape(880, 500)];
+ const tight = autoLayoutRows(panels, [], {}, {}, TWEET_GUIDES['16:9'], {
+ pad: 20, gap: 0, rowGap: 0,
+ });
+ const wide = autoLayoutRows(panels, [], {}, {}, TWEET_GUIDES['16:9'], {
+ pad: 20, gap: 200, rowGap: 200,
+ });
+ expect(tight).toEqual([0, 1, 1]);
+ expect(wide).toEqual([0, 0, 1]);
+ });
});
describe('copyShapeSpec — clipboard copy of any shape kind', () => {
@@ -476,11 +524,11 @@ describe('copyShapeSpec — clipboard copy of any shape kind', () => {
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 regression: line/arrow/curve/freehand 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']) {
+ it('copies the whole points array of line / arrow / curve / freehand kinds', () => {
+ for (const kind of ['line', 'arrow', 'curve', 'freehand']) {
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] });
}
@@ -504,7 +552,7 @@ describe('offsetShape — copy / paste / duplicate', () => {
expect(out).toMatchObject({ x: 36, y: 46, w: 5, h: 5, panel: 'p1' });
});
- it('shifts every vertex of points-based kinds (line/arrow/curve)', () => {
+ it('shifts every vertex of points-based kinds', () => {
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]);
@@ -518,6 +566,29 @@ describe('offsetShape — copy / paste / duplicate', () => {
});
});
+describe('freehand strokes', () => {
+ it('dampens pointer jitter while preserving both endpoints', () => {
+ expect(smoothFreehandPoints([0, 0, 5, 10, 10, 0], 0)).toEqual([
+ 0, 0, 5, 5, 10, 0,
+ ]);
+ });
+
+ it('drops samples that are too close to matter on screen', () => {
+ expect(smoothFreehandPoints([0, 0, 0.2, 0.1, 0.4, -0.1, 10, 0], 2)).toEqual([
+ 0, 0, 10, 0,
+ ]);
+ });
+
+ it('builds a lightly tensioned stroke and rejects accidental tiny drags', () => {
+ expect(freehandShape([0, 0, 1, 1], { minDistance: 0, minLength: 5 })).toBeNull();
+ expect(freehandShape([0, 0, 5, 10, 10, 0], { minDistance: 0, minLength: 5 })).toEqual({
+ kind: 'freehand',
+ points: [0, 0, 5, 5, 10, 0],
+ tension: 0.25,
+ });
+ });
+});
+
describe('coordinates — auto-derive + fallback', () => {
const geo = (lat, lon) => ({ meta: { kind: 'satellite', lat, lon } });
const plain = () => ({ meta: { kind: 'media' } });
@@ -726,12 +797,18 @@ describe('signatureBox — anchoring', () => {
const natural = [200, 100]; // 2:1 logo
const sig = (extra = {}) => ({ ...newSignature(), ...extra });
- it('sizes the logo as a share of the doc width, keeping its aspect', () => {
+ it('sizes the logo inside a proof-relative footprint, keeping its aspect', () => {
const box = signatureBox(sig({ scale: 0.1 }), 1000, 800, natural);
expect(box.w).toBe(100);
expect(box.h).toBe(50); // 2:1 preserved
});
+ it('caps a tall PNG inside the same standard footprint', () => {
+ const box = signatureBox(sig({ scale: 0.1 }), 1000, 800, [100, 400]);
+ expect(box.w).toBe(20);
+ expect(box.h).toBe(80);
+ });
+
it('hangs off each of the four corners, inset by the margin', () => {
const at = (anchor) => signatureBox(sig({ anchor, scale: 0.1 }), 1000, 800, natural);
expect(at('tl')).toMatchObject({ x: SIG_MARGIN, y: SIG_MARGIN });
@@ -761,6 +838,7 @@ describe('signatureBox — anchoring', () => {
it('defaults to bottom-right at the default scale', () => {
const box = signatureBox(newSignature(), 1000, 800, natural);
+ expect(SIG_SCALE).toBe(0.08);
expect(box.w).toBe(1000 * SIG_SCALE);
expect(box.x + box.w).toBe(1000 - SIG_MARGIN);
});
@@ -777,6 +855,43 @@ describe('signatureOffset — a drag round-trips through the anchor', () => {
expect(box).toMatchObject({ x: 300, y: 250 });
}
});
+
+ it('keeps a free placement at the same relative position on another proof size', () => {
+ const sig = { ...newSignature(), anchor: 'tl', scale: 0.1 };
+ const placement = signatureOffset(sig, 1000, 800, natural, 300, 250);
+ const grown = signatureBox({ ...sig, ...placement }, 2000, 1600, natural);
+ expect(grown).toMatchObject({ x: 600, y: 500 });
+ });
+});
+
+describe('signaturePairPositions — untouched branding never overlaps', () => {
+ it('centres the account handle below the logo', () => {
+ const signature = newSignature();
+ const handle = newSignatureText();
+ const logo = signatureBox(signature, 1000, 800, [200, 100]);
+ const pair = signaturePairPositions(signature, handle, 1000, 800, logo, 120, 28);
+ expect(pair.handle.y).toBeGreaterThan(pair.logo.y + pair.logo.h);
+ expect(pair.logo.x + pair.logo.w / 2).toBeCloseTo(pair.handle.x + 60);
+ });
+
+ it('stops grouping after either item is moved', () => {
+ const signature = { ...newSignature(), xRatio: 0.5, yRatio: 0.5 };
+ const logo = signatureBox(signature, 1000, 800, [200, 100]);
+ expect(signaturePairPositions(signature, newSignatureText(), 1000, 800, logo, 120, 28))
+ .toBeNull();
+ });
+});
+
+describe('orientFirstPanels — template direction', () => {
+ it('places the first pair side by side or in two rows', () => {
+ const horizontal = [{ row: 3 }, { row: 4 }, { row: 4 }];
+ orientFirstPanels(horizontal, 'horizontal');
+ expect(horizontal.map((p) => p.row)).toEqual([0, 0, 4]);
+
+ const vertical = [{ row: 3 }, { row: 4 }, { row: 4 }];
+ orientFirstPanels(vertical, 'vertical');
+ expect(vertical.map((p) => p.row)).toEqual([0, 1, 4]);
+ });
});
describe('proofSlug — mirrors the backend _slug', () => {
@@ -810,3 +925,680 @@ describe('uniqueProofTitle — a fresh proof reads apart from the case', () => {
expect(proofSlug(uniqueProofTitle(DEFAULT_PROOF_TITLE, ['Untitled proof']))).toBe('untitled-proof-2');
});
});
+
+describe('proofTitleFromCase — new-proof name', () => {
+ it('uses the trimmed case name and keeps it unique among saved proofs', () => {
+ expect(proofTitleFromCase(' Harbour review ', [])).toBe('Harbour review');
+ expect(proofTitleFromCase('Harbour review', ['Harbour review'])).toBe('Harbour review 2');
+ });
+
+ it('falls back to the normal untitled name when no case name is available', () => {
+ expect(proofTitleFromCase('', [])).toBe(DEFAULT_PROOF_TITLE);
+ expect(proofTitleFromCase(null, [DEFAULT_PROOF_TITLE])).toBe('Untitled proof 2');
+ });
+});
+
+describe('filterProofPanelItems — new-proof panel selector', () => {
+ const items = [
+ {
+ src: 'media/satellite-city.png',
+ label: '48.85, 2.35 · z17',
+ kind: 'satellite',
+ meta: { provider: 'Esri World Imagery', imagery_date: '2026-07-01' },
+ },
+ { src: 'media/storefront.jpg', label: 'Storefront.jpg', kind: 'media', meta: {} },
+ { src: 'media/roof.png', label: 'Red roof.png', kind: 'media', meta: {} },
+ ];
+
+ it('filters satellite captures independently from other images', () => {
+ expect(filterProofPanelItems(items, '', 'satellite').map((item) => item.src))
+ .toEqual(['media/satellite-city.png']);
+ expect(filterProofPanelItems(items, '', 'media').map((item) => item.src))
+ .toEqual(['media/storefront.jpg', 'media/roof.png']);
+ });
+
+ it('searches the active category by label, path, and satellite metadata', () => {
+ expect(filterProofPanelItems(items, 'roof', 'media').map((item) => item.src))
+ .toEqual(['media/roof.png']);
+ expect(filterProofPanelItems(items, 'esri', 'satellite').map((item) => item.src))
+ .toEqual(['media/satellite-city.png']);
+ expect(filterProofPanelItems(items, 'storefront', 'satellite')).toEqual([]);
+ });
+});
+
+describe('hasProofCanvasContent — empty template-only proof', () => {
+ it('keeps template decoration hidden until a panel exists', () => {
+ expect(hasProofCanvasContent({ panels: [], signature: { anchor: 'br' }, footer: 'Source' }))
+ .toBe(false);
+ expect(hasProofCanvasContent({ panels: [{ src: 'media/a.png' }], signature: null }))
+ .toBe(true);
+ });
+});
+
+describe('remapPanelXY — moving a shape between panels', () => {
+ it('is identity when the two boxes coincide', () => {
+ const box = { x: 100, y: 40, scale: 2 };
+ expect(remapPanelXY(10, 5, box, box)).toEqual({ x: 10, y: 5 });
+ });
+
+ it('maps a natural point through doc space into the target scale', () => {
+ const from = { x: 100, y: 40, scale: 2 };
+ const to = { x: 0, y: 0, scale: 4 };
+ // doc point (100 + 10*2, 40 + 5*2) = (120, 50); target natural divides by 4
+ expect(remapPanelXY(10, 5, from, to)).toEqual({ x: 30, y: 12.5 });
+ });
+});
+
+describe('panelHitTest — topmost panel under a point', () => {
+ const boxes = [
+ { x: 0, y: 0, w: 100, h: 100, scale: 2 }, // front (drawn first = z-top)
+ { x: 50, y: 50, w: 100, h: 100, scale: 1 }, // back
+ ];
+
+ it('returns null when the point misses every box', () => {
+ expect(panelHitTest(boxes, { x: 500, y: 500 })).toBeNull();
+ });
+
+ it('returns the front box on overlap, with natural coords', () => {
+ const hit = panelHitTest(boxes, { x: 60, y: 60 });
+ expect(hit.index).toBe(0);
+ expect(hit.nx).toBe(30); // (60-0)/2
+ expect(hit.ny).toBe(30);
+ });
+
+ it('falls through to a lower box when the front one misses', () => {
+ const hit = panelHitTest(boxes, { x: 120, y: 120 });
+ expect(hit.index).toBe(1);
+ expect(hit.nx).toBe(70); // (120-50)/1
+ });
+
+ it('counts the box edges as inside', () => {
+ expect(panelHitTest(boxes, { x: 0, y: 0 }).index).toBe(0);
+ expect(panelHitTest(boxes, { x: 100, y: 100 }).index).toBe(0);
+ });
+});
+
+describe('groupNeighborIndex / hasGroupNeighbor — reorder within a group', () => {
+ // rows [0, 1, 0, 0]: indices 0, 2, 3 share row 0
+ const panels = [{ row: 0 }, { row: 1 }, { row: 0 }, { row: 0 }];
+ const rowOf = (p) => p.row ?? 0;
+
+ it('skips other groups to find the nearest same-group neighbour', () => {
+ expect(groupNeighborIndex(panels, 0, 1, rowOf)).toBe(2); // index 1 is row 1
+ expect(groupNeighborIndex(panels, 2, -1, rowOf)).toBe(0);
+ expect(groupNeighborIndex(panels, 2, 1, rowOf)).toBe(3);
+ });
+
+ it('returns -1 at the group edge', () => {
+ expect(groupNeighborIndex(panels, 0, -1, rowOf)).toBe(-1);
+ expect(groupNeighborIndex(panels, 1, 1, rowOf)).toBe(-1); // lone row 1
+ expect(groupNeighborIndex(panels, 3, 1, rowOf)).toBe(-1);
+ });
+
+ it('hasGroupNeighbor agrees on whether a move is possible', () => {
+ expect(hasGroupNeighbor(panels, 0, -1, rowOf)).toBe(false);
+ expect(hasGroupNeighbor(panels, 0, 1, rowOf)).toBe(true);
+ expect(hasGroupNeighbor(panels, 1, 1, rowOf)).toBe(false);
+ expect(hasGroupNeighbor(panels, 3, -1, rowOf)).toBe(true);
+ });
+
+ it('works for shapes keyed by their panel too', () => {
+ const shapes = [{ panel: 'a' }, { panel: 'b' }, { panel: 'a' }];
+ expect(groupNeighborIndex(shapes, 0, 1, (s) => s.panel)).toBe(2);
+ expect(hasGroupNeighbor(shapes, 1, -1, (s) => s.panel)).toBe(false);
+ });
+});
+
+describe('denseRowValues — collapse sparse rows to 0..n-1', () => {
+ it('renumbers gaps left by an emptied row', () => {
+ const panels = [{ row: 0 }, { row: 2 }, { row: 2 }, { row: 5 }];
+ expect(denseRowValues(panels)).toEqual([0, 1, 1, 2]);
+ });
+
+ it('treats a missing row as 0', () => {
+ expect(denseRowValues([{}, { row: 3 }])).toEqual([0, 1]);
+ });
+});
+
+describe('clampPanelScale', () => {
+ it('adds the delta and clamps to the range', () => {
+ expect(clampPanelScale(1, 0.5, 0.25, 2.5)).toBe(1.5);
+ expect(clampPanelScale(2.4, 0.5, 0.25, 2.5)).toBe(2.5);
+ expect(clampPanelScale(0.3, -0.5, 0.25, 2.5)).toBe(0.25);
+ });
+
+ it('rounds to whole percent and defaults a missing scale to 1', () => {
+ expect(clampPanelScale(1, 0.024, 0.25, 2.5)).toBe(1.02);
+ expect(clampPanelScale(undefined, 0.5, 0.25, 2.5)).toBe(1.5);
+ });
+});
+
+describe('trimClosingDuplicate — drop the double-click tail', () => {
+ it('trims the last vertex when it lands on the previous one', () => {
+ expect(trimClosingDuplicate([0, 0, 10, 10, 10, 11])).toEqual([0, 0, 10, 10]);
+ });
+
+ it('keeps a genuine final vertex', () => {
+ const pts = [0, 0, 10, 10, 40, 40];
+ expect(trimClosingDuplicate(pts)).toEqual(pts);
+ });
+
+ it('returns a copy, never mutating the input', () => {
+ const pts = [0, 0, 10, 10, 10, 10];
+ const out = trimClosingDuplicate(pts);
+ expect(pts).toHaveLength(6);
+ expect(out).toHaveLength(4);
+ });
+
+ it('leaves a genuine two-point line alone', () => {
+ expect(trimClosingDuplicate([0, 0, 40, 40])).toEqual([0, 0, 40, 40]);
+ });
+});
+
+describe('canReassignLegendNote — move a note with a recolored shape', () => {
+ it('moves the note when the new color is free and no other shape keeps the old', () => {
+ const moving = { color: 'red' };
+ const notes = { red: 'the roof' };
+ expect(canReassignLegendNote(notes, 'red', 'blue', [moving], moving)).toBe(true);
+ });
+
+ it('keeps the note when another shape still uses the old color', () => {
+ const moving = { color: 'red' };
+ const other = { color: 'red' };
+ const notes = { red: 'the roof' };
+ expect(canReassignLegendNote(notes, 'red', 'blue', [moving, other], moving)).toBe(false);
+ });
+
+ it('does not clobber an existing note on the new color', () => {
+ const moving = { color: 'red' };
+ const notes = { red: 'the roof', blue: 'the car' };
+ expect(canReassignLegendNote(notes, 'red', 'blue', [moving], moving)).toBe(false);
+ });
+
+ it('is false when the old color had no note', () => {
+ const moving = { color: 'red' };
+ expect(canReassignLegendNote({}, 'red', 'blue', [moving], moving)).toBe(false);
+ });
+});
+
+describe('saved-proof case queries', () => {
+ const entities = [
+ { label: 'Rooftop', attrs: { spec: 'proofs/rooftop.json' } },
+ { label: 'Bridge', attrs: { spec: 'proofs/bridge.json' } },
+ { label: 'A place', attrs: { spec: 'places/x.json' } }, // not a proof
+ { label: 'No spec' },
+ ];
+
+ it('picks only entities filed as proofs/*.json', () => {
+ expect(savedProofEntities(entities).map((e) => e.label)).toEqual(['Rooftop', 'Bridge']);
+ expect(savedProofEntities(undefined)).toEqual([]);
+ });
+
+ it('lists the slugs (filename without proofs/ and .json)', () => {
+ expect(savedProofSlugs(entities)).toEqual(new Set(['rooftop', 'bridge']));
+ });
+
+ it('lists the titles', () => {
+ expect(savedProofTitles(entities)).toEqual(new Set(['Rooftop', 'Bridge']));
+ });
+
+ it('resolves a title by slug, falling back to the slug itself', () => {
+ expect(savedProofTitle(entities, 'bridge')).toBe('Bridge');
+ expect(savedProofTitle(entities, 'unknown')).toBe('unknown');
+ });
+});
+
+describe('isLightColor + textColors — text tracks the proof background', () => {
+ it('reads dark backgrounds as dark and pale ones as light', () => {
+ expect(isLightColor('#0d1117')).toBe(false);
+ expect(isLightColor('#000000')).toBe(false);
+ expect(isLightColor('#ffffff')).toBe(true);
+ expect(isLightColor('#f4f1ea')).toBe(true);
+ expect(isLightColor('#fff')).toBe(true); // 3-digit shorthand
+ });
+
+ it('is tolerant of a missing or malformed colour (treats it as dark)', () => {
+ expect(isLightColor('')).toBe(false);
+ expect(isLightColor('nope')).toBe(false);
+ expect(isLightColor(null)).toBe(false);
+ });
+
+ it('gives light text on the default dark bg and dark text on a light bg', () => {
+ expect(textColors(BG).main).toBe(TEXT_MAIN);
+ expect(textColors('#ffffff').main).toBe(TEXT_MAIN_LIGHT);
+ });
+});
+
+describe('normSpace — panel spacing with shipped-default fallbacks', () => {
+ it('fills every field from the defaults when nothing is given', () => {
+ expect(normSpace()).toEqual({ pad: PAD, gap: GAP, rowGap: ROW_GAP });
+ expect(normSpace(null)).toEqual({ pad: PAD, gap: GAP, rowGap: ROW_GAP });
+ });
+
+ it('keeps the values it is given, defaulting only the missing ones', () => {
+ expect(normSpace({ gap: 40 })).toEqual({ pad: PAD, gap: 40, rowGap: ROW_GAP });
+ expect(normSpace({ pad: 0, gap: 0, rowGap: 0 })).toEqual({ pad: 0, gap: 0, rowGap: 0 });
+ });
+
+ it('clamps unsafe values and replaces non-finite values', () => {
+ expect(normSpace({ pad: -1, gap: 1e308, rowGap: NaN }))
+ .toEqual({ pad: 0, gap: 200, rowGap: ROW_GAP });
+ expect(normSpace({ pad: Infinity, gap: '20', rowGap: {} }))
+ .toEqual({ pad: PAD, gap: GAP, rowGap: ROW_GAP });
+ });
+});
+
+describe('layout — parametric margins (bg/space templates)', () => {
+ it('a wider gap pushes the second panel further right', () => {
+ const panels = [landscape(1000, 500), landscape(500, 500)];
+ const boxes = layoutPanels(panels, undefined, 'grid', { gap: 100 });
+ expect(boxes[1].x).toBeCloseTo(PAD + 1440 + 100);
+ });
+
+ it('a custom outer padding moves the origin of the first panel', () => {
+ const boxes = layoutPanels([landscape(1000, 500)], undefined, 'grid', { pad: 60 });
+ expect(boxes[0]).toMatchObject({ x: 60, y: 60 });
+ });
+
+ it('a custom rowGap changes where the next row stacks', () => {
+ const panels = [landscape(1000, 500, { row: 0, caption: 'a' }), landscape(1000, 500, { row: 1, caption: 'b' })];
+ const boxes = layoutPanels(panels, undefined, 'grid', { rowGap: 80 });
+ expect(boxes[1].y).toBe(PAD + PANEL_H + captionBand() + 80);
+ });
+
+ it('docSize grows with a bigger padding', () => {
+ const tight = docSize([landscape(1000, 500)], [], {}, {}, [], 'grid', { pad: 20 });
+ const roomy = docSize([landscape(1000, 500)], [], {}, {}, [], 'grid', { pad: 60 });
+ expect(roomy.width).toBe(tight.width + 2 * (60 - 20));
+ expect(roomy.height).toBe(tight.height + 2 * (60 - 20));
+ });
+
+ it('defaults leave the layout identical to the shipped constants', () => {
+ const panels = [landscape(1000, 500), landscape(500, 500, { row: 0 })];
+ expect(layoutPanels(panels, undefined, 'grid', normSpace())).toEqual(layoutPanels(panels));
+ });
+});
+
+describe('toSpec — background + spacing persistence', () => {
+ it('defaults a fresh proof to the shipped bg and spacing', () => {
+ const spec = toSpec({ title: 'T', panels: [], shapes: [] });
+ expect(spec.bg).toBe(BG);
+ expect(spec.space).toEqual({ pad: PAD, gap: GAP, rowGap: ROW_GAP });
+ });
+
+ it('persists a custom background and partial spacing (missing fields filled)', () => {
+ const spec = toSpec({ title: 'T', panels: [], shapes: [], bg: '#ffffff', space: { gap: 50 } });
+ expect(spec.bg).toBe('#ffffff');
+ expect(spec.space).toEqual({ pad: PAD, gap: 50, rowGap: ROW_GAP });
+ });
+
+ it('persists a custom drawing palette and defaults older proofs', () => {
+ const custom = toSpec({ title: 'T', panels: [], shapes: [], palette: ['#123456'] });
+ const older = toSpec({ title: 'T', panels: [], shapes: [] });
+ expect(custom.palette).toEqual(['#123456']);
+ expect(older.palette).toEqual(ANNO_COLORS);
+ });
+});
+
+describe('preferred drawing colours', () => {
+ it('uses the seven shipped colours for a missing or empty palette', () => {
+ expect(normalizePreferredColors()).toEqual(ANNO_COLORS);
+ expect(normalizePreferredColors([])).toEqual(ANNO_COLORS);
+ expect(ANNO_COLORS).toHaveLength(MAX_ANNO_COLORS);
+ });
+
+ it('deduplicates colours and caps the palette at seven', () => {
+ expect(normalizePreferredColors([
+ '#111111', '#111111', '#222222', '#333333', '#444444',
+ '#555555', '#666666', '#777777', '#888888', 'invalid',
+ ])).toEqual([
+ '#111111', '#222222', '#333333', '#444444',
+ '#555555', '#666666', '#777777',
+ ]);
+ });
+
+ it('replaces the selected palette slot', () => {
+ expect(replacePreferredColor(ANNO_COLORS, 2, '#123456')).toEqual([
+ ANNO_COLORS[0], ANNO_COLORS[1], '#123456', ...ANNO_COLORS.slice(3),
+ ]);
+ });
+
+ it('swaps slots when the replacement colour is already in the palette', () => {
+ expect(replacePreferredColor(ANNO_COLORS, 2, ANNO_COLORS[0])).toEqual([
+ ANNO_COLORS[2], ANNO_COLORS[1], ANNO_COLORS[0], ...ANNO_COLORS.slice(3),
+ ]);
+ });
+});
+
+describe('templateFromProof — a content-free house style', () => {
+ const proof = {
+ title: 'Rooftop match',
+ bg: '#101418',
+ space: { pad: 30, gap: 40, rowGap: 24 },
+ layout: 'free',
+ captionSize: 24, legendSize: 22, footerSize: 16,
+ footer: 'By the desk',
+ footerEnabled: false,
+ footerColor: '#aabbcc',
+ captionsEnabled: false,
+ signature: { anchor: 'br', dx: 5, dy: 0, scale: 0.12, opacity: 0.9 },
+ signatureText: { text: '@desk', anchor: 'tr', dx: 0, dy: 0, size: 44, color: '#ffffff', opacity: 1 },
+ palette: ['#123456', '#ff5252', '#40c4ff'],
+ notes: { '#ff5252': 'Match', '#40c4ff': 'Reference' },
+ legendOrder: ['#40c4ff', '#ff5252'],
+ coordsText: '48.85, 2.35',
+ source: 'https://x.com/a/1',
+ panels: [{ id: 'p1', src: 'a.png', natural: [10, 10] }],
+ shapes: [{ id: 's1', kind: 'rect', color: '#ff5252', panel: 'p1' }],
+ };
+
+ it('keeps only the style, never the content', () => {
+ const t = templateFromProof(proof);
+ expect(t).toEqual({
+ bg: '#101418',
+ space: { pad: 30, gap: 40, rowGap: 24 },
+ layout: 'free',
+ captionSize: 24, legendSize: 22, footerSize: 16,
+ footer: 'By the desk',
+ footerEnabled: false,
+ footerColor: '#aabbcc',
+ footerAlign: 'left',
+ captionsEnabled: false,
+ panelDirection: 'horizontal',
+ signature: { anchor: 'br', dx: 5, dy: 0, scale: 0.12, opacity: 0.9 },
+ signatureText: { anchor: 'tr', dx: 0, dy: 0, size: 44, color: '#ffffff', opacity: 1 },
+ palette: ['#123456', '#ff5252', '#40c4ff'],
+ });
+ expect(t).not.toHaveProperty('panels');
+ expect(t).not.toHaveProperty('shapes');
+ expect(t).not.toHaveProperty('title');
+ expect(t).not.toHaveProperty('coordsText');
+ expect(t).not.toHaveProperty('source');
+ expect(t).not.toHaveProperty('notes');
+ expect(t).not.toHaveProperty('legendOrder');
+ });
+
+ it('detaches — mutating the template leaves the proof untouched', () => {
+ const t = templateFromProof(proof);
+ t.palette[0] = '#abcdef';
+ t.signature.dx = 999;
+ t.signatureText.size = 99;
+ expect(proof.palette[0]).toBe('#123456');
+ expect(proof.signature.dx).toBe(5);
+ expect(proof.signatureText.size).toBe(44);
+ });
+
+ it('fills shipped defaults for a bare proof', () => {
+ const t = templateFromProof({ panels: [], shapes: [] });
+ expect(t.bg).toBe(BG);
+ expect(t.space).toEqual({ pad: PAD, gap: GAP, rowGap: ROW_GAP });
+ expect(t.layout).toBe('grid');
+ expect(t.signature).toBeNull();
+ expect(t.signatureText).toBeNull();
+ expect(t.footerEnabled).toBe(true);
+ expect(t.footerColor).toBeNull();
+ expect(t.footerAlign).toBe('left');
+ expect(t.panelDirection).toBe('horizontal');
+ expect(t.captionsEnabled).toBe(true);
+ expect(t.palette).toEqual(ANNO_COLORS);
+ });
+});
+
+describe('normalizeProofStyle — renderer boundary', () => {
+ it('normalizes malformed nested values, enums, colors and numbers', () => {
+ const style = normalizeProofStyle({
+ bg: 'red', space: { pad: -10, gap: Infinity, rowGap: 1e308 },
+ layout: 'stacked', captionSize: NaN, legendSize: -1, footerSize: 1e308,
+ footer: 'x'.repeat(250), footerColor: 'white', footerAlign: 'center',
+ signature: { anchor: 'middle', dx: Infinity, scale: 99, opacity: -1 },
+ signatureText: [], palette: ['bad'],
+ });
+ expect(style).toMatchObject({
+ bg: BG,
+ space: { pad: 0, gap: GAP, rowGap: 200 },
+ layout: 'grid',
+ captionSize: 20,
+ legendSize: 8,
+ footerSize: 80,
+ footerColor: null,
+ footerAlign: 'left',
+ signature: { anchor: 'br', dx: 0, scale: 0.6, opacity: 0 },
+ signatureText: null,
+ palette: ANNO_COLORS,
+ });
+ expect(style.footer).toHaveLength(200);
+ });
+
+ it('keeps document-relative branding coordinates within the document range', () => {
+ const style = normalizeProofStyle({
+ signature: { anchor: 'tl', xRatio: 1.5, yRatio: -0.5 },
+ signatureText: { anchor: 'br', xRatio: 0.25, yRatio: 0.75 },
+ });
+ expect(style.signature).toMatchObject({ xRatio: 1, yRatio: 0 });
+ expect(style.signatureText).toMatchObject({ xRatio: 0.25, yRatio: 0.75 });
+ });
+});
+
+describe('proofExportOptions — canvas allocation guard', () => {
+ it('returns the existing export ratio for an ordinary proof', () => {
+ expect(proofExportOptions(1800, 900)).toEqual({
+ pixelRatio: 1, outputWidth: 1800, outputHeight: 900,
+ });
+ });
+
+ it('rejects invalid, over-dimension and over-pixel exports', () => {
+ expect(() => proofExportOptions(Infinity, 900)).toThrow(/dimensions are invalid/i);
+ expect(() => proofExportOptions(30_000, 100)).toThrow(/too large to export/i);
+ expect(() => proofExportOptions(12_000, 12_000)).toThrow(/too large to export/i);
+ });
+});
+
+describe('applyProofStyle — restyle without touching content', () => {
+ const style = {
+ bg: '#ffffff',
+ space: { pad: 40, gap: 40, rowGap: 40 },
+ layout: 'free',
+ captionSize: 26, legendSize: 26, footerSize: 18,
+ footer: 'House line',
+ signature: { anchor: 'tl', dx: 0, dy: 0, scale: 0.1, opacity: 1 },
+ palette: ['#123456', '#abcdef'],
+ };
+
+ it('applies every style field but leaves panels/shapes/title/coords alone', () => {
+ const proof = {
+ title: 'Keep me', coordsText: '1, 2', source: 'http://s',
+ panels: [{ id: 'p1', src: 'a.png' }], shapes: [{ id: 's1' }],
+ notes: { '#ff5252': 'Keep this legend' }, legendOrder: ['#ff5252'],
+ };
+ applyProofStyle(proof, style);
+ expect(proof.bg).toBe('#ffffff');
+ expect(proof.space).toEqual({ pad: 40, gap: 40, rowGap: 40 });
+ expect(proof.layout).toBe('free');
+ expect(proof.footer).toBe('House line');
+ expect(proof.signature).toMatchObject({ anchor: 'tl' });
+ // content untouched
+ expect(proof.title).toBe('Keep me');
+ expect(proof.coordsText).toBe('1, 2');
+ expect(proof.panels).toHaveLength(1);
+ expect(proof.shapes).toHaveLength(1);
+ expect(proof.palette).toEqual(['#123456', '#abcdef']);
+ expect(proof.notes).toEqual({ '#ff5252': 'Keep this legend' });
+ expect(proof.legendOrder).toEqual(['#ff5252']);
+ });
+
+ it('replaces the preferred palette without changing legend content', () => {
+ const proof = {
+ palette: [...ANNO_COLORS],
+ notes: { '#ff5252': 'My own label' },
+ legendOrder: ['#ff5252'],
+ };
+ applyProofStyle(proof, style);
+ expect(proof.palette).toEqual(['#123456', '#abcdef']);
+ expect(proof.notes).toEqual({ '#ff5252': 'My own label' });
+ expect(proof.legendOrder).toEqual(['#ff5252']);
+ });
+
+ it('detaches the applied signature and space objects', () => {
+ const proof = { notes: {}, legendOrder: [] };
+ applyProofStyle(proof, style);
+ proof.signature.dx = 99;
+ proof.space.pad = 99;
+ expect(style.signature.dx).toBe(0);
+ expect(style.space.pad).toBe(40);
+ });
+
+ it('a round-trip through a template reproduces the same style', () => {
+ const original = {
+ bg: '#101418', space: { pad: 30, gap: 40, rowGap: 24 }, layout: 'free',
+ captionSize: 24, legendSize: 22, footerSize: 16, footer: 'By the desk',
+ footerEnabled: false, footerColor: '#aabbcc',
+ signature: { anchor: 'br', dx: 5, dy: 0, scale: 0.12, opacity: 0.9 },
+ signatureText: { text: '@desk', anchor: 'tr', dx: 2, dy: 3, size: 44, color: '#fff', opacity: 1 },
+ palette: ['#123456', '#abcdef'],
+ notes: { '#ff5252': 'Match' }, legendOrder: ['#ff5252'],
+ panels: [], shapes: [],
+ };
+ const target = { notes: {}, legendOrder: [], panels: [], shapes: [] };
+ applyProofStyle(target, templateFromProof(original));
+ expect(templateFromProof(target)).toEqual(templateFromProof(original));
+ });
+
+ it('applies the footer switch/colour and the text signature', () => {
+ const proof = { notes: {}, legendOrder: [], panels: [], shapes: [] };
+ applyProofStyle(proof, {
+ footerEnabled: false,
+ footerColor: '#123456',
+ footerAlign: 'right',
+ signatureText: { text: '@name', anchor: 'tl', dx: 0, dy: 0, size: 50, color: '#fff', opacity: 1 },
+ });
+ expect(proof.footerEnabled).toBe(false);
+ expect(proof.footerColor).toBe('#123456');
+ expect(proof.footerAlign).toBe('right');
+ expect(proof.signatureText).toMatchObject({ anchor: 'tl' });
+ expect(proof.signatureText).not.toHaveProperty('text');
+ // a style without a text signature clears any existing one
+ applyProofStyle(proof, { signatureText: null });
+ expect(proof.signatureText).toBeNull();
+ });
+
+ it('adds logo and account-handle slots only when both the template and Settings provide them', () => {
+ const proof = { notes: {}, legendOrder: [] };
+ const signed = {
+ signature: { anchor: 'br', dx: 0, dy: 0, scale: 0.12, opacity: 1 },
+ signatureText: { anchor: 'tl', dx: 0, dy: 0, size: 50, color: '#fff', opacity: 1 },
+ };
+ applyProofStyle(proof, signed, { logo: false, handle: false });
+ expect(proof.signature).toBeNull();
+ expect(proof.signatureText).toBeNull();
+
+ applyProofStyle(proof, signed, { logo: true, handle: true });
+ expect(proof.signature).toMatchObject({ anchor: 'br' });
+ expect(proof.signatureText).toMatchObject({ anchor: 'tl' });
+ });
+
+ it('applies the template direction to the first two existing panels', () => {
+ const proof = { panels: [{ row: 0 }, { row: 0 }], notes: {}, legendOrder: [] };
+ applyProofStyle(proof, { panelDirection: 'vertical' });
+ expect(proof.panelDirection).toBe('vertical');
+ expect(proof.panels.map((p) => p.row)).toEqual([0, 1]);
+ });
+
+ it('apply-then-discard restores the visual style the proof had before', () => {
+ // The composer's "Discard template" path: snapshot the look, apply a
+ // template over it, then re-apply the snapshot to walk the style back.
+ const proof = {
+ bg: '#0d1117', space: { pad: 40, gap: 24, rowGap: 24 }, layout: 'grid',
+ captionSize: 20, legendSize: 18, footerSize: 14, footer: '',
+ footerEnabled: true, footerColor: null,
+ signature: null, signatureText: null, palette: [...ANNO_COLORS], notes: {}, legendOrder: [],
+ panels: [], shapes: [],
+ };
+ const before = templateFromProof(proof);
+ applyProofStyle(proof, {
+ bg: '#ffffff', space: { pad: 0, gap: 0, rowGap: 0 }, layout: 'free',
+ palette: ['#123456'],
+ footerEnabled: false, signature: { anchor: 'br', dx: 0, dy: 0, scale: 0.2, opacity: 1 },
+ });
+ expect(proof.footerEnabled).toBe(false);
+ applyProofStyle(proof, before); // discard
+ expect(templateFromProof(proof)).toEqual(before);
+ });
+});
+
+describe('toSpec — footer switch/colour + text signature', () => {
+ it('defaults a fresh proof to footer-on, auto colour, no text signature', () => {
+ const spec = toSpec({ title: 'T', panels: [], shapes: [] });
+ expect(spec.footerEnabled).toBe(true);
+ expect(spec.footerColor).toBeNull();
+ expect(spec.footerAlign).toBe('left');
+ expect(spec.panelDirection).toBe('horizontal');
+ expect(spec.signatureText).toBeNull();
+ });
+
+ it('persists a disabled footer, a footer colour and a text signature', () => {
+ const spec = toSpec({
+ title: 'T', panels: [], shapes: [],
+ footerEnabled: false, footerColor: '#334455', footerAlign: 'right', panelDirection: 'vertical',
+ signatureText: { text: '@n', anchor: 'br', dx: 1, dy: 2, size: 44, color: '#fff', opacity: 0.8 },
+ });
+ expect(spec.footerEnabled).toBe(false);
+ expect(spec.footerColor).toBe('#334455');
+ expect(spec.footerAlign).toBe('right');
+ expect(spec.panelDirection).toBe('vertical');
+ expect(spec.signatureText).toMatchObject({ anchor: 'br' });
+ expect(spec.signatureText).not.toHaveProperty('text');
+ });
+});
+
+describe('docSize — footer can be switched off', () => {
+ it('reclaims the footer band height when the footer is disabled', () => {
+ const panels = [landscape(1000, 500)];
+ const on = docSize(panels, [], {}, { footerEnabled: true });
+ const off = docSize(panels, [], {}, { footerEnabled: false });
+ expect(on.height - off.height).toBe(FOOTER_H);
+ });
+
+ it('footer off + no captions + no margins reduces to just the panels', () => {
+ const panels = [landscape(1000, 500), landscape(500, 500)];
+ const { width, height } = docSize(
+ panels, [], {}, { footerEnabled: false }, [], 'grid', { pad: 0, gap: 0, rowGap: 0 }
+ );
+ expect(height).toBe(PANEL_H); // no caption band, no footer, no padding
+ expect(width).toBe(1440 + 720); // the two panels, no gap
+ });
+});
+
+describe('anchoredPos / anchoredOffset — the text-signature placement', () => {
+ it('hangs a box off each corner inset by the margin', () => {
+ expect(anchoredPos({ anchor: 'tl' }, 1000, 800, 100, 40)).toEqual({ x: SIG_MARGIN, y: SIG_MARGIN });
+ expect(anchoredPos({ anchor: 'br' }, 1000, 800, 100, 40))
+ .toEqual({ x: 1000 - SIG_MARGIN - 100, y: 800 - SIG_MARGIN - 40 });
+ });
+
+ it('applies a nudge and clamps inside the document', () => {
+ expect(anchoredPos({ anchor: 'tl', dx: 20, dy: 10 }, 1000, 800, 100, 40)).toEqual({ x: SIG_MARGIN + 20, y: SIG_MARGIN + 10 });
+ expect(anchoredPos({ anchor: 'tl', dx: -9999, dy: -9999 }, 1000, 800, 100, 40)).toEqual({ x: 0, y: 0 });
+ });
+
+ it('anchoredOffset reproduces a dropped position (round-trip)', () => {
+ for (const anchor of ['tl', 'tr', 'bl', 'br']) {
+ const off = anchoredOffset({ anchor }, 1000, 800, 120, 44, 300, 250);
+ const pos = anchoredPos({ anchor, ...off }, 1000, 800, 120, 44);
+ expect(pos).toEqual({ x: 300, y: 250 });
+ }
+ });
+
+ it('keeps a free account-handle placement relative to a resized proof', () => {
+ const placement = anchoredOffset({ anchor: 'tl' }, 1000, 800, 100, 40, 300, 250);
+ const grown = anchoredPos({ anchor: 'tl', ...placement }, 2000, 1600, 200, 80);
+ expect(grown.x).toBeCloseTo(600);
+ expect(grown.y).toBeCloseTo(500);
+ });
+
+ it('newSignatureText is a bottom-right handle at the default size', () => {
+ const s = newSignatureText();
+ expect(SIG_TEXT_SIZE).toBe(28);
+ expect(s).toMatchObject({ anchor: 'br', size: SIG_TEXT_SIZE, opacity: 1 });
+ expect(s).not.toHaveProperty('text');
+ });
+});
diff --git a/frontend/src/lib/gridSearch.js b/frontend/src/lib/gridSearch.js
index db8397a..3efb0bc 100644
--- a/frontend/src/lib/gridSearch.js
+++ b/frontend/src/lib/gridSearch.js
@@ -33,6 +33,43 @@ export function aoiBounds(aoi) {
};
}
+/** Centre {lat, lon} of an area of interest (rect bounds or polygon). */
+export function aoiCenter(aoi) {
+ const b = aoiBounds(aoi);
+ return { lat: (b.south + b.north) / 2, lon: (b.west + b.east) / 2 };
+}
+
+/**
+ * Bounds with each pair sorted low→high, so a box dragged in any direction (a
+ * corner pulled past its opposite) still reads as a valid south<north /
+ * west<east rectangle.
+ */
+export function normalizeBounds(b) {
+ return {
+ south: Math.min(b.south, b.north),
+ north: Math.max(b.south, b.north),
+ west: Math.min(b.west, b.east),
+ east: Math.max(b.west, b.east),
+ };
+}
+
+/**
+ * The [lat, lon] of one corner of a bounds box, addressed by a two-letter code
+ * (n/s then e/w): 'ne', 'sw', … — used to place the rect resize handles.
+ */
+export function cornerLatLng(b, corner) {
+ return [corner[0] === 'n' ? b.north : b.south, corner[1] === 'e' ? b.east : b.west];
+}
+
+/**
+ * Close a polygon ring: `points` with the first repeated at the end so a
+ * polyline draws shut, but only once there are ≥3 points (a segment still
+ * being drawn is left open). Points are [lat, lon] pairs.
+ */
+export function closeRing(points) {
+ return points.length >= 3 ? [...points, points[0]] : points;
+}
+
/** Build a fresh grid over `aoi` with `cellM`-metre cells (no marks yet). */
export function createGrid(aoi, cellM) {
const b = aoiBounds(aoi);
diff --git a/frontend/src/lib/gridSearch.test.js b/frontend/src/lib/gridSearch.test.js
index 89563e5..3aa83ba 100644
--- a/frontend/src/lib/gridSearch.test.js
+++ b/frontend/src/lib/gridSearch.test.js
@@ -18,6 +18,10 @@ import {
pruneStatuses,
resizeRect,
resizePolygon,
+ aoiCenter,
+ normalizeBounds,
+ cornerLatLng,
+ closeRing,
} from './gridSearch.js';
const rect = (south, west, north, east) => ({ type: 'rect', bounds: { south, west, north, east } });
@@ -240,3 +244,48 @@ describe('resizePolygon', () => {
expect(grown.statuses[cellKey(...cells[0])]).toBe('cleared');
});
});
+
+describe('aoiCenter', () => {
+ it('centres a rectangle', () => {
+ expect(aoiCenter(rect(0, 0, 2, 4))).toEqual({ lat: 1, lon: 2 });
+ });
+
+ it('centres a polygon by its bounding box', () => {
+ const aoi = { type: 'polygon', vertices: [[0, 0], [0, 4], [2, 2]] };
+ expect(aoiCenter(aoi)).toEqual({ lat: 1, lon: 2 });
+ });
+});
+
+describe('normalizeBounds', () => {
+ it('leaves an already-ordered box untouched', () => {
+ expect(normalizeBounds({ south: 1, north: 2, west: 3, east: 4 }))
+ .toEqual({ south: 1, north: 2, west: 3, east: 4 });
+ });
+
+ it('sorts a box dragged past its opposite corner', () => {
+ expect(normalizeBounds({ south: 2, north: 1, west: 4, east: 3 }))
+ .toEqual({ south: 1, north: 2, west: 3, east: 4 });
+ });
+});
+
+describe('cornerLatLng', () => {
+ const b = { south: 1, north: 2, west: 3, east: 4 };
+ it('reads each corner code as [lat, lon]', () => {
+ expect(cornerLatLng(b, 'sw')).toEqual([1, 3]);
+ expect(cornerLatLng(b, 'se')).toEqual([1, 4]);
+ expect(cornerLatLng(b, 'nw')).toEqual([2, 3]);
+ expect(cornerLatLng(b, 'ne')).toEqual([2, 4]);
+ });
+});
+
+describe('closeRing', () => {
+ it('repeats the first point once there are three or more', () => {
+ expect(closeRing([[0, 0], [0, 1], [1, 1]])).toEqual([[0, 0], [0, 1], [1, 1], [0, 0]]);
+ });
+
+ it('leaves a segment still being drawn open', () => {
+ expect(closeRing([[0, 0], [0, 1]])).toEqual([[0, 0], [0, 1]]);
+ expect(closeRing([[0, 0]])).toEqual([[0, 0]]);
+ expect(closeRing([])).toEqual([]);
+ });
+});
diff --git a/frontend/src/lib/post.js b/frontend/src/lib/post.js
new file mode 100644
index 0000000..d8a78b8
--- /dev/null
+++ b/frontend/src/lib/post.js
@@ -0,0 +1,448 @@
+/**
+ * Post Composer thread logic — pure functions, no Svelte/DOM here.
+ *
+ * A thread template is a **body string with tokens** (#place, #coordinates, …).
+ * The analyst arranges the tokens in the order and line layout they want; a
+ * template is that layout plus the default mention, the media-tweet flag and any
+ * boilerplate extra tweets. It carries no case content — the tokens are filled
+ * from the live draft at build time. Some accounts drop the place line or post
+ * bare coordinates; a token body expresses either without special-casing.
+ */
+
+// The tokens an analyst can drop into a thread body. `sample` feeds the editor
+// preview so the layout reads before any real draft exists.
+export const TWEET_TOKENS = [
+ { tag: '#place', label: 'Place', sample: 'Bakhmut, Donetsk, Ukraine' },
+ { tag: '#pluscode', label: 'Plus code', sample: '8FPGXXXX+XX' },
+ { tag: '#coordinates', label: 'Coordinates', sample: '48.850000, 2.350000' },
+ { tag: '#description', label: 'Description', sample: 'Rooftop match against the reference imagery' },
+ { tag: '#mention', label: 'Mention', sample: '@GeoConfirmed' },
+ { tag: '#source', label: 'Source', sample: 'https://x.com/example/status/1' },
+];
+
+export const MAX_POST_MEDIA = 4;
+
+/**
+ * Publishing targets share the same prepared thread, but apply their own
+ * character rules and handoff URL. Mastodon uses its documented default here;
+ * an individual server may advertise a different limit.
+ */
+export const POST_TARGETS = Object.freeze({
+ x: { id: 'x', label: 'X', limit: 280, limitLabel: '280' },
+ bluesky: { id: 'bluesky', label: 'Bluesky', limit: 300, limitLabel: '300' },
+ mastodon: {
+ id: 'mastodon', label: 'Mastodon', limit: 500, limitLabel: '500 default',
+ limitHelp: 'Your server may use another limit.',
+ },
+});
+
+const URL_RE = /https?:\/\/\S+/g;
+
+/** Accept stored legacy drafts and unknown values without breaking the form. */
+export function normalizePostTarget(target) {
+ return Object.hasOwn(POST_TARGETS, target) ? target : 'x';
+}
+
+/** Return a target profile, falling back to X for old or hand-edited drafts. */
+export function postTarget(target) {
+ return POST_TARGETS[normalizePostTarget(target)];
+}
+
+/** X and Mastodon reserve a fixed length for every HTTP(S) URL. */
+export function weightedUrlLength(text) {
+ const value = String(text ?? '');
+ const stripped = value.replace(URL_RE, '');
+ const urls = value.match(URL_RE)?.length ?? 0;
+ return [...stripped].length + urls * 23;
+}
+
+/** Bluesky limits posts by visible Unicode grapheme clusters, not code units. */
+export function graphemeLength(text) {
+ const value = String(text ?? '');
+ if (typeof Intl?.Segmenter === 'function') {
+ return [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(value)].length;
+ }
+ return [...value].length;
+}
+
+/** Count text according to the selected target's documented rule. */
+export function postCharacterCount(target, text) {
+ return normalizePostTarget(target) === 'bluesky'
+ ? graphemeLength(text)
+ : weightedUrlLength(text);
+}
+
+/** Build a compose handoff for the first post. Replies stay on the clipboard. */
+export function postComposeUrl(target, text) {
+ const encoded = encodeURIComponent(String(text ?? ''));
+ switch (normalizePostTarget(target)) {
+ case 'bluesky':
+ return `https://bsky.app/intent/compose?text=${encoded}`;
+ case 'mastodon':
+ return `https://share.joinmastodon.org/#text=${encoded}`;
+ default:
+ return `https://x.com/intent/post?text=${encoded}`;
+ }
+}
+
+/**
+ * Turn a prepared social thread into a portable, deliberately small Markdown
+ * report. This is an export handoff, not the future full Report Builder.
+ */
+export function postReportMarkdown({
+ title,
+ place,
+ plusCode,
+ coordinates,
+ description,
+ source,
+ posts = [],
+ attachments = [],
+} = {}) {
+ const clean = (value) => String(value ?? '').trim();
+ const reportTitle = clean(title) || 'Untitled report';
+ const location = [
+ clean(place) && `Place: ${clean(place)}`,
+ clean(plusCode) && `Plus code: ${clean(plusCode)}`,
+ clean(coordinates) && `Coordinates: ${clean(coordinates)}`,
+ ].filter(Boolean);
+ const cleanPosts = posts.map(clean).filter(Boolean);
+ const cleanAttachments = [...new Set(attachments.map(clean).filter(Boolean))];
+ const sections = [`# ${reportTitle}`];
+
+ if (location.length) sections.push(`## Location\n\n${location.join('\n')}`);
+ if (clean(description)) sections.push(`## Assessment\n\n${clean(description)}`);
+ if (clean(source)) sections.push(`## Source\n\n${clean(source)}`);
+ if (cleanPosts.length) {
+ sections.push(`## Prepared posts\n\n${cleanPosts
+ .map((post, index) => `### ${index + 1}\n\n${post}`)
+ .join('\n\n')}`);
+ }
+ if (cleanAttachments.length) {
+ sections.push(`## Attachments\n\n${cleanAttachments.map((path) => `- ${path}`).join('\n')}`);
+ }
+ return `${sections.join('\n\n')}\n`;
+}
+
+/** DOM events are not valid tweet ids when a click handler opens the picker. */
+export function normalizePostMediaPickerTarget(target) {
+ return Number.isInteger(target) ? target : null;
+}
+
+/** Build the conventional prefix used for a tweet that carries media. */
+export function mediaTweetLabel(type, number) {
+ return `${number}/ ${type === 'video' ? 'Video' : 'Image'}:`;
+}
+
+/** Build a media tweet from its conventional prefix and optional body. */
+export function mediaTweetText(type, text, number) {
+ const label = mediaTweetLabel(type, number);
+ return String(text ?? '').trim() ? `${label}\n${String(text).trim()}` : label;
+}
+
+/**
+ * Change an untouched media prefix when its attachment type changes. Once the
+ * analyst edits that prefix, their text is left alone.
+ */
+export function retargetMediaTweetText(text, currentType, nextType, number) {
+ const value = String(text ?? '');
+ const nextLabel = mediaTweetLabel(nextType, number);
+ if (!value.trim()) return nextLabel;
+ if (currentType === 'none') return value;
+
+ const currentLabel = mediaTweetLabel(currentType, number);
+ if (value.trim() === currentLabel) return nextLabel;
+ if (value.startsWith(`${currentLabel}\n`)) {
+ return `${nextLabel}${value.slice(currentLabel.length)}`;
+ }
+ return value;
+}
+
+/** Renumber an untouched media prefix while preserving custom text. */
+export function renumberMediaTweetText(text, type, currentNumber, nextNumber) {
+ const value = String(text ?? '');
+ const currentLabel = mediaTweetLabel(type, currentNumber);
+ const nextLabel = mediaTweetLabel(type, nextNumber);
+ if (value.trim() === currentLabel) return nextLabel;
+ if (value.startsWith(`${currentLabel}\n`)) {
+ return `${nextLabel}${value.slice(currentLabel.length)}`;
+ }
+ return value;
+}
+
+/** Create an editable media tweet at its position in the thread. */
+export function newPostMediaTweet(id, number, mediaType = 'none') {
+ return {
+ id,
+ text: mediaType === 'none' ? '' : mediaTweetText(mediaType, '', number),
+ mediaPaths: [],
+ mediaType,
+ isMediaTweet: true,
+ mediaTextIncludesPrefix: true,
+ };
+}
+
+/** Return the exact text copied for an extra context or media tweet. */
+export function extraPostTweetText(tweet, number) {
+ const text = String(tweet?.text ?? '').trim();
+ if (tweet?.mediaType === 'none' || !tweet?.mediaPaths?.length) return text;
+ return tweet.mediaTextIncludesPrefix ? text : mediaTweetText(tweet.mediaType, text, number);
+}
+
+/**
+ * Toggle one library item in a tweet's media selection. This composer keeps
+ * images and videos in separate tweets, so the other kind replaces the group.
+ */
+export function togglePostMedia({ mediaPaths = [], mediaType = 'none' }, item) {
+ if (!item || !['image', 'video'].includes(item.kind)) {
+ return { mediaPaths, mediaType, outcome: 'unsupported' };
+ }
+ if (mediaPaths.includes(item.path)) {
+ return {
+ mediaPaths: mediaPaths.filter((path) => path !== item.path),
+ mediaType,
+ outcome: 'removed',
+ };
+ }
+
+ const itemType = item.kind === 'video' ? 'video' : 'images';
+ if (mediaType !== 'none' && mediaType !== itemType) {
+ return { mediaPaths: [item.path], mediaType: itemType, outcome: 'replaced' };
+ }
+ if (mediaPaths.length >= MAX_POST_MEDIA) {
+ return { mediaPaths, mediaType, outcome: 'limit' };
+ }
+ return {
+ mediaPaths: [...mediaPaths, item.path],
+ mediaType: itemType,
+ outcome: 'added',
+ };
+}
+
+/** Show only the library items accepted by the tweet's selected media mode. */
+export function postMediaForType(items, mediaType) {
+ const kind = mediaType === 'video' ? 'video' : mediaType === 'images' ? 'image' : null;
+ return kind ? (items ?? []).filter((item) => item.kind === kind) : [];
+}
+
+/**
+ * Pack proof-linked media into same-type tweets while preserving the order in
+ * which each type first appears. Every group respects X's media-item limit.
+ */
+export function groupPostMedia(mediaPaths, kindForPath) {
+ const buckets = new Map();
+ for (const path of mediaPaths ?? []) {
+ const mediaType = kindForPath(path) === 'video' ? 'video' : 'images';
+ if (!buckets.has(mediaType)) buckets.set(mediaType, []);
+ buckets.get(mediaType).push(path);
+ }
+
+ const groups = [];
+ for (const [mediaType, paths] of buckets) {
+ for (let i = 0; i < paths.length; i += MAX_POST_MEDIA) {
+ groups.push({ mediaType, mediaPaths: paths.slice(i, i + MAX_POST_MEDIA) });
+ }
+ }
+ return groups;
+}
+
+// token → the field key it pulls its value from (see tweetFields)
+const TOKEN_FIELD = {
+ '#place': 'place',
+ '#pluscode': 'plusCode',
+ '#coordinates': 'coordinates',
+ '#description': 'description',
+ '#mention': 'mention',
+ '#source': 'source',
+};
+
+// A template can omit a draft field by leaving its token out of the body.
+// Coordinates also supply the plus code and can resolve a place, so keep that
+// field available whenever either of those tokens is present.
+const FIELD_TOKENS = {
+ description: ['#description'],
+ coordinates: ['#coordinates', '#pluscode', '#place'],
+ place: ['#place'],
+ mention: ['#mention'],
+ source: ['#source'],
+};
+
+const TOKEN_RE = /#(?:place|pluscode|coordinates|description|mention|source)/gi;
+
+// The classic GeoConfirmed thread, as a token body. Place + plus code on the
+// first line, then description, decimal coordinates, mention, and a labelled
+// source — each separated by a blank line.
+export const DEFAULT_TWEET_BODY = [
+ '#place - #pluscode',
+ '',
+ '#description',
+ '',
+ '#coordinates',
+ '',
+ '#mention',
+ '',
+ 'Source: #source',
+].join('\n');
+
+/** Resolve the live draft into the string each token stands for ('' when absent). */
+export function tweetFields({ place, plusCode, description, lat, lon, mention, source } = {}) {
+ return {
+ place: place?.trim() ?? '',
+ plusCode: plusCode ?? '',
+ coordinates:
+ lat != null && lon != null ? `${Number(lat).toFixed(6)}, ${Number(lon).toFixed(6)}` : '',
+ description: description?.trim() ?? '',
+ mention: mention?.trim() ?? '',
+ source: source?.trim() ?? '',
+ };
+}
+
+/**
+ * Render a thread body into the first tweet, substituting tokens with the
+ * draft's values. Layout rules, so a partly-filled draft still reads clean:
+ * - a line whose tokens are *all* empty is dropped whole (label and all) —
+ * "Source: #source" vanishes when there's no source, "#place - #pluscode"
+ * when neither is known;
+ * - a dangling separator left by one empty side of a combined line is trimmed
+ * ("Bakhmut - " → "Bakhmut");
+ * - runs of blank lines collapse to one, and the ends are trimmed.
+ */
+export function buildTweet1(body, rawFields = {}) {
+ const fields = tweetFields(rawFields);
+ const out = [];
+ for (const line of String(body ?? '').split('\n')) {
+ const tokens = line.match(TOKEN_RE);
+ if (tokens && tokens.every((t) => !fields[TOKEN_FIELD[t.toLowerCase()]])) {
+ continue; // token-driven line with nothing to show
+ }
+ let text = line.replace(TOKEN_RE, (m) => fields[TOKEN_FIELD[m.toLowerCase()]] ?? '');
+ text = text
+ .replace(/^\s*[-·,]\s*/, '') // leading separator from an empty first token
+ .replace(/\s*[-·,]\s*$/, '') // trailing separator from an empty last token
+ .replace(/[ \t]+$/, '');
+ out.push(text);
+ }
+ const collapsed = [];
+ for (const l of out) {
+ if (l.trim() === '' && collapsed[collapsed.length - 1]?.trim() === '') continue;
+ collapsed.push(l);
+ }
+ while (collapsed.length && collapsed[0].trim() === '') collapsed.shift();
+ while (collapsed.length && collapsed[collapsed.length - 1].trim() === '') collapsed.pop();
+ return collapsed.join('\n');
+}
+
+/** Whether a template body uses a draft field in its first tweet. */
+export function templateUsesPostField(body, field) {
+ const tokens = FIELD_TOKENS[field];
+ if (!tokens) return true;
+ const lowerBody = String(body ?? '').toLowerCase();
+ return tokens.some((token) => lowerBody.includes(token));
+}
+
+/**
+ * Find original downloaded media behind a proof whose source matches the proof
+ * source line. Derived PNGs, collages and satellite captures are excluded.
+ */
+export function proofSourceMediaPaths(caseData, proofPng, proofSource, mediaItems = []) {
+ const wantedUrls = new Set(String(proofSource ?? '').match(/https?:\/\/[^\s·]+/gi) ?? []);
+ if (!wantedUrls.size) return [];
+ const entities = Array.isArray(caseData?.entities) ? caseData.entities : [];
+ const links = Array.isArray(caseData?.links) ? caseData.links : [];
+ const proof = entities.find((e) => e.type === 'proof' && e.attrs?.path === proofPng);
+ if (!proof) return [];
+
+ const byId = new Map(entities.map((entity) => [entity.id, entity]));
+ const sources = new Map();
+ for (const link of links) {
+ if (link.type !== 'derived-from') continue;
+ const list = sources.get(link.from) ?? [];
+ list.push(link.to);
+ sources.set(link.from, list);
+ }
+
+ function collect(id, seen = new Set()) {
+ if (seen.has(id)) return [];
+ const nextSeen = new Set(seen);
+ nextSeen.add(id);
+ const entity = byId.get(id);
+ if (!entity) return [];
+ const children = (sources.get(id) ?? []).map((child) => byId.get(child)).filter(Boolean);
+ const mediaChildren = children.filter((child) => child.type === 'media');
+ if (entity.type === 'media') {
+ if (mediaChildren.length) return mediaChildren.flatMap((child) => collect(child.id, nextSeen));
+ return entity.attrs?.path ? [entity.attrs.path] : [];
+ }
+ return children.flatMap((child) => collect(child.id, nextSeen));
+ }
+
+ const itemByPath = new Map(mediaItems.map((item) => [item.path, item]));
+ return [...new Set(collect(proof.id))].filter((path) => {
+ const source = itemByPath.get(path)?.source;
+ if (source?.type !== 'download') return false;
+ return [source.url, source.webpage_url].some((url) => wantedUrls.has(url));
+ });
+}
+
+/** A legacy toggle template (pre-token) rebuilt as a body, for one-time migration. */
+function bodyFromLegacy(data) {
+ const t = data?.toggles;
+ if (!t) return DEFAULT_TWEET_BODY;
+ const parts = [];
+ if (t.showHeader) parts.push('#place - #pluscode');
+ if (t.showDescription) parts.push('#description');
+ if (t.showCoords) parts.push('#coordinates');
+ if (t.showMention) parts.push('#mention');
+ if (t.showSource) parts.push('Source: #source');
+ return parts.join('\n\n') || DEFAULT_TWEET_BODY;
+}
+
+/**
+ * A thread template's data blob from the composer's live settings. Content-free:
+ * the mention, the token body, whether a media tweet is scaffolded, and any
+ * boilerplate extra tweets (their text, no ids).
+ */
+export function templateFromPost({ mention = '@GeoConfirmed', body = DEFAULT_TWEET_BODY, mediaEnabled = true, extraTweets = [] } = {}) {
+ return {
+ mention: mention ?? '',
+ body: typeof body === 'string' && body.trim() ? body : DEFAULT_TWEET_BODY,
+ mediaEnabled: mediaEnabled !== false,
+ extraTweets: (extraTweets ?? []).map((e) => ({ text: e.text ?? '' })),
+ };
+}
+
+/**
+ * Normalise a stored template blob back into the composer's settings, filling
+ * shipped defaults (and migrating a legacy toggle template to a body).
+ */
+export function normPostTemplate(data = {}) {
+ const source = data && typeof data === 'object' && !Array.isArray(data) ? data : {};
+ return {
+ mention: typeof source.mention === 'string' ? source.mention.slice(0, 120) : '@GeoConfirmed',
+ body: typeof source.body === 'string' && source.body.trim()
+ ? source.body.slice(0, 16_000)
+ : bodyFromLegacy(source),
+ mediaEnabled: typeof source.mediaEnabled === 'boolean' ? source.mediaEnabled : true,
+ extraTweets: Array.isArray(source.extraTweets)
+ ? source.extraTweets.slice(0, 20).map((e) => ({
+ text: typeof e?.text === 'string' ? e.text.slice(0, 4_000) : '',
+ }))
+ : [],
+ };
+}
+
+/** Apply a post-template skeleton while dropping all current attachments. */
+export function applyPostTemplateStructure(current = {}, data = {}) {
+ const normalized = normPostTemplate(data);
+ return {
+ ...current,
+ ...normalized,
+ extraTweets: normalized.extraTweets.map((tweet) => ({
+ text: tweet.text,
+ mediaPaths: [],
+ mediaType: 'none',
+ isMediaTweet: false,
+ mediaTextIncludesPrefix: false,
+ })),
+ };
+}
diff --git a/frontend/src/lib/post.test.js b/frontend/src/lib/post.test.js
new file mode 100644
index 0000000..4c428af
--- /dev/null
+++ b/frontend/src/lib/post.test.js
@@ -0,0 +1,407 @@
+import { describe, it, expect } from 'vitest';
+import {
+ TWEET_TOKENS, DEFAULT_TWEET_BODY, tweetFields, buildTweet1,
+ extraPostTweetText, groupPostMedia, mediaTweetText, newPostMediaTweet,
+ applyPostTemplateStructure, normalizePostMediaPickerTarget, normPostTemplate, postMediaForType,
+ postCharacterCount, postComposeUrl, postReportMarkdown, postTarget,
+ proofSourceMediaPaths, renumberMediaTweetText, retargetMediaTweetText,
+ templateFromPost, templateUsesPostField, togglePostMedia,
+} from './post.js';
+
+const full = {
+ place: 'Bakhmut, Donetsk, Ukraine',
+ plusCode: '8FPGXXXX+XX',
+ description: 'Rooftop match',
+ lat: 48.85, lon: 2.35,
+ mention: '@GeoConfirmed',
+ source: 'https://x.com/a/1',
+};
+
+describe('tweetFields — resolve a draft into token values', () => {
+ it('formats coordinates to six decimals and trims text', () => {
+ const f = tweetFields({ ...full, place: ' Bakhmut ' });
+ expect(f.place).toBe('Bakhmut');
+ expect(f.coordinates).toBe('48.850000, 2.350000');
+ });
+
+ it('leaves absent tokens empty (no coords without a point)', () => {
+ const f = tweetFields({ mention: '' });
+ expect(f.coordinates).toBe('');
+ expect(f.mention).toBe('');
+ });
+});
+
+describe('buildTweet1 — the default body', () => {
+ it('renders the classic full thread', () => {
+ expect(buildTweet1(DEFAULT_TWEET_BODY, full)).toBe(
+ 'Bakhmut, Donetsk, Ukraine - 8FPGXXXX+XX\n\n' +
+ 'Rooftop match\n\n' +
+ '48.850000, 2.350000\n\n' +
+ '@GeoConfirmed\n\n' +
+ 'Source: https://x.com/a/1'
+ );
+ });
+});
+
+describe('buildTweet1 — token ordering + line control', () => {
+ it('honours a custom order', () => {
+ const body = '#coordinates\n#mention\n#place';
+ expect(buildTweet1(body, full)).toBe('48.850000, 2.350000\n@GeoConfirmed\nBakhmut, Donetsk, Ukraine');
+ });
+
+ it('keeps the analyst blank lines between tokens', () => {
+ expect(buildTweet1('#coordinates\n\n#source', full)).toBe('48.850000, 2.350000\n\nhttps://x.com/a/1');
+ });
+
+ it('drops a line whose tokens are all empty, label and all', () => {
+ // no source → the whole "Source: #source" line vanishes
+ const noSource = { ...full, source: '' };
+ expect(buildTweet1(DEFAULT_TWEET_BODY, noSource)).toBe(
+ 'Bakhmut, Donetsk, Ukraine - 8FPGXXXX+XX\n\nRooftop match\n\n48.850000, 2.350000\n\n@GeoConfirmed'
+ );
+ });
+
+ it('trims a dangling separator when one side of a combined line is empty', () => {
+ expect(buildTweet1('#place - #pluscode', { ...full, plusCode: '' })).toBe('Bakhmut, Donetsk, Ukraine');
+ expect(buildTweet1('#place - #pluscode', { ...full, place: '' })).toBe('8FPGXXXX+XX');
+ });
+
+ it('collapses blank-line runs and trims the ends', () => {
+ expect(buildTweet1('\n\n#coordinates\n\n\n\n#mention\n\n', full))
+ .toBe('48.850000, 2.350000\n\n@GeoConfirmed');
+ });
+
+ it('a coords-only body posts barebones', () => {
+ expect(buildTweet1('#coordinates', full)).toBe('48.850000, 2.350000');
+ });
+
+ it('keeps literal text on lines that also carry a filled token', () => {
+ expect(buildTweet1('Filmed at #place today', full)).toBe('Filmed at Bakhmut, Donetsk, Ukraine today');
+ });
+
+ it('exposes the insertable token palette', () => {
+ expect(TWEET_TOKENS.map((t) => t.tag)).toEqual([
+ '#place', '#pluscode', '#coordinates', '#description', '#mention', '#source',
+ ]);
+ for (const t of TWEET_TOKENS) expect(t.sample).toBeTruthy();
+ });
+});
+
+describe('editable media tweets', () => {
+ it('puts the media prefix in the tweet text', () => {
+ expect(mediaTweetText('video', '', 2)).toBe('2/ Video:');
+ expect(mediaTweetText('images', 'Caption', 2)).toBe('2/ Image:\nCaption');
+ expect(mediaTweetText('images', '', 3)).toBe('3/ Image:');
+ });
+
+ it('updates an untouched prefix when the selected media type changes', () => {
+ expect(retargetMediaTweetText('2/ Video:\nCaption', 'video', 'images', 2))
+ .toBe('2/ Image:\nCaption');
+ });
+
+ it('preserves a prefix the analyst edited', () => {
+ expect(retargetMediaTweetText('2/ Footage:\nCaption', 'video', 'images', 2))
+ .toBe('2/ Footage:\nCaption');
+ });
+
+ it('creates an empty third media tweet without choosing a type', () => {
+ expect(newPostMediaTweet(7, 3)).toEqual({
+ id: 7,
+ text: '',
+ mediaPaths: [],
+ mediaType: 'none',
+ isMediaTweet: true,
+ mediaTextIncludesPrefix: true,
+ });
+ });
+
+ it('adds the numbered prefix once a media type is known', () => {
+ expect(newPostMediaTweet(8, 3, 'video')).toEqual({
+ id: 8,
+ text: '3/ Video:',
+ mediaPaths: [],
+ mediaType: 'video',
+ isMediaTweet: true,
+ mediaTextIncludesPrefix: true,
+ });
+ });
+
+ it('renumbers an untouched prefix after an earlier tweet is removed', () => {
+ expect(renumberMediaTweetText('4/ Video:\nCaption', 'video', 4, 3))
+ .toBe('3/ Video:\nCaption');
+ expect(renumberMediaTweetText('Footage:\nCaption', 'video', 4, 3))
+ .toBe('Footage:\nCaption');
+ });
+
+ it('copies new prefixes verbatim and upgrades legacy media tweets', () => {
+ expect(extraPostTweetText({
+ text: '3/ Image:\nCaption', mediaPaths: ['media/a.jpg'],
+ mediaType: 'images', mediaTextIncludesPrefix: true,
+ }, 3)).toBe('3/ Image:\nCaption');
+ expect(extraPostTweetText({
+ text: 'Caption', mediaPaths: ['media/a.jpg'], mediaType: 'images',
+ }, 3)).toBe('3/ Image:\nCaption');
+ });
+});
+
+describe('togglePostMedia — manual media override', () => {
+ it('adds and removes an image', () => {
+ const image = { path: 'media/a.jpg', kind: 'image' };
+ const added = togglePostMedia({}, image);
+ expect(added).toEqual({ mediaPaths: ['media/a.jpg'], mediaType: 'images', outcome: 'added' });
+ expect(togglePostMedia(added, image)).toEqual({
+ mediaPaths: [], mediaType: 'images', outcome: 'removed',
+ });
+ });
+
+ it('replaces proof-filled video when an image is selected', () => {
+ expect(togglePostMedia(
+ { mediaPaths: ['media/source.mp4'], mediaType: 'video' },
+ { path: 'media/override.jpg', kind: 'image' },
+ )).toEqual({
+ mediaPaths: ['media/override.jpg'], mediaType: 'images', outcome: 'replaced',
+ });
+ });
+
+ it('keeps the current selection when the limit is reached', () => {
+ const mediaPaths = ['media/1.jpg', 'media/2.jpg', 'media/3.jpg', 'media/4.jpg'];
+ expect(togglePostMedia(
+ { mediaPaths, mediaType: 'images' },
+ { path: 'media/5.jpg', kind: 'image' },
+ )).toEqual({ mediaPaths, mediaType: 'images', outcome: 'limit' });
+ });
+});
+
+describe('postMediaForType — picker filtering', () => {
+ const items = [
+ { path: 'media/a.jpg', kind: 'image' },
+ { path: 'media/b.mp4', kind: 'video' },
+ { path: 'media/c.mp3', kind: 'audio' },
+ ];
+
+ it('shows only images in image mode', () => {
+ expect(postMediaForType(items, 'images')).toEqual([items[0]]);
+ });
+
+ it('shows only videos in video mode', () => {
+ expect(postMediaForType(items, 'video')).toEqual([items[1]]);
+ });
+});
+
+describe('normalizePostMediaPickerTarget — tweet 2 regression', () => {
+ it('treats a click event as tweet 2 instead of an extra-tweet id', () => {
+ expect(normalizePostMediaPickerTarget({ type: 'click' })).toBeNull();
+ });
+
+ it('keeps an extra tweet id', () => {
+ expect(normalizePostMediaPickerTarget(3)).toBe(3);
+ });
+});
+
+describe('groupPostMedia — proof media tweets', () => {
+ const kind = (path) => path.endsWith('.mp4') ? 'video' : 'image';
+
+ it('packs up to four files of the same type into one tweet', () => {
+ expect(groupPostMedia(
+ ['media/1.mp4', 'media/2.mp4', 'media/3.mp4', 'media/4.mp4'], kind,
+ )).toEqual([{
+ mediaType: 'video',
+ mediaPaths: ['media/1.mp4', 'media/2.mp4', 'media/3.mp4', 'media/4.mp4'],
+ }]);
+ });
+
+ it('separates images and videos', () => {
+ expect(groupPostMedia(
+ ['media/1.mp4', 'media/1.jpg', 'media/2.mp4', 'media/2.jpg'], kind,
+ )).toEqual([
+ { mediaType: 'video', mediaPaths: ['media/1.mp4', 'media/2.mp4'] },
+ { mediaType: 'images', mediaPaths: ['media/1.jpg', 'media/2.jpg'] },
+ ]);
+ });
+
+ it('starts another same-type tweet after four files', () => {
+ expect(groupPostMedia(
+ ['media/1.jpg', 'media/2.jpg', 'media/3.jpg', 'media/4.jpg', 'media/5.jpg'], kind,
+ )).toEqual([
+ { mediaType: 'images', mediaPaths: ['media/1.jpg', 'media/2.jpg', 'media/3.jpg', 'media/4.jpg'] },
+ { mediaType: 'images', mediaPaths: ['media/5.jpg'] },
+ ]);
+ });
+});
+
+describe('templateFromPost / normPostTemplate — round-trip', () => {
+ it('captures mention, body, media and extra-tweet skeleton, no content', () => {
+ const t = templateFromPost({
+ mention: '@Desk',
+ body: '#coordinates\n#source',
+ mediaEnabled: false,
+ extraTweets: [{ id: 1, text: 'Boilerplate close' }],
+ });
+ expect(t).toEqual({
+ mention: '@Desk',
+ body: '#coordinates\n#source',
+ mediaEnabled: false,
+ extraTweets: [{ text: 'Boilerplate close' }],
+ });
+ });
+
+ it('falls back to the default body when none is given', () => {
+ expect(templateFromPost({ mention: '@x' }).body).toBe(DEFAULT_TWEET_BODY);
+ expect(templateFromPost({ body: ' ' }).body).toBe(DEFAULT_TWEET_BODY);
+ });
+
+ it('fills shipped defaults for a bare blob', () => {
+ expect(normPostTemplate({})).toEqual({
+ mention: '@GeoConfirmed', body: DEFAULT_TWEET_BODY, mediaEnabled: true, extraTweets: [],
+ });
+ });
+
+ it('migrates a legacy toggle template to a token body', () => {
+ const legacy = { toggles: { showHeader: false, showDescription: false, showCoords: true, showMention: false, showSource: true } };
+ expect(normPostTemplate(legacy).body).toBe('#coordinates\n\nSource: #source');
+ });
+
+ it('a token template survives a save → normalise round-trip unchanged', () => {
+ const stored = templateFromPost({
+ mention: '@Desk', body: '#place\n#coordinates', mediaEnabled: false,
+ extraTweets: [{ text: 'a' }, { text: 'b' }],
+ });
+ expect(normPostTemplate(stored)).toEqual(stored);
+ });
+
+ it('preserves an intentionally blank mention', () => {
+ const stored = templateFromPost({ mention: '', body: '#place' });
+ expect(normPostTemplate(stored).mention).toBe('');
+ });
+
+ it('caps malformed hand-edited arrays and strings', () => {
+ const normalized = normPostTemplate({
+ mention: 'm'.repeat(200),
+ body: 'b'.repeat(20_000),
+ extraTweets: Array.from({ length: 25 }, () => ({ text: 'x'.repeat(5_000) })),
+ });
+ expect(normalized.mention).toHaveLength(120);
+ expect(normalized.body).toHaveLength(16_000);
+ expect(normalized.extraTweets).toHaveLength(20);
+ expect(normalized.extraTweets[0].text).toHaveLength(4_000);
+ });
+});
+
+describe('applyPostTemplateStructure — replace the whole skeleton', () => {
+ it('clears existing extra posts when the template has none', () => {
+ const current = {
+ mention: '@Old', body: '#source', mediaEnabled: true,
+ extraTweets: [{ text: 'Old', mediaPaths: ['media/a.png'] }],
+ };
+ const applied = applyPostTemplateStructure(current, {
+ mention: '', body: '#place', mediaEnabled: false, extraTweets: [],
+ });
+ expect(applied).toMatchObject({
+ mention: '', body: '#place', mediaEnabled: false, extraTweets: [],
+ });
+ });
+
+ it('drops attachments when creating template extra posts', () => {
+ const applied = applyPostTemplateStructure({}, { extraTweets: [{ text: 'Close' }] });
+ expect(applied.extraTweets).toEqual([{
+ text: 'Close', mediaPaths: [], mediaType: 'none',
+ isMediaTweet: false, mediaTextIncludesPrefix: false,
+ }]);
+ });
+});
+
+describe('templateUsesPostField — compose fields controlled by a template', () => {
+ it('disables fields whose tokens are absent', () => {
+ const body = '#coordinates\n#source';
+ expect(templateUsesPostField(body, 'coordinates')).toBe(true);
+ expect(templateUsesPostField(body, 'source')).toBe(true);
+ expect(templateUsesPostField(body, 'description')).toBe(false);
+ expect(templateUsesPostField(body, 'place')).toBe(false);
+ expect(templateUsesPostField(body, 'mention')).toBe(false);
+ });
+
+ it('keeps coordinates available when they can resolve a place or plus code', () => {
+ expect(templateUsesPostField('#place', 'coordinates')).toBe(true);
+ expect(templateUsesPostField('#pluscode', 'coordinates')).toBe(true);
+ });
+});
+
+describe('proofSourceMediaPaths — source media selected from a proof', () => {
+ it('uses original source media behind a derived frame', () => {
+ const data = {
+ entities: [
+ { id: 'proof', type: 'proof', attrs: { path: 'proofs/check.png' } },
+ { id: 'frame', type: 'media', attrs: { path: 'media/frame.jpg', kind: 'image' } },
+ { id: 'video', type: 'media', attrs: { path: 'media/clip.mp4', kind: 'video' } },
+ { id: 'photo', type: 'media', attrs: { path: 'media/still.jpg', kind: 'image' } },
+ { id: 'capture', type: 'capture', attrs: { path: 'media/satellite.png', kind: 'image' } },
+ { id: 'collage', type: 'media', attrs: { path: 'media/collage.png', kind: 'image' } },
+ ],
+ links: [
+ { from: 'proof', to: 'frame', type: 'derived-from' },
+ { from: 'proof', to: 'photo', type: 'derived-from' },
+ { from: 'proof', to: 'capture', type: 'derived-from' },
+ { from: 'proof', to: 'collage', type: 'derived-from' },
+ { from: 'frame', to: 'video', type: 'derived-from' },
+ ],
+ };
+ const media = [
+ { path: 'media/frame.jpg', source: { type: 'inspect', from: 'media/clip.mp4' } },
+ { path: 'media/clip.mp4', source: { type: 'download', url: 'https://source.test/post', webpage_url: 'https://source.test/post' } },
+ { path: 'media/still.jpg', source: { type: 'download', url: 'https://other.test/post' } },
+ { path: 'media/collage.png', source: { op: 'collage', sources: ['media/still.jpg'] } },
+ ];
+ expect(proofSourceMediaPaths(data, 'proofs/check.png', 'https://source.test/post', media))
+ .toEqual(['media/clip.mp4']);
+ });
+
+ it('does not select media without a matching proof source', () => {
+ expect(proofSourceMediaPaths({ entities: [], links: [] }, 'proofs/missing.png', 'https://source.test/post')).toEqual([]);
+ });
+});
+
+describe('post targets', () => {
+ it('keeps legacy and unknown draft targets on X', () => {
+ expect(postTarget()).toMatchObject({ id: 'x', limit: 280 });
+ expect(postTarget('unknown')).toMatchObject({ id: 'x' });
+ });
+
+ it('counts links for X and Mastodon, but graphemes for Bluesky', () => {
+ expect(postCharacterCount('x', 'A https://example.test/very-long-url')).toBe(25);
+ expect(postCharacterCount('mastodon', 'A https://example.test/very-long-url')).toBe(25);
+ expect(postCharacterCount('bluesky', 'A https://example.test/very-long-url')).toBe(36);
+ expect(postCharacterCount('bluesky', '👍🏽')).toBe(1);
+ });
+
+ it('builds the official compose handoff for each social target', () => {
+ expect(postComposeUrl('x', 'A post')).toBe('https://x.com/intent/post?text=A%20post');
+ expect(postComposeUrl('bluesky', 'A post')).toBe('https://bsky.app/intent/compose?text=A%20post');
+ expect(postComposeUrl('mastodon', 'A post')).toBe('https://share.joinmastodon.org/#text=A%20post');
+ });
+});
+
+describe('postReportMarkdown', () => {
+ it('renders the prepared facts, posts and attachments as portable Markdown', () => {
+ expect(postReportMarkdown({
+ title: 'Rooftop match',
+ place: 'Bakhmut, Ukraine',
+ plusCode: '8FPGXXXX+XX',
+ coordinates: '48.850000, 2.350000',
+ description: 'Match against reference imagery.',
+ source: 'https://example.test/source',
+ posts: ['First post', 'Second post'],
+ attachments: ['proofs/match.png', 'media/a.jpg', 'media/a.jpg'],
+ })).toBe(
+ '# Rooftop match\n\n' +
+ '## Location\n\nPlace: Bakhmut, Ukraine\nPlus code: 8FPGXXXX+XX\nCoordinates: 48.850000, 2.350000\n\n' +
+ '## Assessment\n\nMatch against reference imagery.\n\n' +
+ '## Source\n\nhttps://example.test/source\n\n' +
+ '## Prepared posts\n\n### 1\n\nFirst post\n\n### 2\n\nSecond post\n\n' +
+ '## Attachments\n\n- proofs/match.png\n- media/a.jpg\n'
+ );
+ });
+
+ it('always gives an otherwise empty export a title', () => {
+ expect(postReportMarkdown()).toBe('# Untitled report\n');
+ });
+});
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index 82cba9e..7c90a73 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -20,6 +20,8 @@ export const prefs = $state({
units: 'metric', // 'metric' | 'imperial'
homeView: { lat: 48.8584, lon: 2.2945, zoom: 16 }, // where Satellite opens
postMention: '@GeoConfirmed', // handle a fresh post draft is addressed to
+ postTarget: 'x', // social composer a fresh post draft starts with
+ signatureHandle: '', // account handle stamped onto proofs that opt into it
updateCheckOnStart: true, // ask GitHub for a newer release when the page loads
updateDismissedVersion: '', // the release tag muted with "don't show again"
});
@@ -64,6 +66,8 @@ export function applyPrefs(s) {
if (s.units) prefs.units = s.units;
if (s.home_view) prefs.homeView = s.home_view;
if (s.post_mention !== undefined) prefs.postMention = s.post_mention; // '' = none
+ if (s.post_target !== undefined) prefs.postTarget = s.post_target;
+ if (s.signature_handle !== undefined) prefs.signatureHandle = s.signature_handle; // '' = none
if (s.update_check_on_start !== undefined) prefs.updateCheckOnStart = s.update_check_on_start;
if (s.update_dismissed_version !== undefined)
prefs.updateDismissedVersion = s.update_dismissed_version;
@@ -110,11 +114,43 @@ export const caseState = $state({
rev: 0, // bumped on every reload so tools can re-fetch their own artifacts
});
+/**
+ * Reusable house-style presets (Settings → Templates), app-wide like the
+ * signature. Two families: `proof` (a proof's layout/colours/legend) and
+ * `post` (a thread skeleton). Loaded once at startup and refreshed whenever
+ * Settings edits one, so the composers' "start from a template" menus stay
+ * current without re-fetching. Each entry: { id, name, updated_at, data }.
+ */
+export const templatesState = $state({ proof: [], post: [] });
+
+export async function loadTemplates() {
+ try {
+ const t = await api.get('/api/templates');
+ templatesState.proof = Array.isArray(t.proof) ? t.proof : [];
+ templatesState.post = Array.isArray(t.post) ? t.post : [];
+ } catch {
+ /* templates are a convenience; an empty store is a fine fallback */
+ }
+}
+
+/** Create or update a preset (id present → update), then refresh the store. */
+export async function saveTemplate(kind, { id, name, data }) {
+ const rec = await api.post(`/api/templates/${kind}`, { id, name, data });
+ await loadTemplates();
+ return rec;
+}
+
+export async function deleteTemplate(kind, id) {
+ await api.del(`/api/templates/${kind}/${id}`);
+ await loadTemplates();
+}
+
export const uiState = $state({
- tool: 'media', // 'media' | 'inspect' | 'satellite' | 'proof' | 'post'
+ tool: 'media', // 'media' | 'inspect' | 'satellite' | 'proof' | 'post' | 'settings'
sidebarOpen: true,
sidebarW: loadWidth(), // px, drag-resizable and remembered across reloads
toasts: [],
+ settingsTab: null, // settings section id to open when switching to Settings
// cross-tool handoffs (the workbench glue):
composeQueue: [], // media paths queued for the Proof Composer
postProof: null, // proof spec handed to the Post Composer
@@ -191,6 +227,7 @@ export async function initSession() {
// preferences must land before the tools render, or coordinates would flash
// in the wrong format; a settings read failure is never fatal to a session
await loadPrefs().catch(() => {});
+ await loadTemplates().catch(() => {});
await refreshCaseList();
let lastId = null;
try {
diff --git a/frontend/src/lib/state.test.js b/frontend/src/lib/state.test.js
index e4a252d..4a2f452 100644
--- a/frontend/src/lib/state.test.js
+++ b/frontend/src/lib/state.test.js
@@ -5,7 +5,7 @@ import { MIN_W, MAX_W } from './sidebar.js';
// The prefs tests below exercise import-time module state, so the transport is
// stubbed and the module re-imported fresh per test. The static import above
// still works: these tests never call the API.
-vi.mock('./api.js', () => ({ api: { get: vi.fn() } }));
+vi.mock('./api.js', () => ({ api: { get: vi.fn(), post: vi.fn(), del: vi.fn() } }));
async function freshState() {
vi.resetModules();
@@ -104,8 +104,60 @@ describe('applyPrefs', () => {
expect(prefs.coordFormat).toBe('mgrs');
expect(prefs.units).toBe('imperial');
expect(prefs.postMention).toBe('@GeoConfirmed'); // untouched by a partial payload
+ expect(prefs.postTarget).toBe('x'); // untouched by a partial payload
+ expect(prefs.signatureHandle).toBe(''); // untouched by a partial payload
applyPrefs({ post_mention: '' }); // an empty mention is a real choice, not absence
expect(prefs.postMention).toBe('');
+
+ applyPrefs({ post_target: 'bluesky' });
+ expect(prefs.postTarget).toBe('bluesky');
+
+ applyPrefs({ signature_handle: '@example' });
+ expect(prefs.signatureHandle).toBe('@example');
+ });
+});
+
+describe('templates store', () => {
+ let api;
+ beforeEach(async () => {
+ ({ api } = await import('./api.js'));
+ api.get.mockReset();
+ api.post.mockReset();
+ api.del.mockReset();
+ });
+
+ it('loadTemplates mirrors both families, tolerating a bad payload', async () => {
+ const { loadTemplates, templatesState } = await freshState();
+ ({ api } = await import('./api.js'));
+ api.get.mockResolvedValue({ proof: [{ id: 'a', name: 'Dark' }], post: [{ id: 'b', name: 'Terse' }] });
+ await loadTemplates();
+ expect(templatesState.proof.map((t) => t.id)).toEqual(['a']);
+ expect(templatesState.post.map((t) => t.id)).toEqual(['b']);
+
+ api.get.mockRejectedValue(new Error('offline'));
+ await loadTemplates(); // never throws; leaves the last good store
+ expect(templatesState.proof.map((t) => t.id)).toEqual(['a']);
+ });
+
+ it('saveTemplate posts to the kind endpoint then refreshes the store', async () => {
+ const { saveTemplate, templatesState } = await freshState();
+ ({ api } = await import('./api.js'));
+ api.post.mockResolvedValue({ id: 'x', name: 'Dark', data: {} });
+ api.get.mockResolvedValue({ proof: [{ id: 'x', name: 'Dark' }], post: [] });
+ const rec = await saveTemplate('proof', { name: 'Dark', data: { bg: '#000' } });
+ expect(api.post).toHaveBeenCalledWith('/api/templates/proof', { name: 'Dark', data: { bg: '#000' } });
+ expect(rec.id).toBe('x');
+ expect(templatesState.proof).toHaveLength(1);
+ });
+
+ it('deleteTemplate hits the id endpoint then refreshes', async () => {
+ const { deleteTemplate, templatesState } = await freshState();
+ ({ api } = await import('./api.js'));
+ api.del.mockResolvedValue({ deleted: true });
+ api.get.mockResolvedValue({ proof: [], post: [] });
+ await deleteTemplate('post', 'b');
+ expect(api.del).toHaveBeenCalledWith('/api/templates/post/b');
+ expect(templatesState.post).toEqual([]);
});
});
diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelte
index ff039b8..772b1cf 100644
--- a/frontend/src/tools/PostComposer.svelte
+++ b/frontend/src/tools/PostComposer.svelte
@@ -1,15 +1,21 @@
<script>
import { api } from '../lib/api.js';
import { caseState, uiState, toast, reloadCase, prefs } from '../lib/state.svelte.js';
+ import { templatesState } from '../lib/state.svelte.js';
import { proofCoordsText, proofSource, DEFAULT_PROOF_TITLE } from '../lib/composer.js';
+ import {
+ buildTweet1 as buildTweet1Lines, DEFAULT_TWEET_BODY,
+ extraPostTweetText, groupPostMedia, MAX_POST_MEDIA, mediaTweetText,
+ applyPostTemplateStructure, newPostMediaTweet, proofSourceMediaPaths,
+ normalizePostMediaPickerTarget, postMediaForType, renumberMediaTweetText, retargetMediaTweetText,
+ normalizePostTarget, POST_TARGETS, postCharacterCount, postComposeUrl, postReportMarkdown,
+ postTarget, templateUsesPostField, togglePostMedia,
+ } from '../lib/post.js';
import { bidiSafe } from '../lib/bidi.js';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
- const X_LIMIT = 280;
- const URL_WEIGHT = 23; // X counts every URL as 23 chars
-
let coordsText = $state('');
let geo = $state(null); // {lat, lon, dms, plus_code, links}
let place = $state('');
@@ -21,16 +27,23 @@
let proofVer = $state(0); // cache-buster: bumped whenever proofPng is (re)assigned
let tweet1 = $state('');
let tweet1Edited = $state(false);
+ let target = $state('x');
+ const targetInfo = $derived(postTarget(target));
+
+ // The active thread layout — a token body (lib/post.js). buildTweet1 fills the
+ // tokens from the draft. A post template swaps this out; the default is the
+ // classic GeoConfirmed thread.
+ let body = $state(DEFAULT_TWEET_BODY);
// Media tweet (tweet 2)
let mediaEnabled = $state(true);
let mediaType = $state('none'); // 'none' | 'video' | 'images'
- let mediaText = $state('');
- let mediaPath = $state(null); // media selected from the library (case-relative)
+ let mediaText = $state(''); // complete, editable tweet 2 text (prefix included)
+ let mediaPaths = $state([]); // local media selected for tweet 2 (case-relative)
// Extra context tweets (3, 4, …)
let extraSeq = 0;
- let extraTweets = $state([]); // [{ id, text }]
+ let extraTweets = $state([]); // [{ id, text, mediaPaths, mediaType }]
// Draft persistence
let draftName = $state(null); // slug of the saved draft (null until first save)
@@ -58,6 +71,7 @@
// Media picker modal
let pickerOpen = $state(false);
let mediaLibrary = $state([]);
+ let mediaPickerTarget = $state(null); // null = tweet 2; an id = a later media tweet
// Proof picker modal
let proofPickerOpen = $state(false);
@@ -80,8 +94,10 @@
if (!p) return;
uiState.postProof = null;
description = p.title === DEFAULT_PROOF_TITLE ? '' : (p.title ?? '');
- source = p.source ?? p.sources?.[0] ?? '';
+ const proofSourceUrl = p.source ?? p.sources?.[0] ?? '';
+ source = proofSourceUrl;
setProof(p.png ?? null);
+ preloadProofMedia(p.png, proofSourceUrl);
tweet1Edited = false;
coordsText = p.coordsText
?? (p.coords ? `${p.coords.lat.toFixed(6)}, ${p.coords.lon.toFixed(6)}` : '');
@@ -132,114 +148,240 @@
}
function buildTweet1() {
- const lines = [];
+ return buildTweet1Lines(body, {
+ place,
+ plusCode: geo?.plus_code,
+ description,
+ lat: geo?.lat,
+ lon: geo?.lon,
+ mention,
+ source,
+ });
+ }
- // "Place, State, Country - PLUSCODE"
- const header = [place.trim(), geo?.plus_code].filter(Boolean).join(' - ');
- if (header) lines.push(header);
+ function regenerate() {
+ tweet1 = buildTweet1();
+ tweet1Edited = false;
+ }
- // description
- if (description.trim()) {
- lines.push('');
- lines.push(description.trim());
- }
+ // ---- thread templates ----------------------------------------------------
+ // Apply a saved post template (Settings → Templates). Content-free: only
+ // the mention, token body, media flag and boilerplate extra tweets travel.
+ // The thread structure laid over this draft: { name, prev } so "Discard" can
+ // walk back to the structure the draft had before. UI-only, cleared whenever
+ // the draft is reset or a saved one is opened.
+ let appliedPostTemplate = $state(null);
- // decimal coords only (6 digits), no DMS
- if (geo) {
- lines.push('');
- lines.push(`${geo.lat.toFixed(6)}, ${geo.lon.toFixed(6)}`);
- }
+ const TEMPLATE_FIELD_HINT = 'This template does not use this field.';
- // mention (@GeoConfirmed by default)
- if (mention.trim()) {
- lines.push('');
- lines.push(mention.trim());
- }
+ function fieldDisabledByTemplate(field) {
+ return !!appliedPostTemplate && !templateUsesPostField(body, field);
+ }
- // source
- if (source.trim()) {
- lines.push('');
- lines.push('Source:');
- lines.push(source.trim());
- }
+ // The four structural fields a template swaps, snapshotted for a clean restore.
+ function snapshotPostStructure() {
+ return {
+ mention,
+ body,
+ mediaEnabled,
+ extraTweets: extraTweets.map((e) => ({
+ text: e.text,
+ mediaPaths: [...e.mediaPaths],
+ mediaType: e.mediaType,
+ isMediaTweet: e.isMediaTweet === true,
+ mediaTextIncludesPrefix: e.mediaTextIncludesPrefix === true,
+ })),
+ };
+ }
- return lines.join('\n');
+ function applyPostTemplate(t) {
+ // first apply snapshots the current structure; re-applying keeps that
+ // original, so Discard always returns to the pre-template layout.
+ const prev = appliedPostTemplate?.prev ?? snapshotPostStructure();
+ const norm = applyPostTemplateStructure({}, t.data);
+ mention = norm.mention;
+ body = norm.body;
+ mediaEnabled = norm.mediaEnabled;
+ extraTweets = norm.extraTweets.map((e) => ({ id: ++extraSeq, ...e }));
+ appliedPostTemplate = { name: t.name, prev };
+ if (!tweet1Edited) regenerate();
+ toast(`Template loaded: ${t.name}`, 'ok', 1400);
}
- function regenerate() {
- tweet1 = buildTweet1();
- tweet1Edited = false;
+ function applyPostFromSelect(e) {
+ const t = templatesState.post.find((x) => x.id === e.target.value);
+ e.target.value = '';
+ if (t) applyPostTemplate(t);
}
- function weightedLength(t) {
- // count the bidi-safe text that actually gets copied, so the counter
- // stays honest for Arabic/Hebrew threads (isolates counted, worst case)
- const safe = bidiSafe(t);
- const urlRe = /https?:\/\/\S+/g;
- const stripped = safe.replace(urlRe, '');
- const urls = safe.match(urlRe)?.length ?? 0;
- return [...stripped].length + urls * URL_WEIGHT;
+ function discardPostTemplate() {
+ if (!appliedPostTemplate) return;
+ const p = appliedPostTemplate.prev;
+ mention = p.mention;
+ body = p.body;
+ mediaEnabled = p.mediaEnabled;
+ extraTweets = p.extraTweets.map((e) => ({
+ id: ++extraSeq,
+ text: e.text,
+ mediaPaths: [...(e.mediaPaths ?? [])],
+ mediaType: e.mediaType ?? 'none',
+ isMediaTweet: e.isMediaTweet === true,
+ mediaTextIncludesPrefix: e.mediaTextIncludesPrefix === true,
+ }));
+ appliedPostTemplate = null;
+ if (!tweet1Edited) regenerate();
+ toast('Template removed', 'ok', 1200);
+ }
+
+ function openTemplateSettings() {
+ uiState.settingsTab = 'templates';
+ uiState.tool = 'settings';
+ }
+
+ function targetLength(text) {
+ // Count the bidi-safe text that gets copied, so coordinates, plus codes,
+ // mentions and URLs stay honest in right-to-left posts too.
+ return postCharacterCount(target, bidiSafe(text));
}
function tweet2Text() {
- const label = mediaType === 'video' ? '2/ Video:' : '2/ Image:';
- return mediaText.trim() ? `${label}\n${mediaText.trim()}` : label;
+ return mediaText.trim();
}
- const tweet1Count = $derived(weightedLength(tweet1));
- const tweet1Over = $derived(tweet1Count > X_LIMIT);
+ const tweet1Count = $derived(targetLength(tweet1));
+ const tweet1Over = $derived(tweet1Count > targetInfo.limit);
function addExtraTweet() {
- extraTweets.push({ id: ++extraSeq, text: '' });
+ extraTweets.push({
+ id: ++extraSeq, text: '', mediaPaths: [], mediaType: 'none',
+ isMediaTweet: false,
+ mediaTextIncludesPrefix: false,
+ });
+ }
+
+ function addMediaTweet() {
+ extraTweets.push(newPostMediaTweet(++extraSeq, extraTweets.length + 3));
}
function removeExtraTweet(id) {
const i = extraTweets.findIndex((t) => t.id === id);
- if (i !== -1) extraTweets.splice(i, 1);
+ if (i === -1) return;
+ extraTweets.splice(i, 1);
+ for (let j = i; j < extraTweets.length; j += 1) {
+ const tweet = extraTweets[j];
+ if (!tweet.mediaTextIncludesPrefix || tweet.mediaType === 'none') continue;
+ tweet.text = renumberMediaTweetText(tweet.text, tweet.mediaType, j + 4, j + 3);
+ }
}
- // Copies go through bidiSafe: Arabic/Hebrew threads keep coordinates,
- // plus codes, @mentions and URLs reading left-to-right on X (see lib/bidi).
+ function extraTweetText(tweet, number) {
+ return extraPostTweetText(tweet, number);
+ }
+
+ // Copies go through bidiSafe so coordinates, plus codes, mentions and URLs
+ // keep reading left-to-right in Arabic or Hebrew posts (see lib/bidi).
async function copy(value) {
await navigator.clipboard.writeText(bidiSafe(value));
toast('Copied to clipboard', 'ok', 1600);
}
- async function copyAll() {
+ function threadParts() {
const parts = [tweet1];
if (mediaEnabled && mediaType !== 'none') parts.push(tweet2Text());
- for (const t of extraTweets) {
- if (t.text.trim()) parts.push(t.text.trim());
+ for (let i = 0; i < extraTweets.length; i += 1) {
+ const tweet = extraTweets[i];
+ const text = extraTweetText(tweet, i + 3);
+ if (text) parts.push(text);
}
+ return parts.filter((part) => part.trim());
+ }
+
+ async function copyAll(showToast = true) {
+ const parts = threadParts();
await navigator.clipboard.writeText(parts.map(bidiSafe).join('\n\n---\n\n'));
- toast('All tweets copied', 'ok', 1800);
+ if (showToast) toast('All posts copied', 'ok', 1800);
}
// ---- media picker -------------------------------------------------------
- async function openPicker() {
+ async function openPicker(target = null) {
if (!caseState.current) {
toast('Open a case to pick from your media', 'warn');
return;
}
try {
mediaLibrary = await api.get(`/api/cases/${caseState.current.id}/media`);
+ mediaPickerTarget = normalizePostMediaPickerTarget(target);
pickerOpen = true;
} catch (e) {
toast(e.message, 'danger');
}
}
+ function pickerTweet() {
+ return mediaPickerTarget === null
+ ? { mediaPaths, mediaType }
+ : extraTweets.find((tweet) => tweet.id === mediaPickerTarget);
+ }
+
+ function pickerItems() {
+ return postMediaForType(mediaLibrary, pickerTweet()?.mediaType);
+ }
+
+ function pickerTitle() {
+ const tweet = pickerTweet();
+ const kind = tweet?.mediaType === 'video' ? 'videos' : 'images';
+ return `Choose ${kind} (${tweet?.mediaPaths.length ?? 0}/${MAX_POST_MEDIA})`;
+ }
+
function pickMedia(item) {
- mediaPath = item.path;
- // auto-select the matching media type from the item's kind
- if (item.kind === 'video') mediaType = 'video';
- else if (item.kind === 'image') mediaType = 'images';
- pickerOpen = false;
+ const tweet = pickerTweet();
+ if (!tweet) return;
+ const selection = togglePostMedia(tweet, item);
+ if (selection.outcome === 'unsupported') {
+ toast('Post media must be an image or video', 'warn');
+ return;
+ }
+ if (selection.outcome === 'limit') {
+ toast(`A post can hold up to ${MAX_POST_MEDIA} media files`, 'warn');
+ return;
+ }
+ if (mediaPickerTarget === null) {
+ mediaText = retargetMediaTweetText(mediaText, mediaType, selection.mediaType, 2);
+ mediaPaths = selection.mediaPaths;
+ mediaType = selection.mediaType;
+ } else {
+ tweet.mediaPaths = selection.mediaPaths;
+ tweet.mediaType = selection.mediaType;
+ }
}
- function clearMedia() {
- mediaPath = null;
+ function clearMedia(path) {
+ mediaPaths = mediaPaths.filter((entry) => entry !== path);
+ }
+
+ function clearExtraMedia(id, path) {
+ const tweet = extraTweets.find((entry) => entry.id === id);
+ if (!tweet) return;
+ tweet.mediaPaths = tweet.mediaPaths.filter((entry) => entry !== path);
+ }
+
+ function setMediaType(type) {
+ if (mediaType === type) return;
+ mediaPaths = [];
+ mediaText = retargetMediaTweetText(mediaText, mediaType, type, 2);
+ mediaType = type;
+ }
+
+ function setExtraMediaType(tweet, type) {
+ if (tweet.mediaType === type) return;
+ const number = extraTweets.findIndex((entry) => entry.id === tweet.id) + 3;
+ tweet.mediaPaths = [];
+ if (tweet.mediaTextIncludesPrefix) {
+ tweet.text = retargetMediaTweetText(tweet.text, tweet.mediaType, type, number);
+ }
+ tweet.mediaType = type;
+ tweet.isMediaTweet = true;
}
// ---- proof picker -------------------------------------------------------
@@ -252,6 +394,40 @@
proofVer = png ? Date.now() : 0;
}
+ async function preloadProofMedia(png, proofSourceUrl) {
+ if (!png || !proofSourceUrl || !caseState.current) return;
+ try {
+ const library = await api.get(`/api/cases/${caseState.current.id}/media`);
+ const linkedMedia = proofSourceMediaPaths(caseState.current, png, proofSourceUrl, library);
+ if (!linkedMedia.length) return;
+
+ const selected = new Set([
+ ...mediaPaths,
+ ...extraTweets.flatMap((tweet) => tweet.mediaPaths),
+ ]);
+ const added = linkedMedia.filter((path) => !selected.has(path));
+ if (!added.length) return;
+ const groups = groupPostMedia(added, mediaKind);
+
+ if (!mediaPaths.length && groups.length) {
+ const first = groups.shift();
+ mediaPaths = first.mediaPaths;
+ mediaEnabled = true;
+ const nextType = first.mediaType;
+ mediaText = retargetMediaTweetText(mediaText, mediaType, nextType, 2);
+ mediaType = nextType;
+ }
+ for (const group of groups) {
+ const tweet = newPostMediaTweet(++extraSeq, extraTweets.length + 3, group.mediaType);
+ tweet.mediaPaths = group.mediaPaths;
+ extraTweets.push(tweet);
+ }
+ toast(`${added.length} source media ${added.length === 1 ? 'file' : 'files'} added to the thread`, 'ok', 2000);
+ } catch {
+ /* Media selection is a convenience; attaching the proof still works offline. */
+ }
+ }
+
async function openProofPicker() {
if (!caseState.current) {
toast('Open a case to pick a proof', 'warn');
@@ -276,6 +452,7 @@
const spec = await api.get(`/api/cases/${caseState.current.id}/proofs/${item.name}`);
const src = proofSource(spec);
if (src) source = src;
+ await preloadProofMedia(item.png, src);
const ct = proofCoordsText(spec);
if (ct) { coordsText = ct; await resolveCoords(); return; }
} catch {
@@ -288,9 +465,13 @@
setProof(null);
}
- const mediaHref = $derived(
- mediaPath && caseState.current ? `/files/${caseState.current.id}/${mediaPath}` : null
- );
+ function mediaHref(path) {
+ return path && caseState.current ? `/files/${caseState.current.id}/${path}` : null;
+ }
+
+ function mediaKind(path) {
+ return caseState.current?.entities.find((e) => e.attrs?.path === path)?.attrs?.kind ?? 'image';
+ }
const proofHref = $derived(
proofPng && caseState.current
@@ -300,8 +481,7 @@
// ---- one-click image copy / media download ------------------------------
- /** Rasterise any image blob to PNG (the only format browsers reliably put on
- * the clipboard) so it can be pasted straight into the X composer. */
+ /** Rasterise any image blob to PNG so it can be pasted into a social composer. */
function toPngBlob(blob) {
return new Promise((resolve, reject) => {
const url = URL.createObjectURL(blob);
@@ -322,28 +502,38 @@
});
}
- /** Copy an image into the clipboard so it can be pasted (Ctrl+V) into X. */
+ /** Copy an image into the clipboard for the selected social composer. */
async function copyImage(url) {
try {
const res = await fetch(url);
let blob = await res.blob();
if (blob.type !== 'image/png') blob = await toPngBlob(blob);
await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
- toast('Image copied. Paste it into X (Ctrl+V)', 'ok', 2400);
+ toast(`Image copied. Paste it into ${targetInfo.label}.`, 'ok', 2400);
} catch (e) {
toast(`Could not copy image: ${e.message}`, 'danger');
}
}
- /** Save a media file locally (X has no paste for video — drag it in from here). */
- function downloadMedia(url, path) {
+ function triggerMediaDownload(url, path) {
const a = document.createElement('a');
a.href = url;
a.download = (path ?? '').split('/').pop() || 'media';
document.body.appendChild(a);
a.click();
a.remove();
- toast('Downloaded. Drag it into X', 'info', 2600);
+ }
+
+ /** Download every attachment from one post. */
+ function downloadPostMedia(paths) {
+ for (const path of paths) triggerMediaDownload(mediaHref(path), path);
+ toast(
+ paths.length === 1
+ ? `Media downloaded. Drag it into ${targetInfo.label}.`
+ : `${paths.length} media files downloaded. Drag them into ${targetInfo.label}.`,
+ 'info',
+ 2600,
+ );
}
// ---- draft persistence --------------------------------------------------
@@ -358,11 +548,22 @@
proofPng,
tweet1,
tweet1Edited,
+ target,
+ body,
mediaEnabled,
mediaType,
mediaText,
- mediaPath,
- extraTweets: extraTweets.map((t) => ({ text: t.text })),
+ mediaTextIncludesPrefix: true,
+ mediaPaths: [...mediaPaths],
+ // Kept for drafts saved by older app versions.
+ mediaPath: mediaPaths[0] ?? null,
+ extraTweets: extraTweets.map((t) => ({
+ text: t.text,
+ mediaPaths: [...t.mediaPaths],
+ mediaType: t.mediaType ?? 'none',
+ isMediaTweet: t.isMediaTweet === true,
+ mediaTextIncludesPrefix: t.mediaTextIncludesPrefix === true,
+ })),
};
}
@@ -425,10 +626,34 @@
setProof(s.proofPng ?? null);
mediaEnabled = s.mediaEnabled ?? true;
mediaType = s.mediaType ?? 'none';
- mediaText = s.mediaText ?? '';
- mediaPath = s.mediaPath ?? null;
- extraTweets = (s.extraTweets ?? []).map((t) => ({ id: ++extraSeq, text: t.text ?? '' }));
+ mediaText = mediaType === 'none'
+ ? ''
+ : s.mediaTextIncludesPrefix
+ ? String(s.mediaText ?? '')
+ : mediaTweetText(mediaType, s.mediaText ?? '', 2);
+ mediaPaths = Array.isArray(s.mediaPaths)
+ ? s.mediaPaths.filter((path) => typeof path === 'string').slice(0, MAX_POST_MEDIA)
+ : (s.mediaPath ? [s.mediaPath] : []);
+ body = typeof s.body === 'string' && s.body ? s.body : DEFAULT_TWEET_BODY;
+ extraTweets = (s.extraTweets ?? []).map((t, i) => {
+ const type = t.mediaType ?? 'none';
+ const hasPrefix = t.mediaTextIncludesPrefix === true;
+ const isMediaTweet = t.isMediaTweet === true || type !== 'none';
+ return {
+ id: ++extraSeq,
+ text: type !== 'none' && !hasPrefix
+ ? mediaTweetText(type, t.text ?? '', i + 3)
+ : (t.text ?? ''),
+ mediaPaths: Array.isArray(t.mediaPaths)
+ ? t.mediaPaths.filter((path) => typeof path === 'string').slice(0, MAX_POST_MEDIA)
+ : (typeof t.mediaPath === 'string' ? [t.mediaPath] : []),
+ mediaType: type,
+ isMediaTweet,
+ mediaTextIncludesPrefix: isMediaTweet || hasPrefix,
+ };
+ });
draftName = name;
+ appliedPostTemplate = null;
// restore geo facts from the coordinates, then honor any manual tweet edits
if (s.coordsText?.trim()) {
try {
@@ -441,6 +666,7 @@
}
tweet1 = s.tweet1 ?? buildTweet1();
tweet1Edited = s.tweet1Edited ?? false;
+ target = normalizePostTarget(s.target);
openList = null;
toast('Draft loaded', 'ok', 1400);
} catch (e) {
@@ -458,29 +684,59 @@
setProof(null);
tweet1 = '';
tweet1Edited = false;
+ target = normalizePostTarget(prefs.postTarget);
mediaEnabled = true;
mediaType = 'none';
mediaText = '';
- mediaPath = null;
+ mediaPaths = [];
+ body = DEFAULT_TWEET_BODY;
extraTweets = [];
draftName = null;
+ appliedPostTemplate = null;
discardConfirm = false;
}
const hasContent = $derived(
- !!(draftName || description.trim() || coordsText.trim() || mediaPath || proofPng ||
+ !!(draftName || description.trim() || coordsText.trim() || mediaPaths.length || proofPng ||
extraTweets.length || tweet1.trim())
);
- // ---- publish (prefill X compose — Azimut never posts on your behalf) -----
+ // Preferences can arrive after this tool mounts. A blank composer follows the
+ // preferred platform, while a selected or saved draft keeps its own target.
+ $effect(() => {
+ if (!hasContent) target = normalizePostTarget(prefs.postTarget);
+ });
+
+ async function copyReport() {
+ const attachments = [
+ proofPng,
+ ...mediaPaths,
+ ...extraTweets.flatMap((tweet) => tweet.mediaPaths),
+ ];
+ const coordinates = geo
+ ? `${geo.lat.toFixed(6)}, ${geo.lon.toFixed(6)}`
+ : coordsText.trim();
+ await navigator.clipboard.writeText(postReportMarkdown({
+ title: draftTitle(),
+ place,
+ plusCode: geo?.plus_code,
+ coordinates,
+ description,
+ source,
+ posts: threadParts(),
+ attachments,
+ }));
+ toast('Markdown report copied', 'ok', 1800);
+ }
+
+ // ---- publish handoff (Azimut never posts on the analyst's behalf) --------
async function publish() {
- // X's web intent only prefills the first post; copy the whole thread so the
- // rest can be pasted as replies, then open the compose window.
- await copyAll();
- const url = `https://x.com/intent/post?text=${encodeURIComponent(bidiSafe(tweet1))}`;
+ // Social intents prefill the first post only. The rest is copied as replies.
+ await copyAll(false);
+ const url = postComposeUrl(target, bidiSafe(tweet1));
window.open(url, '_blank', 'noopener,noreferrer');
- toast('Opened X. Thread copied for the replies', 'info', 3200);
+ toast(`Opened ${targetInfo.label}. Posts copied for replies.`, 'info', 3200);
}
</script>
@@ -503,8 +759,8 @@
<button class="btn btn-ghost btn-sm" onclick={saveDraft} disabled={saving}>
<Icon name="save" size={14} /> {draftName ? 'Save draft' : 'Save as draft'}
</button>
- <button class="btn btn-primary btn-sm" onclick={publish} disabled={!tweet1.trim()} title="Copy the thread and open X compose">
- <Icon name="post" size={14} /> Publish on X
+ <button class="btn btn-primary btn-sm" onclick={publish} disabled={!tweet1.trim()} title={`Copy posts and open ${targetInfo.label}`}>
+ <Icon name="post" size={14} /> Publish on {targetInfo.label}
</button>
</div>
</div>
@@ -514,6 +770,72 @@
<!-- left column: ingredients -->
<div class="col">
<div class="field">
+ <span class="label">Publish target</span>
+ <div class="target-tabs" aria-label="Publish target">
+ {#each Object.values(POST_TARGETS) as option (option.id)}
+ <button
+ class="btn btn-sm"
+ class:btn-primary={target === option.id}
+ class:btn-ghost={target !== option.id}
+ onclick={() => (target = option.id)}
+ >{option.label}</button>
+ {/each}
+ </div>
+ </div>
+
+ <!-- Thread style: apply a saved structure (mention, layout, media flag,
+ boilerplate tweets) over this draft. "Discard" returns to the
+ structure the draft had before. -->
+ <div class="field">
+ <div class="style-head">
+ <label class="label" for="pc-tpl">Thread style</label>
+ {#if templatesState.post.length}
+ <button
+ class="tpl-settings-link"
+ type="button"
+ title="Open Settings → Templates to create, edit or delete thread templates"
+ onclick={openTemplateSettings}
+ >
+ Settings templates
+ </button>
+ {/if}
+ </div>
+ {#if appliedPostTemplate}
+ <div class="tpl-loaded" title={`Template loaded: ${appliedPostTemplate.name}`}>
+ <span class="tpl-loaded-name">
+ <Icon name="check" size={12} /> {appliedPostTemplate.name}
+ </span>
+ <button class="tpl-remove" title="Remove this template" onclick={discardPostTemplate} aria-label="Remove template">
+ <Icon name="x" size={12} />
+ </button>
+ </div>
+ {:else if templatesState.post.length}
+ <select id="pc-tpl" class="input" onchange={applyPostFromSelect}>
+ <option value="">Apply a template…</option>
+ {#each templatesState.post as t (t.id)}
+ <option value={t.id}>{t.name}</option>
+ {/each}
+ </select>
+ {:else}
+ <p class="tpl-none">
+ No templates yet.
+ <button
+ class="tpl-inline-link"
+ type="button"
+ title="Open Settings → Templates to create your first thread template"
+ onclick={openTemplateSettings}
+ >
+ Create one in Settings → Templates.
+ </button>
+ </p>
+ {/if}
+ </div>
+
+ <div
+ class="field"
+ class:template-disabled={fieldDisabledByTemplate('description')}
+ title={fieldDisabledByTemplate('description') ? TEMPLATE_FIELD_HINT : undefined}
+ >
<label class="label" for="pc-desc">Description</label>
<input
id="pc-desc"
@@ -521,10 +843,15 @@
placeholder="A formation of 13 helicopters was spotted heading East"
bind:value={description}
onchange={regenerate}
+ disabled={fieldDisabledByTemplate('description')}
/>
</div>
- <div class="field">
+ <div
+ class="field"
+ class:template-disabled={fieldDisabledByTemplate('coordinates')}
+ title={fieldDisabledByTemplate('coordinates') ? TEMPLATE_FIELD_HINT : undefined}
+ >
<label class="label" for="pc-coords">Coordinates</label>
<input
id="pc-coords"
@@ -532,6 +859,7 @@
placeholder="10.303315, -66.874095"
bind:value={coordsText}
onchange={resolveCoords}
+ disabled={fieldDisabledByTemplate('coordinates')}
/>
{#if geo}
<div class="geo-facts card">
@@ -553,7 +881,11 @@
{/if}
</div>
- <div class="field">
+ <div
+ class="field"
+ class:template-disabled={fieldDisabledByTemplate('place')}
+ title={fieldDisabledByTemplate('place') ? TEMPLATE_FIELD_HINT : undefined}
+ >
<label class="label" for="pc-place">
Place {#if placeLoading}<span class="loading">resolving…</span>{/if}
</label>
@@ -563,10 +895,15 @@
placeholder="Village, State, Country"
bind:value={place}
onchange={regenerate}
+ disabled={fieldDisabledByTemplate('place')}
/>
</div>
- <div class="field">
+ <div
+ class="field"
+ class:template-disabled={fieldDisabledByTemplate('mention')}
+ title={fieldDisabledByTemplate('mention') ? TEMPLATE_FIELD_HINT : undefined}
+ >
<label class="label" for="pc-mention">Mention</label>
<input
id="pc-mention"
@@ -574,10 +911,15 @@
placeholder="@GeoConfirmed"
bind:value={mention}
onchange={regenerate}
+ disabled={fieldDisabledByTemplate('mention')}
/>
</div>
- <div class="field">
+ <div
+ class="field"
+ class:template-disabled={fieldDisabledByTemplate('source')}
+ title={fieldDisabledByTemplate('source') ? TEMPLATE_FIELD_HINT : undefined}
+ >
<label class="label" for="pc-source">Source</label>
<input
id="pc-source"
@@ -585,6 +927,7 @@
placeholder="https://instagram.com/… (original post)"
bind:value={source}
onchange={regenerate}
+ disabled={fieldDisabledByTemplate('source')}
/>
</div>
@@ -593,7 +936,7 @@
<div class="proof-head">
<span class="label" style="margin:0">Attached proof</span>
{#if proofPng}
- <button class="btn btn-ghost btn-sm" onclick={() => copyImage(proofHref)} title="Copy the image — paste it into X">
+ <button class="btn btn-ghost btn-sm" onclick={() => copyImage(proofHref)} title="Copy this image">
<Icon name="copy" size={13} /> Copy image
</button>
<button class="btn btn-ghost btn-sm" onclick={openProofPicker} title="Attach a different proof">
@@ -620,17 +963,17 @@
<!-- right column: the thread -->
<div class="col">
- <!-- Tweet 1: geolocation -->
+ <!-- Post 1: geolocation -->
<div class="tweet-block card">
<div class="tweet-head">
<span class="tweet-num">1</span>
- <span class="label" style="margin:0">Geolocation tweet</span>
+ <span class="label" style="margin:0">Geolocation post</span>
{#if tweet1Edited}
<button class="btn btn-ghost btn-sm" onclick={regenerate} title="Rebuild from the fields">
<Icon name="compass" size={13} /> regenerate
</button>
{/if}
- <span class="counter" class:over={tweet1Over}>{tweet1Count}/{X_LIMIT}</span>
+ <span class="counter" class:over={tweet1Over} title={targetInfo.limitHelp}>{tweet1Count}/{targetInfo.limitLabel}</span>
<button class="btn btn-ghost btn-sm" onclick={() => copy(tweet1)} disabled={!tweet1.trim()}>
<Icon name="copy" size={13} /> Copy
</button>
@@ -644,7 +987,7 @@
></textarea>
</div>
- <!-- Tweet 2: media (Video / Image) -->
+ <!-- Post 2: media (Video / Image) -->
{#if mediaEnabled}
<div class="tweet-block card">
<div class="tweet-head">
@@ -655,106 +998,156 @@
class="btn btn-sm"
class:btn-primary={mediaType === 'video'}
class:btn-ghost={mediaType !== 'video'}
- onclick={() => (mediaType = mediaType === 'video' ? 'none' : 'video')}
+ onclick={() => setMediaType('video')}
>Video</button>
<button
class="btn btn-sm"
class:btn-primary={mediaType === 'images'}
class:btn-ghost={mediaType !== 'images'}
- onclick={() => (mediaType = mediaType === 'images' ? 'none' : 'images')}
+ onclick={() => setMediaType('images')}
>Image</button>
</div>
{#if mediaType !== 'none'}
- <span class="counter">{weightedLength(tweet2Text())}/{X_LIMIT}</span>
+ <span class="counter" class:over={targetLength(tweet2Text()) > targetInfo.limit} title={targetInfo.limitHelp}>{targetLength(tweet2Text())}/{targetInfo.limitLabel}</span>
<button class="btn btn-ghost btn-sm" onclick={() => copy(tweet2Text())}>
<Icon name="copy" size={13} /> Copy
</button>
{/if}
- <button class="btn btn-ghost btn-sm danger-hover" onclick={() => (mediaEnabled = false)} title="Remove media tweet">
+ <button class="btn btn-ghost btn-sm danger-hover" onclick={() => (mediaEnabled = false)} title="Remove media post">
<Icon name="x" size={13} />
</button>
</div>
{#if mediaType !== 'none'}
- <div class="media-prefix">{mediaType === 'video' ? '2/ Video:' : '2/ Image:'}</div>
<textarea
class="textarea post-text mono"
dir="auto"
- placeholder="Paste URL or describe the media…"
+ placeholder="Descriptions, captions, hashtags…"
bind:value={mediaText}
rows="3"
></textarea>
<div class="media-attach">
- <button class="btn btn-ghost btn-sm" onclick={openPicker}>
- <Icon name="media" size={13} /> Choose from library
+ <button class="btn btn-ghost btn-sm" onclick={() => openPicker()}>
+ <Icon name="media" size={13} /> Edit media
</button>
- {#if mediaPath}
+ {#each mediaPaths as path (path)}
+ {@const href = mediaHref(path)}
+ {@const kind = mediaKind(path)}
<span class="attach-chip">
- {#if mediaHref}
- <a href={mediaHref} target="_blank" rel="noreferrer" title={mediaPath}>
- {mediaPath.replace(/^media\//, '')}
+ {#if href}
+ <a href={href} target="_blank" rel="noreferrer" title={path}>
+ {path.replace(/^media\//, '')}
</a>
{:else}
- {mediaPath.replace(/^media\//, '')}
+ {path.replace(/^media\//, '')}
{/if}
- <button class="chip-x" onclick={clearMedia} title="Detach media">
+ <button class="chip-x" onclick={() => clearMedia(path)} title="Remove this media">
<Icon name="x" size={11} />
</button>
</span>
- {#if mediaType === 'images'}
- <button class="btn btn-ghost btn-sm" onclick={() => copyImage(mediaHref)} title="Copy the image — paste it into X">
+ {#if kind === 'image'}
+ <button class="btn btn-ghost btn-sm" onclick={() => copyImage(href)} title="Copy this image">
<Icon name="copy" size={13} /> Copy image
</button>
- {:else}
- <button class="btn btn-ghost btn-sm" onclick={() => downloadMedia(mediaHref, mediaPath)} title="Download the video, then drag it into X">
- <Icon name="download" size={13} /> Download
- </button>
{/if}
+ {/each}
+ {#if mediaPaths.length}
+ <button class="btn btn-ghost btn-sm" onclick={() => downloadPostMedia(mediaPaths)} title="Download this post's media">
+ <Icon name="download" size={13} /> {mediaPaths.length > 1 ? `Download all (${mediaPaths.length})` : 'Download'}
+ </button>
{/if}
</div>
{:else}
- <span class="muted">Toggle Video or Image to add a media tweet</span>
+ <span class="muted">Choose Video or Image to add media.</span>
{/if}
</div>
{/if}
- <!-- Extra context tweets (3, 4, …) -->
+ <!-- Extra context posts (3, 4, …) -->
{#each extraTweets as tweet, i (tweet.id)}
<div class="tweet-block card">
<div class="tweet-head">
<span class="tweet-num">{i + 3}</span>
- <span class="label" style="margin:0">Context</span>
- <span class="counter" class:over={weightedLength(tweet.text) > X_LIMIT}>
- {weightedLength(tweet.text)}/{X_LIMIT}
+ <span class="label" style="margin:0">{tweet.isMediaTweet || tweet.mediaType !== 'none' ? 'Media' : 'Context'}</span>
+ {#if tweet.isMediaTweet || tweet.mediaPaths.length || tweet.mediaType !== 'none'}
+ <div class="media-tabs">
+ <button class="btn btn-sm" class:btn-primary={tweet.mediaType === 'video'} class:btn-ghost={tweet.mediaType !== 'video'} onclick={() => setExtraMediaType(tweet, 'video')}>Video</button>
+ <button class="btn btn-sm" class:btn-primary={tweet.mediaType === 'images'} class:btn-ghost={tweet.mediaType !== 'images'} onclick={() => setExtraMediaType(tweet, 'images')}>Image</button>
+ </div>
+ {/if}
+ <span class="counter" class:over={targetLength(extraTweetText(tweet, i + 3)) > targetInfo.limit} title={targetInfo.limitHelp}>
+ {targetLength(extraTweetText(tweet, i + 3))}/{targetInfo.limitLabel}
</span>
- <button class="btn btn-ghost btn-sm" onclick={() => copy(tweet.text)} disabled={!tweet.text.trim()}>
+ <button class="btn btn-ghost btn-sm" onclick={() => copy(extraTweetText(tweet, i + 3))} disabled={!extraTweetText(tweet, i + 3)}>
<Icon name="copy" size={13} /> Copy
</button>
- <button class="btn btn-ghost btn-sm danger-hover" onclick={() => removeExtraTweet(tweet.id)} title="Remove tweet">
+ <button class="btn btn-ghost btn-sm danger-hover" onclick={() => removeExtraTweet(tweet.id)} title="Remove post">
<Icon name="x" size={13} />
</button>
</div>
- <textarea
- class="textarea post-text mono"
- dir="auto"
- placeholder="Additional context…"
- bind:value={tweet.text}
- rows="4"
- ></textarea>
+ {#if tweet.isMediaTweet && tweet.mediaType === 'none'}
+ <span class="muted">Choose Video or Image to add media.</span>
+ {:else}
+ <textarea
+ class="textarea post-text mono"
+ dir="auto"
+ placeholder={tweet.mediaType !== 'none' ? 'Descriptions, captions, hashtags…' : 'Additional context…'}
+ bind:value={tweet.text}
+ rows={tweet.mediaType !== 'none' ? 3 : 4}
+ ></textarea>
+ {/if}
+ {#if tweet.mediaPaths.length || tweet.mediaType !== 'none'}
+ <div class="media-attach">
+ <button class="btn btn-ghost btn-sm" onclick={() => openPicker(tweet.id)}>
+ <Icon name="media" size={13} /> Edit media
+ </button>
+ {#each tweet.mediaPaths as path (path)}
+ {@const href = mediaHref(path)}
+ <span class="attach-chip">
+ {#if href}
+ <a href={href} target="_blank" rel="noreferrer" title={path}>
+ {path.replace(/^media\//, '')}
+ </a>
+ {:else}
+ {path.replace(/^media\//, '')}
+ {/if}
+ <button class="chip-x" onclick={() => clearExtraMedia(tweet.id, path)} title="Remove this media">
+ <Icon name="x" size={11} />
+ </button>
+ </span>
+ {#if tweet.mediaType === 'images'}
+ <button class="btn btn-ghost btn-sm" onclick={() => copyImage(href)} title="Copy this image">
+ <Icon name="copy" size={13} /> Copy image
+ </button>
+ {/if}
+ {/each}
+ {#if tweet.mediaPaths.length}
+ <button class="btn btn-ghost btn-sm" onclick={() => downloadPostMedia(tweet.mediaPaths)} title="Download this post's media">
+ <Icon name="download" size={13} /> {tweet.mediaPaths.length > 1 ? `Download all (${tweet.mediaPaths.length})` : 'Download'}
+ </button>
+ {/if}
+ </div>
+ {/if}
</div>
{/each}
<div class="thread-actions">
{#if !mediaEnabled}
<button class="btn btn-ghost btn-sm" onclick={() => (mediaEnabled = true)}>
- <Icon name="plus" size={13} /> Add media tweet
+ <Icon name="plus" size={13} /> Restore post 2
</button>
{/if}
+ <button class="btn btn-ghost btn-sm" onclick={addMediaTweet}>
+ <Icon name="plus" size={13} /> Add media post
+ </button>
<button class="btn btn-ghost btn-sm" onclick={addExtraTweet}>
- <Icon name="plus" size={13} /> Add context tweet
+ <Icon name="plus" size={13} /> Add context post
</button>
<button class="btn btn-ghost btn-sm" onclick={copyAll}>
<Icon name="copy" size={13} /> Copy all
</button>
+ <button class="btn btn-ghost btn-sm" onclick={copyReport} title="Copy as Markdown">
+ <Icon name="file" size={13} /> Copy report
+ </button>
</div>
</div>
@@ -813,13 +1206,22 @@
{/if}
{#if pickerOpen}
- <Modal title="Choose a media" width="640px" onclose={() => (pickerOpen = false)}>
- {#if mediaLibrary.length === 0}
- <p class="picker-empty">No media in this case yet. Import or download some in the Media tab.</p>
+ <Modal title={pickerTitle()} width="640px" onclose={() => (pickerOpen = false)}>
+ {#if pickerItems().length === 0}
+ <p class="picker-empty">No {pickerTweet()?.mediaType === 'video' ? 'videos' : 'images'} in this case.</p>
{:else}
<div class="picker-grid">
- {#each (caseState.current ? mediaLibrary : []) as item (item.path)}
- <button class="picker-item" onclick={() => pickMedia(item)} title={item.path}>
+ {#each (caseState.current ? pickerItems() : []) as item (item.path)}
+ {@const targetTweet = mediaPickerTarget === null
+ ? null
+ : extraTweets.find((tweet) => tweet.id === mediaPickerTarget)}
+ {@const selected = targetTweet ? targetTweet.mediaPaths.includes(item.path) : mediaPaths.includes(item.path)}
+ <button
+ class="picker-item"
+ class:selected={selected}
+ onclick={() => pickMedia(item)}
+ title={item.path}
+ >
<div class="picker-thumb">
{#if item.thumbnail}
<img src={`/files/${caseState.current.id}/${item.thumbnail}`} alt={item.path} />
@@ -827,11 +1229,15 @@
<Icon name={item.kind === 'video' ? 'video' : item.kind === 'audio' ? 'audio' : 'file'} size={24} />
{/if}
{#if item.kind === 'video'}<span class="kind-badge"><Icon name="video" size={11} /></span>{/if}
+ {#if selected}<span class="select-check"><Icon name="check" size={13} /></span>{/if}
</div>
<span class="picker-name">{(item.label || item.path).replace(/^media\//, '')}</span>
</button>
{/each}
</div>
+ <div class="modal-actions">
+ <button class="btn btn-primary btn-sm" onclick={() => (pickerOpen = false)}>Done</button>
+ </div>
{/if}
</Modal>
{/if}
@@ -961,11 +1367,10 @@
display: flex;
gap: 4px;
}
- .media-prefix {
- font-size: var(--fs-xs);
- font-family: var(--font-mono);
- color: var(--text-2);
- padding: 2px 0;
+ .target-tabs {
+ display: flex;
+ gap: 4px;
+ flex-wrap: wrap;
}
.muted {
font-size: var(--fs-xs);
@@ -999,6 +1404,80 @@
flex-shrink: 0;
}
+ .style-head {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .style-head .label { margin: 0; }
+ .tpl-settings-link {
+ margin-left: auto;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ text-decoration: underline;
+ text-decoration-style: dotted;
+ text-underline-offset: 2px;
+ }
+ .tpl-settings-link:hover { color: var(--text-2); }
+ .tpl-inline-link {
+ color: var(--text-3);
+ font: inherit;
+ text-decoration: underline;
+ text-decoration-style: dotted;
+ text-underline-offset: 2px;
+ }
+ .tpl-inline-link:hover { color: var(--text-2); }
+
+ .tpl-loaded {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 9px;
+ border: 1px solid color-mix(in srgb, var(--ok) 45%, var(--border));
+ border-radius: var(--r-sm);
+ background: color-mix(in srgb, var(--ok) 10%, transparent);
+ }
+ .tpl-loaded-name {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ font-size: var(--fs-sm);
+ font-weight: 600;
+ color: var(--text-1);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .tpl-loaded-name :global(svg) { color: var(--ok); flex-shrink: 0; }
+ .tpl-remove {
+ margin-left: auto;
+ display: inline-flex;
+ padding: 2px;
+ border: 0;
+ border-radius: var(--r-sm);
+ background: none;
+ color: var(--text-3);
+ cursor: pointer;
+ }
+ .tpl-remove:hover { color: var(--text-1); background: var(--bg-2); }
+ .tpl-none {
+ margin: 0;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ line-height: 1.4;
+ }
+ .field.template-disabled {
+ opacity: 0.48;
+ cursor: not-allowed;
+ }
+ .field.template-disabled .input { pointer-events: none; }
+ .field.template-disabled:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 3px;
+ border-radius: var(--r-sm);
+ }
/* media attachment */
.media-attach {
display: flex;
@@ -1065,6 +1544,12 @@
.picker-item:hover .picker-thumb {
border-color: var(--accent);
}
+ .picker-item.selected .picker-thumb {
+ border-color: var(--accent);
+ box-shadow: 0 0 0 2px var(--accent-soft);
+ }
+ .picker-item:disabled { cursor: not-allowed; opacity: 0.38; }
+ .picker-item:disabled .picker-thumb { border-color: var(--border); }
.picker-thumb img {
width: 100%;
height: 100%;
@@ -1080,6 +1565,16 @@
color: #fff;
display: inline-flex;
}
+ .select-check {
+ position: absolute;
+ top: 4px;
+ left: 4px;
+ display: inline-flex;
+ padding: 3px;
+ border-radius: 50%;
+ background: var(--accent);
+ color: var(--accent-text);
+ }
.picker-name {
font-size: var(--fs-xs);
color: var(--text-2);
@@ -1087,6 +1582,7 @@
text-overflow: ellipsis;
white-space: nowrap;
}
+ .modal-actions { display: flex; justify-content: flex-end; margin-top: 14px; }
.open-list { display: flex; flex-direction: column; gap: 8px; }
.open-row-wrap { display: flex; align-items: center; gap: 4px; }
.open-row-wrap .open-row { flex: 1; min-width: 0; }
diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelte
index bdca37d..68f4a8d 100644
--- a/frontend/src/tools/ProofComposer.svelte
+++ b/frontend/src/tools/ProofComposer.svelte
@@ -1,22 +1,48 @@
+<script module>
+ /**
+ * Keep selection out of pointerdown. Selecting rebuilds the Konva document,
+ * so doing it before pointerup destroys the gesture target and can strand
+ * Firefox's drag state. A click/tap or dragend is already a settled gesture.
+ */
+ export function bindPanelPointerLifecycle(group, { onPress, onSelect, onDragEnd }) {
+ group.on('pointerdown', onPress);
+ group.on('click tap', onSelect);
+ if (onDragEnd) {
+ group.on('dragend', () => {
+ onSelect();
+ onDragEnd();
+ });
+ }
+ }
+</script>
+
<script>
import { onMount } from 'svelte';
import Konva from 'konva';
import { api } from '../lib/api.js';
import { caseState, uiState, ensureCase, reloadCase, toast, prefs, fmtCoords } from '../lib/state.svelte.js';
+ import { templatesState } from '../lib/state.svelte.js';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
import {
- ANNO_COLORS, PAD, PANEL_H, TWEET_GUIDES,
+ ANNO_COLORS, PAD, GAP, ROW_GAP, PANEL_H, TWEET_GUIDES,
CAPTION_SIZE, LEGEND_SIZE, FOOTER_SIZE,
- BG, TEXT_MAIN, TEXT_DIM, TEXT_FAINT,
+ BG, TEXT_MAIN, normSpace, textColors,
layoutPanels, panelsBottom, freeNormalizeDelta, legendLineHeight, footerBand,
attributionLine, docSize, offsetShape, autoLayoutRows,
autoCoords, formatCoords, autoSource,
toSpec, newId, loadImage, orderedFeatureColors, notesFromShapes,
+ templateFromProof, applyProofStyle, normalizeProofStyle, newSignatureText,
+ anchoredPos, anchoredOffset, SIG_TEXT_SIZE,
copyShapeSpec, dedupeBySrc, isSatelliteCapture, satPanelInput, mediaPanelInput,
- SIG_ANCHORS, newSignature, signatureBox, signatureOffset,
- DEFAULT_PROOF_TITLE, proofSlug, uniqueProofTitle,
+ SIG_ANCHORS, SIG_SCALE, newSignature, signatureBox, signatureOffset, signaturePairPositions,
+ remapPanelXY, panelHitTest, groupNeighborIndex, hasGroupNeighbor,
+ denseRowValues, clampPanelScale, trimClosingDuplicate, freehandShape,
+ canReassignLegendNote,
+ savedProofSlugs, savedProofTitles as libSavedProofTitles, savedProofTitle as libSavedProofTitle,
+ DEFAULT_PROOF_TITLE, proofSlug, uniqueProofTitle, proofTitleFromCase,
+ filterProofPanelItems, hasProofCanvasContent, proofExportOptions,
} from '../lib/composer.js';
import { createHistory } from '../lib/history.js';
@@ -25,13 +51,14 @@
const SCALE_STEP = 0.05;
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' },
- { id: 'curve', icon: 'curve', label: 'Curve (click points, double-click to finish)' },
- { id: 'text', icon: 'text', label: 'Text' },
+ { id: 'select', icon: 'hand', label: 'Select / move', shortcut: 'v' },
+ { id: 'rect', icon: 'square', label: 'Box', shortcut: 'r' },
+ { id: 'ellipse', icon: 'circle', label: 'Ellipse', shortcut: 'e' },
+ { id: 'arrow', icon: 'arrow', label: 'Arrow', shortcut: 'a' },
+ { id: 'line', icon: 'line', label: 'Line', shortcut: 'l' },
+ { id: 'curve', icon: 'curve', label: 'Curve (click points, double-click to finish)', shortcut: 'c' },
+ { id: 'freehand', icon: 'freehand', label: 'Freehand', shortcut: 'd' },
+ { id: 'text', icon: 'text', label: 'Text', shortcut: 't' },
];
// ---- document state -------------------------------------------------------
@@ -41,8 +68,17 @@
title: DEFAULT_PROOF_TITLE, panels: [], shapes: [], notes: {}, legendOrder: [],
coordsText: '', source: '', // '' → auto-derived from panels; non-empty → manual override
captionSize: CAPTION_SIZE, legendSize: LEGEND_SIZE, footerSize: FOOTER_SIZE, footer: '',
+ footerEnabled: true, // false → no footer line at all
+ footerColor: null, // null → auto from the background
+ footerAlign: 'left',
+ captionsEnabled: true, // whether newly added panels get a default caption
+ bg: BG, // proof background fill; captions/legend/footer follow it (textColors)
+ space: { pad: PAD, gap: GAP, rowGap: ROW_GAP }, // panel spacing, editable per proof
layout: 'grid', // 'grid' (rows) | 'free' (drag panels anywhere, overlap allowed)
+ panelDirection: 'horizontal', // preferred arrangement for the first two panels
signature: null, // null → unsigned; else { anchor, dx, dy, scale, opacity }
+ signatureText: null, // null → none; else a Settings-handle slot over the panels
+ palette: [...ANNO_COLORS], // ordered drawing colours, most preferred first
});
// The analyst's logo (Settings → Signature): one app-wide PNG, loaded once per
@@ -65,6 +101,9 @@
// asks before overwriting an existing proof. Reset on open/discard.
let titleTouched = $state(false);
let dirty = $state(false);
+ // A named proof can exist before it has content. This distinguishes the
+ // initial composer shell from a template-only proof the user just created.
+ let proofStarted = $state(false);
// Kept in step with deletes made anywhere else in the app. If the saved proof
// this canvas came from is gone, the binding has to go with it — otherwise the
@@ -94,8 +133,22 @@
let guide = $state(null); // null | '16:9' | '4:5' — tweet centre-crop overlay
let selectedId = $state(null);
let selectedPanelId = $state(null); // free-layout only: panel picked for move/resize
+ let selectedSig = $state(null); // null | 'logo' | 'text' — signature picked for resize
let picker = $state(false);
let pickerItems = $state([]);
+ let newProofOpen = $state(false);
+ let newProofName = $state('');
+ let newProofTemplateId = $state('');
+ let newProofPanelPaths = $state([]);
+ let newProofQuery = $state('');
+ let newProofCategory = $state('all');
+ let newProofLoading = $state(false);
+ let creatingProof = $state(false);
+ let replaceWithNewConfirm = $state(false);
+ const filteredNewProofItems = $derived(
+ filterProofPanelItems(pickerItems, newProofQuery, newProofCategory)
+ );
+ const proofHasContent = $derived(hasProofCanvasContent(proof));
let openList = $state(null); // list of saved proofs, null = closed
let saving = $state(false);
let proofFor = $state(undefined);
@@ -137,18 +190,31 @@
function applySnapshot(json) {
const spec = JSON.parse(json);
+ const style = normalizeProofStyle(spec);
histBusy = true;
+ proofStarted = true;
if (pathDraft) finishPath(false);
proof.title = spec.title ?? DEFAULT_PROOF_TITLE;
proof.coordsText = spec.coordsText ?? '';
proof.source = spec.source ?? '';
- proof.captionSize = spec.captionSize ?? CAPTION_SIZE;
- proof.legendSize = spec.legendSize ?? LEGEND_SIZE;
- proof.footerSize = spec.footerSize ?? FOOTER_SIZE;
- proof.footer = spec.footer ?? '';
- proof.layout = spec.layout ?? 'grid';
- proof.signature = spec.signature ?? null;
+ proof.captionSize = style.captionSize;
+ proof.legendSize = style.legendSize;
+ proof.footerSize = style.footerSize;
+ proof.footer = style.footer;
+ proof.footerEnabled = style.footerEnabled;
+ proof.footerColor = style.footerColor;
+ proof.footerAlign = style.footerAlign;
+ proof.captionsEnabled = style.captionsEnabled;
+ proof.bg = style.bg;
+ proof.space = style.space;
+ proof.layout = style.layout;
+ proof.panelDirection = style.panelDirection;
+ proof.signature = style.signature;
+ proof.signatureText = style.signatureText;
+ proof.palette = style.palette;
+ color = proof.palette[0];
proof.notes = spec.notes ?? {};
+ proof.legendOrder = spec.legendOrder ?? [];
proof.panels = spec.panels.map((p) => ({ ...p, img: imgCache.get(p.src) ?? null }));
proof.shapes = spec.shapes ?? [];
// a panel image missing from the cache (shouldn't happen) reloads async
@@ -162,6 +228,8 @@
}
selectedId = null;
selectedPanelId = null;
+ selectedSig = null;
+ appliedTemplate = null;
dirty = true;
requestAnimationFrame(fit);
// outlast the capture debounce so the restore itself is not re-recorded
@@ -273,13 +341,20 @@
proof.notes,
proof.legendOrder,
proof.captionSize, proof.legendSize, proof.footerSize, proof.footer,
+ proof.footerEnabled, proof.footerColor,
+ proof.footerAlign,
+ proof.bg, proof.space,
proof.layout,
+ proof.panelDirection,
proof.signature,
+ proof.signatureText,
selectedId,
selectedPanelId,
+ selectedSig,
guide,
]);
sigImg; // the logo lands async — redraw once it does
+ prefs.signatureHandle; // Settings can change the rendered handle live
if (stage) rebuild();
});
@@ -288,12 +363,13 @@
captionSize: proof.captionSize,
legendSize: proof.legendSize,
footerSize: proof.footerSize,
+ footerEnabled: proof.footerEnabled !== false,
});
// Layout boxes + document measure for the active layout mode.
- const boxesOf = () => layoutPanels(proof.panels, proof.captionSize, proof.layout);
+ const boxesOf = () => layoutPanels(proof.panels, proof.captionSize, proof.layout, proof.space);
const measureDoc = () =>
- docSize(proof.panels, proof.shapes, proof.notes, textOpts(), proof.legendOrder, proof.layout);
+ docSize(proof.panels, proof.shapes, proof.notes, textOpts(), proof.legendOrder, proof.layout, proof.space);
function resetDoc() {
proof.title = freshTitle();
@@ -307,12 +383,25 @@
proof.legendSize = LEGEND_SIZE;
proof.footerSize = FOOTER_SIZE;
proof.footer = '';
+ proof.footerEnabled = true;
+ proof.footerColor = null;
+ proof.footerAlign = 'left';
+ proof.captionsEnabled = true;
+ proof.bg = BG;
+ proof.space = { pad: PAD, gap: GAP, rowGap: ROW_GAP };
proof.layout = 'grid';
+ proof.panelDirection = 'horizontal';
proof.signature = null;
+ proof.signatureText = null;
+ proof.palette = [...ANNO_COLORS];
+ color = proof.palette[0];
savedName = null;
titleTouched = false;
+ proofStarted = false;
selectedId = null;
selectedPanelId = null;
+ selectedSig = null;
+ appliedTemplate = null;
dirty = false;
imgCache.clear();
anchorHistory();
@@ -323,14 +412,74 @@
discardConfirm = false;
}
+ // ---- house-style templates ---------------------------------------------------
+ // Apply a saved proof template (Settings → Templates) onto this proof.
+ // Content stays put — templates carry only the look.
+ // The house style laid over this proof: { id, name, prevStyle }. Choosing
+ // "No template" restores the look from before the first template was applied.
+ // It stays out of the saved spec because the style values are already copied.
+ let appliedTemplate = $state(null);
+
+ function applyTemplate(t, { notify = true } = {}) {
+ // first apply snapshots the current look; re-applying keeps that original,
+ // so Discard always walks back to the pre-template style, not the last one.
+ const prevStyle = appliedTemplate?.prevStyle ?? templateFromProof(proof);
+ applyProofStyle(proof, t.data, {
+ logo: !!sigImg,
+ handle: !!prefs.signatureHandle?.trim(),
+ });
+ color = proof.palette[0] ?? ANNO_COLORS[0];
+ appliedTemplate = { id: t.id, name: t.name, prevStyle };
+ dirty = true;
+ requestAnimationFrame(fit); // margins/layout may have changed the doc size
+ if (notify) toast(`Template loaded: ${t.name}`, 'ok', 1400);
+ }
+
+ function applyFromSelect(e) {
+ if (!proofStarted) return;
+ const t = templatesState.proof.find((x) => x.id === e.currentTarget.value);
+ if (t) applyTemplate(t);
+ else discardTemplate();
+ }
+
+ function discardTemplate() {
+ if (!appliedTemplate) return;
+ applyProofStyle(proof, appliedTemplate.prevStyle, {
+ logo: !!sigImg,
+ handle: !!prefs.signatureHandle?.trim(),
+ });
+ color = proof.palette[0] ?? ANNO_COLORS[0];
+ appliedTemplate = null;
+ dirty = true;
+ requestAnimationFrame(fit);
+ toast('Template removed', 'ok', 1200);
+ }
+
+ function openTemplateSettings() {
+ uiState.settingsTab = 'templates';
+ uiState.tool = 'settings';
+ }
+
+ // Pick the logo or the @handle so the transformer wraps it — click a corner to
+ // resize it right on the canvas. Content selections drop, so only one thing
+ // ever carries the handles.
+ function selectSig(which) {
+ selectedSig = which;
+ selectedId = null;
+ selectedPanelId = null;
+ }
+
+ function selectPanel(id) {
+ if (tool !== 'select') return;
+ selectedPanelId = id;
+ selectedId = null;
+ selectedSig = null;
+ }
+
// ---- panels ------------------------------------------------------------------
- async function openPicker() {
- if (!caseState.current) {
- toast('Add media first. The composer works on case images', 'info');
- uiState.tool = 'media';
- return;
- }
+ async function fetchPanelItems() {
+ if (!caseState.current) return [];
const [media, sats] = await Promise.all([
api.get(`/api/cases/${caseState.current.id}/media`),
api.get(`/api/cases/${caseState.current.id}/satellite`),
@@ -339,7 +488,7 @@
// it once, via its richer satellite entry (coordinates/attribution), and drop
// it from the media half. dedupeBySrc is a belt-and-braces guard so a stray
// overlap can never throw the keyed picker's `each_key_duplicate`.
- pickerItems = dedupeBySrc([
+ return dedupeBySrc([
...sats.map((s) => ({
...satPanelInput(s, prefs.coordFormat),
label: `${fmtCoords(s.lat, s.lon)} · z${s.zoom}`,
@@ -355,21 +504,94 @@
kind: 'media',
})),
]);
+ }
+
+ async function openNewProofDialog() {
+ newProofName = proofTitleFromCase(caseState.current?.name, savedProofTitles());
+ newProofTemplateId = '';
+ newProofPanelPaths = [];
+ newProofQuery = '';
+ newProofCategory = 'all';
+ pickerItems = [];
+ newProofOpen = true;
+ newProofLoading = true;
+ try {
+ pickerItems = await fetchPanelItems();
+ } catch (e) {
+ toast(`Could not load case images: ${e.message}`, 'danger');
+ } finally {
+ newProofLoading = false;
+ }
+ }
+
+ function toggleNewProofPanel(src) {
+ newProofPanelPaths = newProofPanelPaths.includes(src)
+ ? newProofPanelPaths.filter((path) => path !== src)
+ : [...newProofPanelPaths, src];
+ }
+
+ function requestNewProofCreation() {
+ if (!newProofName.trim() || creatingProof) return;
+ if (proofStarted && dirty) {
+ replaceWithNewConfirm = true;
+ return;
+ }
+ createNewProof();
+ }
+
+ async function createNewProof() {
+ if (!newProofName.trim() || creatingProof) return;
+ creatingProof = true;
+ const title = newProofName.trim();
+ const template = templatesState.proof.find((t) => t.id === newProofTemplateId);
+ const selectedItems = newProofPanelPaths
+ .map((path) => pickerItems.find((item) => item.src === path))
+ .filter(Boolean);
+ try {
+ resetDoc();
+ proofStarted = true;
+ proof.title = title;
+ titleTouched = true;
+ if (template) applyTemplate(template, { notify: false });
+ for (const item of selectedItems) await addPanel(item);
+ dirty = true;
+ anchorHistory();
+ newProofOpen = false;
+ replaceWithNewConfirm = false;
+ if (proof.panels.length) requestAnimationFrame(fit);
+ } finally {
+ creatingProof = false;
+ }
+ }
+
+ async function openPicker() {
+ if (!caseState.current) {
+ toast('Add media first. The composer works on case images', 'info');
+ uiState.tool = 'media';
+ return;
+ }
+ pickerItems = await fetchPanelItems();
picker = true;
}
async function addPanel(item) {
try {
+ proofStarted = true;
const img = await loadImage(`/files/${caseState.current.id}/${item.src}`);
imgCache.set(item.src, img);
- // append to the current bottom row so new panels join the strip
- const row = proof.panels.length
- ? Math.max(...proof.panels.map((p) => p.row ?? 0))
- : 0;
+ // A template can stack the first pair. Later panels keep joining the
+ // current bottom row, preserving the composer's existing workflow.
+ const row = proof.panels.length === 1
+ ? (proof.panelDirection === 'vertical' ? 1 : 0)
+ : proof.panels.length
+ ? Math.max(...proof.panels.map((p) => p.row ?? 0))
+ : 0;
const panel = {
id: newId('p'),
src: item.src,
- caption: item.caption ?? '',
+ // captionsEnabled off → new panels start caption-less (you can still add
+ // one). On → they carry the panel's own default (satellite coords, etc.).
+ caption: proof.captionsEnabled === false ? '' : (item.caption ?? ''),
row,
scale: 1,
natural: [img.naturalWidth, img.naturalHeight],
@@ -405,19 +627,14 @@
// 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);
+ const rows = denseRowValues(proof.panels);
+ proof.panels.forEach((p, i) => { p.row = rows[i]; });
}
// Swap a panel with its left/right neighbour *within the same row*.
function movePanel(index, delta) {
- 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 target = groupNeighborIndex(proof.panels, index, delta, (p) => p.row ?? 0);
+ if (target < 0) return;
const [panel] = proof.panels.splice(index, 1);
proof.panels.splice(target, 0, panel);
dirty = true;
@@ -436,16 +653,15 @@
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));
+ const canMoveLeft = (i) => hasGroupNeighbor(proof.panels, i, -1, (p) => p.row ?? 0);
+ const canMoveRight = (i) => hasGroupNeighbor(proof.panels, i, 1, (p) => p.row ?? 0);
// 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)) * 100) / 100;
+ const next = clampPanelScale(cur, delta, SCALE_MIN, SCALE_MAX);
if (next === cur) return;
if (proof.layout === 'free') materializeFreePositions(); // others must not reflow
p.scale = next;
@@ -460,7 +676,7 @@
// materialised from the rendered layout so panels only move when moved.
function materializeFreePositions() {
- const boxes = layoutPanels(proof.panels, proof.captionSize, 'free');
+ const boxes = layoutPanels(proof.panels, proof.captionSize, 'free', proof.space);
proof.panels.forEach((p, i) => {
p.x = boxes[i].x;
p.y = boxes[i].y;
@@ -470,7 +686,7 @@
// Re-anchor stored positions at PAD (dragging past the top/left edge grows
// the document) and shift the stage by the same amount so nothing jumps.
function normalizeFree() {
- const { dx, dy } = freeNormalizeDelta(proof.panels, proof.captionSize);
+ const { dx, dy } = freeNormalizeDelta(proof.panels, proof.captionSize, proof.space);
if (!dx && !dy) return;
for (const p of proof.panels) {
p.x += dx;
@@ -520,7 +736,9 @@
proof.layout = 'grid';
selectedPanelId = null;
const target = guide ? TWEET_GUIDES[guide] : TWEET_GUIDES['16:9'];
- const rows = autoLayoutRows(proof.panels, proof.shapes, proof.notes, textOpts(), target);
+ const rows = autoLayoutRows(
+ proof.panels, proof.shapes, proof.notes, textOpts(), target, proof.space,
+ );
proof.panels.forEach((p, i) => { p.row = rows[i]; p.scale = 1; });
normalizeRows();
selectedId = null;
@@ -584,15 +802,7 @@
}
function panelAt(doc) {
- const boxes = boxesOf();
- // array order is front→back, so the first hit is the topmost panel
- 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;
+ return panelHitTest(boxesOf(), doc);
}
function onPointerDown(e) {
@@ -609,6 +819,7 @@
if (onEmpty) {
selectedId = null;
selectedPanelId = null;
+ selectedSig = null;
}
return;
}
@@ -649,6 +860,15 @@
return;
}
const sw = strokeW / hit.box.baseScale;
+ if (tool === 'freehand') {
+ const node = new Konva.Line({
+ points: [hit.nx, hit.ny], tension: 0.25, stroke: color,
+ strokeWidth: sw, lineCap: 'round', lineJoin: 'round', listening: false,
+ });
+ group.add(node);
+ drawing = { panel, node, box: hit.box, kind: tool };
+ return;
+ }
const common = { stroke: color, strokeWidth: sw, listening: false };
let node;
if (tool === 'rect') {
@@ -691,7 +911,12 @@
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') {
+ if (kind === 'freehand') {
+ const points = node.points();
+ const lx = points[points.length - 2];
+ const ly = points[points.length - 1];
+ if (nx !== lx || ny !== ly) node.points([...points, nx, ny]);
+ } else 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),
@@ -731,6 +956,11 @@
if (Math.hypot(pts[2] - pts[0], pts[3] - pts[1]) > minSize) {
shape = { kind, points: pts };
}
+ } else if (kind === 'freehand') {
+ shape = freehandShape(node.points(), {
+ minDistance: 2 / (box.scale * stage.scaleX()),
+ minLength: minSize,
+ });
}
node.destroy();
if (shape) {
@@ -750,14 +980,11 @@
pathDraft = null;
node.destroy();
// the double-click that finishes drops a duplicate last vertex — trim it
- const n = points.length;
- if (n >= 4 && Math.hypot(points[n - 2] - points[n - 4], points[n - 1] - points[n - 3]) < 3) {
- points.length = n - 2;
- }
- if (commit && points.length >= 4) {
+ const pts = trimClosingDuplicate(points);
+ if (commit && pts.length >= 4) {
const s = {
id: newId('s'), panel: panel.id, kind: 'curve', color,
- strokeWidth: strokeW, points, tension: 0.5,
+ strokeWidth: strokeW, points: pts, tension: 0.5,
};
proof.shapes.push(s);
selectedId = s.id;
@@ -772,13 +999,27 @@
function rebuild() {
docLayer.destroyChildren();
+ // A template can be selected before any panels are chosen. Keep its style
+ // in state, but do not render a background, footer, logo, or handle yet.
+ if (!hasProofCanvasContent(proof)) {
+ transformer.nodes([]);
+ endHandles.destroyChildren();
+ panelCtrls.destroyChildren();
+ guideGroup.destroyChildren();
+ docLayer.batchDraw();
+ uiLayer.batchDraw();
+ return;
+ }
const { width, height, legend, cols } = measureDoc();
const boxes = boxesOf();
const capSize = proof.captionSize ?? CAPTION_SIZE;
const free = proof.layout === 'free';
+ const { pad } = normSpace(proof.space);
+ const bgFill = proof.bg ?? BG;
+ const tc = textColors(bgFill); // caption/legend/footer colours track the bg
docLayer.add(
- new Konva.Rect({ name: 'bg', x: 0, y: 0, width, height, fill: BG })
+ new Konva.Rect({ name: 'bg', x: 0, y: 0, width, height, fill: bgFill })
);
// Drawn back→front: array order is front→back, so Z1 (the first panel in
@@ -802,16 +1043,14 @@
x: 0, y: 0, width: panel.natural[0], height: panel.natural[1],
fill: 'transparent', listening: true,
}));
- group.on('pointerdown', () => {
- // only the select tool touches panels — drawing must pass through
- group.draggable(free && tool === 'select' && !spacePan);
- if (tool === 'select') {
- selectedPanelId = panel.id;
- selectedId = null;
- }
+ bindPanelPointerLifecycle(group, {
+ // Only the select tool touches panels. Selection itself waits until the
+ // gesture settles so rebuild() cannot destroy the pointerdown target.
+ onPress: () => group.draggable(free && tool === 'select' && !spacePan),
+ onSelect: () => selectPanel(panel.id),
+ onDragEnd: free ? () => commitPanelNode(panel, group) : null,
});
if (free) {
- group.on('dragend', () => commitPanelNode(panel, group));
group.on('transformend', () => commitPanelNode(panel, group, { resized: true }));
} else {
// grid: corner-drag only changes the panel's scale — the grid decides
@@ -842,7 +1081,7 @@
x: box.x + 2, y: box.y + box.h + 9,
width: box.w - 4, text: panel.caption,
fontSize: capSize, fontFamily: 'system-ui, sans-serif',
- fill: TEXT_DIM, ellipsis: true, wrap: 'none', listening: false,
+ fill: tc.dim, ellipsis: true, wrap: 'none', listening: false,
}));
}
}
@@ -852,41 +1091,66 @@
const legendSize = proof.legendSize ?? 17;
const lineH = legendLineHeight(legendSize);
const r = Math.round(legendSize * 0.62);
- const legendTop = panelsBottom(proof.panels, proof.captionSize, proof.layout) + 8;
- const colW = (width - PAD * 2 - (cols - 1) * PAD) / cols;
+ const legendTop = panelsBottom(proof.panels, proof.captionSize, proof.layout, proof.space) + 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 cx = pad + col * (colW + pad);
const cy = legendTop + rowN * lineH + lineH / 2;
docLayer.add(new Konva.Circle({
x: cx + r, y: cy, radius: r, fill: line.color, listening: false,
}));
docLayer.add(new Konva.Text({
x: cx + r * 2 + 8, y: cy - legendSize * 0.62, width: colW - (r * 2 + 8),
- text: line.text, fontSize: legendSize, fill: TEXT_MAIN,
+ text: line.text, fontSize: legendSize, fill: tc.main,
fontFamily: 'system-ui, sans-serif', ellipsis: true, wrap: 'none', listening: false,
}));
});
- if (proof.panels.length) {
+ if (proof.panels.length && proof.footerEnabled !== false) {
const footerSize = proof.footerSize ?? 13;
const footerText = proof.footer?.trim() || attributionLine(proof.panels);
docLayer.add(new Konva.Text({
- x: PAD,
- y: height - PAD - footerBand(footerSize) + Math.round((footerBand(footerSize) - footerSize) / 2),
- width: width - PAD * 2,
+ x: pad,
+ y: height - pad - footerBand(footerSize) + Math.round((footerBand(footerSize) - footerSize) / 2),
+ width: width - pad * 2,
text: footerText,
- fontSize: footerSize, fill: TEXT_FAINT,
+ align: proof.footerAlign === 'right' ? 'right' : 'left',
+ fontSize: footerSize, fill: proof.footerColor || tc.faint,
fontFamily: 'system-ui, sans-serif', ellipsis: true, wrap: 'none', listening: false,
}));
}
+ const st = proof.signatureText && prefs.signatureHandle?.trim() ? proof.signatureText : null;
+ const pendingHandleNode = st ? new Konva.Text({
+ id: 'sig-text',
+ text: prefs.signatureHandle.trim(),
+ fontSize: st.size ?? SIG_TEXT_SIZE,
+ fontStyle: 'bold',
+ fontFamily: 'system-ui, sans-serif',
+ fill: st.color ?? '#ffffff',
+ opacity: st.opacity ?? 1,
+ listening: true,
+ }) : null;
+ const sigNatural = proof.signature && sigImg
+ ? [sigImg.naturalWidth, sigImg.naturalHeight]
+ : null;
+ const baseLogoBox = sigNatural
+ ? signatureBox(proof.signature, width, height, sigNatural)
+ : null;
+ const pair = pendingHandleNode
+ ? signaturePairPositions(
+ proof.signature, st, width, height, baseLogoBox,
+ pendingHandleNode.width(), pendingHandleNode.height(),
+ )
+ : null;
+
// signature — last, so the logo sits over everything it overlaps. Drawn into
// docLayer (not the UI layer) because it's part of the published image.
if (proof.signature && sigImg) {
- const natural = [sigImg.naturalWidth, sigImg.naturalHeight];
- const box = signatureBox(proof.signature, width, height, natural);
+ const box = pair?.logo ?? baseLogoBox;
const node = new Konva.Image({
+ id: 'sig-logo',
image: sigImg, x: box.x, y: box.y, width: box.w, height: box.h,
opacity: proof.signature.opacity ?? 1,
});
@@ -896,13 +1160,51 @@
node.on('pointerdown', () => {
node.draggable(tool === 'select' && !spacePan);
});
+ // a plain click (no drag) selects the logo so the resize handles appear.
+ node.on('click tap', () => { if (tool === 'select') selectSig('logo'); });
// the corner picker gets you there; the drag fine-tunes. Either way the
// stored value is an offset from the anchor, so it survives a doc resize
node.on('dragend', () => {
- const { dx, dy } = signatureOffset(
- proof.signature, width, height, natural, node.x(), node.y(),
+ const placement = signatureOffset(
+ proof.signature, width, height, sigNatural, node.x(), node.y(),
);
- proof.signature = { ...proof.signature, dx, dy };
+ proof.signature = { ...proof.signature, ...placement };
+ dirty = true;
+ });
+ // corner-drag scales the logo; fold it back into the stored width share.
+ node.on('transformend', () => {
+ const scale = (proof.signature.scale ?? SIG_SCALE) * node.scaleX();
+ node.scale({ x: 1, y: 1 });
+ proof.signature = {
+ ...proof.signature,
+ scale: Math.round(Math.max(0.03, Math.min(0.4, scale)) * 1000) / 1000,
+ };
+ dirty = true;
+ });
+ docLayer.add(node);
+ }
+
+ // Account handle laid over the panels. Positioned
+ // by anchor + drag like the logo, so it survives a document resize; drag it
+ // anywhere with the select tool.
+ if (st && pendingHandleNode) {
+ const node = pendingHandleNode;
+ const tw = node.width();
+ const th = node.height();
+ const pos = pair?.handle ?? anchoredPos(st, width, height, tw, th);
+ node.position(pos);
+ node.on('pointerdown', () => node.draggable(tool === 'select' && !spacePan));
+ node.on('click tap', () => { if (tool === 'select') selectSig('text'); });
+ node.on('dragend', () => {
+ const placement = anchoredOffset(st, width, height, tw, th, node.x(), node.y());
+ proof.signatureText = { ...st, ...placement };
+ dirty = true;
+ });
+ // corner-drag scales the handle; fold it back into the stored font size.
+ node.on('transformend', () => {
+ const size = Math.round((st.size ?? SIG_TEXT_SIZE) * node.scaleX());
+ node.scale({ x: 1, y: 1 });
+ proof.signatureText = { ...st, size: Math.max(12, Math.min(300, size)) };
dirty = true;
});
docLayer.add(node);
@@ -921,6 +1223,10 @@
// free and clamping on release made the panel visibly snap back whenever
// the drag overshot the 25–250% range (worst at the bounds, where a resize
// in the blocked direction just reverted). Shapes stay unconstrained.
+ // the logo or the @handle, picked for a corner-resize (aspect locked).
+ const sigNode = !selectedNode && !panelNode && selectedSig
+ ? docLayer.findOne(selectedSig === 'logo' ? '#sig-logo' : '#sig-text')
+ : null;
const boundPanel = panelNode ? proof.panels.find((p) => p.id === selectedPanelId) : null;
transformer.boundBoxFunc((oldBox, newBox) => {
if (!boundPanel) return newBox;
@@ -928,13 +1234,16 @@
(newBox.width / stage.scaleX()) * (boundPanel.natural[1] / (boundPanel.natural[0] * PANEL_H));
return impliedScale < SCALE_MIN || impliedScale > SCALE_MAX ? oldBox : newBox;
});
- transformer.nodes(selectedNode ? [selectedNode] : panelNode ? [panelNode] : []);
+ transformer.keepRatio(!!sigNode);
+ transformer.nodes(
+ selectedNode ? [selectedNode] : panelNode ? [panelNode] : sigNode ? [sigNode] : []
+ );
const selKind = selectedShape?.kind;
transformer.rotateEnabled(selKind === 'text' || selKind === 'rect' || selKind === 'ellipse');
transformer.enabledAnchors(
selKind === 'rect' || selKind === 'ellipse'
? ['top-left', 'top-right', 'bottom-left', 'bottom-right', 'middle-left', 'middle-right', 'top-center', 'bottom-center']
- : selKind === 'text' || panelNode
+ : selKind === 'text' || panelNode || sigNode
? ['top-left', 'top-right', 'bottom-left', 'bottom-right']
: []
);
@@ -983,6 +1292,8 @@
// 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).
+ // Freehand strokes stay draggable as a whole; showing every sampled point
+ // would cover the stroke in handles.
const POINT_KINDS = new Set(['line', 'arrow', 'curve']);
function drawEndHandles(boxes) {
endHandles.destroyChildren();
@@ -1104,13 +1415,6 @@
}
// 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
@@ -1160,6 +1464,7 @@
e.cancelBubble = true;
selectedId = s.id;
selectedPanelId = null;
+ selectedSig = null;
}
});
node.on('dblclick dbltap', (e) => {
@@ -1169,7 +1474,7 @@
node.on('dragstart', () => node.getParent()?.moveToTop());
node.on('dragend', () => {
const { fromBox, toBox } = rebindOnDrop(s, node);
- const p = toBox ? remapXY(node.x(), node.y(), fromBox, toBox) : { x: node.x(), y: node.y() };
+ const p = toBox ? remapPanelXY(node.x(), node.y(), fromBox, toBox) : { x: node.x(), y: node.y() };
s.x = p.x;
s.y = p.y;
dirty = true;
@@ -1195,9 +1500,9 @@
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 if (s.kind === 'curve') {
+ } else if (s.kind === 'curve' || s.kind === 'freehand') {
node = new Konva.Line({
- points: s.points, tension: s.tension ?? 0.5,
+ points: s.points, tension: s.tension ?? (s.kind === 'freehand' ? 0.25 : 0.5),
lineCap: 'round', lineJoin: 'round', ...common,
});
} else {
@@ -1214,17 +1519,18 @@
e.cancelBubble = true;
selectedId = s.id;
selectedPanelId = null;
+ selectedSig = null;
}
});
node.on('dragstart', () => node.getParent()?.moveToTop());
node.on('dragend', () => {
if (s.kind === 'rect' || s.kind === 'ellipse') {
const { fromBox, toBox } = rebindOnDrop(s, node);
- const p = toBox ? remapXY(node.x(), node.y(), fromBox, toBox) : { x: node.x(), y: node.y() };
+ const p = toBox ? remapPanelXY(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 into every vertex, then
+ // points-based shapes: 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();
const folded = s.points.map((v, i) => (i % 2 === 0 ? v + dx : v + dy));
@@ -1302,7 +1608,7 @@
}
// 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.
+ // the original. Points-based kinds shift every vertex.
function pasteShape() {
if (!clipboard) return;
const target = proof.panels.some((p) => p.id === clipboard.panel)
@@ -1337,21 +1643,17 @@
// (rebuild() adds shapes to their panel group in array order), so moving
// past a shape bound to a different panel would silently no-op visually.
function moveShape(index, delta) {
- const panelId = proof.shapes[index].panel;
- let target = index + delta;
- while (target >= 0 && target < proof.shapes.length && proof.shapes[target].panel !== panelId) {
- target += delta;
- }
- if (target < 0 || target >= proof.shapes.length || proof.shapes[target].panel !== panelId) return;
+ const target = groupNeighborIndex(proof.shapes, index, delta, (s) => s.panel);
+ if (target < 0) return;
const [s] = proof.shapes.splice(index, 1);
proof.shapes.splice(target, 0, s);
dirty = true;
}
- const canMoveShapeUp = (i) => proof.shapes.slice(0, i).some((s) => s.panel === proof.shapes[i].panel);
- const canMoveShapeDown = (i) => proof.shapes.slice(i + 1).some((s) => s.panel === proof.shapes[i].panel);
+ const canMoveShapeUp = (i) => hasGroupNeighbor(proof.shapes, i, -1, (s) => s.panel);
+ const canMoveShapeDown = (i) => hasGroupNeighbor(proof.shapes, i, 1, (s) => s.panel);
- const KIND_ICON = { rect: 'square', ellipse: 'circle', arrow: 'arrow', line: 'line', curve: 'curve', text: 'text' };
- const KIND_LABEL = { rect: 'Box', ellipse: 'Ellipse', arrow: 'Arrow', line: 'Line', curve: 'Curve', text: 'Text' };
+ const KIND_ICON = { rect: 'square', ellipse: 'circle', arrow: 'arrow', line: 'line', curve: 'curve', freehand: 'freehand', text: 'text' };
+ const KIND_LABEL = { rect: 'Box', ellipse: 'Ellipse', arrow: 'Arrow', line: 'Line', curve: 'Curve', freehand: 'Freehand', text: 'Text' };
// Color / stroke controls act on the selected shape when there is one
// (live edit), otherwise they set the defaults for the next drawn shape.
@@ -1360,8 +1662,7 @@
const oldColor = selectedShape.color;
selectedShape.color = c;
// carry the legend note over if this color is otherwise unused
- if (proof.notes[oldColor] && !proof.notes[c] &&
- !proof.shapes.some((s) => s !== selectedShape && s.color === oldColor)) {
+ if (canReassignLegendNote(proof.notes, oldColor, c, proof.shapes, selectedShape)) {
proof.notes[c] = proof.notes[oldColor];
delete proof.notes[oldColor];
}
@@ -1439,6 +1740,7 @@
} else if (e.key === 'Escape') {
selectedId = null;
selectedPanelId = null;
+ selectedSig = null;
tool = 'select';
} else if (e.key === 'v') tool = 'select';
else if (e.key === 'r') tool = 'rect';
@@ -1446,6 +1748,7 @@
else if (e.key === 'a') tool = 'arrow';
else if (e.key === 'l') tool = 'line';
else if (e.key === 'c') tool = 'curve';
+ else if (e.key === 'd') tool = 'freehand';
else if (e.key === 't') tool = 'text';
else if (e.key === 'f') fit();
}
@@ -1463,22 +1766,24 @@
function exportPng() {
const { width, height } = measureDoc();
+ const { pixelRatio } = proofExportOptions(width, height);
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;
+ try {
+ transformer.nodes([]);
+ stage.scale({ x: 1, y: 1 });
+ stage.position({ x: 0, y: 0 });
+ stage.width(width);
+ stage.height(height);
+ return docLayer.toDataURL({ x: 0, y: 0, width, height, pixelRatio });
+ } finally {
+ stage.scale(prevScale);
+ stage.position(prevPos);
+ stage.width(prevSize.w);
+ stage.height(prevSize.h);
+ rebuild();
+ }
}
// Copy the composed PNG straight to the clipboard — for peer review in a
@@ -1501,20 +1806,12 @@
// Every proof already saved in this case, read off the filed entities: the
// slugs (filename without `proofs/…​.json`) to catch a filename collision, and
// the titles so a fresh proof can take a title that reads apart from them.
- function savedProofEntities() {
- return (caseState.current?.entities ?? []).filter((e) => {
- const s = e.attrs?.spec;
- return typeof s === 'string' && s.startsWith('proofs/') && s.endsWith('.json');
- });
- }
- const savedProofNames = () =>
- new Set(savedProofEntities().map((e) => e.attrs.spec.slice(7, -5)));
- const savedProofTitles = () => new Set(savedProofEntities().map((e) => e.label ?? ''));
+ const savedProofNames = () => savedProofSlugs(caseState.current?.entities);
+ const savedProofTitles = () => libSavedProofTitles(caseState.current?.entities);
// Title of a saved proof by its slug, for the overwrite prompt.
function savedProofTitle(name) {
- const e = savedProofEntities().find((x) => x.attrs.spec === `proofs/${name}.json`);
- return e?.label ?? name;
+ return libSavedProofTitle(caseState.current?.entities, name);
}
// Default title for a fresh proof, numbered past any already in the case so
@@ -1593,7 +1890,9 @@
async function openProof(entry) {
const spec = await api.get(`/api/cases/${caseState.current.id}/proofs/${entry.name}`);
+ const style = normalizeProofStyle(spec);
resetDoc();
+ proofStarted = true;
// Bind the opened proof's name up front, before the panel images load: they
// stream in one by one and enable the Save button as they arrive, so a Save
// during the load has to write back over this proof, not file a new one.
@@ -1601,12 +1900,22 @@
proof.title = spec.title;
proof.coordsText = spec.coordsText ?? '';
proof.source = spec.source ?? '';
- proof.captionSize = spec.captionSize ?? CAPTION_SIZE;
- proof.legendSize = spec.legendSize ?? LEGEND_SIZE;
- proof.footerSize = spec.footerSize ?? FOOTER_SIZE;
- proof.footer = spec.footer ?? '';
- proof.layout = spec.layout ?? 'grid';
- proof.signature = spec.signature ?? null;
+ proof.captionSize = style.captionSize;
+ proof.legendSize = style.legendSize;
+ proof.footerSize = style.footerSize;
+ proof.footer = style.footer;
+ proof.footerEnabled = style.footerEnabled;
+ proof.footerColor = style.footerColor;
+ proof.footerAlign = style.footerAlign;
+ proof.captionsEnabled = style.captionsEnabled;
+ proof.bg = style.bg;
+ proof.space = style.space;
+ proof.layout = style.layout;
+ proof.panelDirection = style.panelDirection;
+ proof.signature = style.signature;
+ proof.signatureText = style.signatureText;
+ proof.palette = style.palette;
+ color = proof.palette[0];
for (const p of spec.panels) {
try {
const img = await loadImage(`/files/${caseState.current.id}/${p.src}`);
@@ -1657,34 +1966,36 @@
<div class="tool">
<div class="tool-header">
<h2>Proof Composer</h2>
- <input
- class="input title-input"
- bind:value={proof.title}
- oninput={() => { dirty = true; titleTouched = true; }}
- />
- {#if dirty}<span class="badge">unsaved</span>{/if}
+ {#if proofStarted}
+ <input
+ class="input title-input"
+ bind:value={proof.title}
+ oninput={() => { dirty = true; titleTouched = true; }}
+ />
+ {#if dirty}<span class="badge">unsaved</span>{/if}
+ {/if}
<div class="spacer"></div>
{#if caseState.current}
<button class="btn" onclick={openProofList}><Icon name="folderOpen" size={15} /> Open</button>
{/if}
- {#if proof.panels.length}
+ {#if proofStarted}
<button class="btn" onclick={() => (discardConfirm = true)} title="Clear this proof">
<Icon name="reset" size={15} /> Discard
</button>
{/if}
- <button class="btn" onclick={openPicker}><Icon name="plus" size={15} /> Add panel</button>
+ <button class="btn" onclick={openNewProofDialog}><Icon name="plus" size={15} /> New proof</button>
<button
class="btn"
onclick={copyPng}
- disabled={!proof.panels.length || copying}
+ disabled={!proofHasContent || copying}
title="Copy the composed PNG to the clipboard"
>
<Icon name="copy" size={15} /> {copying ? 'Copying…' : 'Copy PNG'}
</button>
- <button class="btn btn-primary" onclick={() => save()} disabled={!proof.panels.length || saving}>
+ <button class="btn btn-primary" onclick={() => save()} disabled={!proofHasContent || saving}>
<Icon name="check" size={15} /> {saving ? 'Saving…' : 'Save'}
</button>
- <button class="btn" onclick={() => save({ andPost: true })} disabled={!proof.panels.length || saving}>
+ <button class="btn" onclick={() => save({ andPost: true })} disabled={!proofHasContent || saving}>
<Icon name="post" size={15} /> To Post
</button>
</div>
@@ -1703,14 +2014,14 @@
<button
class="tb-btn"
class:active={tool === t.id}
- title="{t.label} ({t.id === 'select' ? 'v' : t.id[0]})"
+ title="{t.label} ({t.shortcut})"
onclick={() => (tool = t.id)}
>
<Icon name={t.icon} size={18} />
</button>
{/each}
<div class="tb-sep"></div>
- {#each ANNO_COLORS as c (c)}
+ {#each proof.palette as c (c)}
<button
class="color-btn"
class:active={activeColor === c}
@@ -1722,7 +2033,7 @@
{/each}
<label
class="color-btn color-pick"
- class:active={!ANNO_COLORS.includes(activeColor)}
+ class:active={!proof.palette.includes(activeColor)}
style:background={activeColor}
title="Custom color"
>
@@ -1805,21 +2116,74 @@
}}
/>
{/if}
- {#if !proof.panels.length}
+ {#if !proofHasContent}
<div class="empty overlay-empty">
<div class="empty-icon"><Icon name="proof" size={42} /></div>
- <h3>Compose a proof</h3>
- <p>Add panels, then mark matching features in the same color.</p>
- <button class="btn" onclick={openPicker}>
- <Icon name="plus" size={15} /> Add panel
- </button>
+ {#if proofStarted}
+ <h3>No panels yet</h3>
+ <p>Add panels when you are ready.</p>
+ <button class="btn" onclick={openPicker}>
+ <Icon name="plus" size={15} /> Add panel
+ </button>
+ {:else}
+ <h3>Compose a proof</h3>
+ <p>Create a proof to choose its template and starting panels.</p>
+ <button class="btn" onclick={openNewProofDialog}>
+ <Icon name="plus" size={15} /> New proof
+ </button>
+ {/if}
</div>
{/if}
</div>
- <!-- right: panels & annotations -->
- <aside class="side">
- <div class="side-scroll">
+ <!-- right: proof settings, panels & annotations -->
+ {#if proofStarted}
+ <aside class="side">
+ <div class="side-scroll">
+ <!-- House style stays independent from content. A new proof can keep a
+ selected template while its canvas remains empty until panels land. -->
+ <div class="meta-field">
+ <div class="meta-head">
+ <Icon name="layers" size={13} />
+ <span>House style</span>
+ {#if templatesState.proof.length}
+ <button
+ class="tpl-settings-link"
+ type="button"
+ title="Open Settings → Templates to create, edit or delete house styles"
+ onclick={openTemplateSettings}
+ >
+ Settings templates
+ </button>
+ {/if}
+ </div>
+ {#if templatesState.proof.length}
+ <select
+ class="input meta-input"
+ value={appliedTemplate?.id ?? ''}
+ title="Choose a saved house style"
+ onchange={applyFromSelect}
+ >
+ <option value="">No template</option>
+ {#each templatesState.proof as t (t.id)}
+ <option value={t.id}>{t.name}</option>
+ {/each}
+ </select>
+ {:else}
+ <p class="tpl-none">
+ No templates yet.
+ <button
+ class="tpl-inline-link"
+ type="button"
+ title="Open Settings → Templates to create your first house style"
+ onclick={openTemplateSettings}
+ >
+ Create one in Settings → Templates.
+ </button>
+ </p>
+ {/if}
+ </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">
@@ -1869,9 +2233,18 @@
/>
</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>
+ <div class="side-title-row" style="margin-top: 14px">
+ <button class="side-title collapsible" onclick={() => (collapsed.panels = !collapsed.panels)}>
+ <span><Icon name={collapsed.panels ? 'chevronRight' : 'chevronDown'} size={13} /> Panels <span class="count">{proof.panels.length}</span></span>
+ </button>
+ <button
+ class="btn btn-ghost btn-sm side-add"
+ title="Add a panel"
+ onclick={openPicker}
+ >
+ <Icon name="plus" size={13} />
+ </button>
+ </div>
{#if !collapsed.panels}
{#if gonePanels.length}
<!-- A panel's media was deleted from the case. The proof keeps it: the
@@ -1945,7 +2318,7 @@
</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>
+ <div class="none">Draw on a panel. Same color = same feature.</div>
{/if}
{#each featureList as c, i (c)}
<div class="anno-row" class:active={activeColor === c}>
@@ -2053,6 +2426,18 @@
</button>
{#if advancedOpen}
<div class="adv-body">
+ <label class="sig-check">
+ <input
+ type="checkbox"
+ checked={proof.captionsEnabled !== false}
+ onchange={(e) => {
+ proof.captionsEnabled = e.currentTarget.checked;
+ dirty = true;
+ }}
+ />
+ <span>Caption new panels</span>
+ </label>
+ <div class="adv-hint">Off: added panels start blank. You can still type a caption on any panel.</div>
<div class="size-row">
<span>Caption size</span>
<input class="size-slider" type="range" min="10" max="40" step="1"
@@ -2065,28 +2450,51 @@
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>
+ <label class="sig-check">
+ <input
+ type="checkbox"
+ checked={proof.footerEnabled !== false}
+ onchange={(e) => {
+ proof.footerEnabled = e.currentTarget.checked;
+ dirty = true;
+ }}
+ />
+ <span>Show footer</span>
+ </label>
+ {#if proof.footerEnabled !== false}
+ <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="size-row">
+ <span>Footer alignment</span>
+ <select class="input" bind:value={proof.footerAlign}
+ onchange={() => (dirty = true)}>
+ <option value="left">Left</option>
+ <option value="right">Right</option>
+ </select>
+ </div>
+ <div class="adv-hint">Leave empty to keep the automatic imagery / source attribution.</div>
+ {:else}
+ <div class="adv-hint">The band under the panels is gone. Drop all margins for panels-only output.</div>
+ {/if}
<label class="sig-check">
<input
type="checkbox"
disabled={!sigImg}
- checked={!!proof.signature}
+ checked={!!proof.signature && !!sigImg}
onchange={(e) => {
proof.signature = e.currentTarget.checked ? newSignature() : null;
dirty = true;
@@ -2106,7 +2514,14 @@
onclick={() => {
// a new corner starts fresh: the old nudge was measured
// from the old corner, so keeping it would fling the logo
- proof.signature = { ...proof.signature, anchor: a.id, dx: 0, dy: 0 };
+ proof.signature = {
+ ...proof.signature,
+ anchor: a.id,
+ dx: 0,
+ dy: 0,
+ xRatio: undefined,
+ yRatio: undefined,
+ };
dirty = true;
}}
>{a.label}</button>
@@ -2114,7 +2529,7 @@
</div>
<div class="size-row">
<span>Size</span>
- <input class="size-slider" type="range" min="0.04" max="0.4" step="0.01"
+ <input class="size-slider" type="range" min="0.03" max="0.4" step="0.01"
value={proof.signature.scale}
oninput={(e) => {
proof.signature = { ...proof.signature, scale: Number(e.currentTarget.value) };
@@ -2134,13 +2549,154 @@
</div>
<div class="adv-hint">Drag the logo on the canvas to nudge it off the corner.</div>
{/if}
+
+ <label class="sig-check">
+ <input
+ type="checkbox"
+ disabled={!prefs.signatureHandle?.trim()}
+ checked={!!proof.signatureText && !!prefs.signatureHandle?.trim()}
+ onchange={(e) => {
+ proof.signatureText = e.currentTarget.checked ? newSignatureText() : null;
+ dirty = true;
+ }}
+ />
+ <span>Add account handle</span>
+ </label>
+ {#if !prefs.signatureHandle?.trim()}
+ <div class="adv-hint">Add your account handle in Settings → Preferences to use it on proofs.</div>
+ {:else if proof.signatureText}
+ <div class="adv-hint">Drag the account handle on the canvas to place it.</div>
+ {/if}
</div>
{/if}
- </div>
- </aside>
+ </div>
+ </aside>
+ {/if}
</div>
</div>
+{#if newProofOpen}
+ <Modal
+ title="Create proof"
+ onclose={() => { if (!creatingProof) newProofOpen = false; }}
+ width="780px"
+ >
+ <form class="new-proof-form" onsubmit={(e) => { e.preventDefault(); requestNewProofCreation(); }}>
+ <label class="new-proof-field">
+ <span>Name</span>
+ <input
+ class="input"
+ bind:value={newProofName}
+ maxlength="200"
+ placeholder="Proof name"
+ />
+ </label>
+
+ <label class="new-proof-field">
+ <span>Template</span>
+ <select class="input" bind:value={newProofTemplateId}>
+ <option value="">No template</option>
+ {#each templatesState.proof as t (t.id)}
+ <option value={t.id}>{t.name}</option>
+ {/each}
+ </select>
+ <small>Sets the look without choosing content.</small>
+ </label>
+
+ <fieldset class="new-proof-panels">
+ <legend>
+ <span>Panels</span>
+ <span class="selected-count">
+ {newProofPanelPaths.length} panel{newProofPanelPaths.length === 1 ? '' : 's'} selected
+ </span>
+ </legend>
+
+ <div class="panel-picker-bar">
+ <div class="panel-search">
+ <Icon name="search" size={13} />
+ <input placeholder="Search panels…" bind:value={newProofQuery} />
+ {#if newProofQuery}
+ <button type="button" onclick={() => (newProofQuery = '')} aria-label="Clear search">
+ <Icon name="x" size={12} />
+ </button>
+ {/if}
+ </div>
+ <div class="panel-categories" aria-label="Panel categories">
+ <button
+ type="button"
+ class:active={newProofCategory === 'all'}
+ onclick={() => (newProofCategory = 'all')}
+ >All <span>{pickerItems.length}</span></button>
+ <button
+ type="button"
+ class:active={newProofCategory === 'satellite'}
+ onclick={() => (newProofCategory = 'satellite')}
+ >Satellite captures <span>{pickerItems.filter((item) => item.kind === 'satellite').length}</span></button>
+ <button
+ type="button"
+ class:active={newProofCategory === 'media'}
+ onclick={() => (newProofCategory = 'media')}
+ >Other images <span>{pickerItems.filter((item) => item.kind === 'media').length}</span></button>
+ </div>
+ </div>
+
+ {#if newProofLoading}
+ <div class="picker-empty">Loading case images…</div>
+ {:else if !pickerItems.length}
+ <div class="picker-empty">No case images yet, but you can add panels later.</div>
+ {:else if !filteredNewProofItems.length}
+ <div class="picker-empty">No panels match this search.</div>
+ {:else}
+ <div class="pick-grid new-proof-grid">
+ {#each filteredNewProofItems as item (item.src)}
+ <button
+ type="button"
+ class="pick card selectable-pick"
+ class:selected={newProofPanelPaths.includes(item.src)}
+ aria-pressed={newProofPanelPaths.includes(item.src)}
+ onclick={() => toggleNewProofPanel(item.src)}
+ >
+ <span class="pick-image">
+ <img src={`/files/${caseState.current?.id}/${item.thumb}`} alt="" loading="lazy" />
+ {#if newProofPanelPaths.includes(item.src)}
+ <span class="pick-selected"><Icon name="check" size={13} /></span>
+ {/if}
+ </span>
+ <span class="pick-label" title={item.label}>
+ <Icon name={item.kind === 'satellite' ? 'satellite' : 'image'} size={12} />
+ {item.label}
+ </span>
+ </button>
+ {/each}
+ </div>
+ {/if}
+ </fieldset>
+
+ <div class="new-proof-actions">
+ <button type="button" class="btn" disabled={creatingProof} onclick={() => (newProofOpen = false)}>
+ Cancel
+ </button>
+ <button type="submit" class="btn btn-primary" disabled={!newProofName.trim() || creatingProof}>
+ <Icon name="plus" size={15} /> {creatingProof ? 'Creating…' : 'Create proof'}
+ </button>
+ </div>
+ </form>
+ </Modal>
+{/if}
+
+{#if replaceWithNewConfirm}
+ <ConfirmDialog
+ title="Create a new proof?"
+ message="The current proof has unsaved changes."
+ detail="Creating a new proof discards those changes."
+ confirmLabel="Create proof"
+ tone="danger"
+ icon="plus"
+ onconfirm={() => { replaceWithNewConfirm = false; createNewProof(); }}
+ oncancel={() => (replaceWithNewConfirm = false)}
+ />
+{/if}
+
{#if discardConfirm}
<ConfirmDialog
title="Discard this proof?"
@@ -2245,6 +2801,131 @@
width: min(320px, 26vw);
font-weight: 600;
}
+ .new-proof-form {
+ display: flex;
+ flex-direction: column;
+ gap: 15px;
+ }
+ .new-proof-field {
+ display: grid;
+ grid-template-columns: 110px minmax(0, 1fr);
+ align-items: center;
+ gap: 5px 12px;
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ }
+ .new-proof-field small {
+ grid-column: 2;
+ color: var(--text-3);
+ font-weight: 400;
+ }
+ .new-proof-panels {
+ min-width: 0;
+ padding: 0;
+ border: 0;
+ }
+ .new-proof-panels legend {
+ width: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 7px;
+ font-size: var(--fs-xs);
+ font-weight: 700;
+ color: var(--text-2);
+ }
+ .selected-count { color: var(--text-3); font-weight: 500; }
+ .panel-picker-bar {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 7px;
+ margin-bottom: 10px;
+ min-width: 0;
+ }
+ .panel-search {
+ min-width: 170px;
+ flex: 1;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-3);
+ }
+ .panel-search:focus-within { border-color: var(--accent); }
+ .panel-search input {
+ width: 100%;
+ min-width: 0;
+ border: 0;
+ outline: 0;
+ background: transparent;
+ color: var(--text-1);
+ font: inherit;
+ }
+ .panel-search button { display: flex; color: var(--text-3); }
+ .panel-categories { display: flex; gap: 5px; overflow-x: auto; max-width: 100%; }
+ .panel-categories button {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ padding: 5px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ white-space: nowrap;
+ }
+ .panel-categories button:hover { border-color: var(--border-strong); color: var(--text-1); }
+ .panel-categories button.active { border-color: var(--accent); color: var(--text-1); }
+ .panel-categories span { color: var(--text-3); }
+ .new-proof-grid {
+ max-height: min(42vh, 390px);
+ overflow-y: auto;
+ padding: 1px;
+ }
+ .selectable-pick { position: relative; }
+ .selectable-pick.selected { border-color: var(--accent); }
+ .pick-image { position: relative; display: block; }
+ .pick-selected {
+ position: absolute;
+ top: 6px;
+ right: 6px;
+ width: 22px;
+ height: 22px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 50%;
+ background: var(--accent);
+ color: var(--accent-text);
+ }
+ .picker-empty {
+ min-height: 120px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 20px;
+ border: 1px dashed var(--border);
+ border-radius: var(--r-md);
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ }
+ .new-proof-actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+ padding-top: 2px;
+ }
+ .tpl-none {
+ margin: 0 0 6px;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ line-height: 1.4;
+ }
.body {
flex: 1;
display: flex;
@@ -2386,6 +3067,9 @@
align-items: center;
gap: 4px;
}
+ .side-title-row { display: flex; align-items: center; gap: 4px; }
+ .side-title-row .side-title { margin-bottom: 0; }
+ .side-add { margin-left: auto; color: var(--text-3); }
.count { color: var(--text-3); }
.meta-field { margin-bottom: 10px; }
.meta-head {
@@ -2408,6 +3092,28 @@
border-radius: var(--r-sm);
}
.meta-reset:hover { color: var(--text-1); background: var(--bg-2); }
+ .tpl-settings-link {
+ margin-left: auto;
+ display: inline-flex;
+ align-items: center;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ text-transform: none;
+ letter-spacing: 0;
+ text-decoration: underline;
+ text-decoration-style: dotted;
+ text-underline-offset: 2px;
+ }
+ .tpl-settings-link:hover { color: var(--text-2); }
+ .tpl-inline-link {
+ color: var(--text-3);
+ font: inherit;
+ text-decoration: underline;
+ text-decoration-style: dotted;
+ text-underline-offset: 2px;
+ }
+ .tpl-inline-link:hover { color: var(--text-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); }
.gone-note {
diff --git a/frontend/src/tools/ProofComposer.test.js b/frontend/src/tools/ProofComposer.test.js
new file mode 100644
index 0000000..8526d6b
--- /dev/null
+++ b/frontend/src/tools/ProofComposer.test.js
@@ -0,0 +1,59 @@
+import { describe, expect, it, vi } from 'vitest';
+import { render } from 'svelte/server';
+
+vi.mock('konva', () => ({ default: {} }));
+
+import ProofComposer, { bindPanelPointerLifecycle } from './ProofComposer.svelte';
+
+describe('Proof Composer empty state', () => {
+ it('hides proof-specific chrome until a proof is started', () => {
+ const { body } = render(ProofComposer);
+
+ expect(body).toContain('Compose a proof');
+ expect(body).toContain('Freehand (d)');
+ expect(body).not.toContain('title-input');
+ expect(body).not.toContain('<aside');
+ expect(body).not.toContain('House style');
+ expect(body).not.toContain('Coordinates');
+ expect(body).not.toContain('Annotations');
+ });
+});
+
+describe('Proof Composer panel pointer lifecycle', () => {
+ function fakeGroup() {
+ const handlers = new Map();
+ return {
+ handlers,
+ group: { on: vi.fn((events, handler) => handlers.set(events, handler)) },
+ };
+ }
+
+ it('does not select and rebuild the panel during pointerdown', () => {
+ const { group, handlers } = fakeGroup();
+ const onPress = vi.fn();
+ const onSelect = vi.fn();
+
+ bindPanelPointerLifecycle(group, { onPress, onSelect, onDragEnd: null });
+ handlers.get('pointerdown')();
+
+ expect(onPress).toHaveBeenCalledOnce();
+ expect(onSelect).not.toHaveBeenCalled();
+
+ handlers.get('click tap')();
+ expect(onSelect).toHaveBeenCalledOnce();
+ });
+
+ it('selects a dragged panel only after the drag has ended', () => {
+ const { group, handlers } = fakeGroup();
+ const calls = [];
+
+ bindPanelPointerLifecycle(group, {
+ onPress: vi.fn(),
+ onSelect: () => calls.push('select'),
+ onDragEnd: () => calls.push('commit'),
+ });
+ handlers.get('dragend')();
+
+ expect(calls).toEqual(['select', 'commit']);
+ });
+});
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index c9bf1a9..568f229 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -1671,19 +1671,6 @@
}
// --- editing the area of interest (rect corners / polygon vertices) ---
- function cornerLatLng(b, c) {
- return [c[0] === 'n' ? b.north : b.south, c[1] === 'e' ? b.east : b.west];
- }
-
- function normBounds(b) {
- return {
- south: Math.min(b.south, b.north),
- north: Math.max(b.south, b.north),
- west: Math.min(b.west, b.east),
- east: Math.max(b.west, b.east),
- };
- }
-
// The area box + handles show only while editing the area; once a grid is
// drawn the box is hidden and just the cells remain.
function renderAoi() {
@@ -1695,7 +1682,7 @@
if (grid.aoi.type === 'rect') {
aoiOutline = L.rectangle([[b.south, b.west], [b.north, b.east]], AOI_STYLE).addTo(gridAoiLayer);
for (const corner of CORNERS) {
- const m = L.marker(cornerLatLng(b, corner), {
+ const m = L.marker(gridSearch.cornerLatLng(b, corner), {
draggable: true,
keyboard: false,
icon: gridHandleIcon(),
@@ -1718,13 +1705,13 @@
else dragBounds.south = latlng.lat;
if (corner[1] === 'e') dragBounds.east = latlng.lng;
else dragBounds.west = latlng.lng;
- const b = normBounds(dragBounds);
+ const b = gridSearch.normalizeBounds(dragBounds);
aoiOutline?.setBounds([[b.south, b.west], [b.north, b.east]]);
}
function commitResize() {
if (!dragBounds || !grid) return;
- const b = normBounds(dragBounds);
+ const b = gridSearch.normalizeBounds(dragBounds);
dragBounds = null;
const resized = gridSearch.resizeRect(grid, b);
if (gridSearch.estimateCells(resized) > GRID_MAX_CELLS) {
@@ -1843,15 +1830,14 @@
const p2 = map.containerPointToLatLng(L.point(r.x1, r.y1));
doApplyArea({
type: 'rect',
- bounds: normBounds({ south: p1.lat, north: p2.lat, west: p1.lng, east: p2.lng }),
+ bounds: gridSearch.normalizeBounds({ south: p1.lat, north: p2.lat, west: p1.lng, east: p2.lng }),
});
}
// polygon area: click to drop vertices (handled in onMapClick), drag the
// handles to adjust, Confirm to build.
function draftLatLngs() {
- const pts = polyDraft.map((p) => [p.lat, p.lon]);
- return pts.length >= 3 ? pts.concat([pts[0]]) : pts;
+ return gridSearch.closeRing(polyDraft.map((p) => [p.lat, p.lon]));
}
function renderDraft() {
@@ -1917,8 +1903,8 @@
}
function gridTitleFor(aoi) {
- const b = gridSearch.aoiBounds(aoi);
- return fmtCoords((b.south + b.north) / 2, (b.west + b.east) / 2);
+ const c = gridSearch.aoiCenter(aoi);
+ return fmtCoords(c.lat, c.lon);
}
// --- sweep loop: fly to a cell, mark it, advance ---
diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelte
index bd2f0cd..c936c40 100644
--- a/frontend/src/tools/Settings.svelte
+++ b/frontend/src/tools/Settings.svelte
@@ -1,7 +1,12 @@
<script>
import { onMount } from 'svelte';
import { api } from '../lib/api.js';
- import { toast, prefs, applyPrefs } from '../lib/state.svelte.js';
+ import { toast, prefs, applyPrefs, uiState } from '../lib/state.svelte.js';
+ import {
+ templatesState, loadTemplates, saveTemplate, deleteTemplate,
+ } from '../lib/state.svelte.js';
+ import { templateFromProof, textSignatureStyle } from '../lib/composer.js';
+ import { POST_TARGETS, templateFromPost } from '../lib/post.js';
import { formatCoords, parseHomeView } from '../lib/coords.js';
import { formatDistance, formatArea } from '../lib/measure.js';
import {
@@ -18,12 +23,16 @@
import { probeKey, googleMapsLoadedKey } from '../lib/gmaps.js';
import { extensionVersion, extensionOutdated } from '../lib/extBridge.js';
import Icon from '../components/Icon.svelte';
+ import ProofTemplateEditor from '../components/ProofTemplateEditor.svelte';
+ import PostTemplateEditor from '../components/PostTemplateEditor.svelte';
+ import ConfirmDialog from '../components/ConfirmDialog.svelte';
// Imagery and Usage were the same four objects seen from two rooms: the key
// here, the meter it feeds there. One tab, one card per provider.
const TABS = [
{ id: 'preferences', label: 'Preferences', icon: 'sliders' },
{ id: 'imagery', label: 'Imagery', icon: 'key' },
+ { id: 'templates', label: 'Templates', icon: 'layers' },
{ id: 'extension', label: 'Capture extension', icon: 'crop' },
{ id: 'about', label: 'About', icon: 'compass' },
];
@@ -208,11 +217,13 @@
// fought by the number parser mid-keystroke; committed on change
let home = $state({ lat: '', lon: '', zoom: '' });
let mention = $state('');
+ let postTarget = $state('x');
let updateOnStart = $state(true); // pop a notice on load when a release is out
// the analyst's logo: app-wide like the API keys, and under the same rule —
// it lives beside settings.json and only ever reaches a case as pixels in a
// rendered proof PNG. `sigBust` re-fetches the <img> after a replace.
let signature = $state(false);
+ let signatureHandle = $state('');
let sigBust = $state(0);
let sigInput = $state(null);
@@ -320,6 +331,7 @@
async function load() {
const s = await api.get('/api/settings');
signature = !!s.signature;
+ signatureHandle = s.signature_handle ?? '';
keys = perProvider((k) => s.api_keys[k.id] ?? '');
usage = s.usage;
month = s.month;
@@ -348,6 +360,7 @@
ingestToken = s.ingest_token ?? '';
home = { lat: String(s.home_view.lat), lon: String(s.home_view.lon), zoom: String(s.home_view.zoom) };
mention = s.post_mention ?? '';
+ postTarget = s.post_target ?? 'x';
updateOnStart = s.update_check_on_start ?? true;
applyPrefs(s); // the rest of the app reads these live
await loadScrapers().catch(() => {}); // local disk read; never blocks Settings
@@ -469,8 +482,77 @@
onMount(() => {
load().catch((e) => toast(`Could not load settings: ${e.message}`, 'danger'));
+ loadTemplates();
+ });
+
+ $effect(() => {
+ if (uiState.tool !== 'settings') return;
+ const target = uiState.settingsTab;
+ if (!target) return;
+ if (TABS.some((t) => t.id === target)) tab = target;
+ uiState.settingsTab = null;
});
+ // ---- reusable templates (proof house style + post thread) ----------------
+ // One editor draft at a time. `editing` = { kind, id|null, name, data }; a
+ // fresh id is null until first save. Content-free presets, workspace-level.
+ let editing = $state(null);
+ let savingTpl = $state(false);
+ let deleteTpl = $state(null); // { kind, id, name } pending confirmation
+
+ function freshTemplate(kind) {
+ return kind === 'proof' ? templateFromProof({}) : templateFromPost({});
+ }
+
+ function newTemplate(kind) {
+ editing = { kind, id: null, name: '', data: freshTemplate(kind) };
+ }
+
+ function editTemplate(kind, rec) {
+ // deep copy so a cancelled edit leaves the stored template untouched. A JSON
+ // round-trip (not structuredClone) because `rec.data` is a Svelte state
+ // proxy and structuredClone throws on a proxy.
+ editing = { kind, id: rec.id, name: rec.name, data: JSON.parse(JSON.stringify(rec.data)) };
+ }
+
+ function cancelEdit() {
+ editing = null;
+ }
+
+ async function saveEditingTemplate() {
+ if (!editing || savingTpl) return;
+ const name = editing.name.trim();
+ if (!name) {
+ toast('Give the template a name', 'warn');
+ return;
+ }
+ savingTpl = true;
+ try {
+ const data = editing.kind === 'proof'
+ ? { ...editing.data, signatureText: textSignatureStyle(editing.data.signatureText) }
+ : editing.data;
+ await saveTemplate(editing.kind, { id: editing.id, name, data });
+ toast('Template saved', 'ok', 1600);
+ editing = null;
+ } catch (e) {
+ toast(`Could not save the template: ${e.message}`, 'danger');
+ } finally {
+ savingTpl = false;
+ }
+ }
+
+ async function confirmDeleteTemplate() {
+ const t = deleteTpl;
+ deleteTpl = null;
+ try {
+ await deleteTemplate(t.kind, t.id);
+ if (editing?.kind === t.kind && editing?.id === t.id) editing = null;
+ toast(`Deleted "${t.name}"`, 'info');
+ } catch (e) {
+ toast(e.message, 'danger');
+ }
+ }
+
// Keys save on change like every other preference here — no Save button to
// forget. The status chip flipping to "Untested" is the receipt, which beats
// a toast: it also says what to do next.
@@ -629,10 +711,42 @@
spellcheck="false"
/>
</div>
+ <div class="row">
+ <div class="row-label">
+ <span>Preferred platform</span>
+ <span class="row-hint">Used for new post drafts.</span>
+ </div>
+ <div class="seg" role="group" aria-label="Preferred platform">
+ {#each Object.values(POST_TARGETS) as option (option.id)}
+ <button
+ class="seg-btn"
+ class:on={postTarget === option.id}
+ onclick={() => {
+ postTarget = option.id;
+ savePrefs({ post_target: option.id });
+ }}
+ >{option.label}</button>
+ {/each}
+ </div>
+ </div>
</section>
<section class="group">
<h3>Signature</h3>
+ <div class="row">
+ <div class="row-label">
+ <span>Your account handle</span>
+ <span class="row-hint">Used when a proof or template enables “Add account handle”; leave empty to hide it.</span>
+ </div>
+ <input
+ class="input mention"
+ bind:value={signatureHandle}
+ onchange={() => savePrefs({ signature_handle: signatureHandle })}
+ placeholder="@my_handle"
+ maxlength="64"
+ spellcheck="false"
+ />
+ </div>
<div class="row">
<div class="row-label">
<span>Your logo</span>
@@ -1160,10 +1274,113 @@
</p>
</section>
{/if}
+
+ {#if tab === 'templates'}
+ <section class="group">
+ <h3>Proof templates</h3>
+ <p class="note">
+ A proof's house style — background, margins, text sizes, footer,
+ signature placement and preferred colours. New proofs can start
+ from one. Shared across every case.
+ </p>
+ <div class="tpl-list">
+ {#each templatesState.proof as t (t.id)}
+ <div class="tpl-row">
+ <span class="tpl-name">{t.name}</span>
+ <div class="tpl-actions">
+ <button class="btn btn-sm" onclick={() => editTemplate('proof', t)}>
+ <Icon name="edit" size={13} /> Edit
+ </button>
+ <button class="btn btn-sm" title="Delete"
+ onclick={() => (deleteTpl = { kind: 'proof', id: t.id, name: t.name })}>
+ <Icon name="trash" size={13} />
+ </button>
+ </div>
+ </div>
+ {/each}
+ {#if !templatesState.proof.length}
+ <p class="empty">No proof templates yet.</p>
+ {/if}
+ </div>
+ <button class="btn btn-sm" onclick={() => newTemplate('proof')}>
+ <Icon name="plus" size={13} /> New proof template
+ </button>
+ </section>
+
+ <section class="group">
+ <h3>Post templates</h3>
+ <p class="note">
+ A thread skeleton — the mention, which lines the first tweet keeps,
+ whether a media tweet rides along, and boilerplate extra tweets.
+ </p>
+ <div class="tpl-list">
+ {#each templatesState.post as t (t.id)}
+ <div class="tpl-row">
+ <span class="tpl-name">{t.name}</span>
+ <div class="tpl-actions">
+ <button class="btn btn-sm" onclick={() => editTemplate('post', t)}>
+ <Icon name="edit" size={13} /> Edit
+ </button>
+ <button class="btn btn-sm" title="Delete"
+ onclick={() => (deleteTpl = { kind: 'post', id: t.id, name: t.name })}>
+ <Icon name="trash" size={13} />
+ </button>
+ </div>
+ </div>
+ {/each}
+ {#if !templatesState.post.length}
+ <p class="empty">No post templates yet.</p>
+ {/if}
+ </div>
+ <button class="btn btn-sm" onclick={() => newTemplate('post')}>
+ <Icon name="plus" size={13} /> New post template
+ </button>
+ </section>
+ {/if}
</div>
</div>
</div>
+{#if editing}
+ <div class="tpl-modal-overlay" role="presentation"
+ onclick={(e) => e.target === e.currentTarget && cancelEdit()}>
+ <div class="tpl-modal">
+ <div class="tpl-modal-head">
+ <input class="tpl-title" type="text" placeholder="Template name"
+ maxlength="120" bind:value={editing.name} />
+ <button class="btn btn-ghost btn-sm" onclick={cancelEdit} aria-label="Close">
+ <Icon name="x" size={16} />
+ </button>
+ </div>
+ <div class="tpl-modal-body">
+ {#if editing.kind === 'proof'}
+ <ProofTemplateEditor bind:data={editing.data} />
+ {:else}
+ <PostTemplateEditor bind:data={editing.data} />
+ {/if}
+ </div>
+ <div class="tpl-modal-foot">
+ <button class="btn btn-ghost" onclick={cancelEdit}>Cancel</button>
+ <button class="btn btn-primary" disabled={savingTpl} onclick={saveEditingTemplate}>
+ <Icon name="save" size={14} /> {savingTpl ? 'Saving…' : 'Save template'}
+ </button>
+ </div>
+ </div>
+ </div>
+{/if}
+
+{#if deleteTpl}
+ <ConfirmDialog
+ title="Delete template"
+ message={`Delete "${deleteTpl.name}"?`}
+ detail="This preset is removed for every case. Proofs already made keep their style."
+ confirmLabel="Delete"
+ tone="danger"
+ onconfirm={confirmDeleteTemplate}
+ oncancel={() => (deleteTpl = null)}
+ />
+{/if}
+
<style>
.tool {
height: 100%;
@@ -1674,4 +1891,88 @@
gap: 6px;
line-height: 1.45;
}
+
+ /* --- templates tab ------------------------------------------------------ */
+ .tpl-list {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin-bottom: 12px;
+ }
+ .tpl-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 7px 10px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-2);
+ }
+ .tpl-name {
+ font-size: var(--fs-sm);
+ color: var(--text-1);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .tpl-actions {
+ display: flex;
+ gap: 6px;
+ flex-shrink: 0;
+ }
+ .empty {
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ font-style: italic;
+ }
+
+ .tpl-modal-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 60;
+ background: rgba(0, 0, 0, 0.55);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 24px;
+ }
+ .tpl-modal {
+ width: min(920px, 100%);
+ max-height: 88vh;
+ display: flex;
+ flex-direction: column;
+ background: var(--bg-1);
+ border: 1px solid var(--border);
+ border-radius: var(--r-lg, 12px);
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4);
+ }
+ .tpl-modal-head {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 12px 14px;
+ border-bottom: 1px solid var(--border);
+ }
+ .tpl-title {
+ flex: 1;
+ background: var(--bg-2);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--text-1);
+ padding: 7px 10px;
+ font: inherit;
+ font-weight: 600;
+ }
+ .tpl-modal-body {
+ padding: 16px;
+ overflow-y: auto;
+ }
+ .tpl-modal-foot {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+ padding: 12px 14px;
+ border-top: 1px solid var(--border);
+ }
</style>
diff --git a/pyproject.toml b/pyproject.toml
index 7758e03..2eb5388 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -49,6 +49,9 @@ dev = [
"pytest>=8,<10",
"pytest-asyncio>=0.23,<2",
"httpx>=0.27,<1.0",
+ # Starlette 1.3+ uses HTTPX2 for TestClient; keep the old HTTPX runtime
+ # client above because application integrations still import that package.
+ "httpx2>=2,<3",
# Static analysis, run in CI (see .github/workflows/ci.yml). ruff is 0.x and
# ships rule changes between minors, so it's pinned to one minor; mypy to the
# next major. Both bounds are raised deliberately, after the suite is green.
diff --git a/src/azimut/api/drafts.py b/src/azimut/api/drafts.py
index f6c1836..f6a9d01 100644
--- a/src/azimut/api/drafts.py
+++ b/src/azimut/api/drafts.py
@@ -12,6 +12,7 @@ from __future__ import annotations
import json
import re
from datetime import datetime, timezone
+from pathlib import PurePosixPath, PureWindowsPath
from typing import Any
from fastapi import APIRouter, HTTPException
@@ -24,6 +25,10 @@ from .cases import delete_by_path, get_case
router = APIRouter(prefix="/api", tags=["drafts"])
DRAFT_MARKER = 1
+MAX_MEDIA_PER_POST = 4
+MAX_EXTRA_POSTS = 20
+MAX_DRAFT_ATTACHMENTS = 1 + MAX_MEDIA_PER_POST * (1 + MAX_EXTRA_POSTS)
+MAX_ARTIFACT_PATH_LENGTH = 512
class DraftIn(BaseModel):
@@ -41,6 +46,74 @@ def _now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+def _artifact_path(value: Any, field: str) -> str | None:
+ if value is None:
+ return None
+ if not isinstance(value, str) or not value or len(value) > MAX_ARTIFACT_PATH_LENGTH:
+ raise HTTPException(status_code=422, detail=f"{field} must be a bounded path string")
+ if (
+ "\\" in value
+ or "\x00" in value
+ or PurePosixPath(value).is_absolute()
+ or PureWindowsPath(value).is_absolute()
+ or bool(PureWindowsPath(value).drive)
+ or value == "."
+ or ".." in PurePosixPath(value).parts
+ ):
+ raise HTTPException(status_code=422, detail=f"{field} must be case-relative")
+ return value
+
+
+def _media_paths(state: dict[str, Any], field: str) -> list[str]:
+ current = state.get("mediaPaths")
+ if current is None:
+ current = [] if state.get("mediaPath") is None else [state.get("mediaPath")]
+ if not isinstance(current, list):
+ raise HTTPException(status_code=422, detail=f"{field}.mediaPaths must be an array")
+ if len(current) > MAX_MEDIA_PER_POST:
+ raise HTTPException(
+ status_code=422,
+ detail=f"{field}.mediaPaths allows at most {MAX_MEDIA_PER_POST} paths",
+ )
+ paths = []
+ for index, value in enumerate(current):
+ path = _artifact_path(value, f"{field}.mediaPaths[{index}]")
+ if path is None:
+ raise HTTPException(
+ status_code=422, detail=f"{field}.mediaPaths[{index}] must be a path string"
+ )
+ paths.append(path)
+ return paths
+
+
+def _draft_source_paths(state: dict[str, Any]) -> list[str]:
+ paths = []
+ proof = _artifact_path(state.get("proofPng"), "state.proofPng")
+ if proof:
+ paths.append(proof)
+ paths.extend(_media_paths(state, "state"))
+
+ extra = state.get("extraTweets", [])
+ if not isinstance(extra, list):
+ raise HTTPException(status_code=422, detail="state.extraTweets must be an array")
+ if len(extra) > MAX_EXTRA_POSTS:
+ raise HTTPException(
+ status_code=422,
+ detail=f"state.extraTweets allows at most {MAX_EXTRA_POSTS} posts",
+ )
+ for index, tweet in enumerate(extra):
+ if not isinstance(tweet, dict):
+ raise HTTPException(
+ status_code=422, detail=f"state.extraTweets[{index}] must be an object"
+ )
+ paths.extend(_media_paths(tweet, f"state.extraTweets[{index}]"))
+
+ unique = list(dict.fromkeys(paths))
+ if len(unique) > MAX_DRAFT_ATTACHMENTS:
+ raise HTTPException(status_code=422, detail="draft has too many attachment paths")
+ return unique
+
+
@router.get("/cases/{case_id}/drafts")
def list_drafts(case_id: str) -> list[dict[str, Any]]:
case = get_case(case_id)
@@ -81,6 +154,7 @@ def save_draft(case_id: str, body: DraftIn) -> dict[str, Any]:
case = get_case(case_id)
name = _slug(body.name or body.title)
exports_dir = case.subdir("exports")
+ source_paths = _draft_source_paths(body.state)
path = exports_dir / f"{name}.json"
existing_created = None
@@ -121,7 +195,7 @@ def save_draft(case_id: str, body: DraftIn) -> dict[str, Any]:
case,
entity_id,
link_engine.DERIVED_FROM,
- [p for p in (body.state.get("proofPng"), body.state.get("mediaPath")) if p],
+ source_paths,
by="post-composer",
)
diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.py
index 532eed9..7f60ecd 100644
--- a/src/azimut/api/settings.py
+++ b/src/azimut/api/settings.py
@@ -33,6 +33,8 @@ ECO_TUNABLE = ("mapbox", "google", "sentinelhub")
DEFAULT_HOME_VIEW = config.DEFAULT_SETTINGS["home_view"]
DEFAULT_POST_MENTION = config.DEFAULT_SETTINGS["post_mention"]
+DEFAULT_POST_TARGET = config.DEFAULT_SETTINGS["post_target"]
+DEFAULT_SIGNATURE_HANDLE = config.DEFAULT_SETTINGS["signature_handle"]
class KeysIn(BaseModel):
@@ -74,6 +76,8 @@ class PrefsIn(BaseModel):
units: str | None = None # one of config.UNIT_SYSTEMS
home_view: HomeView | None = None # where the Satellite tab opens
post_mention: str | None = None # handle a new post draft is addressed to
+ post_target: str | None = None # social composer a new post draft starts with
+ signature_handle: str | None = None # account handle stamped on opted-in proofs
# app self-update pop-up (engine/updates.py) — check on load, and the tag
# the user muted with "don't show again"
update_check_on_start: bool | None = None
@@ -94,6 +98,8 @@ def _prefs(settings: dict[str, Any]) -> dict[str, Any]:
"units": settings.get("units", "metric"),
"home_view": settings.get("home_view", DEFAULT_HOME_VIEW),
"post_mention": settings.get("post_mention", DEFAULT_POST_MENTION),
+ "post_target": settings.get("post_target", DEFAULT_POST_TARGET),
+ "signature_handle": settings.get("signature_handle", DEFAULT_SIGNATURE_HANDLE),
"update_check_on_start": bool(settings.get("update_check_on_start", True)),
"update_dismissed_version": settings.get("update_dismissed_version", ""),
}
@@ -149,6 +155,8 @@ def put_prefs(body: PrefsIn) -> dict[str, Any]:
raise HTTPException(status_code=422, detail=f"unknown coord_format '{body.coord_format}'")
if body.units is not None and body.units not in config.UNIT_SYSTEMS:
raise HTTPException(status_code=422, detail=f"unknown units '{body.units}'")
+ if body.post_target is not None and body.post_target not in config.POST_TARGETS:
+ raise HTTPException(status_code=422, detail=f"unknown post_target '{body.post_target}'")
settings = config.update_settings(lambda s: _apply_prefs(s, body))
return _prefs(settings)
@@ -196,6 +204,10 @@ def _apply_prefs(settings: dict[str, Any], body: PrefsIn) -> None:
settings["home_view"] = body.home_view.model_dump()
if body.post_mention is not None:
settings["post_mention"] = body.post_mention.strip()[:64]
+ if body.post_target is not None:
+ settings["post_target"] = body.post_target
+ if body.signature_handle is not None:
+ settings["signature_handle"] = body.signature_handle.strip()[:64]
if body.update_check_on_start is not None:
settings["update_check_on_start"] = bool(body.update_check_on_start)
if body.update_dismissed_version is not None:
diff --git a/src/azimut/api/templates.py b/src/azimut/api/templates.py
new file mode 100644
index 0000000..14b9c12
--- /dev/null
+++ b/src/azimut/api/templates.py
@@ -0,0 +1,270 @@
+"""REST API for reusable presets: proof house styles and post-thread skeletons.
+
+Templates are app-wide (workspace-level), like the signature and API keys — a
+house style spans every case, so it never lives inside a case folder. Two
+families, keyed by ``kind``: "proof" (a proof's layout/colors/signature)
+and "post" (a thread skeleton: which lines, mention, media, extra tweets). The
+``data`` is validated here and again in the composers so persisted templates
+cannot drive the renderer with malformed or unbounded values.
+"""
+
+from __future__ import annotations
+
+import json
+import secrets
+from datetime import datetime, timezone
+from typing import Annotated, Any, Literal
+
+from fastapi import APIRouter, HTTPException
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ FiniteFloat,
+ StrictBool,
+ ValidationError,
+ field_validator,
+ model_validator,
+)
+
+from .. import config
+
+router = APIRouter(prefix="/api", tags=["templates"])
+
+# Guard rails for a local, single-user store: enough headroom for real use,
+# low enough that a runaway client can't bloat the workspace file unbounded.
+MAX_PER_KIND = 50
+MAX_DATA_BYTES = 64 * 1024
+MAX_POST_TWEETS = 20
+
+Color = Annotated[str, Field(pattern=r"^#[0-9a-fA-F]{6}$")]
+SpacingNumber = Annotated[FiniteFloat, Field(ge=0, le=200)]
+TextSize = Annotated[FiniteFloat, Field(ge=8, le=80)]
+Offset = Annotated[FiniteFloat, Field(ge=-100_000, le=100_000)]
+Ratio = Annotated[FiniteFloat, Field(ge=0, le=1)]
+
+DEFAULT_POST_BODY = (
+ "#place - #pluscode\n\n#description\n\n#coordinates\n\n#mention\n\nSource: #source"
+)
+
+
+class CanonicalModel(BaseModel):
+ model_config = ConfigDict(extra="ignore")
+
+
+class ProofSpace(CanonicalModel):
+ pad: SpacingNumber = 20
+ gap: SpacingNumber = 16
+ rowGap: SpacingNumber = 18
+
+
+class ProofSignature(CanonicalModel):
+ anchor: Literal["tl", "tr", "bl", "br"] = "br"
+ dx: Offset = 0
+ dy: Offset = 0
+ scale: Annotated[FiniteFloat, Field(ge=0.03, le=0.6)] = 0.08
+ opacity: Ratio = 0.9
+ xRatio: Ratio | None = None
+ yRatio: Ratio | None = None
+
+
+class ProofSignatureText(CanonicalModel):
+ anchor: Literal["tl", "tr", "bl", "br"] = "br"
+ dx: Offset = 0
+ dy: Offset = 0
+ size: Annotated[FiniteFloat, Field(ge=12, le=300)] = 28
+ color: Color = "#ffffff"
+ opacity: Ratio = 1
+ xRatio: Ratio | None = None
+ yRatio: Ratio | None = None
+
+ @field_validator("color")
+ @classmethod
+ def normalize_color(cls, color: str) -> str:
+ return color.lower()
+
+
+class ProofTemplateData(CanonicalModel):
+ bg: Color = "#0d1117"
+ space: ProofSpace = Field(default_factory=ProofSpace)
+ layout: Literal["grid", "free"] = "grid"
+ captionSize: TextSize = 20
+ legendSize: TextSize = 20
+ footerSize: TextSize = 15
+ footer: str = Field(default="", max_length=200)
+ footerEnabled: StrictBool = True
+ footerColor: Color | None = None
+ footerAlign: Literal["left", "right"] = "left"
+ captionsEnabled: StrictBool = True
+ panelDirection: Literal["horizontal", "vertical"] = "horizontal"
+ signature: ProofSignature | None = None
+ signatureText: ProofSignatureText | None = None
+ palette: list[Color] = Field(
+ default_factory=lambda: [
+ "#ff5252",
+ "#40c4ff",
+ "#ffd740",
+ "#69f0ae",
+ "#e040fb",
+ "#ff9e40",
+ "#ffffff",
+ ],
+ min_length=1,
+ max_length=7,
+ )
+
+ @field_validator("bg", "footerColor")
+ @classmethod
+ def normalize_color(cls, color: str | None) -> str | None:
+ return color.lower() if color is not None else None
+
+ @field_validator("palette")
+ @classmethod
+ def normalize_palette(cls, colors: list[str]) -> list[str]:
+ normalized = [color.lower() for color in colors]
+ if len(set(normalized)) != len(normalized):
+ raise ValueError("palette colors must be unique")
+ return normalized
+
+
+class PostExtraTweet(CanonicalModel):
+ text: str = Field(default="", max_length=4_000)
+
+
+class PostTemplateData(CanonicalModel):
+ mention: str = Field(default="@GeoConfirmed", max_length=120)
+ body: str = Field(default=DEFAULT_POST_BODY, min_length=1, max_length=16_000)
+ mediaEnabled: StrictBool = True
+ extraTweets: list[PostExtraTweet] = Field(default_factory=list, max_length=MAX_POST_TWEETS)
+
+ @model_validator(mode="before")
+ @classmethod
+ def migrate_legacy_toggles(cls, value: Any) -> Any:
+ if not isinstance(value, dict) or value.get("body"):
+ return value
+ toggles = value.get("toggles")
+ if not isinstance(toggles, dict):
+ return value
+ parts = []
+ if toggles.get("showHeader"):
+ parts.append("#place - #pluscode")
+ if toggles.get("showDescription"):
+ parts.append("#description")
+ if toggles.get("showCoords"):
+ parts.append("#coordinates")
+ if toggles.get("showMention"):
+ parts.append("#mention")
+ if toggles.get("showSource"):
+ parts.append("Source: #source")
+ migrated = dict(value)
+ migrated["body"] = "\n\n".join(parts) or DEFAULT_POST_BODY
+ return migrated
+
+ @field_validator("body")
+ @classmethod
+ def normalize_body(cls, body: str) -> str:
+ return body if body.strip() else DEFAULT_POST_BODY
+
+
+class TemplateIn(BaseModel):
+ # None → create a new preset; an existing id → update it in place
+ id: str | None = Field(default=None, max_length=64, pattern=r"^[A-Za-z0-9_-]+$")
+ name: str = Field(min_length=1, max_length=120)
+ data: dict[str, Any]
+
+ @field_validator("name", mode="before")
+ @classmethod
+ def strip_name(cls, value: Any) -> Any:
+ return value.strip() if isinstance(value, str) else value
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _require_kind(kind: str) -> None:
+ if kind not in config.TEMPLATE_KINDS:
+ raise HTTPException(status_code=404, detail=f"unknown template kind '{kind}'")
+
+
+def _canonical_data(kind: str, data: dict[str, Any]) -> dict[str, Any]:
+ model = ProofTemplateData if kind == "proof" else PostTemplateData
+ try:
+ return model.model_validate(data).model_dump(mode="json")
+ except ValidationError as exc:
+ raise HTTPException(status_code=422, detail=exc.errors(include_input=False)) from exc
+
+
+def _data_size(data: dict[str, Any]) -> int:
+ try:
+ return len(json.dumps(data, allow_nan=False).encode("utf-8"))
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail="template data must be valid JSON") from exc
+
+
[email protected]("/templates")
+def list_templates() -> dict[str, Any]:
+ templates = config.load_templates()
+ for kind in config.TEMPLATE_KINDS:
+ valid = []
+ for item in templates[kind]:
+ try:
+ canonical = _canonical_data(kind, item["data"])
+ except HTTPException:
+ continue
+ valid.append({**item, "data": canonical})
+ templates[kind] = valid
+ return templates
+
+
[email protected]("/templates/{kind}")
+def save_template(kind: str, body: TemplateIn) -> dict[str, Any]:
+ _require_kind(kind)
+ if _data_size(body.data) > MAX_DATA_BYTES:
+ raise HTTPException(status_code=413, detail="template data too large")
+ data = _canonical_data(kind, body.data)
+ if _data_size(data) > MAX_DATA_BYTES:
+ raise HTTPException(status_code=413, detail="template data too large")
+
+ record: dict[str, Any] = {}
+
+ def apply(templates: dict[str, Any]) -> None:
+ nonlocal record
+ items = templates.setdefault(kind, [])
+ if body.id:
+ for item in items:
+ if item.get("id") == body.id:
+ item["name"] = body.name
+ item["data"] = data
+ item["updated_at"] = _now()
+ record = item
+ return
+ raise HTTPException(status_code=404, detail="template not found")
+ if len(items) >= MAX_PER_KIND:
+ raise HTTPException(status_code=409, detail="too many templates")
+ record = {
+ "id": secrets.token_hex(8),
+ "name": body.name,
+ "data": data,
+ "updated_at": _now(),
+ }
+ items.append(record)
+
+ config.update_templates(apply)
+ return record
+
+
[email protected]("/templates/{kind}/{template_id}")
+def delete_template(kind: str, template_id: str) -> dict[str, Any]:
+ _require_kind(kind)
+ removed = False
+
+ def apply(templates: dict[str, Any]) -> None:
+ nonlocal removed
+ items = templates.get(kind, [])
+ kept = [item for item in items if item.get("id") != template_id]
+ removed = len(kept) != len(items)
+ templates[kind] = kept
+
+ config.update_templates(apply)
+ return {"deleted": removed}
diff --git a/src/azimut/config.py b/src/azimut/config.py
index 561de2a..5447fe2 100644
--- a/src/azimut/config.py
+++ b/src/azimut/config.py
@@ -8,7 +8,8 @@ overridable with the ``AZIMUT_HOME`` environment variable):
├── scratch/ # one-shot sessions (promotable to cases)
├── runtime/ # newer scrapers fetched at runtime (engine/scrapers.py)
├── signature.png # optional analyst logo, stamped onto proofs
- └── settings.json
+ ├── settings.json
+ └── templates.json # reusable proof and post styles
No database server — plain files only (spec §4).
"""
@@ -17,12 +18,17 @@ from __future__ import annotations
import copy
import json
+import logging
import os
+import re
+import tempfile
import threading
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable
+logger = logging.getLogger(__name__)
+
# On-disk schema for settings.json — the app-wide sibling of case.json's
# CASE_SCHEMA (workspace.py). An older file is migrated up to this on load; a
# newer file is left alone, since update() below preserves keys this Azimut
@@ -85,6 +91,12 @@ DEFAULT_SETTINGS: dict[str, Any] = {
"home_view": {"lat": 48.8584, "lon": 2.2945, "zoom": 16},
# The handle a new post draft is addressed to. Empty means no mention.
"post_mention": "@GeoConfirmed",
+ # The social composer a new post draft starts with. A saved draft keeps its
+ # own target so a later preference change never rewrites it.
+ "post_target": "x",
+ # The handle stamped onto proofs when a proof/template enables it. Empty
+ # means no account-handle slot can render.
+ "signature_handle": "",
# Pairing token for the capture browser extension (api/ingest.py). Minted
# lazily on first use, shown once in Settings, pasted into the extension.
# Empty means "not minted yet" — never a valid credential.
@@ -104,6 +116,7 @@ DEFAULT_SETTINGS: dict[str, Any] = {
# frontend/src/lib/coords.js and frontend/src/lib/measure.js.
COORD_FORMATS = ("dd", "dms", "mgrs")
UNIT_SYSTEMS = ("metric", "imperial")
+POST_TARGETS = ("x", "bluesky", "mastodon")
# Documented monthly free allowances per meter, in billed requests (verified
# 2026-07: Google 2D Map Tiles 100k then $0.60/1k, and ≤15k/day; Mapbox Static
@@ -166,6 +179,16 @@ def signature_path() -> Path:
return workspace_root() / "signature.png"
+def templates_path() -> Path:
+ """Reusable proof-style and post-thread presets, app-wide.
+
+ A "house style" spans every case, so it lives beside settings.json rather
+ than inside a case — same rule as the signature. Kept out of settings.json
+ itself so the secrets file stays small and single-purpose.
+ """
+ return workspace_root() / "templates.json"
+
+
# Refuse anything larger as a signature: a logo is a small badge on a composite,
# and the file is read into memory to be validated and served.
SIGNATURE_MAX_BYTES = 2 * 1024 * 1024
@@ -274,6 +297,93 @@ def update_settings(mutate: Callable[[dict[str, Any]], None]) -> dict[str, Any]:
return settings
+# Reusable presets file (templates.json). The two families a template can be:
+# "proof" (a proof's house style) and "post" (a thread skeleton).
+TEMPLATE_KINDS = ("proof", "post")
+DEFAULT_TEMPLATES: dict[str, Any] = {"schema": 1, "proof": [], "post": []}
+_templates_lock = threading.Lock()
+
+
+def load_templates() -> dict[str, Any]:
+ try:
+ data = json.loads(
+ templates_path().read_text(encoding="utf-8"),
+ parse_constant=lambda value: (_ for _ in ()).throw(
+ ValueError(f"invalid JSON constant: {value}")
+ ),
+ )
+ except FileNotFoundError:
+ return copy.deepcopy(DEFAULT_TEMPLATES)
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
+ logger.warning("Ignoring unreadable templates.json: %s", exc)
+ return copy.deepcopy(DEFAULT_TEMPLATES)
+ if not isinstance(data, dict) or data.get("schema", 1) != 1:
+ logger.warning("Ignoring templates.json with an unsupported root or schema")
+ return copy.deepcopy(DEFAULT_TEMPLATES)
+ merged = copy.deepcopy(DEFAULT_TEMPLATES)
+ for kind in TEMPLATE_KINDS:
+ value = data.get(kind)
+ if not isinstance(value, list):
+ continue
+ seen: set[str] = set()
+ for item in value:
+ if not isinstance(item, dict):
+ continue
+ template_id = item.get("id")
+ name = item.get("name")
+ template_data = item.get("data")
+ updated_at = item.get("updated_at")
+ if (
+ not isinstance(template_id, str)
+ or not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", template_id)
+ or template_id in seen
+ or not isinstance(name, str)
+ or not name.strip()
+ or len(name.strip()) > 120
+ or not isinstance(template_data, dict)
+ or (updated_at is not None and not isinstance(updated_at, str))
+ or (isinstance(updated_at, str) and len(updated_at) > 64)
+ ):
+ logger.warning("Ignoring malformed %s template record", kind)
+ continue
+ record = {"id": template_id, "name": name.strip(), "data": template_data}
+ if updated_at is not None:
+ record["updated_at"] = updated_at
+ merged[kind].append(record)
+ seen.add(template_id)
+ return merged
+
+
+def save_templates(templates: dict[str, Any]) -> None:
+ path = templates_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ _restrict(path.parent, 0o700)
+ payload = json.dumps(
+ templates, indent=2, ensure_ascii=False, allow_nan=False
+ ) + "\n"
+ fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
+ tmp_path = Path(tmp_name)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(payload)
+ handle.flush()
+ os.fsync(handle.fileno())
+ _restrict(tmp_path, 0o600)
+ os.replace(tmp_path, path)
+ _restrict(path, 0o600)
+ finally:
+ tmp_path.unlink(missing_ok=True)
+
+
+def update_templates(mutate: Callable[[dict[str, Any]], None]) -> dict[str, Any]:
+ """Load → mutate → save templates.json under a writer lock."""
+ with _templates_lock:
+ templates = load_templates()
+ mutate(templates)
+ save_templates(templates)
+ return templates
+
+
def record_usage(meter: str, count: int = 1, when: datetime | None = None) -> int:
"""Bump a provider's tile counter for the month; returns the new total.
diff --git a/src/azimut/engine/links.py b/src/azimut/engine/links.py
index 2bb0bf1..e3564a8 100644
--- a/src/azimut/engine/links.py
+++ b/src/azimut/engine/links.py
@@ -97,8 +97,7 @@ def sync(
"""
found, missing = resolve(case, rel_paths)
case.sync_links(entity_id, type_, found, by=by)
- for path in missing:
- add_tombstone(case, entity_id, {"path": path})
+ add_tombstones(case, entity_id, [{"path": path} for path in missing])
def link_all(
@@ -114,8 +113,7 @@ def link_all(
for to_id in found:
if to_id != entity_id:
case.add_link(entity_id, to_id, type_, by=by, unique=True)
- for path in missing:
- add_tombstone(case, entity_id, {"path": path})
+ add_tombstones(case, entity_id, [{"path": path} for path in missing])
def tombstone_of(entity: dict[str, Any]) -> dict[str, Any]:
@@ -142,12 +140,26 @@ def add_tombstone(case: Case, entity_id: str, info: dict[str, Any]) -> None:
Keyed by path, so re-saving or a second delete never stacks duplicates.
"""
+ add_tombstones(case, entity_id, [info])
+
+
+def add_tombstones(case: Case, entity_id: str, infos: list[dict[str, Any]]) -> None:
+ """Record several lost sources with one case read and at most one write."""
+ if not infos:
+ return
entity = _entity(case, entity_id)
lost = list(entity.get("attrs", {}).get(LOST, []))
- if any(t.get("path") == info.get("path") for t in lost):
- return
- lost.append({**info, "at": info.get("at") or _now()})
- case.update_entity(entity_id, {"attrs": {LOST: lost}})
+ paths = {item.get("path") for item in lost}
+ changed = False
+ for info in infos:
+ path = info.get("path")
+ if path in paths:
+ continue
+ lost.append({**info, "at": info.get("at") or _now()})
+ paths.add(path)
+ changed = True
+ if changed:
+ case.update_entity(entity_id, {"attrs": {LOST: lost}})
def losses(case: Case, doomed_ids: set[str]) -> dict[str, list[dict[str, Any]]]:
diff --git a/src/azimut/server.py b/src/azimut/server.py
index 8038f88..b7f632f 100644
--- a/src/azimut/server.py
+++ b/src/azimut/server.py
@@ -79,7 +79,7 @@ def create_app() -> FastAPI:
app = FastAPI(title="Azimut", version=__version__, docs_url="/api/docs")
- from .api import cases, drafts, events, files, ingest, inspect, media, proofs, satellite, settings
+ from .api import cases, drafts, events, files, ingest, inspect, media, proofs, satellite, settings, templates
app.include_router(cases.router)
app.include_router(media.router)
@@ -91,6 +91,7 @@ def create_app() -> FastAPI:
app.include_router(settings.router)
app.include_router(ingest.router)
app.include_router(events.router)
+ app.include_router(templates.router)
# extension-origin CORS, /api/ingest/* only (see ingest.install_cors)
ingest.install_cors(app)
# last, so it wraps everything: refuse non-loopback Host / cross-origin web
diff --git a/tests/test_config.py b/tests/test_config.py
index f115b06..94d56f9 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -2,6 +2,8 @@
import json
+import pytest
+
from azimut import config
@@ -50,3 +52,54 @@ def test_load_settings_missing_file_returns_defaults(monkeypatch, tmp_path):
loaded = config.load_settings()
assert loaded == config.DEFAULT_SETTINGS
assert loaded is not config.DEFAULT_SETTINGS
+
+
+ "content",
+ ["[]", "{", '{"schema": 2, "proof": [], "post": []}', '{"schema": 1, "proof": [42], "post": []}'],
+)
+def test_load_templates_recovers_from_malformed_stores(monkeypatch, tmp_path, content):
+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
+ config.templates_path().write_text(content, encoding="utf-8")
+ assert config.load_templates() == config.DEFAULT_TEMPLATES
+
+
+def test_load_templates_filters_bad_records_and_duplicate_ids(monkeypatch, tmp_path):
+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
+ config.templates_path().write_text(
+ json.dumps(
+ {
+ "schema": 1,
+ "proof": [
+ {"id": "kept", "name": " First ", "data": {"bg": "#ffffff"}},
+ {"id": "kept", "name": "Duplicate", "data": {}},
+ {"id": "bad id", "name": "Bad", "data": {}},
+ {"id": "scalar", "name": "Bad", "data": 3},
+ ],
+ "post": [None, {"id": "post", "name": " Post ", "data": {}}],
+ }
+ ),
+ encoding="utf-8",
+ )
+ loaded = config.load_templates()
+ assert loaded["proof"] == [{"id": "kept", "name": "First", "data": {"bg": "#ffffff"}}]
+ assert loaded["post"] == [{"id": "post", "name": "Post", "data": {}}]
+
+
+def test_save_templates_is_atomic_when_replace_fails(monkeypatch, tmp_path):
+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))
+ original = {"schema": 1, "proof": [], "post": []}
+ config.save_templates(original)
+ before = config.templates_path().read_bytes()
+
+ def fail_replace(_source, _target):
+ raise OSError("replace failed")
+
+ monkeypatch.setattr(config.os, "replace", fail_replace)
+ with pytest.raises(OSError, match="replace failed"):
+ config.save_templates(
+ {"schema": 1, "proof": [{"id": "x", "name": "X", "data": {}}], "post": []}
+ )
+
+ assert config.templates_path().read_bytes() == before
+ assert list(tmp_path.glob(".templates.json.*.tmp")) == []
diff --git a/tests/test_drafts_api.py b/tests/test_drafts_api.py
index 69cfcdc..243d683 100644
--- a/tests/test_drafts_api.py
+++ b/tests/test_drafts_api.py
@@ -1,11 +1,14 @@
"""Post drafts: save state, list, reload, entity upsert, delete."""
+import pytest
+
STATE = {
"description": "A formation of 13 helicopters was spotted heading East",
"coordsText": "10.303315, -66.874095",
"place": "Los Anacuos, Miranda, Venezuela",
"mention": "@GeoConfirmed",
"source": "https://instagram.com/urreiztieta_ne",
+ "target": "bluesky",
"tweet1": "Los Anacuos, Miranda, Venezuela - 843G+89C",
"mediaEnabled": True,
"mediaType": "video",
@@ -32,6 +35,7 @@ def test_save_load_roundtrip(client):
draft = client.get(f"/api/cases/{cid}/drafts/helicopter-formation").json()
assert draft["title"] == "Helicopter formation"
assert draft["state"]["place"] == "Los Anacuos, Miranda, Venezuela"
+ assert draft["state"]["target"] == "bluesky"
assert draft["state"]["extraTweets"][0]["text"] == "More context here"
@@ -81,3 +85,45 @@ def test_delete_removes_file_and_entity(client):
def test_load_missing_draft_is_404(client):
cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]
assert client.get(f"/api/cases/{cid}/drafts/nope").status_code == 404
+
+
+def test_draft_rejects_malformed_extra_posts_before_writing(client):
+ cid = client.post("/api/cases", json={"name": "Draft bounds"}).json()["id"]
+ response = client.post(
+ f"/api/cases/{cid}/drafts",
+ json={"title": "Bad", "state": {"extraTweets": {"text": "not an array"}}},
+ )
+ assert response.status_code == 422
+ assert client.get(f"/api/cases/{cid}/drafts").json() == []
+
+
+def test_draft_rejects_attachment_fan_out(client):
+ cid = client.post("/api/cases", json={"name": "Draft bounds"}).json()["id"]
+ too_many_media = client.post(
+ f"/api/cases/{cid}/drafts",
+ json={
+ "title": "Media",
+ "state": {"mediaPaths": [f"media/{index}.png" for index in range(5)]},
+ },
+ )
+ too_many_posts = client.post(
+ f"/api/cases/{cid}/drafts",
+ json={
+ "title": "Posts",
+ "state": {"extraTweets": [{"mediaPaths": []} for _ in range(21)]},
+ },
+ )
+ assert too_many_media.status_code == 422
+ assert too_many_posts.status_code == 422
+
+
+ "path", [None, ".", "../outside.png", "/absolute.png", "C:\\outside.png", "x" * 513]
+)
+def test_draft_rejects_unsafe_or_unbounded_paths(client, path):
+ cid = client.post("/api/cases", json={"name": "Draft paths"}).json()["id"]
+ response = client.post(
+ f"/api/cases/{cid}/drafts",
+ json={"title": "Bad path", "state": {"mediaPaths": [path]}},
+ )
+ assert response.status_code == 422
diff --git a/tests/test_links_api.py b/tests/test_links_api.py
index 91d2968..25c7f3c 100644
--- a/tests/test_links_api.py
+++ b/tests/test_links_api.py
@@ -11,6 +11,8 @@ import io
from PIL import Image
+from azimut.engine import links as link_engine
+
def _png_bytes(color=(200, 30, 30), size=(64, 48)) -> bytes:
buf = io.BytesIO()
@@ -137,6 +139,27 @@ def test_post_save_links_to_its_proof_and_media(client):
}
+def test_post_save_links_to_every_selected_media_file(client):
+ cid = _new_case(client, "Post media set")
+ a = _upload(client, cid, "a.png", _png_bytes((7, 8, 9)))["item"]["path"]
+ b = _upload(client, cid, "b.png", _png_bytes((3, 4, 5)))["item"]["path"]
+
+ client.post(
+ f"/api/cases/{cid}/drafts",
+ json={
+ "title": "Thread",
+ "state": {
+ "mediaPaths": [a],
+ "extraTweets": [{"text": "", "mediaPaths": [b], "mediaType": "images"}],
+ },
+ },
+ )
+
+ post = _entity(client, cid, draft="exports/thread.json")
+ targets = {lk["to"] for lk in _links(client, cid, "derived-from") if lk["from"] == post["id"]}
+ assert targets == {_entity(client, cid, path=a)["id"], _entity(client, cid, path=b)["id"]}
+
+
def test_session_save_depends_on_its_subject(client):
cid = _new_case(client, "Session links")
a = _upload(client, cid, "a.png")["item"]["path"]
@@ -224,6 +247,32 @@ def test_a_source_deleted_before_the_save_leaves_a_tombstone(client):
]
+def test_missing_sources_are_tombstoned_in_one_case_update():
+ class FakeCase:
+ def __init__(self):
+ self.read_count = 0
+ self.updates = []
+
+ def read(self):
+ self.read_count += 1
+ return {"entities": [{"id": "post", "attrs": {}}]}
+
+ def update_entity(self, entity_id, changes):
+ self.updates.append((entity_id, changes))
+
+ case = FakeCase()
+ link_engine.add_tombstones(
+ case,
+ "post",
+ [{"path": "media/a.png"}, {"path": "media/b.png"}, {"path": "media/a.png"}],
+ )
+
+ assert case.read_count == 1
+ assert len(case.updates) == 1
+ lost = case.updates[0][1]["attrs"][link_engine.LOST]
+ assert [item["path"] for item in lost] == ["media/a.png", "media/b.png"]
+
+
# ── delete: what goes, what stays ──────────────────────────────────────────
diff --git a/tests/test_settings_api.py b/tests/test_settings_api.py
index c6e391d..bacd012 100644
--- a/tests/test_settings_api.py
+++ b/tests/test_settings_api.py
@@ -191,6 +191,7 @@ def test_get_settings_exposes_prefs_and_free_tier(client):
assert body["eco_zoom_fallback"] is True
assert body["providers_enabled"] == {}
assert body["usage_overrides"] == {}
+ assert body["signature_handle"] == ""
# startup update pop-up: on by default, nothing muted yet
assert body["update_check_on_start"] is True
assert body["update_dismissed_version"] == ""
@@ -209,6 +210,12 @@ def test_put_prefs_roundtrips_update_popup_prefs(client):
assert saved["update_dismissed_version"] == "v0.2.0"
+def test_put_prefs_roundtrips_signature_handle(client):
+ saved = client.put("/api/settings/prefs", json={"signature_handle": " @example "}).json()
+ assert saved["signature_handle"] == "@example"
+ assert client.get("/api/settings").json()["signature_handle"] == "@example"
+
+
def test_put_prefs_roundtrips_and_filters_unknown_providers(client):
saved = client.put(
"/api/settings/prefs",
@@ -657,18 +664,25 @@ def test_display_prefs_default_and_round_trip(client):
body = client.get("/api/settings").json()
assert body["coord_format"] == "dd"
assert body["units"] == "metric"
+ assert body["post_target"] == "x"
- saved = client.put("/api/settings/prefs", json={"coord_format": "mgrs", "units": "imperial"})
+ saved = client.put(
+ "/api/settings/prefs",
+ json={"coord_format": "mgrs", "units": "imperial", "post_target": "bluesky"},
+ )
assert saved.json()["coord_format"] == "mgrs"
assert saved.json()["units"] == "imperial"
+ assert saved.json()["post_target"] == "bluesky"
reloaded = client.get("/api/settings").json()
assert reloaded["coord_format"] == "mgrs"
assert reloaded["units"] == "imperial"
+ assert reloaded["post_target"] == "bluesky"
def test_display_prefs_reject_unknown_values(client):
assert client.put("/api/settings/prefs", json={"coord_format": "utm"}).status_code == 422
assert client.put("/api/settings/prefs", json={"units": "furlongs"}).status_code == 422
+ assert client.put("/api/settings/prefs", json={"post_target": "threads"}).status_code == 422
# a rejected value leaves the stored preference alone
assert client.get("/api/settings").json()["coord_format"] == "dd"
diff --git a/tests/test_templates_api.py b/tests/test_templates_api.py
new file mode 100644
index 0000000..f42dd4c
--- /dev/null
+++ b/tests/test_templates_api.py
@@ -0,0 +1,180 @@
+"""Templates API: workspace-level proof/post presets, CRUD + guard rails."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from azimut import config
+
+
+def test_list_empty_by_default(client):
+ r = client.get("/api/templates")
+ assert r.status_code == 200
+ body = r.json()
+ assert body["proof"] == []
+ assert body["post"] == []
+
+
+def test_create_edit_delete_proof_template(client):
+ created = client.post(
+ "/api/templates/proof",
+ json={"name": "House dark", "data": {"bg": "#0d1117", "footer": "By me"}},
+ )
+ assert created.status_code == 200
+ rec = created.json()
+ assert rec["id"]
+ assert rec["name"] == "House dark"
+ assert rec["data"]["footer"] == "By me"
+
+ # it shows up in the list
+ listed = client.get("/api/templates").json()["proof"]
+ assert [t["id"] for t in listed] == [rec["id"]]
+
+ # editing in place keeps the id, updates fields
+ edited = client.post(
+ "/api/templates/proof",
+ json={"id": rec["id"], "name": "House light", "data": {"bg": "#ffffff"}},
+ )
+ assert edited.status_code == 200
+ assert edited.json()["id"] == rec["id"]
+ assert edited.json()["name"] == "House light"
+ assert client.get("/api/templates").json()["proof"][0]["data"]["bg"] == "#ffffff"
+
+ # delete
+ gone = client.delete(f"/api/templates/proof/{rec['id']}")
+ assert gone.status_code == 200 and gone.json()["deleted"] is True
+ assert client.get("/api/templates").json()["proof"] == []
+
+
+def test_kinds_are_separate(client):
+ client.post("/api/templates/proof", json={"name": "P", "data": {}})
+ client.post("/api/templates/post", json={"name": "T", "data": {"mediaEnabled": False}})
+ body = client.get("/api/templates").json()
+ assert len(body["proof"]) == 1 and len(body["post"]) == 1
+ assert body["post"][0]["data"]["mediaEnabled"] is False
+
+
+def test_unknown_kind_rejected(client):
+ assert client.post("/api/templates/bogus", json={"name": "x", "data": {}}).status_code == 404
+ assert client.delete("/api/templates/bogus/whatever").status_code == 404
+
+
+def test_edit_missing_id_is_404(client):
+ r = client.post(
+ "/api/templates/proof", json={"id": "deadbeef", "name": "x", "data": {}}
+ )
+ assert r.status_code == 404
+
+
+def test_oversize_data_rejected(client):
+ big = {"blob": "x" * (64 * 1024 + 1)}
+ r = client.post("/api/templates/proof", json={"name": "big", "data": big})
+ assert r.status_code == 413
+
+
+def test_per_kind_cap(client):
+ for i in range(50):
+ assert client.post(
+ "/api/templates/proof", json={"name": f"t{i}", "data": {}}
+ ).status_code == 200
+ overflow = client.post("/api/templates/proof", json={"name": "one too many", "data": {}})
+ assert overflow.status_code == 409
+
+
+def test_delete_missing_returns_false(client):
+ assert client.delete("/api/templates/proof/nope").json()["deleted"] is False
+
+
+def test_templates_live_beside_settings_not_in_a_case(client, monkeypatch):
+ client.post("/api/templates/proof", json={"name": "P", "data": {"footer": "hi"}})
+ # stored in the workspace-level file, not settings.json
+ path = config.templates_path()
+ assert path.exists()
+ stored = json.loads(path.read_text(encoding="utf-8"))
+ assert stored["proof"][0]["name"] == "P"
+ assert "proof" not in config.load_settings()
+
+
+ "data",
+ [
+ {"captionSize": 1e308},
+ {"space": {"gap": -1}},
+ {"space": []},
+ {"layout": "stacked"},
+ {"bg": "red"},
+ {"signature": {"scale": 2}},
+ {"signatureText": {"size": 0}},
+ {"footerEnabled": "false"},
+ ],
+)
+def test_invalid_proof_render_values_are_rejected(client, data):
+ response = client.post("/api/templates/proof", json={"name": "Unsafe", "data": data})
+ assert response.status_code == 422
+
+
[email protected]("constant", ["NaN", "Infinity", "-Infinity"])
+def test_non_finite_json_numbers_are_rejected(client, constant):
+ response = client.post(
+ "/api/templates/proof",
+ content=f'{{"name":"Unsafe","data":{{"captionSize":{constant}}}}}',
+ headers={"content-type": "application/json"},
+ )
+ assert response.status_code == 422
+
+
+def test_template_data_is_canonical_and_content_free(client):
+ response = client.post(
+ "/api/templates/proof",
+ json={
+ "name": "Canonical",
+ "data": {"bg": "#AABBCC", "panels": [{"src": "media/private.png"}]},
+ },
+ )
+ assert response.status_code == 200
+ data = response.json()["data"]
+ assert data["bg"] == "#aabbcc"
+ assert "panels" not in data
+
+
+def test_post_template_tweet_count_is_bounded(client):
+ response = client.post(
+ "/api/templates/post",
+ json={
+ "name": "Too many",
+ "data": {"extraTweets": [{"text": str(i)} for i in range(21)]},
+ },
+ )
+ assert response.status_code == 422
+
+
+def test_whitespace_only_names_are_rejected_on_create_and_edit(client):
+ created = client.post("/api/templates/proof", json={"name": "Good", "data": {}})
+ assert created.status_code == 200
+ assert client.post(
+ "/api/templates/proof", json={"name": " ", "data": {}}
+ ).status_code == 422
+ assert client.post(
+ "/api/templates/proof",
+ json={"id": created.json()["id"], "name": "\t ", "data": {}},
+ ).status_code == 422
+
+
+def test_invalid_hand_edited_template_is_not_returned(client):
+ config.save_templates(
+ {
+ "schema": 1,
+ "proof": [
+ {
+ "id": "broken",
+ "name": "Broken",
+ "data": {"space": {"gap": -1}},
+ "updated_at": "2026-07-20T00:00:00Z",
+ }
+ ],
+ "post": [],
+ }
+ )
+ assert client.get("/api/templates").json()["proof"] == []
diff --git a/uv.lock b/uv.lock
index e50cfb3..5cfc5d4 100644
--- a/uv.lock
+++ b/uv.lock
@@ -101,6 +101,7 @@ dependencies = [
[package.optional-dependencies]
dev = [
{ name = "httpx" },
+ { name = "httpx2" },
{ name = "mypy" },
{ name = "pytest" },
{ name = "pytest-asyncio" },
@@ -113,6 +114,7 @@ requires-dist = [
{ name = "gallery-dl", specifier = ">=1.27" },
{ name = "httpx", specifier = ">=0.27,<1.0" },
{ name = "httpx", marker = "extra == 'dev'", specifier = ">=0.27,<1.0" },
+ { name = "httpx2", marker = "extra == 'dev'", specifier = ">=2,<3" },
{ name = "mypy", marker = "extra == 'dev'", specifier = ">=2.3,<3" },
{ name = "numpy", specifier = ">=1.26,<3" },
{ name = "opencv-python-headless", specifier = ">=4.9,<5" },
@@ -282,6 +284,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" },
]
+[[package]]
+name = "httpcore2"
+version = "2.7.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "h11" },
+ { name = "truststore" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/d5/fe/6a3f9f1a8bb8733326140737446aaf72fddb8b54b8f202302f5c84960613/httpcore2-2.7.0.tar.gz", hash = "sha256:6dc0fedf329a52a990930a5579edfebaea81118ea700ea0dd7de2b5e5be49efc", size = 65593, upload-time = "2026-07-14T20:40:01.111Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6f/6c/62e2e279e63fc4f7a5ee841ef13175a8bbc613f258e9dcc186e9de803a42/httpcore2-2.7.0-py3-none-any.whl", hash = "sha256:1452f589fe23f55b44546cd884294c41a29330af902bc0b71a761fd52d18f92b", size = 81506, upload-time = "2026-07-14T20:39:58.053Z" },
+]
+
[[package]]
name = "httptools"
version = "0.8.0"
@@ -340,6 +355,22 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" },
]
+[[package]]
+name = "httpx2"
+version = "2.7.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio" },
+ { name = "httpcore2" },
+ { name = "idna" },
+ { name = "truststore" },
+ { name = "typing-extensions", marker = "python_full_version < '3.13'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/a3/4a/129b2e21b90ac2985d3928d96792bccc39bc6dfe796c5eee2d8ec06d4105/httpx2-2.7.0.tar.gz", hash = "sha256:8b30709aed5c8465b0dd3b95c09ce301c8f79e7e7a2d00ab0af551e0d0375b07", size = 94487, upload-time = "2026-07-14T20:40:02.318Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/1d/b8/c341bba6411bdfda786020343c47a75ef472f6085caf82391b142b1a3ad9/httpx2-2.7.0-py3-none-any.whl", hash = "sha256:ed2a2719c696789e09493bd8e2bec3d8bd925cc6e26b68389ec25ade132f7bf4", size = 90234, upload-time = "2026-07-14T20:39:59.531Z" },
+]
+
[[package]]
name = "idna"
version = "3.18"
@@ -1043,6 +1074,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl", hash = "sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6", size = 73632, upload-time = "2026-06-12T09:23:10.017Z" },
]
+[[package]]
+name = "truststore"
+version = "0.10.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/53/a3/1585216310e344e8102c22482f6060c7a6ea0322b63e026372e6dcefcfd6/truststore-0.10.4.tar.gz", hash = "sha256:9d91bd436463ad5e4ee4aba766628dd6cd7010cf3e2461756b3303710eebc301", size = 26169, upload-time = "2025-08-12T18:49:02.73Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/19/97/56608b2249fe206a67cd573bc93cd9896e1efb9e98bce9c163bcdc704b88/truststore-0.10.4-py3-none-any.whl", hash = "sha256:adaeaecf1cbb5f4de3b1959b42d41f6fab57b2b1666adb59e89cb0b53361d981", size = 18660, upload-time = "2025-08-12T18:49:01.46Z" },
+]
+
[[package]]
name = "typing-extensions"
version = "4.16.0"