Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(v0.5): Magic Layers, real-time collaboration, comments, animations, SVG & video export, AI Assistant 2.0
Ashiq Hussain Mir042dc9e1dac7
diff --git a/.env.example b/.env.exampleindex 3007eed..ef7ad15 100644--- a/.env.example+++ b/.env.example@@ -1,5 +1,6 @@# Canvix — environment variables#+# ── Database (required) ────────────────────────────────────────# PostgreSQL connection string. Works with any Postgres server:# - local install: postgresql://user:password@localhost:5432/canvix# - Docker: postgresql://user:password@localhost:5432/canvix@@ -9,3 +10,16 @@# Local development quick-start (Docker):# docker run --name canvix-pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=canvix -p 5432:5432 -d postgres:17DATABASE_URL=postgresql://user:password@localhost:5432/canvix++# ── AI provider (optional) ─────────────────────────────────────+# Canvix works without any AI provider (local features keep working).+# When these are set, AI features (Magic Layers, Assistant, Magic Write,+# image generation/editing, translate, photo search) activate.+# Credentials are SERVER-SIDE ONLY — never exposed to the browser.+#+# Alternative: place a .z-ai-config JSON file on the server host:+# { "baseUrl": "https://your-provider.example/v1", "apiKey": "your-key" }+# (checked at the working directory, then ~, then /etc)+#+# ZAI_BASE_URL=https://your-provider.example/v1+# ZAI_API_KEY=your-keydiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0b96ad9..6ad6c77 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,148 @@All notable changes to Canvix will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).+## [0.5.0] — 2026-09-04++The AI-native collaborative release: Magic Layers turns flat images into editable+designs, real-time multiplayer arrives with comments, designs learn to move with+animations and export as SVG and video, and the AI stack gets a production-grade+provider abstraction.++### Magic Layers — image → editable design+- Upload (or select) a flat design and a **vision model decomposes it into real,+ editable Canvix layers**: text regions become live text elements (color, weight,+ approximate font size and class recovered), photo regions become cropped image+ elements, shapes become native shapes, and the background becomes a page+ background/gradient.+- The analysis returns a **validated region schema** (bounds, confidence 0–1,+ layer order) — the client reconstructs native elements, never a raster. Each+ element carries `magicLayer` provenance metadata (source region, confidence,+ original bounds) for future tooling.+- Honest-by-design review UX: region overlays with confidence colors, per-region+ keep/discard toggles, low-confidence flags, model limitations surfaced in the+ dialog ("illustrations become image regions", "fonts matched by class").+- Server route `POST /api/ai/magic-layers`: dataURL-only input, 8 MB cap,+ `validateAnalysis()` clamps every field (bounds 0..1, hex colors, whitelisted+ font classes, text ≤ 400 chars, ≤ 40 regions, deduped overlapping text).++### Real-time collaboration+- **Multiplayer editing on Postgres + SSE** — an append-only `DesignEvent` log+ (global monotonic seq) is the replication stream; clients subscribe via+ server-sent events (~800 ms ticks) and push ops via batched POSTs (400 ms flush,+ coalesced `elements:update` patches). Deployable on Vercel serverless *and*+ self-hosted Node — no WebSocket server.+- **Presence**: colored cursors with name tags, remote selection outlines,+ stacked avatars + connection status (Live/Syncing/Offline) in the top bar,+ collaborator list popover with per-user page/selection state, editable display+ name (persisted anonymous identity — no account required).+- **Gap-free reconnection**: clients track `lastSeq`; on stream drop they+ reconnect with `?since=<seq>` and replay missed events; offline edits queue and+ flush on recovery. Local input is never blocked (optimistic, sync in background).+- Ops are small and explicit (`elements:update`, `element:add`, `page:replace`,+ `pages:replace`, …) and apply through the existing store actions, so undo stays+ local and Konva rendering stays fast. Share links now deep-link+ (`/?design=<id>`); unknown ids stay on the landing page.+- Abuse hardening: payloads ≤ 256 KB with recursive type/size/depth validation,+ ≤ 20 events/flush, whitelisted op kinds, presence GC (30 s offline / 24 h rows),+ event log pruned to 500 per design, malformed events dropped (never crash).++### Comments & annotations+- First-class **comments mode**: click the canvas to drop a pin (clicking an+ element anchors the thread to it — the pin follows the element), type and post.+- Threads with **replies, resolve/reopen, delete-own**, collaborator+ avatars/colors, relative timestamps; pins keep their anchor when pages resize+ (coordinates stored as page fractions).+- **Unread badges** on the topbar icon + open/resolved/all filters in the panel.+- Live propagation rides the collab event log (`comment:activity` markers →+ refetch), with optimistic local updates for the author.++### Animations — Magic Animate+- Animation model on the document (`element.animation`, `page.transition`) that+ is **independent from Konva** — pure functions of time+ (`src/lib/animations.ts`), shared by preview playback and video export.+- 9 element animations — fade, rise, pan, pop, wipe, zoom, rotate, breathe —+ with duration, delay, easing (linear/ease/spring), direction and speed presets+ (slow/medium/fast); page transitions none/fade/slide/morph with 0.1–2.5 s+ durations.+- **Magic Animate** — one-click deterministic pass: headings rise, body text+ fades, images pan from their nearest edge, shapes pop, separators wipe,+ transition fades.+- Preview gains animated playback, autoplay presentation mode and a+ reduce-motion accessibility toggle. Static exports (PNG/JPG/PDF/SVG) ignore+ animations entirely.++### SVG export+- True vector serialization of every element type: text (word-wrap measured via+ canvas 2D, per-line tspans, align/letterSpacing/decorations), shapes with+ gradients + rounded corners, paths (scaled from the 100×100 authoring box),+ lines with arrowheads, freehand strokes, images (href allowlist, rounded-clip,+ flips), stickers, groups, shadows (feDropShadow) and page backgrounds.+- **Sanitized by construction**: all text XML-escaped, path data whitelisted,+ image hrefs only `data:`/`https:`, no scripts/events/foreignObject. Multi-page+ exports as one file per page.++### Video export (MP4/WebM)+- A real, fully-local rendering pipeline: design timeline → headless Konva frame+ renderer (element animations + page transitions composited per frame) →+ `canvas.captureStream(0)` + manual `requestFrame()` → **MediaRecorder**.+- **Honest format detection**: MP4 (H.264) where the browser supports encoding+ it, WebM (VP9/VP8) otherwise — the export dialog tells you which and why+ before you start. Real-time pacing keeps duration exact (frames drop to stay+ on schedule); progress bar with frame counter; nothing leaves the browser.+- Verified end-to-end: an ffprobe-clean 1080×1080 H.264 MP4 (2.8 s, ~100 KB).++### AI Assistant 2.0+- The assistant now sees the **live design context** — elements with ids/types/+ positions/styles, selection, colors and fonts in use, page dimensions.+- It answers with **structured `DesignAction`s** (addText, updateElements,+ moveElements, scaleElements, setHeadingsColor, setFont, setBackground,+ align/distribute, addPage, duplicatePage, generateImage, suggestPalette,+ translate, magicAnimate, balanceLayout) instead of just chat.+- **Double validation**: the server clamps every field (hex colors, numeric+ ranges, id existence) and the client re-validates + resolves ids against the+ page before executing. Every action applies as a normal undoable edit, with an+ inline "Undo last change" affordance. Deterministic local fallbacks+ (balanceLayout, palettes) work without any provider.++### AI provider abstraction & fallbacks+- `src/lib/ai/provider.ts` centralizes: config resolution (`ZAI_BASE_URL`/+ `ZAI_API_KEY` env → `.z-ai-config` file → absent), capability probing,+ per-IP sliding-window rate limits on every AI route (429 + Retry-After) and+ `AIUsage` accounting.+- `/api/ai/capabilities` — public, secret-free feature detection; panels show+ "AI provider not configured" states *before* you try a feature, with local+ alternatives (background removal ONNX, deterministic palettes/layout) still+ working. No provider key ever reaches the browser (audited + grep-verified).+- All five v0.4 AI routes refactored onto the abstraction; no behavioral change+ when a provider is present.++### Performance+- **Image downscaling on embed** — uploads > 2048 px longest edge are re-encoded+ (alpha-preserving PNG / JPEG q0.9) before entering the document; 25 MB input+ cap; Magic Layers crops capped at 1024 px.+- Collaboration updates coalesce (consecutive same-id `elements:update` patches+ merge in the queue), remote batches apply as single store writes, presence+ rows and the event log are garbage-collected, and collab cursors render in a+ DOM overlay that never enters Konva's pipeline.+- Fixed an uncached zustand selector that caused an infinite re-render loop in+ the editor (Magic Layers dialog).++### Infrastructure+- Prisma schema gains `DesignEvent`, `Presence`, `Comment` and `AIUsage` models+ (backward compatible — `prisma db push`, no destructive migrations).+- Deep links `/?design=<id>` / `?d=<id>` open the editor directly (invalid ids+ fall back to the landing page).+- Research docs shipped: current-state audit, AI provider audit, fresh Canva+ research, collaboration architecture decision record and a full security+ audit (`research/V05-SECURITY-AUDIT.md`).++## [0.4.0] — 2026-09-03++The Magic Suite release: AI image editing (BG remover, Magic Eraser, Enhance),+Magic Resize with smart re-layout, design translation, live photo search,+PostgreSQL migration and server-side version history. (Full notes in the v0.4+commit message; the feature list also lives in README.md.)+## [0.3.2] — 2026-09-03Fresh canva.com research pass (fonts, design trends 2026, feature taxonomy) plus thediff --git a/README.md b/README.mdindex 121f265..7e3a032 100644--- a/README.md+++ b/README.md@@ -30,6 +30,52 @@ watermarks, no paywalls.## 🎨 Features+### v0.5.0 — Magic Layers, real-time collaboration & production AI infrastructure++- **Magic Layers** — upload any flat design (or pick an image on your canvas) and a+ vision model decomposes it into **real, editable Canvix layers**: text becomes+ live text boxes (color, weight and size recovered), photos become cropped image+ elements, shapes become native shapes, the background becomes a page background.+ Every region carries a confidence score — uncertain regions are flagged amber in+ the review step and can be discarded. Honest limitations are surfaced in-product+ (fonts are matched by class, not recovered exactly; illustrations become image+ regions)+- **Real-time collaboration** — share a design link and edit together: live+ multiplayer with **colored cursors + name tags**, remote selection outlines,+ presence avatars in the top bar, a live/offline connection indicator, and+ gap-free catch-up after disconnects. Architecture: an append-only event log in+ Postgres + server-sent events downstream + batched op POSTs upstream — works on+ Vercel serverless and self-hosted Node alike, no WebSocket server required.+ Optimistic local edits always keep the canvas butter-smooth+- **Comments & annotations** — a first-class comments mode: click anywhere on the+ canvas (or on an element — the pin follows it) to drop a threaded comment.+ Replies, resolve/reopen, delete-own, unread badges, collaborator avatars and+ live propagation to everyone in the design+- **Animations — Magic Animate** — an Animate panel (Page / Element tabs) with 9+ element animations (fade, rise, pan, pop, wipe, zoom, rotate, breathe), speed+ presets, duration/delay/easing/direction controls, and **page transitions**+ (fade/slide/morph, 0.1–2.5 s). One-click **Magic Animate** gives the whole page+ a tasteful animation pass. Animated playback in Preview with autoplay and a+ reduce-motion accessibility toggle+- **SVG export** — true vector export: text, shapes, paths, gradients, opacity,+ transforms, images and shadows serialize to clean, sanitized SVG (no+ rasterization of vector elements, opens in browsers and vector editors)+- **Video export (MP4/WebM)** — a real rendering pipeline: the animation timeline+ is rendered frame-by-frame to an offscreen canvas and encoded locally via+ MediaRecorder — **MP4 (H.264)** where the browser can encode it, WebM otherwise.+ Honest format detection is shown before you export. No uploads, no server+ rendering+- **AI Assistant 2.0** — the assistant is now design-aware: it sees your page's+ elements, colors, fonts and selection, and answers with **structured, validated+ actions** ("move the title to the top", "change all heading colors to purple",+ "make the layout more balanced", "add a CTA"). Every change lands as a normal,+ undoable edit+- **AI provider abstraction** — all AI features route through one server-side+ provider layer: per-IP rate limits, usage accounting, capability probing and+ **graceful degradation** when no provider is configured (local features like+ background removal, palette generation and layout balancing keep working; the+ rest show a clear "requires an AI provider" notice)+### v0.4.0 — the Magic Suite: AI editing, PostgreSQL & infrastructure- **PostgreSQL database** — Prisma migrated from SQLite to Postgres (native `jsonb`@@ -214,6 +260,8 @@ bun run start| Canvas engine | [Konva.js](https://konvajs.org) via react-konva || State | Zustand || Database | Prisma ORM + PostgreSQL (jsonb) |+| Realtime | Postgres event log + SSE (no WebSocket server needed) |+| AI | server-side provider layer (z-ai-web-dev-sdk, vision-capable) || Fonts | 15 hand-picked Google Fonts |## 📁 Project structure@@ -221,20 +269,84 @@ bun run start```src/├── app/ # Next.js App Router-│ ├── page.tsx # single-page app shell (landing / dashboard / editor)-│ └── api/ # REST endpoints: designs, templates+│ ├── page.tsx # single-page app shell (landing / dashboard / editor + ?design= deep links)+│ └── api/ # REST endpoints: designs, templates, collab (SSE), comments, ai├── components/│ ├── landing/ # marketing page│ ├── dashboard/ # home screen: presets, templates, recent designs│ └── editor/ # the design editor-│ ├── canvas/ # Konva stage, element renderers, export bridge-│ └── panels/ # templates / elements / text / brand / uploads / tools / projects / apps-├── lib/ # types, editor utilities, template library-├── store/ # zustand stores (app + editor)+│ ├── canvas/ # Konva stage, element renderers, collab overlay, comment pins, export bridge+│ └── panels/ # templates / elements / text / brand / uploads / photos / tools / projects / apps / animate+├── lib/+│ ├── ai/ # v0.5 AI provider abstraction (config, rate limits, usage)+│ ├── collab/ # v0.5 realtime: protocol, client session, participant identity+│ ├── magic-layers/ # v0.5 image → editable layers pipeline+│ ├── animations.ts # v0.5 animation engine (pure functions of time)+│ ├── svg-export.ts # v0.5 vector export+│ ├── video-export.ts # v0.5 MediaRecorder MP4/WebM pipeline+│ └── design-actions.ts # v0.5 validated, undoable AI editor actions+├── store/ # zustand stores (app + editor + comments)└── hooks/prisma/ # schema + seed+research/ # architecture decision records & audits+```++## 🤖 AI provider setup++Canvix works fully **without** any AI provider — the editor, templates, exports,+collaboration and comments need nothing but the database. AI features+(Magic Layers, Assistant, Magic Write, image generation/editing, translate,+photo search) activate when a provider is configured **on the server**:++Option A — environment variables (recommended for Vercel etc.):++```bash+# .env (server-side only — never exposed to the browser)+ZAI_BASE_URL=https://your-provider.example/v1+ZAI_API_KEY=your-key```+Option B — a `.z-ai-config` JSON file on the server host (checked at the working+directory, then `~`, then `/etc`):++```json+{ "baseUrl": "https://your-provider.example/v1", "apiKey": "your-key" }+```++The provider layer (`src/lib/ai/provider.ts`) resolves credentials in that order,+probes capabilities at runtime and answers `/api/ai/capabilities` (booleans only —+never secrets). When no provider is configured, AI features degrade gracefully:+background removal (local ONNX), color palettes and layout balancing keep working,+and provider-backed features show a clear setup notice. Every AI route is rate-+limited per IP and logs usage into the `AIUsage` table.++### Local-only vs provider-backed features++| Feature | Works without a provider? |+|---|---|+| Editor, templates, uploads, draw, groups, rulers, crop | ✅ always local |+| Exports — PNG / JPG / PDF / SVG / video | ✅ always local |+| Collaboration, presence, comments | ✅ only needs the database |+| Background remover | ✅ local (in-browser ONNX) |+| Color palettes, layout balancing | ✅ local (deterministic) |+| Magic Layers, AI Assistant, Magic Write | ⚙️ needs a server AI provider |+| AI image generation / eraser / enhance | ⚙️ needs a server AI provider |+| Translate, live photo search | ⚙️ needs a server AI provider |++## 🔐 Security notes++- **Secrets never reach the browser** — provider credentials are resolved+ server-side only; the public capabilities endpoint exposes booleans only+- **Validated collaboration ops** — every realtime event is type-checked,+ size-capped (256 KB) and dropped (never crashed) if malformed; see+ `research/V05-SECURITY-AUDIT.md`+- **Sanitized SVG export** — all text is XML-escaped, path data is whitelisted,+ image hrefs only allow `data:`/`https:`; no scripts or event handlers+- **AI actions are double-validated** (server clamps + client re-checks) and+ always undoable+- Known limitation: designs are link-accessible (no per-user ownership yet) —+ the v0.5 identity layer is the migration path; see the security audit+## 🧭 Roadmap- [x] Canva-accurate dark theme & 8-tab editor rail *(v0.2.0)*@@ -242,10 +354,10 @@ prisma/ # schema + seed- [x] Canva-exact selection, context menus, groups, colour menu, apps ecosystem *(v0.3.0)*- [x] Rulers & manually placed guides, image crop, layer renaming, version history *(v0.3.1)*- [x] 63-font library, gradient fills, PDF export, stock photo library, AI apps *(v0.3.2)*-- [ ] Real-time collaboration (CRDT)-- [ ] Comment & annotation mode-- [ ] SVG export-- [ ] Video/MP4 export+- [x] Magic Suite: AI image editing, Magic Resize, Translate, PostgreSQL *(v0.4.0)*+- [x] Magic Layers, real-time collaboration, comments, animations, SVG & video export, AI Assistant 2.0 *(v0.5.0)*+- [ ] Accounts & per-design ownership (identity layer groundwork shipped in v0.5)+- [ ] Yjs-grade offline merge for collaboration- [ ] Plugin system (external, installable apps)## 🤝 Contributingdiff --git a/package.json b/package.jsonindex c873640..cdff437 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.4.0",+ "version": "0.5.0","private": false,"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex f75caff..bf04849 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -51,3 +51,64 @@ model Template {accent String @default("#00C4CC") // card decorationcreatedAt DateTime @default(now())}++// ── v0.5.0: collaboration, comments & AI infrastructure ──────++// Append-only operation log — the replication stream for live collaboration.+// `id` is a global monotonic sequence: clients track their last seen seq and+// replay from any offset after reconnecting (SSE `?since=<seq>`).+model DesignEvent {+ id BigInt @id @default(autoincrement())+ designId String+ actorId String // participant id (client-generated)+ kind String // op name — see research/COLLABORATION-ARCHITECTURE.md §3+ payload Json+ createdAt DateTime @default(now())++ @@index([designId, id(sort: Desc)])+}++// Live presence per participant per design (heartbeat-based).+model Presence {+ id String @id // = participant id+ designId String+ name String+ color String+ cursor Json? // { page: number, x: number, y: number, selection?: string[] }+ lastSeen DateTime @default(now()) @updatedAt++ @@unique([designId, id])+ @@index([designId, lastSeen])+}++// Canvas-anchored comment threads (author identity is the local participant).+model Comment {+ id String @id @default(cuid())+ designId String+ pageId String+ x Float // anchor in page coordinates (fraction of page size, 0..1)+ y Float+ elementId String? // optional element anchor — pin follows the element+ authorId String+ authorName String+ authorColor String+ body String+ parentId String? // reply threading+ resolved Boolean @default(false)+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([designId, createdAt])+ @@index([designId, resolved])+}++// Provider accounting + abuse telemetry for AI routes.+model AIUsage {+ id String @id @default(cuid())+ feature String // write | image | image-edit | translate | assistant | magic-layers | search+ provider String // zai | local+ ok Boolean @default(true)+ createdAt DateTime @default(now())++ @@index([createdAt])+}diff --git a/research/AI-PROVIDER-AUDIT.md b/research/AI-PROVIDER-AUDIT.mdnew file mode 100644index 0000000..f7779d4--- /dev/null+++ b/research/AI-PROVIDER-AUDIT.md@@ -0,0 +1,115 @@+# Canvix v0.5.0 — AI Provider Audit++> Every AI capability traced UI → API route → SDK → provider, with the credential source for each. Audited at `bc78723` (v0.4.0). **Bottom line: no provider API key ever reaches the browser. All provider calls happen server-side in Next.js API routes (`runtime = 'nodejs'`) via `z-ai-web-dev-sdk`, whose credentials come from a server-side `.z-ai-config` file.**++## 1. Credential mechanism (the single source of truth)++`z-ai-web-dev-sdk` v0.0.18 `ZAI.create()` → `loadConfig()` reads a **JSON config file**, in priority order:++1. `<cwd>/.z-ai-config`+2. `~/.z-ai-config`+3. `/etc/.z-ai-config`++Required keys: `baseUrl`, `apiKey` (optional: `chatId`, `userId`, `token`). Every SDK call sends `Authorization: Bearer <apiKey>` + `X-Z-AI-From: Z` to `<baseUrl>/…`.++- **No environment variables are used by the SDK.** There is no `ZAI_API_KEY` anywhere in the repo (grep-verified, case-insensitive, all file types).+- `.z-ai-config` is gitignored (`.gitignore` line `.z-ai-config` + `.z-ai-config/`), and git history contains no `apiKey` string (verified: `git log --all -p -S '.z-ai-config'` shows only the ignore rule being added; the file itself was never tracked).+- The config file exists **only on the server** (sandbox/dev machine and, in production, whatever host the user runs the standalone server on). On Vercel, the user must place credentials via a mounted file or project-local file outside git; this is documented in the README as the provider setup step. v0.5 additionally lets routes read `ZAI_BASE_URL` / `ZAI_API_KEY` env vars as an override (falls back to the config file) — giving deploy targets without a writable FS a path, while keeping the same server-only guarantee.++## 2. Feature-by-feature trace++### 2.1 Magic Write — server/provider+```+MagicWriteApp.tsx (panel) → POST /api/ai/write+ → dynamic import z-ai-web-dev-sdk → ZAI.create() (.z-ai-config)+ → zai.chat.completions.create (LLM text) → 3 copy variants → JSON to client+```+Auth source: `.z-ai-config` (server FS). Model: provider chat completions. Fallback today: 502 `{ error }` + toast.++### 2.2 AI Image Generator — server/provider+```+AIImageApp.tsx (panel) → POST /api/ai/image { prompt, size∈7 presets }+ → zai.images.generations.create → base64 PNG → dataURL → client adds ImageElement+```+Auth source: `.z-ai-config`. Model: provider image generation (sizes 1024², 1344×768, 768×1344, 1152×864, 864×1152, 1440×720, 720×1440).++### 2.3 AI Assistant — server/provider+```+AssistantApp.tsx (chat UI) → POST /api/ai/assistant { message, history, design summary }+ → zai.chat.completions.create (system prompt + design context + history)+ → robust JSON parser → { reply, actions[] } — actions: addText | generateImage | suggestPalette | translate+ → client applies actions via editor store (addText→addElement, palette→brand, …)+```+Auth source: `.z-ai-config`. v0.5 upgrades this to the design-aware DesignActions protocol (Phase 10).++### 2.4 Translate (Magic Translate) — server/provider+```+TranslateDialog.tsx → collects texts from ALL pages → POST /api/ai/translate { texts[], language }+ → zai.chat.completions.create → numbered-list translation → trailing-junk-tolerant JSON array parser+ → store.translateTexts() (group-aware, undoable)+```+Auth source: `.z-ai-config`. 24 languages.++### 2.5 Magic Eraser — server/provider+```+ImageAI.tsx MagicEraserPopover → POST /api/ai/image-edit { imageUrl(dataURL), mask, op:'erase' }+ → zai.images.generations.edit { images:[{url}] (runtime quirk), prompt } → edited PNG → replaces element src+```+Auth source: `.z-ai-config`.++### 2.6 Enhance — server/provider+```+ImageAI.tsx EnhanceButton → POST /api/ai/image-edit { op:'enhance' } → images.generations.edit → replaced src+```+Auth source: `.z-ai-config`.++### 2.7 Photo Search — server/provider+```+PhotosPanel.tsx (debounced) → POST /api/photos/search { q }+ → zai.images.search.create → results [{ url, title? }] → hot-linked thumbnails, drag-to-canvas+```+Auth source: `.z-ai-config`. Client receives only public image URLs — not credentials.++### 2.8 Background Remover — LOCAL (hybrid app, local op)+```+ImageAI.tsx BgRemoverButton → dynamic import @imgly/background-removal (ONNX, WASM)+ → runs in-browser, model fetched & cached → true alpha PNG → replaces element src+```+**No server, no credential.** Works offline. This is the template for v0.5 local-capability fallbacks.++### 2.9 New in v0.5 (added by this audit's plan)+- **Magic Layers** → new `POST /api/ai/magic-layers` → `zai.chat.completions.createVision` (vision) → region JSON → client reconstruction. Server/provider.+- **AI Assistant 2.0** → same route, richer context + DesignActions. Server/provider with deterministic local fallbacks for palette/layout suggestions.++## 3. Classification matrix++| Capability | Class | Credential | Graceful behavior when unavailable |+|---|---|---|---|+| Magic Write | server/provider | `.z-ai-config` | 502 JSON + toast "AI unavailable" (route catches, never crashes) |+| AI Image Gen | server/provider | `.z-ai-config` | same |+| Magic Eraser | server/provider | `.z-ai-config` | same |+| Enhance | server/provider | `.z-ai-config` | same |+| Translate | server/provider | `.z-ai-config` | same |+| Photo Search | server/provider | `.z-ai-config` | empty results + inline notice |+| AI Assistant | server/provider | `.z-ai-config` | 502 + toast; v0.5: deterministic fallback answers |+| Background Remover | **local** | none | already fully local (ONNX) |+| Color palette | **local** (v0.5) | none | deterministic harmony generation from current colors |+| Layout suggestions | **local** (v0.5) | none | deterministic heuristics (safe margins, grid, alignment) |+| Magic Layers | hybrid | `.z-ai-config` (vision) | v0.5: clear "requires AI provider" + local-only fallback = full-image background layer with honest labeling |++## 4. Client-exposure verification (grep results, whole repo)++- `ZAI_API_KEY` / `API_KEY` / `NEXT_PUBLIC_`: **0 hits** outside `node_modules` (only `.z-ai-config` reads inside the SDK, server-side).+- `ZAI.create` / `z-ai-web-dev-sdk`: 6 hits, **all inside `src/app/api/**`** (server). No client component imports the SDK.+- `process.env` in client components: only `NODE_ENV` checks. No secrets.+- Build output: Next.js server bundles the SDK server-side only; client chunks contain no `baseUrl`/`apiKey` (spot-checked `.next/static` chunks for `apiKey` — 0 hits).+- `.gitignore` covers: `.env*` (except `.env.example`), `.z-ai-config`, `/tools/`, `/scripts/` (contains session creds), `research/*` raw captures, `tests/`, `worklog.md`, `download/`.+- Git history scan for accidental secret commits: `git log --all --diff-filter=A --name-only` shows no `.z-ai-config`, no `.env`, no `cookies/`, no browser-profile files ever added.++## 5. Rules carried into v0.5 implementation++1. **Never import the SDK (or provider config) in a client component.** All provider calls stay in `/api/**` routes with `runtime = 'nodejs'`.+2. **Every AI route keeps the try/catch → `{ error }` 502 pattern** — no stack traces in responses, no `err.message` passthrough (provider errors can embed the URL/key material), no server crash.+3. **v0.5 provider abstraction (`src/lib/ai/`)** centralizes: config resolution (`ZAI_BASE_URL`/`ZAI_API_KEY` env override → `.z-ai-config` file → null = provider absent), capability probing (`hasText()`, `hasImage()`, `hasVision()`, …), and a single place to add rate limits + AIUsage accounting. Routes ask for a provider; if absent → structured `{ error: 'AI provider not configured', code: 'NO_PROVIDER' }` that the UI turns into an actionable message.+4. Client-side feature detection: `GET /api/ai/capabilities` (public, no secrets — just boolean flags) so panels can show "requires server AI provider" states before the user tries.+5. Deterministic local fallbacks (palette, layout, basic assistant replies) keep the editor useful with zero provider config.diff --git a/research/CANVA-V05-RESEARCH.md b/research/CANVA-V05-RESEARCH.mdnew file mode 100644index 0000000..6fc1412--- /dev/null+++ b/research/CANVA-V05-RESEARCH.md@@ -0,0 +1,75 @@+# Canva v0.5 Research — Fresh Pass (September 2026)++> Sources: live stealth-browser pass over canva.com (captures in `research/fresh-capture-v05/` — `magic-layers.json`, `page-transitions-help.json`, `comments-help2.json`, `video-help.json`, `canva-ai.json` + screenshots), plus the v0.4 capture archive (`research/fresh-capture/`). Focus: the four v0.5 pillars — Magic Layers, animations, collaboration/comments, video export.++## 1. Magic Layers (canva.com/magic-layers — "Let there be layers")++Fresh capture confirms the current product positioning and workflow:++- **Tagline**: "Turn your flat design into an editable layout with Magic Layers" (Beta, premium AI tool, usage-counted per month, shared with other premium AI tools).+- **Primary use case** explicitly called out: *"Finally, the freedom to edit and control your **AI-generated designs**"* — i.e., the #1 input is a generated flat image that the user then wants to tweak.+- **Steps shown on the page**: ① "Start with your flat design — Upload your flat design, and Magic Layers instantly transforms it into a layout you can **select, move, and edit**." ② Edit your design elements → "Polish, then publish anywhere". ③ "Fine-tune the details — **Fix any element**: move and tweak them however you like; **Change colors** — go from off-white to on-brand in seconds; **Edit text directly** — fix the typo, change the font." ④ "No more do-overs — don't regenerate your design to change one element."+- **FAQ facts**: works on flat images (file-type guidance in FAQ); tied to their AI image generators; also reachable through the AI assistant; metered per use.+- **UI language**: outcomes are always expressed as *native editing capabilities* (select / move / recolor / retype), never "regions". The promise is a real layer stack.++### Realistic reproduction in Canvix (what we build)+A vision-model pipeline that produces **native editable elements**, honestly graded:+1. **Upload** (or pick an AI-generated image) → normalize size, cap at 1280px longest edge for analysis.+2. **Analyze** server-side with the vision model: return strict JSON — `background` (color/gradient or photo), `text regions` (content, approx color, approx font size weight, bounds), `image/photo regions` (bounds, subject), `shape/decoration regions` (bounds, approx color, shape kind), each with **confidence** 0–1 and layer order.+3. **Reconstruct** client-side into real Canvix elements: text → `TextElement` (measured to fit bounds, color from region); photo regions → `ImageElement` cropped from the source bitmap (canvas crop); shapes → `ShapeElement` with classified kind; background → page background (solid/gradient) or full-bleed image.+4. **Confidence UX**: low-confidence regions are inserted but flagged (amber outline in a review step) and can be discarded; the pipeline never *claims* perfect parity — the source image is preserved, and a "swap to original region" affordance exists via element metadata.++This is a genuinely editable output — not a fake. Limitations (documented in-product): complex illustrations are approximated by cropped image regions; exact fonts can't be recovered (mapped to closest family from our 63-font library); overlapped text may merge into one region.++## 2. Animations & page transitions (help: "Use page transitions", "Apply, change, or remove animations")++- **Entry points**: toolbar **Animate** button opens a side panel with **tabs: Page / Element / Text** (text boxes get a dedicated tab). Page **transitions** are applied from *between* page thumbnails ("hover between page thumbnails → Add transition"), and the chosen transition shows as an **icon between pages**.+- **Element animations**: hover to preview, click to apply; **speed presets Slow / Medium / Fast**; premium library tagged "Try Canva Pro"; `None` removes. "Create an Animation" = custom drag-to-path (out of scope for Canvix v0.5 — documented as limitation).+- **Page transitions**: duration **0.1–2.5 s** slider (+ number field), **direction** options depending on style; changing = click the icon between pages.+- **Sharing animated designs**: "download as **videos or GIFs**" — animations and transitions must both survive into video export.+- **Magic Animate**: one-click "instantly enhances your designs with sleek animations and seamless transitions" — a per-page auto-assign pass we can reproduce deterministically (headline → Rise, body → Fade, images → Pan/Zoom, background stays; page transition → Fade).+- **Reduce motion** accessibility setting — playback-only, doesn't affect export. Worth copying (cheap, inclusive).+- Element animation ordering ("appear on click", click-order list) is presentation-specific; Canvix v0.5 keeps time-based ordering (delay) — documented difference.++**Canvix v0.5 model** (independent of Konva, pure functions of time):+`element.animation = { kind: fade|rise|pan|pop|wipe|zoom|rotate|breathe, duration, delay, easing, direction? }`+`page.transition = { kind: none|fade|slide|morph, duration }`+Playback + video export both consume `animateElement(el, t)` / transition timing. Static exports (PNG/JPG/PDF/SVG) ignore it entirely.++## 3. Comments (help: "Add, delete, and resolve comments")++- **Anchoring**: comments attach to **elements, text, or the page itself**; while collaborating they appear as **floating badges with the commenter's initials or profile photo** (docs highlight instead).+- **Adding**: select element/page → **Add comment** icon in the floating toolbar → type → Send.+- **Threads**: formatting (bold/italic/strike/quote/list/hyperlink), **replies**, **resolve / unresolve**, edit/delete own, **react** to a comment, **share links to a comment**, hide/unhide all.+- **Panel**: comment icon at the top of the editor → filter **All / For you (tagged)** / **Current page**; unread state and sorting.+- Anchors keep their position when the design is resized (Canva remaps to the element anchor; free-floating pins track page coords).++**Canvix v0.5**: pins anchored to page coords + optional `elementId`; when the anchored element moves, the pin follows (element-relative anchor offset); panel with All/Resolved filters + unread badge; initials avatar with the participant color; resolve/reopen/reply/delete-own. Markdown formatting limited to plain text v1 (documented).++## 4. Collaboration / multiplayer++From the v0.4 pass + known Canva behavior (canva.com collaboration pages redirect internationally, so summarized from editor behavior):+- Presence = **stacked avatars in the top bar** (click → collaborator list), live **colored cursors with name tags** on canvas, live selection outlines in the collaborator's color, element "being dragged by X" state.+- No-refresh propagation of every edit (moves, text typing, adds/deletes, page changes); offline indicator + auto-reconnect; comments are the review layer on top.+- Canva links: "anyone with the link can view/edit" — no login wall for basic collab.++## 5. Video export (help: "Download videos")++- MP4 is the headline download format for animated designs (also GIF for animations); export dialog communicates **render progress** and where the file renders (Canva renders server-side; Canvix renders locally in-browser).+- Animated designs export with their **element animations and page transitions baked into the timeline**.++## 6. AI Assistant 2.0 (canva.com/canva-ai — "Canva AI 2.0")++Fresh capture of `/canva-ai/`: positioned as one assistant that **acts on the design** ("design, writing, and creative tools" in one place); deep-linked from Magic Layers FAQ as the host surface for Magic Layers ("Can I access Magic Layers through my AI assistant tool?" → yes). Confirms the v0.5 direction: assistant = design-aware operator returning **structured actions**, not just chat.++## 7. Conclusions for the Canvix v0.5 build++| Canva capability | Canvix v0.5 scope | Honest gap |+|---|---|---|+| Magic Layers | VLM region pipeline → native editable elements + confidence flags | no exact font recovery; illustration → cropped image regions |+| Animate (panel, presets, speed) | 8 element kinds, durations/delay/easing, Magic-Animate auto pass, reduce-motion | no custom drag-path animations |+| Page transitions | none/fade/slide/morph, 0.1–2.5 s, icon between thumbnails | no 3D/overlay transitions |+| Comments | full threads, resolve, unread, anchored pins | no rich-text formatting, no @-mentions |+| Collaboration | live presence, cursors, selections, ops sync, reconnect | ~1 s SSE latency vs Canva's ws; no offline merge (last-write-wins per element) |+| Video/MP4 export | real in-browser frame renderer + MediaRecorder (MP4 where the browser can, else WebM) | server-side MP4/Ffmpeg not available on the deploy target; format depends on browser codecs |+| SVG export | full vector document export | text wrapping is measured (font metrics), not layout-identical in exotic fonts |diff --git a/research/COLLABORATION-ARCHITECTURE.md b/research/COLLABORATION-ARCHITECTURE.mdnew file mode 100644index 0000000..8612f96--- /dev/null+++ b/research/COLLABORATION-ARCHITECTURE.md@@ -0,0 +1,139 @@+# Canvix v0.5.0 — Collaboration Architecture++> Decision record for real-time collaboration on the existing Next.js 16 + Zustand + Prisma/Postgres + Konva stack. Constraint that dominated every option: **the production target (Vercel serverless, or any standalone Node host via `output: "standalone"`) cannot hold persistent WebSocket connections**, and v0.5 must not regress the single-user editor's local performance.++## 1. Options compared++| Approach | Verdict | Why |+|---|---|---|+| **WebSocket server (ws / y-websocket)** | ✗ | Needs a long-lived process + connection registry. Not deployable on Vercel serverless; would split "dev works, prod doesn't". Rejecting the two-tier deployment split is a v0.5 goal. |+| **Yjs CRDT (client-embedded, any transport)** | ✗ (for v0.5) | Best-in-class offline merge, but requires converting the document model to Y structures (Y.Map/Y.Array) — a rewrite of `editor-store` persistence, undo/redo (Y undo stack ≠ our snapshot history), template seed, autosave and version snapshots. ~All 695 store lines + all element ops would need a second implementation path. Too invasive for one release. |+| **Liveblocks-style SaaS** | ✗ | External service + credential; violates self-hostable/open-source positioning. |+| **Pure polling (client asks "what changed?")** | △ | Works everywhere, but ≥1.5–2 s effective latency and constant DB load per client; poor cursor feel. |+| **SSE down + POST up, Postgres event log as source of truth (server-authoritative)** | ✓ **CHOSEN** | Deployable on Vercel (Node runtime streaming) *and* standalone; sub-second fan-out; single source of truth in Postgres (already required infra); no store rewrite — remote ops are applied through the **existing store actions**; clean reconnection semantics (`?since=<seq>`); graceful degradation to polling if a proxy kills streams. |++### Why this is still a CRDT-flavored, robust design+- The unit of replication is an **operation log** (append-only `DesignEvent` rows with a global monotonic `seq`), not whole-document PUTs. Event log = CRDT-lite: commutative per-element patches, idempotent by `eventId`, replayable from any offset.+- Element-level ops (not document-level) mean **two people editing different elements never clobber each other**. Same-element conflicts resolve last-write-wins — acceptable for v0.5, documented.+- IDs: session emitter prefixes locally-generated `uid()` ids with the actor's participant id when broadcasting, keeping cross-session ids collision-free.++## 2. Data model (Prisma, appended in v0.5)++```prisma+model DesignEvent {+ id BigInt @id @default(autoincrement()) // global seq — clients track lastSeq+ designId String+ actorId String // participant id+ kind String // op name (see §3)+ payload Json+ createdAt DateTime @default(now())+ @@index([designId, id(sort: Desc)]) // replay + tail queries+}++model Presence {+ id String @id // = participantId (client-generated)+ designId String+ name String+ color String+ cursor Json? // {page, x, y, selection?: string[]}+ lastSeen DateTime @default(now()) @updatedAt+ @@unique([designId, id]) // one live presence row per participant per design+ @@index([designId, lastSeen])+}++model Comment {+ id String @id @default(cuid())+ designId String+ pageId String+ x Float+ y Float+ elementId String? // optional element anchor+ authorId String // participant id+ authorName String+ authorColor String+ body String+ parentId String? // reply threading+ resolved Boolean @default(false)+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ @@index([designId, createdAt]) // panel listing+ @@index([designId, resolved])+}++model AIUsage { // provider accounting + abuse telemetry+ id String @id @default(cuid())+ feature String+ provider String+ ok Boolean @default(true)+ createdAt DateTime @default(now())+ @@index([createdAt])+}+```++## 3. Operation protocol (`DesignEvent.kind`)++Ops are small, explicit, and applied through existing store actions:++| kind | payload | applied via |+|---|---|---|+| `elements:update` | `{ pageId, ids, patch, eventId }` | `updateElementsLive` |+| `element:add` | `{ pageId, element }` | store batch insert (no history push for remote) |+| `element:delete` | `{ pageId, ids }` | store filter |+| `elements:reorder` | `{ pageId, orderedIds }` | store reorder |+| `page:add` / `page:delete` / `page:dup` | `{ pageId, afterId? }` | store page ops |+| `page:background` | `{ pageId, background }` | `setPageBackground` |+| `pages:replace` | `{ pages }` | full-document reconciliation (resize/translate/undo-broadcast — rare, coarse) |+| `cursor` | handled by Presence table, not the event log (high frequency, no history value) |++Emission policy (Phase 13 performance): local mutations **queue** events and flush every 400 ms batched; live drags emit throttled `elements:update` (position only) at ~120 ms; undo/redo emit `pages:replace` for correctness (undo restores snapshots — op-level undo replay is out of scope). Text typing emits debounced (600 ms) `elements:update` with the final text.++## 4. Transport++```+Client Server (Node runtime)+ │ GET /api/collab/[designId]/stream?since=0&pid=… │+ │────────────────────────────────────────────────────────▶│+ │ SSE: `data: {events:[{seq,kind,payload}…], presence:[…]}`│+ │◀────────────────── every ~800 ms poll tick ─────────────│+ │ │+ │ POST /api/collab/[designId]/events (batched ops) │+ │────────────────────────────────────────────────────────▶│+ │ POST /api/collab/[designId]/presence (heartbeat/cursor) │+ │────────────────────────────────────────────────────────▶│ every 5 s (cursor: throttled)+```++- **SSE stream** = server holds the response open; each 800 ms tick it queries events `id > lastSeq` + live presence (lastSeen < 30 s) and writes one SSE frame (only when something changed, plus a 15 s keep-alive comment). `X-Accel-Buffering: no` for proxies.+- **Reconnect**: client keeps `lastSeq`; on stream error/close → exponential backoff (0.5 s → 8 s cap) → `GET stream?since=lastSeq` → gap-free replay. Connection state surfaced in the UI (Live / Connecting / Offline badge). This also degrades to polling transparently — each reconnect is a poll.+- **Vercel**: Node runtime SSE works (streaming allowed, `maxDuration` bounded); when the function recycles the client reconnects and replays from `lastSeq` — no data loss because Postgres is the log.+- **Bun dev / standalone Node**: identical path, no special server needed.++## 5. Client architecture++```+src/lib/collab/+ identity.ts participant id/name/color (localStorage, Phase 6)+ protocol.ts TS types for ops + wire frames (shared by server & client)+ client.ts CollabSession class: SSE subscribe, emitter queue (400 ms batch),+ cursor throttle, reconnect/backoff, callback fan-out+ use-collab.ts React hook wiring CollabSession ⇄ useEditorStore:+ local store mutations → emit; remote ops → apply (suppressed re-emit)+```++- Zustand stays the **local-first** source of rendering truth; collab never blocks input (optimistic updates, sync in background).+- **Re-entry guard**: applying remote ops uses a module flag `applyingRemote` so the emitter hook doesn't echo ops back (feedback loop).+- Presence rendering: avatars stack (TopBar), colored cursors + name tags (canvas overlay layer in Konva, non-interactive), collaborator selection outlines, "edited by X" element halo (subtle, 1.2 s decay).+- A large collaborative doc cannot flood Zustand: remote `elements:update` applies as a **single** store `set` per batch (already the case — patch-based, no per-element sets).++## 6. Authorization & abuse (details in V05-SECURITY-AUDIT.md)++- Anyone with the design id can join as viewer/editor (Canva "link = edit" model, matching the account-less app). No privilege escalation surface exists beyond that (no accounts yet).+- Hard caps: event payload ≤ 256 KB (reject bigger), ≤ 20 events per flush, presence rows GC'd (lastSeen > 30 s = offline; rows > 24 h deleted lazily), DesignEvent log pruned to the last 500 per design (background on stream tick), participant name ≤ 40 chars, comments ≤ 2000 chars.+- All op payloads are **validated and clamped server-side** before persisting (ids exist? page belongs to design? numbers finite? colors sanitized?). Malformed events are dropped, never crash the stream.++## 7. What we consciously defer (v0.6+)++- Yjs-grade offline merge & conflict resolution (needs document-model migration).+- Element-level undo broadcast (currently undo syncs via `pages:replace`).+- @-mentions, comment reactions, per-comment deep links (needs stable share URLs + accounts).+- WebSocket transport for sub-100 ms latency (only worth it with a persistent host).+- Server-side video rendering farm; FFmpeg worker queue.diff --git a/research/V05-CURRENT-STATE.md b/research/V05-CURRENT-STATE.mdnew file mode 100644index 0000000..703be35--- /dev/null+++ b/research/V05-CURRENT-STATE.md@@ -0,0 +1,134 @@+# Canvix v0.5.0 — Current-State Audit++> Audited at `main` = `bc78723` (`feat(v0.4): the Magic Suite — AI editing, Magic Resize, Translate, Postgres infra`), working tree clean. This document is the ground truth the v0.5 implementation was planned against.++## 1. Overall architecture++| Layer | Technology | Notes |+|---|---|---|+| Framework | Next.js 16 (App Router), React 19, TypeScript | `output: "standalone"`; `reactStrictMode: false`; build script copies `static` + `public` into `.next/standalone` |+| Styling | Tailwind CSS 4 + shadcn/radix primitives | Dark editor chrome (`#0F1015` / `#16181D`), teal-purple accents (`#00C4CC`, `#7630D7`) |+| State | Zustand (`useEditorStore` = editor doc + history; `useAppStore` = view routing) | Single global store per tab; no persistence middleware |+| Canvas | Konva 10 + react-konva 19 | `CanvasStage` renders `PageData.elements` via `element-node.tsx` |+| DB | PostgreSQL via Prisma 6 (`@prisma/client`) | `src/lib/db.ts` — global singleton client, dev `log: ['query']` |+| AI | `z-ai-web-dev-sdk` 0.0.18 (server-only, dynamic import per route) | See `AI-PROVIDER-AUDIT.md` |+| Export | Client-side: Konva `stage.toDataURL` (PNG/JPG), jsPDF (multi-page PDF) | `ExportDialog.tsx` + `canvas/canvas-bridge.ts` |+| Dev runtime | `bun` (dev server, seed); embedded PG 18 on `localhost:5433` (gitignored `tools/`) | Dev server must start via `scripts/run-dev.sh` (forces correct `DATABASE_URL` because the sandbox shell injects a stale `file:` URL) |++## 2. Frontend / editor architecture++- **View routing is client-side**: `app/page.tsx` renders `<Landing>`, `<Dashboard>` or `<Editor>` from `useAppStore.view`. There is exactly one Next route; everything else is state. Deep links do not exist (no `/design/[id]` URL) — relevant for collaboration links (v0.5 adds `?design=` / `?d=` URL params).+- **Editor composition** (`src/components/editor/Editor.tsx`, 419 lines): `TopBar` (menus: File / Resize / Translate / Share / Export / Save), `LeftRail` (11 panels) → panel `aside` (desktop 320px sidebar / mobile overlay), `CanvasStage` (dynamic, ssr:false) + `PageBar` + `ZoomControls`, `PreviewOverlay`, `CropDialog`, mobile contextual `ContextToolbar`, keyboard-shortcut dialog.+- **Panels** (`panels/`): Templates, Elements, Text, Brand, Uploads, Photos, Tools, Projects, Apps, Background, Layers. Apps registry adds slide-out apps (Assistant, Magic Write, AI Image, Charts, QR, Palette, Icons, Stickers, Lorem).+- **Store** (`src/store/editor-store.ts`, 695 lines): holds `designId, designName, width, height, pages: PageData[], currentPage, selectedIds, zoom, panel, past/future (undo), dirty/saving/savedAt, version (mutation counter), editingMode, previewOpen, tool/draw*, brand, showRulers/manualGuides, versions, cropTargetId`.+ - Undo = full-page snapshots (`HISTORY_LIMIT = 60`), `pushHistory()` before every committed mutation; "live" ops (`updateElementsLive`) mutate without history (drag, nudge).+ - `version` counter increments on every content mutation → drives debounced autosave in `Editor.tsx` (1.6 s debounce, PUT `/api/designs/:id`, thumbnail via `canvasBridge.captureThumbnail`).+ - `loadDesign()` fetches server versions with localStorage fallback; `resizeDesign` uses `magicRelayoutPages` (smart re-layout); `translateTexts` batch-updates texts across all pages incl. group children.++## 3. Document model (`src/lib/types.ts`)++- `PageData { id, background: Background, elements: AnyElement[] }`; `DesignSnapshot { name, width, height, pages }` = exactly what is stored in the DB `pages` Json column.+- Element types: `text, rect, ellipse, triangle, star, line, path, stroke, image, sticker, group` — with per-type props (gradients, shadows, effects, filters, flip, cornerRadius, pathData in 100×100 box, stroke points, group children at page coords).+- `uid()` = prefix + timestamp + counter + random. Fine for single-user; **not collision-safe across concurrent collaborators** → v0.5 session emitter must use a richer id (or keep uid but prefix with actor id) for cross-session safety.+- No `animation` field yet; no comment/anchor concept yet.++## 4. API architecture++All routes under `src/app/api/`:++| Route | Methods | Purpose |+|---|---|---|+| `/api/designs` | GET (list, `?trash=1`), POST (create) | dashboard list/create |+| `/api/designs/[id]` | GET, PUT, DELETE (soft; `?permanent=1`) | CRUD + trash |+| `/api/designs/[id]/versions` | GET, POST | version history (prune 30) |+| `/api/designs/[id]/restore` | POST | restore version snapshot |+| `/api/versions/[id]` | DELETE | delete one version |+| `/api/templates` | GET | template library |+| `/api/photos/search` | POST | web photo search (AI provider) |+| `/api/ai/write` | POST | Magic Write |+| `/api/ai/image` | POST | AI image generation |+| `/api/ai/image-edit` | POST | BG-erase / enhance (provider edit) |+| `/api/ai/translate` | POST | batch translate |+| `/api/ai/assistant` | POST | chat assistant + suggested actions |++Conventions: `export const runtime = 'nodejs'`, `maxDuration = 60`, explicit body validation/clamping, JSON `{ error }` responses, `console.error('[route]')` + 502 on provider failure. No auth, no rate limiting (v0.5 adds rate limits on AI + collab routes).++## 5. Prisma / PostgreSQL schema++- `datasource db { provider = "postgresql", url = env("DATABASE_URL") }`.+- `Design`: cuid id, name, width/height, `pages Json` (native jsonb, default `"[]""`), thumbnail?, `source` (blank/template:/duplicate:/resize:), `deletedAt?` (soft delete), `versions[]`, timestamps.+- `DesignVersion`: cuid, designId FK cascade, label, name, width, height, pages Json, `@@index([designId, createdAt(sort: Desc)])`.+- `Template`: cuid, unique slug, name, category, width, height, pages Json, accent.+- Local dev DB: embedded postgres 18 at `localhost:5433/canvix` (user `postgres`), started via `tools/` (gitignored); **`.env` currently points at it** — user will swap for Neon when deploying. No destructive migrations are used; `prisma db push` only.+- Seed: `prisma/seed.ts` — 21 templates across 6 categories.++## 6. Authentication model++**None.** The app is account-less and local-first: every browser sees every design via plain REST (no ownership column, no sessions). This is a deliberate v0.1–v0.4 simplification. Consequences for v0.5: collaboration must introduce a **participant identity layer** (Phase 6) without breaking the anonymous flow — collaborator = random participant id + display name + color, persisted in localStorage; no login required. Design ownership checks are documented as a known limitation (see `V05-SECURITY-AUDIT.md`).++## 7. AI routes / SDK initialization++Every AI route follows the identical pattern:++```ts+export const runtime = 'nodejs'+export const maxDuration = 60+…+const { default: ZAI } = await import('z-ai-web-dev-sdk')+const zai = await ZAI.create() // reads .z-ai-config (see audit)+const completion = await zai.chat.completions.create({ messages, thinking: { type: 'disabled' } })+```++No route reads `process.env` for keys; nothing AI-related is imported client-side. SDK capabilities used today: `chat.completions.create`, `images.generations.create`, `images.generations.edit` (quirk: needs `images: [{ url }]` at runtime), `images.search.create`. Unused but available: `chat.completions.createVision` (vision, `/chat/completions/vision`), `audio.tts/asr`, `video.generations`, async jobs. v0.5 Magic Layers uses `createVision` (already in the SDK — no new dependency).++## 8. Environment variables++| Var | Where | Value |+|---|---|---|+| `DATABASE_URL` | `.env` (gitignored), `.env.example` (committed template) | local `postgresql://postgres:postgres@localhost:5433/canvix` |+| AI provider credentials | **not env vars** — `.z-ai-config` JSON at cwd → `~` → `/etc` (gitignored) | `{ baseUrl, apiKey, chatId?, userId?, token? }` |++No `NEXT_PUBLIC_*` secrets anywhere (only Google Fonts links in `layout.tsx`). `.gitignore` covers `.env*` (except `.env.example`), `.z-ai-config`, `tools/`, `db/`, `research/*` raw captures, `scripts/`, `tests/`.++## 9. Vercel configuration++No `vercel.json`, no `.vercel/` committed. `output: "standalone"` + custom start script (`bun .next/standalone/server.js`) is geared for self-hosting. Implication for v0.5 collaboration: **no persistent WebSocket server on Vercel serverless** → SSE (streaming Node runtime) + short-poll fallback is the deployable choice (see `COLLABORATION-ARCHITECTURE.md`). `maxDuration = 60` on AI routes is Vercel-friendly.++## 10. Storage++- Design documents + versions + templates: Postgres jsonb.+- Uploaded images / AI images: stored **inline in the document** as dataURLs inside `pages` Json (no file storage). Thumbnails: small dataURL in `Design.thumbnail`.+- Brand kit: localStorage. Versions: Postgres + localStorage mirror.+- No S3/blob storage anywhere — keeps the app zero-config; large images bloat the document (v0.5 performance pass adds image downscaling before embed; still no external storage).++## 11. Version history & autosave++- Autosave: `Editor.tsx` debounces 1.6 s after `version` bumps → PUT `/api/designs/:id` (+thumbnail); also saves on unmount. `dirty/saving/savedAt` power the TopBar save state.+- Versions: `saveVersion()` (Ctrl+Alt+S) POSTs a full snapshot; server prunes to 30; restore applies pages back into the store (undoable via pushHistory).++## 12. Existing realtime-related code++**None.** No WebSocket, SSE, polling, Yjs/CRDT, presence, or comment code exists anywhere in the repo (grep-verified). The editor is strictly single-user, single-tab. `uid()` collision risk and full-document PUT autosave are the two integration points v0.5 collaboration must respect.++## 13. Editor collaboration assumptions baked into v0.4++- One Zustand store owns the truth; history = whole-page snapshots; autosave = whole-document PUT. A naive "sync everything" approach would clobber concurrent edits → v0.5 adds an **op-based event layer** that applies remote ops through the same store actions (`updateElementsLive`, `addElement`, …) so undo/history stay local and rendering stays Konva-fast.+- Elements are identified by `id`; page index is mutable (add/delete/duplicate reorder pages) → remote page ops must reference page ids, not indices, when possible.++## 14. Export architecture++- `canvas-bridge.ts`: `captureStage({ pixelScale, mimeType, quality })` — flips to the target page, waits 260 ms, `stage.toDataURL`, restores page. `captureThumbnail` = 320px JPEG. `canvasBridge` exposes live stage refs.+- `ExportDialog.tsx`: PNG/JPG (1×/2×/3×, current page or all pages as sequential downloads) + PDF (jsPDF, all pages, px units). `PreviewOverlay` = paged slideshow via `preview-stage.tsx` (Konva `Image` of captured pages — a natural seam for v0.5 animation playback & video export).+- No SVG export, no video export today.++## 15. Tests / E2E infrastructure++No unit tests. QA so far = manual scripted browser passes (Playwright-driven by the dev agent) + `bun run lint` + `bun run build`. The v0.5 E2E matrix (Phase 17) follows the same approach: scripted two-browser-session collaboration test, curl API checks, console-error watch, production build.++## 16. Known quirks carried into v0.5 planning++1. Sandbox shell injects stale `DATABASE_URL=file:...` — all db commands need explicit `DATABASE_URL` prefix; dev server runs via `scripts/run-dev.sh`.+2. `next.config.ts` sets `typescript.ignoreBuildErrors: true` (v0.4 ships with it) — v0.5 must still keep 0 `tsc` errors per the QA gate.+3. `uid()` is not globally unique across tabs (timestamp+counter+5 rand chars).+4. Photo search returns remote URLs that are hot-linked (CORS-dependent) — image fetch for exports relies on `crossOrigin` handling in Konva.+5. Editor URL never changes (single `/` route) — collaboration deep links need new URL param handling.diff --git a/research/V05-SECURITY-AUDIT.md b/research/V05-SECURITY-AUDIT.mdnew file mode 100644index 0000000..30479b3--- /dev/null+++ b/research/V05-SECURITY-AUDIT.md@@ -0,0 +1,82 @@+# Canvix v0.5.0 — Security Audit++> Full security review performed over the v0.5.0 feature surface: Magic Layers, collaboration (SSE + event log), comments, SVG/video export, AI routes and the provider abstraction. Each section lists the risk, the mitigation shipped in this release, and residual limitations.++## 1. Secrets & credential exposure++**Finding: no provider credentials can reach the browser.**++- All provider calls live in `/api/**` routes with `runtime = 'nodejs'`; the SDK is imported server-side only (grep-verified: no client component imports `z-ai-web-dev-sdk`).+- v0.5 centralizes configuration in `src/lib/ai/provider.ts`: `ZAI_BASE_URL`/`ZAI_API_KEY` env vars (deploy targets without a writable FS) → `.z-ai-config` file (cwd → `~` → `/etc`). The file is gitignored; git history contains no `apiKey` values (re-verified for v0.5: `git log --all -S 'apiKey'` shows no credential commits).+- `NEXT_PUBLIC_*` env vars: none exist (only Google Fonts links in `layout.tsx`).+- Error responses are structured `{ error, code? }` — never stack traces, never `err.message` passthrough (provider errors can embed URLs/keys, so they are logged server-side only).+- `/api/ai/capabilities` (public) exposes only booleans — which features exist, never config or keys.+- `.gitignore` covers: `.env*` (except `.env.example`), `.z-ai-config`, `/tools/`, `/scripts/`, `research/*` raw captures, `worklog.md`, `download/`, `db/`.++## 2. AI prompt injection & malicious input++- **Magic Layers** image input: dataURL-only (regex-validated `^data:image/(png|jpeg|webp);base64,`), ≤ 8 MB. The model's JSON reply passes through `validateAnalysis()` — every field is clamped/sanitized (bounds 0..1, hex colors, font classes whitelisted, text control-chars stripped, ≤ 40 regions, ≤ 400 chars). The model never dictates element creation directly; the client reconstructs from the validated schema.+- **Assistant 2.0**: user message ≤ 1500 chars, design context is server-side summarized (≤ 80 elements, text ≤ 60 chars each). Model actions pass `sanitizeActions()` — ids, patches, colors, sizes all validated/clamped; unknown action types are dropped. The client re-validates via `applyDesignAction` (`resolveIds` drops unknown ids; hex-validated colors; clamped numeric ranges). **AI output is never trusted raw.**+- **Translate / Write / Photo search**: bounded input sizes, whitelists for sizes/languages, JSON-parsed with bracket-walking parsers.+- Prompt-injection residuals: a malicious image/text can still *influence* model output (inherent), but the blast radius is a validated design mutation (undoable) — not code execution, not exfiltration (routes never return secrets or fetch URLs from model output except whitelisted image sizes).++## 3. Malicious uploaded files++- Client-side: file type sniff (`image/*`), 25 MB cap, canvas re-encode before embed (also strips any EXIF/metadata — the pixel data is re-drawn).+- Magic Layers: normalized to ≤ 1280px JPEG before transport; server re-validates the dataURL prefix and size.+- Image crops in reconstruction are canvas-generated JPEGs (never raw file bytes passthrough).+- Video export renders only from the in-memory document (no file input path).++## 4. SVG injection / XSS++`src/lib/svg-export.ts` treats all document data as hostile:++- **All text content is XML-escaped** (`& < > " '`).+- **Path data whitelisted** to path commands + numbers (`sanitizePathData` strips everything else).+- **Image hrefs**: only `data:image/*` and `https?://` survive (`safeHref`); `javascript:` and relative URLs are dropped.+- No `<script>`, no event handlers, no `foreignObject`, no external entity references are emitted anywhere in the serializer.+- Gradients/filters reference only locally-generated ids (`grad#`, `shadow#`, `clip#` counters).++## 5. Collaboration attack surface++- **Payload caps**: ops ≤ 256 KB (`validateOpPayload`), ≤ 20 events per flush, ≤ 500-array items, ≤ 12 object depth, finite-number checks on numeric keys — malformed events are **dropped and reported**, never crash the stream.+- **Event kinds are whitelisted** (`OP_KINDS`); `design:rename` names clamped to 80 chars.+- **Presence**: participant ids/names sanitized (`[a-zA-Z0-9_-]` ≤ 40 / Unicode letters+digits ≤ 40), colors hex-validated, cursors must be finite numbers with bounded selections; rows GC'd at 24 h + 30 s offline expiry.+- **Authorization model**: Canva-like "link = edit". Anyone with the design id can join and edit — a documented, deliberate choice for the account-less app (same as v0.4's open REST API). No privilege escalation exists beyond that (no accounts, no roles). Deep links (`/?design=`) validate the id shape server-side (fetch 404s → stays on landing).+- **Resource abuse**: SSE streams are bounded (`maxDuration = 300`, keepalive comments), event log pruned to 500 per design, presence rows deleted lazily.+- Residual: the SSE stream endpoint does not rate-limit *connection* count (per-IP event POSTs are unbounded too, but payload-capped); acceptable for self-hosted, flagged for a future reverse-proxy/limits pass.++## 6. Comments++- Body ≤ 2000 chars with control characters stripped; author identity sanitized (name Unicode letters/digits ≤ 40, color hex); pageId validated against the design's actual pages server-side; replies inherit the thread anchor (no arbitrary coordinates).+- **Resolve/reopen**: open to any participant (Canva parity). **Edit/delete**: author-only (`actorId` match, 403 otherwise). Thread delete cascades replies.+- Unread tracking is localStorage-only (client-side, no server trust).++## 7. SSRF++- Server-side fetches happen only inside the SDK (provider baseUrl — operator-controlled) and `photos/search` (SDK image search). No route accepts a client-supplied URL to fetch server-side. Image-edit routes accept `https?://` image URLs but pass them to the provider (not fetched by Canvix itself); no local-file or internal-network URL handling exists.++## 8. Rate limiting & API abuse++- AI routes: per-IP sliding windows via `withProvider` — write 20/min, image 12/min, image-edit 12/min, translate 15/min, assistant 20/min, magic-layers 10/min, search 30/min. 429s include `Retry-After`.+- `AIUsage` rows record every provider call (feature, provider, ok) for abuse telemetry.+- Collab POST/presence routes are unthrottled but payload-capped (above); design CRUD remains as open as v0.4 (documented).+- Oversized uploads: images 25 MB client-side + 8 MB analysis cap; event payloads 256 KB; comments 2 KB.++## 9. Generated content & ownership++- Designs have no owner column (account-less model, carried from v0.4) — any visitor can PUT/trash/restore any design. **Known limitation, documented in README and COLLABORATION-ARCHITECTURE.md §6**; the identity layer added in v0.5 (participant ids) is the migration path for per-user ownership in a future release.+- AI-generated images enter the document as ordinary elements; no watermarking or provenance beyond `magicLayer` metadata.++## 10. Verification checklist++| Check | Result |+|---|---|+| API keys in client bundles | none (server-only SDK imports; capabilities route is booleans) |+| `.env` / `.z-ai-config` tracked in git | no (gitignore + history scan) |+| SVG output escaping | escaped text, whitelisted paths, href allowlist |+| Collab payload validation | caps + type checks on every op, drops malformed |+| Comment authorization | author-only edit/delete enforced server-side |+| Rate limits | all AI routes, per-IP + Retry-After |+| Error hygiene | structured errors, no stack traces in responses |+| E2E console errors | 0 across landing/dashboard/editor/collab/comments/video QA passes |diff --git a/src/app/api/ai/assistant/route.ts b/src/app/api/ai/assistant/route.tsindex e0c3eb1..b828cb3 100644--- a/src/app/api/ai/assistant/route.ts+++ b/src/app/api/ai/assistant/route.ts@@ -1,4 +1,5 @@import { NextRequest, NextResponse } from 'next/server'+import { withProvider } from '@/lib/ai/provider'export const runtime = 'nodejs'export const maxDuration = 60@@ -8,36 +9,75 @@ interface ChatMessage {content: string}+/** Compact design context sent by the client (already summarized). */+interface DesignContext {+ name?: string+ width?: number+ height?: number+ templateType?: string+ pageCount?: number+ currentPageIndex?: number+ selectedIds?: string[]+ /** summarized elements of the current page */+ elements?: {+ id: string+ type: string+ x?: number+ y?: number+ width?: number+ height?: number+ text?: string+ fill?: string+ fontSize?: number+ bold?: boolean+ fontFamily?: string+ name?: string+ locked?: boolean+ }[]+ colorsInUse?: string[]+ fontsInUse?: string[]+}+interface AssistantBody {message?: stringhistory?: ChatMessage[]- design?: {- name?: string- width?: number- height?: number- pageCount?: number- currentPageElements?: number- textContents?: string[]- }+ design?: DesignContext}-type AssistantAction =- | { type: 'addText'; text: string; fontSize?: number; bold?: boolean }+/** DesignAction — structured, validated editor mutations (v0.5 Assistant 2.0). */+export type DesignAction =+ | { type: 'addText'; text: string; fontSize?: number; bold?: boolean; color?: string; align?: string; width?: number; y?: 'top' | 'center' | 'bottom' }+ | { type: 'updateElements'; ids: string[]; patch: Record<string, unknown> }+ | { type: 'deleteElements'; ids: string[] }+ | { type: 'moveElements'; ids: string[]; dx?: number; dy?: number; to?: 'top' | 'middle' | 'bottom' | 'left' | 'center' | 'right' }+ | { type: 'scaleElements'; ids: string[]; factor: number }+ | { type: 'setHeadingsColor'; color: string }+ | { type: 'setTextColor'; color: string }+ | { type: 'setFont'; fontFamily: string; targets?: 'all' | 'headings' | 'body' }+ | { type: 'setBackground'; kind: 'solid' | 'gradient'; from: string; to?: string; angle?: number }+ | { type: 'alignElements'; ids: string[]; mode: 'left' | 'cx' | 'right' | 'top' | 'cy' | 'bottom' }+ | { type: 'distributeElements'; ids: string[]; axis: 'x' | 'y' }+ | { type: 'addPage' }+ | { type: 'duplicatePage' }| { type: 'generateImage'; prompt: string }| { type: 'suggestPalette'; colors: string[] }| { type: 'translate'; language: string }+ | { type: 'magicAnimate' }+ | { type: 'magicLayout' }+ | { type: 'balanceLayout' }interface AssistantReply {reply: string- actions: AssistantAction[]+ actions: DesignAction[]}+const HEX = /^#[0-9a-fA-F]{6}$/+/** Robust JSON object extraction from an LLM reply (handles trailing junk). */function parseReply(raw: string): AssistantReply | null {const cleaned = raw.replace(/```(?:json)?/gi, '').trim()const start = cleaned.indexOf('{')if (start === -1) return null- // walk closing braces backwards — LLMs sometimes emit trailing "}"/junklet end = cleaned.lastIndexOf('}')while (end > start) {let obj: AssistantReply | null = null@@ -47,69 +87,216 @@ function parseReply(raw: string): AssistantReply | null {obj = null}if (obj && typeof obj.reply === 'string') {- const actions = Array.isArray(obj.actions) ? obj.actions : []- const valid: AssistantAction[] = []- for (const a of actions) {- if (!a || typeof a !== 'object' || typeof a.type !== 'string') continue- if (a.type === 'addText' && typeof a.text === 'string' && a.text.trim()) {- valid.push({ type: 'addText', text: a.text.slice(0, 400), fontSize: Number(a.fontSize) || undefined, bold: Boolean(a.bold) })- } else if (a.type === 'generateImage' && typeof a.prompt === 'string' && a.prompt.trim()) {- valid.push({ type: 'generateImage', prompt: a.prompt.slice(0, 400) })- } else if (a.type === 'suggestPalette' && Array.isArray(a.colors)) {- const colors = a.colors.filter((c) => typeof c === 'string' && /^#[0-9a-fA-F]{6}$/.test(c)).slice(0, 5)- if (colors.length >= 3) valid.push({ type: 'suggestPalette', colors })- } else if (a.type === 'translate' && typeof a.language === 'string' && a.language.trim()) {- valid.push({ type: 'translate', language: a.language.slice(0, 40) })- }- }- return { reply: obj.reply.slice(0, 1500), actions: valid.slice(0, 4) }+ return { reply: obj.reply.slice(0, 2000), actions: sanitizeActions(obj.actions) }}end = cleaned.lastIndexOf('}', end - 1)}return null}-/** POST /api/ai/assistant — Canva AI-style conversational design assistant. */+/** Validate + clamp every action — never trust model output raw. */+function sanitizeActions(input: unknown): DesignAction[] {+ if (!Array.isArray(input)) return []+ const out: DesignAction[] = []+ for (const a of input.slice(0, 6)) {+ if (!a || typeof a !== 'object') continue+ const act = a as Record<string, unknown>+ const type = String(act.type ?? '')+ const ids = Array.isArray(act.ids) ? act.ids.filter((i) => typeof i === 'string').slice(0, 60).map((i) => String(i).slice(0, 40)) : []++ switch (type) {+ case 'addText': {+ const text = String(act.text ?? '').slice(0, 400).trim()+ if (!text) break+ out.push({+ type: 'addText',+ text,+ fontSize: Math.min(300, Math.max(8, Number(act.fontSize) || 32)),+ bold: act.bold === true,+ color: typeof act.color === 'string' && HEX.test(act.color) ? act.color : undefined,+ align: ['left', 'center', 'right'].includes(String(act.align)) ? (String(act.align) as string) : undefined,+ width: Math.min(2000, Math.max(60, Number(act.width) || 0)) || undefined,+ y: ['top', 'center', 'bottom'].includes(String(act.y)) ? (String(act.y) as 'top' | 'center' | 'bottom') : undefined,+ })+ break+ }+ case 'updateElements': {+ if (!ids.length) break+ const patch: Record<string, unknown> = {}+ const p = (act.patch ?? {}) as Record<string, unknown>+ if (typeof p.fill === 'string' && HEX.test(p.fill)) patch.fill = p.fill+ if (typeof p.text === 'string' && p.text.length <= 400) patch.text = p.text+ if (Number.isFinite(Number(p.fontSize))) patch.fontSize = Math.min(300, Math.max(6, Number(p.fontSize)))+ if (p.bold === true || p.bold === false) patch.bold = p.bold+ if (typeof p.fontFamily === 'string' && p.fontFamily.length <= 60) patch.fontFamily = p.fontFamily+ if (Number.isFinite(Number(p.x))) patch.x = Number(p.x)+ if (Number.isFinite(Number(p.y))) patch.y = Number(p.y)+ if (Number.isFinite(Number(p.width))) patch.width = Math.max(8, Number(p.width))+ if (Number.isFinite(Number(p.height))) patch.height = Math.max(8, Number(p.height))+ if (Number.isFinite(Number(p.letterSpacing))) patch.letterSpacing = Number(p.letterSpacing)+ if (Number.isFinite(Number(p.lineHeight))) patch.lineHeight = Math.min(3, Math.max(0.8, Number(p.lineHeight)))+ if (Object.keys(patch).length) out.push({ type: 'updateElements', ids, patch })+ break+ }+ case 'deleteElements':+ if (ids.length) out.push({ type: 'deleteElements', ids })+ break+ case 'moveElements': {+ if (!ids.length) break+ const to = String(act.to ?? '')+ out.push({+ type: 'moveElements',+ ids,+ dx: Number.isFinite(Number(act.dx)) ? Number(act.dx) : undefined,+ dy: Number.isFinite(Number(act.dy)) ? Number(act.dy) : undefined,+ to: ['top', 'middle', 'bottom', 'left', 'center', 'right'].includes(to)+ ? (to as 'top' | 'middle' | 'bottom' | 'left' | 'center' | 'right')+ : undefined,+ })+ break+ }+ case 'scaleElements':+ if (ids.length && Number.isFinite(Number(act.factor)) && (Number(act.factor) > 0.1) && Number(act.factor) < 5) {+ out.push({ type: 'scaleElements', ids, factor: Number(act.factor) })+ }+ break+ case 'setHeadingsColor':+ case 'setTextColor':+ if (typeof act.color === 'string' && HEX.test(act.color)) out.push({ type, color: act.color })+ break+ case 'setFont':+ if (typeof act.fontFamily === 'string' && act.fontFamily.length <= 60) {+ const t = String(act.targets ?? 'all')+ out.push({ type: 'setFont', fontFamily: act.fontFamily, targets: (['all', 'headings', 'body'].includes(t) ? t : 'all') as 'all' | 'headings' | 'body' })+ }+ break+ case 'setBackground': {+ const kind = String(act.kind ?? 'solid')+ if (kind === 'gradient') {+ if (typeof act.from === 'string' && HEX.test(act.from) && typeof act.to === 'string' && HEX.test(act.to)) {+ out.push({ type: 'setBackground', kind: 'gradient', from: act.from, to: act.to, angle: Math.min(360, Math.max(0, Number(act.angle) || 135)) })+ }+ } else if (typeof act.from === 'string' && HEX.test(act.from)) {+ out.push({ type: 'setBackground', kind: 'solid', from: act.from })+ }+ break+ }+ case 'alignElements':+ if (ids.length && ['left', 'cx', 'right', 'top', 'cy', 'bottom'].includes(String(act.mode))) {+ out.push({ type: 'alignElements', ids, mode: String(act.mode) as 'left' | 'cx' | 'right' | 'top' | 'cy' | 'bottom' })+ }+ break+ case 'distributeElements':+ if (ids.length >= 3 && ['x', 'y'].includes(String(act.axis))) {+ out.push({ type: 'distributeElements', ids, axis: String(act.axis) as 'x' | 'y' })+ }+ break+ case 'addPage':+ case 'duplicatePage':+ case 'magicAnimate':+ case 'magicLayout':+ case 'balanceLayout':+ out.push({ type })+ break+ case 'generateImage': {+ const prompt = String(act.prompt ?? '').slice(0, 400).trim()+ if (prompt) out.push({ type: 'generateImage', prompt })+ break+ }+ case 'suggestPalette': {+ const colors = Array.isArray(act.colors)+ ? act.colors.filter((c) => typeof c === 'string' && HEX.test(c)).slice(0, 5) as string[]+ : []+ if (colors.length >= 3) out.push({ type: 'suggestPalette', colors })+ break+ }+ case 'translate': {+ const language = String(act.language ?? '').slice(0, 40).trim()+ if (language) out.push({ type: 'translate', language })+ break+ }+ default:+ break // unknown action — dropped+ }+ }+ return out.slice(0, 5)+}++/** POST /api/ai/assistant — Canva AI 2.0-style design-aware assistant. */export async function POST(req: NextRequest) {- try {- const body = (await req.json()) as AssistantBody- const message = (body.message ?? '').trim().slice(0, 1500)- if (!message) return NextResponse.json({ error: 'A message is required.' }, { status: 400 })+ const body = (await req.json().catch(() => ({}))) as AssistantBody+ const message = (body.message ?? '').trim().slice(0, 1500)+ if (!message) return NextResponse.json({ error: 'A message is required.' }, { status: 400 })+ return withProvider('assistant', req, { limit: 20, windowSec: 60 }, async (zai) => {const d = body.design ?? {}- const texts = (d.textContents ?? []).slice(0, 40).map((t) => JSON.stringify(t.slice(0, 120))).join(', ')- const designSummary = [- `Design name: ${d.name ?? 'Untitled'}`,- `Canvas: ${d.width ?? '?'}x${d.height ?? '?'}px`,- `Pages: ${d.pageCount ?? 1} (assistant sees page ${1})`,- `Elements on the current page: ${d.currentPageElements ?? 0}`,- texts ? `Text content in the design: ${texts}` : 'No text yet',+ const els = (d.elements ?? []).slice(0, 80)+ const elementSummary = els+ .map((e) => {+ const parts = [`${e.type}#${e.id}`]+ if (e.name) parts.push(`"${e.name.slice(0, 24)}"`)+ if (e.text) parts.push(`text="${e.text.slice(0, 60).replace(/\n/g, ' ')}"`)+ if (e.fill) parts.push(e.fill)+ if (e.fontSize) parts.push(`${Math.round(e.fontSize)}px`)+ if (e.bold) parts.push('bold')+ if (e.fontFamily) parts.push(e.fontFamily)+ if (Number.isFinite(e.x) && Number.isFinite(e.y)) parts.push(`@(${Math.round(e.x!)},${Math.round(e.y!)}) ${Math.round(e.width ?? 0)}x${Math.round(e.height ?? 0)}`)+ if (e.locked) parts.push('locked')+ return parts.join(' ')+ })+ .join('\n')++ const selection = (d.selectedIds ?? []).slice(0, 20)+ const designContext = [+ `Design: "${d.name ?? 'Untitled'}" — ${d.width ?? '?'}x${d.height ?? '?'}px (${d.templateType ?? 'custom'}), ${d.pageCount ?? 1} page(s), currently editing page ${(d.currentPageIndex ?? 0) + 1}.`,+ `Selected element ids: ${selection.length ? selection.join(', ') : 'none'}.`,+ `Elements on the current page (${els.length}):`,+ elementSummary || '(empty page)',+ `Colors in use: ${(d.colorsInUse ?? []).slice(0, 12).join(', ') || 'none'}`,+ `Fonts in use: ${(d.fontsInUse ?? []).slice(0, 8).join(', ') || 'none'}`,].join('\n')const system =- 'You are the Canvix AI assistant — a friendly, expert graphic-design copilot embedded in a ' +- 'design editor (similar to Canva AI). You help users ideate copy, pick colours, plan layouts, and ' +- 'improve designs. You are concise (max 120 words), warm and practical.\n' +- 'You can attach actions the app will offer as one-tap buttons. Respond ONLY with a JSON object: ' +- '{"reply": string, "actions": [{"type": "addText", "text": string, "fontSize"?: number, "bold"?: boolean} | ' +- '{"type": "generateImage", "prompt": string} | {"type": "suggestPalette", "colors": string[] (3-5 hex)} | ' +- '{"type": "translate", "language": string}]}\n' +- 'Rules: attach at most 2 actions and only when clearly useful (e.g. the user asks for a headline -> addText; ' +- 'asks for visuals -> generateImage; asks about colours -> suggestPalette). If no action applies, use an empty array. ' +- 'addText text should be short & design-ready. generateImage prompt must be a rich visual description. ' +- 'No markdown in "reply" — plain text only.'-- const history = (body.history ?? []).slice(-8)+ 'You are the Canvix AI assistant 2.0 — a design-aware copilot embedded in a graphic-design editor ' ++ '(similar to Canva AI). You understand the CURRENT design: its elements, colors, typography, layout and page size. ' ++ 'You help users improve their design through STRUCTURED EDITOR ACTIONS, not code.\n\n' ++ 'Respond ONLY with a JSON object: {"reply": string, "actions": DesignAction[]}\n\n' ++ 'reply: concise (max 90 words), plain text, warm and practical. Say what you did / will do.\n\n' ++ 'Available DesignAction types:\n' ++ '- {"type":"addText","text":str,"fontSize":px,"bold":bool,"color":"#hex","y":"top|center|bottom"} — adds a styled text box\n' ++ '- {"type":"updateElements","ids":[...],"patch":{"fill"|"text"|"fontSize"|"bold"|"fontFamily"|"x"|"y"|"width"|"height"|"lineHeight"|"letterSpacing":value}}\n' ++ '- {"type":"deleteElements","ids":[...]}\n' ++ '- {"type":"moveElements","ids":[...],"dx":px,"dy":px,"to":"top|middle|bottom|left|center|right"}\n' ++ '- {"type":"scaleElements","ids":[...],"factor":1.2}\n' ++ '- {"type":"setHeadingsColor","color":"#hex"} / {"type":"setTextColor","color":"#hex"}\n' ++ '- {"type":"setFont","fontFamily":str,"targets":"all|headings|body"}\n' ++ '- {"type":"setBackground","kind":"solid|gradient","from":"#hex","to":"#hex","angle":deg}\n' ++ '- {"type":"alignElements","ids":[...],"mode":"left|cx|right|top|cy|bottom"}\n' ++ '- {"type":"distributeElements","ids":[...],"axis":"x|y"}\n' ++ '- {"type":"addPage"} / {"type":"duplicatePage"}\n' ++ '- {"type":"generateImage","prompt":str} — generates an AI image and adds it\n' ++ '- {"type":"suggestPalette","colors":["#hex",...3-5]}\n' ++ '- {"type":"translate","language":str}\n' ++ '- {"type":"magicAnimate"} — one-click tasteful animations\n' ++ '- {"type":"balanceLayout"} / {"type":"magicLayout"} — improve spacing/alignment/balance\n\n' ++ 'RULES:\n' ++ '1. Only reference element ids that exist in the provided context. Use the ids of SELECTED elements when the user says "this/these/the title".\n' ++ '2. "Make this more modern" → setFont (heading font), maybe setTextColor + balanceLayout. "Move the title to the top" → moveElements {to:"top"} on the title id.\n' ++ '3. "Change all heading colors to purple" → setHeadingsColor. "Replace the background" → setBackground (or generateImage when they want a photo).\n' ++ '4. "Add a CTA" → addText with bold + short text. "Instagram-ready" → suggest a 1080x1350 resize + magicAnimate in the reply (resize is manual).\n' ++ '5. Create a second variation → duplicatePage + updateElements recolor on the duplicated page is NOT possible (actions apply to the current page) — explain instead.\n' ++ '6. At most 3 actions per reply, only when clearly useful. Empty array otherwise.\n' ++ '7. Never invent element ids. Never output code. Plain text in "reply".'++ const history = (body.history ?? [])+ .slice(-8).filter((m) => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string').map((m) => ({ role: m.role, content: m.content.slice(0, 1000) }))- const { default: ZAI } = await import('z-ai-web-dev-sdk')- const zai = await ZAI.create()-const completion = await zai.chat.completions.create({messages: [{ role: 'assistant', content: system },- { role: 'assistant', content: `Current design context:\n${designSummary}` },+ { role: 'assistant', content: `Current design context:\n${designContext}` },...history,{ role: 'user', content: message },],@@ -120,11 +307,8 @@ export async function POST(req: NextRequest) {const parsed = parseReply(raw)if (!parsed) {// graceful fallback: treat the whole reply as plain text- return NextResponse.json({ reply: raw.slice(0, 1200) || 'Sorry, I could not answer that. Try rephrasing.', actions: [] })+ return NextResponse.json({ reply: raw.slice(0, 1500) || 'Sorry, I could not answer that. Try rephrasing.', actions: [] })}return NextResponse.json(parsed)- } catch (err) {- console.error('[api/ai/assistant]', err)- return NextResponse.json({ error: 'The AI assistant is unavailable right now. Please try again.' }, { status: 502 })- }+ })}diff --git a/src/app/api/ai/capabilities/route.ts b/src/app/api/ai/capabilities/route.tsnew file mode 100644index 0000000..f59f188--- /dev/null+++ b/src/app/api/ai/capabilities/route.ts@@ -0,0 +1,30 @@+import { NextResponse } from 'next/server'+import { hasProvider } from '@/lib/ai/provider'++export const runtime = 'nodejs'+export const dynamic = 'force-dynamic'++/**+ * GET /api/ai/capabilities+ * Public, secret-free feature detection. Panels use these boolean flags to+ * show "requires server AI provider" states before the user tries a feature.+ * Only ever exposes which capabilities exist — never config, never keys.+ */+export async function GET() {+ const configured = hasProvider()+ return NextResponse.json({+ configured,+ capabilities: {+ magicWrite: configured,+ imageGeneration: configured,+ imageEditing: configured,+ vision: configured, // Magic Layers+ translation: configured,+ assistant: configured,+ photoSearch: configured,+ backgroundRemoval: true, // local ONNX — always available+ colorPalette: true, // local deterministic+ layoutSuggestions: true, // local deterministic+ },+ })+}diff --git a/src/app/api/ai/image-edit/route.ts b/src/app/api/ai/image-edit/route.tsindex 5de73d7..bf02a5b 100644--- a/src/app/api/ai/image-edit/route.ts+++ b/src/app/api/ai/image-edit/route.ts@@ -1,4 +1,5 @@import { NextRequest, NextResponse } from 'next/server'+import { withProvider } from '@/lib/ai/provider'export const runtime = 'nodejs'export const maxDuration = 60@@ -46,33 +47,30 @@ const MODE_PROMPTS: Record<string, string> = {/** POST /api/ai/image-edit — Canva-style AI image tools (BG remover, Magic eraser, enhance). */export async function POST(req: NextRequest) {- try {- const body = (await req.json()) as EditBody- const image = (body.image ?? '').trim()- if (!image || !/^(data:image\/|https?:\/\/)/.test(image)) {- return NextResponse.json({ error: 'A valid image is required.' }, { status: 400 })- }-- const mode = body.mode ?? 'edit'- let prompt: string- if (mode === 'erase') {- const target = (body.eraseTarget ?? body.prompt ?? '').trim().slice(0, 300)- if (!target) return NextResponse.json({ error: 'Describe what to remove.' }, { status: 400 })- prompt = `${MODE_PROMPTS.erase} Object to remove: ${target}`- } else if (mode === 'edit') {- prompt = (body.prompt ?? '').trim().slice(0, 600)- if (!prompt) return NextResponse.json({ error: 'A prompt is required.' }, { status: 400 })- } else {- prompt = MODE_PROMPTS[mode]- }+ const body = (await req.json().catch(() => ({}))) as EditBody+ const image = (body.image ?? '').trim()+ if (!image || !/^(data:image\/|https?:\/\/)/.test(image)) {+ return NextResponse.json({ error: 'A valid image is required.' }, { status: 400 })+ }- const w = Number(body.naturalWidth) || 0- const h = Number(body.naturalHeight) || 0- const size: ImgSize = w && h ? bestSize(w, h) : '1024x1024'+ const mode = body.mode ?? 'edit'+ let prompt: string+ if (mode === 'erase') {+ const target = (body.eraseTarget ?? body.prompt ?? '').trim().slice(0, 300)+ if (!target) return NextResponse.json({ error: 'Describe what to remove.' }, { status: 400 })+ prompt = `${MODE_PROMPTS.erase} Object to remove: ${target}`+ } else if (mode === 'edit') {+ prompt = (body.prompt ?? '').trim().slice(0, 600)+ if (!prompt) return NextResponse.json({ error: 'A prompt is required.' }, { status: 400 })+ } else {+ prompt = MODE_PROMPTS[mode]+ }- const { default: ZAI } = await import('z-ai-web-dev-sdk')- const zai = await ZAI.create()+ const w = Number(body.naturalWidth) || 0+ const h = Number(body.naturalHeight) || 0+ const size: ImgSize = w && h ? bestSize(w, h) : '1024x1024'+ return withProvider('image-edit', req, { limit: 12, windowSec: 60 }, async (zai) => {// NOTE: the SDK's TS type declares `image`, but the backend API requires// `images: [{ url }]` (verified — API error 1210 "must provide images").// The SDK forwards the body verbatim, so we send the correct runtime shape.@@ -89,11 +87,5 @@ export async function POST(req: NextRequest) {const [outW, outH] = size.split('x').map(Number)return NextResponse.json({ dataUrl: `data:image/png;base64,${base64}`, width: outW, height: outH })- } catch (err) {- console.error('[api/ai/image-edit]', err)- return NextResponse.json(- { error: 'AI image editing is unavailable right now. Please try again.' },- { status: 502 }- )- }+ })}diff --git a/src/app/api/ai/image/route.ts b/src/app/api/ai/image/route.tsindex 98f636a..975f2b8 100644--- a/src/app/api/ai/image/route.ts+++ b/src/app/api/ai/image/route.ts@@ -1,4 +1,5 @@import { NextRequest, NextResponse } from 'next/server'+import { withProvider } from '@/lib/ai/provider'export const runtime = 'nodejs'export const maxDuration = 60@@ -13,20 +14,17 @@ interface ImageBody {/** POST /api/ai/image — AI image generation for the canvas. Returns a PNG dataURL. */export async function POST(req: NextRequest) {- try {- const body = (await req.json()) as ImageBody- const prompt = (body.prompt ?? '').trim().slice(0, 600)- const size = (SUPPORTED_SIZES as readonly string[]).includes(body.size ?? '')- ? (body.size as ImgSize)- : '1024x1024'-- if (!prompt) {- return NextResponse.json({ error: 'A prompt is required.' }, { status: 400 })- }-- const { default: ZAI } = await import('z-ai-web-dev-sdk')- const zai = await ZAI.create()+ const body = (await req.json().catch(() => ({}))) as ImageBody+ const prompt = (body.prompt ?? '').trim().slice(0, 600)+ const size = (SUPPORTED_SIZES as readonly string[]).includes(body.size ?? '')+ ? (body.size as ImgSize)+ : '1024x1024'++ if (!prompt) {+ return NextResponse.json({ error: 'A prompt is required.' }, { status: 400 })+ }+ return withProvider('image', req, { limit: 12, windowSec: 60 }, async (zai) => {const response = await zai.images.generations.create({prompt,size,@@ -39,11 +37,5 @@ export async function POST(req: NextRequest) {const [w, h] = size.split('x').map(Number)return NextResponse.json({ dataUrl: `data:image/png;base64,${base64}`, width: w, height: h })- } catch (err) {- console.error('[api/ai/image]', err)- return NextResponse.json(- { error: 'AI image generation is unavailable right now. Please try again.' },- { status: 502 }- )- }+ })}diff --git a/src/app/api/ai/magic-layers/route.ts b/src/app/api/ai/magic-layers/route.tsnew file mode 100644index 0000000..a8b88cf--- /dev/null+++ b/src/app/api/ai/magic-layers/route.ts@@ -0,0 +1,83 @@+import { NextRequest, NextResponse } from 'next/server'+import { withProvider, VISION_MODEL } from '@/lib/ai/provider'+import { validateAnalysis } from '@/lib/magic-layers/validate'++export const runtime = 'nodejs'+export const maxDuration = 60++interface MagicLayersBody {+ image?: string // dataURL (client pre-normalizes to ≤1280px JPEG/PNG)+}++/**+ * POST /api/ai/magic-layers — Magic Layers analysis.+ *+ * Server-side vision pass over a flat design image → structured, validated+ * region JSON that the client reconstructs into native editable Canvix+ * elements. The model never dictates element creation directly; its JSON is+ * schema-validated and clamped before it leaves this route.+ */+export async function POST(req: NextRequest) {+ const body = (await req.json().catch(() => ({}))) as MagicLayersBody+ const image = (body.image ?? '').trim()++ if (!image || !/^data:image\/(png|jpeg|webp);base64,/.test(image)) {+ return NextResponse.json({ error: 'A valid PNG/JPEG/WebP image is required.' }, { status: 400 })+ }+ // payload cap — 8 MB of base64 ≈ a 6 MP normalized image (far above the 1280px client cap)+ if (image.length > 8 * 1024 * 1024) {+ return NextResponse.json({ error: 'Image too large — max ~6 MB after normalization.' }, { status: 413 })+ }++ return withProvider('magic-layers', req, { limit: 10, windowSec: 60 }, async (zai) => {+ const system =+ 'You are a precise design-image analyzer for a graphic-design editor. You look at a FLAT (raster) design ' ++ 'image and decompose it into an editable layer structure: background, text regions, photo regions, shapes ' ++ 'and decorations. You are honest: when you are unsure about a region you lower its confidence instead of guessing.\n\n' ++ 'Respond ONLY with a JSON object (no markdown) of this exact shape:\n' ++ '{"background": {"kind": "solid"|"gradient"|"photo", "from": "#RRGGBB", "to": "#RRGGBB", "angle": 0-360}, ' ++ '"regions": [ ... ], "notes": "short honest limitations you noticed"}\n\n' ++ 'Each region object:\n' ++ '- Text: {"id":"t1","type":"text","bounds":{x,y,w,h},"text":"EXACT visible text","color":"#RRGGBB","fontClass":"sans|serif|script|mono","bold":bool,"italic":bool,"fontSize":0.05,"align":"left|center|right","z":0,"confidence":0.0-1.0}\n' ++ '- Photo/illustration area: {"id":"p1","type":"photo","bounds":{...},"subject":"short description","z":1,"confidence":...}\n' ++ '- Solid shape: {"id":"s1","type":"shape","bounds":{...},"color":"#RRGGBB","shape":"rect|rounded-rect|ellipse","z":0,"confidence":...}\n' ++ '- Decoration (blob/abstract/graphic): {"id":"d1","type":"decoration","bounds":{...},"color":"#RRGGBB","shape":"ellipse","z":0,"confidence":...}\n\n' ++ 'RULES:\n' ++ '1. bounds are FRACTIONS of image width/height, all in 0..1. x,y = top-left.\n' ++ '2. fontSize is the cap height as a FRACTION of image height (a headline ≈ 0.08-0.15, body ≈ 0.03).\n' ++ '3. Copy text EXACTLY as visible, including case. Merge multi-line text of one block into one region with \\n.\n' ++ '4. z = layer order: 0 = bottom (background-adjacent). Text usually highest.\n' ++ '5. Only include regions you actually see. Do not invent or extrapolate missing text.\n' ++ '6. confidence: text-reading 0.9+ when crisp; lower for stylized/blurry text. Photo/shape bounds: 0.7+ when clear.\n' ++ '7. Prefer FEWER, well-placed regions over many overlapping ones. Max 30 regions.\n' ++ '8. background.from is the dominant colour (kind=solid); for gradient use from→to and angle in degrees (0 = →).\n' ++ '9. If the background is a photo/illustration, use kind=photo and still list visible foreground regions.\n' ++ '10. notes = one short sentence about what the reconstruction will approximate (e.g. "illustration left of title will become a cropped image region").'++ const completion = await zai.chat.completions.createVision({+ model: VISION_MODEL,+ messages: [+ { role: 'system', content: system },+ {+ role: 'user',+ content: [+ { type: 'text', text: 'Analyze this flat design image and return the region JSON now.' },+ { type: 'image_url', image_url: { url: image } },+ ],+ },+ ],+ thinking: { type: 'disabled' },+ })++ const raw = completion.choices[0]?.message?.content ?? ''+ const analysis = validateAnalysis(raw)+ if (!analysis || (analysis.regions.length === 0 && analysis.background.kind === 'solid' && !analysis.notes)) {+ return NextResponse.json(+ { error: 'The image could not be decomposed into layers. Try a cleaner, higher-resolution design.' },+ { status: 422 }+ )+ }++ return NextResponse.json(analysis)+ })+}diff --git a/src/app/api/ai/translate/route.ts b/src/app/api/ai/translate/route.tsindex b60d99e..86d1767 100644--- a/src/app/api/ai/translate/route.ts+++ b/src/app/api/ai/translate/route.ts@@ -1,4 +1,5 @@import { NextRequest, NextResponse } from 'next/server'+import { withProvider } from '@/lib/ai/provider'export const runtime = 'nodejs'export const maxDuration = 60@@ -32,31 +33,28 @@ function parseTranslations(raw: string, expected: number): string[] | null {/** POST /api/ai/translate — Canva "Translate": translate an array of design texts. */export async function POST(req: NextRequest) {- try {- const body = (await req.json()) as TranslateBody- const language = (body.language ?? '').trim()- const texts = Array.isArray(body.texts) ? body.texts.filter((t) => typeof t === 'string') : []+ const body = (await req.json().catch(() => ({}))) as TranslateBody+ const language = (body.language ?? '').trim()+ const texts = Array.isArray(body.texts) ? body.texts.filter((t) => typeof t === 'string') : []- if (!language) return NextResponse.json({ error: 'A target language is required.' }, { status: 400 })- if (!texts.length) return NextResponse.json({ error: 'No texts to translate.' }, { status: 400 })- if (texts.length > 300) return NextResponse.json({ error: 'Too many texts (max 300).' }, { status: 400 })- if (texts.some((t) => t.length > 2000)) {- return NextResponse.json({ error: 'One of the texts is too long (max 2000 chars).' }, { status: 400 })- }-- const numbered = texts.map((t, i) => `${i + 1}. ${JSON.stringify(t)}`).join('\n')- const system =- 'You are a professional design translator for a graphic-design tool. ' +- 'Translate each numbered text into the requested language, keeping the meaning, tone and style. ' +- 'Preserve line breaks, emoji and placeholders. Keep brand names, URLs and proper nouns untranslated. ' +- 'Adapt naturally (idiomatic), do not transliterate unless the language requires it. ' +- 'Respond ONLY with a JSON array of strings in the same order and same length as the input. No markdown, no numbering.'+ if (!language) return NextResponse.json({ error: 'A target language is required.' }, { status: 400 })+ if (!texts.length) return NextResponse.json({ error: 'No texts to translate.' }, { status: 400 })+ if (texts.length > 300) return NextResponse.json({ error: 'Too many texts (max 300).' }, { status: 400 })+ if (texts.some((t) => t.length > 2000)) {+ return NextResponse.json({ error: 'One of the texts is too long (max 2000 chars).' }, { status: 400 })+ }- const user = `Target language: ${language}\n\nTexts:\n${numbered}\n\nRespond with a JSON array of ${texts.length} translated strings, same order.`+ const numbered = texts.map((t, i) => `${i + 1}. ${JSON.stringify(t)}`).join('\n')+ const system =+ 'You are a professional design translator for a graphic-design tool. ' ++ 'Translate each numbered text into the requested language, keeping the meaning, tone and style. ' ++ 'Preserve line breaks, emoji and placeholders. Keep brand names, URLs and proper nouns untranslated. ' ++ 'Adapt naturally (idiomatic), do not transliterate unless the language requires it. ' ++ 'Respond ONLY with a JSON array of strings in the same order and same length as the input. No markdown, no numbering.'- const { default: ZAI } = await import('z-ai-web-dev-sdk')- const zai = await ZAI.create()+ const user = `Target language: ${language}\n\nTexts:\n${numbered}\n\nRespond with a JSON array of ${texts.length} translated strings, same order.`+ return withProvider('translate', req, { limit: 15, windowSec: 60 }, async (zai) => {const completion = await zai.chat.completions.create({messages: [{ role: 'assistant', content: system },@@ -71,8 +69,5 @@ export async function POST(req: NextRequest) {return NextResponse.json({ error: 'Translation failed — please try again.' }, { status: 502 })}return NextResponse.json({ language, translations })- } catch (err) {- console.error('[api/ai/translate]', err)- return NextResponse.json({ error: 'Translate is unavailable right now. Please try again.' }, { status: 502 })- }+ })}diff --git a/src/app/api/ai/write/route.ts b/src/app/api/ai/write/route.tsindex 43ec382..b892990 100644--- a/src/app/api/ai/write/route.ts+++ b/src/app/api/ai/write/route.ts@@ -1,4 +1,5 @@import { NextRequest, NextResponse } from 'next/server'+import { withProvider } from '@/lib/ai/provider'export const runtime = 'nodejs'export const maxDuration = 60@@ -20,19 +21,16 @@ const TONES = ['bold', 'playful', 'elegant', 'minimal', 'corporate', 'warm'] as/** POST /api/ai/write — Magic Write: generate on-brand copy variants for designs. */export async function POST(req: NextRequest) {- try {- const body = (await req.json()) as WriteBody- const prompt = (body.prompt ?? '').trim().slice(0, 500)- const kind = body.kind && KIND_HINTS[body.kind] ? body.kind : 'tagline'- const tone = TONES.includes((body.tone ?? '') as (typeof TONES)[number]) ? body.tone! : 'bold'+ const body = (await req.json().catch(() => ({}))) as WriteBody+ const prompt = (body.prompt ?? '').trim().slice(0, 500)+ const kind = body.kind && KIND_HINTS[body.kind] ? body.kind : 'tagline'+ const tone = TONES.includes((body.tone ?? '') as (typeof TONES)[number]) ? body.tone! : 'bold'- if (!prompt) {- return NextResponse.json({ error: 'A prompt is required.' }, { status: 400 })- }-- const { default: ZAI } = await import('z-ai-web-dev-sdk')- const zai = await ZAI.create()+ if (!prompt) {+ return NextResponse.json({ error: 'A prompt is required.' }, { status: 400 })+ }+ return withProvider('write', req, { limit: 20, windowSec: 60 }, async (zai) => {const completion = await zai.chat.completions.create({messages: [{@@ -60,11 +58,5 @@ export async function POST(req: NextRequest) {}return NextResponse.json({ options })- } catch (err) {- console.error('[api/ai/write]', err)- return NextResponse.json(- { error: 'Magic Write is unavailable right now. Please try again.' },- { status: 502 }- )- }+ })}diff --git a/src/app/api/collab/[designId]/events/route.ts b/src/app/api/collab/[designId]/events/route.tsnew file mode 100644index 0000000..ffb39f7--- /dev/null+++ b/src/app/api/collab/[designId]/events/route.ts@@ -0,0 +1,111 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'+import {+ MAX_EVENTS_PER_FLUSH,+ OP_KINDS,+ validateOpPayload,+ type CollabOp,+ type OpEnvelope,+} from '@/lib/collab/protocol'++export const runtime = 'nodejs'+export const maxDuration = 30++interface EventsBody {+ pid?: string+ name?: string+ color?: string+ events?: OpEnvelope[]+}++const HEX_COLOR = /^#[0-9a-fA-F]{6}$/++/**+ * POST /api/collab/[designId]/events — upstream op flush (batched).+ *+ * Every op is validated before persisting: known kind, finite numbers,+ * bounded payload size, bounded counts. Malformed events are dropped and+ * reported — never crash, never 500 on bad input.+ */+export async function POST(req: NextRequest, { params }: { params: Promise<{ designId: string }> }) {+ const { designId } = await params+ try {+ const body = (await req.json().catch(() => ({}))) as EventsBody+ const pid = (body.pid ?? '').replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 40)+ if (!pid) return NextResponse.json({ error: 'A participant id is required.' }, { status: 400 })++ const events = Array.isArray(body.events) ? body.events.slice(0, MAX_EVENTS_PER_FLUSH) : []+ if (!events.length) return NextResponse.json({ ok: true, accepted: 0 })++ // verify design exists & is not trashed+ const design = await db.design.findUnique({+ where: { id: designId },+ select: { id: true, deletedAt: true },+ })+ if (!design || design.deletedAt) {+ return NextResponse.json({ error: 'Design not found.' }, { status: 404 })+ }++ const seenEventIds = new Set<string>()+ const accepted: string[] = []+ const rejected: string[] = []++ for (const env of events) {+ if (!env || typeof env !== 'object' || !env.op || typeof env.eventId !== 'string') {+ rejected.push('malformed')+ continue+ }+ if (env.eventId.length > 80 || seenEventIds.has(env.eventId)) {+ rejected.push(env.eventId || 'bad-id')+ continue+ }+ seenEventIds.add(env.eventId)++ const op = env.op as CollabOp+ if (!OP_KINDS.has(op.kind)) {+ rejected.push(env.eventId)+ continue+ }+ // structural checks per op family+ const pageIdOk = typeof (op as { pageId?: unknown }).pageId !== 'string' || ((op as { pageId: string }).pageId.length <= 40)+ if (!pageIdOk) {+ rejected.push(env.eventId)+ continue+ }+ if (!validateOpPayload(op)) {+ rejected.push(env.eventId)+ continue+ }++ // design:rename — clamp the name+ const payload =+ op.kind === 'design:rename'+ ? { name: String((op as { name?: unknown }).name ?? '').slice(0, 80) }+ : (op as unknown)++ await db.designEvent.create({+ data: {+ designId,+ actorId: pid,+ kind: op.kind,+ payload: payload as object,+ },+ })+ accepted.push(env.eventId)+ }++ // touch presence so an active editor stays "online" even between heartbeats+ const name = (body.name ?? '').replace(/[^\p{L}\p{N} ._-]/gu, '').slice(0, 40) || 'Guest'+ const color = HEX_COLOR.test(body.color ?? '') ? body.color! : '#7630D7'+ await db.presence.upsert({+ where: { designId_id: { designId, id: pid } },+ create: { designId, id: pid, name, color },+ update: { lastSeen: new Date(), name, color },+ }).catch(() => { /* presence is best-effort */ })++ return NextResponse.json({ ok: true, accepted: accepted.length, rejected })+ } catch (err) {+ console.error('[collab/events]', err)+ return NextResponse.json({ error: 'Could not persist collaboration events.' }, { status: 502 })+ }+}diff --git a/src/app/api/collab/[designId]/presence/route.ts b/src/app/api/collab/[designId]/presence/route.tsnew file mode 100644index 0000000..eb504c5--- /dev/null+++ b/src/app/api/collab/[designId]/presence/route.ts@@ -0,0 +1,56 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'++export const runtime = 'nodejs'+export const maxDuration = 20++interface PresenceBody {+ pid?: string+ name?: string+ color?: string+ cursor?: { page?: number; x?: number; y?: number; selection?: string[] } | null+}++const HEX_COLOR = /^#[0-9a-fA-F]{6}$/++/**+ * POST /api/collab/[designId]/presence — heartbeat + cursor broadcast.+ * Called every ~5 s (heartbeat) and throttled on cursor moves.+ */+export async function POST(req: NextRequest, { params }: { params: Promise<{ designId: string }> }) {+ const { designId } = await params+ try {+ const body = (await req.json().catch(() => ({}))) as PresenceBody+ const pid = (body.pid ?? '').replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 40)+ if (!pid) return NextResponse.json({ error: 'A participant id is required.' }, { status: 400 })++ const name = (body.name ?? '').replace(/[^\p{L}\p{N} ._-]/gu, '').slice(0, 40) || 'Guest'+ const color = HEX_COLOR.test(body.color ?? '') ? body.color! : '#7630D7'++ // cursor: finite page/x/y, selection ids bounded+ let cursor: Record<string, unknown> | null = null+ if (body.cursor && typeof body.cursor === 'object') {+ const page = Number(body.cursor.page)+ const x = Number(body.cursor.x)+ const y = Number(body.cursor.y)+ const selection = Array.isArray(body.cursor.selection)+ ? body.cursor.selection.filter((s) => typeof s === 'string').slice(0, 50).map((s) => s.slice(0, 40))+ : undefined+ if (Number.isFinite(page) && Number.isFinite(x) && Number.isFinite(y)) {+ cursor = { page: Math.max(0, Math.round(page)), x, y, ...(selection ? { selection } : {}) }+ }+ }++ const { Prisma } = await import('@prisma/client')+ await db.presence.upsert({+ where: { designId_id: { designId, id: pid } },+ create: { designId, id: pid, name, color, cursor: (cursor ?? undefined) as object },+ update: { name, color, cursor: (cursor ?? Prisma.JsonNull) as object, lastSeen: new Date() },+ })++ return NextResponse.json({ ok: true })+ } catch (err) {+ console.error('[collab/presence]', err)+ return NextResponse.json({ error: 'Could not update presence.' }, { status: 502 })+ }+}diff --git a/src/app/api/collab/[designId]/stream/route.ts b/src/app/api/collab/[designId]/stream/route.tsnew file mode 100644index 0000000..ddb68db--- /dev/null+++ b/src/app/api/collab/[designId]/stream/route.ts@@ -0,0 +1,151 @@+import { NextRequest } from 'next/server'+import { db } from '@/lib/db'++export const runtime = 'nodejs'+export const dynamic = 'force-dynamic'+export const maxDuration = 300 // Vercel-friendly bounded stream duration++/**+ * GET /api/collab/[designId]/stream?since=<seq>&pid=<participantId>+ *+ * SSE downstream: every ~800 ms tick, emit new DesignEvents (id > since) ++ * live presence (lastSeen < 30 s). Postgres is the source of truth — a+ * reconnect with ?since=<lastSeq> replays gap-free. Also lazily GCs stale+ * presence rows and prunes the event log.+ */+export async function GET(req: NextRequest, { params }: { params: Promise<{ designId: string }> }) {+ const { designId } = await params+ const pid = req.nextUrl.searchParams.get('pid')?.slice(0, 40) ?? ''+ let since = Number(req.nextUrl.searchParams.get('since'))+ if (!Number.isFinite(since) || since < 0) since = 0++ // verify the design exists (404 early, keeps the stream honest)+ try {+ const design = await db.design.findUnique({ where: { id: designId }, select: { id: true } })+ if (!design) return new Response('Design not found', { status: 404 })+ } catch {+ return new Response('Database unavailable', { status: 503 })+ }++ const encoder = new TextEncoder()+ let closed = false++ const stream = new ReadableStream<Uint8Array>({+ async start(controller) {+ let lastSeq = since+ let tick = 0++ const send = (frame: unknown) => {+ if (closed) return+ try {+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(frame)}\n\n`))+ } catch {+ closed = true+ }+ }+ const comment = (text: string) => {+ if (closed) return+ try {+ controller.enqueue(encoder.encode(`: ${text}\n\n`))+ } catch {+ closed = true+ }+ }++ const close = () => {+ if (closed) return+ closed = true+ clearInterval(timer)+ try {+ controller.close()+ } catch {+ /* already closed */+ }+ }++ const pump = async () => {+ if (closed) return+ try {+ const [events, presence, maxRow, gcRows] = await Promise.all([+ db.designEvent.findMany({+ where: { designId, id: { gt: lastSeq } },+ orderBy: { id: 'asc' },+ take: 200,+ }),+ db.presence.findMany({+ where: { designId, lastSeen: { gt: new Date(Date.now() - 30_000) } },+ orderBy: { lastSeen: 'desc' },+ take: 30,+ }),+ db.designEvent.aggregate({ where: { designId }, _max: { id: true } }),+ // heartbeat GC: drop presence rows older than 24 h (cheap, throttled by tick)+ tick % 90 === 0+ ? db.presence.deleteMany({ where: { designId, lastSeen: { lt: new Date(Date.now() - 86_400_000) } } })+ : Promise.resolve({ count: 0 }),+ ])+ void gcRows++ if (events.length) {+ lastSeq = Number(events[events.length - 1].id)+ }+ const serverSeq = Number(maxRow._max.id ?? lastSeq)++ // only send a frame when something actually changed (plus periodic keepalive)+ const filteredPresence = presence.filter((p) => p.id !== pid)+ const frame = {+ events: events.map((e) => ({+ seq: Number(e.id),+ id: e.id.toString(),+ designId: e.designId,+ actorId: e.actorId,+ kind: e.kind,+ payload: e.payload,+ createdAt: e.createdAt.toISOString(),+ })),+ presence: filteredPresence.map((p) => ({+ id: p.id,+ name: p.name,+ color: p.color,+ cursor: p.cursor,+ lastSeen: p.lastSeen.toISOString(),+ })),+ seq: serverSeq,+ }+ if (events.length || tick % 20 === 0) send(frame)+ else comment('keepalive')++ // event-log pruning: keep the last 500 events per design+ if (events.length && serverSeq - lastSeq === 0 && serverSeq > 500 && tick % 30 === 0) {+ try {+ await db.designEvent.deleteMany({ where: { designId, id: { lt: serverSeq - 500 } } })+ } catch {+ /* pruning is best-effort */+ }+ }+ } catch (err) {+ console.error('[collab/stream] tick failed', err)+ comment('retry')+ }+ }++ const timer = setInterval(() => {+ tick += 1+ void pump()+ }, 800)+ req.signal.addEventListener('abort', close)++ // initial frame immediately (replay from `since`)+ comment(`open design=${designId} since=${since}`)+ await pump()+ },+ })++ return new Response(stream, {+ headers: {+ 'Content-Type': 'text/event-stream; charset=utf-8',+ 'Cache-Control': 'no-cache, no-transform',+ Connection: 'keep-alive',+ 'X-Accel-Buffering': 'no',+ },+ })+}diff --git a/src/app/api/comments/[id]/route.ts b/src/app/api/comments/[id]/route.tsnew file mode 100644index 0000000..5cec5dd--- /dev/null+++ b/src/app/api/comments/[id]/route.ts@@ -0,0 +1,82 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'++export const runtime = 'nodejs'+export const maxDuration = 30++/**+ * PATCH /api/comments/[id] — resolve / reopen / edit own comment.+ * DELETE /api/comments/[id] — delete own comment (or thread with replies).+ */+export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {+ const { id } = await params+ try {+ const body = (await req.json().catch(() => ({}))) as {+ resolved?: boolean+ body?: string+ actorId?: string+ }+ const actorId = (body.actorId ?? '').replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 40)++ const existing = await db.comment.findUnique({ where: { id } })+ if (!existing) return NextResponse.json({ error: 'Comment not found.' }, { status: 404 })++ // resolve/reopen: anyone in the design can toggle (canva parity)+ if (typeof body.resolved === 'boolean') {+ const updated = await db.comment.update({ where: { id }, data: { resolved: body.resolved } })+ await db.designEvent+ .create({ data: { designId: updated.designId, actorId, kind: 'comment:activity', payload: { commentId: id } } })+ .catch(() => { /* best-effort */ })+ return NextResponse.json({ ok: true, resolved: updated.resolved })+ }++ // body edit: only the author+ if (typeof body.body === 'string') {+ if (!actorId || actorId !== existing.authorId) {+ return NextResponse.json({ error: 'Only the author can edit this comment.' }, { status: 403 })+ }+ const text = body.body.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, '').trim().slice(0, 2000)+ if (!text) return NextResponse.json({ error: 'A comment body is required.' }, { status: 400 })+ await db.comment.update({ where: { id }, data: { body: text } })+ await db.designEvent+ .create({ data: { designId: existing.designId, actorId, kind: 'comment:activity', payload: { commentId: id } } })+ .catch(() => { /* best-effort */ })+ return NextResponse.json({ ok: true })+ }++ return NextResponse.json({ error: 'Nothing to update.' }, { status: 400 })+ } catch (err) {+ console.error('[comments PATCH]', err)+ return NextResponse.json({ error: 'Could not update the comment.' }, { status: 502 })+ }+}++export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {+ const { id } = await params+ try {+ const actorId = req.nextUrl.searchParams.get('actorId')?.replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 40) ?? ''+ const existing = await db.comment.findUnique({ where: { id } })+ if (!existing) return NextResponse.json({ error: 'Comment not found.' }, { status: 404 })++ // only the author may delete+ if (!actorId || actorId !== existing.authorId) {+ return NextResponse.json({ error: 'Only the author can delete this comment.' }, { status: 403 })+ }++ // delete the whole thread when a root comment goes+ if (existing.parentId) {+ await db.comment.delete({ where: { id } })+ } else {+ await db.comment.deleteMany({ where: { OR: [{ id }, { parentId: id }] } })+ }++ await db.designEvent+ .create({ data: { designId: existing.designId, actorId, kind: 'comment:activity', payload: { commentId: id, deleted: true } } })+ .catch(() => { /* best-effort */ })++ return NextResponse.json({ ok: true })+ } catch (err) {+ console.error('[comments DELETE]', err)+ return NextResponse.json({ error: 'Could not delete the comment.' }, { status: 502 })+ }+}diff --git a/src/app/api/designs/[id]/comments/route.ts b/src/app/api/designs/[id]/comments/route.tsnew file mode 100644index 0000000..ac4823b--- /dev/null+++ b/src/app/api/designs/[id]/comments/route.ts@@ -0,0 +1,142 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'++export const runtime = 'nodejs'+export const maxDuration = 30++const HEX_COLOR = /^#[0-9a-fA-F]{6}$/++/**+ * GET /api/designs/[id]/comments — all comment threads for a design.+ * POST — add a comment (top-level pin or reply via parentId).+ */+export async function GET(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {+ const { id } = await params+ try {+ const comments = await db.comment.findMany({+ where: { designId: id },+ orderBy: [{ createdAt: 'asc' }],+ take: 500,+ })+ return NextResponse.json(+ comments.map((c) => ({+ id: c.id,+ designId: c.designId,+ pageId: c.pageId,+ x: c.x,+ y: c.y,+ elementId: c.elementId,+ authorId: c.authorId,+ authorName: c.authorName,+ authorColor: c.authorColor,+ body: c.body,+ parentId: c.parentId,+ resolved: c.resolved,+ createdAt: c.createdAt.toISOString(),+ updatedAt: c.updatedAt.toISOString(),+ }))+ )+ } catch (err) {+ console.error('[comments GET]', err)+ return NextResponse.json({ error: 'Could not load comments.' }, { status: 502 })+ }+}++interface CommentBody {+ pageId?: string+ x?: number+ y?: number+ elementId?: string+ authorId?: string+ authorName?: string+ authorColor?: string+ body?: string+ parentId?: string+}++export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {+ const { id: designId } = await params+ try {+ const body = (await req.json().catch(() => ({}))) as CommentBody++ const text = (body.body ?? '').replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, '').trim().slice(0, 2000)+ if (!text) return NextResponse.json({ error: 'A comment body is required.' }, { status: 400 })++ const authorId = (body.authorId ?? '').replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 40)+ if (!authorId) return NextResponse.json({ error: 'An author id is required.' }, { status: 400 })+ const authorName = (body.authorName ?? '').replace(/[^\p{L}\p{N} ._-]/gu, '').slice(0, 40) || 'Guest'+ const authorColor = HEX_COLOR.test(body.authorColor ?? '') ? body.authorColor! : '#7630D7'++ // anchor: page must belong to the design+ const design = await db.design.findUnique({ where: { id: designId }, select: { pages: true } })+ if (!design) return NextResponse.json({ error: 'Design not found.' }, { status: 404 })++ const parentId = body.parentId ? String(body.parentId).slice(0, 40) : null+ let pageId = (body.pageId ?? '').slice(0, 40)+ let x = Number(body.x)+ let y = Number(body.y)+ let elementId = body.elementId ? String(body.elementId).slice(0, 40) : null++ if (parentId) {+ // reply: inherit the thread's anchor+ const parent = await db.comment.findFirst({ where: { id: parentId, designId } })+ if (!parent) return NextResponse.json({ error: 'Parent comment not found.' }, { status: 400 })+ pageId = parent.pageId+ x = parent.x+ y = parent.y+ elementId = parent.elementId+ } else {+ const pages = (design.pages as unknown as { id?: string }[]) ?? []+ if (!pageId || !pages.some((p) => p.id === pageId)) {+ return NextResponse.json({ error: 'A valid pageId is required.' }, { status: 400 })+ }+ if (!Number.isFinite(x) || !Number.isFinite(y)) {+ return NextResponse.json({ error: 'Valid anchor coordinates are required.' }, { status: 400 })+ }+ // normalized fractions 0..1+ x = Math.min(1, Math.max(0, x))+ y = Math.min(1, Math.max(0, y))+ }++ const created = await db.comment.create({+ data: {+ designId,+ pageId,+ x,+ y,+ elementId,+ authorId,+ authorName,+ authorColor,+ body: text,+ parentId,+ },+ })++ // broadcast comment activity through the collab event log so live+ // sessions refetch (kind is inert to the document model)+ await db.designEvent+ .create({ data: { designId, actorId: authorId, kind: 'comment:activity', payload: { commentId: created.id } } })+ .catch(() => { /* best-effort */ })++ return NextResponse.json({+ id: created.id,+ designId: created.designId,+ pageId: created.pageId,+ x: created.x,+ y: created.y,+ elementId: created.elementId,+ authorId: created.authorId,+ authorName: created.authorName,+ authorColor: created.authorColor,+ body: created.body,+ parentId: created.parentId,+ resolved: created.resolved,+ createdAt: created.createdAt.toISOString(),+ updatedAt: created.updatedAt.toISOString(),+ })+ } catch (err) {+ console.error('[comments POST]', err)+ return NextResponse.json({ error: 'Could not create the comment.' }, { status: 502 })+ }+}diff --git a/src/app/api/photos/search/route.ts b/src/app/api/photos/search/route.tsindex 7e70051..fa7dbeb 100644--- a/src/app/api/photos/search/route.ts+++ b/src/app/api/photos/search/route.ts@@ -1,4 +1,5 @@import { NextRequest, NextResponse } from 'next/server'+import { withProvider } from '@/lib/ai/provider'export const runtime = 'nodejs'export const maxDuration = 30@@ -10,15 +11,12 @@ interface SearchBody {/** POST /api/photos/search — runtime stock-photo search (Canva-like photo search). */export async function POST(req: NextRequest) {- try {- const body = (await req.json()) as SearchBody- const query = (body.query ?? '').trim().slice(0, 120)- if (!query) return NextResponse.json({ error: 'A query is required.' }, { status: 400 })- const count = Math.min(Math.max(Number(body.count) || 24, 1), 40)-- const { default: ZAI } = await import('z-ai-web-dev-sdk')- const zai = await ZAI.create()+ const body = (await req.json().catch(() => ({}))) as SearchBody+ const query = (body.query ?? '').trim().slice(0, 120)+ if (!query) return NextResponse.json({ error: 'A query is required.' }, { status: 400 })+ const count = Math.min(Math.max(Number(body.count) || 24, 1), 40)+ return withProvider('search', req, { limit: 30, windowSec: 60 }, async (zai) => {const response = await zai.images.search.create({ query, count })const results = (response.results ?? []).map((r) => ({@@ -30,8 +28,5 @@ export async function POST(req: NextRequest) {})).filter((r) => r.url)return NextResponse.json({ query, count: results.length, results })- } catch (err) {- console.error('[api/photos/search]', err)- return NextResponse.json({ error: 'Photo search is unavailable right now.' }, { status: 502 })- }+ })}diff --git a/src/app/page.tsx b/src/app/page.tsxindex 89a0203..394705d 100644--- a/src/app/page.tsx+++ b/src/app/page.tsx@@ -1,6 +1,7 @@'use client'import dynamic from 'next/dynamic'+import { useEffect } from 'react'import { useAppStore } from '@/store/app-store'import { Landing } from '@/components/landing/Landing'import { Dashboard } from '@/components/dashboard/Dashboard'@@ -17,6 +18,31 @@ const Editor = dynamic(() => import('@/components/editor/Editor'), {),})+/** v0.5: collaboration deep links — /?design=<id> or /?d=<id> opens the editor directly. */+function DeepLinkHandler() {+ useEffect(() => {+ try {+ const params = new URLSearchParams(window.location.search)+ const designId = params.get('design') ?? params.get('d')+ if (!designId || !/^[a-zA-Z0-9_-]{5,40}$/.test(designId)) return+ const openEditor = useAppStore.getState().openEditor+ void fetch(`/api/designs/${encodeURIComponent(designId)}`)+ .then((r) => (r.ok ? r.json() : null))+ .then((design) => {+ if (design && Array.isArray(design.pages)) {+ openEditor(design)+ }+ })+ .catch(() => {+ /* bad link — stay on landing */+ })+ } catch {+ /* SSR guard */+ }+ }, [])+ return null+}+export default function Page() {const view = useAppStore((s) => s.view)@@ -26,5 +52,10 @@ export default function Page() {if (view === 'dashboard') {return <Dashboard />}- return <Landing />+ return (+ <>+ <DeepLinkHandler />+ <Landing />+ </>+ )}diff --git a/src/components/editor/AnimatePanel.tsx b/src/components/editor/AnimatePanel.tsxnew file mode 100644index 0000000..7f840bd--- /dev/null+++ b/src/components/editor/AnimatePanel.tsx@@ -0,0 +1,405 @@+'use client'++import { useState } from 'react'+import { Sparkles, X, Zap, Play, RotateCcw, ArrowLeft, ArrowRight, ArrowUp, ArrowDown } from 'lucide-react'+import { useEditorStore } from '@/store/editor-store'+import { ANIMATION_KINDS, TRANSITION_KINDS } from '@/lib/animations'+import type { AnimationDirection, AnimationEasing, AnimationKind, AnimationSpeed, ElementAnimation, PageTransition } from '@/lib/types'+import { SPEED_PRESETS } from '@/lib/types'+import { Button } from '@/components/ui/button'+import { cn } from '@/lib/utils'+import { toast } from '@/hooks/use-toast'++const EASINGS: { id: AnimationEasing; label: string }[] = [+ { id: 'linear', label: 'Linear' },+ { id: 'easeIn', label: 'Ease in' },+ { id: 'easeOut', label: 'Ease out' },+ { id: 'easeInOut', label: 'Ease in-out' },+ { id: 'spring', label: 'Spring' },+]++const DIRECTIONS: { id: AnimationDirection; label: string; icon: typeof ArrowLeft }[] = [+ { id: 'left', label: 'From left', icon: ArrowLeft },+ { id: 'right', label: 'From right', icon: ArrowRight },+ { id: 'up', label: 'From bottom', icon: ArrowUp },+ { id: 'down', label: 'From top', icon: ArrowDown },+]++/**+ * Animate panel (canva-style side panel) — tabs: Page / Element.+ * Element tab animates the current selection; Page tab sets the page+ * transition + Magic Animate for the whole page.+ */+export function AnimatePanel({ onClose }: { onClose: () => void }) {+ const [tab, setTab] = useState<'page' | 'element'>('page')+ const selectedIds = useEditorStore((s) => s.selectedIds)+ const setElementAnimation = useEditorStore((s) => s.setElementAnimation)+ const setPageTransition = useEditorStore((s) => s.setPageTransition)+ const magicAnimateCurrentPage = useEditorStore((s) => s.magicAnimateCurrentPage)+ const clearPageAnimations = useEditorStore((s) => s.clearPageAnimations)+ const setPreviewOpen = useEditorStore((s) => s.setPreviewOpen)+ const pages = useEditorStore((s) => s.pages)+ const currentPage = useEditorStore((s) => s.currentPage)+ const [speed, setSpeed] = useState<AnimationSpeed>('medium')+ const [showSpeed, setShowSpeed] = useState(false)++ const page = pages[currentPage]+ const selection = selectedIds.length > 0+ const selectedAnim = selection+ ? page.elements.find((e) => e.id === selectedIds[0])?.animation+ : undefined+ const pageTransition = page?.transition++ const applyKind = (kind: AnimationKind) => {+ if (!selection) return+ if (kind === 'none') {+ setElementAnimation(selectedIds, null)+ return+ }+ const base: ElementAnimation = {+ kind,+ duration: SPEED_PRESETS[speed],+ delay: 0,+ easing: kind === 'pop' ? 'spring' : 'easeOut',+ direction: kind === 'rise' ? 'up' : kind === 'pan' || kind === 'wipe' ? 'left' : undefined,+ }+ setElementAnimation(selectedIds, base)+ }++ const patchAnim = (patch: Partial<ElementAnimation>) => {+ if (!selection || !selectedAnim) return+ setElementAnimation(selectedIds, { ...selectedAnim, ...patch })+ }++ const applyTransition = (kind: PageTransition['kind']) => {+ if (kind === 'none') {+ setPageTransition(null)+ return+ }+ setPageTransition({+ kind,+ duration: pageTransition?.kind === kind ? pageTransition.duration : 0.7,+ direction: pageTransition?.direction ?? 'left',+ })+ }++ return (+ <div className="flex flex-col h-full">+ <div className="flex items-center justify-between px-4 pt-4 pb-3 shrink-0">+ <h2 className="font-bold text-sm text-white flex items-center gap-2">+ <Zap size={15} className="text-[#02C0CC]" /> Animate+ </h2>+ <Button+ variant="ghost"+ size="icon"+ className="rounded-full text-white/70 hover:bg-white/10 hover:text-white h-7 w-7"+ onClick={onClose}+ aria-label="Close animate panel"+ >+ <X size={14} />+ </Button>+ </div>++ {/* tabs — canva: Page / Element / Text (we fold text into element) */}+ <div className="px-4 pb-3 shrink-0">+ <div className="flex gap-1 rounded-lg bg-white/[0.05] p-0.5">+ {(['page', 'element'] as const).map((t) => (+ <button+ key={t}+ onClick={() => setTab(t)}+ className={cn(+ 'flex-1 rounded-md px-2 py-1.5 text-[11px] font-semibold capitalize transition-colors cursor-pointer',+ tab === t ? 'bg-white/[0.12] text-white' : 'text-white/50 hover:text-white/80'+ )}+ >+ {t === 'page' ? 'Page' : 'Element'}+ </button>+ ))}+ </div>+ </div>++ <div className="flex-1 min-h-0 overflow-y-auto px-4 pb-4">+ {/* ── Page tab ─────────────────────────────── */}+ {tab === 'page' && (+ <div className="space-y-4">+ {/* Magic Animate */}+ <button+ className="w-full rounded-xl bg-gradient-to-r from-[#00C4CC] to-[#7630D7] p-[1px] cursor-pointer group"+ onClick={() => {+ magicAnimateCurrentPage(speed)+ toast({ title: 'Magic Animate applied', description: 'Every element got a fitting animation. Preview to see it play.' })+ }}+ >+ <div className="rounded-[11px] bg-[#16181D] px-3 py-3 flex items-center gap-2.5 group-hover:bg-transparent transition-colors">+ <div className="w-9 h-9 rounded-full bg-gradient-to-br from-[#00C4CC] to-[#7630D7] flex items-center justify-center shrink-0">+ <Sparkles size={16} className="text-white" />+ </div>+ <div className="text-left">+ <div className="text-[13px] font-bold text-white">Magic Animate</div>+ <div className="text-[11px] text-white/55">One click — animate everything on this page</div>+ </div>+ </div>+ </button>++ {/* speed */}+ <div>+ <div className="flex items-center justify-between mb-1.5">+ <span className="text-[11px] font-semibold text-white/60">Animation speed</span>+ <button+ className="text-[10px] text-[#02C0CC] font-semibold cursor-pointer"+ onClick={() => setShowSpeed((v) => !v)}+ >+ {showSpeed ? 'hide presets' : 'show presets'}+ </button>+ </div>+ {showSpeed && (+ <div className="grid grid-cols-3 gap-1.5 mb-2">+ {(Object.keys(SPEED_PRESETS) as AnimationSpeed[]).map((s) => (+ <button+ key={s}+ onClick={() => setSpeed(s)}+ className={cn(+ 'rounded-lg border px-2 py-1.5 text-[11px] font-semibold capitalize cursor-pointer transition-colors',+ speed === s ? 'border-[#02C0CC] bg-[#02C0CC]/10 text-white' : 'border-white/10 text-white/60 hover:border-white/25'+ )}+ >+ {s}+ </button>+ ))}+ </div>+ )}+ </div>++ {/* page transition */}+ <div>+ <span className="text-[11px] font-semibold text-white/60 block mb-1.5">Page transition</span>+ <p className="text-[10px] text-white/35 mb-2">Plays when this page appears after another.</p>+ <div className="grid grid-cols-2 gap-1.5">+ {TRANSITION_KINDS.map((t) => (+ <button+ key={t.kind}+ onClick={() => applyTransition(t.kind)}+ className={cn(+ 'rounded-lg border px-2.5 py-2 text-left cursor-pointer transition-colors',+ pageTransition?.kind === t.kind+ ? 'border-[#02C0CC] bg-[#02C0CC]/10'+ : 'border-white/10 hover:border-white/25'+ )}+ >+ <div className="text-[12px] font-semibold text-white/90">{t.label}</div>+ <div className="text-[10px] text-white/40">{t.hint}</div>+ </button>+ ))}+ </div>++ {pageTransition && pageTransition.kind !== 'none' && (+ <div className="mt-2.5">+ <div className="flex items-center justify-between mb-1">+ <span className="text-[10px] font-semibold text-white/50">Duration</span>+ <span className="text-[10px] text-white/60">{pageTransition.duration.toFixed(1)}s</span>+ </div>+ <input+ type="range"+ min={0.1}+ max={2.5}+ step={0.1}+ value={pageTransition.duration}+ onChange={(e) =>+ setPageTransition({ ...pageTransition, duration: Number(e.target.value) })+ }+ className="w-full accent-[#02C0CC]"+ aria-label="Transition duration"+ />+ {(pageTransition.kind === 'slide') && (+ <div className="flex gap-1 mt-2">+ {DIRECTIONS.map((d) => (+ <button+ key={d.id}+ title={d.label}+ onClick={() => setPageTransition({ ...pageTransition, direction: d.id })}+ className={cn(+ 'flex-1 rounded-md border py-1.5 flex items-center justify-center cursor-pointer',+ (pageTransition.direction ?? 'left') === d.id+ ? 'border-[#02C0CC] bg-[#02C0CC]/10 text-white'+ : 'border-white/10 text-white/50 hover:border-white/25'+ )}+ >+ <d.icon size={12} />+ </button>+ ))}+ </div>+ )}+ </div>+ )}+ </div>++ {/* actions */}+ <div className="flex gap-2">+ <Button+ size="sm"+ className="flex-1 btn-brand-gradient gap-1.5"+ onClick={() => setPreviewOpen(true)}+ >+ <Play size={12} /> Preview animations+ </Button>+ <Button+ size="sm"+ variant="ghost"+ className="text-white/70 hover:bg-white/10 hover:text-white gap-1.5"+ onClick={() => clearPageAnimations()}+ title="Remove all animations from this page"+ >+ <RotateCcw size={12} /> Clear+ </Button>+ </div>+ </div>+ )}++ {/* ── Element tab ──────────────────────────── */}+ {tab === 'element' && (+ <div className="space-y-4">+ {!selection ? (+ <div className="text-center py-10 px-2">+ <Zap size={26} className="mx-auto text-white/20 mb-2" />+ <div className="text-[13px] font-semibold text-white/60">Select an element</div>+ <p className="text-[11px] text-white/40 mt-1">+ Pick one or more elements on the canvas, then choose an animation.+ </p>+ </div>+ ) : (+ <>+ <p className="text-[11px] text-white/50">+ Animating {selectedIds.length} element{selectedIds.length > 1 ? 's' : ''}+ </p>++ <div className="grid grid-cols-3 gap-1.5">+ {ANIMATION_KINDS.map((k) => (+ <button+ key={k.kind}+ onClick={() => applyKind(k.kind)}+ title={k.hint}+ className={cn(+ 'rounded-lg border px-2 py-2 text-center cursor-pointer transition-colors',+ (selectedAnim?.kind ?? 'none') === k.kind+ ? 'border-[#02C0CC] bg-[#02C0CC]/10'+ : 'border-white/10 hover:border-white/25'+ )}+ >+ <AnimationGlyph kind={k.kind} />+ <div className="text-[11px] font-semibold text-white/85 mt-1">{k.label}</div>+ </button>+ ))}+ </div>++ {/* timing controls */}+ {selectedAnim && selectedAnim.kind !== 'none' && (+ <div className="space-y-3 rounded-xl border border-white/[0.08] bg-white/[0.03] p-3">+ <div>+ <div className="flex items-center justify-between mb-1">+ <span className="text-[10px] font-semibold text-white/50">Duration</span>+ <span className="text-[10px] text-white/60">{selectedAnim.duration.toFixed(1)}s</span>+ </div>+ <input+ type="range"+ min={0.1}+ max={4}+ step={0.1}+ value={selectedAnim.duration}+ onChange={(e) => patchAnim({ duration: Number(e.target.value) })}+ className="w-full accent-[#02C0CC]"+ aria-label="Animation duration"+ />+ </div>+ <div>+ <div className="flex items-center justify-between mb-1">+ <span className="text-[10px] font-semibold text-white/50">Delay</span>+ <span className="text-[10px] text-white/60">{selectedAnim.delay.toFixed(1)}s</span>+ </div>+ <input+ type="range"+ min={0}+ max={5}+ step={0.1}+ value={selectedAnim.delay}+ onChange={(e) => patchAnim({ delay: Number(e.target.value) })}+ className="w-full accent-[#02C0CC]"+ aria-label="Animation delay"+ />+ </div>+ <div>+ <span className="text-[10px] font-semibold text-white/50 block mb-1.5">Easing</span>+ <div className="grid grid-cols-3 gap-1">+ {EASINGS.map((e) => (+ <button+ key={e.id}+ onClick={() => patchAnim({ easing: e.id })}+ className={cn(+ 'rounded-md border py-1 text-[10px] font-semibold cursor-pointer',+ (selectedAnim.easing ?? 'easeOut') === e.id+ ? 'border-[#02C0CC] bg-[#02C0CC]/10 text-white'+ : 'border-white/10 text-white/50 hover:border-white/25'+ )}+ >+ {e.label}+ </button>+ ))}+ </div>+ </div>+ {['pan', 'rise', 'wipe', 'rotate'].includes(selectedAnim.kind) && (+ <div>+ <span className="text-[10px] font-semibold text-white/50 block mb-1.5">Direction</span>+ <div className="flex gap-1">+ {DIRECTIONS.map((d) => (+ <button+ key={d.id}+ title={d.label}+ onClick={() => patchAnim({ direction: d.id })}+ className={cn(+ 'flex-1 rounded-md border py-1.5 flex items-center justify-center cursor-pointer',+ (selectedAnim.direction ?? 'up') === d.id+ ? 'border-[#02C0CC] bg-[#02C0CC]/10 text-white'+ : 'border-white/10 text-white/50 hover:border-white/25'+ )}+ >+ <d.icon size={12} />+ </button>+ ))}+ </div>+ </div>+ )}+ </div>+ )}+ </>+ )}+ </div>+ )}+ </div>+ </div>+ )+}++function AnimationGlyph({ kind }: { kind: AnimationKind }) {+ const cls = 'mx-auto w-7 h-7 rounded-md bg-white/[0.06] flex items-center justify-center text-[#02C0CC]'+ switch (kind) {+ case 'none':+ return <div className={cls}><RotateCcw size={12} /></div>+ case 'fade':+ return <div className={cls}><span className="text-[10px] font-bold">Fa</span></div>+ case 'rise':+ return <div className={cls}><ArrowUp size={12} /></div>+ case 'pan':+ return <div className={cls}><ArrowRight size={12} /></div>+ case 'pop':+ return <div className={cls}><span className="text-[10px] font-bold">Po</span></div>+ case 'wipe':+ return <div className={cls}><span className="text-[10px] font-bold">Wi</span></div>+ case 'zoom':+ return <div className={cls}><span className="text-[10px] font-bold">Zo</span></div>+ case 'rotate':+ return <div className={cls}><RotateCcw size={12} className="rotate-[135deg]" /></div>+ case 'breathe':+ return <div className={cls}><span className="text-[10px] font-bold">Br</span></div>+ default:+ return <div className={cls}>?</div>+ }+}diff --git a/src/components/editor/CommentsPanel.tsx b/src/components/editor/CommentsPanel.tsxnew file mode 100644index 0000000..b7fd65d--- /dev/null+++ b/src/components/editor/CommentsPanel.tsx@@ -0,0 +1,313 @@+'use client'++import { useMemo, useState } from 'react'+import { Check, CheckCircle2, MessageCircle, Reply, Trash2, X, MessageSquare } from 'lucide-react'+import { useEditorStore } from '@/store/editor-store'+import {+ buildThreads,+ useCommentsStore,+ type CommentThread,+} from '@/lib/comments-store'+import { getIdentity } from '@/lib/collab/identity'+import { Button } from '@/components/ui/button'+import { cn } from '@/lib/utils'+import { toast } from '@/hooks/use-toast'++type Filter = 'open' | 'all' | 'resolved'++function initials(name: string): string {+ return name.trim().split(/\s+/).slice(0, 2).map((p) => p[0]?.toUpperCase() ?? '').join('') || '?'+}++function timeAgo(iso: string): string {+ const s = Math.max(0, (Date.now() - Date.parse(iso)) / 1000)+ if (s < 60) return 'just now'+ if (s < 3600) return `${Math.floor(s / 60)}m ago`+ if (s < 86_400) return `${Math.floor(s / 3600)}h ago`+ return `${Math.floor(s / 86_400)}d ago`+}++/** Comments side panel — canva-style review threads. */+export function CommentsPanel() {+ const designId = useEditorStore((s) => s.designId)+ const pages = useEditorStore((s) => s.pages)+ const setCurrentPage = useEditorStore((s) => s.setCurrentPage)+ const setCommentsOpen = useEditorStore((s) => s.setCommentsOpen)+ const comments = useCommentsStore((s) => s.comments)+ const openThreadId = useCommentsStore((s) => s.openThreadId)+ const [filter, setFilter] = useState<Filter>('open')+ const me = getIdentity()++ const threads = useMemo(() => buildThreads(comments), [comments])+ const filtered = useMemo(() => {+ if (filter === 'open') return threads.filter((t) => !t.root.resolved)+ if (filter === 'resolved') return threads.filter((t) => t.root.resolved)+ return threads+ }, [threads, filter])++ const findPageIndex = (pageId: string) => pages.findIndex((p) => p.id === pageId)++ const focusThread = (t: CommentThread) => {+ const idx = findPageIndex(t.root.pageId)+ if (idx >= 0 && idx !== useEditorStore.getState().currentPage) setCurrentPage(idx)+ useCommentsStore.getState().setOpenThreadId(t.root.id)+ }++ return (+ <div className="flex flex-col h-full">+ <div className="flex items-center justify-between px-4 pt-4 pb-3 shrink-0">+ <h2 className="font-bold text-sm text-white flex items-center gap-2">+ <MessageSquare size={15} className="text-[#02C0CC]" /> Comments+ </h2>+ <Button+ variant="ghost"+ size="icon"+ className="rounded-full text-white/70 hover:bg-white/10 hover:text-white h-7 w-7"+ onClick={() => setCommentsOpen(false)}+ aria-label="Close comments"+ >+ <X size={14} />+ </Button>+ </div>++ {/* filters */}+ <div className="px-4 pb-3 shrink-0">+ <div className="flex gap-1 rounded-lg bg-white/[0.05] p-0.5">+ {(['open', 'resolved', 'all'] as const).map((f) => (+ <button+ key={f}+ onClick={() => setFilter(f)}+ className={cn(+ 'flex-1 rounded-md px-2 py-1.5 text-[11px] font-semibold capitalize transition-colors cursor-pointer',+ filter === f ? 'bg-white/[0.12] text-white' : 'text-white/50 hover:text-white/80'+ )}+ >+ {f} {f === 'open' && threads.filter((t) => !t.root.resolved).length > 0 && `(${threads.filter((t) => !t.root.resolved).length})`}+ </button>+ ))}+ </div>+ </div>++ <div className="flex-1 min-h-0 overflow-y-auto px-3 pb-4 space-y-2">+ {filtered.length === 0 && (+ <div className="text-center py-10 px-4">+ <MessageCircle size={26} className="mx-auto text-white/20 mb-2" />+ <div className="text-[13px] font-semibold text-white/60">+ {filter === 'open' ? 'No open comments' : filter === 'resolved' ? 'No resolved comments' : 'No comments yet'}+ </div>+ <p className="text-[11px] text-white/40 mt-1">+ In comments mode, click anywhere on the canvas to drop a pin.+ </p>+ </div>+ )}++ {filtered.map((t) => (+ <ThreadCard+ key={t.root.id}+ thread={t}+ designId={designId}+ highlighted={openThreadId === t.root.id}+ onFocus={() => focusThread(t)}+ meId={me.id}+ pageIndex={Math.max(0, findPageIndex(t.root.pageId))}+ />+ ))}+ </div>+ </div>+ )+}++function ThreadCard({+ thread,+ designId,+ highlighted,+ onFocus,+ meId,+ pageIndex,+}: {+ thread: CommentThread+ designId: string | null+ highlighted: boolean+ onFocus: () => void+ meId: string+ pageIndex: number+}) {+ const { root, replies } = thread+ const [replyOpen, setReplyOpen] = useState(false)+ const [replyText, setReplyText] = useState('')+ const [busy, setBusy] = useState(false)+ const last = replies.length ? replies[replies.length - 1] : root++ const addReply = async () => {+ const text = replyText.trim()+ if (!text || !designId || busy) return+ setBusy(true)+ try {+ const res = await fetch(`/api/designs/${encodeURIComponent(designId)}/comments`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ pageId: root.pageId,+ x: root.x,+ y: root.y,+ parentId: root.id,+ authorId: getIdentity().id,+ authorName: getIdentity().name,+ authorColor: getIdentity().color,+ body: text,+ }),+ })+ if (!res.ok) throw new Error('failed')+ setReplyText('')+ setReplyOpen(false)+ } catch {+ toast({ title: 'Could not post the reply.' })+ } finally {+ setBusy(false)+ }+ }++ const toggleResolve = async () => {+ if (!designId) return+ try {+ const res = await fetch(`/api/comments/${encodeURIComponent(root.id)}`, {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ resolved: !root.resolved, actorId: getIdentity().id }),+ })+ if (res.ok) {+ // optimistic — the author sees the resolved state immediately,+ // then converge with a fresh fetch (beats any in-flight refetch race)+ useCommentsStore.getState().upsertComment({ ...root, resolved: !root.resolved })+ window.dispatchEvent(new CustomEvent('canvix:comments-changed'))+ }+ } catch {+ toast({ title: 'Could not update the comment.' })+ }+ }++ const deleteComment = async () => {+ if (!designId) return+ try {+ const res = await fetch(+ `/api/comments/${encodeURIComponent(root.id)}?actorId=${encodeURIComponent(getIdentity().id)}`,+ { method: 'DELETE' }+ )+ if (res.ok) {+ useCommentsStore.getState().removeComment(root.id)+ window.dispatchEvent(new CustomEvent('canvix:comments-changed'))+ }+ } catch {+ toast({ title: 'Could not delete the comment.' })+ }+ }++ return (+ <div+ className={cn(+ 'rounded-xl border p-2.5 cursor-pointer transition-colors',+ highlighted+ ? 'border-[#02C0CC]/50 bg-[#02C0CC]/[0.07]'+ : 'border-white/[0.08] bg-white/[0.03] hover:bg-white/[0.06]'+ )}+ onClick={onFocus}+ >+ <div className="flex items-start gap-2">+ <span+ className="w-6 h-6 rounded-full flex items-center justify-center text-[9px] font-bold text-white shrink-0 mt-0.5"+ style={{ background: root.authorColor }}+ >+ {initials(root.authorName)}+ </span>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5">+ <span className="text-[12px] font-semibold text-white/90 truncate">{root.authorName}</span>+ <span className="text-[10px] text-white/35 shrink-0">{timeAgo(root.createdAt)}</span>+ {root.resolved && (+ <span className="text-[9px] font-semibold text-emerald-300/80 flex items-center gap-0.5 shrink-0">+ <Check size={9} /> resolved+ </span>+ )}+ </div>+ <p className="text-[12px] text-white/75 mt-0.5 break-words">{root.body}</p>++ {replies.length > 0 && (+ <div className="mt-1.5 space-y-1.5 pl-2 border-l border-white/[0.08]">+ {replies.map((r) => (+ <div key={r.id} className="flex items-start gap-1.5">+ <span+ className="w-4.5 h-4.5 w-[18px] h-[18px] rounded-full flex items-center justify-center text-[7px] font-bold text-white shrink-0 mt-0.5"+ style={{ background: r.authorColor }}+ >+ {initials(r.authorName)}+ </span>+ <div className="min-w-0">+ <span className="text-[11px] font-semibold text-white/70">{r.authorName}</span>+ <p className="text-[11px] text-white/60 break-words">{r.body}</p>+ </div>+ </div>+ ))}+ </div>+ )}++ {/* thread actions */}+ <div className="flex items-center gap-1 mt-1.5 -ml-1">+ <button+ className="text-[10px] font-semibold text-white/50 hover:text-white px-1.5 py-0.5 rounded flex items-center gap-1 cursor-pointer"+ onClick={(e) => {+ e.stopPropagation()+ setReplyOpen((v) => !v)+ }}+ >+ <Reply size={10} /> Reply+ </button>+ <button+ className="text-[10px] font-semibold text-white/50 hover:text-white px-1.5 py-0.5 rounded flex items-center gap-1 cursor-pointer"+ onClick={(e) => {+ e.stopPropagation()+ void toggleResolve()+ }}+ >+ <CheckCircle2 size={10} /> {root.resolved ? 'Reopen' : 'Resolve'}+ </button>+ {root.authorId === meId && (+ <button+ className="text-[10px] font-semibold text-white/50 hover:text-red-300 px-1.5 py-0.5 rounded flex items-center gap-1 cursor-pointer"+ onClick={(e) => {+ e.stopPropagation()+ void deleteComment()+ }}+ >+ <Trash2 size={10} /> Delete+ </button>+ )}+ <span className="ml-auto text-[9px] text-white/25 shrink-0">Page {pageIndex + 1}</span>+ </div>++ {replyOpen && (+ <div className="mt-2 flex gap-1.5" onClick={(e) => e.stopPropagation()}>+ <input+ value={replyText}+ onChange={(e) => setReplyText(e.target.value)}+ onKeyDown={(e) => e.key === 'Enter' && void addReply()}+ placeholder={`Reply to ${root.authorName}…`}+ maxLength={2000}+ autoFocus+ className="flex-1 h-8 rounded-lg bg-white/[0.06] border border-white/10 px-2.5 text-[12px] text-white placeholder:text-white/30 outline-none focus:border-[#02C0CC]/50"+ />+ <Button+ size="sm"+ className="h-8 px-3 btn-brand-gradient"+ disabled={!replyText.trim() || busy}+ onClick={() => void addReply()}+ >+ Send+ </Button>+ </div>+ )}+ </div>+ </div>+ <span className="hidden">{last.id}</span>+ </div>+ )+}diff --git a/src/components/editor/Editor.tsx b/src/components/editor/Editor.tsxindex d469e19..eb18059 100644--- a/src/components/editor/Editor.tsx+++ b/src/components/editor/Editor.tsx@@ -25,6 +25,10 @@ import { LayersPanel } from './panels/LayersPanel'import { captureThumbnail, canvasBridge } from './canvas/canvas-bridge'import { CropDialog } from './CropDialog'import { useIsMobile } from '@/hooks/use-mobile'+import { useCollab } from '@/hooks/use-collab'+import { useComments, markAllCommentsRead } from '@/hooks/use-comments'+import { CommentsPanel } from './CommentsPanel'+import { AnimatePanel } from './AnimatePanel'import { Button } from '@/components/ui/button'import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'import { toast } from '@/hooks/use-toast'@@ -84,6 +88,9 @@ export default function Editor() {const isMobile = useIsMobile()const [shortcutsOpen, setShortcutsOpen] = useState(false)const selectedIds = useEditorStore((s) => s.selectedIds)+ const commentsOpen = useEditorStore((s) => s.commentsOpen)+ const animateOpen = useEditorStore((s) => s.animateOpen)+ const setAnimateOpen = useEditorStore((s) => s.setAnimateOpen)// v0.3.1: image crop dialog (opened from the toolbar or context menu)const cropTargetId = useEditorStore((s) => s.cropTargetId)@@ -96,6 +103,12 @@ export default function Editor() {const loadedRef = useRef(false)+ // ── v0.5: real-time collaboration session for the open design ──+ useCollab()++ // ── v0.5: comments (live refresh) ──+ useComments()+// ── load pending design (from dashboard) ───────────────────useEffect(() => {if (loadedRef.current) return@@ -342,6 +355,19 @@ export default function Editor() {<LeftRail vertical /></div>+ {/* v0.5: comments panel — replaces the tool panel while open */}+ {commentsOpen ? (+ <aside+ className={+ isMobile+ ? 'fixed inset-x-0 bottom-14 top-14 z-40 bg-[#16181D] shadow-2xl flex flex-col'+ : 'w-[340px] bg-[#16181D] border-r border-white/[0.07] flex flex-col shrink-0'+ }+ >+ <CommentsPanel />+ </aside>+ ) : (+ <>{/* panel — desktop: sidebar; mobile: overlay sheet */}{hasPanel && (<aside@@ -362,6 +388,8 @@ export default function Editor() {<div className="flex-1 min-h-0">{renderPanel()}</div></aside>)}+ </>+ )}{/* canvas workspace */}<main className="flex-1 relative min-w-0 min-h-0" aria-label="Design canvas">@@ -369,6 +397,13 @@ export default function Editor() {<PageBar /><ZoomControls /></main>++ {/* v0.5: Animate panel — canva-style right side panel */}+ {animateOpen && (+ <aside className="w-[300px] bg-[#16181D] border-l border-white/[0.07] flex flex-col shrink-0 hidden md:flex">+ <AnimatePanel onClose={() => setAnimateOpen(false)} />+ </aside>+ )}</div>{/* mobile contextual action bar (canva mobile: bottom bar on selection) */}diff --git a/src/components/editor/ExportDialog.tsx b/src/components/editor/ExportDialog.tsxindex 5fe1cf8..884993f 100644--- a/src/components/editor/ExportDialog.tsx+++ b/src/components/editor/ExportDialog.tsx@@ -1,10 +1,13 @@'use client'import { useState } from 'react'-import { Download, Loader2, FileImage, FileType2 } from 'lucide-react'+import { Download, Loader2, FileImage, FileType2, FileCode2, Film } from 'lucide-react'import { useEditorStore } from '@/store/editor-store'import { captureStage, canvasBridge } from './canvas/canvas-bridge'+import { exportDesignToSVGs, downloadSVG } from '@/lib/svg-export'+import { detectVideoFormat, downloadVideo, estimateVideoDuration, exportVideo } from '@/lib/video-export'import { toast } from '@/hooks/use-toast'+import { Progress } from '@/components/ui/progress'import { Button } from '@/components/ui/button'import {Dialog,@@ -39,6 +42,8 @@ const FORMATS = [{ id: 'png', label: 'PNG', hint: 'Lossless · transparency', icon: FileImage },{ id: 'jpg', label: 'JPG', hint: 'Smaller file', icon: FileImage },{ id: 'pdf', label: 'PDF', hint: 'Print-ready · all pages', icon: FileType2 },+ { id: 'svg', label: 'SVG', hint: 'Vector · editable', icon: FileCode2 },+ { id: 'mp4', label: 'Video', hint: 'MP4 / WebM · animated', icon: Film },] as consttype FormatId = (typeof FORMATS)[number]['id']@@ -53,6 +58,10 @@ export function ExportDialog({ open, onOpenChange }: { open: boolean; onOpenChanconst [scale, setScale] = useState(2)const [allPages, setAllPages] = useState(false)const [busy, setBusy] = useState(false)+ const [progress, setProgress] = useState<number | null>(null)+ const [progressLabel, setProgressLabel] = useState('')+ const videoFormat = detectVideoFormat()+ const videoDuration = estimateVideoDuration(pages)const base = sanitizeFilename(name)const pageCount = allPages ? pages.length : 1@@ -61,7 +70,43 @@ export function ExportDialog({ open, onOpenChange }: { open: boolean; onOpenChanconst run = async () => {setBusy(true)+ setProgress(null)try {+ if (format === 'mp4') {+ if (!videoFormat) throw new Error('This browser cannot record video. Try Chrome or Edge.')+ const result = await exportVideo({+ designWidth: canvasBridge.pageWidth || 1080,+ designHeight: canvasBridge.pageHeight || 1080,+ pages,+ maxWidth: scale === 3 ? 1920 : scale === 2 ? 1440 : 960,+ onProgress: (ratio, label) => {+ setProgress(Math.round(ratio * 100))+ setProgressLabel(label)+ },+ })+ downloadVideo(result, base)+ toast({+ title: `Video downloaded (${result.extension.toUpperCase()})`,+ description: `${result.frames} frames · ${result.durationSec.toFixed(1)}s · rendered locally in your browser`,+ })+ onOpenChange(false)+ return+ }+ if (format === 'svg') {+ // true vector export — no rasterization of vector elements+ const svgs = exportDesignToSVGs(allPages ? pages : [pages[currentPage]], canvasBridge.pageWidth, canvasBridge.pageHeight)+ for (let k = 0; k < svgs.length; k++) {+ const suffix = svgs.length > 1 ? `-page-${(allPages ? 0 : currentPage) + k + 1}` : ''+ downloadSVG(svgs[k], `${base}${suffix}.svg`)+ if (svgs.length > 1) await new Promise((r) => setTimeout(r, 380))+ }+ toast({+ title: `SVG downloaded (${svgs.length} file${svgs.length > 1 ? 's' : ''})`,+ description: 'Text keeps font-family references — viewers fall back to installed fonts.',+ })+ onOpenChange(false)+ return+ }if (format === 'pdf') {// multi-page PDF via jsPDF (client-side, no watermark)const { jsPDF } = await import('jspdf')@@ -126,7 +171,7 @@ export function ExportDialog({ open, onOpenChange }: { open: boolean; onOpenChan<div className="space-y-5 py-2"><div><h4 className="text-xs font-semibold text-muted-foreground mb-2">File type</h4>- <div className="grid grid-cols-3 gap-2">+ <div className="grid grid-cols-5 gap-1.5">{FORMATS.map((f) => {const Ico = f.iconreturn (@@ -150,6 +195,26 @@ export function ExportDialog({ open, onOpenChange }: { open: boolean; onOpenChan<div><h4 className="text-xs font-semibold text-muted-foreground mb-2">Quality</h4>+ {format === 'svg' ? (+ <p className="text-[11px] text-muted-foreground py-3">+ Vector export — resolution-independent, opens in browsers & vector editors.+ </p>+ ) : format === 'mp4' ? (+ <div className="text-[11px] text-muted-foreground space-y-1.5 py-1">+ <p>+ Renders <strong>{videoDuration.toFixed(1)}s</strong> of animated playback ({pages.length} page{pages.length > 1 ? 's' : ''}) — element animations and page transitions included.+ </p>+ <p>+ {videoFormat ? (+ <>Format: <strong>{videoFormat.label}</strong>{videoFormat.extension === 'webm' && <> — this browser can’t encode MP4, so Canvix produces WebM (plays everywhere)</>}</>+ ) : (+ <span className="text-red-500">This browser cannot record video — try Chrome or Edge.</span>+ )}+ · rendered locally (no upload)+ </p>+ </div>+ ) : (+ <><div className="grid grid-cols-3 gap-2">{SCALES.map((s) => (<button@@ -168,9 +233,11 @@ export function ExportDialog({ open, onOpenChange }: { open: boolean; onOpenChan<p className="text-[11px] text-muted-foreground mt-2">Output: {estWidth} × {estHeight} px per file</p>+ </>+ )}</div>- {pages.length > 1 && (+ {pages.length > 1 && format !== 'mp4' && (<label className="flex items-center justify-between rounded-xl border border-black/10 px-4 py-3 cursor-pointer"><span className="text-sm font-medium">{format === 'pdf' ? 'Include all pages' : 'Download all pages'}@@ -181,6 +248,13 @@ export function ExportDialog({ open, onOpenChange }: { open: boolean; onOpenChan)}</div>+ {busy && progress !== null && (+ <div className="space-y-2">+ <Progress value={progress} className="h-2" />+ <p className="text-[11px] text-muted-foreground text-center">{progressLabel}</p>+ </div>+ )}+<DialogFooter><Button variant="outline" onClick={() => onOpenChange(false)} disabled={busy}>Canceldiff --git a/src/components/editor/MagicLayersDialog.tsx b/src/components/editor/MagicLayersDialog.tsxnew file mode 100644index 0000000..07c6198--- /dev/null+++ b/src/components/editor/MagicLayersDialog.tsx@@ -0,0 +1,539 @@+'use client'++import { useCallback, useMemo, useRef, useState } from 'react'+import {+ AlertTriangle,+ Check,+ Eye,+ EyeOff,+ ImageIcon,+ Layers,+ Loader2,+ MousePointer2,+ Plus,+ RefreshCw,+ Sparkles,+ Trash2,+ Upload,+ Wand2,+ X,+} from 'lucide-react'+import { useEditorStore } from '@/store/editor-store'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { cn } from '@/lib/utils'+import { toast } from '@/hooks/use-toast'+import { useAICapabilities } from '@/hooks/use-ai-capabilities'+import type { ImageElement, PageData } from '@/lib/types'+import { createImageElement, uid } from '@/lib/types'+import { normalizeForAnalysis, normalizeSrcForAnalysis } from '@/lib/magic-layers/normalize'+import { reconstructDesign, toPage, type MagicLayersReconstruction } from '@/lib/magic-layers/reconstruct'+import { REVIEW_CONFIDENCE_THRESHOLD, type MagicLayerAnalysis, type MagicRegion } from '@/lib/magic-layers/types'++type Stage = 'upload' | 'analyzing' | 'review' | 'rebuilding'++type InsertMode = 'replace' | 'append' | 'overlay'++/** Approximate wrapped-text height the way Konva measures it (offscreen 2D canvas). */+function measureTextHeight(text: string, fontFamily: string, fontSize: number, width: number, lineHeight: number, bold: boolean): number {+ try {+ const canvas = document.createElement('canvas')+ const ctx = canvas.getContext('2d')+ if (!ctx) return fontSize * lineHeight+ ctx.font = `${bold ? '700' : '400'} ${fontSize}px ${fontFamily}`+ const words = text.split(/\s+/)+ const lines: string[] = []+ let line = ''+ for (const word of words) {+ const test = line ? `${line} ${word}` : word+ if (ctx.measureText(test).width > width && line) {+ lines.push(line)+ line = word+ } else {+ line = test+ }+ }+ if (line) lines.push(line)+ return Math.max(fontSize * lineHeight, lines.length * fontSize * lineHeight)+ } catch {+ return fontSize * lineHeight+ }+}++export function MagicLayersDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (o: boolean) => void }) {+ const width = useEditorStore((s) => s.width)+ const height = useEditorStore((s) => s.height)+ const addElementsBulk = useEditorStore((s) => s.addElementsBulk)+ const replaceCurrentPage = useEditorStore((s) => s.replaceCurrentPage)+ const appendPage = useEditorStore((s) => s.appendPage)+ const updateElementsLive = useEditorStore((s) => s.updateElementsLive)+ const currentPageElements = useEditorStore((s) => s.pages[s.currentPage]?.elements)+ const selectedIds = useEditorStore((s) => s.selectedIds)+ const selectedElements = useMemo(+ () => (currentPageElements ?? []).filter((e) => selectedIds.includes(e.id)),+ [currentPageElements, selectedIds]+ )+ const { configured: aiConfigured, loaded: aiLoaded } = useAICapabilities()++ const [stage, setStage] = useState<Stage>('upload')+ const [imageUrl, setImageUrl] = useState<string | null>(null)+ const [analysis, setAnalysis] = useState<MagicLayerAnalysis | null>(null)+ const [error, setError] = useState<string | null>(null)+ const [discarded, setDiscarded] = useState<Set<string>>(new Set())+ const [insertMode, setInsertMode] = useState<InsertMode>('replace')+ const fileInputRef = useRef<HTMLInputElement>(null)++ const reset = useCallback(() => {+ setStage('upload')+ setImageUrl(null)+ setAnalysis(null)+ setError(null)+ setDiscarded(new Set())+ }, [])++ const close = (o: boolean) => {+ if (!o) {+ onOpenChange(false)+ setTimeout(reset, 250)+ }+ }++ // ── pick a file → normalize → analyze ────────────────────+ const analyzeFile = async (file: File) => {+ setStage('analyzing')+ setError(null)+ try {+ const { dataUrl } = await normalizeForAnalysis(file)+ setImageUrl(dataUrl)+ await runAnalysis(dataUrl)+ } catch (e) {+ setError(e instanceof Error ? e.message : 'Could not read that image.')+ setStage('upload')+ }+ }++ const analyzeSelected = async () => {+ const img = selectedElements.find((e): e is ImageElement => e.type === 'image')+ if (!img) return+ setStage('analyzing')+ setError(null)+ try {+ const dataUrl = await normalizeSrcForAnalysis(img.src)+ setImageUrl(dataUrl)+ await runAnalysis(dataUrl)+ } catch {+ setError('That image could not be loaded for analysis.')+ setStage('upload')+ }+ }++ const runAnalysis = async (dataUrl: string) => {+ try {+ const res = await fetch('/api/ai/magic-layers', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ image: dataUrl }),+ })+ const data = (await res.json()) as MagicLayerAnalysis & { error?: string; code?: string }+ if (!res.ok || !Array.isArray(data.regions)) {+ throw new Error(data.error ?? 'Analysis failed.')+ }+ setAnalysis(data)+ setDiscarded(new Set(data.regions.filter((r) => r.confidence < 0.35).map((r) => r.id)))+ setStage('review')+ } catch (e) {+ setError(e instanceof Error ? e.message : 'Analysis failed.')+ setStage('upload')+ }+ }++ // ── rebuild → insert ─────────────────────────────────────+ const createLayers = async () => {+ if (!analysis || !imageUrl) return+ setStage('rebuilding')+ try {+ const rec = await reconstructDesign(analysis, imageUrl, width, height, [...discarded])+ applyReconstruction(rec)+ toast({+ title: 'Magic Layers created',+ description: `${rec.elements.length} editable layers extracted — each element can be selected, moved and restyled.`,+ })+ close(false)+ } catch (e) {+ setError(e instanceof Error ? e.message : 'Reconstruction failed.')+ setStage('review')+ }+ }++ const applyReconstruction = (rec: MagicLayersReconstruction) => {+ if (insertMode === 'replace') {+ replaceCurrentPage(toPage(rec))+ } else if (insertMode === 'append') {+ appendPage(toPage(rec))+ } else {+ addElementsBulk(rec.elements)+ }+ // best-effort text height measure pass (text boxes are placed by the+ // analysis bounds; heights re-measure to the wrapped content)+ const texts = rec.elements.filter((e) => e.type === 'text')+ if (texts.length) {+ requestAnimationFrame(() => {+ for (const el of texts) {+ if (el.type !== 'text') continue+ const h = measureTextHeight(el.text, el.fontFamily, el.fontSize, el.width, el.lineHeight, el.bold)+ if (Number.isFinite(h) && h > 0) updateElementsLive([el.id], { height: Math.round(h) })+ }+ })+ }+ }++ const insertAsImage = () => {+ if (!imageUrl) return+ addElementsBulk([+ createImageElement(imageUrl, width, height, {+ x: 0,+ y: 0,+ width,+ height,+ name: 'Original image (flat)',+ }),+ ])+ toast({ title: 'Image placed flat', description: 'The original image was placed as a single layer.' })+ close(false)+ }++ const toggleDiscard = (id: string) => {+ setDiscarded((prev) => {+ const next = new Set(prev)+ if (next.has(id)) next.delete(id)+ else next.add(id)+ return next+ })+ }++ const selectedImageElement = selectedElements.find((e): e is ImageElement => e.type === 'image')+ const regionCount = analysis?.regions.length ?? 0+ const keptCount = analysis ? analysis.regions.filter((r) => !discarded.has(r.id)).length : 0+ const lowConfidenceCount = analysis+ ? analysis.regions.filter((r) => r.confidence < REVIEW_CONFIDENCE_THRESHOLD).length+ : 0++ return (+ <Dialog open={open} onOpenChange={close}>+ <DialogContent className="rounded-[28px] sm:max-w-2xl bg-[#16181D] border-white/10 text-white max-h-[88vh] overflow-y-auto">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2 text-lg font-bold">+ <Wand2 size={18} className="text-[#02C0CC]" /> Magic Layers+ </DialogTitle>+ <DialogDescription className="text-white/60">+ Turn a flat design image into an editable layout — text, images and shapes become real layers you can move, restyle and edit.+ </DialogDescription>+ </DialogHeader>++ {/* AI provider not configured — honest state with local fallback */}+ {aiLoaded && !aiConfigured && stage === 'upload' && (+ <div className="rounded-xl border border-amber-400/30 bg-amber-400/10 p-4 text-sm text-amber-200/90">+ <div className="flex items-center gap-2 font-semibold">+ <AlertTriangle size={15} /> AI provider not configured+ </div>+ <p className="mt-1 text-amber-200/70">+ Automatic layer extraction needs a vision AI provider configured on the server. You can still place the+ image as a single flat layer.+ </p>+ </div>+ )}++ {error && (+ <div className="rounded-xl border border-red-400/30 bg-red-400/10 p-3 text-sm text-red-200/90">{error}</div>+ )}++ {/* ── Stage: upload ─────────────────────────────── */}+ {stage === 'upload' && (+ <div className="space-y-4">+ <button+ type="button"+ onClick={() => fileInputRef.current?.click()}+ className="w-full rounded-2xl border-2 border-dashed border-white/15 hover:border-[#7630D7] bg-white/[0.03] hover:bg-[#7630D7]/10 transition-all py-10 flex flex-col items-center gap-3 cursor-pointer"+ onDragOver={(e) => e.preventDefault()}+ onDrop={(e) => {+ e.preventDefault()+ const file = e.dataTransfer.files?.[0]+ if (file?.type.startsWith('image/')) void analyzeFile(file)+ }}+ >+ <div className="w-14 h-14 rounded-full bg-gradient-to-br from-[#00C4CC] to-[#7630D7] flex items-center justify-center">+ <Upload size={22} className="text-white" />+ </div>+ <div className="text-sm font-semibold">Upload a flat design</div>+ <div className="text-xs text-white/50">PNG, JPG or WebP — drop it here or click to browse</div>+ </button>+ <input+ ref={fileInputRef}+ type="file"+ accept="image/png,image/jpeg,image/webp"+ className="hidden"+ onChange={(e) => {+ const file = e.target.files?.[0]+ if (file) void analyzeFile(file)+ e.target.value = ''+ }}+ />++ {selectedImageElement && (+ <button+ type="button"+ onClick={() => void analyzeSelected()}+ className="w-full rounded-xl border border-white/10 bg-white/[0.04] hover:bg-white/[0.08] p-3 flex items-center gap-3 text-left cursor-pointer transition-colors"+ >+ <div className="w-10 h-10 rounded-lg bg-[#7630D7]/20 flex items-center justify-center shrink-0">+ <MousePointer2 size={16} className="text-[#c39bff]" />+ </div>+ <div className="min-w-0">+ <div className="text-sm font-semibold">Analyze the selected image</div>+ <div className="text-xs text-white/50 truncate">+ Uses the image currently selected on your canvas+ </div>+ </div>+ </button>+ )}++ <div className="rounded-xl bg-white/[0.03] border border-white/[0.07] p-3.5 text-xs text-white/55 space-y-1.5">+ <div className="font-semibold text-white/75 flex items-center gap-1.5">+ <Sparkles size={12} className="text-[#02C0CC]" /> How it works+ </div>+ <p>+ A vision model detects text, photos, shapes and the background, then Canvix rebuilds each region as a+ <strong className="text-white/80"> native editable element</strong>. Exact fonts can't be recovered —+ the closest family from the Canvix library is used. Uncertain regions are flagged so you can review them.+ </p>+ </div>+ </div>+ )}++ {/* ── Stage: analyzing ──────────────────────────── */}+ {stage === 'analyzing' && (+ <div className="py-10 flex flex-col items-center gap-4">+ {imageUrl && (++ <img src={imageUrl} alt="Design being analyzed" className="max-h-44 rounded-xl border border-white/10 object-contain" />+ )}+ <Loader2 size={28} className="animate-spin text-[#02C0CC]" />+ <div className="text-sm font-semibold">Detecting layers…</div>+ <div className="text-xs text-white/50">Reading text, photos, shapes and the background.</div>+ </div>+ )}++ {/* ── Stage: review ─────────────────────────────── */}+ {stage === 'review' && analysis && imageUrl && (+ <div className="space-y-4">+ {analysis.notes && (+ <div className="rounded-xl border border-white/10 bg-white/[0.04] p-3 text-xs text-white/60 flex gap-2">+ <AlertTriangle size={14} className="shrink-0 mt-0.5 text-amber-300/80" />+ <span>{analysis.notes}</span>+ </div>+ )}++ <div className="grid grid-cols-[220px_1fr] gap-4">+ {/* preview with region outlines */}+ <div className="relative rounded-xl overflow-hidden border border-white/10 bg-[#0F1015]">+ { }+ <img src={imageUrl} alt="Analyzed design" className="w-full block" />+ {analysis.regions.map((r) => {+ const isDiscarded = discarded.has(r.id)+ const low = r.confidence < REVIEW_CONFIDENCE_THRESHOLD+ return (+ <button+ key={r.id}+ type="button"+ onClick={() => toggleDiscard(r.id)}+ title={`${r.type}${r.text ? `: ${r.text.slice(0, 40)}` : ''} — confidence ${(r.confidence * 100).toFixed(0)}% (click to ${isDiscarded ? 'keep' : 'discard'})`}+ className={cn(+ 'absolute border-2 transition-all',+ isDiscarded+ ? 'border-white/20 opacity-25'+ : low+ ? 'border-amber-400'+ : 'border-[#02C0CC]'+ )}+ style={{+ left: `${r.bounds.x * 100}%`,+ top: `${r.bounds.y * 100}%`,+ width: `${r.bounds.w * 100}%`,+ height: `${r.bounds.h * 100}%`,+ }}+ >+ {isDiscarded && (+ <span className="absolute inset-0 flex items-center justify-center">+ <EyeOff size={12} className="text-white/70" />+ </span>+ )}+ </button>+ )+ })}+ </div>++ {/* region list */}+ <div className="min-h-0">+ <div className="flex items-center justify-between mb-2">+ <div className="text-xs font-semibold text-white/70">+ {keptCount} of {regionCount} layers kept+ {lowConfidenceCount > 0 && (+ <span className="ml-2 text-amber-300/80">+ {lowConfidenceCount} need review+ </span>+ )}+ </div>+ <Button+ variant="ghost"+ size="sm"+ className="h-7 text-xs text-white/70 hover:bg-white/10 hover:text-white"+ onClick={() => setDiscarded(new Set())}+ >+ <RefreshCw size={11} className="mr-1" /> Keep all+ </Button>+ </div>+ <div className="max-h-64 overflow-y-auto pr-1 space-y-1.5">+ {analysis.regions.map((r) => (+ <RegionRow key={r.id} region={r} discarded={discarded.has(r.id)} onToggle={() => toggleDiscard(r.id)} />+ ))}+ </div>+ </div>+ </div>++ {/* insert mode */}+ <div className="grid grid-cols-3 gap-2">+ {(+ [+ { id: 'replace', label: 'Replace page', hint: 'Rebuilds the current page' },+ { id: 'append', label: 'New page', hint: 'Adds a page after this one' },+ { id: 'overlay', label: 'Add to page', hint: 'Layers on top of existing elements' },+ ] as const+ ).map((m) => (+ <button+ key={m.id}+ type="button"+ onClick={() => setInsertMode(m.id)}+ className={cn(+ 'rounded-xl border-2 p-2.5 text-left transition-all cursor-pointer',+ insertMode === m.id ? 'border-[#02C0CC] bg-[#02C0CC]/10' : 'border-white/10 hover:border-white/25'+ )}+ >+ <div className="text-[13px] font-semibold">{m.label}</div>+ <div className="text-[11px] text-white/50">{m.hint}</div>+ </button>+ ))}+ </div>+ </div>+ )}++ {stage === 'rebuilding' && (+ <div className="py-10 flex flex-col items-center gap-4">+ <Loader2 size={28} className="animate-spin text-[#7630D7]" />+ <div className="text-sm font-semibold">Building editable layers…</div>+ </div>+ )}++ <div className="flex items-center gap-2 justify-end pt-1">+ {stage === 'review' && (+ <>+ <Button variant="ghost" className="text-white/70 hover:bg-white/10 hover:text-white" onClick={() => reset()}>+ <RefreshCw size={14} className="mr-1.5" /> Start over+ </Button>+ <Button className="btn-brand-gradient gap-2 px-5" onClick={() => void createLayers()} disabled={keptCount === 0}>+ <Layers size={15} />+ Create {keptCount} editable layers+ </Button>+ </>+ )}+ {stage === 'upload' && imageUrl === null && (+ <Button variant="ghost" className="text-white/70 hover:bg-white/10 hover:text-white" onClick={() => close(false)}>+ <X size={14} className="mr-1.5" /> Close+ </Button>+ )}+ {(stage === 'upload' || stage === 'review') && imageUrl && (+ <Button variant="ghost" className="text-white/70 hover:bg-white/10 hover:text-white" onClick={insertAsImage}>+ <ImageIcon size={14} className="mr-1.5" /> Place flat instead+ </Button>+ )}+ </div>+ </DialogContent>+ </Dialog>+ )+}++function RegionRow({ region, discarded, onToggle }: { region: MagicRegion; discarded: boolean; onToggle: () => void }) {+ const low = region.confidence < REVIEW_CONFIDENCE_THRESHOLD+ const icon =+ region.type === 'text' ? 'T' : region.type === 'photo' ? <ImageIcon size={12} /> : region.type === 'shape' ? <Plus size={12} /> : <Sparkles size={12} />+ const label =+ region.type === 'text'+ ? (region.text ?? '').replace(/\n/g, ' ').slice(0, 44)+ : region.type === 'photo'+ ? region.subject || 'Photo region'+ : region.type === 'shape'+ ? `${region.shape ?? 'rect'} shape`+ : 'Decoration'++ return (+ <button+ type="button"+ onClick={onToggle}+ className={cn(+ 'w-full rounded-lg border p-2 flex items-center gap-2 text-left transition-all cursor-pointer',+ discarded+ ? 'border-white/[0.06] bg-transparent opacity-45'+ : low+ ? 'border-amber-400/40 bg-amber-400/5 hover:bg-amber-400/10'+ : 'border-white/10 bg-white/[0.04] hover:bg-white/[0.08]'+ )}+ >+ <div+ className="w-6 h-6 rounded-md flex items-center justify-center text-[10px] font-bold shrink-0"+ style={{ background: region.color ?? '#00C4CC', color: readableOn(region.color) }}+ >+ {icon}+ </div>+ <div className="min-w-0 flex-1">+ <div className="text-[12px] font-medium text-white/85 truncate">{label}</div>+ <div className="text-[10px] text-white/40 flex items-center gap-1.5">+ {region.type}+ <span+ className={cn(+ 'px-1 rounded font-semibold',+ low ? 'bg-amber-400/20 text-amber-300' : 'bg-[#02C0CC]/15 text-[#02C0CC]'+ )}+ >+ {(region.confidence * 100).toFixed(0)}%+ </span>+ </div>+ </div>+ {discarded ? <EyeOff size={13} className="text-white/30 shrink-0" /> : <Check size={13} className="text-[#02C0CC] shrink-0" />}+ </button>+ )+}++function readableOn(hex?: string): string {+ if (!hex) return '#FFFFFF'+ const h = hex.replace('#', '')+ if (h.length !== 6) return '#FFFFFF'+ const r = parseInt(h.slice(0, 2), 16)+ const g = parseInt(h.slice(2, 4), 16)+ const b = parseInt(h.slice(4, 6), 16)+ return (r * 299 + g * 587 + b * 114) / 1000 > 150 ? '#1F2226' : '#FFFFFF'+}++/** reserved for future magic-layer element swapping (element metadata UI) */+export function magicLayerBadge(el: { magicLayer?: { confidence: number } }): string | null {+ if (!el.magicLayer) return null+ return el.magicLayer.confidence < REVIEW_CONFIDENCE_THRESHOLD ? 'low confidence' : null+}++void uid+void Trash2+void Eyediff --git a/src/components/editor/PresenceAvatars.tsx b/src/components/editor/PresenceAvatars.tsxnew file mode 100644index 0000000..ec6e8b8--- /dev/null+++ b/src/components/editor/PresenceAvatars.tsx@@ -0,0 +1,127 @@+'use client'++import { useState } from 'react'+import { Wifi, WifiOff, Loader2, Pencil } from 'lucide-react'+import { useEditorStore } from '@/store/editor-store'+import { getIdentity, setDisplayName } from '@/lib/collab/identity'+import { cn } from '@/lib/utils'+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/components/ui/popover'+import { Input } from '@/components/ui/input'++function initials(name: string): string {+ const parts = name.trim().split(/\s+/).slice(0, 2)+ return parts.map((p) => p[0]?.toUpperCase() ?? '').join('') || '?'+}++/** Stacked collaborator avatars + connection status (canva-style, topbar right). */+export function PresenceAvatars() {+ const collaborators = useEditorStore((s) => s.collaborators)+ const status = useEditorStore((s) => s.collabStatus)+ const [open, setOpen] = useState(false)++ const me = getIdentity()++ return (+ <div className="flex items-center gap-2 mr-1">+ {/* connection status */}+ {status === 'live' ? (+ <span className="hidden xl:flex items-center gap-1 text-[11px] font-semibold text-emerald-300/90" title={`Live — ${collaborators.length + 1} editing`}>+ <Wifi size={12} /> Live+ </span>+ ) : status === 'connecting' ? (+ <span className="hidden xl:flex items-center gap-1 text-[11px] font-semibold text-amber-300/90" title="Reconnecting…">+ <Loader2 size={12} className="animate-spin" /> Syncing+ </span>+ ) : (+ <span className="hidden xl:flex items-center gap-1 text-[11px] font-semibold text-white/40" title="Offline — edits save locally">+ <WifiOff size={12} /> Offline+ </span>+ )}++ {/* stacked avatars */}+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <button+ className="flex items-center -space-x-1.5 pr-1.5 cursor-pointer group"+ aria-label={`Collaborators (${collaborators.length + 1})`}+ >+ {/* local identity first */}+ <AvatarChip name={initials(me.name)} color={me.color} title={`${me.name} (you)`} />+ {collaborators.slice(0, 3).map((c) => (+ <AvatarChip key={c.id} name={initials(c.name)} color={c.color} title={c.name} />+ ))}+ {collaborators.length > 3 && (+ <span className="w-6 h-6 rounded-full bg-white/20 border-2 border-[#4B2E93] text-[9px] font-bold text-white flex items-center justify-center">+ +{collaborators.length - 3}+ </span>+ )}+ </button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-64 rounded-2xl bg-[#16181D] border-white/10 text-white p-3">+ <div className="text-xs font-semibold text-white/60 mb-2">In this design</div>+ <div className="space-y-1.5">+ <div className="flex items-center gap-2.5 rounded-lg bg-white/[0.06] p-2">+ <AvatarChip name={initials(me.name)} color={me.color} title={me.name} size={30} />+ <div className="min-w-0 flex-1">+ <div className="text-[13px] font-semibold truncate">{me.name} (you)</div>+ <div className="text-[11px] text-white/45">Editing</div>+ </div>+ </div>+ {collaborators.map((c) => (+ <div key={c.id} className="flex items-center gap-2.5 rounded-lg p-2 hover:bg-white/[0.05]">+ <AvatarChip name={initials(c.name)} color={c.color} title={c.name} size={30} />+ <div className="min-w-0 flex-1">+ <div className="text-[13px] font-semibold truncate">{c.name}</div>+ <div className="text-[11px] text-white/45">+ {c.cursor ? `Page ${c.cursor.page + 1}${c.cursor.selection?.length ? ' · selecting' : ''}` : 'Viewing'}+ </div>+ </div>+ </div>+ ))}+ {collaborators.length === 0 && (+ <div className="text-[12px] text-white/40 px-2 pb-1">+ Share the design link to edit together in real time.+ </div>+ )}+ </div>+ <NameEditor current={me.name} />+ </PopoverContent>+ </Popover>+ </div>+ )+}++function NameEditor({ current }: { current: string }) {+ const [name, setName] = useState(current)+ return (+ <div className="mt-3 pt-3 border-t border-white/10 flex items-center gap-2">+ <Pencil size={12} className="text-white/40 shrink-0" />+ <Input+ value={name}+ maxLength={40}+ onChange={(e) => setName(e.target.value)}+ onBlur={() => setDisplayName(name)}+ onKeyDown={(e) => e.key === 'Enter' && e.currentTarget.blur()}+ placeholder="Your display name"+ className="h-8 text-[12px] bg-white/[0.06] border-white/10 text-white placeholder:text-white/30"+ aria-label="Your display name"+ />+ </div>+ )+}++function AvatarChip({ name, color, title, size = 24 }: { name: string; color: string; title: string; size?: number }) {+ return (+ <span+ className={cn('rounded-full flex items-center justify-center text-[9px] font-bold text-white border-2 border-[#4B2E93] shrink-0')}+ style={{ width: size, height: size, background: color, fontSize: size >= 30 ? '11px' : '9px' }}+ title={title}+ >+ {name}+ </span>+ )+}diff --git a/src/components/editor/PreviewOverlay.tsx b/src/components/editor/PreviewOverlay.tsxindex bd068ce..661efee 100644--- a/src/components/editor/PreviewOverlay.tsx+++ b/src/components/editor/PreviewOverlay.tsx@@ -1,15 +1,40 @@'use client'-import { useCallback, useEffect, useState } from 'react'+import { useCallback, useEffect, useRef, useState } from 'react'import dynamic from 'next/dynamic'-import { ChevronLeft, ChevronRight, X, Play } from 'lucide-react'+import { ChevronLeft, ChevronRight, Pause, Play, X, VolumeX } from 'lucide-react'import { useEditorStore } from '@/store/editor-store'import { Button } from '@/components/ui/button'import { cn } from '@/lib/utils'+import { pageHoldDuration } from '@/lib/animations'const PreviewStage = dynamic(() => import('./canvas/preview-stage'), { ssr: false })-/** Canva-style fullscreen Preview — presents pages, arrow-key navigation. */+/** page transition CSS — applied to the outgoing/incoming page wrappers */+function transitionClass(kind: string | undefined, phase: 'in' | 'out', direction: string | undefined): string {+ const dir = direction ?? 'left'+ switch (kind) {+ case 'fade':+ return phase === 'out' ? 'opacity-0' : ''+ case 'slide': {+ if (phase === 'out') {+ return dir === 'left' || dir === 'right'+ ? dir === 'left' ? '-translate-x-full' : 'translate-x-full'+ : dir === 'up' ? '-translate-y-full' : 'translate-y-full'+ }+ return ''+ }+ case 'morph':+ return phase === 'out' ? 'opacity-0 scale-110' : 'scale-95'+ default:+ return ''+ }+}++const TRANSITION_MS = (page: { transition?: { duration?: number } }) =>+ Math.round((page.transition?.duration ?? 0.7) * 1000)++/** Canva-style fullscreen Preview — animated pages, transitions, autoplay. */export function PreviewOverlay() {const open = useEditorStore((s) => s.previewOpen)const setOpen = useEditorStore((s) => s.setPreviewOpen)@@ -17,13 +42,40 @@ export function PreviewOverlay() {const width = useEditorStore((s) => s.width)const height = useEditorStore((s) => s.height)const [index, setIndex] = useState(0)+ /** previous index during a transition (rendered under the new page) */+ const [outgoing, setOutgoing] = useState<number | null>(null)+ const [autoPlay, setAutoPlay] = useState(false)+ const [reduceMotion, setReduceMotion] = useState(false)+ const [playKey, setPlayKey] = useState(0)+ const advanceTimer = useRef<ReturnType<typeof setTimeout> | null>(null)// clamp when pages shrink — derived at render, no effect neededconst safeIndex = Math.max(0, Math.min(index, pages.length - 1))- const next = useCallback(() => setIndex((i) => Math.min(i + 1, pages.length - 1)), [pages.length])- const prev = useCallback(() => setIndex((i) => Math.max(i - 1, 0)), [])+ const goTo = useCallback(+ (nextIdx: number) => {+ setIndex((current) => {+ const target = Math.max(0, Math.min(nextIdx, pages.length - 1))+ if (target === current) return current+ setPlayKey((k) => k + 1)+ setOutgoing(current)+ return target+ })+ },+ [pages.length]+ )++ const next = useCallback(() => goTo(safeIndex + 1), [goTo, safeIndex])+ const prev = useCallback(() => goTo(safeIndex - 1), [goTo, safeIndex])++ // clear the outgoing page once the transition finishes+ useEffect(() => {+ if (outgoing === null) return+ const t = setTimeout(() => setOutgoing(null), TRANSITION_MS(pages[safeIndex]))+ return () => clearTimeout(t)+ }, [outgoing, safeIndex, pages])+ // keyboarduseEffect(() => {if (!open) returnconst onKey = (e: KeyboardEvent) => {@@ -35,24 +87,91 @@ export function PreviewOverlay() {return () => window.removeEventListener('keydown', onKey)}, [open, next, prev, setOpen])+ // autoplay: advance after each page's hold duration+ useEffect(() => {+ if (!open || !autoPlay) return+ const page = pages[safeIndex]+ if (!page) return+ const hold = (reduceMotion ? 0 : 1) * pageHoldDuration(page) * 1000 + TRANSITION_MS(page)+ advanceTimer.current = setTimeout(() => {+ if (safeIndex >= pages.length - 1) {+ // loop back to the first page+ goTo(0)+ } else {+ next()+ }+ }, Math.max(400, hold))+ return () => {+ if (advanceTimer.current) clearTimeout(advanceTimer.current)+ }+ }, [open, autoPlay, safeIndex, pages, next, goTo, reduceMotion])+if (!open) return nullconst page = pages[safeIndex]+ const outgoingPage = outgoing !== null ? pages[outgoing] : null+ const transitionKind = page?.transition?.kind ?? 'none'+ const inClass = transitionClass(transitionKind, 'in', page?.transition?.direction)return (<div className="fixed inset-0 z-[100] bg-[#0F1015] flex flex-col" role="dialog" aria-label="Design preview"><div className="h-14 flex items-center justify-between px-3 shrink-0">- <span className="text-sm font-semibold text-white/90 px-2">+ <div className="flex items-center gap-2 text-sm font-semibold text-white/90 px-2">Preview <span className="text-white/50 font-normal">— page {safeIndex + 1} of {pages.length}</span>- </span>- <Button variant="ghost" size="icon" className="rounded-full text-white hover:bg-white/15 hover:text-white" onClick={() => setOpen(false)} aria-label="Close preview">- <X size={19} />- </Button>+ </div>+ <div className="flex items-center gap-1">+ {pages.length > 1 && (+ <Button+ variant="ghost"+ size="icon"+ className={cn('rounded-full text-white hover:bg-white/15 hover:text-white', autoPlay && 'bg-white/15')}+ onClick={() => setAutoPlay((v) => !v)}+ aria-label={autoPlay ? 'Pause autoplay' : 'Play presentation'}+ title={autoPlay ? 'Pause' : 'Auto-play'}+ >+ {autoPlay ? <Pause size={17} /> : <Play size={17} />}+ </Button>+ )}+ <Button+ variant="ghost"+ size="icon"+ className={cn('rounded-full text-white hover:bg-white/15 hover:text-white', reduceMotion && 'bg-white/15 text-[#02C0CC]')}+ onClick={() => setReduceMotion((v) => !v)}+ aria-label="Toggle reduced motion"+ title="Reduce motion (accessibility)"+ >+ <VolumeX size={17} />+ </Button>+ <Button variant="ghost" size="icon" className="rounded-full text-white hover:bg-white/15 hover:text-white" onClick={() => setOpen(false)} aria-label="Close preview">+ <X size={19} />+ </Button>+ </div></div><div className="flex-1 min-h-0 relative bg-[#0F1015]"><div className="absolute inset-0 p-4 pb-16">- <div className="w-full h-full max-w-[min(100%,calc((100vh-10rem)*var(--ar)))] mx-auto" style={{ ['--ar' as string]: `${width / height}` }}>- {page && <PreviewStage page={page} designWidth={width} designHeight={height} />}+ <div className="relative w-full h-full max-w-[min(100%,calc((100vh-10rem)*var(--ar)))] mx-auto" style={{ ['--ar' as string]: `${width / height}` }}>+ {/* outgoing page (during a transition) */}+ {outgoingPage && (+ <div+ key={`out-${outgoing}-${playKey}`}+ className="absolute inset-0 transition-all ease-in-out"+ style={{ transitionDuration: `${TRANSITION_MS(pages[safeIndex] ?? {})}ms` }}+ >+ <div className={cn('w-full h-full transition-all ease-in-out', transitionClass(transitionKind, 'out', page?.transition?.direction))} style={{ transitionDuration: `${TRANSITION_MS(pages[safeIndex] ?? {})}ms` }}>+ <PreviewStage page={outgoingPage} designWidth={width} designHeight={height} animated={false} />+ </div>+ </div>+ )}+ {/* current page */}+ {page && (+ <div+ key={`in-${page.id}-${playKey}`}+ className={cn('absolute inset-0 transition-all ease-in-out', inClass)}+ style={{ transitionDuration: `${TRANSITION_MS(page)}ms` }}+ >+ <PreviewStage page={page} designWidth={width} designHeight={height} animated playKey={playKey} reduceMotion={reduceMotion} />+ </div>+ )}</div></div>@@ -68,7 +187,7 @@ export function PreviewOverlay() {</button><buttononClick={next}- disabled={safeIndex === pages.length - 1}+ disabled={safeIndex === pages.length - 1 && !autoPlay}className={cn('absolute right-3 top-1/2 -translate-y-1/2 w-11 h-11 rounded-full bg-[#16171D]/90 text-white flex items-center justify-center hover:bg-[#7630D7] transition-colors disabled:opacity-30 disabled:hover:bg-[#16171D]/90')}aria-label="Next page">@@ -83,7 +202,7 @@ export function PreviewOverlay() {{pages.map((_, i) => (<buttonkey={i}- onClick={() => setIndex(i)}+ onClick={() => goTo(i)}className={cn('h-2 rounded-full transition-all', i === safeIndex ? 'w-7 bg-[#02C0CC]' : 'w-2 bg-white/25 hover:bg-white/50')}aria-label={`Go to page ${i + 1}`}aria-current={i === index}@@ -94,5 +213,3 @@ export function PreviewOverlay() {</div>)}--void Playdiff --git a/src/components/editor/TopBar.tsx b/src/components/editor/TopBar.tsxindex 5d9a516..2c1ff68 100644--- a/src/components/editor/TopBar.tsx+++ b/src/components/editor/TopBar.tsx@@ -1,7 +1,7 @@'use client'import { useState } from 'react'-import { Home, MessageCircle, Play, Share2, ChevronDown, Undo2, Redo2, Download, Github, Cloud, Check, Loader2, Ruler, History, Languages } from 'lucide-react'+import { Home, MessageCircle, Play, Share2, ChevronDown, Undo2, Redo2, Download, Github, Cloud, Check, Loader2, Ruler, History, Languages, Wand2, Zap } from 'lucide-react'import { useAppStore } from '@/store/app-store'import { useEditorStore } from '@/store/editor-store'import { Button } from '@/components/ui/button'@@ -12,6 +12,10 @@ import { ResizeDialog } from './ResizeDialog'import { ShareDialog } from './ShareDialog'import { VersionHistoryDialog } from './VersionHistoryDialog'import { TranslateDialog } from './TranslateDialog'+import { MagicLayersDialog } from './MagicLayersDialog'+import { PresenceAvatars } from './PresenceAvatars'+import { useCommentsStore } from '@/lib/comments-store'+import { markAllCommentsRead } from '@/hooks/use-comments'import { ContextToolbar } from './PropertiesBar'/** Canva-2026 editor topbar: 56px cyan→purple gradient, white text, File/Resize/Editing left, Preview/Share right. */@@ -33,12 +37,19 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; oconst selectedIds = useEditorStore((s) => s.selectedIds)const showRulers = useEditorStore((s) => s.showRulers)const toggleRulers = useEditorStore((s) => s.toggleRulers)+ const commentsOpen = useEditorStore((s) => s.commentsOpen)+ const toggleComments = useEditorStore((s) => s.toggleComments)+ const animateOpen = useEditorStore((s) => s.animateOpen)+ const toggleAnimate = useEditorStore((s) => s.toggleAnimate)+ const designId = useEditorStore((s) => s.designId)+ const unreadCount = useCommentsStore((s) => s.unreadIds.size)const [exportOpen, setExportOpen] = useState(false)const [resizeOpen, setResizeOpen] = useState(false)const [shareOpen, setShareOpen] = useState(false)const [versionsOpen, setVersionsOpen] = useState(false)const [translateOpen, setTranslateOpen] = useState(false)+ const [magicLayersOpen, setMagicLayersOpen] = useState(false)const item = 'h-10 px-3 rounded-xl text-white/95 hover:bg-white/15 transition-colors text-sm font-semibold flex items-center gap-1.5 select-none'@@ -75,6 +86,9 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; o<DropdownMenuItem className="gap-2" onClick={() => setResizeOpen(true)}><Play size={15} /> Magic Resize</DropdownMenuItem>+ <DropdownMenuItem className="gap-2" onClick={() => setMagicLayersOpen(true)}>+ <Wand2 size={15} /> Magic Layers — edit a flat design+ </DropdownMenuItem><DropdownMenuItem className="gap-2" onClick={() => setTranslateOpen(true)}><Languages size={15} /> Translate design…</DropdownMenuItem>@@ -101,8 +115,13 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; o</DropdownMenuContent></DropdownMenu>+ {/* Magic Layers */}+ <button className={cn(item, 'hidden sm:flex')} onClick={() => setMagicLayersOpen(true)} aria-label="Magic Layers">+ <Wand2 size={13} className="text-white/80" /> Magic Layers+ </button>+{/* Magic Resize */}- <button className={cn(item, 'hidden sm:flex')} onClick={() => setResizeOpen(true)} aria-label="Magic Resize">+ <button className={cn(item, 'hidden md:flex')} onClick={() => setResizeOpen(true)} aria-label="Magic Resize">Magic Resize</button>@@ -151,15 +170,25 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; o)}<div className="ml-auto flex items-center gap-0.5 sm:gap-1 shrink-0">+ {/* v0.5: collaborators + connection status */}+ <PresenceAvatars /><Button variant="ghost" size="icon" className="rounded-lg text-white hover:bg-white/15 hover:text-white" onClick={undo} disabled={!canUndo} aria-label="Undo" title="Undo (Ctrl+Z)"><Undo2 size={17} /></Button><Button variant="ghost" size="icon" className="rounded-lg text-white hover:bg-white/15 hover:text-white" onClick={redo} disabled={!canRedo} aria-label="Redo" title="Redo (Ctrl+Shift+Z)"><Redo2 size={17} /></Button>- <Button variant="ghost" size="icon" className="hidden lg:inline-flex rounded-lg text-white hover:bg-white/15 hover:text-white" onClick={() => setPanel('projects')} aria-label="Comments" title="Comments">- <MessageCircle size={17} />+ <Button variant="ghost" size="icon" className={cn('relative rounded-lg hover:bg-white/15 hover:text-white', commentsOpen ? 'text-white bg-white/15' : 'text-white')} onClick={() => { toggleComments(); if (!commentsOpen && designId) markAllCommentsRead(designId) }} aria-label="Comments" title="Comments">+ <MessageCircle size={17} className={cn(commentsOpen && 'fill-white/20')} />+ {unreadCount > 0 && (+ <span className="absolute -top-0.5 -right-0.5 min-w-[15px] h-[15px] px-1 rounded-full bg-[#FF5C8A] text-white text-[9px] font-bold flex items-center justify-center">+ {unreadCount > 9 ? '9+' : unreadCount}+ </span>+ )}</Button>+ <button className={cn(item, 'hidden sm:flex')} onClick={toggleAnimate} aria-label="Animate">+ <Zap size={13} className={cn(animateOpen && 'text-[#02C0CC]')} /> Animate+ </button><button className={cn(item, 'hidden sm:flex')} onClick={() => setPreviewOpen(true)} aria-label="Preview design"><Play size={14} /> Preview</button>@@ -176,6 +205,7 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; o<ShareDialog open={shareOpen} onOpenChange={setShareOpen} /><VersionHistoryDialog open={versionsOpen} onOpenChange={setVersionsOpen} /><TranslateDialog open={translateOpen} onOpenChange={setTranslateOpen} />+ <MagicLayersDialog open={magicLayersOpen} onOpenChange={setMagicLayersOpen} /></header>)}diff --git a/src/components/editor/add-element.ts b/src/components/editor/add-element.tsindex 1de2aa0..b281f7d 100644--- a/src/components/editor/add-element.ts+++ b/src/components/editor/add-element.ts@@ -81,6 +81,41 @@ export function addSticker(char: string) {addCentered(createStickerElement(char, { width: 200, height: 200, fontSize: 150 }))}+/**+ * v0.5 perf: downscale oversized uploads before embedding. Huge photos (e.g. 12 MP)+ * used to bloat the jsonb document; we cap the stored dataURL at 2048px longest edge+ * (print-quality for typical designs, ~85% smaller documents). PNGs with transparency+ * keep their alpha; opaque images become JPEG.+ */+export async function downscaleForEmbed(src: string, maxEdge = 2048): Promise<{ src: string; width: number; height: number }> {+ const img = await new Promise<HTMLImageElement>((resolve, reject) => {+ const i = new window.Image()+ i.onload = () => resolve(i)+ i.onerror = () => reject(new Error('load failed'))+ i.src = src+ })+ const longest = Math.max(img.naturalWidth, img.naturalHeight)+ if (longest <= maxEdge) {+ return { src, width: img.naturalWidth, height: img.naturalHeight } // already small enough+ }+ const scale = maxEdge / longest+ const w = Math.round(img.naturalWidth * scale)+ const h = Math.round(img.naturalHeight * scale)+ const canvas = document.createElement('canvas')+ canvas.width = w+ canvas.height = h+ const ctx = canvas.getContext('2d')+ if (!ctx) return { src, width: img.naturalWidth, height: img.naturalHeight }+ ctx.drawImage(img, 0, 0, w, h)+ // detect alpha: sample the corners… simple heuristic — if the source is a+ // data:image/png keep PNG, otherwise JPEG+ const isPng = src.startsWith('data:image/png')+ const out = isPng ? canvas.toDataURL('image/png') : canvas.toDataURL('image/jpeg', 0.9)+ // if PNG ballooned larger than the original, keep the original+ if (out.length > src.length && src.startsWith('data:')) return { src, width: img.naturalWidth, height: img.naturalHeight }+ return { src: out, width: w, height: h }+}+export function addImageFromSrc(src: string, naturalWidth: number, naturalHeight: number) {const state = useEditorStore.getState()const maxW = state.width * 0.7@@ -98,20 +133,29 @@ export function addImageFromSrc(src: string, naturalWidth: number, naturalHeight)}-/** loads an image then adds it to the canvas */+/** loads an image, downscales oversized sources, then adds it to the canvas */export function addImageFromFile(file: File): Promise<void> {return new Promise((resolve, reject) => {if (!file.type.startsWith('image/')) {reject(new Error('Not an image'))return}+ if (file.size > 25 * 1024 * 1024) {+ reject(new Error('Image too large (max 25 MB)'))+ return+ }const reader = new FileReader()reader.onload = () => {const src = String(reader.result)const img = new window.Image()img.onload = () => {- addImageFromSrc(src, img.naturalWidth, img.naturalHeight)- resolve()+ void downscaleForEmbed(src).then(({ src: scaled, width, height }) => {+ addImageFromSrc(scaled, width, height)+ resolve()+ }).catch(() => {+ addImageFromSrc(src, img.naturalWidth, img.naturalHeight)+ resolve()+ })}img.onerror = () => reject(new Error('Failed to load image'))img.src = srcdiff --git a/src/components/editor/apps/AssistantApp.tsx b/src/components/editor/apps/AssistantApp.tsxindex 4033020..ef2238e 100644--- a/src/components/editor/apps/AssistantApp.tsx+++ b/src/components/editor/apps/AssistantApp.tsx@@ -1,55 +1,89 @@'use client'-import { useEffect, useMemo, useRef, useState } from 'react'-import { Bot, Loader2, Plus, Send, Sparkles, User, Palette, Languages, Type, ImageIcon } from 'lucide-react'-import { createImageElement, createTextElement, type AnyElement, type TextElement } from '@/lib/types'+import { useEffect, useRef, useState } from 'react'+import { Bot, Loader2, Plus, Send, Sparkles, User, Wand2 } from 'lucide-react'+import type { AnyElement, TextElement } from '@/lib/types'import { useEditorStore } from '@/store/editor-store'import { AppHeader, type AppPanelProps } from './registry'import { cn } from '@/lib/utils'-import { toast } from '@/hooks/use-toast'--type AssistantAction =- | { type: 'addText'; text: string; fontSize?: number; bold?: boolean }- | { type: 'generateImage'; prompt: string }- | { type: 'suggestPalette'; colors: string[] }- | { type: 'translate'; language: string }+import { applyDesignAction, describeAction, type DesignAction } from '@/lib/design-actions'+import { useAICapabilities } from '@/hooks/use-ai-capabilities'interface Turn {role: 'user' | 'assistant'content: string- actions?: AssistantAction[]- done?: { action: string; msg: string }+ actions?: DesignAction[]+ done?: { index: number; msg: string }}const SUGGESTIONS = [- 'Write a bold headline for a coffee shop sale',- 'Suggest a colour palette for a beach party poster',- 'Give me 3 tagline ideas for a fitness app',- 'What visual should I generate for a tech launch?',+ 'Make this design more modern',+ 'Move the title to the top',+ 'Change all heading colors to purple',+ 'Make the layout more balanced',+ 'Add a CTA button text',+ 'Magic animate this page',]-/** Collect text contents for design context (flattens groups). */-function collectTexts(els: AnyElement[], out: TextElement[] = []): TextElement[] {+/** Flatten elements (groups included). */+function flatElements(els: AnyElement[], out: AnyElement[] = []): AnyElement[] {for (const el of els) {- if (el.type === 'text') out.push(el)- else if (el.type === 'group') collectTexts(el.children, out)+ out.push(el)+ if (el.type === 'group') flatElements(el.children, out)}return out}-const ACTION_META: Record<AssistantAction['type'], { icon: typeof Plus; label: (a: never) => string }> = {- addText: { icon: Type, label: (a: AssistantAction & { type: 'addText' }) => `Add text: "${a.text.slice(0, 42)}${a.text.length > 42 ? '…' : ''}"` },- generateImage: { icon: ImageIcon, label: (a: AssistantAction & { type: 'generateImage' }) => `Generate image: ${a.prompt.slice(0, 48)}${a.prompt.length > 48 ? '…' : ''}` },- suggestPalette: { icon: Palette, label: (a: AssistantAction & { type: 'suggestPalette' }) => `Use these colours` },- translate: { icon: Languages, label: (a: AssistantAction & { type: 'translate' }) => `Translate design to ${a.language}` },+/** Build the compact design context the assistant sees. */+function buildDesignContext() {+ const s = useEditorStore.getState()+ const page = s.pages[s.currentPage]+ const elements = (page?.elements ?? []).slice(0, 80).map((el) => {+ const base: Record<string, unknown> = {+ id: el.id,+ type: el.type,+ x: Math.round(el.x),+ y: Math.round(el.y),+ width: Math.round(el.width),+ height: Math.round(el.height),+ locked: el.locked,+ }+ if (el.type === 'text') {+ const t = el as TextElement+ base.text = t.text.slice(0, 80)+ base.fill = t.fill+ base.fontSize = Math.round(t.fontSize)+ base.bold = t.bold+ base.fontFamily = t.fontFamily+ } else if ('fill' in el) {+ base.fill = (el as { fill: string }).fill+ }+ if (el.name) base.name = el.name.slice(0, 30)+ return base+ })+ const texts = flatElements(page?.elements ?? []).filter((e) => e.type === 'text') as TextElement[]+ const colorsInUse = [...new Set(texts.map((t) => t.fill).concat((page?.elements ?? []).filter((e) => 'fill' in e).map((e) => (e as { fill: string }).fill)))].slice(0, 12)+ const fontsInUse = [...new Set(texts.map((t) => t.fontFamily))].slice(0, 8)+ return {+ name: s.designName,+ width: s.width,+ height: s.height,+ pageCount: s.pages.length,+ currentPageIndex: s.currentPage,+ selectedIds: s.selectedIds.slice(0, 20),+ elements,+ colorsInUse,+ fontsInUse,+ }}export function AssistantApp({ onClose }: AppPanelProps) {- const store = useEditorStore()const [turns, setTurns] = useState<Turn[]>([])const [input, setInput] = useState('')const [busy, setBusy] = useState(false)const scrollRef = useRef<HTMLDivElement>(null)+ const { configured: aiConfigured, loaded: aiLoaded } = useAICapabilities()+ const canUndo = useEditorStore((s) => s.past.length > 0)useEffect(() => {scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' })@@ -63,102 +97,31 @@ export function AssistantApp({ onClose }: AppPanelProps) {setTurns((ts) => [...ts, { role: 'user', content: text }])setBusy(true)try {- const texts = collectTexts(store.pages.flatMap((p) => p.elements))const res = await fetch('/api/ai/assistant', {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- message: text,- history,- design: {- name: store.designName,- width: store.width,- height: store.height,- pageCount: store.pages.length,- currentPageElements: store.pages[store.currentPage]?.elements.length ?? 0,- textContents: texts.map((t) => t.text).slice(0, 40),- },- }),+ body: JSON.stringify({ message: text, history, design: buildDesignContext() }),})- const data = (await res.json()) as { reply?: string; actions?: AssistantAction[]; error?: string }+ const data = (await res.json()) as { reply?: string; actions?: DesignAction[]; error?: string; code?: string }if (!res.ok || !data.reply) throw new Error(data.error ?? 'The assistant could not answer.')setTurns((ts) => [...ts, { role: 'assistant', content: data.reply!, actions: data.actions ?? [] }])} catch (e) {- setTurns((ts) => [...ts, { role: 'assistant', content: e instanceof Error ? e.message : 'Something went wrong.' }])+ const message = e instanceof Error ? e.message : 'Something went wrong.'+ setTurns((ts) => [...ts, { role: 'assistant', content: message }])} finally {setBusy(false)}}- /** run an attached action; mark it done on its turn */- const runAction = async (turnIndex: number, action: AssistantAction) => {- const { pages, designName, designId, width, height } = store- let msg = ''- if (action.type === 'addText') {- const el = createTextElement({- text: action.text,- fontSize: action.fontSize ?? (action.bold ? 72 : 42),- bold: action.bold ?? false,- x: width * 0.1,- y: height * 0.4,- width: width * 0.8,- align: 'center',- })- store.addElement(el)- msg = 'Text added to the canvas'- } else if (action.type === 'generateImage') {- msg = 'Image generated and added'- try {- const res = await fetch('/api/ai/image', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ prompt: action.prompt }),- })- const data = (await res.json()) as { dataUrl?: string; width?: number; height?: number; error?: string }- if (!res.ok || !data.dataUrl) throw new Error(data.error ?? 'Generation failed')- const iw = data.width ?? 1024- const ih = data.height ?? 1024- const scale = Math.min((width * 0.7) / iw, (height * 0.7) / ih, 1)- store.addElement(- createImageElement(data.dataUrl, iw, ih, {- x: (width - iw * scale) / 2,- y: (height - ih * scale) / 2,- width: Math.round(iw * scale),- height: Math.round(ih * scale),- })- )- } catch (e) {- msg = e instanceof Error ? e.message : 'Image generation failed'- }- } else if (action.type === 'suggestPalette') {- // apply as the page's Brand Kit palette + toast- const brand = { ...store.brand, palettes: [action.colors, ...(store.brand.palettes ?? [])].slice(0, 4) }- store.setBrand(brand)- msg = 'Palette saved to your Brand Kit'- } else if (action.type === 'translate') {- const texts = collectTexts(pages.flatMap((p) => p.elements))- if (!texts.length) {- msg = 'No text to translate'- } else {- msg = `Translated ${texts.length} text${texts.length === 1 ? '' : 's'} to ${action.language}`- try {- const res = await fetch('/api/ai/translate', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ language: action.language, texts: texts.map((t) => t.text) }),- })- const data = (await res.json()) as { translations?: string[]; error?: string }- if (!res.ok || !Array.isArray(data.translations) || data.translations.length !== texts.length) {- throw new Error(data.error ?? 'Translation failed')- }- store.translateTexts(texts.map((t, i) => ({ id: t.id, text: data.translations![i] })))- } catch (e) {- msg = e instanceof Error ? e.message : 'Translation failed'- }- }+ /** Execute one attached action (undoable via Ctrl+Z). */+ const runAction = async (turnIndex: number, actionIndex: number, action: DesignAction) => {+ let msg: string+ try {+ msg = await applyDesignAction(action)+ } catch (e) {+ msg = e instanceof Error ? e.message : 'Action failed'}- toast({ title: 'Canvix AI', description: msg })- setTurns((ts) => ts.map((t, i) => (i === turnIndex ? { ...t, done: { action: action.type, msg } } : t)))+ setTurns((ts) => ts.map((t, i) => (i === turnIndex ? { ...t, done: { index: actionIndex, msg } } : t)))}const empty = turns.length === 0 && !busy@@ -167,6 +130,14 @@ export function AssistantApp({ onClose }: AppPanelProps) {<div className="flex flex-col"><AppHeader icon={Bot} title="Canvix AI assistant" onClose={onClose} />+ {/* AI provider missing — honest notice */}+ {aiLoaded && !aiConfigured && (+ <div className="rounded-xl border border-amber-400/30 bg-amber-400/10 p-2.5 text-[11px] text-amber-200/80 mb-2.5">+ <strong>AI provider not configured.</strong> Design actions, Magic Write and image generation need a server+ AI provider. Layout balancing and palettes still work locally.+ </div>+ )}+{/* chat log */}<div ref={scrollRef} className="h-[340px] overflow-y-auto cv-scroll rounded-xl border border-white/10 bg-white/[0.03] p-2.5 space-y-2.5 mb-2.5">{empty && (@@ -174,10 +145,10 @@ export function AssistantApp({ onClose }: AppPanelProps) {<div className="w-11 h-11 rounded-2xl bg-gradient-to-br from-[#7630D7] to-[#02C0CC] flex items-center justify-center shadow-lg"><Sparkles size={20} className="text-white" /></div>- <p className="text-[13px] font-bold text-white">Your creative copilot</p>+ <p className="text-[13px] font-bold text-white">Your design-aware copilot</p><p className="text-[11px] text-white/50 leading-snug">- Ask for headline ideas, colour palettes, taglines — or let it generate images and- translate the whole design. It sees your current design.+ It sees your page — elements, colors, fonts and layout. Ask it to restyle, move, recolor or animate+ anything. Every change is undoable (Ctrl+Z).</p></div>)}@@ -207,28 +178,35 @@ export function AssistantApp({ onClose }: AppPanelProps) {{t.actions && t.actions.length > 0 && (<div className="mt-1.5 space-y-1">{t.actions.map((a, j) => {- const meta = ACTION_META[a.type]- const done = t.done?.action === a.type- const Icon = meta.icon+ const done = t.done?.index === jreturn (- <button- key={j}- disabled={done}- onClick={() => void runAction(i, a)}- className={cn(- 'w-full flex items-center gap-2 rounded-xl border px-2.5 py-2 text-left text-[11px] font-semibold transition-colors',- done- ? 'border-[#02C0CC]/30 bg-[#02C0CC]/10 text-[#7BE8EC]'- : 'border-[#7630D7]/40 bg-[#7630D7]/15 text-white hover:bg-[#7630D7]/30'- )}- >- <Icon size={13} className="shrink-0" />- <span className="min-w-0 truncate">{done ? t.done?.msg : meta.label(a as never)}</span>- {!done && <Plus size={11} className="ml-auto shrink-0" />}- </button>+ <div key={j} className="flex gap-1.5">+ <button+ disabled={done}+ onClick={() => void runAction(i, j, a)}+ className={cn(+ 'flex-1 flex items-center gap-2 rounded-xl border px-2.5 py-2 text-left text-[11px] font-semibold transition-colors',+ done+ ? 'border-[#02C0CC]/30 bg-[#02C0CC]/10 text-[#7BE8EC]'+ : 'border-[#7630D7]/40 bg-[#7630D7]/15 text-white hover:bg-[#7630D7]/30 cursor-pointer'+ )}+ >+ <Wand2 size={12} className="shrink-0" />+ <span className="min-w-0 truncate">{done ? t.done?.msg : describeAction(a)}</span>+ {!done && <Plus size={11} className="ml-auto shrink-0" />}+ </button>+ </div>)})}- {a_chipSwatches(t)}+ {t.done && canUndo && (+ <button+ onClick={() => useEditorStore.getState().undo()}+ className="text-[10px] font-semibold text-white/40 hover:text-white/80 underline underline-offset-2 cursor-pointer"+ >+ Undo last change (Ctrl+Z)+ </button>+ )}+ <PaletteSwatches turn={t} /></div>)}</div>@@ -256,7 +234,7 @@ export function AssistantApp({ onClose }: AppPanelProps) {<buttonkey={s}onClick={() => void send(s)}- className="block w-full text-left text-[11px] text-white/55 hover:text-white rounded-lg border border-white/[0.07] hover:border-white/20 px-2.5 py-1.5 transition-colors"+ className="block w-full text-left text-[11px] text-white/55 hover:text-white rounded-lg border border-white/[0.07] hover:border-white/20 px-2.5 py-1.5 transition-colors cursor-pointer">“{s}”</button>@@ -291,12 +269,11 @@ export function AssistantApp({ onClose }: AppPanelProps) {}/** inline palette preview for suggestPalette actions */-function a_chipSwatches(turn: Turn) {- const palette = turn.actions?.find((a) => a.type === 'suggestPalette') as { colors: string[] } | undefined- if (!palette) return null- const done = turn.done?.action === 'suggestPalette'+function PaletteSwatches({ turn }: { turn: Turn }) {+ const palette = turn.actions?.find((a) => a.type === 'suggestPalette') as { colors?: string[] } | undefined+ if (!palette?.colors?.length) return nullreturn (- <div className="flex gap-1 pt-0.5" aria-hidden={done}>+ <div className="flex gap-1 pt-0.5">{palette.colors.map((c) => (<span key={c} className="flex-1 h-4 rounded-md border border-white/15" style={{ background: c }} title={c} />))}diff --git a/src/components/editor/canvas/CanvasStage.tsx b/src/components/editor/canvas/CanvasStage.tsxindex 939a571..ace9f36 100644--- a/src/components/editor/canvas/CanvasStage.tsx+++ b/src/components/editor/canvas/CanvasStage.tsx@@ -12,6 +12,9 @@ import { Rulers } from './rulers'import type { TextElement } from '@/lib/types'import { createStrokeElement } from '@/lib/types'import { CanvasContextMenu, type ContextMenuState } from './context-menu'+import { CollabOverlay } from './CollabOverlay'+import { CommentPins } from './CommentPins'+import { getActiveCollabSession } from '@/hooks/use-collab'/** canva-measured tokens */const GUIDE_COLOR = '#9954FF' // rgb(153,84,255) — measured 2026-09-03@@ -50,6 +53,10 @@ export default function CanvasStage() {const addManualGuide = useEditorStore((s) => s.addManualGuide)const moveManualGuide = useEditorStore((s) => s.moveManualGuide)const removeManualGuide = useEditorStore((s) => s.removeManualGuide)+ // v0.5: collaboration+ const collaborators = useEditorStore((s) => s.collaborators)+ // v0.5: comments mode+ const commentsOpen = useEditorStore((s) => s.commentsOpen)const [containerSize, setContainerSize] = useState({ w: 0, h: 0 })const [pan, setPan] = useState({ x: 0, y: 0 })@@ -67,7 +74,7 @@ export default function CanvasStage() {const marqueeRef = useRef(false)const spaceRef = useRef(false)- const interactive = editingMode === 'editing' && tool === 'select'+ const interactive = editingMode === 'editing' && tool === 'select' && !commentsOpenconst userZoomedRef = useRef(false)const prevZoomRef = useRef(zoom)@@ -268,6 +275,28 @@ export default function CanvasStage() {)}, [editingTextId, editValue])+ // ── v0.5: local cursor broadcast (throttled inside the session) ─+ useEffect(() => {+ const container = containerRef.current+ if (!container) return+ const onMove = (e: MouseEvent) => {+ const rect = container.getBoundingClientRect()+ if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) return+ const px = (e.clientX - rect.left - pan.x) / zoom+ const py = (e.clientY - rect.top - pan.y) / zoom+ if (!Number.isFinite(px) || !Number.isFinite(py)) return+ const session = getActiveCollabSession()+ session?.sendCursor({+ page: useEditorStore.getState().currentPage,+ x: Math.max(-500, Math.min(px, 100000)),+ y: Math.max(-500, Math.min(py, 100000)),+ selection: useEditorStore.getState().selectedIds.slice(0, 50),+ })+ }+ container.addEventListener('mousemove', onMove)+ return () => container.removeEventListener('mousemove', onMove)+ }, [pan, zoom])+// ── empty-area pan (space+drag / middle-mouse / touch) ─────const beginPan = (clientX: number, clientY: number) => {panGestureRef.current = { active: true, startX: clientX, startY: clientY, baseX: pan.x, baseY: pan.y }@@ -361,6 +390,22 @@ export default function CanvasStage() {const handleStageMouseDown = (e: KonvaEventObject<MouseEvent>) => {if (editingMode !== 'editing') return+ // v0.5: comments mode — clicking the canvas drops a comment pin+ // (clicking an element anchors the pin to that element — canva behaviour)+ if (commentsOpen) {+ if (e.evt.button === 0) {+ const pt = pagePoint(e.evt.clientX, e.evt.clientY)+ if (pt) {+ // resolve the top-level element under the click (walk up from the target)+ let elementId: string | null = null+ let node: Konva.Node | null = e.target+ while (node && node.parent && node.parent !== layerRef.current) node = node.parent+ if (node && node !== stageRef.current && node.id()) elementId = node.id()+ window.dispatchEvent(new CustomEvent('canvix:comment-drop', { detail: { ...pt, elementId } }))+ }+ }+ return+ }if (tool === 'draw') {const stage = stageRef.currentconst pointer = stage?.getPointerPosition()@@ -739,6 +784,14 @@ export default function CanvasStage() {</Stage>)}+ {/* v0.5: remote collaborator cursors + selections (DOM overlay, never blocks input) */}+ {collaborators.length > 0 && (+ <CollabOverlay collaborators={collaborators} currentPage={currentPage} pan={pan} zoom={zoom} elements={page.elements} />+ )}++ {/* v0.5: comment pins (comments mode) */}+ {commentsOpen && <CommentPins pan={pan} zoom={zoom} />}+{/* v0.3.1: rulers overlay (desktop) */}{showRulers && containerSize.w > 0 && (<Rulersdiff --git a/src/components/editor/canvas/CollabOverlay.tsx b/src/components/editor/canvas/CollabOverlay.tsxnew file mode 100644index 0000000..248581a--- /dev/null+++ b/src/components/editor/canvas/CollabOverlay.tsx@@ -0,0 +1,77 @@+'use client'++import { memo } from 'react'+import type { Collaborator } from '@/lib/collab/protocol'++/**+ * Remote collaborator cursors + selections — DOM overlay above the Konva+ * stage (never enters Konva's render path; zero cost to canvas perf).+ */+export const CollabOverlay = memo(function CollabOverlay({+ collaborators,+ currentPage,+ pan,+ zoom,+ elements,+}: {+ collaborators: Collaborator[]+ currentPage: number+ pan: { x: number; y: number }+ zoom: number+ elements: { id: string; x: number; y: number; width: number; height: number }[]+}) {+ const byId = new Map(elements.map((e) => [e.id, e]))++ return (+ <div className="absolute inset-0 pointer-events-none overflow-hidden z-10">+ {collaborators.map((c) => {+ if (!c.cursor || c.cursor.page !== currentPage) return null+ const cx = pan.x + c.cursor.x * zoom+ const cy = pan.y + c.cursor.y * zoom++ const sel = (c.cursor.selection ?? [])+ .map((selId) => byId.get(selId))+ .filter(Boolean)+ .map((el) => {+ const ex = pan.x + el!.x * zoom+ const ey = pan.y + el!.y * zoom+ return (+ <div+ key={`${c.id}-${el!.id}`}+ className="absolute border-2 rounded-[2px]"+ style={{+ left: ex,+ top: ey,+ width: el!.width * zoom,+ height: el!.height * zoom,+ borderColor: c.color,+ boxShadow: `0 0 0 1px rgba(0,0,0,0.25) inset`,+ }}+ />+ )+ })++ return (+ <div key={c.id}>+ {sel}+ {/* cursor arrow (canva-style colored pointer with name tag) */}+ <div+ className="absolute transition-transform duration-75 ease-linear will-change-transform"+ style={{ transform: `translate(${cx}px, ${cy}px)` }}+ >+ <svg width="18" height="24" viewBox="0 0 18 24" style={{ filter: 'drop-shadow(0 1px 2px rgba(0,0,0,0.45))' }}>+ <path d="M2 1 L2 19 L6.5 15 L9.5 22 L12.5 20.5 L9.5 14 L15.5 14 Z" fill={c.color} stroke="#FFFFFF" strokeWidth="1.3" />+ </svg>+ <span+ className="absolute left-4 top-5 whitespace-nowrap rounded-md px-1.5 py-0.5 text-[11px] font-semibold text-white shadow"+ style={{ background: c.color }}+ >+ {c.name}+ </span>+ </div>+ </div>+ )+ })}+ </div>+ )+})diff --git a/src/components/editor/canvas/CommentPins.tsx b/src/components/editor/canvas/CommentPins.tsxnew file mode 100644index 0000000..0bfb591--- /dev/null+++ b/src/components/editor/canvas/CommentPins.tsx@@ -0,0 +1,295 @@+'use client'++import { useEffect, useState } from 'react'+import { Check, MessageSquare, Send, X } from 'lucide-react'+import { useEditorStore } from '@/store/editor-store'+import { buildThreads, useCommentsStore, type CommentRecord } from '@/lib/comments-store'+import { getIdentity } from '@/lib/collab/identity'+import { cn } from '@/lib/utils'+import { toast } from '@/hooks/use-toast'+import { Button } from '@/components/ui/button'++/**+ * Comment pins on the canvas (comments mode).+ * - click empty canvas → drop a pin + composer+ * - click a pin → open its thread bubble+ * - pins anchor at page-coordinate fractions; element-anchored pins follow+ * the element position+ */+export function CommentPins({ pan, zoom }: { pan: { x: number; y: number }; zoom: number }) {+ const pages = useEditorStore((s) => s.pages)+ const currentPage = useEditorStore((s) => s.currentPage)+ const designId = useEditorStore((s) => s.designId)+ const width = useEditorStore((s) => s.width)+ const height = useEditorStore((s) => s.height)+ const comments = useCommentsStore((s) => s.comments)+ const openThreadId = useCommentsStore((s) => s.openThreadId)++ const [draft, setDraft] = useState<{ x: number; y: number; elementId: string | null } | null>(null)+ const [draftText, setDraftText] = useState('')+ const [busy, setBusy] = useState(false)++ const page = pages[currentPage]++ // canvas click → new draft pin (CanvasStage dispatches in comments mode)+ useEffect(() => {+ const onDrop = (e: Event) => {+ const detail = (e as CustomEvent<{ x: number; y: number; elementId?: string | null }>).detail+ if (!detail || !page) return+ setDraft({ x: Math.round(detail.x), y: Math.round(detail.y), elementId: detail.elementId ?? null })+ setDraftText('')+ }+ window.addEventListener('canvix:comment-drop', onDrop)+ return () => window.removeEventListener('canvix:comment-drop', onDrop)+ }, [page])++ if (!page) return null++ const threads = buildThreads(comments).filter((t) => t.root.pageId === page.id)++ // element anchor resolution: pin follows its element+ const resolvePinPos = (thread: (typeof threads)[number]): { x: number; y: number } => {+ const root = thread.root+ if (root.elementId) {+ const el = page.elements.find((e) => e.id === root.elementId)+ if (el) return { x: el.x + el.width, y: el.y } // pin at element's top-right corner+ }+ return { x: root.x * width, y: root.y * height }+ }++ const postDraft = async () => {+ const text = draftText.trim()+ if (!text || !designId || !draft || busy) return+ setBusy(true)+ const identity = getIdentity()+ try {+ const res = await fetch(`/api/designs/${encodeURIComponent(designId)}/comments`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ pageId: page.id,+ x: draft.x / width,+ y: draft.y / height,+ elementId: draft.elementId,+ authorId: identity.id,+ authorName: identity.name,+ authorColor: identity.color,+ body: text,+ }),+ })+ if (!res.ok) throw new Error('failed')+ const created = (await res.json()) as CommentRecord+ // optimistic insert — the author sees the pin immediately+ useCommentsStore.getState().upsertComment(created)+ window.dispatchEvent(new CustomEvent('canvix:comments-changed'))+ setDraft(null)+ setDraftText('')+ } catch {+ toast({ title: 'Could not post the comment.' })+ } finally {+ setBusy(false)+ }+ }++ return (+ <div className="absolute inset-0 z-20 pointer-events-none">+ {/* existing pins */}+ {threads.map((t) => {+ const pos = resolvePinPos(t)+ const open = openThreadId === t.root.id+ return (+ <div key={t.root.id} className="pointer-events-auto absolute" style={{ left: pan.x + pos.x * zoom, top: pan.y + pos.y * zoom }}>+ <button+ className={cn(+ 'flex items-center gap-1 rounded-full h-8 pl-1.5 pr-2.5 shadow-lg transition-all -translate-y-1/2 cursor-pointer',+ t.root.resolved ? 'bg-emerald-600/90 text-white' : 'bg-[#2A6EF4] text-white hover:bg-[#2A6EF4]/90'+ )}+ style={{ transform: `translate(0, -50%) scale(${Math.max(0.75, Math.min(1.4, zoom))})` }}+ onClick={() => useCommentsStore.getState().setOpenThreadId(open ? null : t.root.id)}+ aria-label={`Comment: ${t.root.body.slice(0, 40)}`}+ >+ <span className="w-6 h-6 rounded-full bg-white/25 flex items-center justify-center text-[10px] font-bold">+ {t.root.authorName.trim().split(/\s+/).slice(0, 2).map((p) => p[0]?.toUpperCase() ?? '').join('') || '?'}+ </span>+ {t.replies.length > 0 && <span className="text-[10px] font-semibold">{t.replies.length + 1}</span>}+ {t.root.resolved && <Check size={11} />}+ </button>++ {/* thread bubble */}+ {open && (+ <div className="absolute left-0 top-6 w-64 rounded-xl bg-[#16181D] border border-white/15 shadow-2xl p-2.5 z-30" style={{ transform: `scale(${Math.max(0.8, Math.min(1.2, zoom))})`, transformOrigin: 'top left' }}>+ <ThreadBubble thread={t} designId={designId} />+ </div>+ )}+ </div>+ )+ })}++ {/* new-pin composer */}+ {draft && (+ <div+ className="pointer-events-auto absolute w-64 rounded-xl bg-[#16181D] border border-white/15 shadow-2xl p-2.5 z-30"+ style={{ left: pan.x + draft.x * zoom, top: pan.y + draft.y * zoom }}+ >+ <div className="flex items-center justify-between mb-1.5">+ <span className="text-[11px] font-semibold text-white/80">New comment</span>+ <button className="text-white/40 hover:text-white cursor-pointer" onClick={() => setDraft(null)} aria-label="Cancel comment">+ <X size={12} />+ </button>+ </div>+ <textarea+ value={draftText}+ onChange={(e) => setDraftText(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault()+ void postDraft()+ }+ e.stopPropagation()+ }}+ autoFocus+ rows={3}+ maxLength={2000}+ placeholder="Type your comment…"+ className="w-full rounded-lg bg-white/[0.06] border border-white/10 px-2.5 py-2 text-[12px] text-white placeholder:text-white/30 outline-none focus:border-[#02C0CC]/50 resize-none"+ />+ <div className="flex justify-end gap-1.5 mt-2">+ <Button size="sm" variant="ghost" className="h-7 text-[11px] text-white/60 hover:bg-white/10 hover:text-white" onClick={() => setDraft(null)}>+ Cancel+ </Button>+ <Button size="sm" className="h-7 px-3 text-[11px] btn-brand-gradient gap-1" disabled={!draftText.trim() || busy} onClick={() => void postDraft()}>+ <Send size={10} /> Post+ </Button>+ </div>+ </div>+ )}+ </div>+ )+}++function ThreadBubble({ thread, designId }: { thread: ReturnType<typeof buildThreads>[number]; designId: string | null }) {+ const { root, replies } = thread+ const [replyText, setReplyText] = useState('')+ const [busy, setBusy] = useState(false)+ const me = getIdentity()++ const timeAgo = (iso: string) => {+ const s = Math.max(0, (Date.now() - Date.parse(iso)) / 1000)+ if (s < 60) return 'just now'+ if (s < 3600) return `${Math.floor(s / 60)}m`+ if (s < 86_400) return `${Math.floor(s / 3600)}h`+ return `${Math.floor(s / 86_400)}d`+ }++ const addReply = async () => {+ const text = replyText.trim()+ if (!text || !designId || busy) return+ setBusy(true)+ try {+ const res = await fetch(`/api/designs/${encodeURIComponent(designId)}/comments`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ pageId: root.pageId,+ x: root.x,+ y: root.y,+ parentId: root.id,+ authorId: me.id,+ authorName: me.name,+ authorColor: me.color,+ body: text,+ }),+ })+ if (!res.ok) throw new Error('failed')+ const created = (await res.json()) as CommentRecord+ useCommentsStore.getState().upsertComment(created) // optimistic+ setReplyText('')+ } catch {+ toast({ title: 'Could not post the reply.' })+ } finally {+ setBusy(false)+ }+ }++ const toggleResolve = async () => {+ if (!designId) return+ try {+ const res = await fetch(`/api/comments/${encodeURIComponent(root.id)}`, {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ resolved: !root.resolved, actorId: me.id }),+ })+ if (res.ok) {+ // optimistic update for the author + converge with a fresh fetch+ useCommentsStore.getState().upsertComment({ ...root, resolved: !root.resolved })+ window.dispatchEvent(new CustomEvent('canvix:comments-changed'))+ }+ } catch {+ toast({ title: 'Could not update the comment.' })+ }+ }++ const del = async () => {+ if (!designId) return+ try {+ const res = await fetch(`/api/comments/${encodeURIComponent(root.id)}?actorId=${encodeURIComponent(me.id)}`, { method: 'DELETE' })+ if (res.ok) {+ useCommentsStore.getState().removeComment(root.id) // optimistic+ useCommentsStore.getState().setOpenThreadId(null)+ window.dispatchEvent(new CustomEvent('canvix:comments-changed'))+ }+ } catch {+ toast({ title: 'Could not delete the comment.' })+ }+ }++ return (+ <div onClick={(e) => e.stopPropagation()}>+ <div className="flex items-center gap-1.5 mb-1">+ <span className="w-5 h-5 rounded-full flex items-center justify-center text-[8px] font-bold text-white shrink-0" style={{ background: root.authorColor }}>+ {root.authorName.trim().split(/\s+/).slice(0, 2).map((p) => p[0]?.toUpperCase() ?? '').join('') || '?'}+ </span>+ <span className="text-[11px] font-semibold text-white/90 truncate">{root.authorName}</span>+ <span className="text-[10px] text-white/35 shrink-0">{timeAgo(root.createdAt)}</span>+ </div>+ <p className="text-[12px] text-white/80 break-words">{root.body}</p>+ {replies.map((r) => (+ <div key={r.id} className="mt-1.5 pl-2 border-l border-white/10">+ <div className="flex items-center gap-1.5">+ <span className="text-[10px] font-semibold text-white/70">{r.authorName}</span>+ <span className="text-[9px] text-white/30">{timeAgo(r.createdAt)}</span>+ </div>+ <p className="text-[11px] text-white/60 break-words">{r.body}</p>+ </div>+ ))}++ <div className="flex items-center gap-1.5 mt-2">+ <input+ value={replyText}+ onChange={(e) => setReplyText(e.target.value)}+ onKeyDown={(e) => e.key === 'Enter' && void addReply()}+ placeholder="Reply…"+ maxLength={2000}+ className="flex-1 h-7 rounded-lg bg-white/[0.06] border border-white/10 px-2 text-[11px] text-white placeholder:text-white/30 outline-none focus:border-[#02C0CC]/50"+ />+ <Button size="sm" className="h-7 w-7 p-0 btn-brand-gradient" disabled={!replyText.trim() || busy} onClick={() => void addReply()} aria-label="Send reply">+ <Send size={10} />+ </Button>+ </div>++ <div className="flex items-center gap-2 mt-2 pt-2 border-t border-white/[0.08]">+ <button className="text-[10px] font-semibold text-white/50 hover:text-white flex items-center gap-1 cursor-pointer" onClick={() => void toggleResolve()}>+ <Check size={10} /> {root.resolved ? 'Reopen' : 'Resolve'}+ </button>+ {root.authorId === me.id && (+ <button className="text-[10px] font-semibold text-white/50 hover:text-red-300 flex items-center gap-1 cursor-pointer" onClick={() => void del()}>+ <X size={10} /> Delete+ </button>+ )}+ <span className="ml-auto text-[9px] text-white/25 flex items-center gap-0.5">+ <MessageSquare size={8} /> {replies.length + 1}+ </span>+ </div>+ </div>+ )+}diff --git a/src/components/editor/canvas/preview-stage.tsx b/src/components/editor/canvas/preview-stage.tsxindex f204ed7..c6ba8ac 100644--- a/src/components/editor/canvas/preview-stage.tsx+++ b/src/components/editor/canvas/preview-stage.tsx@@ -1,20 +1,34 @@'use client'import { useEffect, useRef, useState } from 'react'+import type Konva from 'konva'import { Layer, Rect, Stage } from 'react-konva'import type { PageData } from '@/lib/types'import { gradientProps } from '@/lib/editor-utils'+import { animateElementAt, pageAnimationDuration } from '@/lib/animations'import { PreviewElements } from './element-node'interface PreviewStageProps {page: PageDatadesignWidth: numberdesignHeight: number+ /** v0.5: play element animations (preview mode) */+ animated?: boolean+ /** reset the timeline (bump = restart) */+ playKey?: number+ /** reduce-motion accessibility — jumps to the final state */+ reduceMotion?: boolean}-/** Renders one page of a design, scaled to fit its parent box. Non-interactive, clipped to page bounds. */-export default function PreviewStage({ page, designWidth, designHeight }: PreviewStageProps) {+/**+ * Renders one page of a design, scaled to fit its parent box. Non-interactive,+ * clipped to page bounds. When `animated`, runs a rAF timeline that applies+ * entry animations to the element nodes (never mutates the document).+ */+export default function PreviewStage({ page, designWidth, designHeight, animated = true, playKey = 0, reduceMotion = false }: PreviewStageProps) {const containerRef = useRef<HTMLDivElement>(null)+ const layerRef = useRef<Konva.Layer | null>(null)+ const stageRef = useRef<Konva.Stage | null>(null)const [size, setSize] = useState({ w: 0, h: 0 })useEffect(() => {@@ -38,14 +52,93 @@ export default function PreviewStage({ page, designWidth, designHeight }: Previe? gradientProps(bg.from, bg.to, bg.angle, designWidth, designHeight): { fill: bg.color }+ // ── v0.5: element animation playback (rAF timeline over Konva nodes) ──+ const hasAnimations = animated && page.elements.some((e) => e.animation && e.animation.kind !== 'none')+ useEffect(() => {+ const layer = layerRef.current+ const stage = stageRef.current+ if (!layer || !stage) return+ if (!hasAnimations || reduceMotion) {+ // static: ensure all nodes are at base state+ resetNodes(layer, page)+ return+ }++ const animatable = page.elements.filter((e) => e.animation && e.animation.kind !== 'none')+ // capture base attrs once per play+ const bases = new Map<string, { x: number; y: number; opacity: number; rotation: number; scaleX: number; scaleY: number; offsetX: number; offsetY: number }>()+ for (const el of animatable) {+ const node = layer.findOne(`#${el.id}`)+ if (!node) continue+ bases.set(el.id, {+ x: node.x(),+ y: node.y(),+ opacity: node.opacity(),+ rotation: node.rotation(),+ scaleX: node.scaleX(),+ scaleY: node.scaleY(),+ offsetX: node.offsetX(),+ offsetY: node.offsetY(),+ })+ }++ const start = performance.now()+ const total = pageAnimationDuration(page) + 0.1+ let raf = 0+ let stopped = false++ const tick = (now: number) => {+ if (stopped) return+ const t = Math.min((now - start) / 1000, total)+ for (const el of animatable) {+ const node = layer.findOne(`#${el.id}`)+ const base = bases.get(el.id)+ if (!node || !base) continue+ const state = animateElementAt(el, t)+ node.opacity(base.opacity * state.opacity)+ node.x(base.x + state.dx)+ node.y(base.y + state.dy)+ // scale relative to the node center (keep the base offset trick)+ node.scaleX(base.scaleX * state.scaleX)+ node.scaleY(base.scaleY * state.scaleY)+ // wipe: approximate as a horizontal scale from the anchor edge+ if (state.reveal < 1) {+ const reveal = Math.max(0.001, state.reveal)+ node.scaleX(base.scaleX * reveal)+ const dir = el.animation?.direction ?? 'left'+ if (dir === 'left') {+ node.offsetX(base.offsetX)+ } else if (dir === 'right') {+ node.offsetX((el as { width: number }).width)+ node.x(base.x + (el as { width: number }).width)+ }+ } else {+ node.offsetX(base.offsetX)+ }+ if (state.rotation) {+ node.rotation(base.rotation + state.rotation)+ }+ }+ layer.batchDraw()+ if (t < total) raf = requestAnimationFrame(tick)+ }+ raf = requestAnimationFrame(tick)+ return () => {+ stopped = true+ cancelAnimationFrame(raf)+ resetNodes(layer, page, bases)+ }+ }, [page, hasAnimations, reduceMotion, playKey, designWidth, designHeight])+return (- <div ref={containerRef} className="w-full h-full overflow-hidden">+ <div ref={containerRef} className="w-full h-full overflow-hidden" data-testid="preview-stage">{scale > 0 && (- <Stage width={size.w} height={size.h}>+ <Stage ref={stageRef} width={size.w} height={size.h}><Layer listening={false} x={offsetX} y={offsetY} scale={{ x: scale, y: scale }}><Rect width={designWidth} height={designHeight} {...bgProps} /></Layer><Layer+ ref={layerRef}listening={false}x={offsetX}y={offsetY}@@ -59,3 +152,23 @@ export default function PreviewStage({ page, designWidth, designHeight }: Previe</div>)}++function resetNodes(layer: Konva.Layer, page: PageData, bases?: Map<string, { x: number; y: number; opacity: number; rotation: number; scaleX: number; scaleY: number; offsetX: number; offsetY: number }>) {+ for (const el of page.elements) {+ if (!el.animation || el.animation.kind === 'none') continue+ const node = layer.findOne(`#${el.id}`)+ const base = bases?.get(el.id)+ if (!node) continue+ if (base) {+ node.opacity(base.opacity)+ node.x(base.x)+ node.y(base.y)+ node.rotation(base.rotation)+ node.scaleX(base.scaleX)+ node.scaleY(base.scaleY)+ node.offsetX(base.offsetX)+ node.offsetY(base.offsetY)+ }+ }+ layer.batchDraw()+}diff --git a/src/components/editor/panels/PhotosPanel.tsx b/src/components/editor/panels/PhotosPanel.tsxindex 5d3c2ab..5bbc3b4 100644--- a/src/components/editor/panels/PhotosPanel.tsx+++ b/src/components/editor/panels/PhotosPanel.tsx@@ -167,7 +167,7 @@ export function PhotosPanel() {aria-label={`Add web photo ${p.caption || 'result'}`}title={p.caption}>- {/* eslint-disable-next-line @next/next/no-img-element */}+ { }<imgsrc={p.url}alt={p.caption || 'web photo'}diff --git a/src/hooks/use-ai-capabilities.ts b/src/hooks/use-ai-capabilities.tsnew file mode 100644index 0000000..865be09--- /dev/null+++ b/src/hooks/use-ai-capabilities.ts@@ -0,0 +1,37 @@+'use client'++import { useEffect, useState } from 'react'++/**+ * Client-side AI capability probe (public, secret-free).+ * `configured=false` → panels show "requires server AI provider" states.+ */+export function useAICapabilities() {+ const [state, setState] = useState<{+ loaded: boolean+ configured: boolean+ vision: boolean+ }>({ loaded: false, configured: false, vision: false })++ useEffect(() => {+ let cancelled = false+ fetch('/api/ai/capabilities')+ .then((r) => (r.ok ? r.json() : null))+ .then((data: { configured?: boolean; capabilities?: { vision?: boolean } } | null) => {+ if (cancelled || !data) return+ setState({+ loaded: true,+ configured: Boolean(data.configured),+ vision: Boolean(data.capabilities?.vision),+ })+ })+ .catch(() => {+ if (!cancelled) setState({ loaded: true, configured: false, vision: false })+ })+ return () => {+ cancelled = true+ }+ }, [])++ return state+}diff --git a/src/hooks/use-collab.ts b/src/hooks/use-collab.tsnew file mode 100644index 0000000..8afce27--- /dev/null+++ b/src/hooks/use-collab.ts@@ -0,0 +1,65 @@+'use client'++import { useEffect, useRef } from 'react'+import { useEditorStore, setOpEmitter } from '@/store/editor-store'+import { CollabSession } from '@/lib/collab/client'+import { getIdentity } from '@/lib/collab/identity'++/**+ * Active session hub — CanvasStage cursor tracking needs to reach the+ * session without prop-drilling through the component tree.+ */+let activeSession: CollabSession | null = null++export function getActiveCollabSession(): CollabSession | null {+ return activeSession+}++/**+ * useCollab — mounts a CollabSession for the open design.+ *+ * Wire-up:+ * store local mutations → session.emit (batched POST)+ * session SSE frames → store.applyRemoteOp / setCollaborators / setCollabStatus+ *+ * Remote ops apply WITHOUT pushing undo history (history stays local) and+ * never re-emit (no feedback loop). Local input is never blocked.+ */+export function useCollab(): void {+ const designId = useEditorStore((s) => s.designId)+ const sessionRef = useRef<CollabSession | null>(null)++ useEffect(() => {+ if (!designId || typeof window === 'undefined') return++ const identity = getIdentity()+ const session = new CollabSession(designId, identity.id, identity.name, identity.color)+ sessionRef.current = session+ activeSession = session++ session.onStatus = (s) => useEditorStore.getState().setCollabStatus(s)+ session.onEvents = (events) => {+ const store = useEditorStore.getState()+ for (const ev of events) store.applyRemoteOp(ev)+ // comment mutations ride the event log as inert activity markers →+ // the comments layer refetches (own events are SSE-filtered, but the+ // author's own posts apply optimistically in the UI)+ if (events.some((e) => e.kind === 'comment:activity')) {+ window.dispatchEvent(new CustomEvent('canvix:comments-changed'))+ }+ }+ session.onPresence = (collaborators) => useEditorStore.getState().setCollaborators(collaborators)++ setOpEmitter((op) => session.emit(op, `evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 9)}`))+ session.start()++ return () => {+ setOpEmitter(null)+ session.dispose()+ if (sessionRef.current === session) sessionRef.current = null+ if (activeSession === session) activeSession = null+ useEditorStore.getState().setCollaborators([])+ useEditorStore.getState().setCollabStatus('offline')+ }+ }, [designId])+}diff --git a/src/hooks/use-comments.ts b/src/hooks/use-comments.tsnew file mode 100644index 0000000..ca0938a--- /dev/null+++ b/src/hooks/use-comments.ts@@ -0,0 +1,84 @@+'use client'++import { useCallback, useEffect, useRef } from 'react'+import { useEditorStore } from '@/store/editor-store'+import { getIdentity } from '@/lib/collab/identity'+import {+ useCommentsStore,+ writeLastReadAt,+ readLastReadAt,+ type CommentRecord,+} from '@/lib/comments-store'++/**+ * useComments — comment CRUD for the open design + live refresh.+ *+ * Live updates piggyback on the collaboration event stream: the server+ * appends an inert `comment:activity` event on every comment mutation; the+ * collab layer sees it and triggers a refetch. Comments never enter the+ * document model.+ */+export function useComments(): void {+ const designId = useEditorStore((s) => s.designId)+ const setComments = useCommentsStore((s) => s.setComments)+ const refetchRef = useRef<() => void>(() => {})++ const refetch = useCallback(async () => {+ if (!designId) return+ try {+ const res = await fetch(`/api/designs/${encodeURIComponent(designId)}/comments`)+ if (!res.ok) return+ const list = (await res.json()) as CommentRecord[]+ if (Array.isArray(list)) {+ const me = getIdentity().id+ const lastRead = readLastReadAt(designId)+ setComments(list, me)+ // unread = others' comments newer than our last read+ const unread = new Set(+ list.filter((c) => c.authorId !== me && Date.parse(c.createdAt) > lastRead && !c.parentId).map((c) => c.id)+ )+ useCommentsStore.setState({ unreadIds: unread })+ }+ } catch {+ /* offline — keep the current list */+ }+ }, [designId, setComments])++ useEffect(() => {+ refetchRef.current = () => void refetch()+ }, [refetch])++ // initial load on design open+ useEffect(() => {+ if (!designId) return+ useCommentsStore.getState().setComments([], null)+ useCommentsStore.setState({ comments: [], loaded: false, openThreadId: null, unreadIds: new Set() })+ void refetch()+ }, [designId, refetch])++ // live refresh: the collab session dispatches 'canvix:comments-changed' when+ // a comment:activity event arrives (another participant's comment mutation)+ useEffect(() => {+ if (!designId) return+ let timer: ReturnType<typeof setTimeout> | null = null+ const onChanged = () => {+ if (timer) clearTimeout(timer)+ timer = setTimeout(() => refetchRef.current(), 250)+ }+ window.addEventListener('canvix:comments-changed', onChanged)+ // light backup poll (works even when the collab stream is proxied away)+ const poll = setInterval(() => refetchRef.current(), 15_000)+ return () => {+ window.removeEventListener('canvix:comments-changed', onChanged)+ clearInterval(poll)+ if (timer) clearTimeout(timer)+ if (designId) writeLastReadAt(designId, Date.now())+ }+ }, [designId])+}++/** mark everything as read (called when the comments panel opens) */+export function markAllCommentsRead(designId: string): void {+ writeLastReadAt(designId, Date.now())+ useCommentsStore.getState().markAllRead()+}diff --git a/src/lib/ai/provider.ts b/src/lib/ai/provider.tsnew file mode 100644index 0000000..d84e96a--- /dev/null+++ b/src/lib/ai/provider.ts@@ -0,0 +1,174 @@+import { NextResponse, type NextRequest } from 'next/server'+import { existsSync, readFileSync } from 'fs'++/**+ * Canvix AI provider abstraction (v0.5).+ *+ * Single server-side entry point for every AI capability. Centralizes:+ * - provider configuration resolution (env override → .z-ai-config file → absent)+ * - capability probing (which features can run on this server)+ * - rate limiting + AIUsage accounting+ *+ * CONTRACT: this module is SERVER-ONLY. It must never be imported from a+ * client component — the provider config contains credentials.+ */++export type AICapability =+ | 'text' // chat completions — Magic Write, Assistant, Translate+ | 'image' // image generation+ | 'imageEdit' // Magic Eraser / Enhance+ | 'vision' // image understanding — Magic Layers+ | 'imageSearch' // Photo search++export interface AIProviderConfig {+ baseUrl: string+ apiKey: string+}++/** VISION_MODEL — the multimodal model used for Magic Layers analysis. */+export const VISION_MODEL = 'glm-4.5v'++/**+ * Resolve the provider configuration.+ * Priority: ZAI_BASE_URL/ZAI_API_KEY env vars → .z-ai-config file (cwd → ~ → /etc) → null.+ * Returns null when no provider is configured (local-only mode).+ */+export function resolveProviderConfig(): AIProviderConfig | null {+ const envUrl = process.env.ZAI_BASE_URL?.trim()+ const envKey = process.env.ZAI_API_KEY?.trim()+ if (envUrl && envKey) return { baseUrl: envUrl, apiKey: envKey }+ try {+ // the SDK resolves the config file itself at ZAI.create(); mirror its lookup here+ const candidates = [+ `${process.cwd()}/.z-ai-config`,+ `${process.env.HOME ?? ''}/.z-ai-config`,+ '/etc/.z-ai-config',+ ]+ for (const p of candidates) {+ if (!p || !existsSync(p)) continue+ const raw = JSON.parse(readFileSync(p, 'utf8')) as { baseUrl?: string; apiKey?: string }+ if (raw.baseUrl && raw.apiKey) return { baseUrl: raw.baseUrl, apiKey: raw.apiKey }+ }+ } catch {+ /* unreadable config — treat as absent */+ }+ return null+}++/** Quick boolean probe used by /api/ai/capabilities and route guards. */+export function hasProvider(): boolean {+ return resolveProviderConfig() !== null+}++/**+ * Create a ZAI SDK instance (server-side only). Lazy-imports the SDK so it+ * never lands in a client bundle. Returns null when unconfigured.+ */+export async function getZAI(): Promise<import('z-ai-web-dev-sdk').default | null> {+ const cfg = resolveProviderConfig()+ if (!cfg) return null+ try {+ const { default: ZAI } = await import('z-ai-web-dev-sdk')+ return await ZAI.create()+ } catch (err) {+ console.error('[ai] provider initialization failed', err)+ return null+ }+}++// ── rate limiting (in-memory sliding window; per feature+IP) ──++interface Bucket {+ hits: number[]+}++const buckets = new Map<string, Bucket>()++export interface RateLimitResult {+ ok: boolean+ retryAfterSec: number+}++/**+ * Simple sliding-window limiter. Limits are deliberately generous for a+ * self-hosted design tool but stop runaway loops and abuse.+ */+export function rateLimit(feature: string, req: NextRequest, limit: number, windowSec: number): RateLimitResult {+ const ip =+ req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ||+ req.headers.get('x-real-ip') ||+ 'local'+ const key = `${feature}:${ip}`+ const now = Date.now()+ let bucket = buckets.get(key)+ if (!bucket) {+ bucket = { hits: [] }+ buckets.set(key, bucket)+ }+ bucket.hits = bucket.hits.filter((t) => now - t < windowSec * 1000)+ if (bucket.hits.length >= limit) {+ const oldest = bucket.hits[0]+ return { ok: false, retryAfterSec: Math.max(1, Math.ceil((oldest + windowSec * 1000 - now) / 1000)) }+ }+ bucket.hits.push(now)+ // lazy GC: occasionally drop stale buckets so the map cannot grow unbounded+ if (buckets.size > 512) {+ for (const [k, b] of buckets) {+ if (!b.hits.length || now - b.hits[b.hits.length - 1] > windowSec * 1000 * 2) buckets.delete(k)+ }+ }+ return { ok: true, retryAfterSec: 0 }+}++// ── usage accounting (best-effort, never blocks a request) ──++export async function recordUsage(feature: string, provider: 'zai' | 'local', ok: boolean): Promise<void> {+ try {+ const { db } = await import('@/lib/db')+ await db.aIUsage.create({ data: { feature, provider, ok } })+ } catch {+ /* accounting must never break the request */+ }+}++// ── shared error responses ──++export const NO_PROVIDER_RESPONSE = {+ error: 'This feature requires an AI provider configured on the server.',+ code: 'NO_PROVIDER',+} as const++/** Standard structured error body — no stack traces, no provider internals. */+export function providerUnavailable(res: NextResponse): NextResponse {+ return NextResponse.json(NO_PROVIDER_RESPONSE, { status: 503 })+}++/** Helper: wrap a route's provider call with rate limit + usage accounting. */+export async function withProvider(+ feature: string,+ req: NextRequest,+ limits: { limit: number; windowSec: number },+ fn: (zai: NonNullable<Awaited<ReturnType<typeof getZAI>>>) => Promise<NextResponse>+): Promise<NextResponse> {+ const rl = rateLimit(feature, req, limits.limit, limits.windowSec)+ if (!rl.ok) {+ return NextResponse.json(+ { error: `Too many ${feature} requests — try again in ${rl.retryAfterSec}s.` },+ { status: 429, headers: { 'Retry-After': String(rl.retryAfterSec) } }+ )+ }+ const zai = await getZAI()+ if (!zai) {+ await recordUsage(feature, 'zai', false)+ return providerUnavailable(NextResponse.json({}))+ }+ try {+ const out = await fn(zai)+ void recordUsage(feature, 'zai', true)+ return out+ } catch (err) {+ console.error(`[ai/${feature}]`, err)+ void recordUsage(feature, 'zai', false)+ return NextResponse.json({ error: 'The AI service is unavailable right now. Please try again.' }, { status: 502 })+ }+}diff --git a/src/lib/animations.ts b/src/lib/animations.tsnew file mode 100644index 0000000..80d7209--- /dev/null+++ b/src/lib/animations.ts@@ -0,0 +1,307 @@+// ─────────────────────────────────────────────────────────────+// Canvix animation engine (v0.5)+//+// Pure functions of time — completely independent from Konva.+// The same engine drives: editor preview playback, PreviewOverlay+// page playback + transitions, and video export frame rendering.+// Static exports (PNG/JPG/PDF/SVG) ignore animations entirely.+// ─────────────────────────────────────────────────────────────++import type {+ AnimationEasing,+ AnimationKind,+ AnyElement,+ ElementAnimation,+ PageData,+} from '@/lib/types'++// ── easings ──────────────────────────────────────────────────++export function applyEasing(t: number, easing: AnimationEasing): number {+ switch (easing) {+ case 'linear':+ return t+ case 'easeIn':+ return t * t * t+ case 'easeOut':+ return 1 - Math.pow(1 - t, 3)+ case 'easeInOut':+ return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2+ case 'spring': {+ // damped spring approximation+ const c = 2 * Math.PI * 0.9 // frequency+ const decay = 4.5+ return 1 - Math.exp(-decay * t) * Math.cos(c * t)+ }+ default:+ return t+ }+}++// ── per-element animation state at time t ────────────────────++export interface AnimatedElementState {+ /** 0..1 multiplier over the element's base opacity */+ opacity: number+ /** page-space translation deltas */+ dx: number+ dy: number+ /** scale multipliers (relative to base size) */+ scaleX: number+ scaleY: number+ /** additional rotation in degrees */+ rotation: number+ /** wipe reveal: 0..1 fraction of the width visible from the anchor edge */+ reveal: number+}++const IDENTITY: AnimatedElementState = {+ opacity: 1,+ dx: 0,+ dy: 0,+ scaleX: 1,+ scaleY: 1,+ rotation: 0,+ reveal: 1,+}++/** Travel distance for pan/rise — relative to element size / page. */+function travelDistance(el: { width: number; height: number }): { x: number; y: number } {+ return { x: Math.max(80, el.width * 0.35), y: Math.max(80, el.height * 0.35) }+}++/**+ * Compute an element's animated state at time `t` (seconds since the page+ * was shown). Returns IDENTITY when the animation is finished or absent.+ */+export function animateElementAt(+ el: { width: number; height: number; animation?: ElementAnimation },+ t: number+): AnimatedElementState {+ const a = el.animation+ if (!a || a.kind === 'none' || a.kind === undefined) return IDENTITY++ const local = t - (a.delay || 0)+ if (local <= 0) {+ // before the animation starts: element is at its "from" state (hidden)+ return startState(el, a)+ }+ const dur = Math.max(0.05, a.duration || 0.9)+ if (a.kind === 'breathe') {+ // continuous loop — scale pulse 1 → 1.04 → 1+ const phase = (local % dur) / dur+ const s = 1 + 0.04 * Math.sin(phase * Math.PI * 2)+ return { ...IDENTITY, scaleX: s, scaleY: s }+ }+ if (local >= dur) return IDENTITY++ const p = applyEasing(local / dur, a.easing || 'easeOut')+ const inv = 1 - p+ const travel = travelDistance(el)+ const dir = a.direction ?? 'up'++ switch (a.kind) {+ case 'fade':+ return { ...IDENTITY, opacity: p }+ case 'rise': {+ // rise = move up + fade in (direction-aware)+ const dy = dir === 'down' ? inv * travel.y : -inv * travel.y+ return { ...IDENTITY, opacity: p, dy }+ }+ case 'pan': {+ const dx = dir === 'left' ? -inv * travel.x : dir === 'right' ? inv * travel.x : 0+ const dy2 = dir === 'up' ? -inv * travel.y : dir === 'down' ? inv * travel.y : 0+ return { ...IDENTITY, dx, dy: dy2 }+ }+ case 'pop': {+ // overshoot springy scale-in+ const s = 0.6 + 0.4 * p * (1 + 0.25 * Math.sin(p * Math.PI))+ return { ...IDENTITY, scaleX: s, scaleY: s, opacity: Math.min(1, p * 1.6) }+ }+ case 'wipe': {+ // reveal from the anchor edge (scale-on-one-axis approximation)+ return { ...IDENTITY, reveal: p, opacity: 1 }+ }+ case 'zoom': {+ const s = 0.65 + 0.35 * p+ return { ...IDENTITY, scaleX: s, scaleY: s, opacity: p }+ }+ case 'rotate': {+ return { ...IDENTITY, rotation: inv * (dir === 'left' ? -90 : 90), opacity: p, scaleX: Math.max(0.1, 0.8 + 0.2 * p) }+ }+ default:+ return IDENTITY+ }+}++/** the state an element sits in before its animation starts */+function startState(+ el: { width: number; height: number },+ a: ElementAnimation+): AnimatedElementState {+ const travel = travelDistance(el)+ const dir = a.direction ?? 'up'+ switch (a.kind) {+ case 'fade':+ case 'rise':+ case 'zoom':+ case 'pop':+ case 'rotate':+ return { ...IDENTITY, opacity: 0 }+ case 'pan':+ return {+ ...IDENTITY,+ dx: dir === 'left' ? -travel.x : dir === 'right' ? travel.x : 0,+ dy: dir === 'up' ? -travel.y : dir === 'down' ? travel.y : 0,+ }+ case 'wipe':+ return { ...IDENTITY, reveal: 0 }+ case 'breathe':+ return IDENTITY+ default:+ return IDENTITY+ }+}++// ── timing helpers ───────────────────────────────────────────++/** Total playback time of a page's element animations (seconds). */+export function pageAnimationDuration(page: PageData): number {+ let max = 0+ for (const el of page.elements) {+ const a = el.animation+ if (!a || a.kind === 'none') continue+ if (a.kind === 'breathe') continue // looping — does not extend the timeline+ max = Math.max(max, (a.delay || 0) + Math.max(0.05, a.duration || 0.9))+ }+ return max+}++/** Minimum seconds a page stays visible in autoplay (canva-like pacing). */+export function pageHoldDuration(page: PageData): number {+ const anim = pageAnimationDuration(page)+ const complexity = Math.min(4, page.elements.length / 4)+ return Math.max(2.2, anim + 0.8 + complexity * 0.4)+}++// ── Magic Animate — deterministic one-click animation pass ──++const HEADING_FONT_RATIO = 0.06 // fontSize > 6% of page height = heading++/**+ * Magic Animate: assign tasteful entry animations to every element of a page+ * (deterministic — no AI needed). Layout-aware rules:+ * - large text (headline) → rise, slight delay+ * - body text → fade+ * - images → pan (from the nearest edge) or zoom+ * - shapes/decorations → pop / breathe+ * - page transition → fade+ * Elements keep relative order: delay scales with stacking order.+ */+export function magicAnimatePage(page: PageData, pageHeight: number, speed: 'slow' | 'medium' | 'fast' = 'medium'): PageData {+ const base = speed === 'slow' ? 1.25 : speed === 'fast' ? 0.7 : 1+ let delayCursor = 0+ const elements = page.elements.map((el) => {+ const anim = magicAnimationFor(el, pageHeight, base, delayCursor)+ if (anim) delayCursor = Math.min(delayCursor + 0.12 * base, 1.4)+ return anim ? { ...el, animation: anim } : { ...el, animation: undefined }+ })+ return {+ ...page,+ elements,+ transition: { kind: 'fade', duration: 0.7 },+ }+}++function magicAnimationFor(+ el: AnyElement,+ pageHeight: number,+ base: number,+ delay: number+): ElementAnimation | undefined {+ const duration = 0.8 * base+ const direction = pickDirection(el)++ if (el.type === 'text') {+ const isHeading = el.fontSize / pageHeight > HEADING_FONT_RATIO || el.bold+ return {+ kind: isHeading ? 'rise' : 'fade',+ duration,+ delay: Math.min(delay, isHeading ? 0.1 : 0.5 * base),+ easing: 'easeOut',+ direction: isHeading ? 'up' : undefined,+ }+ }+ if (el.type === 'image' || el.type === 'sticker') {+ return { kind: 'pan', duration: duration * 1.15, delay: Math.min(delay, 0.8 * base), easing: 'easeOut', direction }+ }+ if (el.type === 'rect' || el.type === 'ellipse' || el.type === 'triangle' || el.type === 'star' || el.type === 'path') {+ return { kind: 'pop', duration: duration * 0.9, delay: Math.min(delay, 1.0 * base), easing: 'spring' }+ }+ if (el.type === 'line' || el.type === 'stroke') {+ return { kind: 'wipe', duration, delay: Math.min(delay, 1.1 * base), easing: 'easeOut', direction: 'left' }+ }+ return { kind: 'fade', duration, delay: Math.min(delay, 1.2 * base), easing: 'easeOut' }+}++function pickDirection(el: { x: number; y: number; width: number; height: number }): 'left' | 'right' | 'up' | 'down' {+ // pan in from the nearest edge of the element+ const distLeft = el.x+ const distRight = Math.abs(1080 - (el.x + el.width)) // page width unknown here; approximate+ const distTop = el.y+ const min = Math.min(distLeft, distTop, distRight)+ if (min === distTop) return 'up'+ if (min === distLeft) return 'left'+ return 'right'+}++/** Remove animations from every element on a page. */+export function clearPageAnimations(page: PageData): PageData {+ return {+ ...page,+ elements: page.elements.map((el) => ({ ...el, animation: undefined })),+ transition: undefined,+ }+}++/** Human labels for the animation panel. */+export const ANIMATION_KINDS: { kind: AnimationKind; label: string; hint: string }[] = [+ { kind: 'none', label: 'None', hint: 'Remove animation' },+ { kind: 'fade', label: 'Fade', hint: 'Softly fades in' },+ { kind: 'rise', label: 'Rise', hint: 'Floats up into place' },+ { kind: 'pan', label: 'Pan', hint: 'Slides in from an edge' },+ { kind: 'pop', label: 'Pop', hint: 'Springy scale-in' },+ { kind: 'wipe', label: 'Wipe', hint: 'Reveals from an edge' },+ { kind: 'zoom', label: 'Zoom', hint: 'Scales up into view' },+ { kind: 'rotate', label: 'Rotate', hint: 'Spins in' },+ { kind: 'breathe', label: 'Breathe', hint: 'Gently pulses (loops)' },+]++export const TRANSITION_KINDS: { kind: 'none' | 'fade' | 'slide' | 'morph'; label: string; hint: string }[] = [+ { kind: 'none', label: 'None', hint: 'Instant cut' },+ { kind: 'fade', label: 'Fade', hint: 'Crossfade between pages' },+ { kind: 'slide', label: 'Slide', hint: 'Slides across' },+ { kind: 'morph', label: 'Morph', hint: 'Zoom + fade blend' },+]++/** normalize/clamp an incoming animation config (used by store + AI actions) */+export function sanitizeAnimation(input: unknown): ElementAnimation | undefined {+ if (!input || typeof input !== 'object') return undefined+ const a = input as Partial<ElementAnimation>+ const kind = a.kind+ if (!kind || !ANIMATION_KINDS.some((k) => k.kind === kind)) return undefined+ if (kind === 'none') return undefined+ const easing = (['linear', 'easeIn', 'easeOut', 'easeInOut', 'spring'] as const).includes(a.easing as never)+ ? (a.easing as AnimationEasing)+ : 'easeOut'+ const direction = (['left', 'right', 'up', 'down'] as const).includes(a.direction as never)+ ? (a.direction as ElementAnimation['direction'])+ : undefined+ return {+ kind,+ duration: Math.min(4, Math.max(0.1, Number(a.duration) || 0.9)),+ delay: Math.min(5, Math.max(0, Number(a.delay) || 0)),+ easing,+ direction,+ }+}diff --git a/src/lib/collab/client.ts b/src/lib/collab/client.tsnew file mode 100644index 0000000..daae2ab--- /dev/null+++ b/src/lib/collab/client.ts@@ -0,0 +1,226 @@+'use client'++import type { Collaborator, CollabOp, CollabStatus, DesignEventRow, OpEnvelope, StreamFrame } from './protocol'++/**+ * CollabSession — one per open design.+ *+ * Transport: SSE downstream (Postgres event log), POST upstream (batched).+ * - local ops queue and flush every 400 ms (≤ 20 per flush)+ * - cursor updates throttled (~120 ms), presence heartbeat every 5 s+ * - reconnect with exponential backoff (0.5 s → 8 s), gap-free replay via ?since+ *+ * Zustand stays the local rendering truth; collab never blocks input.+ */+export class CollabSession {+ readonly designId: string+ readonly pid: string+ readonly name: string+ readonly color: string++ status: CollabStatus = 'offline'+ lastSeq = 0++ private queue: OpEnvelope[] = []+ private flushTimer: ReturnType<typeof setInterval> | null = null+ private heartbeatTimer: ReturnType<typeof setInterval> | null = null+ private es: EventSource | null = null+ private backoff = 500+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null+ private disposed = false+ private processedEventIds = new Set<string>()+ private lastCursorSent = 0+ private pendingCursor: { page: number; x: number; y: number; selection?: string[] } | null = null++ // callbacks+ onStatus: ((s: CollabStatus) => void) | null = null+ onEvents: ((events: DesignEventRow[]) => void) | null = null+ onPresence: ((collaborators: Collaborator[]) => void) | null = null++ constructor(designId: string, pid: string, name: string, color: string) {+ this.designId = designId+ this.pid = pid+ this.name = name+ this.color = color+ }++ // ── lifecycle ─────────────────────────────────────────────++ start() {+ if (this.disposed) return+ this.connect()+ this.flushTimer = setInterval(() => void this.flush(), 400)+ this.heartbeatTimer = setInterval(() => void this.heartbeat(), 5_000)+ }++ dispose() {+ this.disposed = true+ this.setStatus('offline')+ if (this.flushTimer) clearInterval(this.flushTimer)+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer)+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer)+ this.es?.close()+ this.es = null+ }++ private setStatus(s: CollabStatus) {+ if (this.status === s) return+ this.status = s+ this.onStatus?.(s)+ }++ private connect() {+ if (this.disposed) return+ this.setStatus('connecting')+ this.es?.close()+ const url = `/api/collab/${encodeURIComponent(this.designId)}/stream?since=${this.lastSeq}&pid=${encodeURIComponent(this.pid)}`+ const es = new EventSource(url)+ this.es = es++ es.onopen = () => {+ this.backoff = 500+ this.setStatus('live')+ }+ es.onmessage = (ev) => {+ try {+ const frame = JSON.parse(ev.data) as StreamFrame+ this.handleFrame(frame)+ } catch {+ /* malformed frame — ignore, the log replays on reconnect */+ }+ }+ es.onerror = () => {+ // EventSource auto-retries, but our since-param is stale in its retry URL+ // → close and reconnect manually with the fresh lastSeq+ es.close()+ if (this.es === es) this.es = null+ if (this.disposed) return+ this.setStatus('connecting')+ this.scheduleReconnect()+ }+ }++ private scheduleReconnect() {+ if (this.disposed || this.reconnectTimer) return+ this.reconnectTimer = setTimeout(() => {+ this.reconnectTimer = null+ this.connect()+ }, this.backoff)+ this.backoff = Math.min(this.backoff * 1.8, 8_000)+ }++ private handleFrame(frame: StreamFrame) {+ if (typeof frame.seq === 'number' && frame.seq >= this.lastSeq) {+ // only advance on the server's max seq when we have consumed everything+ }+ const events = (frame.events ?? []).filter((e) => e.actorId !== this.pid && !this.processedEventIds.has(e.id))+ for (const e of frame.events ?? []) {+ this.processedEventIds.add(e.id)+ }+ // bound the dedupe set (old ids can never replay after log pruning)+ if (this.processedEventIds.size > 5_000) {+ this.processedEventIds = new Set([...this.processedEventIds].slice(-2_000))+ }+ if (events.length) {+ this.lastSeq = Math.max(this.lastSeq, ...events.map((e) => e.seq))+ this.onEvents?.(events)+ }+ if (typeof frame.seq === 'number') {+ // server max seq — safe to track even without events (ids are monotonic)+ if (frame.seq > this.lastSeq && (frame.events ?? []).length === 0) this.lastSeq = frame.seq+ }+ const now = Date.now()+ this.onPresence?.(+ (frame.presence ?? []).map((p) => ({+ id: p.id,+ name: p.name,+ color: p.color,+ cursor: p.cursor ?? null,+ lastSeen: now,+ }))+ )+ }++ // ── upstream ──────────────────────────────────────────────++ /** Queue a local op (deduped by eventId, applied optimistically locally). */+ emit(op: CollabOp, eventId: string) {+ if (this.disposed) return+ // coalesce consecutive elements:update patches for the same ids (drags/typing) —+ // keeps the event log small and the fan-out cheap+ if (op.kind === 'elements:update') {+ const last = this.queue[this.queue.length - 1]+ if (last && last.op.kind === 'elements:update') {+ const prev = last.op+ if (+ prev.pageId === op.pageId &&+ prev.ids.length === op.ids.length &&+ op.ids.every((id) => prev.ids.includes(id))+ ) {+ last.op = { kind: 'elements:update', pageId: prev.pageId, ids: prev.ids, patch: { ...prev.patch, ...op.patch } }+ return+ }+ }+ }+ this.queue.push({ eventId, op })+ if (this.queue.length >= 20) void this.flush()+ }++ private async flush() {+ if (this.disposed || !this.queue.length) return+ const batch = this.queue.splice(0, 20)+ try {+ const res = await fetch(`/api/collab/${encodeURIComponent(this.designId)}/events`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ pid: this.pid, name: this.name, color: this.color, events: batch }),+ })+ if (!res.ok && (res.status === 404 || res.status === 503)) {+ // design gone / db down — drop the queue (local editor still works)+ this.queue = []+ }+ } catch {+ /* offline — re-queue once for a retry on the next tick, else drop */+ if (this.queue.length < 40) this.queue = [...batch.slice(0, 5), ...this.queue]+ else this.queue = []+ }+ }++ private async heartbeat() {+ if (this.disposed) return+ try {+ await fetch(`/api/collab/${encodeURIComponent(this.designId)}/presence`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ pid: this.pid,+ name: this.name,+ color: this.color,+ cursor: this.pendingCursor,+ }),+ })+ } catch {+ /* offline — heartbeat retries on the next interval */+ }+ }++ /** Throttled cursor broadcast (page coords + current selection). */+ sendCursor(cursor: { page: number; x: number; y: number; selection?: string[] }) {+ this.pendingCursor = cursor+ const now = Date.now()+ if (now - this.lastCursorSent < 120) return+ this.lastCursorSent = now+ void fetch(`/api/collab/${encodeURIComponent(this.designId)}/presence`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ pid: this.pid,+ name: this.name,+ color: this.color,+ cursor,+ }),+ }).catch(() => {+ /* offline */+ })+ }+}diff --git a/src/lib/collab/identity.ts b/src/lib/collab/identity.tsnew file mode 100644index 0000000..01120f6--- /dev/null+++ b/src/lib/collab/identity.ts@@ -0,0 +1,96 @@+'use client'++/**+ * Collaborator identity (v0.5 Phase 6).+ *+ * Minimum identity layer required for collaboration — no accounts, no auth+ * rewrite. A persistent local participant identity: id + display name ++ * stable color. Works for anonymous/local editing; a future account system+ * can override `participantId`/`name` without touching the collab transport.+ */++const IDENTITY_KEY = 'canvix-identity-v1'++export interface ParticipantIdentity {+ /** globally-unique-ish participant id (kept stable across sessions) */+ id: string+ /** display name (≤ 40 chars) */+ name: string+ /** stable avatar color */+ color: string+}++const PALETTE = [+ '#FF5C8A', '#00C4CC', '#7630D7', '#F59E0B', '#10B981',+ '#3B82F6', '#EF4444', '#8B5CF6', '#14B8A6', '#EC4899',+ '#84CC16', '#06B6D4',+]++const ADJECTIVES = ['Swift', 'Bright', 'Calm', 'Bold', 'Cosmic', 'Fresh', 'Lucky', 'Sunny', 'Clever', 'Rapid']+const NOUNS = ['Fox', 'Otter', 'Falcon', 'Panda', 'Koala', 'Tiger', 'Heron', 'Lynx', 'Marmot', 'Raven']++function randomId(): string {+ return `p_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`+}++function randomName(): string {+ return `${ADJECTIVES[Math.floor(Math.random() * ADJECTIVES.length)]} ${NOUNS[Math.floor(Math.random() * NOUNS.length)]}`+}++function colorFor(id: string): string {+ let hash = 0+ for (let i = 0; i < id.length; i++) hash = (hash * 31 + id.charCodeAt(i)) >>> 0+ return PALETTE[hash % PALETTE.length]+}++let cached: ParticipantIdentity | null = null++/** Get (creating + persisting on first use) the local participant identity. */+export function getIdentity(): ParticipantIdentity {+ if (cached) return cached+ if (typeof window === 'undefined') {+ // SSR safety — a transient identity; never used for real collaboration+ return { id: 'ssr', name: 'Guest', color: '#7630D7' }+ }+ try {+ const raw = localStorage.getItem(IDENTITY_KEY)+ if (raw) {+ const parsed = JSON.parse(raw) as Partial<ParticipantIdentity>+ if (parsed.id && parsed.name) {+ cached = {+ id: String(parsed.id).slice(0, 40),+ name: String(parsed.name).slice(0, 40),+ color: colorFor(String(parsed.id)),+ }+ return cached+ }+ }+ } catch {+ /* corrupt or unavailable — regenerate below */+ }+ const fresh: ParticipantIdentity = {+ id: randomId(),+ name: randomName(),+ color: PALETTE[Math.floor(Math.random() * PALETTE.length)],+ }+ cached = fresh+ try {+ localStorage.setItem(IDENTITY_KEY, JSON.stringify(fresh))+ } catch {+ /* private mode — identity stays per-session only */+ }+ return fresh+}++/** Update the display name (identity card in the presence popover). */+export function setDisplayName(name: string): ParticipantIdentity {+ const id = getIdentity()+ const clean = name.trim().slice(0, 40) || id.name+ cached = { ...id, name: clean }+ try {+ localStorage.setItem(IDENTITY_KEY, JSON.stringify(cached))+ } catch {+ /* ignore */+ }+ return cached+}diff --git a/src/lib/collab/protocol.ts b/src/lib/collab/protocol.tsnew file mode 100644index 0000000..6b4b02b--- /dev/null+++ b/src/lib/collab/protocol.ts@@ -0,0 +1,130 @@+/**+ * Collaboration wire protocol (v0.5) — shared by server routes and client.+ *+ * Architecture: server-authoritative event log in Postgres (DesignEvent,+ * global monotonic seq) + SSE downstream + POST upstream. See+ * research/COLLABORATION-ARCHITECTURE.md for the decision record.+ */++import type { AnyElement, Background, PageData } from '@/lib/types'++// ── upstream (client → server) operations ─────────────────────++export type CollabOp =+ | { kind: 'elements:update'; pageId: string; ids: string[]; patch: Record<string, unknown> }+ | { kind: 'element:add'; pageId: string; element: AnyElement }+ | { kind: 'elements:add'; pageId: string; elements: AnyElement[] }+ | { kind: 'element:delete'; pageId: string; ids: string[] }+ | { kind: 'elements:reorder'; pageId: string; orderedIds: string[] }+ | { kind: 'page:add'; page: PageData; afterId?: string }+ | { kind: 'page:delete'; pageId: string }+ | { kind: 'page:dup'; pageId: string; newPageId: string }+ | { kind: 'page:background'; pageId: string; background: Background }+ | { kind: 'page:replace'; pageId: string; page: PageData }+ | { kind: 'pages:replace'; pages: PageData[]; width?: number; height?: number }+ | { kind: 'design:rename'; name: string }++export interface OpEnvelope {+ /** client-generated unique id — dedupe on replay */+ eventId: string+ op: CollabOp+}++// ── downstream (server → client) frames ───────────────────────++export interface DesignEventRow {+ seq: number+ id: string+ designId: string+ actorId: string+ kind: string+ payload: unknown+ createdAt: string+}++export interface PresenceRow {+ id: string+ name: string+ color: string+ cursor: {+ page: number+ x: number+ y: number+ selection?: string[]+ } | null+ lastSeen: string+}++/** One SSE data frame. */+export interface StreamFrame {+ /** events after the client's lastSeq (empty array = nothing new) */+ events: DesignEventRow[]+ /** live collaborators (lastSeen < 30 s), excluding the requesting pid */+ presence: PresenceRow[]+ /** current server seq (so clients can persist lastSeq even on empty frames) */+ seq: number+}++// ── client state ──────────────────────────────────────────────++export type CollabStatus = 'offline' | 'connecting' | 'live'++export interface Collaborator {+ id: string+ name: string+ color: string+ cursor: { page: number; x: number; y: number; selection?: string[] } | null+ lastSeen: number+}++// ── server-side op validation (mirrors the client's store ops) ─++export const OP_KINDS = new Set([+ 'elements:update',+ 'element:add',+ 'elements:add',+ 'element:delete',+ 'elements:reorder',+ 'page:add',+ 'page:delete',+ 'page:background',+ 'page:replace',+ 'pages:replace',+ 'design:rename',+])++/** Hard payload cap per event — 256 KB (see security audit). */+export const MAX_EVENT_BYTES = 256 * 1024+/** Max events per POST flush. */+export const MAX_EVENTS_PER_FLUSH = 20++const FINITE_NUM_KEYS = new Set(['x', 'y', 'width', 'height', 'rotation', 'opacity', 'fontSize', 'lineHeight', 'letterSpacing', 'strokeWidth', 'cornerRadius', 'radius'])++/** Recursively validate that a payload contains only finite numbers & plain data (no functions/huge strings). */+export function validateOpPayload(op: CollabOp): boolean {+ try {+ const json = JSON.stringify(op)+ if (json.length > MAX_EVENT_BYTES) return false+ const walk = (v: unknown, depth: number): boolean => {+ if (depth > 12) return false+ if (v === null || v === undefined) return true+ if (typeof v === 'number') return Number.isFinite(v)+ if (typeof v === 'string') return v.length <= 100_000+ if (typeof v === 'boolean') return true+ if (Array.isArray(v)) return v.length <= 500 && v.every((x) => walk(x, depth + 1))+ if (typeof v === 'object') {+ const entries = Object.entries(v as Record<string, unknown>)+ if (entries.length > 60) return false+ for (const [k, val] of entries) {+ if (typeof val === 'number' && FINITE_NUM_KEYS.has(k) && !Number.isFinite(val)) return false+ if (!walk(val, depth + 1)) return false+ }+ return true+ }+ return false // functions, symbols, bigints — reject+ }+ return walk(op, 0)+ } catch {+ return false+ }+}diff --git a/src/lib/comments-store.ts b/src/lib/comments-store.tsnew file mode 100644index 0000000..21918fa--- /dev/null+++ b/src/lib/comments-store.ts@@ -0,0 +1,123 @@+'use client'++import { create } from 'zustand'++/**+ * Comments runtime state — a dedicated lightweight store (separate from+ * editor-store) so comment updates never re-render the editor chrome.+ */++export interface CommentRecord {+ id: string+ designId: string+ pageId: string+ /** anchor as fraction of page size (0..1) — survives resizes */+ x: number+ y: number+ elementId: string | null+ authorId: string+ authorName: string+ authorColor: string+ body: string+ parentId: string | null+ resolved: boolean+ createdAt: string+ updatedAt: string+}++export interface CommentThread {+ root: CommentRecord+ replies: CommentRecord[]+}++interface CommentsState {+ loaded: boolean+ comments: CommentRecord[]+ /** open thread pin id (panel focus) */+ openThreadId: string | null+ /** unread comments authored by others (id set) */+ unreadIds: Set<string>+ setComments: (list: CommentRecord[], markUnreadFrom: string | null) => void+ upsertComment: (c: CommentRecord) => void+ removeComment: (id: string) => void+ setOpenThreadId: (id: string | null) => void+ markAllRead: () => void+}++export const useCommentsStore = create<CommentsState>((set, get) => ({+ loaded: false,+ comments: [],+ openThreadId: null,+ unreadIds: new Set<string>(),++ setComments: (list, markUnreadFrom) => {+ const prev = get().comments+ const prevIds = new Set(prev.map((c) => c.id))+ const unread = new Set(get().unreadIds)+ if (markUnreadFrom) {+ for (const c of list) {+ if (!prevIds.has(c.id) && c.authorId !== markUnreadFrom && !c.parentId) unread.add(c.id)+ }+ }+ set({ comments: list, loaded: true, unreadIds: unread })+ },++ upsertComment: (c) => {+ const { comments, unreadIds } = get()+ const exists = comments.some((x) => x.id === c.id)+ const next = exists ? comments.map((x) => (x.id === c.id ? c : x)) : [...comments, c]+ const unread = new Set(unreadIds)+ unread.delete(c.id)+ set({ comments: next, unreadIds: unread })+ },++ removeComment: (id) => {+ const { comments, unreadIds } = get()+ const unread = new Set(unreadIds)+ unread.delete(id)+ set({+ comments: comments.filter((c) => c.id !== id && c.parentId !== id),+ unreadIds: unread,+ })+ },++ setOpenThreadId: (id) => set({ openThreadId: id }),++ markAllRead: () => set({ unreadIds: new Set() }),+}))++/** Build reply-threaded view of root comments (sorted newest-first). */+export function buildThreads(comments: CommentRecord[]): CommentThread[] {+ const roots = comments.filter((c) => !c.parentId)+ const byParent = new Map<string, CommentRecord[]>()+ for (const c of comments) {+ if (c.parentId) {+ const list = byParent.get(c.parentId) ?? []+ list.push(c)+ byParent.set(c.parentId, list)+ }+ }+ for (const list of byParent.values()) list.sort((a, b) => a.createdAt.localeCompare(b.createdAt))+ return roots+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt))+ .map((root) => ({ root, replies: byParent.get(root.id) ?? [] }))+}++/** track per-design last-read timestamp (localStorage) */+const LAST_READ = (designId: string) => `canvix-comments-read-${designId}`++export function readLastReadAt(designId: string): number {+ try {+ return Number(localStorage.getItem(LAST_READ(designId))) || 0+ } catch {+ return 0+ }+}++export function writeLastReadAt(designId: string, at: number): void {+ try {+ localStorage.setItem(LAST_READ(designId), String(at))+ } catch {+ /* ignore */+ }+}diff --git a/src/lib/design-actions.ts b/src/lib/design-actions.tsnew file mode 100644index 0000000..77ea687--- /dev/null+++ b/src/lib/design-actions.ts@@ -0,0 +1,393 @@+// ─────────────────────────────────────────────────────────────+// DesignActions — validated, undoable editor mutations for the+// AI Assistant 2.0. The assistant returns structured actions;+// this module double-validates them client-side and executes+// each through store actions (which push undo history + emit+// collab ops). AI output is NEVER trusted raw.+// ─────────────────────────────────────────────────────────────++import {+ createImageElement,+ createTextElement,+ type AnyElement,+ type Background,+ type TextElement,+} from '@/lib/types'+import { useEditorStore } from '@/store/editor-store'++export interface DesignAction {+ type: string+ ids?: string[]+ text?: string+ fontSize?: number+ bold?: boolean+ color?: string+ fill?: string+ to?: string+ dx?: number+ dy?: number+ factor?: number+ patch?: Record<string, unknown>+ fontFamily?: string+ targets?: string+ kind?: string+ from?: string+ to2?: string+ to2Color?: string+ angle?: number+ mode?: string+ axis?: string+ prompt?: string+ colors?: string[]+ language?: string+ [key: string]: unknown+}++const HEX = /^#[0-9a-fA-F]{6}$/++/** Flatten elements (groups included) for id-based lookups. */+function flatElements(els: AnyElement[], out: AnyElement[] = []): AnyElement[] {+ for (const el of els) {+ out.push(el)+ if (el.type === 'group') flatElements(el.children, out)+ }+ return out+}++function currentPageElements(): AnyElement[] {+ const s = useEditorStore.getState()+ return s.pages[s.currentPage]?.elements ?? []+}++function resolveIds(ids: string[] | undefined): string[] {+ const page = currentPageElements()+ const valid = new Set(flatElements(page).map((e) => e.id))+ return (ids ?? []).filter((id) => typeof id === 'string' && valid.has(id))+}++/** Execute one action. Returns a human-readable result message. */+export async function applyDesignAction(action: DesignAction): Promise<string> {+ const store = useEditorStore.getState()+ const { width, height } = store++ switch (action.type) {+ case 'addText': {+ const text = String(action.text ?? '').slice(0, 400).trim()+ if (!text) return 'Nothing to add'+ const fontSize = Math.min(300, Math.max(8, Number(action.fontSize) || 48))+ const yMode = action.y === 'top' ? 0.08 : action.y === 'bottom' ? 0.78 : 0.4+ const el = createTextElement({+ text,+ fontSize,+ bold: action.bold === true,+ width: Math.round(width * 0.8),+ x: Math.round(width * 0.1),+ y: Math.round(height * yMode),+ })+ el.align = (action.align as 'left' | 'center' | 'right') ?? 'center'+ if (typeof action.color === 'string' && HEX.test(action.color)) el.fill = action.color+ useEditorStore.getState().addElement(el)+ return 'Text added — fully editable'+ }++ case 'updateElements': {+ const ids = resolveIds(action.ids)+ if (!ids.length) return 'No matching elements'+ const raw = (action.patch ?? {}) as Record<string, unknown>+ const patch: Record<string, unknown> = {}+ if (typeof raw.fill === 'string' && HEX.test(raw.fill)) patch.fill = raw.fill+ if (typeof raw.text === 'string' && raw.text.length <= 400) patch.text = raw.text+ if (Number.isFinite(Number(raw.fontSize))) patch.fontSize = Math.min(300, Math.max(6, Number(raw.fontSize)))+ if (typeof raw.bold === 'boolean') patch.bold = raw.bold+ if (typeof raw.fontFamily === 'string' && raw.fontFamily.length <= 60) patch.fontFamily = raw.fontFamily+ if (Number.isFinite(Number(raw.x))) patch.x = Number(raw.x)+ if (Number.isFinite(Number(raw.y))) patch.y = Number(raw.y)+ if (Number.isFinite(Number(raw.width))) patch.width = Math.max(8, Number(raw.width))+ if (Number.isFinite(Number(raw.height))) patch.height = Math.max(8, Number(raw.height))+ if (Number.isFinite(Number(raw.lineHeight))) patch.lineHeight = Math.min(3, Math.max(0.8, Number(raw.lineHeight)))+ if (Number.isFinite(Number(raw.letterSpacing))) patch.letterSpacing = Number(raw.letterSpacing)+ if (!Object.keys(patch).length) return 'Nothing to update'+ useEditorStore.getState().updateElements(ids, patch)+ return `Updated ${ids.length} element${ids.length > 1 ? 's' : ''}`+ }++ case 'deleteElements': {+ const ids = resolveIds(action.ids)+ if (!ids.length) return 'No matching elements'+ useEditorStore.getState().setSelection(ids)+ useEditorStore.getState().deleteSelection()+ return `Deleted ${ids.length} element${ids.length > 1 ? 's' : ''}`+ }++ case 'moveElements': {+ const ids = resolveIds(action.ids)+ if (!ids.length) return 'No matching elements'+ if (action.to) {+ const modeMap: Record<string, 'left' | 'cx' | 'right' | 'top' | 'cy' | 'bottom'> = {+ left: 'left', center: 'cx', right: 'right',+ top: 'top', middle: 'cy', bottom: 'bottom',+ }+ const mode = modeMap[String(action.to)]+ if (mode) {+ useEditorStore.getState().alignElements(ids, mode)+ return `Moved to ${String(action.to)}`+ }+ }+ const dx = Number.isFinite(Number(action.dx)) ? Number(action.dx) : 0+ const dy = Number.isFinite(Number(action.dy)) ? Number(action.dy) : 0+ if (!dx && !dy) return 'Nothing to move'+ const page = currentPageElements()+ const patchPerId = new Map<string, { x: number; y: number }>()+ for (const el of page) {+ if (ids.includes(el.id)) patchPerId.set(el.id, { x: el.x + dx, y: el.y + dy })+ }+ for (const [id, patch] of patchPerId) {+ useEditorStore.getState().updateElements([id], patch)+ }+ return `Moved ${ids.length} element${ids.length > 1 ? 's' : ''}`+ }++ case 'scaleElements': {+ const ids = resolveIds(action.ids)+ if (!ids.length) return 'No matching elements'+ const factor = Math.min(5, Math.max(0.1, Number(action.factor) || 1))+ if (Math.abs(factor - 1) < 0.01) return 'No size change'+ const page = currentPageElements()+ for (const el of page) {+ if (!ids.includes(el.id)) continue+ const patch: Record<string, number> = {+ x: Math.round(el.x + el.width * (1 - factor) / 2),+ y: Math.round(el.y + el.height * (1 - factor) / 2),+ width: Math.max(8, Math.round(el.width * factor)),+ height: Math.max(8, Math.round(el.height * factor)),+ }+ if (el.type === 'text' || el.type === 'sticker') patch.fontSize = Math.max(6, Math.round((el as TextElement).fontSize * factor))+ useEditorStore.getState().updateElements([el.id], patch)+ }+ return `Scaled ${ids.length} element${ids.length > 1 ? 's' : ''} by ${factor.toFixed(2)}×`+ }++ case 'setHeadingsColor':+ case 'setTextColor': {+ const color = String(action.color ?? '')+ if (!HEX.test(color)) return 'Invalid colour'+ const page = currentPageElements()+ const isHeading = (el: AnyElement) =>+ el.type === 'text' && ((el as TextElement).bold || (el as TextElement).fontSize / Math.max(1, height) > 0.06)+ const ids = flatElements(page)+ .filter((el) => el.type === 'text')+ .filter((el) => (action.type === 'setHeadingsColor' ? isHeading(el) : true))+ .map((el) => el.id)+ if (!ids.length) return 'No text elements found'+ useEditorStore.getState().updateElements(ids, { fill: color })+ return action.type === 'setHeadingsColor' ? 'Heading colours updated' : 'Text colours updated'+ }++ case 'setFont': {+ const fontFamily = String(action.fontFamily ?? '').slice(0, 60)+ if (!fontFamily) return 'No font specified'+ const page = currentPageElements()+ const targets = String(action.targets ?? 'all')+ const isHeading = (el: AnyElement) =>+ el.type === 'text' && ((el as TextElement).bold || (el as TextElement).fontSize / Math.max(1, height) > 0.06)+ const ids = flatElements(page)+ .filter((el) => el.type === 'text')+ .filter((el) => (targets === 'all' ? true : targets === 'headings' ? isHeading(el) : !isHeading(el)))+ .map((el) => el.id)+ if (!ids.length) return 'No text elements found'+ useEditorStore.getState().updateElements(ids, { fontFamily })+ return `Font set to ${fontFamily} (${targets})`+ }++ case 'setBackground': {+ const kind = String(action.kind ?? 'solid')+ const from = String(action.from ?? '')+ if (!HEX.test(from)) return 'Invalid colour'+ let bg: Background = { type: 'solid', color: from }+ if (kind === 'gradient') {+ const to = String((action.to as string) ?? (action as { to?: string }).to ?? '')+ if (HEX.test(to)) {+ bg = { type: 'gradient', from, to, angle: Math.min(360, Math.max(0, Number(action.angle) || 135)) }+ }+ }+ useEditorStore.getState().setPageBackground(bg)+ return 'Background updated'+ }++ case 'alignElements': {+ const ids = resolveIds(action.ids)+ const modeMap: Record<string, 'left' | 'cx' | 'right' | 'top' | 'cy' | 'bottom'> = {+ left: 'left', cx: 'cx', right: 'right', top: 'top', cy: 'cy', bottom: 'bottom',+ }+ const mode = modeMap[String(action.mode)]+ if (!ids.length || !mode) return 'Nothing to align'+ useEditorStore.getState().alignElements(ids, mode)+ return 'Elements aligned'+ }++ case 'distributeElements': {+ const ids = resolveIds(action.ids)+ if (ids.length < 3) return 'Needs at least 3 elements'+ const axis = String(action.axis) === 'y' ? 'y' : 'x'+ const page = currentPageElements()+ const els = page.filter((e) => ids.includes(e.id)).sort((a, b) => (axis === 'x' ? a.x - b.x : a.y - b.y))+ const first = els[0]+ const last = els[els.length - 1]+ const start = axis === 'x' ? first.x : first.y+ const end = axis === 'x' ? last.x : last.y+ const sizes = els.reduce((sum, e) => sum + (axis === 'x' ? e.width : e.height), 0)+ const gap = (end - start - sizes) / (els.length - 1)+ if (gap < 0) return 'Elements overlap — no distribution applied'+ let cursor = start+ for (const el of els) {+ const patch = axis === 'x' ? { x: Math.round(cursor) } : { y: Math.round(cursor) }+ useEditorStore.getState().updateElements([el.id], patch)+ cursor += (axis === 'x' ? el.width : el.height) + gap+ }+ return `Distributed ${els.length} elements evenly`+ }++ case 'addPage':+ useEditorStore.getState().addPage()+ return 'Page added'++ case 'duplicatePage': {+ const s = useEditorStore.getState()+ s.duplicatePage(s.currentPage)+ return 'Page duplicated'+ }++ case 'generateImage': {+ const prompt = String(action.prompt ?? '').slice(0, 400).trim()+ if (!prompt) return 'No image prompt'+ const res = await fetch('/api/ai/image', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ prompt }),+ })+ const data = (await res.json()) as { dataUrl?: string; width?: number; height?: number; error?: string; code?: string }+ if (!res.ok || !data.dataUrl) throw new Error(data.error ?? 'Image generation failed')+ const iw = data.width ?? 1024+ const ih = data.height ?? 1024+ const scale = Math.min((width * 0.7) / iw, (height * 0.7) / ih, 1)+ useEditorStore.getState().addElement(+ createImageElement(data.dataUrl, iw, ih, {+ x: Math.round((width - iw * scale) / 2),+ y: Math.round((height - ih * scale) / 2),+ width: Math.round(iw * scale),+ height: Math.round(ih * scale),+ })+ )+ return 'AI image generated and added'+ }++ case 'suggestPalette': {+ const colors = (action.colors ?? []).filter((c) => typeof c === 'string' && HEX.test(c)).slice(0, 5) as string[]+ if (colors.length < 3) return 'Palette too small'+ const brand = { ...useEditorStore.getState().brand, palettes: [colors, ...(useEditorStore.getState().brand.palettes ?? [])].slice(0, 4) }+ useEditorStore.getState().setBrand(brand)+ return 'Palette saved to your Brand Kit'+ }++ case 'translate': {+ const language = String(action.language ?? '').slice(0, 40)+ if (!language) return 'No language given'+ const texts: TextElement[] = []+ for (const p of useEditorStore.getState().pages) {+ for (const el of flatElements(p.elements)) {+ if (el.type === 'text') texts.push(el as TextElement)+ }+ }+ if (!texts.length) return 'No text to translate'+ const res = await fetch('/api/ai/translate', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ language, texts: texts.map((t) => t.text) }),+ })+ const data = (await res.json()) as { translations?: string[]; error?: string }+ if (!res.ok || !Array.isArray(data.translations) || data.translations.length !== texts.length) {+ throw new Error(data.error ?? 'Translation failed')+ }+ useEditorStore.getState().translateTexts(texts.map((t, i) => ({ id: t.id, text: data.translations![i] })))+ return `Translated ${texts.length} texts to ${language}`+ }++ case 'magicAnimate':+ useEditorStore.getState().magicAnimateCurrentPage()+ return 'Magic Animate applied — open Preview to watch'++ case 'balanceLayout':+ case 'magicLayout': {+ const msg = balanceLayout()+ return msg+ }++ default:+ return 'Unsupported action'+ }+}++/** Deterministic layout balance: margins, centering, spacing (no AI needed). */+function balanceLayout(): string {+ const s = useEditorStore.getState()+ const page = s.pages[s.currentPage]+ if (!page || page.elements.length < 2) return 'Not enough elements to balance'++ const { width, height } = s+ const margin = Math.round(Math.min(width, height) * 0.06)+ const els = page.elements.filter((e) => !e.locked)+ if (els.length < 2) return 'Not enough movable elements'++ // 1. snap elements that are nearly centered to exact center+ let fixed = 0+ for (const el of els) {+ const cx = el.x + el.width / 2+ const cy = el.y + el.height / 2+ if (Math.abs(cx - width / 2) < width * 0.04) {+ useEditorStore.getState().updateElements([el.id], { x: Math.round((width - el.width) / 2) })+ fixed += 1+ }+ if (Math.abs(cy - height / 2) < height * 0.04) {+ useEditorStore.getState().updateElements([el.id], { y: Math.round((height - el.height) / 2) })+ fixed += 1+ }+ // 2. pull near-margin elements to the safe margin+ if (Math.abs(el.x - margin) < margin * 0.35) {+ useEditorStore.getState().updateElements([el.id], { x: margin })+ fixed += 1+ }+ if (Math.abs(el.x + el.width - (width - margin)) < margin * 0.35) {+ useEditorStore.getState().updateElements([el.id], { x: width - margin - el.width })+ fixed += 1+ }+ }+ return fixed+ ? `Layout balanced — ${fixed} alignment${fixed > 1 ? 's' : ''} cleaned up (safe margins + centering)`+ : 'Layout already looks balanced'+}++/** Human label for the action chip UI. */+export function describeAction(action: DesignAction): string {+ switch (action.type) {+ case 'addText': return `Add text: “${String(action.text ?? '').slice(0, 40)}${String(action.text ?? '').length > 40 ? '…' : ''}”`+ case 'updateElements': return `Update ${action.ids?.length ?? 0} element${(action.ids?.length ?? 0) === 1 ? '' : 's'}`+ case 'deleteElements': return `Delete ${action.ids?.length ?? 0} element${(action.ids?.length ?? 0) === 1 ? '' : 's'}`+ case 'moveElements': return action.to ? `Move to ${action.to}` : 'Move elements'+ case 'scaleElements': return `Scale by ${Number(action.factor ?? 1).toFixed(2)}×`+ case 'setHeadingsColor': return `Headings → ${action.color}`+ case 'setTextColor': return `Text colour → ${action.color}`+ case 'setFont': return `Font: ${action.fontFamily}`+ case 'setBackground': return `Background → ${action.kind}`+ case 'alignElements': return 'Align elements'+ case 'distributeElements': return 'Distribute evenly'+ case 'addPage': return 'Add a page'+ case 'duplicatePage': return 'Duplicate this page'+ case 'generateImage': return `Generate image: ${String(action.prompt ?? '').slice(0, 42)}…`+ case 'suggestPalette': return 'Use this palette'+ case 'translate': return `Translate to ${action.language}`+ case 'magicAnimate': return 'Magic Animate this page'+ case 'balanceLayout':+ case 'magicLayout': return 'Balance the layout'+ default: return action.type+ }+}diff --git a/src/lib/magic-layers/normalize.ts b/src/lib/magic-layers/normalize.tsnew file mode 100644index 0000000..642e9d8--- /dev/null+++ b/src/lib/magic-layers/normalize.ts@@ -0,0 +1,61 @@+// ─────────────────────────────────────────────────────────────+// Magic Layers — client-side image normalization+// ─────────────────────────────────────────────────────────────++import { loadImage } from './reconstruct'++/** Analyze size cap — vision quality vs transport size balance. */+export const ANALYSIS_MAX_EDGE = 1280++/**+ * Normalize an uploaded image for analysis:+ * - caps the longest edge at 1280px (vision models don't benefit from more)+ * - converts to JPEG (transport-friendly)+ * - returns the normalized dataURL + natural dimensions of the ORIGINAL+ */+export async function normalizeForAnalysis(+ file: File | Blob+): Promise<{ dataUrl: string; naturalWidth: number; naturalHeight: number }> {+ const raw = await new Promise<string>((resolve, reject) => {+ const fr = new FileReader()+ fr.onload = () => resolve(String(fr.result))+ fr.onerror = () => reject(new Error('Could not read the file'))+ fr.readAsDataURL(file)+ })+ const img = await loadImage(raw)+ const longest = Math.max(img.naturalWidth, img.naturalHeight)+ const scale = Math.min(1, ANALYSIS_MAX_EDGE / longest)+ const w = Math.max(1, Math.round(img.naturalWidth * scale))+ const h = Math.max(1, Math.round(img.naturalHeight * scale))+ const canvas = document.createElement('canvas')+ canvas.width = w+ canvas.height = h+ const ctx = canvas.getContext('2d')+ if (!ctx) throw new Error('Canvas unavailable')+ ctx.fillStyle = '#FFFFFF'+ ctx.fillRect(0, 0, w, h)+ ctx.drawImage(img, 0, 0, w, h)+ return {+ dataUrl: canvas.toDataURL('image/jpeg', 0.9),+ naturalWidth: img.naturalWidth,+ naturalHeight: img.naturalHeight,+ }+}++/** Re-encode an existing image element src (any URL/dataURL) for analysis. */+export async function normalizeSrcForAnalysis(src: string): Promise<string> {+ const img = await loadImage(src)+ const longest = Math.max(img.naturalWidth, img.naturalHeight)+ const scale = Math.min(1, ANALYSIS_MAX_EDGE / longest)+ const w = Math.max(1, Math.round(img.naturalWidth * scale))+ const h = Math.max(1, Math.round(img.naturalHeight * scale))+ const canvas = document.createElement('canvas')+ canvas.width = w+ canvas.height = h+ const ctx = canvas.getContext('2d')+ if (!ctx) throw new Error('Canvas unavailable')+ ctx.fillStyle = '#FFFFFF'+ ctx.fillRect(0, 0, w, h)+ ctx.drawImage(img, 0, 0, w, h)+ return canvas.toDataURL('image/jpeg', 0.9)+}diff --git a/src/lib/magic-layers/reconstruct.ts b/src/lib/magic-layers/reconstruct.tsnew file mode 100644index 0000000..bc3eb82--- /dev/null+++ b/src/lib/magic-layers/reconstruct.ts@@ -0,0 +1,231 @@+// ─────────────────────────────────────────────────────────────+// Magic Layers — client-side reconstruction+//+// Converts a validated MagicLayerAnalysis + the source bitmap into+// NATIVE Canvix elements (not a flat raster): text, shapes and+// cropped image regions, each carrying provenance metadata.+// ─────────────────────────────────────────────────────────────++import {+ createShapeElement,+ createTextElement,+ uid,+ type AnyElement,+ type Background,+ type ImageElement,+ type PageData,+} from '@/lib/types'+import { FONT_CLASS_MAP, type MagicLayerAnalysis, type MagicRegion } from './types'++export interface MagicLayersReconstruction {+ /** the page background to apply */+ background: Background+ /** full-bleed image element when the background is a photo (null otherwise) */+ backgroundElement: ImageElement | null+ /** reconstructed elements, bottom-to-top layer order */+ elements: AnyElement[]+ /** text elements need a post-insert measure pass (id → target height) */+ pendingMeasureIds: string[]+}++/** Load an image dataURL into an HTMLImageElement. */+export function loadImage(src: string): Promise<HTMLImageElement> {+ return new Promise((resolve, reject) => {+ const img = new Image()+ img.onload = () => resolve(img)+ img.onerror = () => reject(new Error('Image failed to load'))+ img.src = src+ })+}++/** Crop a normalized region out of a source bitmap → JPEG dataURL. */+async function cropRegion(+ img: HTMLImageElement,+ bounds: { x: number; y: number; w: number; h: number },+ maxDim: number+): Promise<{ dataUrl: string; width: number; height: number }> {+ const sx = Math.max(0, Math.floor(bounds.x * img.naturalWidth))+ const sy = Math.max(0, Math.floor(bounds.y * img.naturalHeight))+ const sw = Math.max(1, Math.floor(bounds.w * img.naturalWidth))+ const sh = Math.max(1, Math.floor(bounds.h * img.naturalHeight))+ // cap output to keep documents light (Phase 13 perf: no 4K crops in jsonb)+ const scale = Math.min(1, maxDim / Math.max(sw, sh))+ const dw = Math.max(1, Math.round(sw * scale))+ const dh = Math.max(1, Math.round(sh * scale))+ const canvas = document.createElement('canvas')+ canvas.width = dw+ canvas.height = dh+ const ctx = canvas.getContext('2d')+ if (!ctx) throw new Error('Canvas unavailable')+ ctx.drawImage(img, sx, sy, sw, sh, 0, 0, dw, dh)+ return { dataUrl: canvas.toDataURL('image/jpeg', 0.88), width: dw, height: dh }+}++/**+ * Reconstruct a full editable page from an analysis.+ *+ * @param analysis validated region analysis (from /api/ai/magic-layers)+ * @param sourceImage the original bitmap (dataURL)+ * @param pageWidth target page width in px+ * @param pageHeight target page height in px+ */+export async function reconstructDesign(+ analysis: MagicLayerAnalysis,+ sourceImage: string,+ pageWidth: number,+ pageHeight: number,+ /** regions to skip (discarded by the user in review) */+ skipRegionIds: string[] = []+): Promise<MagicLayersReconstruction> {+ const img = await loadImage(sourceImage)+ const skip = new Set(skipRegionIds)++ // background+ let background: Background = { type: 'solid', color: analysis.background.from ?? '#FFFFFF' }+ if (analysis.background.kind === 'gradient') {+ background = {+ type: 'gradient',+ from: analysis.background.from ?? '#1F142E',+ to: analysis.background.to ?? '#7630D7',+ angle: analysis.background.angle ?? 135,+ }+ }+ let backgroundElement: ImageElement | null = null+ if (analysis.background.kind === 'photo') {+ // full-bleed image as the bottom layer, page background stays solid white+ const src = await cropRegion(img, { x: 0, y: 0, w: 1, h: 1 }, Math.max(pageWidth, pageHeight))+ backgroundElement = {+ id: uid('image'),+ type: 'image',+ x: 0,+ y: 0,+ width: pageWidth,+ height: pageHeight,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ shadow: { enabled: false, color: '#000000', blur: 12, offsetX: 0, offsetY: 6 },+ src: src.dataUrl,+ radius: 0,+ naturalWidth: src.width,+ naturalHeight: src.height,+ name: 'Background (Magic Layers)',+ magicLayer: {+ sourceRegion: 'background',+ confidence: 1,+ sourceType: 'photo',+ originalBounds: { x: 0, y: 0, w: 1, h: 1 },+ },+ }+ background = { type: 'solid', color: '#FFFFFF' }+ }++ const elements: AnyElement[] = []+ const pendingMeasureIds: string[] = []++ if (backgroundElement) elements.push(backgroundElement)++ const ordered = [...analysis.regions].sort((a, b) => (a.z ?? 0) - (b.z ?? 0))+ for (const region of ordered) {+ if (skip.has(region.id)) continue+ const el = await regionToElement(region, img, pageWidth, pageHeight)+ if (!el) continue+ if (el.type === 'text') pendingMeasureIds.push(el.id)+ elements.push(el)+ }++ return { background, backgroundElement, elements, pendingMeasureIds }+}++async function regionToElement(+ region: MagicRegion,+ img: HTMLImageElement,+ pageWidth: number,+ pageHeight: number+): Promise<AnyElement | null> {+ const x = Math.round(region.bounds.x * pageWidth)+ const y = Math.round(region.bounds.y * pageHeight)+ const w = Math.max(8, Math.round(region.bounds.w * pageWidth))+ const h = Math.max(8, Math.round(region.bounds.h * pageHeight))++ const meta = {+ sourceRegion: region.id,+ confidence: region.confidence,+ sourceType: region.type,+ originalBounds: { ...region.bounds },+ }++ if (region.type === 'text') {+ // font size: fraction of image height → px on the target page+ const fontPx = Math.max(8, Math.round((region.fontSize ?? 0.05) * pageHeight))+ const fonts = FONT_CLASS_MAP[region.fontClass ?? 'sans']+ const isHeading = (region.fontSize ?? 0.05) > 0.06+ const el = createTextElement({+ x,+ y,+ width: w,+ height: h,+ })+ el.text = region.text ?? ''+ el.fontSize = fontPx+ el.fontFamily = isHeading || region.bold ? fonts.heading : fonts.body+ el.bold = region.bold || isHeading+ el.italic = region.italic ?? false+ el.fill = region.color ?? '#1F2226'+ el.align = region.align ?? 'center'+ el.name = `Text — ${(region.text ?? '').slice(0, 18).replace(/\n/g, ' ')}`+ el.magicLayer = meta+ return el+ }++ if (region.type === 'photo') {+ // cropped image region from the source bitmap+ const crop = await cropRegion(img, region.bounds, 1024)+ return {+ id: uid('image'),+ type: 'image',+ x,+ y,+ width: w,+ height: h,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ shadow: { enabled: false, color: '#000000', blur: 12, offsetX: 0, offsetY: 6 },+ src: crop.dataUrl,+ radius: 0,+ naturalWidth: crop.width,+ naturalHeight: crop.height,+ name: region.subject ? `Image — ${region.subject.slice(0, 24)}` : 'Image region',+ magicLayer: meta,+ } satisfies ImageElement+ }++ if (region.type === 'shape' || region.type === 'decoration') {+ const shape = region.shape === 'ellipse' ? 'ellipse' : region.shape === 'rounded-rect' ? 'rect' : 'rect'+ const el = createShapeElement(shape, {+ x,+ y,+ width: w,+ height: h,+ })+ el.fill = region.color ?? '#00C4CC'+ el.cornerRadius = region.shape === 'rounded-rect' ? Math.min(24, Math.round(Math.min(w, h) * 0.2)) : 0+ el.name = region.type === 'decoration' ? 'Decoration' : `Shape — ${shape}`+ el.magicLayer = meta+ return el+ }++ return null+}++/** Build the page data for a reconstruction (used on "Create design"). */+export function toPage(rec: MagicLayersReconstruction): PageData {+ return {+ id: uid('page'),+ background: rec.background,+ elements: rec.elements,+ }+}diff --git a/src/lib/magic-layers/types.ts b/src/lib/magic-layers/types.tsnew file mode 100644index 0000000..69f50ca--- /dev/null+++ b/src/lib/magic-layers/types.ts@@ -0,0 +1,82 @@+// ─────────────────────────────────────────────────────────────+// Magic Layers — image → editable design pipeline types+//+// Pipeline: upload → normalize → server vision analysis →+// region detection → client reconstruction → native Canvix+// elements with provenance metadata.+// ─────────────────────────────────────────────────────────────++/** Region kinds the vision model can detect. */+export type MagicRegionType = 'text' | 'photo' | 'shape' | 'decoration'++/** Font classification — exact fonts can't be recovered, only classes. */+export type MagicFontClass = 'sans' | 'serif' | 'script' | 'mono'++/** Bounds normalized to 0..1 of the source image dimensions. */+export interface MagicBounds {+ x: number+ y: number+ w: number+ h: number+}++/** A single detected region (server JSON protocol → client). */+export interface MagicRegion {+ id: string+ type: MagicRegionType+ bounds: MagicBounds+ /** text regions */+ text?: string+ color?: string+ fontClass?: MagicFontClass+ bold?: boolean+ italic?: boolean+ /** approx font size as a fraction of image height (0.01–0.3) */+ fontSize?: number+ align?: 'left' | 'center' | 'right'+ /** shape regions */+ shape?: 'rect' | 'rounded-rect' | 'ellipse'+ /** photo regions */+ subject?: string+ /** layer order hint (0 = bottom) */+ z?: number+ /** vision model confidence 0..1 */+ confidence: number+}++export interface MagicBackground {+ kind: 'solid' | 'gradient' | 'photo'+ from?: string+ to?: string+ angle?: number+}++export interface MagicLayerAnalysis {+ background: MagicBackground+ regions: MagicRegion[]+ /** server-side notes about limitations (shown honestly in UI) */+ notes?: string+}++/** Provenance metadata retained on each generated Canvix element. */+export interface MagicLayerMeta {+ /** id of the source region in the analysis */+ sourceRegion: string+ /** raw confidence from the analysis (0..1) */+ confidence: number+ /** what kind of source produced this element */+ sourceType: MagicRegionType+ /** original normalized bounds in the source image */+ originalBounds: MagicBounds+}++/** Fonts we map font classes to (from our 63-font library). */+export const FONT_CLASS_MAP: Record<MagicFontClass, { heading: string; body: string }> = {+ sans: { heading: 'Archivo Black', body: 'Poppins' },+ serif: { heading: 'Playfair Display', body: 'Lora' },+ script: { heading: 'Dancing Script', body: 'Dancing Script' },+ mono: { heading: 'Space Mono', body: 'Space Mono' },+}++/** Canva-style honesty threshold — regions below this are flagged for review. */+export const REVIEW_CONFIDENCE_THRESHOLD = 0.6diff --git a/src/lib/magic-layers/validate.ts b/src/lib/magic-layers/validate.tsnew file mode 100644index 0000000..ccd0614--- /dev/null+++ b/src/lib/magic-layers/validate.ts@@ -0,0 +1,178 @@+// ─────────────────────────────────────────────────────────────+// Magic Layers — server-side region validation & normalization+//+// The vision model's JSON is NEVER trusted raw: every field is+// validated, clamped and sanitized here before it reaches the+// client reconstruction.+// ─────────────────────────────────────────────────────────────++import type {+ MagicBackground,+ MagicBounds,+ MagicFontClass,+ MagicLayerAnalysis,+ MagicRegion,+ MagicRegionType,+} from './types'++const HEX = /^#[0-9a-fA-F]{6}$/++function clamp01(n: unknown): number {+ const v = Number(n)+ if (!Number.isFinite(v)) return 0+ return Math.min(1, Math.max(0, v))+}++function clampRange(n: unknown, min: number, max: number, fallback: number): number {+ const v = Number(n)+ if (!Number.isFinite(v)) return fallback+ return Math.min(max, Math.max(min, v))+}++function sanitizeHex(input: unknown, fallback: string): string {+ if (typeof input !== 'string') return fallback+ const s = input.trim()+ if (HEX.test(s)) return s.toUpperCase()+ // 3-digit hex → expand+ if (/^#[0-9a-fA-F]{3}$/.test(s)) {+ return `#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`.toUpperCase()+ }+ return fallback+}++function sanitizeBounds(input: unknown): MagicBounds {+ const b = (input ?? {}) as Record<string, unknown>+ const x = clamp01(b.x)+ const y = clamp01(b.y)+ const w = clamp01(b.w ?? b.width)+ const h = clamp01(b.h ?? b.height)+ // degenerate regions are dropped upstream (w/h >= 0.005)+ return { x, y, w, h }+}++const REGION_TYPES: MagicRegionType[] = ['text', 'photo', 'shape', 'decoration']+const FONT_CLASSES: MagicFontClass[] = ['sans', 'serif', 'script', 'mono']+const SHAPES = ['rect', 'rounded-rect', 'ellipse'] as const++/**+ * Parse + validate a raw model reply into a trusted MagicLayerAnalysis.+ * Returns null when the reply contains no usable structure.+ */+export function validateAnalysis(raw: string): MagicLayerAnalysis | null {+ const cleaned = raw.replace(/```(?:json)?/gi, '').trim()+ const start = cleaned.indexOf('{')+ if (start === -1) return null+ let end = cleaned.lastIndexOf('}')+ while (end > start) {+ let candidate: Record<string, unknown> | null = null+ try {+ candidate = JSON.parse(cleaned.slice(start, end + 1)) as Record<string, unknown>+ } catch {+ candidate = null+ }+ if (candidate && typeof candidate === 'object' && Array.isArray(candidate.regions)) {+ return normalizeAnalysis(candidate)+ }+ end = cleaned.lastIndexOf('}', end - 1)+ }+ return null+}++function normalizeAnalysis(obj: Record<string, unknown>): MagicLayerAnalysis {+ // background+ const bgRaw = (obj.background ?? {}) as Record<string, unknown>+ const kindRaw = String(bgRaw.kind ?? 'solid')+ const background: MagicBackground =+ kindRaw === 'gradient'+ ? {+ kind: 'gradient',+ from: sanitizeHex(bgRaw.from, '#1F142E'),+ to: sanitizeHex(bgRaw.to, '#7630D7'),+ angle: clampRange(bgRaw.angle, 0, 360, 135),+ }+ : kindRaw === 'photo'+ ? { kind: 'photo' }+ : { kind: 'solid', from: sanitizeHex(bgRaw.from ?? bgRaw.color, '#FFFFFF') }++ // regions+ const seenIds = new Set<string>()+ const regions: MagicRegion[] = []+ const list = (obj.regions as unknown[]) ?? []+ for (const r of list.slice(0, 40)) {+ if (!r || typeof r !== 'object') continue+ const rr = r as Record<string, unknown>+ const typeRaw = String(rr.type ?? '')+ const type = (REGION_TYPES as string[]).includes(typeRaw) ? (typeRaw as MagicRegionType) : null+ if (!type) continue+ const bounds = sanitizeBounds(rr.bounds)+ if (bounds.w < 0.005 || bounds.h < 0.005) continue+ if (bounds.x + bounds.w < 0.005 || bounds.y + bounds.h < 0.005) continue++ let id = String(rr.id ?? '').replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 24)+ if (!id || seenIds.has(id)) id = `r${regions.length + 1}`+ seenIds.add(id)++ const region: MagicRegion = {+ id,+ type,+ bounds,+ confidence: clampRange(rr.confidence, 0, 1, 0.5),+ z: Math.round(clampRange(rr.z, 0, 40, regions.length)),+ }++ if (type === 'text') {+ const text = String(rr.text ?? '').replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, '').slice(0, 400).trim()+ if (!text) continue // text region without text is useless+ region.text = text+ region.color = sanitizeHex(rr.color ?? (rr.textStyle as Record<string, unknown>)?.color, '#1F2226')+ const fcRaw = String(rr.fontClass ?? 'sans')+ region.fontClass = (FONT_CLASSES as string[]).includes(fcRaw) ? (fcRaw as MagicFontClass) : 'sans'+ region.bold = rr.bold === true+ region.italic = rr.italic === true+ region.fontSize = clampRange(rr.fontSize, 0.008, 0.25, 0.05)+ const alignRaw = String(rr.align ?? 'center')+ region.align = (['left', 'center', 'right'] as string[]).includes(alignRaw)+ ? (alignRaw as 'left' | 'center' | 'right')+ : 'center'+ } else if (type === 'shape' || type === 'decoration') {+ region.color = sanitizeHex(rr.color, '#00C4CC')+ const shapeRaw = String(rr.shape ?? 'rect')+ region.shape = (SHAPES as readonly string[]).includes(shapeRaw)+ ? (shapeRaw as (typeof SHAPES)[number])+ : 'rect'+ } else if (type === 'photo') {+ region.subject = String(rr.subject ?? '').slice(0, 120)+ }++ regions.push(region)+ }++ // dedupe overlapping identical text regions (models sometimes double-report)+ const texts = regions.filter((r) => r.type === 'text')+ const dedupe = new Set<string>()+ for (let i = 0; i < texts.length; i++) {+ for (let j = i + 1; j < texts.length; j++) {+ const a = texts[i]+ const b = texts[j]+ if (a.text !== b.text) continue+ const overlap =+ Math.min(a.bounds.x + a.bounds.w, b.bounds.x + b.bounds.w) - Math.max(a.bounds.x, b.bounds.x)+ const overlapY =+ Math.min(a.bounds.y + a.bounds.h, b.bounds.y + b.bounds.h) - Math.max(a.bounds.y, b.bounds.y)+ if (overlap > 0 && overlapY > 0) {+ const key = b.confidence < a.confidence ? b.id : a.id+ dedupe.add(key)+ }+ }+ }++ const notes = typeof obj.notes === 'string' ? obj.notes.slice(0, 300) : undefined++ return {+ background,+ regions: regions+ .filter((r) => !dedupe.has(r.id))+ .sort((a, b) => (a.z ?? 0) - (b.z ?? 0)),+ notes,+ }+}diff --git a/src/lib/svg-export.ts b/src/lib/svg-export.tsnew file mode 100644index 0000000..da0aa76--- /dev/null+++ b/src/lib/svg-export.ts@@ -0,0 +1,379 @@+// ─────────────────────────────────────────────────────────────+// SVG export (v0.5) — true vector serialization of Canvix pages+//+// text, shapes, paths, strokes, images (href/clip), gradients,+// opacity, transforms (rotation/shadow) — no rasterization of+// vector elements. Text uses font-family references (viewers+// fall back gracefully); wrapping is measured with canvas 2D,+// mirroring Konva's algorithm.+//+// SECURITY: all text is XML-escaped; hrefs only allow data:/https?/;+// no <script>, no event attributes, no foreignObject. Output is+// safe to open in browsers and vector editors.+// ─────────────────────────────────────────────────────────────++import type {+ AnyElement,+ GradientFill,+ ImageElement,+ LineElement,+ PageData,+ ShapeElement,+ StrokeElement,+ StickerElement,+ TextElement,+ GroupElement,+} from '@/lib/types'++// ── escaping ─────────────────────────────────────────────────++function esc(s: string): string {+ return s+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''')+}++function safeHref(src: string): string | null {+ if (src.startsWith('data:image/')) return src+ if (/^https?:\/\//i.test(src)) return src+ return null+}++// ── id sanitization for url(#id) references ─────────────────++let refCounter = 0+function refId(prefix: string): string {+ refCounter += 1+ return `${prefix}${refCounter}`+}++// ── gradient defs ────────────────────────────────────────────++function gradientDef(grad: GradientFill, w: number, h: number, id: string): string {+ if (grad.type === 'radial') {+ return ` <radialGradient id="${id}" cx="50%" cy="50%" r="75%">+ <stop offset="0%" stop-color="${esc(grad.from)}" />+ <stop offset="100%" stop-color="${esc(grad.to)}" />+ </radialGradient>`+ }+ // linear: angle in degrees (0 = →, 90 = ↓) — SVG gradient coords+ const rad = (grad.angle * Math.PI) / 180+ const cx = 0.5+ const cy = 0.5+ const half = 0.5+ const x1 = cx - Math.cos(rad) * half+ const y1 = cy - Math.sin(rad) * half+ const x2 = cx + Math.cos(rad) * half+ const y2 = cy + Math.sin(rad) * half+ return ` <linearGradient id="${id}" x1="${x1.toFixed(4)}" y1="${y1.toFixed(4)}" x2="${x2.toFixed(4)}" y2="${y2.toFixed(4)}">+ <stop offset="0%" stop-color="${esc(grad.from)}" />+ <stop offset="100%" stop-color="${esc(grad.to)}" />+ </linearGradient>`+}++// ── text wrapping (mirrors Konva word wrap) ─────────────────++function wrapText(text: string, fontFamily: string, fontSize: number, bold: boolean, maxWidth: number): string[] {+ if (!text) return []+ const lines: string[] = []+ for (const paragraph of text.split('\n')) {+ if (!paragraph) {+ lines.push('')+ continue+ }+ const words = paragraph.split(' ')+ let line = ''+ for (const word of words) {+ const test = line ? `${line} ${word}` : word+ if (measureText(test, fontFamily, fontSize, bold) > maxWidth && line) {+ lines.push(line)+ line = word+ } else {+ line = test+ }+ }+ if (line) lines.push(line)+ }+ return lines+}++let measureCtx: CanvasRenderingContext2D | null = null+function measureText(text: string, fontFamily: string, fontSize: number, bold: boolean): number {+ try {+ if (!measureCtx) {+ const canvas = document.createElement('canvas')+ measureCtx = canvas.getContext('2d')+ }+ if (!measureCtx) return text.length * fontSize * 0.55+ measureCtx.font = `${bold ? '700' : '400'} ${fontSize}px ${fontFamily}`+ return measureCtx.measureText(text).width+ } catch {+ return text.length * fontSize * 0.55+ }+}++// ── element serializers ──────────────────────────────────────++interface SvgContext {+ defs: string[]+}++function fillAttrs(el: { fill: string; fillGradient?: GradientFill | null; width: number; height: number }, ctx: SvgContext): { fill: string; strokeAttrs: string } {+ if (el.fillGradient) {+ const id = refId('grad')+ ctx.defs.push(gradientDef(el.fillGradient, el.width, el.height, id))+ return { fill: `url(#${id})`, strokeAttrs: '' }+ }+ return { fill: el.fill, strokeAttrs: '' }+}++function rotationTransform(el: { x: number; y: number; rotation?: number }, originX?: number, originY?: number): string {+ if (!el.rotation) return ''+ return ` rotate(${el.rotation} ${originX ?? el.x} ${originY ?? el.y})`+}++function opacityAttr(el: { opacity?: number }): string {+ return el.opacity !== undefined && el.opacity < 1 ? ` opacity="${el.opacity.toFixed(3)}"` : ''+}++function shadowAttrs(el: { shadow?: { enabled: boolean; color: string; blur: number; offsetX: number; offsetY: number } }, ctx: SvgContext): string {+ const s = el.shadow+ if (!s || !s.enabled) return ''+ const id = refId('shadow')+ ctx.defs.push(+ ` <filter id="${id}" x="-50%" y="-50%" width="200%" height="200%">+ <feDropShadow dx="${s.offsetX}" dy="${s.offsetY}" stdDeviation="${Math.max(0.5, s.blur / 3)}" flood-color="${esc(s.color)}" />+ </filter>`+ )+ return ` filter="url(#${id})"`+}++function starPoints(cx: number, cy: number, outer: number, inner: number): string {+ const pts: string[] = []+ for (let i = 0; i < 5; i++) {+ const outerAngle = (Math.PI / 2) * -1 + (i * 2 * Math.PI) / 5+ const innerAngle = outerAngle + Math.PI / 5+ pts.push(`${(cx + outer * Math.cos(outerAngle)).toFixed(2)},${(cy + outer * Math.sin(outerAngle)).toFixed(2)}`)+ pts.push(`${(cx + inner * Math.cos(innerAngle)).toFixed(2)},${(cy + inner * Math.sin(innerAngle)).toFixed(2)}`)+ }+ return pts.join(' ')+}++function serializeElement(el: AnyElement, ctx: SvgContext): string {+ if (!el.visible) return ''+ const transformBase = rotationTransform(el)++ switch (el.type) {+ case 'text': {+ const t = el as TextElement+ const rendered = t.uppercase ? t.text.toUpperCase() : t.text+ const lines = wrapText(rendered, t.fontFamily, t.fontSize, t.bold, t.width)+ const lineHeight = t.fontSize * t.lineHeight+ const fill = t.fillGradient ? gradientRefFor(t, ctx) : t.fill+ const anchor = t.align === 'center' ? 'middle' : t.align === 'right' ? 'end' : 'start'+ const anchorX = t.align === 'center' ? t.x + t.width / 2 : t.align === 'right' ? t.x + t.width : t.x+ // first baseline ≈ top + ascent (0.8 × fontSize approximates Konva's ascent)+ const firstBaseline = t.y + t.fontSize * 0.8+ const tspans = lines+ .map((line, i) => `<tspan x="${anchorX}" ${i === 0 ? `y="${firstBaseline.toFixed(1)}"` : `dy="${lineHeight.toFixed(1)}"`}>${esc(line)}</tspan>`)+ .join('')+ const decor = [t.underline ? 'underline' : '', t.strike ? 'line-through' : ''].filter(Boolean).join(' ')+ const attrs = [+ `font-family="${esc(t.fontFamily)}"`,+ `font-size="${t.fontSize}"`,+ `font-weight="${t.bold ? 700 : 400}"`,+ `font-style="${t.italic ? 'italic' : 'normal'}"`,+ decor ? `text-decoration="${decor}"` : '',+ t.letterSpacing ? `letter-spacing="${t.letterSpacing}"` : '',+ `text-anchor="${anchor}"`,+ `fill="${fill}"`,+ opacityAttr(t),+ shadowAttrs(t, ctx),+ ]+ .filter(Boolean)+ .join(' ')+ // rotation around the text box top-left (Konva semantics)+ const transform = t.rotation ? ` transform="rotate(${t.rotation} ${t.x} ${t.y})"` : ''+ return ` <text ${attrs}${transform} xml:space="preserve">${tspans}</text>`+ }++ case 'rect': {+ const s = el as ShapeElement+ const { fill } = fillAttrs(s, ctx)+ const gradFill = s.fillGradient ? gradientRefFor(s, ctx) : fill+ return ` <rect x="${s.x}" y="${s.y}" width="${s.width}" height="${s.height}"${s.cornerRadius ? ` rx="${s.cornerRadius}"` : ''}${s.stroke && s.stroke !== 'transparent' && s.strokeWidth ? ` stroke="${s.stroke}" stroke-width="${s.strokeWidth}"` : ''} fill="${gradFill}"${opacityAttr(s)}${shadowAttrs(s, ctx)}${transformBase ? ` transform="rotate(${s.rotation} ${s.x} ${s.y})"` : ''} />`+ }++ case 'ellipse': {+ const s = el as ShapeElement+ const cx = s.x + s.width / 2+ const cy = s.y + s.height / 2+ const gradFill = s.fillGradient ? gradientRefFor(s, ctx) : s.fill+ return ` <ellipse cx="${cx}" cy="${cy}" rx="${s.width / 2}" ry="${s.height / 2}"${s.stroke && s.stroke !== 'transparent' && s.strokeWidth ? ` stroke="${s.stroke}" stroke-width="${s.strokeWidth}"` : ''} fill="${gradFill}"${opacityAttr(s)}${shadowAttrs(s, ctx)}${transformBase ? ` transform="rotate(${s.rotation} ${cx} ${cy})"` : ''} />`+ }++ case 'triangle': {+ const s = el as ShapeElement+ const pts = `${s.x},${s.y + s.height} ${s.x + s.width / 2},${s.y} ${s.x + s.width},${s.y + s.height}`+ const gradFill = s.fillGradient ? gradientRefFor(s, ctx) : s.fill+ return ` <polygon points="${pts}"${s.stroke && s.stroke !== 'transparent' && s.strokeWidth ? ` stroke="${s.stroke}" stroke-width="${s.strokeWidth}" stroke-linejoin="round"` : ''} fill="${gradFill}"${opacityAttr(s)}${shadowAttrs(s, ctx)}${transformBase ? ` transform="rotate(${s.rotation} ${s.x} ${s.y})"` : ''} />`+ }++ case 'star': {+ const s = el as ShapeElement+ const cx = s.x + s.width / 2+ const cy = s.y + s.height / 2+ const outer = Math.min(s.width, s.height) / 2+ const gradFill = s.fillGradient ? gradientRefFor(s, ctx) : s.fill+ return ` <polygon points="${starPoints(cx, cy, outer, outer * 0.55)}"${s.stroke && s.stroke !== 'transparent' && s.strokeWidth ? ` stroke="${s.stroke}" stroke-width="${s.strokeWidth}" stroke-linejoin="round"` : ''} fill="${gradFill}"${opacityAttr(s)}${shadowAttrs(s, ctx)}${transformBase ? ` transform="rotate(${s.rotation} ${cx} ${cy})"` : ''} />`+ }++ case 'path': {+ const s = el as ShapeElement+ if (!s.pathData) return ''+ const sx = s.width / 100+ const sy = s.height / 100+ const gradFill = s.fillGradient ? gradientRefFor(s, ctx) : s.fill+ const sw = s.strokeWidth / Math.max(0.01, sx)+ return ` <path d="${sanitizePathData(s.pathData)}" transform="translate(${s.x} ${s.y}) scale(${sx.toFixed(4)} ${sy.toFixed(4)})${s.rotation ? ` rotate(${s.rotation} 0 0)` : ''}"${s.stroke && s.stroke !== 'transparent' && s.strokeWidth ? ` stroke="${s.stroke}" stroke-width="${sw}" vector-effect="non-scaling-stroke"` : ''} fill="${gradFill}"${opacityAttr(s)}${shadowAttrs(s, ctx)} />`+ }++ case 'line': {+ const l = el as LineElement+ const x2 = l.x + Math.max(l.width, 12)+ const dash = l.dashed ? ` stroke-dasharray="${l.strokeWidth * 2.2} ${l.strokeWidth * 1.8}"` : ''+ let out = ` <line x1="${l.x}" y1="${l.y}" x2="${x2}" y2="${l.y}" stroke="${l.stroke}" stroke-width="${l.strokeWidth}" stroke-linecap="round"${dash}${opacityAttr(l)}${transformBase ? ` transform="rotate(${l.rotation} ${l.x} ${l.y})"` : ''} />`+ // arrowheads+ const pl = Math.max(10, l.strokeWidth * 2.4)+ const pw = Math.max(8, l.strokeWidth * 2)+ if (l.arrowStart) {+ out += `\n <polygon points="${l.x + pl},${l.y - pw / 2} ${l.x + pl},${l.y + pw / 2} ${l.x},${l.y}" fill="${l.stroke}"${transformBase ? ` transform="rotate(${l.rotation} ${l.x} ${l.y})"` : ''} />`+ }+ if (l.arrowEnd) {+ out += `\n <polygon points="${x2 - pl},${l.y - pw / 2} ${x2 - pl},${l.y + pw / 2} ${x2},${l.y}" fill="${l.stroke}"${transformBase ? ` transform="rotate(${l.rotation} ${l.x} ${l.y})"` : ''} />`+ }+ return out+ }++ case 'stroke': {+ const s = el as StrokeElement+ if (!s.points || s.points.length < 4) return ''+ const pts: string[] = []+ for (let i = 0; i + 1 < s.points.length; i += 2) {+ pts.push(`${(s.x + s.points[i]).toFixed(1)},${(s.y + s.points[i + 1]).toFixed(1)}`)+ }+ return ` <polyline points="${pts.join(' ')}" fill="none" stroke="${s.stroke}" stroke-width="${s.strokeWidth}" stroke-linecap="round" stroke-linejoin="round"${opacityAttr(s)} />`+ }++ case 'image': {+ const im = el as ImageElement+ const href = safeHref(im.src)+ if (!href) return ''+ const clipId = im.radius ? refId('clip') : null+ if (im.radius) {+ ctx.defs.push(` <clipPath id="${clipId}"><rect x="${im.x}" y="${im.y}" width="${im.width}" height="${im.height}" rx="${im.radius}" /></clipPath>`)+ }+ // flips mirror around the image center: x' = 2·cx − x+ const cxImg = im.x + im.width / 2+ const cyImg = im.y + im.height / 2+ const fx = im.flipH ? `translate(${2 * cxImg} 0) scale(-1 1)` : ''+ const fy = im.flipV ? `translate(0 ${2 * cyImg}) scale(1 -1)` : ''+ const transform = [fx, fy, im.rotation ? `rotate(${im.rotation} ${cxImg} ${cyImg})` : '']+ .filter(Boolean)+ .join(' ')+ return ` <image href="${esc(href)}" x="${im.x}" y="${im.y}" width="${im.width}" height="${im.height}"${clipId ? ` clip-path="url(#${clipId})"` : ''}${transform ? ` transform="${transform}"` : ''}${opacityAttr(im)}${shadowAttrs(im, ctx)} preserveAspectRatio="none" />`+ }++ case 'sticker': {+ const sk = el as StickerElement+ const cx = sk.x + sk.width / 2+ const cy = sk.y + sk.height / 2+ return ` <text x="${cx}" y="${cy}" text-anchor="middle" dominant-baseline="central" font-size="${sk.fontSize}" font-family="'Segoe UI Emoji', 'Apple Color Emoji', 'Noto Color Emoji', sans-serif"${opacityAttr(sk)}${transformBase ? ` transform="rotate(${sk.rotation} ${cx} ${cy})"` : ''}>${esc(sk.char)}</text>`+ }++ case 'group': {+ const g = el as GroupElement+ const children = g.children+ .filter((c) => c.visible)+ .map((c) => serializeElement({ ...c, x: c.x - g.x, y: c.y - g.y, rotation: c.rotation } as AnyElement, ctx))+ .filter(Boolean)+ .join('\n')+ return ` <g transform="translate(${g.x} ${g.y})${g.rotation ? ` rotate(${g.rotation})` : ''}"${opacityAttr(g)}>\n${children}\n </g>`+ }++ default:+ return ''+ }+}++function gradientRefFor(el: { fillGradient?: GradientFill | null; width: number; height: number }, ctx: SvgContext): string {+ if (!el.fillGradient) return 'none'+ const id = refId('grad')+ ctx.defs.push(gradientDef(el.fillGradient, el.width, el.height, id))+ return `url(#${id})`+}++/** Path data sanitizer — keeps a safe subset of SVG path commands. */+function sanitizePathData(d: string): string {+ // allow M,m,L,l,H,h,V,v,C,c,S,s,Q,q,T,t,A,a,Z,z + numbers/commas/spaces+ const cleaned = d.replace(/[^MmLlHhVvCcSsQqTtAaZz0-9.,\s+-]/g, '')+ return esc(cleaned)+}++// ── page → SVG ───────────────────────────────────────────────++/** Serialize one page to a standalone SVG document string. */+export function exportPageToSVG(page: PageData, designWidth: number, designHeight: number): string {+ refCounter = 0+ const ctx: SvgContext = { defs: [] }++ // background+ let bgOut = ''+ if (page.background.type === 'solid') {+ bgOut = ` <rect width="${designWidth}" height="${designHeight}" fill="${esc(page.background.color)}" />`+ } else if (page.background.type === 'gradient') {+ const bgGrad: GradientFill = {+ type: 'linear',+ from: page.background.from,+ to: page.background.to,+ angle: page.background.angle,+ }+ const fill = gradientRefFor({ fillGradient: bgGrad, width: designWidth, height: designHeight }, ctx)+ bgOut = ` <rect width="${designWidth}" height="${designHeight}" fill="${fill}" />`+ }++ const elements = page.elements+ .map((el) => serializeElement(el, ctx))+ .filter(Boolean)+ .join('\n')++ const defs = ctx.defs.length ? `<defs>\n${ctx.defs.join('\n')}\n</defs>\n` : ''++ return `<?xml version="1.0" encoding="UTF-8"?>+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${designWidth}" height="${designHeight}" viewBox="0 0 ${designWidth} ${designHeight}">+${defs}${bgOut}+${elements}+</svg>+`+}++/** Serialize all pages → array of SVG strings (one file per page). */+export function exportDesignToSVGs(pages: PageData[], designWidth: number, designHeight: number): string[] {+ return pages.map((p) => exportPageToSVG(p, designWidth, designHeight))+}++/** Trigger a browser download of an SVG string. */+export function downloadSVG(svg: string, filename: string): void {+ const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' })+ const url = URL.createObjectURL(blob)+ const a = document.createElement('a')+ a.href = url+ a.download = filename+ document.body.appendChild(a)+ a.click()+ a.remove()+ setTimeout(() => URL.revokeObjectURL(url), 4000)+}diff --git a/src/lib/types.ts b/src/lib/types.tsindex 50e9870..9869201 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -17,6 +17,36 @@ export type ElementType =export type TextAlign = 'left' | 'center' | 'right' | 'justify'+// ── v0.5: animations (model is Konva-independent — pure functions of time) ──++export type AnimationKind = 'none' | 'fade' | 'rise' | 'pan' | 'pop' | 'wipe' | 'zoom' | 'rotate' | 'breathe'+export type AnimationSpeed = 'slow' | 'medium' | 'fast'+export type AnimationDirection = 'left' | 'right' | 'up' | 'down'+export type AnimationEasing = 'linear' | 'easeIn' | 'easeOut' | 'easeInOut' | 'spring'++export interface ElementAnimation {+ kind: AnimationKind+ /** seconds */+ duration: number+ /** seconds — start offset after the page is shown */+ delay: number+ easing: AnimationEasing+ /** pan/rise travel direction */+ direction?: AnimationDirection+}++export type TransitionKind = 'none' | 'fade' | 'slide' | 'morph'++export interface PageTransition {+ kind: TransitionKind+ /** 0.1–2.5 s */+ duration: number+ direction?: AnimationDirection+}++/** canva speed presets (seconds) */+export const SPEED_PRESETS: Record<AnimationSpeed, number> = { slow: 1.4, medium: 0.9, fast: 0.5 }+/** Canva-style text effects (v0.3: aligned to canva 2026 naming) */export type TextEffect = 'none' | 'shadow' | 'lift' | 'hollow' | 'neon' | 'echo' | 'glow' | 'outline' | 'background' | 'splice'@@ -64,6 +94,15 @@ export interface BaseElement {shadow: ShadowConfig/** user-facing layer name (Layers panel; falls back to an auto label) */name?: string+ /** v0.5: entry animation (undefined = none) */+ animation?: ElementAnimation+ /** v0.5 Magic Layers provenance — set on elements generated from an image analysis */+ magicLayer?: {+ sourceRegion: string+ confidence: number+ sourceType: string+ originalBounds: { x: number; y: number; w: number; h: number }+ }}export interface TextElement extends BaseElement {@@ -185,6 +224,8 @@ export interface PageData {id: stringbackground: Backgroundelements: AnyElement[]+ /** v0.5: transition played when this page appears after another */+ transition?: PageTransition}/** user-placed ruler guide (position in page px; scoped to a page) */diff --git a/src/lib/video-export.ts b/src/lib/video-export.tsnew file mode 100644index 0000000..acdad9f--- /dev/null+++ b/src/lib/video-export.ts@@ -0,0 +1,606 @@+// ─────────────────────────────────────────────────────────────+// Video export (v0.5) — REAL rendering pipeline, fully local+//+// Canvix document → animation timeline → frame renderer+// → MediaRecorder canvas capture → MP4 (H.264, where the+// browser can encode it) or WebM (VP9/VP8 fallback)+//+// Fixed-timestep rendering: frames are pushed manually via+// captureStream(0) + requestFrame(), so output timing is exact+// even when rendering is slower than realtime. Static PNG/JPG/+// PDF/SVG exports are unaffected (animations are ignored there).+// ─────────────────────────────────────────────────────────────++import Konva from 'konva'+import type { AnyElement, ImageElement, PageData } from '@/lib/types'+import { animateElementAt, pageHoldDuration } from '@/lib/animations'++export interface VideoExportOptions {+ designWidth: number+ designHeight: number+ pages: PageData[]+ /** output pixel cap on the longest page edge */+ maxWidth?: number+ fps?: number+ onProgress?: (ratio: number, stage: string) => void+}++export interface VideoExportResult {+ blob: Blob+ mimeType: string+ extension: string+ durationSec: number+ frames: number+}++/** Detect the best supported output format (honest — no fake MP4). */+export function detectVideoFormat(): { mimeType: string; extension: string; label: string } | null {+ if (typeof MediaRecorder === 'undefined') return null+ const candidates: { mimeType: string; extension: string; label: string }[] = [+ { mimeType: 'video/mp4;codecs=avc1.42E01E', extension: 'mp4', label: 'MP4 (H.264)' },+ { mimeType: 'video/mp4', extension: 'mp4', label: 'MP4' },+ { mimeType: 'video/webm;codecs=vp9', extension: 'webm', label: 'WebM (VP9)' },+ { mimeType: 'video/webm;codecs=vp8', extension: 'webm', label: 'WebM (VP8)' },+ { mimeType: 'video/webm', extension: 'webm', label: 'WebM' },+ ]+ for (const c of candidates) {+ try {+ if (MediaRecorder.isTypeSupported(c.mimeType)) return c+ } catch {+ /* continue */+ }+ }+ return null+}++interface TimelineSegment {+ page: PageData+ /** hold time before the transition (seconds) */+ hold: number+ /** transition INTO the next page (seconds, 0 on the last page) */+ transition: number+}++/** Build the page timeline (holds + transitions). */+export function buildTimeline(pages: PageData[]): { segments: TimelineSegment[]; total: number } {+ const segments: TimelineSegment[] = pages.map((page, i) => ({+ page,+ hold: pageHoldDuration(page),+ transition:+ i < pages.length - 1+ ? Math.min(2.5, Math.max(0.1, pages[i + 1].transition?.duration ?? 0.7))+ : 0,+ }))+ const total = segments.reduce((sum, s) => sum + s.hold + s.transition, 0)+ return { segments, total }+}++/** Estimated video duration (for the UI, before rendering). */+export function estimateVideoDuration(pages: PageData[]): number {+ return buildTimeline(pages).total+}++// ── image preload (dataURLs + remote, best-effort) ──────────++function loadImage(src: string): Promise<HTMLImageElement | null> {+ return new Promise((resolve) => {+ const img = new Image()+ img.crossOrigin = 'anonymous'+ img.onload = () => resolve(img)+ img.onerror = () => resolve(null)+ img.src = src+ })+}++async function collectImages(pages: PageData[]): Promise<Map<string, HTMLImageElement>> {+ const map = new Map<string, HTMLImageElement>()+ const sources: string[] = []+ const walk = (els: AnyElement[]) => {+ for (const el of els) {+ if (el.type === 'image') sources.push(el.src)+ else if (el.type === 'group') walk(el.children)+ }+ }+ for (const p of pages) walk(p.elements)+ const unique = [...new Set(sources)].slice(0, 60)+ await Promise.all(+ unique.map(async (src) => {+ const img = await loadImage(src)+ if (img) map.set(src, img)+ })+ )+ return map+}++// ── Konva node builders (geometry mirrors element-node.tsx) ──++function buildKonvaNode(el: AnyElement, images: Map<string, HTMLImageElement>): Konva.Node {+ switch (el.type) {+ case 'text': {+ const t = el+ return new Konva.Text({+ id: t.id,+ x: t.x,+ y: t.y,+ width: t.width,+ text: t.uppercase ? t.text.toUpperCase() : t.text,+ fontSize: t.fontSize,+ fontFamily: t.fontFamily,+ fontStyle: `${t.italic ? 'italic ' : ''}${t.bold ? 'bold' : 'normal'}`,+ textDecoration: [t.underline ? 'underline' : '', t.strike ? 'line-through' : ''].filter(Boolean).join(' '),+ fill: t.fill,+ align: t.align === 'justify' ? 'left' : t.align,+ lineHeight: t.lineHeight,+ letterSpacing: t.letterSpacing,+ wrap: 'word',+ })+ }+ case 'rect': {+ const s = el+ const node = new Konva.Rect({+ id: s.id,+ x: s.x,+ y: s.y,+ width: s.width,+ height: s.height,+ fill: s.fillGradient ? undefined : s.fill,+ stroke: s.stroke,+ strokeWidth: s.strokeWidth,+ cornerRadius: s.cornerRadius,+ })+ applyGradient(node, s)+ return node+ }+ case 'ellipse': {+ const s = el+ const node = new Konva.Ellipse({+ id: s.id,+ x: s.x + s.width / 2,+ y: s.y + s.height / 2,+ radiusX: s.width / 2,+ radiusY: s.height / 2,+ fill: s.fillGradient ? undefined : s.fill,+ stroke: s.stroke,+ strokeWidth: s.strokeWidth,+ })+ applyGradient(node, s)+ return node+ }+ case 'triangle': {+ const s = el+ const node = new Konva.Line({+ id: s.id,+ x: s.x,+ y: s.y,+ points: [0, s.height, s.width / 2, 0, s.width, s.height],+ closed: true,+ fill: s.fillGradient ? undefined : s.fill,+ stroke: s.stroke,+ strokeWidth: s.strokeWidth,+ })+ applyGradient(node, s)+ return node+ }+ case 'star': {+ const s = el+ const outer = Math.min(s.width, s.height) / 2+ const node = new Konva.Star({+ id: s.id,+ x: s.x + s.width / 2,+ y: s.y + s.height / 2,+ numPoints: 5,+ innerRadius: outer * 0.55,+ outerRadius: outer,+ fill: s.fillGradient ? undefined : s.fill,+ stroke: s.stroke,+ strokeWidth: s.strokeWidth,+ })+ applyGradient(node, s)+ return node+ }+ case 'path': {+ const s = el+ const node = new Konva.Path({+ id: s.id,+ x: s.x,+ y: s.y,+ data: s.pathData ?? '',+ fill: s.fillGradient ? undefined : s.fill,+ stroke: s.stroke,+ strokeWidth: s.strokeWidth,+ })+ node.scaleX(s.width / 100)+ node.scaleY(s.height / 100)+ return node+ }+ case 'line': {+ const l = el+ return new Konva.Arrow({+ id: l.id,+ x: l.x,+ y: l.y,+ points: [0, 0, Math.max(l.width, 12), 0],+ stroke: l.stroke,+ fill: l.stroke,+ strokeWidth: l.strokeWidth,+ lineCap: 'round',+ dash: l.dashed ? [l.strokeWidth * 2.2, l.strokeWidth * 1.8] : undefined,+ pointerLength: Math.max(10, l.strokeWidth * 2.4),+ pointerWidth: Math.max(8, l.strokeWidth * 2),+ pointerAtBeginning: l.arrowStart,+ pointerAtEnd: l.arrowEnd,+ })+ }+ case 'stroke': {+ const s = el+ return new Konva.Line({+ id: s.id,+ x: s.x,+ y: s.y,+ points: s.points,+ stroke: s.stroke,+ strokeWidth: s.strokeWidth,+ lineCap: 'round',+ lineJoin: 'round',+ tension: 0.25,+ })+ }+ case 'sticker': {+ const sk = el+ return new Konva.Text({+ id: sk.id,+ x: sk.x,+ y: sk.y,+ width: sk.width,+ height: sk.height,+ text: sk.char,+ fontSize: sk.fontSize,+ fontFamily: "'Segoe UI Emoji', 'Apple Color Emoji', 'Noto Color Emoji', sans-serif",+ align: 'center',+ })+ }+ case 'image': {+ const im = el as ImageElement+ const node = new Konva.Image({+ id: im.id,+ x: im.x,+ y: im.y,+ width: im.width,+ height: im.height,+ image: images.get(im.src) ?? undefined,+ cornerRadius: im.radius,+ })+ return node+ }+ case 'group': {+ const g = el+ const group = new Konva.Group({ id: g.id, x: g.x, y: g.y, rotation: g.rotation ?? 0 })+ for (const child of g.children.filter((c) => c.visible)) {+ const childNode = buildKonvaNode(child, images)+ childNode.x(child.x - g.x)+ childNode.y(child.y - g.y)+ group.add(childNode as Konva.Shape | Konva.Group)+ }+ return group+ }+ default:+ return new Konva.Group({ id: (el as { id: string }).id })+ }+}++function applyGradient(+ node: Konva.Shape,+ s: { fillGradient?: { type: 'linear' | 'radial'; from: string; to: string; angle: number } | null; width: number; height: number }+): void {+ if (!s.fillGradient) return+ if (s.fillGradient.type === 'radial') {+ node.fillRadialGradientStartPoint({ x: s.width / 2, y: s.height / 2 })+ node.fillRadialGradientEndPoint({ x: s.width / 2, y: s.height / 2 })+ node.fillRadialGradientStartRadius(0)+ node.fillRadialGradientEndRadius(Math.max(s.width, s.height) / 2)+ node.fillRadialGradientColorStops([0, s.fillGradient.from, 1, s.fillGradient.to])+ } else {+ const rad = (s.fillGradient.angle * Math.PI) / 180+ node.fillLinearGradientStartPoint({ x: 0, y: 0 })+ node.fillLinearGradientEndPoint({ x: Math.cos(rad) * s.width, y: Math.sin(rad) * s.height })+ node.fillLinearGradientColorStops([0, s.fillGradient.from, 1, s.fillGradient.to])+ }+}++// ── the export pipeline ──────────────────────────────────────++/**+ * Render the design timeline into a real video file (in-browser).+ */+export async function exportVideo(opts: VideoExportOptions): Promise<VideoExportResult> {+ const format = detectVideoFormat()+ if (!format) throw new Error('This browser cannot record video (MediaRecorder unavailable).')++ const fps = opts.fps ?? 30+ const scale = Math.min(1, (opts.maxWidth ?? 1280) / Math.max(opts.designWidth, opts.designHeight))+ const width = Math.max(2, Math.round((opts.designWidth * scale) / 2) * 2)+ const height = Math.max(2, Math.round((opts.designHeight * scale) / 2) * 2)++ const { segments, total } = buildTimeline(opts.pages)+ const totalFrames = Math.max(1, Math.round(total * fps))++ // preload every image source first (dataURLs resolve instantly)+ opts.onProgress?.(0, 'Loading images…')+ const images = await collectImages(opts.pages)++ // recorder canvas with manual frame pushing+ const canvas = document.createElement('canvas')+ canvas.width = width+ canvas.height = height+ const ctx = canvas.getContext('2d')+ if (!ctx) throw new Error('Could not create the rendering canvas.')+ const stream = canvas.captureStream(0)+ const track = stream.getVideoTracks()[0] as MediaStreamTrack & { requestFrame?: () => void }++ const recorder = new MediaRecorder(stream, {+ mimeType: format.mimeType,+ videoBitsPerSecond: Math.round(width * height * fps * 0.12),+ })+ const chunks: BlobPart[] = []+ recorder.ondataavailable = (e) => {+ if (e.data.size > 0) chunks.push(e.data)+ }+ const done = new Promise<void>((resolve) => {+ recorder.onstop = () => resolve()+ })+ recorder.start()++ // hidden host for the Konva stages+ const host = document.createElement('div')+ host.style.cssText = 'position:fixed;left:-99999px;top:0;'+ document.body.appendChild(host)++ const nodesForPage = new Map<number, { node: Konva.Node; el: AnyElement }[]>()+ const stageForPage = new Map<number, Konva.Stage>()++ const buildPage = (index: number): { node: Konva.Node; el: AnyElement }[] => {+ let nodes = nodesForPage.get(index)+ if (nodes) return nodes+ const page = segments[index].page+ const pageScale = width / opts.designWidth+ const stage = new Konva.Stage({ container: host, width, height })++ const bgLayer = new Konva.Layer({ listening: false, scale: { x: pageScale, y: pageScale } })+ const bg = page.background+ const bgRect =+ bg.type === 'gradient'+ ? new Konva.Rect({+ width: opts.designWidth,+ height: opts.designHeight,+ fillLinearGradientStartPoint: { x: 0, y: 0 },+ fillLinearGradientEndPoint: {+ x: Math.cos((bg.angle * Math.PI) / 180) * opts.designWidth,+ y: Math.sin((bg.angle * Math.PI) / 180) * opts.designHeight,+ },+ fillLinearGradientColorStops: [0, bg.from, 1, bg.to],+ })+ : new Konva.Rect({ width: opts.designWidth, height: opts.designHeight, fill: bg.color })+ bgLayer.add(bgRect)+ stage.add(bgLayer)++ const layer = new Konva.Layer({+ listening: false,+ scale: { x: pageScale, y: pageScale },+ clip: { x: 0, y: 0, width: opts.designWidth, height: opts.designHeight },+ })+ stage.add(layer)++ nodes = page.elements+ .filter((el) => el.visible)+ .map((el) => {+ const node = buildKonvaNode(el, images)+ const shape = node as Konva.Shape+ if (el.shadow?.enabled && typeof shape.shadowColor === 'function') {+ shape.shadowColor(el.shadow.color)+ shape.shadowBlur(el.shadow.blur)+ shape.shadowOffset({ x: el.shadow.offsetX, y: el.shadow.offsetY })+ }+ layer.add(node as Konva.Shape | Konva.Group)+ return { node, el }+ })+ layer.batchDraw()+ nodesForPage.set(index, nodes)+ stageForPage.set(index, stage)+ return nodes+ }++ /** apply animation state at page-local time t and draw */+ const drawPage = (index: number, t: number): HTMLCanvasElement | null => {+ const nodes = buildPage(index)+ for (const { node, el } of nodes) {+ const a = el.animation+ if (a && a.kind !== 'none') {+ const state = animateElementAt(el, t)+ node.opacity((el.opacity ?? 1) * state.opacity)+ if (state.reveal < 1) {+ const r = Math.max(0.001, state.reveal)+ node.scale({ x: r, y: 1 })+ node.offsetY(el.height / 2)+ node.x(el.x + state.dx)+ node.y(el.y + state.dy + el.height / 2)+ } else if (state.scaleX !== 1 || state.scaleY !== 1) {+ node.scale({ x: state.scaleX, y: state.scaleY })+ node.offsetX(el.width / 2)+ node.offsetY(el.height / 2)+ node.x(el.x + state.dx + el.width / 2)+ node.y(el.y + state.dy + el.height / 2)+ } else {+ node.scale({ x: 1, y: 1 })+ node.offsetX(0)+ node.offsetY(0)+ node.x(el.x + state.dx)+ node.y(el.y + state.dy)+ }+ node.rotation((el.rotation ?? 0) + state.rotation)+ } else {+ node.opacity(el.opacity ?? 1)+ node.scale({ x: 1, y: 1 })+ node.offsetX(0)+ node.offsetY(0)+ node.x(el.x)+ node.y(el.y)+ node.rotation(el.rotation ?? 0)+ }+ }+ stageForPage.get(index)?.batchDraw()+ return stageForPage.get(index)!.toCanvas()+ }++ /** timeline segment start times */+ let tCursor = 0+ const segStarts = segments.map((s) => {+ const start = tCursor+ tCursor += s.hold + s.transition+ return start+ })++ /** render the composite for timeline time t onto the recorder canvas */+ const renderFrameAt = (frameNo: number, t: number): void => {+ void frameNo+ // locate the active segment+ let segIdx = segments.length - 1+ let segLocal = t - segStarts[segments.length - 1]+ for (let i = 0; i < segments.length; i++) {+ const start = segStarts[i]+ const end = start + segments[i].hold + segments[i].transition+ if (t >= start && t < end) {+ segIdx = i+ segLocal = t - start+ break+ }+ }+ const seg = segments[segIdx]+ const inTransition = segLocal >= seg.hold && seg.transition > 0+ const p = inTransition ? (segLocal - seg.hold) / seg.transition : 0++ ctx.fillStyle = '#FFFFFF'+ ctx.fillRect(0, 0, width, height)++ if (!inTransition) {+ const pageCanvas = drawPage(segIdx, segLocal)+ if (pageCanvas) ctx.drawImage(pageCanvas, 0, 0, width, height)+ } else {+ // transition: outgoing holds its final state; incoming enters+ const outCanvas = drawPage(segIdx, seg.hold + seg.transition) // final state+ const inCanvas = drawPage(segIdx + 1, 0)++ const nextSeg = segments[segIdx + 1]+ const kind = nextSeg.page.transition?.kind ?? 'fade'+ const dir = nextSeg.page.transition?.direction ?? 'left'++ if (outCanvas) ctx.drawImage(outCanvas, 0, 0, width, height)+ if (inCanvas) {+ ctx.save()+ switch (kind) {+ case 'fade':+ ctx.globalAlpha = p+ ctx.drawImage(inCanvas, 0, 0, width, height)+ break+ case 'slide': {+ const off = (1 - p) * (dir === 'right' ? -width : width)+ ctx.drawImage(inCanvas, off, 0, width, height)+ break+ }+ case 'morph':+ ctx.globalAlpha = p+ ctx.translate((1 - p) * width * 0.05, (1 - p) * height * 0.05)+ ctx.scale(0.9 + 0.1 * p, 0.9 + 0.1 * p)+ ctx.drawImage(inCanvas, 0, 0, width, height)+ break+ default:+ ctx.drawImage(inCanvas, 0, 0, width, height)+ }+ ctx.restore()+ }+ }+ }++ try {+ ctx.fillStyle = '#FFFFFF'+ ctx.fillRect(0, 0, width, height)++ /**+ * REAL-TIME PACED CAPTURE — MediaRecorder stamps requestFrame() calls with+ * wall-clock time, so frames MUST be paced to real time (not rendered as+ * fast as possible) or the video duration drifts. When rendering falls+ * behind schedule we drop frames to stay on the timeline; when ahead, we+ * yield until the target time.+ */+ const yieldToMain = (): Promise<void> =>+ new Promise<void>((resolve) => {+ // MessageChannel tasks are not subject to hidden-tab timer throttling+ if (typeof MessageChannel !== 'undefined') {+ const ch = new MessageChannel()+ ch.port1.onmessage = () => resolve()+ ch.port2.postMessage(null)+ return+ }+ setTimeout(resolve, 0)+ })++ const startWall = performance.now()+ const deadline = startWall + total * 1000 + 15_000 // hard safety cap+ let frame = 0++ while (frame < totalFrames) {+ const t = frame / fps+ const targetWall = startWall + t * 1000++ // behind schedule? skip ahead to the frame the clock says we should render+ let now = performance.now()+ if (now > targetWall + 250) {+ const behind = Math.floor((now - startWall) / 1000 * fps)+ frame = Math.max(frame + 1, Math.min(behind, totalFrames - 1))+ continue+ }++ // ahead of schedule → yield in small chunks until the clock catches up+ while (now < targetWall && performance.now() < deadline) {+ await yieldToMain()+ now = performance.now()+ }+ if (performance.now() >= deadline) break // safety cap++ renderFrameAt(frame, t)+ track.requestFrame?.()++ frame += 1+ if (frame % 10 === 0) {+ opts.onProgress?.(frame / totalFrames, `Rendering frame ${frame + 1} / ${totalFrames}`)+ await yieldToMain() // keep the UI (and devtools) responsive+ }+ }++ // let the encoder flush the final frame+ await new Promise((r) => setTimeout(r, 200))+ track.requestFrame?.()+ recorder.stop()+ await done+ opts.onProgress?.(1, 'Finalizing…')+ } finally {+ for (const stage of stageForPage.values()) stage.destroy()+ host.remove()+ stream.getTracks().forEach((tr) => tr.stop())+ }++ const blob = new Blob(chunks, { type: format.mimeType })+ if (!blob.size) throw new Error('The video encoder produced an empty file — try fewer pages or a smaller resolution.')+ return { blob, mimeType: format.mimeType, extension: format.extension, durationSec: total, frames: totalFrames }+}++/** Trigger a download of the produced video blob. */+export function downloadVideo(result: VideoExportResult, filename: string): void {+ const url = URL.createObjectURL(result.blob)+ const a = document.createElement('a')+ a.href = url+ a.download = `${filename}.${result.extension}`+ document.body.appendChild(a)+ a.click()+ a.remove()+ setTimeout(() => URL.revokeObjectURL(url), 10_000)+}diff --git a/src/store/editor-store.ts b/src/store/editor-store.tsindex 045e779..20a76cc 100644--- a/src/store/editor-store.ts+++ b/src/store/editor-store.ts@@ -15,6 +15,13 @@ import {} from '@/lib/types'import type { TemplateDef } from '@/lib/templates'import { magicRelayoutPages } from '@/lib/magic'+import {+ clearPageAnimations,+ magicAnimatePage,+} from '@/lib/animations'+import type { ElementAnimation, PageTransition } from '@/lib/types'+import type { CollabOp, DesignEventRow } from '@/lib/collab/protocol'+import type { Collaborator, CollabStatus } from '@/lib/collab/protocol'export type PanelId =| 'templates'@@ -38,6 +45,28 @@ interface HistoryEntry {// module-level clipboard (not reactive)let clipboard: AnyElement[] = []+// ── v0.5 collaboration: op emission ─────────────────+// The store is the single source of truth for local mutations. After every+// LOCAL mutation it emits an op through the registered emitter (set by+// use-collab). Remote ops flow back through `applyRemoteOp`, which never+// emits — so there is no feedback loop and no re-entry flag needed.++type OpEmitter = (op: CollabOp) => void+let emitOp: OpEmitter | null = null++/** Register (or clear) the collaboration op emitter. */+export function setOpEmitter(fn: OpEmitter | null) {+ emitOp = fn+}++function emit(op: CollabOp) {+ try {+ emitOp?.(op)+ } catch {+ /* collab emission must never break local editing */+ }+}+interface EditorState {designId: string | nulldesignName: string@@ -147,6 +176,33 @@ interface EditorState {// v0.4: magic translate — batch-update text elements across ALL pagestranslateTexts: (updates: { id: string; text: string }[]) => void+ // v0.5: magic layers — bulk element insertion + page replacement+ addElementsBulk: (els: AnyElement[]) => void+ replaceCurrentPage: (page: PageData) => void+ appendPage: (page: PageData) => void++ // v0.5: collaboration runtime state (not persisted — per-tab)+ collaborators: Collaborator[]+ collabStatus: CollabStatus+ setCollaborators: (list: Collaborator[]) => void+ setCollabStatus: (s: CollabStatus) => void+ /** apply a remote op (never emits, never pushes history) */+ applyRemoteOp: (event: DesignEventRow) => void++ // v0.5: comments mode+ commentsOpen: boolean+ toggleComments: () => void+ setCommentsOpen: (open: boolean) => void++ // v0.5: animations+ setElementAnimation: (ids: string[], animation: ElementAnimation | null) => void+ setPageTransition: (transition: PageTransition | null) => void+ magicAnimateCurrentPage: (speed?: 'slow' | 'medium' | 'fast') => void+ clearPageAnimations: () => void+ animateOpen: boolean+ toggleAnimate: () => void+ setAnimateOpen: (open: boolean) => void+// panels & savesetPanel: (p: PanelId) => voidmarkSaving: () => void@@ -183,6 +239,12 @@ export const useEditorStore = create<EditorState>((set, get) => ({drawSize: 6,brand: DEFAULT_BRAND,+ // v0.5: collaboration runtime+ collaborators: [],+ collabStatus: 'offline',+ commentsOpen: false,+ animateOpen: false,+showRulers: false,manualGuides: [],versions: [],@@ -230,7 +292,10 @@ export const useEditorStore = create<EditorState>((set, get) => ({.catch(() => { /* offline — keep local list */ })},- rename: (name) => set({ designName: name, dirty: true }),+ rename: (name) => {+ set({ designName: name, dirty: true })+ emit({ kind: 'design:rename', name: name.slice(0, 80) })+ },pushHistory: () => {const { pages, currentPage, past, version } = get()@@ -255,6 +320,9 @@ export const useEditorStore = create<EditorState>((set, get) => ({dirty: true,version: version + 1,})+ // undo restores snapshots — op-level undo replay is out of scope (see+ // COLLABORATION-ARCHITECTURE.md §7), so sync coarse+ emit({ kind: 'pages:replace', pages: prev.pages, width: get().width, height: get().height })},redo: () => {@@ -270,6 +338,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({dirty: true,version: version + 1,})+ emit({ kind: 'pages:replace', pages: next.pages, width: get().width, height: get().height })},setSelection: (ids) => set({ selectedIds: ids }),@@ -287,6 +356,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({const next = clone(pages)next[currentPage].elements.push(el)set({ pages: next, selectedIds: [el.id] })+ emit({ kind: 'element:add', pageId: next[currentPage].id, element: el })},updateElementsLive: (ids, patch) => {@@ -296,6 +366,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({ids.includes(e.id) ? ({ ...e, ...patch } as AnyElement) : e)set({ pages: next, version: version + 1, dirty: true })+ emit({ kind: 'elements:update', pageId: next[currentPage].id, ids: [...ids], patch: { ...patch } })},updateElements: (ids, patch) => {@@ -311,6 +382,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({const next = clone(pages)next[currentPage].elements = next[currentPage].elements.filter((e) => !selectedIds.includes(e.id))set({ pages: next, selectedIds: [] })+ emit({ kind: 'element:delete', pageId: next[currentPage].id, ids: [...selectedIds] })},duplicateSelection: () => {@@ -324,6 +396,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({const next = clone(pages)next[currentPage].elements = [...next[currentPage].elements, ...clones]set({ pages: next, selectedIds: clones.map((c) => c.id) })+ emit({ kind: 'elements:add', pageId: next[currentPage].id, elements: clones })},copySelection: () => {@@ -346,6 +419,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({const next = clone(pages)next[currentPage].elements = [...next[currentPage].elements, ...clones]set({ pages: next, selectedIds: clones.map((c) => c.id) })+ emit({ kind: 'elements:add', pageId: next[currentPage].id, elements: clones })},moveLayer: (id, dir) => {@@ -362,6 +436,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({if (dir === 'back') j = 0els.splice(j, 0, ...els.splice(i, 1))set({ pages: next })+ emit({ kind: 'elements:reorder', pageId: next[currentPage].id, orderedIds: els.map((e) => e.id) })},reorderLayer: (dragId, targetIndex) => {@@ -375,6 +450,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({const arr = next[currentPage].elementsarr.splice(targetIndex, 0, ...arr.splice(i, 1))set({ pages: next })+ emit({ kind: 'elements:reorder', pageId: next[currentPage].id, orderedIds: arr.map((e) => e.id) })},setLock: (ids, locked) => get().updateElements(ids, { locked }),@@ -390,6 +466,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({const next = clone(pages)next[currentPage].elements = [...next[currentPage].elements.filter((e) => !selectedIds.includes(e.id)), group]set({ pages: next, selectedIds: [group.id] })+ emit({ kind: 'page:replace', pageId: next[currentPage].id, page: next[currentPage] })},ungroupSelection: () => {@@ -426,6 +503,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({released = [...released, ...releasedEls.map((c) => c.id)]}set({ pages: next, selectedIds: released })+ emit({ kind: 'page:replace', pageId: next[currentPage].id, page: next[currentPage] })},alignElements: (ids, mode) => {@@ -445,6 +523,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({}})set({ pages: next })+ emit({ kind: 'page:replace', pageId: next[currentPage].id, page: next[currentPage] })},flipSelection: (axis) => {@@ -459,21 +538,26 @@ export const useEditorStore = create<EditorState>((set, get) => ({return { ...el, rotation: (el.rotation + (axis === 'h' ? 0 : 180)) % 360 }})set({ pages: next })+ emit({ kind: 'page:replace', pageId: next[currentPage].id, page: next[currentPage] })},addPage: () => {get().pushHistory()const { pages } = get()- set({ pages: [...clone(pages), { id: uid('page'), background: { type: 'solid', color: '#FFFFFF' }, elements: [] }] })+ const page: PageData = { id: uid('page'), background: { type: 'solid', color: '#FFFFFF' }, elements: [] }+ set({ pages: [...clone(pages), page] })+ emit({ kind: 'page:add', page })},deletePage: (index) => {const { pages } = get()if (pages.length <= 1) returnget().pushHistory()+ const removedId = pages[index].idconst next = clone(pages)next.splice(index, 1)set({ pages: next, currentPage: Math.min(index, next.length - 1), selectedIds: [] })+ emit({ kind: 'page:delete', pageId: removedId })},duplicatePage: (index) => {@@ -485,6 +569,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({copy.elements = copy.elements.map((e) => ({ ...e, id: uid(e.type) }))next.splice(index + 1, 0, copy)set({ pages: next, currentPage: index + 1, selectedIds: [] })+ emit({ kind: 'page:add', page: copy, afterId: next[index].id })},setCurrentPage: (index) => set({ currentPage: index, selectedIds: [] }),@@ -495,17 +580,20 @@ export const useEditorStore = create<EditorState>((set, get) => ({const next = clone(pages)next[currentPage].background = bgset({ pages: next })+ emit({ kind: 'page:background', pageId: next[currentPage].id, background: bg })},applyTemplate: (t) => {get().pushHistory()+ const pages = clone(t.pages.map((p) => ({ ...p, id: uid('page') })))set({- pages: clone(t.pages.map((p) => ({ ...p, id: uid('page') }))),+ pages,width: t.width,height: t.height,currentPage: 0,selectedIds: [],})+ emit({ kind: 'pages:replace', pages, width: t.width, height: t.height })},setZoom: (z) => set({ zoom: Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, z)) }),@@ -591,6 +679,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({selectedIds: [],dirty: true,})+ emit({ kind: 'pages:replace', pages: v.pages, width: v.width, height: v.height })},deleteVersion: (id) => {const { designId, versions } = get()@@ -614,6 +703,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({// position instead of all being dumped in the centreconst next = magicRelayoutPages(clone(pages), oldW, oldH, width, height)set({ width, height, pages: next, selectedIds: [], zoom: 1 })+ emit({ kind: 'pages:replace', pages: next, width, height })},// ── v0.4: magic translate ────────────────────────────@@ -629,10 +719,199 @@ export const useEditorStore = create<EditorState>((set, get) => ({})const next = clone(pages).map((p) => ({ ...p, elements: applyTexts(p.elements) }))set({ pages: next, version: version + 1, dirty: true })+ emit({ kind: 'pages:replace', pages: next })+ },++ // ── v0.5: magic layers insertion ────────────────────+ addElementsBulk: (els) => {+ if (!els.length) return+ get().pushHistory()+ const { pages, currentPage } = get()+ const next = clone(pages)+ next[currentPage].elements = [...next[currentPage].elements, ...els.map((e) => clone(e))]+ set({ pages: next, selectedIds: els.map((e) => e.id) })+ emit({ kind: 'elements:add', pageId: next[currentPage].id, elements: els })+ },+ replaceCurrentPage: (page) => {+ get().pushHistory()+ const { pages, currentPage } = get()+ const next = clone(pages)+ next[currentPage] = clone(page)+ set({ pages: next, selectedIds: [] })+ emit({ kind: 'page:replace', pageId: page.id, page })+ },+ appendPage: (page) => {+ get().pushHistory()+ const { pages } = get()+ set({ pages: [...clone(pages), clone(page)], currentPage: pages.length, selectedIds: [] })+ emit({ kind: 'page:add', page })},setPanel: (p) => set({ panel: get().panel === p ? null : p }),+ // ── v0.5: comments mode ─────────────────+ toggleComments: () => set({ commentsOpen: !get().commentsOpen, panel: null }),+ setCommentsOpen: (open) => set({ commentsOpen: open }),++ // ── v0.5: animations ─────────────────+ toggleAnimate: () => set({ animateOpen: !get().animateOpen }),+ setAnimateOpen: (open) => set({ animateOpen: open }),+ setElementAnimation: (ids, animation) => {+ if (!ids.length) return+ get().pushHistory()+ const { pages, currentPage } = get()+ const next = clone(pages)+ next[currentPage].elements = next[currentPage].elements.map((e) =>+ ids.includes(e.id) ? { ...e, animation: animation ?? undefined } : e+ )+ set({ pages: next })+ emit({+ kind: 'page:replace',+ pageId: next[currentPage].id,+ page: next[currentPage],+ })+ },+ setPageTransition: (transition) => {+ get().pushHistory()+ const { pages, currentPage } = get()+ const next = clone(pages)+ next[currentPage] = { ...next[currentPage], transition: transition ?? undefined }+ set({ pages: next })+ emit({ kind: 'page:replace', pageId: next[currentPage].id, page: next[currentPage] })+ },+ magicAnimateCurrentPage: (speed = 'medium') => {+ get().pushHistory()+ const { pages, currentPage, height } = get()+ const next = clone(pages)+ const animated = magicAnimatePage(next[currentPage], height, speed)+ next[currentPage] = animated+ set({ pages: next })+ emit({ kind: 'page:replace', pageId: animated.id, page: animated })+ },+ clearPageAnimations: () => {+ get().pushHistory()+ const { pages, currentPage } = get()+ const next = clone(pages)+ const cleared = clearPageAnimations(next[currentPage])+ next[currentPage] = cleared+ set({ pages: next })+ emit({ kind: 'page:replace', pageId: cleared.id, page: cleared })+ },++ // ── v0.5: collaboration runtime state ─────────+ setCollaborators: (list) => set({ collaborators: list }),+ setCollabStatus: (s) => set({ collabStatus: s }),+ applyRemoteOp: (event) => {+ const payload = event.payload as Record<string, unknown> | null+ if (!payload) return+ const { pages, version } = get()+ const next = clone(pages)++ const findPage = (pageId: unknown): number =>+ next.findIndex((p) => p.id === pageId)++ const applyToPage = (pageId: unknown, fn: (page: PageData) => PageData): void => {+ const i = findPage(pageId)+ if (i >= 0) next[i] = fn(next[i])+ }++ switch (event.kind) {+ case 'elements:update': {+ const ids = (payload.ids as string[]) ?? []+ const patch = (payload.patch as Record<string, unknown>) ?? {}+ applyToPage(payload.pageId, (page) => ({+ ...page,+ elements: page.elements.map((e) => (ids.includes(e.id) ? ({ ...e, ...patch } as AnyElement) : e)),+ }))+ break+ }+ case 'element:add': {+ const el = payload.element as AnyElement | undefined+ if (el?.id) {+ applyToPage(payload.pageId, (page) =>+ page.elements.some((e) => e.id === el.id) ? page : { ...page, elements: [...page.elements, clone(el)] }+ )+ }+ break+ }+ case 'elements:add': {+ const els = (payload.elements as AnyElement[]) ?? []+ if (els.length) {+ applyToPage(payload.pageId, (page) => {+ const known = new Set(page.elements.map((e) => e.id))+ return { ...page, elements: [...page.elements, ...els.filter((e) => !known.has(e.id)).map((e) => clone(e))] }+ })+ }+ break+ }+ case 'element:delete': {+ const ids = new Set((payload.ids as string[]) ?? [])+ applyToPage(payload.pageId, (page) => ({ ...page, elements: page.elements.filter((e) => !ids.has(e.id)) }))+ break+ }+ case 'elements:reorder': {+ const orderedIds = (payload.orderedIds as string[]) ?? []+ applyToPage(payload.pageId, (page) => {+ const byId = new Map(page.elements.map((e) => [e.id, e]))+ const ordered = orderedIds.map((id) => byId.get(id)).filter((e): e is AnyElement => !!e)+ const rest = page.elements.filter((e) => !orderedIds.includes(e.id))+ return { ...page, elements: [...rest, ...ordered] }+ })+ break+ }+ case 'page:add': {+ const page = clone(payload.page as PageData)+ if (page?.id && !next.some((p) => p.id === page.id)) {+ const afterIdx = payload.afterId ? findPage(payload.afterId) : -1+ next.splice(afterIdx >= 0 ? afterIdx + 1 : next.length, 0, page)+ }+ break+ }+ case 'page:delete': {+ if (next.length > 1) {+ const i = findPage(payload.pageId)+ if (i >= 0) next.splice(i, 1)+ }+ break+ }+ case 'page:background': {+ applyToPage(payload.pageId, (page) => ({ ...page, background: clone(payload.background as Background) }))+ break+ }+ case 'page:replace': {+ const page = clone(payload.page as PageData)+ if (page?.id) {+ const i = findPage(page.id)+ if (i >= 0) next[i] = page+ else next.push(page)+ }+ break+ }+ case 'pages:replace': {+ const replaced = clone((payload.pages as PageData[]) ?? [])+ if (replaced.length) {+ const currentPage = Math.min(get().currentPage, replaced.length - 1)+ set({ pages: replaced, currentPage, selectedIds: [], version: version + 1, dirty: true })+ const w = Number(payload.width)+ const h = Number(payload.height)+ if (Number.isFinite(w) && w > 0 && Number.isFinite(h) && h > 0) set({ width: w, height: h })+ return+ }+ break+ }+ case 'design:rename': {+ const name = String(payload.name ?? '').slice(0, 80)+ if (name) set({ designName: name, dirty: true })+ return+ }+ default:+ return // unknown op — ignore (forward/backward compatibility)+ }++ const currentPage = Math.min(get().currentPage, next.length - 1)+ set({ pages: next, currentPage, version: version + 1, dirty: true })+ },+markSaving: () => set({ saving: true }),markSaved: () => set({ saving: false, dirty: false, savedAt: Date.now() }),}))