Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: annotation canvas component + page for media images (#2036)

Adam Eivy09a334523e2b
diff --git a/client/src/components/media/AnnotationCanvas.jsx b/client/src/components/media/AnnotationCanvas.jsx
new file mode 100644
index 0000000000..f0f0b29f02
--- /dev/null
+++ b/client/src/components/media/AnnotationCanvas.jsx
@@ -0,0 +1,132 @@
+import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react';
+import { drawStrokes, createStroke, appendPoint } from '../../lib/sketchCanvas';
+
+// Drawing surface for the Sketch & Annotation Canvas (issue #2036, phase 1).
+// Renders the target image with a transparent <canvas> stroke layer on top.
+// Controlled: the parent owns `strokes` + the active `tool` and receives
+// committed strokes via `onStrokesChange`. Pointer events cover mouse, pen, AND
+// touch (the canvas sets `touch-action: none` so a drag doesn't scroll the page).
+//
+// The imperative handle exposes `exportPng()` (flattened image + strokes) and
+// `dimensions` so the parent can persist / download without reaching into refs.
+const AnnotationCanvas = forwardRef(function AnnotationCanvas(
+ { imageSrc, strokes, tool, onStrokesChange, onImageLoad, onImageError },
+ ref,
+) {
+ const canvasRef = useRef(null);
+ const imgRef = useRef(null);
+ const drawingRef = useRef(null); // in-progress (uncommitted) stroke
+ const [dims, setDims] = useState(null); // { w, h } in natural pixels
+ const [inProgress, setInProgress] = useState(null);
+
+ const handleImgLoad = useCallback(() => {
+ const img = imgRef.current;
+ if (!img) return;
+ const w = img.naturalWidth || img.width || 1;
+ const h = img.naturalHeight || img.height || 1;
+ setDims({ w, h });
+ onImageLoad?.({ w, h });
+ }, [onImageLoad]);
+
+ // Redraw the whole layer from the committed strokes plus any in-progress
+ // stroke. Full redraw (rather than incremental) keeps undo/erase trivially
+ // correct — the layer is a pure function of the stroke list.
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas || !dims) return;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return;
+ const all = inProgress ? [...strokes, inProgress] : strokes;
+ drawStrokes(ctx, all, canvas.width, canvas.height);
+ }, [strokes, inProgress, dims]);
+
+ // Map a pointer event to natural-pixel canvas coordinates, accounting for the
+ // CSS scale between the displayed size and the canvas's internal resolution.
+ const toNatural = useCallback((e) => {
+ const canvas = canvasRef.current;
+ const rect = canvas.getBoundingClientRect();
+ const scaleX = canvas.width / (rect.width || 1);
+ const scaleY = canvas.height / (rect.height || 1);
+ return {
+ x: (e.clientX - rect.left) * scaleX,
+ y: (e.clientY - rect.top) * scaleY,
+ };
+ }, []);
+
+ const handlePointerDown = useCallback((e) => {
+ if (!dims) return;
+ e.preventDefault();
+ // Capture so strokes continue smoothly even when the pointer leaves the
+ // canvas bounds mid-draw. Auto-releases on pointerup/cancel.
+ canvasRef.current?.setPointerCapture?.(e.pointerId);
+ const { x, y } = toNatural(e);
+ const stroke = createStroke({ mode: tool.mode, color: tool.color, size: tool.size, x, y });
+ drawingRef.current = stroke;
+ setInProgress(stroke);
+ }, [dims, tool, toNatural]);
+
+ const handlePointerMove = useCallback((e) => {
+ if (!drawingRef.current) return;
+ e.preventDefault();
+ const { x, y } = toNatural(e);
+ const next = appendPoint(drawingRef.current, x, y);
+ drawingRef.current = next;
+ setInProgress(next);
+ }, [toNatural]);
+
+ const finishStroke = useCallback(() => {
+ const stroke = drawingRef.current;
+ if (!stroke) return;
+ drawingRef.current = null;
+ setInProgress(null);
+ onStrokesChange([...strokes, stroke]);
+ }, [strokes, onStrokesChange]);
+
+ useImperativeHandle(ref, () => ({
+ dimensions: dims,
+ // Flatten the image + stroke layer into a single PNG data URL at natural
+ // resolution. Same-origin image (/data/images/...) so the canvas isn't
+ // tainted and toDataURL succeeds.
+ exportPng: () => {
+ const canvas = canvasRef.current;
+ const img = imgRef.current;
+ if (!canvas || !img || !dims) return null;
+ const out = document.createElement('canvas');
+ out.width = dims.w;
+ out.height = dims.h;
+ const ctx = out.getContext('2d');
+ if (!ctx) return null;
+ ctx.drawImage(img, 0, 0, dims.w, dims.h);
+ ctx.drawImage(canvas, 0, 0, dims.w, dims.h);
+ return out.toDataURL('image/png');
+ },
+ }), [dims]);
+
+ return (
+ <div className="relative inline-block max-w-full bg-port-bg rounded-lg overflow-hidden">
+ <img
+ ref={imgRef}
+ src={imageSrc}
+ onLoad={handleImgLoad}
+ onError={onImageError}
+ alt="Media being annotated"
+ className="block max-w-full h-auto select-none"
+ draggable={false}
+ />
+ {dims && (
+ <canvas
+ ref={canvasRef}
+ width={dims.w}
+ height={dims.h}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={finishStroke}
+ onPointerCancel={finishStroke}
+ className="absolute inset-0 w-full h-full touch-none cursor-crosshair"
+ />
+ )}
+ </div>
+ );
+});
+
+export default AnnotationCanvas;
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 86845deb4e..0231374f8e 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -92,6 +92,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. |
| `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image src (`imageUrl` → served `image:<file>` bytes → null). Shared by MoodBoardDetail + MoodBoardReferenceStrip. |
| `sameJsonShape.js` | `sameJsonShape(prev, next)` — JSON.stringify-based equality for `useAutoRefetch`'s `compare` option on small, deterministically-shaped poll payloads. |
+| `sketchCanvas.js` | Pure stroke model + 2D-context renderer for the media annotation canvas (`createStroke`, `appendPoint`, `undoStrokes`, `drawStrokes`, `clampSize`). Points stored in natural-pixel space; erase strokes use `destination-out`. Used by `AnnotationCanvas.jsx` / `MediaAnnotate.jsx` (#2036). |
| `unsorted.js` | Synthetic "Unsorted" collection from media not filed in any real collection. |
| `upsertByIdPrepend.js` | Newest-first upsert into an id-keyed list. |
| `voiceLabel.js` | `formatVoiceLabel(v, engine?)` — display label for a TTS voice record. Engine-specific formatters plug into a lookup table; new engines extend that map. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index d7db01ee26..1211550e9f 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -63,6 +63,7 @@ export * from './mediaNavigation.js';
export * from './mediaSearch.js';
export * from './moodBoardItemSrc.js';
export * from './sameJsonShape.js';
+export * from './sketchCanvas.js';
export * from './unsorted.js';
export * from './upsertByIdPrepend.js';
export * from './voiceLabel.js';
diff --git a/client/src/lib/sketchCanvas.js b/client/src/lib/sketchCanvas.js
new file mode 100644
index 0000000000..f3de47a563
--- /dev/null
+++ b/client/src/lib/sketchCanvas.js
@@ -0,0 +1,69 @@
+// Pure stroke model + 2D-context renderer for the media Sketch & Annotation
+// Canvas (issue #2036, phase 1). Kept free of React/DOM lookups so the drawing
+// and undo logic is unit-testable with a mock 2D context.
+//
+// Points are stored in the image's NATURAL-pixel space (the canvas element is
+// sized to naturalWidth x naturalHeight and CSS-scaled to fit). Storing natural
+// coordinates makes strokes restore identically at any display size — the phone
+// (360px) and desktop render the same persisted vectors.
+
+export const DEFAULT_COLOR = '#ef4444';
+export const DEFAULT_SIZE = 6;
+export const MIN_SIZE = 1;
+export const MAX_SIZE = 64;
+
+export const clampSize = (n) => {
+ const v = Math.round(Number(n));
+ if (!Number.isFinite(v)) return DEFAULT_SIZE;
+ return Math.max(MIN_SIZE, Math.min(MAX_SIZE, v));
+};
+
+export const createStroke = ({ mode = 'draw', color = DEFAULT_COLOR, size = DEFAULT_SIZE, x, y }) => ({
+ mode: mode === 'erase' ? 'erase' : 'draw',
+ color,
+ size: clampSize(size),
+ points: [{ x, y }],
+});
+
+// Immutable append — returns a new stroke so React state updates re-render.
+export const appendPoint = (stroke, x, y) => ({
+ ...stroke,
+ points: [...stroke.points, { x, y }],
+});
+
+// Pop the most recent committed stroke. Returns the same array reference when
+// empty so callers can no-op cheaply.
+export const undoStrokes = (strokes) => (strokes.length ? strokes.slice(0, -1) : strokes);
+
+// Render every stroke onto a 2D context sized `width` x `height`. Erase strokes
+// use destination-out so they cut transparent holes in earlier draw strokes
+// (revealing the underlying image when the layer is composited over it).
+export function drawStrokes(ctx, strokes, width, height) {
+ if (!ctx) return;
+ ctx.clearRect(0, 0, width, height);
+ for (const stroke of strokes) {
+ if (!stroke || !Array.isArray(stroke.points) || stroke.points.length === 0) continue;
+ ctx.save();
+ ctx.lineJoin = 'round';
+ ctx.lineCap = 'round';
+ ctx.lineWidth = stroke.size;
+ const erase = stroke.mode === 'erase';
+ ctx.globalCompositeOperation = erase ? 'destination-out' : 'source-over';
+ const paint = erase ? 'rgba(0,0,0,1)' : stroke.color;
+ ctx.strokeStyle = paint;
+ ctx.fillStyle = paint;
+ const pts = stroke.points;
+ if (pts.length === 1) {
+ // A single tap draws a dot rather than a zero-length line.
+ ctx.beginPath();
+ ctx.arc(pts[0].x, pts[0].y, Math.max(stroke.size / 2, 0.5), 0, Math.PI * 2);
+ ctx.fill();
+ } else {
+ ctx.beginPath();
+ ctx.moveTo(pts[0].x, pts[0].y);
+ for (let i = 1; i < pts.length; i += 1) ctx.lineTo(pts[i].x, pts[i].y);
+ ctx.stroke();
+ }
+ ctx.restore();
+ }
+}
diff --git a/client/src/lib/sketchCanvas.test.js b/client/src/lib/sketchCanvas.test.js
new file mode 100644
index 0000000000..cd83eebd6a
--- /dev/null
+++ b/client/src/lib/sketchCanvas.test.js
@@ -0,0 +1,84 @@
+import { describe, it, expect, vi } from 'vitest';
+import {
+ createStroke, appendPoint, undoStrokes, clampSize, drawStrokes,
+ DEFAULT_COLOR, DEFAULT_SIZE, MIN_SIZE, MAX_SIZE,
+} from './sketchCanvas';
+
+describe('sketchCanvas stroke model', () => {
+ it('clampSize bounds and rounds; falls back on garbage', () => {
+ expect(clampSize(1000)).toBe(MAX_SIZE);
+ expect(clampSize(-5)).toBe(MIN_SIZE);
+ expect(clampSize(6.7)).toBe(7);
+ expect(clampSize('abc')).toBe(DEFAULT_SIZE);
+ });
+
+ it('createStroke seeds a single point and normalizes mode/size', () => {
+ const s = createStroke({ mode: 'erase', color: '#fff', size: 9999, x: 2, y: 3 });
+ expect(s.mode).toBe('erase');
+ expect(s.color).toBe('#fff');
+ expect(s.size).toBe(MAX_SIZE);
+ expect(s.points).toEqual([{ x: 2, y: 3 }]);
+
+ const d = createStroke({ x: 0, y: 0 });
+ expect(d.mode).toBe('draw');
+ expect(d.color).toBe(DEFAULT_COLOR);
+ expect(d.size).toBe(DEFAULT_SIZE);
+ });
+
+ it('appendPoint returns a new stroke (immutable) with the point added', () => {
+ const s = createStroke({ x: 0, y: 0 });
+ const s2 = appendPoint(s, 5, 6);
+ expect(s2).not.toBe(s);
+ expect(s.points).toHaveLength(1); // original untouched
+ expect(s2.points).toEqual([{ x: 0, y: 0 }, { x: 5, y: 6 }]);
+ });
+
+ it('undoStrokes pops the last stroke, no-ops on empty', () => {
+ const a = createStroke({ x: 0, y: 0 });
+ const b = createStroke({ x: 1, y: 1 });
+ expect(undoStrokes([a, b])).toEqual([a]);
+ const empty = [];
+ expect(undoStrokes(empty)).toBe(empty);
+ });
+});
+
+describe('drawStrokes renderer', () => {
+ const makeCtx = () => ({
+ save: vi.fn(), restore: vi.fn(), beginPath: vi.fn(), moveTo: vi.fn(),
+ lineTo: vi.fn(), stroke: vi.fn(), arc: vi.fn(), fill: vi.fn(), clearRect: vi.fn(),
+ lineJoin: '', lineCap: '', lineWidth: 0, globalCompositeOperation: '', strokeStyle: '', fillStyle: '',
+ });
+
+ it('clears then draws a polyline for a multi-point draw stroke', () => {
+ const ctx = makeCtx();
+ const stroke = { mode: 'draw', color: '#f00', size: 4, points: [{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 2 }] };
+ drawStrokes(ctx, [stroke], 10, 10);
+ expect(ctx.clearRect).toHaveBeenCalledWith(0, 0, 10, 10);
+ expect(ctx.moveTo).toHaveBeenCalledWith(0, 0);
+ expect(ctx.lineTo).toHaveBeenCalledTimes(2);
+ expect(ctx.stroke).toHaveBeenCalled();
+ });
+
+ it('draws a dot (arc+fill) for a single-point stroke', () => {
+ const ctx = makeCtx();
+ drawStrokes(ctx, [{ mode: 'draw', color: '#0f0', size: 8, points: [{ x: 3, y: 3 }] }], 10, 10);
+ expect(ctx.arc).toHaveBeenCalled();
+ expect(ctx.fill).toHaveBeenCalled();
+ expect(ctx.stroke).not.toHaveBeenCalled();
+ });
+
+ it('erase strokes use destination-out compositing', () => {
+ const ctx = makeCtx();
+ const composites = [];
+ // Record the composite op at the moment stroke() is invoked.
+ ctx.stroke = vi.fn(() => composites.push(ctx.globalCompositeOperation));
+ drawStrokes(ctx, [{ mode: 'erase', size: 5, points: [{ x: 0, y: 0 }, { x: 1, y: 1 }] }], 10, 10);
+ expect(composites).toContain('destination-out');
+ });
+
+ it('skips empty/invalid strokes without throwing', () => {
+ const ctx = makeCtx();
+ expect(() => drawStrokes(ctx, [null, { points: [] }, {}], 5, 5)).not.toThrow();
+ expect(ctx.stroke).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/pages/MediaAnnotate.jsx b/client/src/pages/MediaAnnotate.jsx
new file mode 100644
index 0000000000..f8e02e4b29
--- /dev/null
+++ b/client/src/pages/MediaAnnotate.jsx
@@ -0,0 +1,239 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useParams, Link } from 'react-router-dom';
+import { Pencil, Eraser, Undo2, Trash2, Save, Download, ArrowLeft, ImageOff } from 'lucide-react';
+import toast from '../components/ui/Toast';
+import AnnotationCanvas from '../components/media/AnnotationCanvas';
+import { useAsyncAction } from '../hooks/useAsyncAction';
+import { undoStrokes, clampSize, DEFAULT_COLOR, DEFAULT_SIZE, MIN_SIZE, MAX_SIZE } from '../lib/sketchCanvas';
+import { getMediaSketch, saveMediaSketch } from '../services/api';
+
+// Parse a media key `<kind>:<ref>` on the client (mirrors server/lib/mediaItemKey.js
+// rules loosely — the server re-validates authoritatively). Phase 1 only supports
+// annotating images.
+function parseMediaKey(key) {
+ if (typeof key !== 'string') return null;
+ const idx = key.indexOf(':');
+ if (idx <= 0) return null;
+ const kind = key.slice(0, idx);
+ const ref = key.slice(idx + 1);
+ if (!ref || ref.includes(':')) return null;
+ return { kind, ref };
+}
+
+const COLOR_SWATCHES = ['#ef4444', '#f59e0b', '#22c55e', '#3b82f6', '#a855f7', '#ffffff', '#000000'];
+
+export default function MediaAnnotate() {
+ const { mediaKey } = useParams();
+ const parsed = useMemo(() => parseMediaKey(mediaKey), [mediaKey]);
+ const isImage = parsed?.kind === 'image';
+ // Images are served from /data/images/<filename>; the ref IS the filename.
+ const imageSrc = isImage ? `/data/images/${parsed.ref}` : null;
+
+ const canvasApiRef = useRef(null);
+ const [strokes, setStrokes] = useState([]);
+ const [dims, setDims] = useState(null);
+ const [color, setColor] = useState(DEFAULT_COLOR);
+ const [size, setSize] = useState(DEFAULT_SIZE);
+ const [mode, setMode] = useState('draw'); // 'draw' | 'erase'
+ const [loading, setLoading] = useState(true);
+ const [imageError, setImageError] = useState(false);
+
+ // Load any previously-saved strokes for this media key.
+ useEffect(() => {
+ if (!isImage) { setLoading(false); return; }
+ let active = true;
+ setLoading(true);
+ getMediaSketch(mediaKey, { silent: true })
+ .then((res) => {
+ if (!active) return;
+ const loaded = Array.isArray(res?.sketch?.strokes) ? res.sketch.strokes : [];
+ setStrokes(loaded);
+ if (loaded.length > 0) toast.success(`Restored ${loaded.length} stroke${loaded.length === 1 ? '' : 's'}`);
+ })
+ .catch(() => { if (active) toast.error('Failed to load saved annotation'); })
+ .finally(() => { if (active) setLoading(false); });
+ return () => { active = false; };
+ }, [mediaKey, isImage]);
+
+ const tool = useMemo(() => ({ color, size, mode }), [color, size, mode]);
+
+ const handleUndo = useCallback(() => setStrokes((prev) => undoStrokes(prev)), []);
+ const handleClear = useCallback(() => setStrokes([]), []);
+
+ const [save, saving] = useAsyncAction(async () => {
+ if (!dims) throw new Error('Canvas not ready');
+ const png = canvasApiRef.current?.exportPng?.() || undefined;
+ const res = await saveMediaSketch(mediaKey, {
+ width: dims.w,
+ height: dims.h,
+ strokes,
+ png,
+ }, { silent: true });
+ return res;
+ }, { errorMessage: 'Failed to save annotation' });
+
+ const handleSave = useCallback(async () => {
+ const res = await save();
+ if (res) toast.success(strokes.length ? 'Annotation saved' : 'Annotation cleared');
+ }, [save, strokes.length]);
+
+ const handleExport = useCallback(() => {
+ const dataUrl = canvasApiRef.current?.exportPng?.();
+ if (!dataUrl) { toast.error('Nothing to export yet'); return; }
+ const a = document.createElement('a');
+ a.href = dataUrl;
+ a.download = `annotated-${parsed?.ref || 'image'}.png`;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ }, [parsed]);
+
+ if (!isImage) {
+ return (
+ <div className="p-4 md:p-6 max-w-3xl mx-auto text-sm text-gray-400">
+ <Link to="/media/history" className="text-port-accent hover:underline inline-flex items-center gap-1">
+ <ArrowLeft className="w-4 h-4" /> Back to Media History
+ </Link>
+ <div className="mt-6 bg-port-card border border-port-border rounded-xl p-8 text-center">
+ <ImageOff className="w-8 h-8 mx-auto mb-2 text-gray-600" />
+ {mediaKey
+ ? 'Only generated images can be annotated. This link points at an unsupported or missing item.'
+ : 'Open a generated image from Media History or a Collection and choose “Annotate” to draw over it.'}
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col h-full overflow-y-auto">
+ <div className="p-3 md:p-4 border-b border-port-border flex flex-wrap items-center gap-2 sticky top-0 bg-port-bg/95 backdrop-blur z-10">
+ <Link to="/media/history" className="text-gray-400 hover:text-white inline-flex items-center gap-1 text-sm mr-1" title="Back to Media History">
+ <ArrowLeft className="w-4 h-4" /> <span className="hidden sm:inline">History</span>
+ </Link>
+
+ {/* Draw / erase */}
+ <div className="flex rounded-lg overflow-hidden border border-port-border">
+ <button
+ type="button"
+ onClick={() => setMode('draw')}
+ className={`px-2.5 py-1.5 text-xs flex items-center gap-1 ${mode === 'draw' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-300 hover:bg-port-border'}`}
+ aria-pressed={mode === 'draw'}
+ >
+ <Pencil className="w-3.5 h-3.5" /> Draw
+ </button>
+ <button
+ type="button"
+ onClick={() => setMode('erase')}
+ className={`px-2.5 py-1.5 text-xs flex items-center gap-1 ${mode === 'erase' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-300 hover:bg-port-border'}`}
+ aria-pressed={mode === 'erase'}
+ >
+ <Eraser className="w-3.5 h-3.5" /> Erase
+ </button>
+ </div>
+
+ {/* Color swatches */}
+ <div className="flex items-center gap-1">
+ {COLOR_SWATCHES.map((c) => (
+ <button
+ key={c}
+ type="button"
+ onClick={() => { setColor(c); setMode('draw'); }}
+ className={`w-6 h-6 rounded-full border-2 ${color === c && mode === 'draw' ? 'border-white' : 'border-port-border'}`}
+ style={{ backgroundColor: c }}
+ title={`Color ${c}`}
+ aria-label={`Color ${c}`}
+ />
+ ))}
+ <label htmlFor="annotate-color" className="sr-only">Custom color</label>
+ <input
+ id="annotate-color"
+ type="color"
+ value={color}
+ onChange={(e) => { setColor(e.target.value); setMode('draw'); }}
+ className="w-6 h-6 rounded cursor-pointer bg-transparent border border-port-border"
+ title="Custom color"
+ />
+ </div>
+
+ {/* Brush size */}
+ <div className="flex items-center gap-1.5">
+ <label htmlFor="annotate-size" className="text-xs text-gray-400">Size</label>
+ <input
+ id="annotate-size"
+ type="range"
+ min={MIN_SIZE}
+ max={MAX_SIZE}
+ value={size}
+ onChange={(e) => setSize(clampSize(e.target.value))}
+ className="w-20 md:w-28 accent-port-accent"
+ />
+ <span className="text-xs text-gray-400 w-5 tabular-nums">{size}</span>
+ </div>
+
+ <div className="flex items-center gap-1 ml-auto">
+ <button
+ type="button"
+ onClick={handleUndo}
+ disabled={strokes.length === 0}
+ className="px-2 py-1.5 text-xs bg-port-card border border-port-border rounded hover:bg-port-border disabled:opacity-40 inline-flex items-center gap-1"
+ title="Undo last stroke"
+ >
+ <Undo2 className="w-3.5 h-3.5" /> <span className="hidden sm:inline">Undo</span>
+ </button>
+ <button
+ type="button"
+ onClick={handleClear}
+ disabled={strokes.length === 0}
+ className="px-2 py-1.5 text-xs bg-port-card border border-port-border rounded hover:bg-port-border disabled:opacity-40 inline-flex items-center gap-1"
+ title="Clear all strokes"
+ >
+ <Trash2 className="w-3.5 h-3.5" /> <span className="hidden sm:inline">Clear</span>
+ </button>
+ <button
+ type="button"
+ onClick={handleExport}
+ disabled={!dims}
+ className="px-2 py-1.5 text-xs bg-port-card border border-port-border rounded hover:bg-port-border disabled:opacity-40 inline-flex items-center gap-1"
+ title="Download flattened PNG"
+ >
+ <Download className="w-3.5 h-3.5" /> <span className="hidden sm:inline">Export</span>
+ </button>
+ <button
+ type="button"
+ onClick={handleSave}
+ disabled={saving || !dims}
+ className="px-3 py-1.5 text-xs bg-port-accent text-white rounded hover:bg-port-accent/80 disabled:opacity-40 inline-flex items-center gap-1"
+ title="Save annotation"
+ >
+ <Save className="w-3.5 h-3.5" /> {saving ? 'Saving…' : 'Save'}
+ </button>
+ </div>
+ </div>
+
+ <div className="flex-1 p-3 md:p-6 flex items-start justify-center">
+ {imageError ? (
+ <div className="bg-port-card border border-port-border rounded-xl p-8 text-center text-sm text-gray-400 max-w-md">
+ <ImageOff className="w-8 h-8 mx-auto mb-2 text-gray-600" />
+ Couldn't load this image. It may have been deleted or not yet synced from a peer.
+ <div className="mt-3">
+ <Link to="/media/history" className="text-port-accent hover:underline">← Back to Media History</Link>
+ </div>
+ </div>
+ ) : (
+ <div className="w-full max-w-4xl">
+ {loading && <div className="text-gray-500 text-sm mb-2">Loading saved annotation…</div>}
+ <AnnotationCanvas
+ ref={canvasApiRef}
+ imageSrc={imageSrc}
+ strokes={strokes}
+ tool={tool}
+ onStrokesChange={setStrokes}
+ onImageLoad={setDims}
+ onImageError={() => setImageError(true)}
+ />
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}