Skip to content

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.

feat(v0.6): the Agent Edition — MCP server, tables, frames, curved text & embeds

Ashiq Hussain Mir14a293d652bb
diff --git a/.env.example b/.env.example
index ef7ad15..94dca88 100644
--- a/.env.example
+++ b/.env.example
@@ -23,3 +23,11 @@ DATABASE_URL=postgresql://user:password@localhost:5432/canvix
#
# ZAI_BASE_URL=https://your-provider.example/v1
# ZAI_API_KEY=your-key
+
+# ── AI agents / MCP server (optional, v0.6) ───────────────────
+# Model Context Protocol endpoint: POST /api/mcp
+# Lets AI assistants (Claude Desktop, Cursor, ChatGPT, any MCP client)
+# create & edit real Canvix designs on this server. Disabled until
+# you set a token; requests must send "Authorization: Bearer <token>".
+# Generate one with: openssl rand -hex 24
+# CANVIX_MCP_TOKEN=change-me-to-a-long-random-secret
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6ad6c77..3260552 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,88 @@
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.6.0] — 2026-09-04
+
+The Agent Edition: Canvix speaks the Model Context Protocol, so AI assistants
+(Claude Desktop, Cursor, ChatGPT, any MCP client) can create and edit real
+designs on your server — and the editor closes the remaining Canva-parity gaps
+with native tables, image frames, curved text and embed cards.
+
+### MCP server — AI agents drive Canvix
+- **`POST /api/mcp`** implements MCP 2025-03-26 *Streamable HTTP* (stateless
+ profile): JSON-RPC 2.0 requests answered with one JSON object, notifications
+ with `202 Accepted`, `GET` → `405` (no server-initiated stream — spec-compliant),
+ full lifecycle (`initialize` → `notifications/initialized` → `tools/list` /
+ `tools/call`), `ping`, empty `resources/list` / `prompts/list`, batches ≤ 32.
+- **20 tools, all backed by real subsystems** — discover (`get_capabilities`,
+ `list_templates`, `search_designs`, `get_design`, `get_design_content`),
+ create (`create_design` blank-or-template — id *or* slug accepted, first page
+ auto-created), edit (`add_text`, `add_shape`, `add_image`, `add_table`,
+ `add_embed`, `set_background`, `update_element`, `delete_element`,
+ `animate_page` — the same Magic Animate engine), export (`export_design`:
+ true-vector SVG server-side, PNG via sharp, JSON), collaborate
+ (`comment_on_design`, `list_comments`) and `list_fonts`.
+- **`generate_design`** — AI-generated designs as *native editable elements*:
+ the provider is asked for a structured page spec (strict JSON mode with
+ repair + one retry), then every field is normalized/clamped (coords, hex
+ colors, whitelisted fonts, ≤ 25 elements) before a real Design row is
+ created. Without a provider the tool errors honestly and points at
+ template-based creation.
+- **Live propagation**: every MCP write appends a `pages:replace` event to the
+ design's collab log (actor `agent:mcp`) — open editor sessions replay agent
+ edits in real time; comments emit `comment:activity` markers.
+- **Hardening** — disabled until `CANVIX_MCP_TOKEN` is set (503 with setup
+ instructions otherwise); Bearer auth with timing-safe comparison; Origin
+ validation (DNS-rebinding guard); 120 req/min/IP; SSRF-guarded image fetch
+ (private hosts denied, 8 MB / 10 s caps, content-type allow-list) → dataURL;
+ per-type patch whitelists with clamps; no stack traces on the wire.
+- **Dashboard "AI agents (MCP)" card** — live status probe (`OPTIONS /api/mcp`),
+ copyable endpoint + client config JSON for Claude Desktop / Cursor / any
+ remote MCP client. `.env.example` documents the token.
+- **Protocol E2E** (`scripts/mcp-e2e.sh`): 37 assertions — initialize handshake,
+ 202 notifications, tools/list (20), auth (401), GET 405, unknown method/tool,
+ full create → style → add (text/shape/table/embed) → update (curve) →
+ animate → get → comment → export (svg/png/json) → delete flow, batch, parse
+ errors, AI generation — **37/37 passing**.
+
+### Tables (native, editable)
+- New `table` element: rows × cols with per-cell text/fill/bold, proportional
+ column widths, header band, border color/width, text style — four starter
+ styles (classic / minimal / bold / soft).
+- **Click any cell to edit it in place** (cell-scoped textarea overlay), add /
+ remove rows & columns from the context toolbar, restyle via the Style popover.
+- Renders in editor, previews, thumbnails, PNG/PDF/video exports; SVG export
+ serializes per-cell rects + text; **AI Translate now walks table cells too**.
+
+### Frames (image-in-shape)
+- New `frame` element: rect (with corner radius), ellipse, circle, triangle,
+ hexagon — images clip to the shape with cover-fit (Konva `clipFunc`).
+- **Drop an upload or photo onto a frame to fill it** (drop-to-fill), or use
+ the Fill button / shape switcher in the context toolbar. Empty frames show a
+ dashed placeholder. SVG export uses true vector `<clipPath>`.
+
+### Curved text
+- `TextElement.curve` (−180…180°): arch up or valley down, rendered as real
+ text-on-path (Konva `TextPath`) — editable, transformable, exports to
+ SVG `<textPath>` and rides PNG/PDF/video export unchanged. Curve slider in
+ the text toolbar with live reset.
+
+### Embed cards
+- New `embed` element for YouTube / Google Maps / generic links — a native
+ vector card (tinted media band, play / pin / link glyph, host + title) that
+ opens the URL when clicked in Preview or shared views. YouTube pulls the
+ public thumbnail (CORS-safe, graceful fallback). Honest scope: a styled
+ card, not an iframe.
+
+### Infrastructure
+- **`src/lib/v06-geometry.ts`** — pure shared geometry (arc math, table
+ layout, frame clip paths, embed card metrics) used by BOTH the Konva
+ renderers and the server-side SVG exporter (server-safe, no DOM imports).
+- SVG exporter gained table / frame (clipPath) / embed (band + glyphs) /
+ curved-text (defs path + textPath) serializers, all escaped and
+ `data:`/`https:`-only hrefs.
+- MCP tool schema definitions double as living API documentation for agents.
+
## [0.5.0] — 2026-09-04
The AI-native collaborative release: Magic Layers turns flat images into editable
diff --git a/README.md b/README.md
index 7e3a032..72b1963 100644
--- a/README.md
+++ b/README.md
@@ -30,6 +30,43 @@ watermarks, no paywalls.
## 🎨 Features
+### v0.6.0 — the Agent Edition: MCP, tables, frames, curved text & embeds
+
+- **MCP server (Model Context Protocol)** — Canvix becomes an **agent-native design platform**:
+ `POST /api/mcp` speaks standard MCP (JSON-RPC 2.0 over Streamable HTTP, stateless —
+ same transport profile Canva's AI Connector uses), so AI assistants like Claude
+ Desktop, Cursor, ChatGPT and any MCP client can **create and edit real designs on
+ your server**. **20 tools**: browse templates, search/get/create designs, add
+ text/shapes/images/tables/embeds, restyle & move elements, set backgrounds,
+ animate pages, comment, and export (SVG/PNG/JSON) — plus **`generate_design`**,
+ which asks the server AI provider for a structured, fully-validated page layout
+ and materializes it as native editable elements. Every tool maps to a real
+ subsystem; without a provider everything works except `generate_design`, which
+ says so plainly. Agent edits append to the same event log the editor replays, so
+ **a design an agent is editing updates live for humans in the editor**
+- **Security by default** — the endpoint stays disabled until you set
+ `CANVIX_MCP_TOKEN`; requests need `Authorization: Bearer <token>` (timing-safe
+ compare), cross-origin requests are rejected, per-IP rate limits apply, image
+ fetches are SSRF-guarded (private hosts denied, 8 MB cap), patches are
+ whitelisted & clamped per element type, and errors never leak stack traces
+- **Tables** — Canva-style native tables: click any cell on the canvas to edit it,
+ add/remove rows & columns from the toolbar, style borders/header/text, four
+ starter styles. Cells export to SVG and translate with the design
+- **Frames** — image-in-shape frames (rectangle, rounded, ellipse, circle,
+ triangle, hexagon). Drop an upload or photo on a frame to fill it — the image is
+ clipped to the shape with cover-fit (also true vector `<clipPath>` in SVG export)
+- **Curved text** — Canva's signature arc effect: curve any text −180°…+180°
+ (arch up / valley down), rendered as a real text-on-path (Konva `TextPath`, SVG
+ `<textPath>`) so it stays crisp in PNG/PDF/video exports and editable everywhere
+- **Embed cards** — YouTube videos, Google Maps places and any link become native
+ vector link cards (media band, play/pin glyph, title). Clicking a card in Preview
+ or shared views opens the URL — honest scope: a styled card, not an iframe
+- **Translate covers tables** — the AI translator now also walks table cells, not
+ just text boxes
+- **Dashboard “AI agents (MCP)” card** — shows the live endpoint status and a
+ copy-paste client config (endpoint URL + bearer headers) for Claude Desktop /
+ Cursor / any MCP client
+
### 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
@@ -332,6 +369,65 @@ limited per IP and logs usage into the `AIUsage` table.
| 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 |
+| MCP server (agent tools) | ✅ with token set — `generate_design` additionally needs the AI provider |
+
+## 🤖 AI agents (MCP)
+
+Canvix ships a **Model Context Protocol server** — the same interoperability
+standard Canva's “AI Connector” uses. It turns your Canvix instance into a set of
+tools an AI assistant can call: create designs, add elements, restyle, animate,
+comment, export.
+
+### Enable it
+
+```bash
+# 1. set a secret on the server (openssl rand -hex 24)
+CANVIX_MCP_TOKEN=your-long-random-secret
+# 2. restart Canvix — the dashboard "AI agents (MCP)" card flips to Enabled
+```
+
+### Connect a client
+
+Endpoint: `https://your-canvix.example.com/api/mcp` (Streamable HTTP, stateless).
+Client config (Claude Desktop / Cursor / any MCP client that supports remote
+HTTP servers):
+
+```json
+{
+ "mcpServers": {
+ "canvix": {
+ "url": "https://your-canvix.example.com/api/mcp",
+ "headers": { "Authorization": "Bearer <CANVIX_MCP_TOKEN>" }
+ }
+ }
+}
+```
+
+### Tool surface (20 tools)
+
+| Area | Tools |
+|---|---|
+| Discover | `get_capabilities`, `list_templates`, `search_designs`, `get_design`, `get_design_content` |
+| Create | `create_design` (blank or from template), `generate_design` (AI) |
+| Edit | `add_text`, `add_shape`, `add_image`, `add_table`, `add_embed`, `set_background`, `update_element`, `delete_element`, `animate_page` |
+| Export | `export_design` (svg / png / json) |
+| Collaborate | `comment_on_design`, `list_comments` |
+| Reference | `list_fonts` |
+
+Every write tool validates and clamps its arguments (hex colors, coordinates,
+font whitelists, size caps) and appends a `pages:replace` event to the design's
+collab log — so edits by agents appear live in any open editor session, and
+humans can undo or keep refining them.
+
+`generate_design` asks the server's AI provider for a structured page layout,
+normalizes it into native elements (clamped sizes, whitelisted fonts, element
+caps) and saves a real, editable design — not a raster. Without a provider
+configured, the tool returns an honest setup error; template-based creation
+keeps working.
+
+PNG export rasterizes server-side with sharp (system fonts render the text);
+SVG is true vector with font-family references — both caveats are stated in the
+tool descriptions so agents pick the right format.
## 🔐 Security notes
@@ -344,6 +440,11 @@ limited per IP and logs usage into the `AIUsage` table.
image hrefs only allow `data:`/`https:`; no scripts or event handlers
- **AI actions are double-validated** (server clamps + client re-checks) and
always undoable
+- **MCP endpoint hardening** — disabled until `CANVIX_MCP_TOKEN` is set; Bearer
+ auth with timing-safe compare; cross-origin requests rejected (DNS-rebinding
+ guard per the MCP spec); 120 req/min/IP; SSRF-guarded image fetches (private
+ hosts denied, 8 MB/10 s caps); tool arguments whitelisted & clamped per element
+ type; agent writes ride the same validated event log as human edits
- Known limitation: designs are link-accessible (no per-user ownership yet) —
the v0.5 identity layer is the migration path; see the security audit
@@ -356,8 +457,10 @@ limited per IP and logs usage into the `AIUsage` table.
- [x] 63-font library, gradient fills, PDF export, stock photo library, AI apps *(v0.3.2)*
- [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)*
+- [x] MCP server (20 agent tools), tables, frames, curved text, embed cards *(v0.6.0)*
- [ ] Accounts & per-design ownership (identity layer groundwork shipped in v0.5)
- [ ] Yjs-grade offline merge for collaboration
+- [ ] Audio/video elements & Beat Sync
- [ ] Plugin system (external, installable apps)
## 🤝 Contributing
diff --git a/package.json b/package.json
index cdff437..9154f2e 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "canvix",
- "version": "0.5.0",
+ "version": "0.6.0",
"private": false,
"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
diff --git a/research/CANVA-V06-RESEARCH.md b/research/CANVA-V06-RESEARCH.md
new file mode 100644
index 0000000..2e55c85
--- /dev/null
+++ b/research/CANVA-V06-RESEARCH.md
@@ -0,0 +1,146 @@
+# Canva + MCP Research — v0.6.0 ("The Agent Edition")
+
+Date: 2026-09-04 · Baseline: v0.5.0 @ `4139ffc` · Focus: MCP (Model Context Protocol)
+integration, remaining Canva feature gaps.
+
+---
+
+## 1. Fresh Canva research (canva.com, Sept 2026)
+
+### 1.1 What Canva markets today
+
+- **Canva AI 2.0 / "design through conversation"** — AI generates *editable* layouts,
+ not flat images; "Turn AI designs into editable layouts".
+- **Magic Studio suite** — Magic Write, Magic Media (image/video via Veo 3), Magic
+ Edit/Erase/Expand/Grab, Magic Switch, Magic Animate, Magic Resize, Translate.
+- **Visual Suite 2.0 (Canva Create 2025)** — docs, decks, whiteboards, sheets, videos.
+- **The AI Connector** — *"Bring editable design to your AI assistant chats. Generate
+ content, repurpose assets, and more in flow. Powered by the Canva MCP Server."*
+- **Editor staples** — curved text, frames, tables, charts, embeds (YouTube/Maps),
+ smart snapping guides, brand kits, comments, version history.
+
+### 1.2 Canvix v0.5 parity check
+
+| Canva capability | Canvix v0.5 | Verdict |
+|---|---|---|
+| Curved text (arc) | ❌ | **gap → v0.6** |
+| Frames (image clipped in shape) | ❌ (only corner radius) | **gap → v0.6** |
+| Tables (native, editable cells) | ❌ | **gap → v0.6** |
+| Embeds (YouTube/Maps/link cards) | ❌ | **gap → v0.6 (card form)** |
+| Charts | ✅ native elements (v0.3) | ok |
+| Smart snapping guides | ✅ #9954FF guides + manual ruler guides | ok |
+| Magic Animate | ✅ 9 anims + transitions (v0.5) | ok |
+| Magic Grab / Layers | ✅ Magic Layers (v0.5) | ok |
+| Magic Resize | ✅ (v0.4) | ok |
+| Magic Switch (format swap) | partial (resize only) | roadmap |
+| Real-time collaboration | ✅ SSE + event log (v0.5) | ok |
+| Comments | ✅ (v0.5) | ok |
+| Audio/video elements + Beat Sync | ❌ | roadmap (needs timeline work) |
+| MCP / AI agents | ❌ | **headline → v0.6** |
+
+---
+
+## 2. MCP research
+
+### 2.1 Canva's official MCP server (`mcp.canva.com/mcp`)
+
+Remote MCP server, OAuth, 22 tools (catalog via Speakeasy + canva.dev docs):
+
+- **Generate**: `generate-design` (returns *candidates* w/ preview thumbnails →
+ `create-design-from-candidate` materializes one), `search-brand-templates`,
+ `autofill`-style editing via `start-editing-transaction`.
+- **Discover**: `search-designs`, `get-design`, `get-design-pages`,
+ `get-design-content`, `get-presenter-notes`, `resolve-shortlink`.
+- **Edit**: `start-editing-transaction` (targeted text edits, autocomplete-magic).
+- **Assets**: `upload-asset-from-url`, `import-design-from-url` (PDF/PPTX/HTML→design).
+- **Organize**: `create-folder`, `search-folders`, `list-folder-items`,
+ `move-item-to-folder`.
+- **Export**: `get-export-formats`, `export-design` (PDF/JPG/PNG/PPTX/GIF/MP4,
+ returns a download URL).
+- **Collaborate**: `comment-on-design`, `list-comments`, `reply-to-comment`,
+ `list-replies`.
+
+Design principles worth copying: candidates-then-materialize for AI generation,
+explicit format probing before export, comments as first-class agent tools,
+rich prompting guidance embedded in tool descriptions.
+
+### 2.2 MCP Streamable HTTP transport (spec 2025-03-26)
+
+- **One endpoint** (`/api/mcp`), POST + GET.
+- POST body = single JSON-RPC 2.0 request/notification/response **or batch array**.
+- Input = only notifications/responses → **202 Accepted**, no body.
+- Input contains requests → respond `Content-Type: application/json` (single JSON
+ object) **or** `text/event-stream`. Client must support both — a plain-JSON
+ server is fully spec-compliant (no SSE needed).
+- GET → server MAY stream SSE or return **405**.
+- Lifecycle: `initialize` (protocolVersion, capabilities, serverInfo) →
+ `notifications/initialized` → `tools/list` / `tools/call`.
+- `tools/call` result: `{ content: [{type:'text', text}], isError? }`.
+- JSON-RPC error object: `{ code, message, data? }` (-32700 parse, -32600 invalid
+ request, -32601 method not found, -32602 invalid params, -32603 internal).
+- Security: validate `Origin`, require auth, rate limit.
+
+### 2.3 Canvix MCP design decisions
+
+- **Transport**: stateless Streamable HTTP, POST → JSON, GET → 405, no sessions
+ (works on Vercel serverless; no state to manage).
+- **Auth**: `Authorization: Bearer <CANVIX_MCP_TOKEN>` (env var). If unset, the
+ server responds with a JSON-RPC error saying MCP is not configured (no
+ capability leak). Per-IP rate limit reuses `rateLimit()`.
+- **Tool surface (18 tools)** — every tool maps to a real, existing Canvix
+ subsystem (no vaporware):
+
+ | Tool | Backing |
+ |---|---|
+ | `list_templates` | Template table |
+ | `search_designs` / `get_design` / `get_design_pages` / `get_design_content` | Design table |
+ | `create_design` (blank or `template_id`) | Design table |
+ | `add_text` / `add_shape` / `add_image` / `set_background` | element factories + SSRF-guarded fetch |
+ | `update_element` / `delete_element` | validated patches (design-action style) |
+ | `animate_page` | `src/lib/animations.ts` (pure, runs server-side) |
+ | `export_design` (svg / png / json) | `svg-export.ts` server-side + sharp → PNG |
+ | `comment_on_design` / `list_comments` | Comment table |
+ | `list_fonts` | 63 font registry |
+ | `generate_design` | AI provider → validated structured design → real Design row |
+ | `get_capabilities` | provider probe + build info |
+
+- **generate-design honesty**: with a provider, an LLM emits a full page spec
+ (validated: sizes, hex colors, clamped coords/fonts, element caps); without a
+ provider the tool errors with "requires an AI provider" (same contract as the
+ rest of the app). No candidate indirection — Canvix materializes one editable
+ design directly and returns its edit URL.
+- **Live propagation**: MCP writes append `DesignEvent` rows (same op schema the
+ collab client already replays), so an agent editing a design is visible to
+ humans in the editor *live*.
+- **Export honesty**: SVG is true vector (font-family references — viewers fall
+ back); PNG is rasterized server-side via sharp using system fonts (documented
+ caveat); the tool description states both.
+
+---
+
+## 3. v0.6 feature design
+
+### 3.1 Curved text
+`TextElement.curve?: number` (−180…180°, 0 = straight). Konva `TextPath` along a
+computed arc; slider in the text toolbar (0–±180). SVG export → `<textPath>` on
+the same arc. Interop: video/PNG/PDF export already render through Konva → free.
+
+### 3.2 Tables
+`TableElement { rows, cols, cells: {text, fill?}[], colWidths, rowHeight,
+borderColor, borderWidth, headerFill }`. Rendered natively (rect + text per
+cell in a Konva Group — every cell editable via double-click). Add/remove
+row/column from PropertiesBar; four starter styles in Elements panel.
+
+### 3.3 Frames
+`FrameElement { frameShape: 'rect'|'ellipse'|'triangle'|'hexagon'|'circle', src,
+naturalWidth/Height, fill }` — image clipped inside the shape (Konva group
+clipFunc). Dropping an upload/photo on a frame fills it. SVG export via
+`<clipPath>`. Empty frame renders the shape with a dashed hint.
+
+### 3.4 Embed cards
+`EmbedElement { url, title?, kind: 'youtube'|'map'|'link' }`. Native vector card
+(link icon, hostname, title; YouTube shows the video thumbnail). Click in
+Preview/Share opens the URL. Honest scope: a *card*, not an iframe.
+
+### 3.5 DB
+**No schema changes.** MCP reuses Design/Template/Comment/DesignEvent/AIUsage.
diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.ts
new file mode 100644
index 0000000..d817d2d
--- /dev/null
+++ b/src/app/api/mcp/route.ts
@@ -0,0 +1,59 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { checkAuth, handleMcpRequest, mcpRateLimit, mcpTokenConfigured } from '@/lib/mcp/server'
+
+export const runtime = 'nodejs'
+export const maxDuration = 60
+
+// ─────────────────────────────────────────────────────────────
+// POST /api/mcp — Model Context Protocol endpoint
+// (Streamable HTTP, stateless profile; see src/lib/mcp/server.ts)
+//
+// Auth: Authorization: Bearer <CANVIX_MCP_TOKEN>
+// Disabled: until CANVIX_MCP_TOKEN is set (responds with a
+// JSON-RPC error explaining how to enable it).
+// GET: 405 (no server-initiated SSE stream — spec-compliant)
+// ─────────────────────────────────────────────────────────────
+
+export async function POST(req: NextRequest) {
+ const authError = checkAuth(req)
+ if (authError) {
+ const status = authError.error?.code === -32001 ? 401 : 503
+ return NextResponse.json(authError, { status })
+ }
+ if (!mcpRateLimit(req)) {
+ return NextResponse.json(
+ { jsonrpc: '2.0', id: null, error: { code: -32000, message: 'Rate limit reached — max 120 requests/minute.' } },
+ { status: 429 }
+ )
+ }
+ const outcome = await handleMcpRequest(req)
+ if (outcome.status === 202) {
+ return new NextResponse(null, { status: 202 })
+ }
+ return NextResponse.json(outcome.body, { status: outcome.status })
+}
+
+// stateless server: no SSE stream for server-initiated messages
+export async function GET() {
+ return NextResponse.json(
+ { jsonrpc: '2.0', id: null, error: { code: -32000, message: 'This MCP server is stateless — use POST. GET streams are not offered.' } },
+ { status: 405, headers: { Allow: 'POST' } }
+ )
+}
+
+export async function DELETE() {
+ // no sessions to terminate (stateless)
+ return new NextResponse(null, { status: 405, headers: { Allow: 'POST' } })
+}
+
+export async function PUT() {
+ return new NextResponse(null, { status: 405, headers: { Allow: 'POST' } })
+}
+
+// let capability probes know whether the server is configured
+export async function OPTIONS() {
+ return NextResponse.json(
+ { mcp: mcpTokenConfigured() ? 'enabled' : 'disabled', transport: 'streamable-http', endpoint: '/api/mcp' },
+ { status: 200, headers: { Allow: 'POST, OPTIONS' } }
+ )
+}
diff --git a/src/components/dashboard/Dashboard.tsx b/src/components/dashboard/Dashboard.tsx
index df3dd2d..2cc41df 100644
--- a/src/components/dashboard/Dashboard.tsx
+++ b/src/components/dashboard/Dashboard.tsx
@@ -32,6 +32,7 @@ import { Logo } from '@/components/logo'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { DesignPreview } from '@/components/design-preview'
+import { McpCard } from '@/components/dashboard/McpCard'
import { TEMPLATES } from '@/lib/templates'
import { createPage, TEMPLATE_CATEGORIES, type TemplateRecord } from '@/lib/types'
import { PRESET_SIZES } from '@/lib/editor-utils'
@@ -487,6 +488,9 @@ export function Dashboard() {
</div>
</section>
+ {/* ── AI agents (MCP) ── */}
+ <McpCard />
+
{/* ── Recent designs ── */}
<section id="cv-recents" className="pt-12 scroll-mt-20">
<div className="flex items-center justify-between flex-wrap gap-3">
diff --git a/src/components/dashboard/McpCard.tsx b/src/components/dashboard/McpCard.tsx
new file mode 100644
index 0000000..a582bad
--- /dev/null
+++ b/src/components/dashboard/McpCard.tsx
@@ -0,0 +1,155 @@
+'use client'
+
+import { useEffect, useState } from 'react'
+import { Bot, Copy, Check, Plug, KeyRound, Info } from 'lucide-react'
+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
+import { Button } from '@/components/ui/button'
+import { cn } from '@/lib/utils'
+
+/**
+ * v0.6 — "AI agents (MCP)" dashboard card. Shows the real endpoint status
+ * (probed via OPTIONS /api/mcp) and a copy-paste client config.
+ */
+export function McpCard() {
+ const [status, setStatus] = useState<'checking' | 'enabled' | 'disabled'>('checking')
+ const [copied, setCopied] = useState<'url' | 'config' | null>(null)
+
+ useEffect(() => {
+ let cancelled = false
+ fetch('/api/mcp', { method: 'OPTIONS' })
+ .then((r) => r.json())
+ .then((d: { mcp?: string }) => {
+ if (!cancelled) setStatus(d.mcp === 'enabled' ? 'enabled' : 'disabled')
+ })
+ .catch(() => {
+ if (!cancelled) setStatus('disabled')
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [])
+
+ const origin = typeof window !== 'undefined' ? window.location.origin : 'https://your-canvix.example.com'
+ const endpoint = `${origin}/api/mcp`
+ const clientConfig = JSON.stringify(
+ {
+ mcpServers: {
+ canvix: {
+ url: endpoint,
+ headers: { Authorization: 'Bearer <CANVIX_MCP_TOKEN>' },
+ },
+ },
+ },
+ null,
+ 2
+ )
+
+ const copy = async (what: 'url' | 'config', text: string) => {
+ try {
+ await navigator.clipboard.writeText(text)
+ setCopied(what)
+ setTimeout(() => setCopied(null), 1800)
+ } catch {
+ /* clipboard unavailable */
+ }
+ }
+
+ return (
+ <section id="cv-agents" className="pt-12 scroll-mt-20">
+ <h2 className="text-xl font-bold">AI agents (MCP)</h2>
+ <div className="mt-4 rounded-2xl border border-white/10 bg-[#16171D] p-5 flex flex-col sm:flex-row items-center gap-6">
+ <div className="h-12 w-12 rounded-2xl bg-brand-gradient-soft flex items-center justify-center text-[#A78BFA] shrink-0">
+ <Bot size={24} />
+ </div>
+ <div className="flex-1 text-center sm:text-left">
+ <div className="text-sm font-semibold flex items-center justify-center sm:justify-start gap-2 flex-wrap">
+ Let AI assistants design with Canvix
+ <span
+ className={cn(
+ 'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide',
+ status === 'enabled'
+ ? 'bg-emerald-500/15 text-emerald-300'
+ : status === 'disabled'
+ ? 'bg-amber-500/15 text-amber-300'
+ : 'bg-white/10 text-white/50'
+ )}
+ data-testid="mcp-status"
+ >
+ <span className={cn('h-1.5 w-1.5 rounded-full', status === 'enabled' ? 'bg-emerald-400' : status === 'disabled' ? 'bg-amber-400' : 'bg-white/40')} />
+ {status === 'enabled' ? 'Enabled' : status === 'disabled' ? 'Off — set CANVIX_MCP_TOKEN' : 'Checking…'}
+ </span>
+ </div>
+ <div className="text-xs text-white/40 mt-1">
+ Claude, Cursor, ChatGPT &amp; any MCP client can create and edit real designs on this server — same canvas as you.
+ </div>
+ </div>
+ <Dialog>
+ <DialogTrigger asChild>
+ <Button variant="outline" className="rounded-xl border-white/15 bg-transparent text-white hover:bg-white/10 hover:text-white shrink-0">
+ <Plug size={14} className="mr-1.5" /> Connect an agent
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="max-w-lg bg-[#16171D] border-white/10 text-white">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <Bot size={16} className="text-[#A78BFA]" /> Connect an AI agent to Canvix
+ </DialogTitle>
+ </DialogHeader>
+
+ <div className="space-y-4 text-sm">
+ <div className="flex items-start gap-2 text-[13px] text-white/70">
+ <KeyRound size={14} className="mt-0.5 shrink-0 text-[#A78BFA]" />
+ <p>
+ <span className="text-white font-medium">1. Set a token.</span> On the server running Canvix, add{' '}
+ <code className="rounded bg-white/10 px-1 py-0.5 text-[11px]">CANVIX_MCP_TOKEN=&lt;your-secret&gt;</code> to the environment and
+ restart. The endpoint stays disabled until then.
+ </p>
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-[13px] font-medium text-white">2. Point your MCP client at this endpoint</span>
+ <button
+ className="flex items-center gap-1 text-[11px] text-white/50 hover:text-white"
+ onClick={() => void copy('url', endpoint)}
+ aria-label="Copy endpoint URL"
+ >
+ {copied === 'url' ? <Check size={12} /> : <Copy size={12} />} Copy URL
+ </button>
+ </div>
+ <code className="block rounded-lg bg-black/40 border border-white/10 px-3 py-2 text-[12px] text-[#02C0CC] break-all" data-testid="mcp-endpoint">
+ {endpoint}
+ </code>
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-[13px] font-medium text-white">3. Client config (Claude Desktop, Cursor, …)</span>
+ <button
+ className="flex items-center gap-1 text-[11px] text-white/50 hover:text-white"
+ onClick={() => void copy('config', clientConfig)}
+ aria-label="Copy client config"
+ >
+ {copied === 'config' ? <Check size={12} /> : <Copy size={12} />} Copy JSON
+ </button>
+ </div>
+ <pre className="rounded-lg bg-black/40 border border-white/10 px-3 py-2 text-[11.5px] leading-relaxed text-white/80 overflow-x-auto cv-scroll-dark">
+ {clientConfig}
+ </pre>
+ </div>
+
+ <div className="flex items-start gap-2 text-[12px] text-white/50 border-t border-white/10 pt-3">
+ <Info size={13} className="mt-0.5 shrink-0" />
+ <p>
+ 20 tools: generate &amp; create designs, add text/shapes/images/tables/embeds, restyle elements, animate, comment and export
+ (SVG/PNG/JSON). Agent edits show up live in open editor sessions. Requests need the Bearer token; per-IP rate limits apply.
+ Details in the README → <span className="text-white/70">AI agents (MCP)</span>.
+ </p>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </div>
+ </section>
+ )
+}
diff --git a/src/components/editor/Editor.tsx b/src/components/editor/Editor.tsx
index eb18059..b5bdaa9 100644
--- a/src/components/editor/Editor.tsx
+++ b/src/components/editor/Editor.tsx
@@ -307,15 +307,27 @@ export default function Editor() {
e.preventDefault()
const images = Array.from(files).filter((f) => f.type.startsWith('image/'))
if (!images.length) return
- const { addImageFromFile } = await import('./add-element')
+ const { addImageFromFile, fillFrameAt, readImageFile } = await import('./add-element')
+ const { canvasBridge } = await import('./canvas/canvas-bridge')
let ok = 0
+ let filled = 0
for (const file of images) {
try {
+ // v0.6: dropping over a frame fills the frame instead of adding an image
+ const { src, w, h } = await readImageFile(file)
+ const pageX = (e.clientX - canvasBridge.pan.x) / canvasBridge.zoom
+ const pageY = (e.clientY - canvasBridge.pan.y) / canvasBridge.zoom
+ if (fillFrameAt(pageX, pageY, src, w, h)) {
+ filled += 1
+ ok += 1
+ continue
+ }
await addImageFromFile(file)
ok += 1
} catch { /* ignore */ }
}
- if (ok) toast({ title: `${ok} image${ok > 1 ? 's' : ''} added` })
+ if (filled) toast({ title: `Frame filled with ${filled} image${filled > 1 ? 's' : ''}` })
+ else if (ok) toast({ title: `${ok} image${ok > 1 ? 's' : ''} added` })
}
window.addEventListener('dragover', onDragOver)
window.addEventListener('drop', onDrop)
diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsx
index 9713b50..47f4282 100644
--- a/src/components/editor/PropertiesBar.tsx
+++ b/src/components/editor/PropertiesBar.tsx
@@ -8,11 +8,11 @@ import {
AlignVerticalJustifyStart, AlignVerticalJustifyCenter, AlignVerticalJustifyEnd,
AlignHorizontalJustifyStart, AlignHorizontalJustifyCenter, AlignHorizontalJustifyEnd,
FlipHorizontal, FlipVertical, Sun, Contrast, Palette, RotateCcw, Replace, Lock, LockOpen,
- Layers, SquareDashed, Crop,
+ Layers, SquareDashed, Crop, Spline, Table2, Rows3, Columns3, Trash, Upload, ExternalLink,
} from 'lucide-react'
import { useEditorStore, selectedElements, currentPageData } from '@/store/editor-store'
-import type { ImageElement, LineElement, ShapeElement, StickerElement, TextElement, AnyElement } from '@/lib/types'
-import { isGroup } from '@/lib/types'
+import type { EmbedElement, FrameElement, ImageElement, LineElement, ShapeElement, StickerElement, TableElement, TextElement, AnyElement, FrameShape } from '@/lib/types'
+import { FRAME_SHAPES, isGroup } from '@/lib/types'
import { TEXT_EFFECTS } from '@/lib/types'
import { cn } from '@/lib/utils'
import { FontDropdown } from './toolbar/FontDropdown'
@@ -58,6 +58,9 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm
const image = first.type === 'image' ? (first as ImageElement) : null
const sticker = first.type === 'sticker' ? (first as StickerElement) : null
const group = first.type === 'group' ? first : null
+ const table = first.type === 'table' ? (first as TableElement) : null
+ const frame = first.type === 'frame' ? (first as FrameElement) : null
+ const embed = first.type === 'embed' ? (first as EmbedElement) : null
const canGroup = isMulti
const canUngroup = sel.some((e) => isGroup(e))
@@ -176,6 +179,27 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm
<SliderRow label="Line spacing" value={text.lineHeight} min={0.6} max={3} step={0.05} onChange={(v) => updateLive(ids, { lineHeight: v })} onCommit={() => update(ids, { lineHeight: text.lineHeight })} format={(v) => `${v.toFixed(2)}×`} />
</ToolbarPopover>
+ {/* v0.6: curved text (canva “Curve”) */}
+ <ToolbarPopover
+ width={228}
+ trigger={(open) => (
+ <button className="cv-tbtn" data-active={open || !!text.curve} aria-label="Curve text" title="Curve text">
+ <Spline size={14} />
+ </button>
+ )}
+ >
+ <div className="flex items-center justify-between mb-1.5">
+ <div className="text-[12px] font-bold text-white/90">Curved text</div>
+ <button className="text-[11px] text-white/60 hover:text-white" onClick={() => update(ids, { curve: 0 })}>Reset</button>
+ </div>
+ <SliderRow label="Curve" value={text.curve ?? 0} min={-180} max={180} step={5} onChange={(v) => updateLive(ids, { curve: v })} onCommit={() => update(ids, { curve: text.curve ?? 0 })} format={(v) => `${v}°`} />
+ <div className="flex justify-center pt-1.5">
+ <span className="text-[15px] text-white/85" style={{ fontFamily: text.fontFamily, color: text.fill }} aria-hidden="true">
+ {(text.curve ?? 0) >= 0 ? '◠' : '◡'} Curved preview
+ </span>
+ </div>
+ </ToolbarPopover>
+
{/* transparency */}
<ToolbarPopover
trigger={(open) => (
@@ -321,11 +345,196 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm
<Divider />
<PositionPopover ids={ids} count={1} element={first} />
</>
+ ) : table ? (
+ <>
+ <span className="text-[12px] font-semibold text-white/85 px-2 shrink-0 flex items-center gap-1.5">
+ <Table2 size={13} /> Table
+ </span>
+ <TableToolbar table={table} ids={ids} />
+ <Divider />
+ <PositionPopover ids={ids} count={1} element={first} />
+ </>
+ ) : frame ? (
+ <>
+ <span className="text-[12px] font-semibold text-white/85 px-2 shrink-0 flex items-center gap-1.5">
+ <SquareDashed size={13} /> Frame
+ </span>
+ <FrameToolbar frame={frame} ids={ids} />
+ <Divider />
+ <PositionPopover ids={ids} count={1} element={first} />
+ </>
+ ) : embed ? (
+ <>
+ <span className="text-[12px] font-semibold text-white/85 px-2 shrink-0 flex items-center gap-1.5 capitalize">
+ <ExternalLink size={13} /> {embed.kind} card
+ </span>
+ <EmbedToolbar embed={embed} ids={ids} />
+ <ToolbarPopover trigger={(open) => (
+ <button className="cv-tbtn" data-active={open} aria-label="Transparency" title="Transparency">
+ <Percent size={14} />
+ </button>
+ )}>
+ <SliderRow label="Transparency" value={Math.round(embed.opacity * 100)} min={0} max={100} step={1}
+ onChange={(v) => updateLive(ids, { opacity: v / 100 })}
+ onCommit={() => update(ids, { opacity: embed.opacity })}
+ format={(v) => `${100 - v}% transparent`} />
+ </ToolbarPopover>
+ <Divider />
+ <PositionPopover ids={ids} count={1} element={first} />
+ </>
) : null}
</div>
)
}
+// ── v0.6: table / frame / embed toolbars ──────────────────────
+
+function TableToolbar({ table, ids }: { table: TableElement; ids: string[] }) {
+ const update = useEditorStore((s) => s.updateElements)
+ const updateLive = useEditorStore((s) => s.updateElementsLive)
+
+ const addRow = () => {
+ const cells = [...table.cells]
+ for (let c = 0; c < table.cols; c += 1) cells.push({ text: '' })
+ update(ids, { rows: table.rows + 1, cells, height: Math.round((table.rows + 1) * (table.height / table.rows)) })
+ }
+ const addCol = () => {
+ const cells: typeof table.cells = []
+ for (let r = 0; r < table.rows; r += 1) {
+ for (let c = 0; c < table.cols; c += 1) {
+ cells.push(table.cells[r * table.cols + c] ?? { text: '' })
+ }
+ if (r === 0) cells.push({ text: '', bold: true, fill: table.headerFill })
+ else cells.push({ text: '' })
+ }
+ const colWidths = [...table.colWidths, Math.round(table.width / (table.cols + 1))]
+ update(ids, { cols: table.cols + 1, cells, colWidths, width: table.width + Math.round(table.width / (table.cols + 1)) })
+ }
+ const removeRow = () => {
+ if (table.rows <= 1) return
+ update(ids, { rows: table.rows - 1, cells: table.cells.slice(0, (table.rows - 1) * table.cols), height: Math.round((table.rows - 1) * (table.height / table.rows)) })
+ }
+ const removeCol = () => {
+ if (table.cols <= 1) return
+ const cells: typeof table.cells = []
+ for (let r = 0; r < table.rows; r += 1) {
+ for (let c = 0; c < table.cols - 1; c += 1) cells.push(table.cells[r * table.cols + c] ?? { text: '' })
+ }
+ update(ids, { cols: table.cols - 1, cells, colWidths: table.colWidths.slice(0, -1) })
+ }
+
+ return (
+ <>
+ <TBtn onClick={addRow} title="Add row" ariaLabel="Add row"><Rows3 size={15} /><Plus size={9} className="-ml-1.5 -mb-1.5" /></TBtn>
+ <TBtn onClick={removeRow} title="Remove row" ariaLabel="Remove row"><Rows3 size={15} /><Minus size={9} className="-ml-1.5 -mb-1.5" /></TBtn>
+ <TBtn onClick={addCol} title="Add column" ariaLabel="Add column"><Columns3 size={15} /><Plus size={9} className="-ml-1.5 -mb-1.5" /></TBtn>
+ <TBtn onClick={removeCol} title="Remove column" ariaLabel="Remove column"><Columns3 size={15} /><Minus size={9} className="-ml-1.5 -mb-1.5" /></TBtn>
+ <ToolbarPopover trigger={(open) => (
+ <button className="cv-tbtn gap-1 !px-2.5" data-active={open} aria-label="Table style" title="Table style">
+ <Palette size={14} /> <span className="text-[12px] hidden lg:inline">Style</span>
+ </button>
+ )}>
+ <div className="text-[12px] font-bold text-white/90 mb-2">Table style</div>
+ <div className="flex items-center gap-2 mb-2">
+ <span className="text-[11px] text-white/60">Border</span>
+ <ColorMenu value={table.borderColor} onChange={(c, committed) => committed ? update(ids, { borderColor: c }) : updateLive(ids, { borderColor: c })} title="Border colour" />
+ </div>
+ <div className="flex items-center gap-2 mb-2">
+ <span className="text-[11px] text-white/60">Header</span>
+ <ColorMenu value={table.headerFill} onChange={(c, committed) => committed ? update(ids, { headerFill: c }) : updateLive(ids, { headerFill: c })} title="Header fill" />
+ </div>
+ <SliderRow label="Border width" value={table.borderWidth} min={0} max={6} step={0.5} onChange={(v) => updateLive(ids, { borderWidth: v })} onCommit={() => update(ids, { borderWidth: table.borderWidth })} />
+ <SliderRow label="Text size" value={table.fontSize} min={8} max={40} step={1} onChange={(v) => updateLive(ids, { fontSize: v })} onCommit={() => update(ids, { fontSize: table.fontSize })} />
+ </ToolbarPopover>
+ </>
+ )
+}
+
+function FrameToolbar({ frame, ids }: { frame: FrameElement; ids: string[] }) {
+ const update = useEditorStore((s) => s.updateElements)
+
+ const onFill = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0]
+ if (!file) return
+ const reader = new FileReader()
+ reader.onload = () => {
+ const src = String(reader.result)
+ const img = new window.Image()
+ img.onload = () => update(ids, { src, naturalWidth: img.naturalWidth, naturalHeight: img.naturalHeight })
+ img.src = src
+ }
+ reader.readAsDataURL(file)
+ e.target.value = ''
+ }
+
+ return (
+ <>
+ <label className="cv-tbtn gap-1 !px-2.5 cursor-pointer" title="Fill frame with an image" aria-label="Fill frame with an image">
+ <Upload size={14} /> <span className="text-[12px] hidden lg:inline">Fill</span>
+ <input type="file" accept="image/*" className="hidden" onChange={onFill} />
+ </label>
+ <ToolbarPopover trigger={(open) => (
+ <button className="cv-tbtn gap-1 !px-2.5" data-active={open} aria-label="Frame shape" title="Frame shape">
+ <SquareDashed size={14} /> <span className="text-[12px] hidden lg:inline">Shape</span>
+ </button>
+ )}>
+ <div className="text-[12px] font-bold text-white/90 mb-2">Frame shape</div>
+ <div className="grid grid-cols-3 gap-1.5">
+ {FRAME_SHAPES.map((fs: FrameShape) => (
+ <button
+ key={fs}
+ onClick={() => update(ids, { frameShape: fs })}
+ className={cn(
+ 'h-9 rounded-lg text-[11px] font-medium capitalize border transition-colors',
+ frame.frameShape === fs ? 'bg-white/[0.16] border-white/30 text-white' : 'border-white/[0.09] text-white/75 hover:bg-white/[0.07]'
+ )}
+ aria-label={`Frame shape ${fs}`}
+ >
+ {fs}
+ </button>
+ ))}
+ </div>
+ {frame.frameShape === 'rect' && (
+ <div className="mt-2 border-t border-white/[0.08] pt-2">
+ <SliderRow label="Corner radius" value={frame.radius} min={0} max={Math.round(frame.width / 2)} step={1} onChange={(v) => useEditorStore.getState().updateElementsLive(ids, { radius: v })} onCommit={() => update(ids, { radius: frame.radius })} />
+ </div>
+ )}
+ </ToolbarPopover>
+ </>
+ )
+}
+
+function EmbedToolbar({ embed, ids }: { embed: EmbedElement; ids: string[] }) {
+ const update = useEditorStore((s) => s.updateElements)
+ const [editingUrl, setEditingUrl] = useState(embed.url)
+
+ return (
+ <>
+ <ToolbarPopover width={280} trigger={(open) => (
+ <button className="cv-tbtn gap-1 !px-2.5" data-active={open} aria-label="Edit link" title="Edit link">
+ <ExternalLink size={14} /> <span className="text-[12px] hidden lg:inline">Link</span>
+ </button>
+ )}>
+ <div className="text-[12px] font-bold text-white/90 mb-2">Embed link</div>
+ <input
+ value={editingUrl}
+ onChange={(e) => setEditingUrl(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && editingUrl.trim()) update(ids, { url: editingUrl.trim(), title: undefined })
+ }}
+ className="w-full h-8 rounded-lg bg-white/[0.06] border border-white/10 px-2.5 text-[12px] text-white outline-none focus:border-[#7630D7]"
+ aria-label="Embed URL"
+ />
+ <div className="flex gap-1.5 mt-2">
+ <button className="btn-cv h-8 px-3 text-[11px]" onClick={() => editingUrl.trim() && update(ids, { url: editingUrl.trim(), title: undefined })}>Apply</button>
+ <button className="h-8 px-3 text-[11px] rounded-lg border border-white/10 text-white/70 hover:bg-white/[0.07]" onClick={() => setEditingUrl(embed.url)}>Reset</button>
+ </div>
+ <p className="text-[10px] text-white/40 mt-2 leading-relaxed">Cards open their link in Preview &amp; shared views.</p>
+ </ToolbarPopover>
+ </>
+ )
+}
+
/** canva position popover: arrange 2×2 + align 6 + advanced W/H/X/Y/rotate */
function PositionPopover({ ids, count, element }: { ids: string[]; count: number; element?: AnyElement }) {
const store = useEditorStore()
diff --git a/src/components/editor/TranslateDialog.tsx b/src/components/editor/TranslateDialog.tsx
index 90aa8a1..9a10136 100644
--- a/src/components/editor/TranslateDialog.tsx
+++ b/src/components/editor/TranslateDialog.tsx
@@ -7,7 +7,7 @@ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } f
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { toast } from '@/hooks/use-toast'
-import type { AnyElement, TextElement } from '@/lib/types'
+import type { AnyElement, TableElement, TextElement } from '@/lib/types'
const LANGUAGES: { name: string; native: string; code: string }[] = [
{ name: 'Spanish', native: 'Español', code: 'es' },
@@ -45,6 +45,26 @@ function collectTexts(els: AnyElement[], out: TextElement[] = []): TextElement[]
return out
}
+/** v0.6: collect table cells with text (tables at top level + inside groups). */
+interface TableCellEntry {
+ id: string
+ index: number
+ text: string
+}
+function collectCellTexts(els: AnyElement[], out: TableCellEntry[] = []): TableCellEntry[] {
+ for (const el of els) {
+ if (el.type === 'table') {
+ const tb = el as TableElement
+ tb.cells.forEach((c, i) => {
+ if (c.text.trim()) out.push({ id: tb.id, index: i, text: c.text })
+ })
+ } else if (el.type === 'group') {
+ collectCellTexts(el.children, out)
+ }
+ }
+ return out
+}
+
/** Canva "Translate" — AI-translate every text element in the design. */
export function TranslateDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (v: boolean) => void }) {
const pages = useEditorStore((s) => s.pages)
@@ -53,27 +73,54 @@ export function TranslateDialog({ open, onOpenChange }: { open: boolean; onOpenC
const [busy, setBusy] = useState(false)
const texts = useMemo(() => collectTexts(pages.flatMap((p) => p.elements)), [pages])
+ const cellEntries = useMemo(() => collectCellTexts(pages.flatMap((p) => p.elements)), [pages])
const picked = LANGUAGES.find((l) => l.code === lang) ?? null
const run = async () => {
- if (!picked || !texts.length || busy) return
+ if (!picked || busy) return
+ if (!texts.length && !cellEntries.length) return
setBusy(true)
try {
+ const allTexts = [...texts.map((t) => t.text), ...cellEntries.map((c) => c.text)]
const res = await fetch('/api/ai/translate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
language: `${picked.name} (${picked.native})`,
- texts: texts.map((t) => t.text),
+ texts: allTexts,
}),
})
const data = (await res.json()) as { translations?: string[]; error?: string }
- if (!res.ok || !Array.isArray(data.translations) || data.translations.length !== texts.length) {
+ if (!res.ok || !Array.isArray(data.translations) || data.translations.length !== allTexts.length) {
toast({ title: 'Translate failed', description: data.error ?? 'Please try again.', variant: 'destructive' })
return
}
- translateTexts(texts.map((t, i) => ({ id: t.id, text: data.translations![i] })))
- toast({ title: `Translated to ${picked.native}`, description: `${texts.length} text${texts.length === 1 ? '' : 's'} updated. Ctrl+Z to undo.` })
+ const translations = data.translations
+ // v0.6: text elements ride the store action (undoable)…
+ if (texts.length) {
+ translateTexts(texts.map((t, i) => ({ id: t.id, text: translations[i] })))
+ }
+ // …and table cell texts apply as element patches
+ const cellsById = new Map<string, { index: number; text: string }[]>()
+ cellEntries.forEach((c, k) => {
+ const translated = translations[texts.length + k]
+ const list = cellsById.get(c.id) ?? []
+ list.push({ index: c.index, text: translated })
+ cellsById.set(c.id, list)
+ })
+ const updateElements = useEditorStore.getState().updateElements
+ const currentPageTables = pages.flatMap((p) => p.elements).filter((e) => e.type === 'table') as TableElement[]
+ for (const [id, list] of cellsById) {
+ const table = currentPageTables.find((t) => t.id === id)
+ if (!table) continue
+ const cells = table.cells.map((c, i) => {
+ const hit = list.find((l) => l.index === i)
+ return hit ? { ...c, text: hit.text } : c
+ })
+ updateElements([id], { cells })
+ }
+ const total = texts.length + cellEntries.length
+ toast({ title: `Translated to ${picked.native}`, description: `${total} text${total === 1 ? '' : 's'} updated. Ctrl+Z to undo.` })
onOpenChange(false)
} catch {
toast({ title: 'Translate is unavailable right now.', variant: 'destructive' })
@@ -90,8 +137,8 @@ export function TranslateDialog({ open, onOpenChange }: { open: boolean; onOpenC
<Languages size={17} className="text-[#02C0CC]" /> Translate design
</DialogTitle>
<DialogDescription className="text-white/60">
- {texts.length
- ? `Translate all ${texts.length} text${texts.length === 1 ? '' : 's'} across ${pages.length} page${pages.length === 1 ? '' : 's'} with AI. Your layout stays intact.`
+ {texts.length + cellEntries.length
+ ? `Translate all ${texts.length + cellEntries.length} text${texts.length + cellEntries.length === 1 ? '' : 's'} (incl. table cells) across ${pages.length} page${pages.length === 1 ? '' : 's'} with AI. Your layout stays intact.`
: 'This design has no text to translate yet.'}
</DialogDescription>
</DialogHeader>
@@ -130,7 +177,7 @@ export function TranslateDialog({ open, onOpenChange }: { open: boolean; onOpenC
</span>
<Button
className="btn-cv h-11 rounded-xl ml-auto px-5"
- disabled={!picked || !texts.length || busy}
+ disabled={!picked || (!texts.length && !cellEntries.length) || busy}
onClick={() => void run()}
>
{busy ? <Loader2 size={15} className="mr-1.5 animate-spin" /> : <Languages size={15} className="mr-1.5" />}
diff --git a/src/components/editor/add-element.ts b/src/components/editor/add-element.ts
index b281f7d..f50793a 100644
--- a/src/components/editor/add-element.ts
+++ b/src/components/editor/add-element.ts
@@ -6,7 +6,11 @@ import {
createShapeElement,
createStickerElement,
createLineElement,
+ createTableElement,
+ createFrameElement,
+ createEmbedElement,
type AnyElement,
+ type FrameShape,
} from '@/lib/types'
import { useEditorStore } from '@/store/editor-store'
import { GRAPHICS } from '@/lib/editor-utils'
@@ -81,6 +85,107 @@ export function addSticker(char: string) {
addCentered(createStickerElement(char, { width: 200, height: 200, fontSize: 150 }))
}
+// ── v0.6: tables, frames, embeds ───────────────────────────
+
+export type TableStyle = 'classic' | 'minimal' | 'bold' | 'soft'
+
+/** Add a native table — every cell stays editable on the canvas. */
+export function addTable(style: TableStyle = 'classic') {
+ const styles: Record<TableStyle, Partial<import('@/lib/types').TableElement> & { header?: string[] }> = {
+ classic: {
+ header: ['Header 1', 'Header 2', 'Header 3'],
+ rows: 4,
+ cols: 3,
+ headerFill: '#1F142E',
+ borderColor: '#E0E1E6',
+ fill: 'transparent',
+ textColor: '#1F2226',
+ },
+ minimal: {
+ header: ['Item', 'Qty', 'Price'],
+ rows: 4,
+ cols: 3,
+ headerFill: 'transparent',
+ headerTextColor: '#7630D7',
+ borderColor: '#EDEFF2',
+ borderWidth: 1,
+ fill: 'transparent',
+ textColor: '#1F2226',
+ },
+ bold: {
+ header: ['Plan', 'Features', 'Price'],
+ rows: 4,
+ cols: 3,
+ headerFill: '#7630D7',
+ borderColor: '#7630D7',
+ borderWidth: 2,
+ fill: '#F6F2FC',
+ textColor: '#1F142E',
+ },
+ soft: {
+ header: ['Task', 'Owner', 'Due'],
+ rows: 4,
+ cols: 3,
+ headerFill: '#02C0CC',
+ borderColor: '#C8EDF0',
+ borderWidth: 1.5,
+ fill: '#F2FBFC',
+ textColor: '#0E3A40',
+ },
+ }
+ const s = styles[style]
+ addCentered(createTableElement({ width: 480, rowHeight: 46, ...s }))
+}
+
+export function addFrame(frameShape: FrameShape) {
+ const size = 340
+ addCentered(
+ createFrameElement(frameShape, {
+ width: size,
+ height: frameShape === 'circle' || frameShape === 'ellipse' ? size : Math.round(size * 0.66),
+ })
+ )
+}
+
+/** Add an embed link card (YouTube / Maps / generic URL). */
+export function addEmbed(url: string, title?: string) {
+ const trimmed = url.trim()
+ if (!trimmed) return
+ const withProto = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`
+ addCentered(createEmbedElement(withProto, { width: 340, height: 214, ...(title ? { title } : {}) }))
+}
+
+/** If a page point lands inside a frame element, fill that frame with the image (canva drop-to-fill). */
+export function fillFrameAt(pageX: number, pageY: number, src: string, naturalWidth: number, naturalHeight: number): boolean {
+ const state = useEditorStore.getState()
+ const page = state.pages[state.currentPage]
+ const hit = [...page.elements]
+ .reverse()
+ .find(
+ (el) =>
+ el.type === 'frame' &&
+ el.visible &&
+ pageX >= el.x &&
+ pageX <= el.x + el.width &&
+ pageY >= el.y &&
+ pageY <= el.y + el.height
+ ) as import('@/lib/types').FrameElement | undefined
+ if (!hit) return false
+ state.updateElements([hit.id], { src, naturalWidth, naturalHeight })
+ return true
+}
+
+/** replace the image inside a selected frame (canva "Fill frame") */
+export function fillSelectedFrame(src: string, naturalWidth: number, naturalHeight: number): boolean {
+ const state = useEditorStore.getState()
+ const sel = state.pages[state.currentPage].elements.find(
+ (e) => state.selectedIds.includes(e.id) && e.type === 'frame'
+ )
+ if (!sel) return false
+ state.updateElements([sel.id], { src, naturalWidth, naturalHeight })
+ return true
+}
+
/**
* 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
diff --git a/src/components/editor/canvas/CanvasStage.tsx b/src/components/editor/canvas/CanvasStage.tsx
index ace9f36..4315294 100644
--- a/src/components/editor/canvas/CanvasStage.tsx
+++ b/src/components/editor/canvas/CanvasStage.tsx
@@ -15,6 +15,7 @@ import { CanvasContextMenu, type ContextMenuState } from './context-menu'
import { CollabOverlay } from './CollabOverlay'
import { CommentPins } from './CommentPins'
import { getActiveCollabSession } from '@/hooks/use-collab'
+import { tableGeometry } from '@/lib/v06-geometry'
/** canva-measured tokens */
const GUIDE_COLOR = '#9954FF' // rgb(153,84,255) — measured 2026-09-03
@@ -62,6 +63,8 @@ export default function CanvasStage() {
const [pan, setPan] = useState({ x: 0, y: 0 })
const [guides, setGuides] = useState<GuideLine[]>([])
const [editingTextId, setEditingTextId] = useState<string | null>(null)
+ /** v0.6: table cell being edited via the overlay ({ id, row, col }) */
+ const [editingCell, setEditingCell] = useState<{ id: string; row: number; col: number } | null>(null)
const [editValue, setEditValue] = useState('')
/** freehand draft: [x0,y0,x1,y1,…] in page coords */
const [draft, setDraft] = useState<number[] | null>(null)
@@ -247,11 +250,20 @@ export default function CanvasStage() {
}, [])
// ── text editing ───────────────────────────────────────────
- const startEditText = useCallback((id: string) => {
+ const startEditText = useCallback((id: string, cell?: { row: number; col: number }) => {
const state = useEditorStore.getState()
const p = currentPageData(state)
const el = p.elements.find((e) => e.id === id)
- if (!el || el.type !== 'text' || el.locked) return
+ if (!el || el.locked) return
+ if (cell && el.type === 'table') {
+ // v0.6: table cell editing
+ state.pushHistory()
+ setEditingCell({ id, row: cell.row, col: cell.col })
+ const tb = el as import('@/lib/types').TableElement
+ setEditValue(tb.cells[cell.row * tb.cols + cell.col]?.text ?? '')
+ return
+ }
+ if (el.type !== 'text') return
// if the text lives inside a group, edit via double-click is disabled for simplicity
state.pushHistory()
setEditingTextId(id)
@@ -259,9 +271,22 @@ export default function CanvasStage() {
}, [])
const commitEditText = useCallback(async () => {
+ const cellRef = editingCell
const id = editingTextId
- if (!id) return
const text = editValue
+ if (cellRef) {
+ const { id: tid, row, col } = cellRef
+ setEditingCell(null)
+ const state = useEditorStore.getState()
+ const p = currentPageData(state)
+ const el = p.elements.find((e) => e.id === tid) as import('@/lib/types').TableElement | undefined
+ if (el && el.type === 'table') {
+ const cells = el.cells.map((c, i) => (i === row * el.cols + col ? { ...c, text } : c))
+ state.updateElementsLive([tid], { cells })
+ }
+ return
+ }
+ if (!id) return
setEditingTextId(null)
useEditorStore.getState().updateElementsLive([id], { text })
// sync measured height after the Konva text re-renders
@@ -273,7 +298,7 @@ export default function CanvasStage() {
}
})
)
- }, [editingTextId, editValue])
+ }, [editingTextId, editingCell, editValue])
// ── v0.5: local cursor broadcast (throttled inside the session) ─
useEffect(() => {
@@ -610,6 +635,32 @@ export default function CanvasStage() {
const editingText = editingTextId ? (page.elements.find((e) => e.id === editingTextId) as TextElement | undefined) : undefined
+ // v0.6: table cell overlay geometry
+ const editingTable = editingCell ? (page.elements.find((e) => e.id === editingCell.id) as import('@/lib/types').TableElement | undefined) : undefined
+ const cellStyle: React.CSSProperties | null = editingTable && editingCell
+ ? (() => {
+ const geo = tableGeometry(editingTable)
+ const cell = editingTable.cells[editingCell.row * editingTable.cols + editingCell.col]
+ const isHeader = editingCell.row === 0
+ return {
+ left: pan.x + (editingTable.x + geo.colX[editingCell.col]) * zoom,
+ top: pan.y + (editingTable.y + editingCell.row * geo.rowH) * zoom,
+ width: Math.max(24, (geo.colW[editingCell.col] - 20) * zoom),
+ height: geo.rowH * zoom,
+ transform: `rotate(${editingTable.rotation}deg)`,
+ fontSize: editingTable.fontSize * zoom,
+ fontFamily: editingTable.fontFamily,
+ fontWeight: cell?.bold || isHeader ? 700 : 400,
+ color: isHeader ? (editingTable.headerTextColor ?? '#FFFFFF') : editingTable.textColor,
+ background: (cell?.fill ?? (isHeader ? editingTable.headerFill : editingTable.fill)) === 'transparent' ? 'rgba(255,255,255,0.06)' : (cell?.fill ?? (isHeader ? editingTable.headerFill : '#FFFFFF')),
+ textAlign: 'left' as const,
+ lineHeight: 1.2,
+ padding: '0 10px',
+ borderRadius: 4,
+ }
+ })()
+ : null
+
const textareaStyle: React.CSSProperties | null = editingText
? {
left: pan.x + editingText.x * zoom,
@@ -666,6 +717,7 @@ export default function CanvasStage() {
onDragEndNode={() => setGuides([])}
onDoubleClick={startEditText}
hiding={editingTextId === el.id}
+ hideCell={editingCell && editingCell.id === el.id ? { row: editingCell.row, col: editingCell.col } : null}
/>
))}
<Transformer
@@ -839,6 +891,37 @@ export default function CanvasStage() {
aria-label="Edit text"
/>
)}
+
+ {/* v0.6: table cell editing overlay */}
+ {editingTable && editingCell && cellStyle && (
+ <textarea
+ className="cv-textarea-overlay"
+ style={cellStyle}
+ value={editValue}
+ autoFocus
+ onChange={(e) => {
+ setEditValue(e.target.value)
+ // live-update the cell so the rest of the table reflects typing
+ const tb = editingTable
+ const { row, col } = editingCell
+ const cells = tb.cells.map((c, i) => (i === row * tb.cols + col ? { ...c, text: e.target.value } : c))
+ useEditorStore.getState().updateElementsLive([tb.id], { cells })
+ }}
+ onBlur={() => void commitEditText()}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape' || e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault()
+ void commitEditText()
+ }
+ e.stopPropagation()
+ }}
+ onFocus={(e) => {
+ const len = e.target.value.length
+ e.target.setSelectionRange(len, len)
+ }}
+ aria-label="Edit table cell"
+ />
+ )}
</div>
)
}
diff --git a/src/components/editor/canvas/element-node.tsx b/src/components/editor/canvas/element-node.tsx
index fb8822d..3c975b4 100644
--- a/src/components/editor/canvas/element-node.tsx
+++ b/src/components/editor/canvas/element-node.tsx
@@ -6,18 +6,22 @@ import { Ellipse, Group, Image as KonvaImage, Line, Path, Rect, Star, Text } fro
import type { KonvaEventObject } from 'konva/lib/Node'
import type {
AnyElement,
+ EmbedElement,
+ FrameElement,
GroupElement,
ImageElement,
LineElement,
ShapeElement,
StickerElement,
StrokeElement,
+ TableElement,
TextElement,
} from '@/lib/types'
import { isLine, withAlpha, type GradientFill } from '@/lib/types'
import { elementGradientProps } from '@/lib/editor-utils'
import { useEditorStore } from '@/store/editor-store'
import { useLoadedImage } from './use-loaded-image'
+import { CurvedTextNode, EmbedNode, FrameNode, TableNode, type TableCellRef } from './v06-nodes'
export interface ElementNodeProps {
element: AnyElement
@@ -31,8 +35,10 @@ export interface ElementNodeProps {
onDragMoveNode?: (id: string, node: Konva.Node) => void
/** called when a drag finishes (parent clears snapping guides) */
onDragEndNode?: (id: string) => void
- /** double-click / double-tap (text editing) */
- onDoubleClick?: (id: string) => void
+ /** double-click / double-tap (text editing; tables report the clicked cell) */
+ onDoubleClick?: (id: string, cell?: TableCellRef) => void
+ /** table cell currently edited via the overlay (its text is hidden underneath) */
+ hideCell?: TableCellRef | null
/** render nested (inside a group / preview) — page coords are baked by the parent */
nested?: boolean
}
@@ -120,7 +126,7 @@ function ImageNode({ el, common }: { el: ImageElement; common: Record<string, un
)
}
-export function ElementNode({ element: el, interactive, hiding, registerNode, onDragMoveNode, onDragEndNode, onDoubleClick, nested }: ElementNodeProps) {
+export function ElementNode({ element: el, interactive, hiding, hideCell, registerNode, onDragMoveNode, onDragEndNode, onDoubleClick, nested }: ElementNodeProps) {
const store = useEditorStore()
// ── shared interaction handlers ────────────────────────────
@@ -296,6 +302,13 @@ export function ElementNode({ element: el, interactive, hiding, registerNode, on
...shadowProps(el),
}
+ const { curve = 0 } = el as TextElement
+ if (el.type === 'text' && curve !== 0) {
+ // v0.6: curved text (single-line arc — effects fall back to plain fill)
+ const t = el as TextElement
+ return <CurvedTextNode t={t} common={common} />
+ }
+
switch (el.type) {
case 'text': {
const t = el as TextElement
@@ -446,6 +459,29 @@ export function ElementNode({ element: el, interactive, hiding, registerNode, on
return <ImageNode el={im} common={common} />
}
+ case 'table': {
+ const tb = el as TableElement
+ return (
+ <TableNode
+ el={tb}
+ common={common}
+ interactive={interactive}
+ onCellDoubleClick={(cell) => interactive && onDoubleClick?.(el.id, cell)}
+ hideCell={hideCell ?? null}
+ />
+ )
+ }
+
+ case 'frame': {
+ const fr = el as FrameElement
+ return <FrameNode el={fr} common={common} />
+ }
+
+ case 'embed': {
+ const em = el as EmbedElement
+ return <EmbedNode el={em} common={common} />
+ }
+
case 'sticker': {
const sk = el as StickerElement
return <Text {...common} text={sk.char} fontSize={sk.fontSize} fontFamily="'Segoe UI Emoji', 'Apple Color Emoji', 'Noto Color Emoji', sans-serif" width={sk.width} height={sk.height} align="center" />
diff --git a/src/components/editor/canvas/preview-stage.tsx b/src/components/editor/canvas/preview-stage.tsx
index c6ba8ac..48262e1 100644
--- a/src/components/editor/canvas/preview-stage.tsx
+++ b/src/components/editor/canvas/preview-stage.tsx
@@ -147,6 +147,24 @@ export default function PreviewStage({ page, designWidth, designHeight, animated
>
<PreviewElements elements={page.elements} />
</Layer>
+ {/* v0.6: embed cards are clickable in preview — open in a new tab */}
+ <Layer x={offsetX} y={offsetY} scale={{ x: scale, y: scale }}>
+ {page.elements
+ .filter((el): el is import('@/lib/types').EmbedElement => el.type === 'embed' && el.visible)
+ .map((el) => (
+ <Rect
+ key={el.id}
+ x={el.x}
+ y={el.y}
+ width={el.width}
+ height={el.height}
+ fill="transparent"
+ cursor="pointer"
+ onClick={() => window.open(el.url, '_blank', 'noopener,noreferrer')}
+ onTap={() => window.open(el.url, '_blank', 'noopener,noreferrer')}
+ />
+ ))}
+ </Layer>
</Stage>
)}
</div>
diff --git a/src/components/editor/canvas/v06-nodes.tsx b/src/components/editor/canvas/v06-nodes.tsx
new file mode 100644
index 0000000..99935a4
--- /dev/null
+++ b/src/components/editor/canvas/v06-nodes.tsx
@@ -0,0 +1,312 @@
+'use client'
+
+// ─────────────────────────────────────────────────────────────
+// v0.6 node renderers — curved text, tables, frames, embeds
+// ─────────────────────────────────────────────────────────────
+
+import Konva from 'konva'
+import { Ellipse, Group, Image as KonvaImage, Line, Path, Rect, Text, TextPath } from 'react-konva'
+import type { KonvaEventObject } from 'konva/lib/Node'
+import type { EmbedElement, FrameElement, TableElement, TextElement } from '@/lib/types'
+import { withAlpha } from '@/lib/types'
+import { arcForCurve, embedLayout, hexPoints, hostOf, tableGeometry, youtubeThumbUrl } from '@/lib/v06-geometry'
+import { useLoadedImage } from './use-loaded-image'
+
+// ── curved text ──────────────────────────────────────────────
+
+/** Curved text — rendered as a single Konva TextPath (no wrapping, canva-style). */
+export function CurvedTextNode({ t, common }: { t: TextElement; common: Record<string, unknown> }) {
+ const arc = arcForCurve(t.curve ?? 0, t.width)
+ const rendered = t.uppercase ? t.text.toUpperCase() : t.text
+ if (!arc) {
+ return (
+ <Text
+ {...common}
+ text={rendered}
+ 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}
+ width={t.width}
+ lineHeight={t.lineHeight}
+ letterSpacing={t.letterSpacing}
+ wrap="word"
+ perfectDrawEnabled={false}
+ />
+ )
+ }
+ return (
+ <TextPath
+ {...common}
+ data={arc.data}
+ text={rendered}
+ 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}
+ letterSpacing={t.letterSpacing}
+ perfectDrawEnabled={false}
+ />
+ )
+}
+
+// ── tables ───────────────────────────────────────────────────
+
+export interface TableCellRef {
+ row: number
+ col: number
+}
+
+export function TableNode({
+ el,
+ common,
+ interactive,
+ onCellDoubleClick,
+ hideCell,
+}: {
+ el: TableElement
+ common: Record<string, unknown>
+ interactive?: boolean
+ onCellDoubleClick?: (cell: TableCellRef) => void
+ /** the cell whose text is being edited via the overlay (hidden underneath) */
+ hideCell?: TableCellRef | null
+}) {
+ const { colX, colW, rowH } = tableGeometry(el)
+ const bw = el.borderWidth
+
+ const cellNodes = Array.from({ length: el.rows * el.cols }, (_, idx) => {
+ const r = Math.floor(idx / el.cols)
+ const c = idx % el.cols
+ const cell = el.cells[idx] ?? { text: '' }
+ const isHeader = r === 0
+ const cellFill = cell.fill ?? (isHeader ? el.headerFill : el.fill)
+ const hidingThis = hideCell && hideCell.row === r && hideCell.col === c
+ const startDbl = (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
+ if (!interactive) return
+ e.cancelBubble = true
+ onCellDoubleClick?.({ row: r, col: c })
+ }
+ return (
+ <Group key={`c${idx}`}>
+ <Rect
+ x={colX[c]}
+ y={r * rowH}
+ width={colW[c]}
+ height={rowH}
+ fill={cellFill === 'transparent' ? undefined : cellFill}
+ stroke={el.borderColor}
+ strokeWidth={bw}
+ onDblClick={startDbl}
+ onDblTap={startDbl}
+ />
+ <Text
+ x={colX[c] + 10}
+ y={r * rowH}
+ width={Math.max(8, colW[c] - 20)}
+ height={rowH}
+ text={cell.text}
+ fontSize={el.fontSize}
+ fontFamily={el.fontFamily}
+ fontStyle={cell.bold || isHeader ? 'bold' : 'normal'}
+ fill={isHeader ? (el.headerTextColor ?? '#FFFFFF') : el.textColor}
+ verticalAlign="middle"
+ align="left"
+ wrap="none"
+ ellipsis
+ visible={!hidingThis}
+ onDblClick={startDbl}
+ onDblTap={startDbl}
+ perfectDrawEnabled={false}
+ />
+ </Group>
+ )
+ })
+
+ return <Group {...common} clip={undefined}>{cellNodes}</Group>
+}
+
+// ── frames ───────────────────────────────────────────────────
+
+function roundedRectPath(ctx: Konva.Context, w: number, h: number, r: number) {
+ const rr = Math.min(r, w / 2, h / 2)
+ ctx.beginPath()
+ ctx.moveTo(rr, 0)
+ ctx.lineTo(w - rr, 0)
+ ctx.quadraticCurveTo(w, 0, w, rr)
+ ctx.lineTo(w, h - rr)
+ ctx.quadraticCurveTo(w, h, w - rr, h)
+ ctx.lineTo(rr, h)
+ ctx.quadraticCurveTo(0, h, 0, h - rr)
+ ctx.lineTo(0, rr)
+ ctx.quadraticCurveTo(0, 0, rr, 0)
+ ctx.closePath()
+}
+
+function polygonPath(ctx: Konva.Context, pts: [number, number][]) {
+ ctx.beginPath()
+ ctx.moveTo(pts[0][0], pts[0][1])
+ for (let i = 1; i < pts.length; i += 1) ctx.lineTo(pts[i][0], pts[i][1])
+ ctx.closePath()
+}
+
+/** clip function for a frame shape (used by the Konva group) */
+function frameClip(el: FrameElement) {
+ return (ctx: Konva.Context) => {
+ const { width: w, height: h } = el
+ switch (el.frameShape) {
+ case 'ellipse':
+ case 'circle': {
+ const rx = el.frameShape === 'circle' ? Math.min(w, h) / 2 : w / 2
+ const ry = el.frameShape === 'circle' ? Math.min(w, h) / 2 : h / 2
+ ctx.beginPath()
+ ctx.ellipse(w / 2, h / 2, rx, ry, 0, 0, Math.PI * 2, false)
+ ctx.closePath()
+ break
+ }
+ case 'triangle':
+ polygonPath(ctx, [[0, h], [w / 2, 0], [w, h]])
+ break
+ case 'hexagon':
+ polygonPath(ctx, hexPoints(w, h))
+ break
+ default:
+ roundedRectPath(ctx, w, h, el.radius)
+ }
+ }
+}
+
+/** placeholder outline shape for an empty frame */
+function framePlaceholder(el: FrameElement) {
+ const stroke = withAlpha('#FFFFFF', 0.85)
+ switch (el.frameShape) {
+ case 'ellipse':
+ case 'circle': {
+ const rx = el.frameShape === 'circle' ? Math.min(el.width, el.height) / 2 : el.width / 2
+ const ry = el.frameShape === 'circle' ? Math.min(el.width, el.height) / 2 : el.height / 2
+ return <Ellipse x={el.width / 2} y={el.height / 2} radiusX={rx} radiusY={ry} fill={withAlpha(el.fill, 0.16)} stroke={stroke} strokeWidth={2} dash={[8, 6]} />
+ }
+ case 'triangle':
+ return <Line points={[0, el.height, el.width / 2, 0, el.width, el.height]} closed fill={withAlpha(el.fill, 0.16)} stroke={stroke} strokeWidth={2} dash={[8, 6]} />
+ case 'hexagon': {
+ const pts = hexPoints(el.width, el.height)
+ return <Line points={pts.flat()} closed fill={withAlpha(el.fill, 0.16)} stroke={stroke} strokeWidth={2} dash={[8, 6]} />
+ }
+ default:
+ return <Rect width={el.width} height={el.height} cornerRadius={el.radius} fill={withAlpha(el.fill, 0.16)} stroke={stroke} strokeWidth={2} dash={[8, 6]} />
+ }
+}
+
+export function FrameNode({ el, common }: { el: FrameElement; common: Record<string, unknown> }) {
+ const image = useLoadedImage(el.src || undefined)
+
+ // cover-fit the image inside the frame box
+ let img: React.ReactNode = null
+ if (image && el.naturalWidth > 0 && el.naturalHeight > 0) {
+ const scale = Math.max(el.width / el.naturalWidth, el.height / el.naturalHeight)
+ const dw = el.naturalWidth * scale
+ const dh = el.naturalHeight * scale
+ const dx = (el.width - dw) / 2
+ const dy = (el.height - dh) / 2
+ img = <KonvaImage image={image} x={dx} y={dy} width={dw} height={dh} listening={false} />
+ }
+
+ return (
+ <Group {...common} clip={undefined} clipFunc={frameClip(el)}>
+ {img ?? framePlaceholder(el)}
+ </Group>
+ )
+}
+
+// ── embed cards ──────────────────────────────────────────────
+
+/** Embed card — a native vector link card (opens in the browser on click). */
+export function EmbedNode({ el, common }: { el: EmbedElement; common: Record<string, unknown> }) {
+ const w = el.width
+ const h = el.height
+ const thumbUrl = el.kind === 'youtube' ? youtubeThumbUrl(el.url) : null
+ const thumb = useLoadedImage(thumbUrl ?? undefined)
+
+ const { bandH, iconR } = embedLayout(w, h)
+ const cx = w / 2
+ const cy = bandH / 2
+
+ // icon glyphs (pure vector, export-safe)
+ let glyph: React.ReactNode = null
+ if (el.kind === 'youtube') {
+ glyph = (
+ <Group>
+ <Ellipse x={cx} y={cy} radiusX={iconR} radiusY={iconR} fill="rgba(255,255,255,0.92)" />
+ <Line points={[cx - iconR * 0.32, cy - iconR * 0.42, cx - iconR * 0.32, cy + iconR * 0.42, cx + iconR * 0.46, cy]} closed fill="#FF0033" />
+ </Group>
+ )
+ } else if (el.kind === 'map') {
+ glyph = (
+ <Group>
+ <Ellipse x={cx} y={cy} radiusX={iconR} radiusY={iconR} fill="rgba(255,255,255,0.95)" />
+ <Ellipse x={cx} y={cy - iconR * 0.12} radiusX={iconR * 0.34} radiusY={iconR * 0.46} fill="#34A853" />
+ <Line points={[cx - iconR * 0.24, cy + iconR * 0.1, cx, cy + iconR * 0.58, cx + iconR * 0.24, cy + iconR * 0.1]} closed fill="#34A853" />
+ </Group>
+ )
+ } else {
+ const s = iconR * 0.8
+ glyph = (
+ <Group>
+ <Ellipse x={cx} y={cy} radiusX={iconR} radiusY={iconR} fill="rgba(255,255,255,0.14)" stroke="rgba(255,255,255,0.9)" strokeWidth={2.5} />
+ <Path
+ data={`M ${cx - s * 0.4} ${cy + s * 0.4} L ${cx + s * 0.42} ${cy - s * 0.42} M ${cx - s * 0.05} ${cy - s * 0.42} L ${cx + s * 0.42} ${cy - s * 0.42} L ${cx + s * 0.42} ${cy + s * 0.05}`}
+ stroke="#FFFFFF"
+ strokeWidth={Math.max(2, iconR * 0.16)}
+ lineCap="round"
+ lineJoin="round"
+ />
+ </Group>
+ )
+ }
+
+ return (
+ <Group {...common} clip={undefined}>
+ <Rect width={w} height={h} cornerRadius={14} fill="#15171C" />
+ {/* media band */}
+ {thumb ? (
+ <KonvaImage image={thumb} y={0} width={w} height={bandH} crop={{ x: 45, y: 0, width: 270, height: 157 }} listening={false} />
+ ) : (
+ <Rect y={0} width={w} height={bandH} cornerRadius={[14, 14, 0, 0]} fill={withAlpha(el.tint, 0.28)} />
+ )}
+ {glyph}
+ {/* text block */}
+ <Text
+ x={14}
+ y={bandH + 10}
+ width={Math.max(8, w - 28)}
+ height={18}
+ text={hostOf(el.url).toUpperCase()}
+ fontSize={Math.max(9, Math.round(h * 0.055))}
+ fontFamily="Inter"
+ fill="rgba(255,255,255,0.55)"
+ letterSpacing={1.2}
+ wrap="none"
+ ellipsis
+ listening={false}
+ perfectDrawEnabled={false}
+ />
+ <Text
+ x={14}
+ y={bandH + 30}
+ width={Math.max(8, w - 28)}
+ height={Math.max(16, h - bandH - 40)}
+ text={el.title ?? el.url}
+ fontSize={Math.max(11, Math.round(h * 0.07))}
+ fontFamily="Inter"
+ fontStyle="600"
+ fill="#FFFFFF"
+ wrap="word"
+ ellipsis
+ listening={false}
+ perfectDrawEnabled={false}
+ />
+ </Group>
+ )
+}
diff --git a/src/components/editor/panels/ElementsPanel.tsx b/src/components/editor/panels/ElementsPanel.tsx
index ddb02a9..8be941f 100644
--- a/src/components/editor/panels/ElementsPanel.tsx
+++ b/src/components/editor/panels/ElementsPanel.tsx
@@ -1,11 +1,12 @@
'use client'
import { useMemo, useState } from 'react'
-import { Square, Circle, Triangle, Star, Minus, ArrowRight, MoveHorizontal, Search, Hexagon, Pentagon, Diamond, CircleDashed } from 'lucide-react'
+import { Square, Circle, Triangle, Star, Minus, ArrowRight, MoveHorizontal, Search, Hexagon, Pentagon, Diamond, CircleDashed, Frame, Youtube, MapPin, Link2 } from 'lucide-react'
import { GRAPHICS, STICKER_GROUPS } from '@/lib/editor-utils'
-import { addGraphic, addLine, addShape, addSticker } from '../add-element'
+import { addEmbed, addFrame, addGraphic, addLine, addShape, addSticker, addTable, type TableStyle } from '../add-element'
import { cn } from '@/lib/utils'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
+import { FRAME_SHAPES } from '@/lib/types'
function GraphicIcon({ path }: { path: string }) {
return (
@@ -37,6 +38,13 @@ const GRAPHIC_GROUPS: { name: string; ids: string[] }[] = [
{ name: 'Icons', ids: ['bolt', 'check-circle', 'arrow'] },
]
+const TABLE_STYLES: { id: TableStyle; label: string; swatch: React.CSSProperties }[] = [
+ { id: 'classic', label: 'Classic', swatch: { background: '#FFFFFF', border: '1px solid #E0E1E6' } },
+ { id: 'minimal', label: 'Minimal', swatch: { background: '#FFFFFF', borderTop: '2px solid #7630D7' } },
+ { id: 'bold', label: 'Bold', swatch: { background: '#F6F2FC', border: '2px solid #7630D7' } },
+ { id: 'soft', label: 'Soft', swatch: { background: '#F2FBFC', border: '1px solid #02C0CC' } },
+]
+
export function ElementsPanel() {
const [tab, setTab] = useState('shapes')
const [query, setQuery] = useState('')
@@ -71,6 +79,9 @@ export function ElementsPanel() {
<TabsTrigger value="lines" className="text-xs data-[state=active]:bg-[#7630D7] data-[state=active]:text-white">Lines</TabsTrigger>
<TabsTrigger value="graphics" className="text-xs data-[state=active]:bg-[#7630D7] data-[state=active]:text-white">Graphics</TabsTrigger>
<TabsTrigger value="stickers" className="text-xs data-[state=active]:bg-[#7630D7] data-[state=active]:text-white">Stickers</TabsTrigger>
+ <TabsTrigger value="tables" className="text-[11px] data-[state=active]:bg-[#7630D7] data-[state=active]:text-white">Tables</TabsTrigger>
+ <TabsTrigger value="frames" className="text-[11px] data-[state=active]:bg-[#7630D7] data-[state=active]:text-white">Frames</TabsTrigger>
+ <TabsTrigger value="embeds" className="text-[11px] data-[state=active]:bg-[#7630D7] data-[state=active]:text-white">Embeds</TabsTrigger>
</TabsList>
</div>
@@ -160,6 +171,54 @@ export function ElementsPanel() {
</div>
))}
</TabsContent>
+
+ {/* v0.6: native tables */}
+ <TabsContent value="tables" className="flex-1 overflow-y-auto cv-scroll-dark p-4 mt-0">
+ <p className="text-[11px] text-white/45 leading-relaxed mb-3">
+ Tables are native elements — click a cell on the canvas to edit it. Add or remove rows &amp; columns from the toolbar.
+ </p>
+ <SectionTitle>Styles</SectionTitle>
+ <div className="grid grid-cols-2 gap-2">
+ {TABLE_STYLES.map((t) => (
+ <button
+ key={t.id}
+ onClick={() => addTable(t.id)}
+ className="flex flex-col items-center gap-2 rounded-xl border border-white/10 bg-white/[0.03] p-3 h-[92px] hover:border-[#7630D7] hover:bg-[#7630D7]/10 transition-all"
+ aria-label={`Add ${t.label} table`}
+ >
+ <span className="w-14 h-10 rounded-md grid grid-cols-3 grid-rows-2 gap-px overflow-hidden" style={t.swatch} aria-hidden="true">
+ {Array.from({ length: 6 }, (_, i) => (
+ <span key={i} className={cn('bg-current opacity-10', i < 3 && 'opacity-40')} />
+ ))}
+ </span>
+ <span className="text-[11px] text-white/55">{t.label}</span>
+ </button>
+ ))}
+ </div>
+ </TabsContent>
+
+ {/* v0.6: frames (image-in-shape) */}
+ <TabsContent value="frames" className="flex-1 overflow-y-auto cv-scroll-dark p-4 mt-0">
+ <p className="text-[11px] text-white/45 leading-relaxed mb-3">
+ Drop an upload or photo onto a frame to fill it — the image is clipped to the shape.
+ </p>
+ <SectionTitle>Shapes</SectionTitle>
+ <div className="grid grid-cols-3 gap-2">
+ {FRAME_SHAPES.map((fs) => (
+ <ShapeTile key={fs} label={fs === 'rect' ? 'Rectangle' : fs === 'ellipse' ? 'Ellipse' : fs === 'triangle' ? 'Triangle' : fs === 'hexagon' ? 'Hexagon' : 'Circle'} onClick={() => addFrame(fs)}>
+ <FrameIconFor shape={fs} />
+ </ShapeTile>
+ ))}
+ </div>
+ </TabsContent>
+
+ {/* v0.6: embed link cards */}
+ <TabsContent value="embeds" className="flex-1 overflow-y-auto cv-scroll-dark p-4 mt-0">
+ <p className="text-[11px] text-white/45 leading-relaxed mb-3">
+ Embed cards open their link when clicked in Preview or shared views. Paste any URL — YouTube and Maps get a styled card.
+ </p>
+ <EmbedComposer />
+ </TabsContent>
</Tabs>
)
}
@@ -168,6 +227,75 @@ function SectionTitle({ children }: { children: React.ReactNode }) {
return <h4 className="text-[11px] font-bold text-white/45 uppercase tracking-wide mb-2.5">{children}</h4>
}
+function FrameIconFor({ shape }: { shape: string }) {
+ if (shape === 'ellipse') return <span className="h-6 w-6 rounded-full border-2 border-dashed border-white/80" aria-hidden="true" />
+ if (shape === 'circle') return <span className="h-6 w-6 rounded-full border-2 border-dashed border-[#7630D7]" aria-hidden="true" />
+ if (shape === 'triangle') return <span className="w-0 h-0 border-l-[14px] border-r-[14px] border-b-[24px] border-l-transparent border-r-transparent border-b-white/60" aria-hidden="true" />
+ if (shape === 'hexagon') return <Hexagon size={26} strokeWidth={1.8} className="text-white/80" />
+ return <Frame size={26} strokeWidth={1.8} className="text-white/80" />
+}
+
+function EmbedComposer() {
+ const [url, setUrl] = useState('')
+ return (
+ <div>
+ <SectionTitle>Add a link card</SectionTitle>
+ <div className="flex items-center gap-2 h-10 rounded-lg bg-white/[0.06] border border-white/10 px-3">
+ <Link2 size={14} className="text-white/40 shrink-0" />
+ <input
+ value={url}
+ onChange={(e) => setUrl(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && url.trim()) {
+ addEmbed(url)
+ setUrl('')
+ }
+ }}
+ className="bg-transparent outline-none text-[12px] text-white w-full placeholder:text-white/35"
+ placeholder="https://youtube.com/watch?v=…"
+ aria-label="Embed URL"
+ />
+ <button
+ className="btn-cv h-7 px-3 text-[11px] shrink-0"
+ onClick={() => {
+ if (url.trim()) {
+ addEmbed(url)
+ setUrl('')
+ }
+ }}
+ >
+ Add
+ </button>
+ </div>
+ <div className="grid grid-cols-2 gap-2 mt-4">
+ <QuickEmbed
+ icon={Youtube}
+ label="YouTube video"
+ placeholder="https://youtube.com/watch?v=dQw4w9WgXcQ"
+ />
+ <QuickEmbed
+ icon={MapPin}
+ label="Google Maps"
+ placeholder="https://maps.google.com/?q=Paris"
+ />
+ </div>
+ </div>
+ )
+}
+
+function QuickEmbed({ icon: Icon, label, placeholder }: { icon: typeof Youtube; label: string; placeholder: string }) {
+ return (
+ <button
+ onClick={() => addEmbed(placeholder)}
+ className="flex flex-col items-center justify-center gap-1.5 rounded-xl border border-white/10 bg-white/[0.03] p-3 h-[92px] hover:border-[#7630D7] hover:bg-[#7630D7]/10 transition-all"
+ aria-label={`Add ${label} embed`}
+ >
+ <Icon size={24} strokeWidth={1.6} className="text-white/80" />
+ <span className="text-[11px] text-white/55">{label}</span>
+ </button>
+ )
+}
+
function ShapeTile({ label, children, onClick }: { label: string; children: React.ReactNode; onClick: () => void }) {
return (
<button
diff --git a/src/components/editor/panels/LayersPanel.tsx b/src/components/editor/panels/LayersPanel.tsx
index 182b9b1..c30006d 100644
--- a/src/components/editor/panels/LayersPanel.tsx
+++ b/src/components/editor/panels/LayersPanel.tsx
@@ -1,7 +1,7 @@
'use client'
import { useState } from 'react'
-import { ChevronUp, ChevronDown, ChevronsUp, ChevronsDown, Lock, LockOpen, Eye, EyeOff, Trash2, Type, Image as ImageIcon, Square, Minus, Smile, PenTool, Group as GroupIcon } from 'lucide-react'
+import { ChevronUp, ChevronDown, ChevronsUp, ChevronsDown, Lock, LockOpen, Eye, EyeOff, Trash2, Type, Image as ImageIcon, Square, Minus, Smile, PenTool, Group as GroupIcon, Table2, Frame as FrameIcon, ExternalLink } from 'lucide-react'
import { useEditorStore, currentPageData } from '@/store/editor-store'
import { cn } from '@/lib/utils'
import type { AnyElement } from '@/lib/types'
@@ -15,6 +15,9 @@ function elementIcon(el: AnyElement) {
case 'sticker': return Smile
case 'path': return PenTool
case 'group': return GroupIcon
+ case 'table': return Table2
+ case 'frame': return FrameIcon
+ case 'embed': return ExternalLink
default: return Square
}
}
@@ -28,6 +31,9 @@ function elementLabel(el: AnyElement): string {
if (el.type === 'stroke') return 'Stroke'
if (el.type === 'path') return 'Graphic'
if (el.type === 'group') return 'Group'
+ if (el.type === 'table') return 'Table'
+ if (el.type === 'frame') return el.src ? 'Frame' : 'Empty frame'
+ if (el.type === 'embed') return 'Embed card'
return el.type.charAt(0).toUpperCase() + el.type.slice(1)
}
diff --git a/src/lib/mcp/server.ts b/src/lib/mcp/server.ts
new file mode 100644
index 0000000..87cb5cf
--- /dev/null
+++ b/src/lib/mcp/server.ts
@@ -0,0 +1,270 @@
+// ─────────────────────────────────────────────────────────────
+// Canvix MCP server — MCP 2025-03-26 "Streamable HTTP" transport
+// (stateless profile): every client message is an HTTP POST of a
+// JSON-RPC 2.0 request/notification/response; the server answers
+// requests with one application/json object, notifications with
+// 202 Accepted, and does not offer the optional SSE stream.
+// ─────────────────────────────────────────────────────────────
+
+import type { NextRequest } from 'next/server'
+import { buildTools, SERVER_VERSION, type ToolResult, type ToolDef } from './tools'
+import { rateLimit } from '@/lib/ai/provider'
+
+export const SUPPORTED_PROTOCOL_VERSIONS = ['2025-03-26', '2024-11-05', '2025-06-18']
+export const DEFAULT_PROTOCOL_VERSION = '2025-03-26'
+
+// ── JSON-RPC types ───────────────────────────────────────────
+
+export interface JsonRpcRequest {
+ jsonrpc?: '2.0'
+ id?: string | number | null
+ method?: string
+ params?: Record<string, unknown>
+ /** present only on client→server responses (resuming streams etc.) */
+ result?: unknown
+ error?: JsonRpcError
+}
+
+export interface JsonRpcError {
+ code: number
+ message: string
+ data?: unknown
+}
+
+export interface JsonRpcResponse {
+ jsonrpc: '2.0'
+ id: string | number | null
+ result?: unknown
+ error?: JsonRpcError
+}
+
+const PARSE_ERROR = -32700
+const INVALID_REQUEST = -32600
+const METHOD_NOT_FOUND = -32601
+const INVALID_PARAMS = -32602
+const INTERNAL_ERROR = -32603
+const SERVER_NOT_CONFIGURED = -32000
+const UNAUTHORIZED = -32001
+
+// ── auth ─────────────────────────────────────────────────────
+
+/** Timing-safe token comparison (both must be non-empty to match). */
+function tokenMatches(expected: string, provided: string): boolean {
+ if (!expected || !provided) return false
+ const a = Buffer.from(expected)
+ const b = Buffer.from(provided)
+ if (a.length !== b.length) {
+ // still burn a comparison to keep timing uniform
+ a.compare(Buffer.alloc(a.length))
+ return false
+ }
+ return a.compare(b) === 0
+}
+
+export function mcpTokenConfigured(): boolean {
+ return Boolean(process.env.CANVIX_MCP_TOKEN)
+}
+
+export function checkAuth(req: NextRequest): JsonRpcResponse | null {
+ const expected = process.env.CANVIX_MCP_TOKEN ?? ''
+ if (!expected) {
+ return {
+ jsonrpc: '2.0',
+ id: null,
+ error: {
+ code: SERVER_NOT_CONFIGURED,
+ message:
+ 'The Canvix MCP server is disabled: set CANVIX_MCP_TOKEN in the server environment to enable it. See README → "AI agents (MCP)".',
+ },
+ }
+ }
+ const header = req.headers.get('authorization') ?? ''
+ const bearer = header.replace(/^Bearer\s+/i, '').trim()
+ if (!tokenMatches(expected, bearer)) {
+ return {
+ jsonrpc: '2.0',
+ id: null,
+ error: { code: UNAUTHORIZED, message: 'Unauthorized — send "Authorization: Bearer <CANVIX_MCP_TOKEN>".' },
+ }
+ }
+ // spec security note: validate Origin when present (DNS-rebinding guard)
+ const origin = req.headers.get('origin')
+ if (origin) {
+ try {
+ const originHost = new URL(origin).host
+ const host = req.headers.get('x-forwarded-host') ?? req.headers.get('host') ?? ''
+ if (originHost && host && originHost !== host) {
+ return {
+ jsonrpc: '2.0',
+ id: null,
+ error: { code: INVALID_REQUEST, message: 'Cross-origin requests are not accepted by the MCP endpoint.' },
+ }
+ }
+ } catch {
+ return {
+ jsonrpc: '2.0',
+ id: null,
+ error: { code: INVALID_REQUEST, message: 'Invalid Origin header.' },
+ }
+ }
+ }
+ return null
+}
+
+// ── message classification ───────────────────────────────────
+
+function isNotification(msg: JsonRpcRequest): boolean {
+ return typeof msg.method === 'string' && msg.id === undefined
+}
+function isClientResponse(msg: JsonRpcRequest): boolean {
+ return msg.method === undefined && (msg.result !== undefined || msg.error !== undefined)
+}
+
+// ── protocol handlers ─────────────────────────────────────────
+
+function errorResponse(id: string | number | null, code: number, message: string, data?: unknown): JsonRpcResponse {
+ return { jsonrpc: '2.0', id, error: { code, message, ...(data !== undefined ? { data } : {}) } }
+}
+
+export function handleInitialize(msg: JsonRpcRequest): JsonRpcResponse {
+ const requested = typeof msg.params?.protocolVersion === 'string' ? (msg.params.protocolVersion as string) : ''
+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : DEFAULT_PROTOCOL_VERSION
+ return {
+ jsonrpc: '2.0',
+ id: msg.id ?? null,
+ result: {
+ protocolVersion,
+ capabilities: {
+ tools: { listChanged: false },
+ resources: {},
+ prompts: {},
+ logging: {},
+ },
+ serverInfo: {
+ name: 'canvix',
+ version: SERVER_VERSION,
+ title: 'Canvix — open-source design tool',
+ },
+ instructions:
+ 'Canvix is a self-hosted, open-source design tool. Every tool creates or edits REAL, editable designs: ' +
+ 'create/generate designs, add text/shapes/images/tables/embeds, restyle, animate, comment and export (svg/png/json). ' +
+ 'Start with get_capabilities, then list_templates / search_designs. Edits made here appear live to humans in the editor.',
+ },
+ }
+}
+
+function toolsList(tools: ToolDef[]): JsonRpcResponse {
+ return {
+ jsonrpc: '2.0',
+ id: null,
+ result: {
+ tools: tools.map((t) => ({
+ name: t.name,
+ description: t.description,
+ inputSchema: t.inputSchema,
+ })),
+ },
+ }
+}
+
+async function toolsCall(msg: JsonRpcRequest, tools: ToolDef[]): Promise<JsonRpcResponse> {
+ const id = msg.id ?? null
+ const name = typeof msg.params?.name === 'string' ? (msg.params.name as string) : ''
+ const args = (msg.params?.arguments && typeof msg.params.arguments === 'object' ? msg.params.arguments : {}) as Record<string, unknown>
+ const tool = tools.find((t) => t.name === name)
+ if (!tool) {
+ return errorResponse(id, INVALID_PARAMS, `Unknown tool "${name}". Call tools/list for the available tools.`)
+ }
+ try {
+ const result: ToolResult = await tool.handler(args)
+ return { jsonrpc: '2.0', id, result: { content: result.content, isError: result.isError ?? false } }
+ } catch (err) {
+ // never leak stack traces to the wire
+ const message = err instanceof Error ? `Tool execution failed: ${err.message.slice(0, 200)}` : 'Tool execution failed.'
+ return errorResponse(id, INTERNAL_ERROR, message)
+ }
+}
+
+// ── entry point ───────────────────────────────────────────────
+
+export interface McpOutcome {
+ status: number
+ body: JsonRpcResponse | JsonRpcResponse[] | null
+}
+
+/**
+ * Process an HTTP POST body (single message or batch).
+ * - notifications / client responses only → 202 Accepted, no body
+ * - requests → 200 with one JSON object, or an array for multi-request batches
+ */
+export async function handleMcpRequest(req: NextRequest): Promise<McpOutcome> {
+ const parsed: unknown = await req.json().catch(() => null)
+ if (parsed === null) {
+ return {
+ status: 400,
+ body: errorResponse(null, PARSE_ERROR, 'Invalid JSON body.'),
+ }
+ }
+
+ const messages: JsonRpcRequest[] = Array.isArray(parsed) ? (parsed as JsonRpcRequest[]) : [parsed as JsonRpcRequest]
+ if (!messages.length) {
+ return { status: 400, body: errorResponse(null, INVALID_REQUEST, 'Empty batch.') }
+ }
+ if (messages.length > 32) {
+ return { status: 400, body: errorResponse(null, INVALID_REQUEST, 'Batch too large (max 32 messages).') }
+ }
+
+ const responses: JsonRpcResponse[] = []
+ for (const msg of messages) {
+ if (!msg || typeof msg !== 'object' || typeof msg.method !== 'string') {
+ // malformed entry — respond as an error if it looks like a request, else drop
+ if (msg && typeof msg === 'object' && 'id' in (msg as object)) {
+ responses.push(errorResponse((msg as JsonRpcRequest).id ?? null, INVALID_REQUEST, 'Invalid JSON-RPC message.'))
+ }
+ continue
+ }
+
+ // notifications & client responses → accepted, nothing to answer
+ if (isNotification(msg) || isClientResponse(msg)) continue
+
+ switch (msg.method) {
+ case 'initialize':
+ responses.push(handleInitialize(msg))
+ break
+ case 'ping':
+ responses.push({ jsonrpc: '2.0', id: msg.id ?? null, result: {} })
+ break
+ case 'tools/list':
+ responses.push(toolsList(buildTools({ req })))
+ break
+ case 'tools/call':
+ responses.push(await toolsCall(msg, buildTools({ req })))
+ break
+ case 'resources/list':
+ responses.push({ jsonrpc: '2.0', id: msg.id ?? null, result: { resources: [] } })
+ break
+ case 'resources/templates/list':
+ responses.push({ jsonrpc: '2.0', id: msg.id ?? null, result: { resourceTemplates: [] } })
+ break
+ case 'prompts/list':
+ responses.push({ jsonrpc: '2.0', id: msg.id ?? null, result: { prompts: [] } })
+ break
+ case 'completion/complete':
+ responses.push({ jsonrpc: '2.0', id: msg.id ?? null, result: { completion: { values: [], total: 0, hasMore: false } } })
+ break
+ default:
+ responses.push(errorResponse(msg.id ?? null, METHOD_NOT_FOUND, `Method "${msg.method}" is not supported.`))
+ }
+ }
+
+ if (!responses.length) {
+ // only notifications / responses were sent
+ return { status: 202, body: null }
+ }
+ return { status: 200, body: responses.length === 1 ? responses[0] : responses }
+}
+
+/** Rate limit for the MCP endpoint (per IP, generous — agents batch). */
+export function mcpRateLimit(req: NextRequest): boolean {
+ return rateLimit('mcp', req, 120, 60).ok
+}
diff --git a/src/lib/mcp/tools.ts b/src/lib/mcp/tools.ts
new file mode 100644
index 0000000..1cd47d0
--- /dev/null
+++ b/src/lib/mcp/tools.ts
@@ -0,0 +1,1279 @@
+// ─────────────────────────────────────────────────────────────
+// Canvix MCP tools — every tool maps to a real subsystem
+// (Design/Template/Comment tables, element factories, the SVG
+// exporter, animations, the AI provider layer). No vaporware.
+// ─────────────────────────────────────────────────────────────
+
+import type { NextRequest } from 'next/server'
+import { db } from '@/lib/db'
+import { FONTS } from '@/lib/editor-utils'
+import { exportPageToSVG } from '@/lib/svg-export'
+import { magicAnimatePage, clearPageAnimations } from '@/lib/animations'
+import { hasProvider, getZAI, recordUsage, rateLimit } from '@/lib/ai/provider'
+import {
+ createTextElement,
+ createShapeElement,
+ createImageElement,
+ createTableElement,
+ createEmbedElement,
+ createPage,
+ type AnyElement,
+ type PageData,
+} from '@/lib/types'
+
+export const SERVER_VERSION = '0.6.0'
+
+// ── tool plumbing ────────────────────────────────────────────
+
+export interface McpContent {
+ type: 'text' | 'image'
+ text?: string
+ data?: string
+ mimeType?: string
+}
+
+export interface ToolResult {
+ content: McpContent[]
+ isError?: boolean
+}
+
+export interface ToolDef {
+ name: string
+ description: string
+ inputSchema: Record<string, unknown>
+ handler: (args: Record<string, unknown>) => Promise<ToolResult>
+}
+
+export function textResult(text: string, isError = false): ToolResult {
+ return { content: [{ type: 'text', text }], isError }
+}
+
+function ok(data: unknown): ToolResult {
+ return textResult(JSON.stringify(data, null, 2))
+}
+
+function fail(message: string): ToolResult {
+ return textResult(message, true)
+}
+
+// ── validation helpers ────────────────────────────────────────
+
+const HEX = /^#[0-9a-fA-F]{6}$/
+
+function asString(v: unknown, fallback = ''): string {
+ return typeof v === 'string' ? v : fallback
+}
+
+function asNumber(v: unknown, fallback: number): number {
+ const n = typeof v === 'number' ? v : Number(v)
+ return Number.isFinite(n) ? n : fallback
+}
+
+function asInt(v: unknown, fallback: number): number {
+ return Math.round(asNumber(v, fallback))
+}
+
+function clamp(n: number, min: number, max: number): number {
+ return Math.max(min, Math.min(max, n))
+}
+
+function asHex(v: unknown, fallback: string): string {
+ return typeof v === 'string' && HEX.test(v) ? v : fallback
+}
+
+function asBool(v: unknown, fallback = false): boolean {
+ return typeof v === 'boolean' ? v : fallback
+}
+
+function asEnum<T extends string>(v: unknown, allowed: readonly T[], fallback: T): T {
+ return typeof v === 'string' && (allowed as readonly string[]).includes(v) ? (v as T) : fallback
+}
+
+function isHttpsUrl(u: unknown): u is string {
+ if (typeof u !== 'string' || !/^https?:\/\//i.test(u)) return false
+ try {
+ const parsed = new URL(u)
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:'
+ } catch {
+ return false
+ }
+}
+
+// ── design access + persistence (with live collab propagation) ─
+
+const AGENT_ACTOR = 'agent:mcp'
+
+async function getDesign(designId: string) {
+ const design = await db.design.findUnique({ where: { id: designId } })
+ if (!design || design.deletedAt) return null
+ return design
+}
+
+async function saveDesign(designId: string, pages: PageData[]): Promise<void> {
+ await db.design.update({
+ where: { id: designId },
+ data: {
+ pages: pages as unknown as object,
+ updatedAt: new Date(),
+ },
+ })
+ // propagate to live collaborators — the same op the collab client replays
+ await db.designEvent
+ .create({
+ data: {
+ designId,
+ actorId: AGENT_ACTOR,
+ kind: 'pages:replace',
+ payload: { kind: 'pages:replace', pages } as object,
+ },
+ })
+ .catch(() => undefined)
+}
+
+function parsePages(design: { pages: unknown }): PageData[] {
+ const raw = Array.isArray(design.pages) ? design.pages : []
+ return raw as PageData[]
+}
+
+function editUrl(designId: string, origin: string): string {
+ return `${origin}/?design=${designId}`
+}
+
+function pageAt(pages: PageData[], index: number): PageData | null {
+ return index >= 0 && index < pages.length ? pages[index] : null
+}
+
+function summarizeElement(el: AnyElement) {
+ 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),
+ rotation: el.rotation,
+ locked: el.locked,
+ }
+ if (el.type === 'text') {
+ base.text = el.text.slice(0, 120)
+ base.fontSize = el.fontSize
+ base.fontFamily = el.fontFamily
+ base.fill = el.fill
+ base.curve = el.curve ?? 0
+ } else if (el.type === 'table') {
+ base.rows = el.rows
+ base.cols = el.cols
+ } else if (el.type === 'embed') {
+ base.url = el.url
+ base.kind = el.kind
+ } else if (el.type === 'frame') {
+ base.hasImage = Boolean(el.src)
+ }
+ return base
+}
+
+/** text content of a design — like canva's get-design-content */
+function pageTextContent(page: PageData): string[] {
+ const out: string[] = []
+ for (const el of page.elements) {
+ if (!el.visible) continue
+ if (el.type === 'text') out.push(el.text)
+ if (el.type === 'table') out.push(...el.cells.map((c) => c.text).filter((t) => t.trim()))
+ if (el.type === 'embed' && el.title) out.push(el.title)
+ if (el.type === 'group') {
+ for (const c of el.children) {
+ if (c.type === 'text' && c.visible) out.push(c.text)
+ }
+ }
+ }
+ return out.filter((t) => t.trim().length > 0)
+}
+
+// ── SSRF-guarded image fetch → dataURL ──────────────────────
+
+const PRIVATE_HOST =
+ /^(localhost|127\.|0\.|10\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|\[?::1\]?)/i
+
+async function fetchImageAsDataUrl(url: string): Promise<{ src: string; width: number; height: number }> {
+ if (!isHttpsUrl(url)) throw new Error('Only http(s) image URLs are allowed.')
+ const parsed = new URL(url)
+ if (PRIVATE_HOST.test(parsed.hostname)) throw new Error('Private/internal hosts are not allowed.')
+ const res = await fetch(url, {
+ signal: AbortSignal.timeout(10_000),
+ redirect: 'follow',
+ headers: { 'user-agent': 'Canvix-MCP/0.6 (image fetch)' },
+ })
+ if (!res.ok) throw new Error(`Fetch failed with HTTP ${res.status}.`)
+ const type = (res.headers.get('content-type') ?? '').split(';')[0].trim()
+ if (!/^image\/(png|jpeg|jpg|webp|gif)$/i.test(type)) {
+ throw new Error(`Unsupported content type "${type}" — expected an image.`)
+ }
+ const buf = Buffer.from(await res.arrayBuffer())
+ if (buf.byteLength > 8 * 1024 * 1024) throw new Error('Image exceeds the 8 MB cap.')
+ const src = `data:${type.replace('jpg', 'jpeg')};base64,${buf.toString('base64')}`
+ const { default: sharp } = await import('sharp')
+ const meta = await sharp(buf).metadata()
+ return { src, width: meta.width ?? 800, height: meta.height ?? 600 }
+}
+
+// ── origin resolution (for edit URLs) ─────────────────────────
+
+function originOf(req: NextRequest): string {
+ const proto = req.headers.get('x-forwarded-proto') ?? 'http'
+ const host = req.headers.get('x-forwarded-host') ?? req.headers.get('host') ?? 'localhost:3000'
+ return `${proto}://${host}`
+}
+
+// ═════════════════════════════════════════════════════════════
+// tool definitions
+// ═════════════════════════════════════════════════════════════
+
+export interface ToolDeps {
+ req: NextRequest
+}
+
+export function buildTools(deps: ToolDeps): ToolDef[] {
+ const origin = originOf(deps.req)
+
+ // ── discovery ─────────────────────────────────────────────
+
+ const listTemplates: ToolDef = {
+ name: 'list_templates',
+ description:
+ 'Browse Canvix starter templates. Returns id, name, category, dimensions and page count. Use a template_id with create_design to start a design from it.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ category: { type: 'string', enum: ['social', 'presentation', 'print', 'document', 'logo', 'thumbnail'], description: 'Filter by category (optional)' },
+ query: { type: 'string', description: 'Case-insensitive name filter (optional)' },
+ },
+ },
+ handler: async (args) => {
+ const category = asString(args.category, '')
+ const query = asString(args.query, '').toLowerCase()
+ const where: Record<string, unknown> = {}
+ if (category) where.category = category
+ const templates = await db.template.findMany({
+ where,
+ select: { id: true, slug: true, name: true, category: true, width: true, height: true, pages: true },
+ take: 60,
+ orderBy: { createdAt: 'asc' },
+ })
+ const filtered = query ? templates.filter((t) => t.name.toLowerCase().includes(query)) : templates
+ return ok({
+ count: filtered.length,
+ templates: filtered.map((t) => ({
+ id: t.id,
+ slug: t.slug,
+ name: t.name,
+ category: t.category,
+ width: t.width,
+ height: t.height,
+ pageCount: Array.isArray(t.pages) ? t.pages.length : 0,
+ })),
+ })
+ },
+ }
+
+ const searchDesigns: ToolDef = {
+ name: 'search_designs',
+ description: "Search the user's Canvix designs by name. Returns id, name, dimensions, updatedAt and the edit URL.",
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Case-insensitive name filter (optional — omit to list recent designs)' },
+ },
+ },
+ handler: async (args) => {
+ const query = asString(args.query, '').toLowerCase()
+ const designs = await db.design.findMany({
+ where: { deletedAt: null },
+ select: { id: true, name: true, width: true, height: true, updatedAt: true, pages: true },
+ take: 40,
+ orderBy: { updatedAt: 'desc' },
+ })
+ const filtered = query ? designs.filter((d) => d.name.toLowerCase().includes(query)) : designs
+ return ok({
+ count: filtered.length,
+ designs: filtered.map((d) => ({
+ id: d.id,
+ name: d.name,
+ width: d.width,
+ height: d.height,
+ pageCount: Array.isArray(d.pages) ? d.pages.length : 0,
+ updatedAt: d.updatedAt.toISOString(),
+ editUrl: editUrl(d.id, origin),
+ })),
+ })
+ },
+ }
+
+ const getDesignTool: ToolDef = {
+ name: 'get_design',
+ description:
+ 'Get design metadata: name, dimensions, page count, per-page element summaries, edit URL and text content outline. For the full document JSON use export_design with format "json".',
+ inputSchema: {
+ type: 'object',
+ properties: { design_id: { type: 'string', description: 'Design id (from search_designs / create_design)' } },
+ required: ['design_id'],
+ },
+ handler: async (args) => {
+ const id = asString(args.design_id)
+ const design = await getDesign(id)
+ if (!design) return fail(`Design "${id}" was not found.`)
+ const pages = parsePages(design)
+ return ok({
+ id: design.id,
+ name: design.name,
+ width: design.width,
+ height: design.height,
+ pageCount: pages.length,
+ updatedAt: design.updatedAt.toISOString(),
+ editUrl: editUrl(design.id, origin),
+ pages: pages.map((p, i) => ({
+ index: i,
+ id: p.id,
+ background: p.background,
+ elementCount: p.elements.length,
+ elements: p.elements.map(summarizeElement),
+ textContent: pageTextContent(p).slice(0, 30),
+ })),
+ })
+ },
+ }
+
+ const getDesignContent: ToolDef = {
+ name: 'get_design_content',
+ description: 'Read the text content of a design (per page). Use this when you only need the copy, not the structure.',
+ inputSchema: {
+ type: 'object',
+ properties: { design_id: { type: 'string' } },
+ required: ['design_id'],
+ },
+ handler: async (args) => {
+ const design = await getDesign(asString(args.design_id))
+ if (!design) return fail('Design not found.')
+ const pages = parsePages(design)
+ return ok({
+ name: design.name,
+ pages: pages.map((p, i) => ({ index: i, lines: pageTextContent(p) })),
+ })
+ },
+ }
+
+ // ── create ────────────────────────────────────────────────
+
+ const createDesign: ToolDef = {
+ name: 'create_design',
+ description:
+ 'Create a new, fully editable Canvix design — blank (set width/height) or from a template (pass template_id from list_templates). Returns the design id + edit URL. This does NOT use AI; for AI generation see generate_design.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ name: { type: 'string', description: 'Design name (default "Agent design")' },
+ width: { type: 'number', minimum: 40, maximum: 8000, description: 'Page width in px (default 1080)' },
+ height: { type: 'number', minimum: 40, maximum: 8000, description: 'Page height in px (default 1080)' },
+ template_id: { type: 'string', description: 'Start from this template (from list_templates)' },
+ },
+ },
+ handler: async (args) => {
+ const name = asString(args.name, 'Agent design').slice(0, 80) || 'Agent design'
+ const templateRef = asString(args.template_id, '')
+ if (templateRef) {
+ // accept a template id OR a slug (both are returned by list_templates)
+ const template = (await db.template.findUnique({ where: { id: templateRef } }))
+ ?? (await db.template.findUnique({ where: { slug: templateRef } }))
+ if (!template) return fail(`Template "${templateRef}" was not found. Call list_templates for valid ids.`)
+ const pages = (Array.isArray(template.pages) ? template.pages : []) as unknown as PageData[]
+ const design = await db.design.create({
+ data: {
+ name,
+ width: template.width,
+ height: template.height,
+ pages: (pages.length ? pages : [createPage()]) as object,
+ source: `template:${template.slug}`,
+ },
+ })
+ return ok({ design_id: design.id, name, width: design.width, height: design.height, fromTemplate: template.slug, editUrl: editUrl(design.id, origin) })
+ }
+ const width = clamp(asInt(args.width, 1080), 40, 8000)
+ const height = clamp(asInt(args.height, 1080), 40, 8000)
+ const design = await db.design.create({
+ data: { name, width, height, pages: [createPage()] as unknown as object, source: 'mcp' },
+ })
+ return ok({ design_id: design.id, name, width, height, pageCount: 1, editUrl: editUrl(design.id, origin) })
+ },
+ }
+
+ const generateDesign: ToolDef = {
+ name: 'generate_design',
+ description:
+ 'Generate a complete, editable design from a text description using the server AI provider (layouts, colors, typography as real Canvix elements — not a flat image). Requires an AI provider on the server; without one, use create_design with a template instead. Provide a detailed brief: purpose, headline, sub copy, palette, page size.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'What to design — be specific (headline text, tone, palette, purpose)' },
+ width: { type: 'number', minimum: 200, maximum: 8000 },
+ height: { type: 'number', minimum: 200, maximum: 8000 },
+ name: { type: 'string', description: 'Design name (optional)' },
+ },
+ required: ['query'],
+ },
+ handler: async (args) => {
+ const query = asString(args.query).slice(0, 2000)
+ if (query.length < 4) return fail('Provide a design brief ("query"), e.g. "Instagram post for a coffee shop launch — warm palette".')
+ const zai = await getZAI()
+ if (!zai) {
+ await recordUsage('assistant', 'local', false).catch(() => undefined)
+ return fail(
+ 'generate_design requires an AI provider configured on the server (set ZAI_API_KEY or a .z-ai-config file). ' +
+ 'Without a provider you can still create designs from templates: list_templates → create_design → add_text/add_shape.'
+ )
+ }
+ const rl = rateLimit('mcp-generate', deps.req, 6, 60)
+ if (!rl.ok) return fail('Rate limit reached — try again in a minute.')
+
+ const width = clamp(asInt(args.width, 1080), 200, 8000)
+ const height = clamp(asInt(args.height, 1080), 200, 8000)
+ const fontList = FONTS.slice(0, 24)
+ .map((f) => (typeof f === "string" ? f : f.family))
+ .join(', ')
+
+ const system = [
+ 'You generate structured designs for the Canvix editor. Reply with ONLY a JSON object (no markdown fences) of shape:',
+ '{"name":string,"pages":[{"background":{"type":"solid","color":"#RRGGBB"}|{"type":"gradient","from":"#RRGGBB","to":"#RRGGBB","angle":number},',
+ '"elements":[ ... ]}]}',
+ `Element types (all coordinates in px on a ${width}x${height} page):`,
+ `{"type":"text","text":string,"x":n,"y":n,"width":n,"fontSize":n,"fontFamily":one of [${fontList}],"bold":bool,"fill":"#RRGGBB","align":"left|center|right","curve":optional number -180..180}`,
+ '{"type":"rect","x":n,"y":n,"width":n,"height":n,"fill":"#RRGGBB","cornerRadius":n}',
+ '{"type":"ellipse","x":n,"y":n,"width":n,"height":n,"fill":"#RRGGBB"}',
+ '{"type":"table","x":n,"y":n,"width":n,"header":["col a","col b"],"rows":n,"cells":[{"text":string}]}',
+ 'Rules: max 1 page, max 25 elements, keep 60px margins, hex colors only, text must fit its width (estimate ~0.6*fontSize px per char), make it look professionally designed (clear hierarchy, contrast, alignment).',
+ ].join('\n')
+
+ try {
+ const raw = await completeGeneration(zai, system, `Design brief: ${query}\nPage size: ${width}x${height}px`)
+ if (!raw) return fail('The AI reply was not parseable JSON after one retry. Try rephrasing the brief.')
+ const parsed = raw as Record<string, unknown>
+ const spec = normalizeGeneratedDesign(parsed, width, height)
+ const name = (asString(args.name, '') || asString(parsed.name, 'Generated design')).slice(0, 80) || 'Generated design'
+ const design = await db.design.create({
+ data: { name, width: spec.width, height: spec.height, pages: spec.pages as unknown as object, source: 'ai:mcp' },
+ })
+ await recordUsage('assistant', 'zai', true)
+ return ok({
+ design_id: design.id,
+ name,
+ width: spec.width,
+ height: spec.height,
+ pageCount: spec.pages.length,
+ elementCount: spec.pages[0]?.elements.length ?? 0,
+ editUrl: editUrl(design.id, origin),
+ note: 'Fully editable native elements — open the edit URL to tweak anything.',
+ })
+ } catch (err) {
+ await recordUsage('assistant', 'zai', false).catch(() => undefined)
+ return fail(`Generation failed: ${err instanceof Error ? err.message.slice(0, 200) : 'unknown error'}`)
+ }
+ },
+ }
+
+ // ── element mutations ─────────────────────────────────────
+
+ /** shared mutation wrapper: loads design, applies fn to pages, saves, emits collab event */
+ async function mutateDesign(
+ designId: string,
+ fn: (pages: PageData[], width: number, height: number) => { pages: PageData[]; summary: Record<string, unknown> } | null
+ ): Promise<ToolResult> {
+ const design = await getDesign(designId)
+ if (!design) return fail(`Design "${designId}" was not found.`)
+ const pages = parsePages(design)
+ if (!pages.length) return fail('This design has no pages yet — call it once via the editor (or create_design from a template) so a page exists.')
+ const result = fn(pages, design.width, design.height)
+ if (!result) return fail('Nothing to change — check your arguments (page index, element id…).')
+ await saveDesign(designId, result.pages)
+ return ok({ ok: true, design_id: designId, ...result.summary })
+ }
+
+ const addText: ToolDef = {
+ name: 'add_text',
+ description: 'Add a text element to a design page. Font, size, color, bold, alignment, position and curvature are optional. The element is a real editable text box.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ design_id: { type: 'string' },
+ page: { type: 'number', minimum: 0, description: '0-based page index (default 0)' },
+ text: { type: 'string', description: 'Text content (max 400 chars)' },
+ x: { type: 'number' },
+ y: { type: 'number' },
+ width: { type: 'number', description: 'Text box width (default: page width minus margins)' },
+ fontSize: { type: 'number', minimum: 6, maximum: 400 },
+ fontFamily: { type: 'string', description: 'One of the fonts from list_fonts' },
+ color: { type: 'string', description: 'Hex #RRGGBB' },
+ bold: { type: 'boolean' },
+ align: { type: 'string', enum: ['left', 'center', 'right'] },
+ curve: { type: 'number', minimum: -180, maximum: 180, description: 'Curved text arc in degrees (optional)' },
+ },
+ required: ['design_id', 'text'],
+ },
+ handler: async (args) => {
+ const designId = asString(args.design_id)
+ const text = asString(args.text).slice(0, 400)
+ if (!text.trim()) return fail('text must not be empty.')
+ const fontName = asString(args.fontFamily, '')
+ const font = FONTS.some((f) => (typeof f === "string" ? f : f.family) === fontName) ? fontName : 'Poppins'
+ return mutateDesign(designId, (pages, w, h) => {
+ const pageIndex = clamp(asInt(args.page, 0), 0, pages.length - 1)
+ const page = pageAt(pages, pageIndex)
+ if (!page) return null
+ const el = createTextElement({
+ text,
+ x: clamp(asNumber(args.x, 60), -w, w),
+ y: clamp(asNumber(args.y, h * 0.4), -h, h),
+ width: clamp(asNumber(args.width, w - 120), 40, w * 1.5),
+ fontSize: clamp(asInt(args.fontSize, 48), 6, 400),
+ fontFamily: font,
+ bold: asBool(args.bold, false),
+ fill: asHex(args.color, '#1F2226'),
+ align: asEnum(args.align, ['left', 'center', 'right'] as const, 'center'),
+ ...(typeof args.curve === 'number' && Math.abs(args.curve) > 1 ? { curve: clamp(asInt(args.curve, 0), -180, 180) } : {}),
+ })
+ const next = pages.map((p, i) => (i === pageIndex ? { ...p, elements: [...p.elements, el] } : p))
+ return { pages: next, summary: { added: 'text', element_id: el.id, page: pageIndex } }
+ })
+ },
+ }
+
+ const addShape: ToolDef = {
+ name: 'add_shape',
+ description: 'Add a native shape (rect / ellipse / triangle / star / line) to a design page.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ design_id: { type: 'string' },
+ page: { type: 'number', minimum: 0 },
+ shape: { type: 'string', enum: ['rect', 'ellipse', 'triangle', 'star', 'line'] },
+ x: { type: 'number' },
+ y: { type: 'number' },
+ width: { type: 'number' },
+ height: { type: 'number' },
+ fill: { type: 'string', description: 'Hex #RRGGBB' },
+ stroke: { type: 'string', description: 'Hex border color (shapes) or line color' },
+ strokeWidth: { type: 'number', minimum: 0, maximum: 60 },
+ cornerRadius: { type: 'number', minimum: 0, maximum: 400, description: 'rect only' },
+ },
+ required: ['design_id', 'shape'],
+ },
+ handler: async (args) => {
+ const designId = asString(args.design_id)
+ const shape = asEnum(args.shape, ['rect', 'ellipse', 'triangle', 'star', 'line'] as const, 'rect')
+ return mutateDesign(designId, (pages, w, h) => {
+ const pageIndex = clamp(asInt(args.page, 0), 0, pages.length - 1)
+ const page = pageAt(pages, pageIndex)
+ if (!page) return null
+ let el: AnyElement
+ if (shape === 'line') {
+ const seed = createShapeElement('rect', {})
+ el = {
+ id: seed.id,
+ type: 'line',
+ x: clamp(asNumber(args.x, 100), -w, w),
+ y: clamp(asNumber(args.y, h / 2), -h, h),
+ width: clamp(asNumber(args.width, 320), 12, w * 2),
+ height: 0,
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ visible: true,
+ shadow: { enabled: false, color: '#000000', blur: 12, offsetX: 0, offsetY: 6 },
+ stroke: asHex(args.stroke, '#1F2226'),
+ strokeWidth: clamp(asNumber(args.strokeWidth, 6), 1, 60),
+ dashed: false,
+ arrowStart: false,
+ arrowEnd: false,
+ }
+ } else {
+ el = createShapeElement(shape, {
+ x: clamp(asNumber(args.x, w * 0.25), -w, w),
+ y: clamp(asNumber(args.y, h * 0.25), -h, h),
+ width: clamp(asNumber(args.width, Math.min(400, w * 0.4)), 8, w * 2),
+ height: clamp(asNumber(args.height, Math.min(400, h * 0.3)), 8, h * 2),
+ fill: asHex(args.fill, '#00C4CC'),
+ stroke: asHex(args.stroke, 'transparent'),
+ strokeWidth: clamp(asNumber(args.strokeWidth, 0), 0, 60),
+ ...(shape === 'rect' ? { cornerRadius: clamp(asNumber(args.cornerRadius, 0), 0, 400) } : {}),
+ })
+ }
+ const next = pages.map((p, i) => (i === pageIndex ? { ...p, elements: [...p.elements, el] } : p))
+ return { pages: next, summary: { added: shape, element_id: el.id, page: pageIndex } }
+ })
+ },
+ }
+
+ const addImage: ToolDef = {
+ name: 'add_image',
+ description:
+ 'Add an image to a design from a public https URL. The image is fetched server-side (private hosts and files > 8 MB are rejected) and embedded as a data URL so it renders reliably in the editor.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ design_id: { type: 'string' },
+ page: { type: 'number', minimum: 0 },
+ url: { type: 'string', description: 'Public https image URL' },
+ x: { type: 'number' },
+ y: { type: 'number' },
+ width: { type: 'number', description: 'Display width (default: fitted to page)' },
+ height: { type: 'number', description: 'Display height (default: keeps aspect)' },
+ },
+ required: ['design_id', 'url'],
+ },
+ handler: async (args) => {
+ const designId = asString(args.design_id)
+ const url = asString(args.url)
+ let fetched: { src: string; width: number; height: number }
+ try {
+ fetched = await fetchImageAsDataUrl(url)
+ } catch (err) {
+ return fail(err instanceof Error ? err.message : 'Image fetch failed.')
+ }
+ return mutateDesign(designId, (pages, w, h) => {
+ const pageIndex = clamp(asInt(args.page, 0), 0, pages.length - 1)
+ const page = pageAt(pages, pageIndex)
+ if (!page) return null
+ const dispW = asNumber(args.width, Math.round(w * 0.6))
+ const dispH = asNumber(args.height, Math.round(dispW * (fetched.height / Math.max(1, fetched.width))))
+ const el = createImageElement(fetched.src, fetched.width, fetched.height, {
+ x: clamp(asNumber(args.x, (w - dispW) / 2), -w, w),
+ y: clamp(asNumber(args.y, (h - dispH) / 2), -h, h),
+ width: clamp(dispW, 8, w * 2),
+ height: clamp(dispH, 8, h * 2),
+ })
+ const next = pages.map((p, i) => (i === pageIndex ? { ...p, elements: [...p.elements, el] } : p))
+ return { pages: next, summary: { added: 'image', element_id: el.id, page: pageIndex, naturalWidth: fetched.width, naturalHeight: fetched.height } }
+ })
+ },
+ }
+
+ const addTable: ToolDef = {
+ name: 'add_table',
+ description: 'Add a native table element (editable cells) to a design page.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ design_id: { type: 'string' },
+ page: { type: 'number', minimum: 0 },
+ x: { type: 'number' },
+ y: { type: 'number' },
+ width: { type: 'number' },
+ header: { type: 'array', items: { type: 'string' }, description: 'Header cell labels (column count follows this)' },
+ rows: { type: 'number', minimum: 1, maximum: 20, description: 'Total rows including header (default 4)' },
+ },
+ required: ['design_id'],
+ },
+ handler: async (args) => {
+ const designId = asString(args.design_id)
+ const header = Array.isArray(args.header) ? args.header.map((h) => asString(h).slice(0, 60)).slice(0, 8) : undefined
+ return mutateDesign(designId, (pages, w, h) => {
+ const pageIndex = clamp(asInt(args.page, 0), 0, pages.length - 1)
+ const page = pageAt(pages, pageIndex)
+ if (!page) return null
+ const cols = header?.length ?? 3
+ const rows = clamp(asInt(args.rows, 4), 1, 20)
+ const tableWidth = clamp(asNumber(args.width, Math.min(560, w * 0.7)), 120, w)
+ const el = createTableElement({
+ x: clamp(asNumber(args.x, (w - tableWidth) / 2), -w, w),
+ y: clamp(asNumber(args.y, h * 0.3), -h, h),
+ width: tableWidth,
+ rows,
+ cols,
+ rowHeight: 44,
+ ...(header ? { header } : {}),
+ })
+ const next = pages.map((p, i) => (i === pageIndex ? { ...p, elements: [...p.elements, el] } : p))
+ return { pages: next, summary: { added: 'table', element_id: el.id, page: pageIndex, rows, cols } }
+ })
+ },
+ }
+
+ const addEmbed: ToolDef = {
+ name: 'add_embed',
+ description: 'Add an embed link card (YouTube / Google Maps / generic link) to a design page. The card is native vector content that opens the URL in previews and shared views.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ design_id: { type: 'string' },
+ page: { type: 'number', minimum: 0 },
+ url: { type: 'string', description: 'https URL (YouTube/Maps get styled cards)' },
+ title: { type: 'string', description: 'Card title (optional)' },
+ x: { type: 'number' },
+ y: { type: 'number' },
+ },
+ required: ['design_id', 'url'],
+ },
+ handler: async (args) => {
+ const designId = asString(args.design_id)
+ const url = asString(args.url)
+ if (!isHttpsUrl(url)) return fail('url must be a valid http(s) URL.')
+ return mutateDesign(designId, (pages, w, h) => {
+ const pageIndex = clamp(asInt(args.page, 0), 0, pages.length - 1)
+ const page = pageAt(pages, pageIndex)
+ if (!page) return null
+ const el = createEmbedElement(url, {
+ x: clamp(asNumber(args.x, (w - 340) / 2), -w, w),
+ y: clamp(asNumber(args.y, h * 0.3), -h, h),
+ width: 340,
+ height: 214,
+ ...(asString(args.title, '') ? { title: asString(args.title).slice(0, 80) } : {}),
+ })
+ const next = pages.map((p, i) => (i === pageIndex ? { ...p, elements: [...p.elements, el] } : p))
+ return { pages: next, summary: { added: 'embed', element_id: el.id, kind: el.kind, page: pageIndex } }
+ })
+ },
+ }
+
+ const setBackground: ToolDef = {
+ name: 'set_background',
+ description: 'Set the background of a design page — solid color or a two-stop gradient with an angle.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ design_id: { type: 'string' },
+ page: { type: 'number', minimum: 0 },
+ kind: { type: 'string', enum: ['solid', 'gradient'] },
+ color: { type: 'string', description: 'solid: hex #RRGGBB' },
+ from: { type: 'string', description: 'gradient start hex' },
+ to: { type: 'string', description: 'gradient end hex' },
+ angle: { type: 'number', minimum: 0, maximum: 360 },
+ },
+ required: ['design_id', 'kind'],
+ },
+ handler: async (args) => {
+ const designId = asString(args.design_id)
+ const kind = asEnum(args.kind, ['solid', 'gradient'] as const, 'solid')
+ return mutateDesign(designId, (pages) => {
+ const pageIndex = clamp(asInt(args.page, 0), 0, pages.length - 1)
+ const page = pageAt(pages, pageIndex)
+ if (!page) return null
+ const background =
+ kind === 'gradient'
+ ? {
+ type: 'gradient' as const,
+ from: asHex(args.from, '#7630D7'),
+ to: asHex(args.to, '#02C0CC'),
+ angle: clamp(asNumber(args.angle, 135), 0, 360),
+ }
+ : { type: 'solid' as const, color: asHex(args.color, '#FFFFFF') }
+ const next = pages.map((p, i) => (i === pageIndex ? { ...p, background } : p))
+ return { pages: next, summary: { background, page: pageIndex } }
+ })
+ },
+ }
+
+ const updateElement: ToolDef = {
+ name: 'update_element',
+ description:
+ 'Update properties of an element by id (position, size, rotation, opacity, text, colors, fontSize…). Patches are validated and clamped; unknown keys are ignored. Use get_design to find element ids.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ design_id: { type: 'string' },
+ element_id: { type: 'string' },
+ page: { type: 'number', minimum: 0 },
+ patch: { type: 'object', description: 'Partial element properties to apply' },
+ },
+ required: ['design_id', 'element_id', 'patch'],
+ },
+ handler: async (args) => {
+ const designId = asString(args.design_id)
+ const elementId = asString(args.element_id)
+ const patchIn = (args.patch && typeof args.patch === 'object' ? args.patch : {}) as Record<string, unknown>
+ if (!Object.keys(patchIn).length) return fail('patch must contain at least one property.')
+ return mutateDesign(designId, (pages, w, h) => {
+ const pageIndex = clamp(asInt(args.page, 0), 0, pages.length - 1)
+ const page = pageAt(pages, pageIndex)
+ if (!page) return null
+ const el = page.elements.find((e) => e.id === elementId)
+ if (!el) return null
+ const clean = sanitizePatch(patchIn, el, w, h)
+ if (!Object.keys(clean).length) return null
+ const updated = { ...el, ...clean } as AnyElement
+ const nextPages = pages.map((p, i) =>
+ i === pageIndex ? { ...p, elements: p.elements.map((e) => (e.id === elementId ? updated : e)) } : p
+ )
+ return { pages: nextPages, summary: { updated: elementId, applied: Object.keys(clean) } }
+ })
+ },
+ }
+
+ const deleteElement: ToolDef = {
+ name: 'delete_element',
+ description: 'Delete an element by id from a design page.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ design_id: { type: 'string' },
+ element_id: { type: 'string' },
+ page: { type: 'number', minimum: 0 },
+ },
+ required: ['design_id', 'element_id'],
+ },
+ handler: async (args) => {
+ const designId = asString(args.design_id)
+ const elementId = asString(args.element_id)
+ return mutateDesign(designId, (pages) => {
+ const pageIndex = clamp(asInt(args.page, 0), 0, pages.length - 1)
+ const page = pageAt(pages, pageIndex)
+ if (!page || !page.elements.some((e) => e.id === elementId)) return null
+ const nextPages = pages.map((p, i) => (i === pageIndex ? { ...p, elements: p.elements.filter((e) => e.id !== elementId) } : p))
+ return { pages: nextPages, summary: { deleted: elementId, page: pageIndex } }
+ })
+ },
+ }
+
+ const animatePage: ToolDef = {
+ name: 'animate_page',
+ description:
+ 'Apply or clear animations on a design page. style "magic" gives the page a tasteful animation pass (fade/rise/pan mix — the same engine as the editor Magic Animate); "clear" removes all animations.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ design_id: { type: 'string' },
+ page: { type: 'number', minimum: 0 },
+ style: { type: 'string', enum: ['magic', 'clear'] },
+ speed: { type: 'string', enum: ['slow', 'medium', 'fast'] },
+ },
+ required: ['design_id'],
+ },
+ handler: async (args) => {
+ const designId = asString(args.design_id)
+ const style = asEnum(args.style, ['magic', 'clear'] as const, 'magic')
+ return mutateDesign(designId, (pages, _w, h) => {
+ const pageIndex = clamp(asInt(args.page, 0), 0, pages.length - 1)
+ const page = pageAt(pages, pageIndex)
+ if (!page) return null
+ const speed = asEnum(args.speed, ['slow', 'medium', 'fast'] as const, 'medium')
+ const updated = style === 'clear' ? clearPageAnimations(page) : magicAnimatePage(page, h, speed)
+ const next = pages.map((p, i) => (i === pageIndex ? updated : p))
+ const animatedCount = updated.elements.filter((e) => e.animation && e.animation.kind !== 'none').length
+ return { pages: next, summary: { page: pageIndex, style, animatedElements: animatedCount } }
+ })
+ },
+ }
+
+ // ── export ─────────────────────────────────────────────────
+
+ const exportDesign: ToolDef = {
+ name: 'export_design',
+ description:
+ 'Export a design page. format "svg" returns true vector SVG (text uses font-family references — viewers fall back gracefully); "png" rasterizes server-side (system fonts) and returns an image block; "json" returns the full editable document. page defaults to 0; use page "all" for every page (svg/json only).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ design_id: { type: 'string' },
+ format: { type: 'string', enum: ['svg', 'png', 'json'] },
+ page: { type: ['number', 'string'], description: '0-based page index or "all" (default 0)' },
+ },
+ required: ['design_id'],
+ },
+ handler: async (args) => {
+ const designId = asString(args.design_id)
+ const format = asEnum(args.format, ['svg', 'png', 'json'] as const, 'svg')
+ const design = await getDesign(designId)
+ if (!design) return fail(`Design "${designId}" was not found.`)
+ const pages = parsePages(design)
+ if (!pages.length) return fail('This design has no pages yet — add elements first.')
+ const pageArg = args.page
+ const indices =
+ pageArg === 'all'
+ ? pages.map((_, i) => i)
+ : [clamp(typeof pageArg === 'number' ? Math.round(pageArg) : asInt(pageArg, 0), 0, pages.length - 1)]
+
+ if (format === 'json') {
+ return ok({ design_id: designId, name: design.name, width: design.width, height: design.height, pages: pages.filter((_, i) => indices.includes(i)) })
+ }
+
+ if (format === 'svg') {
+ const svgs = indices.map((i) => exportPageToSVG(pages[i], design.width, design.height))
+ if (svgs.length === 1) return textResult(svgs[0])
+ return ok({ pages: indices.map((i, k) => ({ index: i, svg: svgs[k] })) })
+ }
+
+ // png — rasterize the server-side SVG with sharp
+ try {
+ const { default: sharp } = await import('sharp')
+ const pngs: { index: number; data: string }[] = []
+ for (const i of indices.slice(0, 3)) {
+ const svg = exportPageToSVG(pages[i], design.width, design.height)
+ const png = await sharp(Buffer.from(svg), { density: 96 })
+ .resize({ width: Math.min(2000, design.width), withoutEnlargement: design.width <= 2000 })
+ .png()
+ .toBuffer()
+ pngs.push({ index: i, data: png.toString('base64') })
+ }
+ const content: McpContent[] = [
+ ...pngs.map((p) => ({ type: 'image' as const, data: p.data, mimeType: 'image/png' })),
+ {
+ type: 'text' as const,
+ text: `PNG export of page${pngs.length > 1 ? 's' : ''} ${pngs.map((p) => p.index).join(', ')} (${design.width}x${design.height}). Rasterized server-side — fonts render with server-installed families.`,
+ },
+ ]
+ return { content }
+ } catch (err) {
+ return fail(`PNG rasterization failed: ${err instanceof Error ? err.message.slice(0, 160) : 'unknown'}. Try format "svg".`)
+ }
+ },
+ }
+
+ // ── comments ──────────────────────────────────────────────
+
+ const commentOnDesign: ToolDef = {
+ name: 'comment_on_design',
+ description: 'Add a comment to a design (optionally anchored to a page position, fractions 0..1). Visible to all collaborators in the editor.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ design_id: { type: 'string' },
+ body: { type: 'string', description: 'Comment text (max 500 chars)' },
+ page: { type: 'number', minimum: 0 },
+ x: { type: 'number', minimum: 0, maximum: 1, description: 'Anchor x as fraction of page width' },
+ y: { type: 'number', minimum: 0, maximum: 1, description: 'Anchor y as fraction of page height' },
+ author: { type: 'string', description: 'Author display name (default "AI Agent")' },
+ },
+ required: ['design_id', 'body'],
+ },
+ handler: async (args) => {
+ const designId = asString(args.design_id)
+ const body = asString(args.body).slice(0, 500)
+ if (!body.trim()) return fail('body must not be empty.')
+ const design = await getDesign(designId)
+ if (!design) return fail(`Design "${designId}" was not found.`)
+ const pages = parsePages(design)
+ const pageIndex = clamp(asInt(args.page, 0), 0, Math.max(0, pages.length - 1))
+ const pageId = pages[pageIndex]?.id ?? 'page_0'
+ const author = asString(args.author, 'AI Agent').replace(/[^\p{L}\p{N} ._-]/gu, '').slice(0, 40) || 'AI Agent'
+ const comment = await db.comment.create({
+ data: {
+ designId,
+ pageId,
+ x: clamp(asNumber(args.x, 0.5), 0, 1),
+ y: clamp(asNumber(args.y, 0.5), 0, 1),
+ authorId: AGENT_ACTOR,
+ authorName: author,
+ authorColor: '#9954FF',
+ body,
+ },
+ })
+ // notify live sessions (comment markers ride the same event stream)
+ await db.designEvent
+ .create({
+ data: {
+ designId,
+ actorId: AGENT_ACTOR,
+ kind: 'comment:activity',
+ payload: { kind: 'comment:activity', commentId: comment.id, page: pageIndex } as object,
+ },
+ })
+ .catch(() => undefined)
+ return ok({ ok: true, comment_id: comment.id, author, page: pageIndex })
+ },
+ }
+
+ const listComments: ToolDef = {
+ name: 'list_comments',
+ description: 'List comments on a design with resolve state and replies.',
+ inputSchema: {
+ type: 'object',
+ properties: { design_id: { type: 'string' } },
+ required: ['design_id'],
+ },
+ handler: async (args) => {
+ const design = await getDesign(asString(args.design_id))
+ if (!design) return fail('Design not found.')
+ const comments = await db.comment.findMany({
+ where: { designId: design.id },
+ orderBy: { createdAt: 'asc' },
+ take: 100,
+ })
+ const threads = comments.filter((c) => !c.parentId)
+ const replies = comments.filter((c) => c.parentId)
+ return ok({
+ count: threads.length,
+ threads: threads.map((t) => ({
+ id: t.id,
+ author: t.authorName,
+ body: t.body,
+ resolved: t.resolved,
+ page: t.pageId,
+ at: t.createdAt.toISOString(),
+ replies: replies
+ .filter((r) => r.parentId === t.id)
+ .map((r) => ({ id: r.id, author: r.authorName, body: r.body, at: r.createdAt.toISOString() })),
+ })),
+ })
+ },
+ }
+
+ // ── misc ───────────────────────────────────────────────────
+
+ const listFonts: ToolDef = {
+ name: 'list_fonts',
+ description: 'List the font families available in the editor (use with add_text / update_element).',
+ inputSchema: { type: 'object', properties: {} },
+ handler: async () => {
+ return ok({ count: FONTS.length, fonts: FONTS.map((f) => (typeof f === "string" ? f : f.family)) })
+ },
+ }
+
+ const getCapabilities: ToolDef = {
+ name: 'get_capabilities',
+ description: 'Report server capabilities: Canvix version, AI provider availability, and how the server is secured.',
+ inputSchema: { type: 'object', properties: {} },
+ handler: async () => {
+ return ok({
+ server: 'canvix',
+ version: SERVER_VERSION,
+ aiProvider: hasProvider() ? 'available (generate_design works)' : 'not configured (generate_design unavailable; all other tools work)',
+ transport: 'streamable-http (stateless)',
+ auth: 'bearer token via CANVIX_MCP_TOKEN',
+ })
+ },
+ }
+
+ return [
+ getCapabilities,
+ listTemplates,
+ searchDesigns,
+ getDesignTool,
+ getDesignContent,
+ createDesign,
+ generateDesign,
+ addText,
+ addShape,
+ addImage,
+ addTable,
+ addEmbed,
+ setBackground,
+ updateElement,
+ deleteElement,
+ animatePage,
+ exportDesign,
+ commentOnDesign,
+ listComments,
+ listFonts,
+ ]
+}
+
+// ── patch sanitizer (whitelist per element type) ──────────────
+
+const COMMON_KEYS = new Set(['x', 'y', 'width', 'height', 'rotation', 'opacity', 'visible', 'locked', 'name'])
+const TEXT_KEYS = new Set([...COMMON_KEYS, 'text', 'fontSize', 'fontFamily', 'bold', 'italic', 'underline', 'strike', 'uppercase', 'fill', 'align', 'lineHeight', 'letterSpacing', 'curve'])
+const SHAPE_KEYS = new Set([...COMMON_KEYS, 'fill', 'stroke', 'strokeWidth', 'cornerRadius'])
+const IMAGE_KEYS = new Set([...COMMON_KEYS, 'src', 'radius'])
+const TABLE_KEYS = new Set([...COMMON_KEYS, 'rows', 'cols', 'cells', 'colWidths', 'rowHeight', 'borderColor', 'borderWidth', 'headerFill', 'textColor', 'fontSize', 'fontFamily'])
+const FRAME_KEYS = new Set([...COMMON_KEYS, 'frameShape', 'src', 'radius'])
+const EMBED_KEYS = new Set([...COMMON_KEYS, 'url', 'title', 'tint'])
+
+function sanitizePatch(patch: Record<string, unknown>, el: AnyElement, pageW: number, pageH: number): Record<string, unknown> {
+ const allowed =
+ el.type === 'text' ? TEXT_KEYS
+ : el.type === 'image' ? IMAGE_KEYS
+ : el.type === 'table' ? TABLE_KEYS
+ : el.type === 'frame' ? FRAME_KEYS
+ : el.type === 'embed' ? EMBED_KEYS
+ : el.type === 'line' ? new Set([...COMMON_KEYS, 'stroke', 'strokeWidth', 'dashed'])
+ : SHAPE_KEYS
+
+ const out: Record<string, unknown> = {}
+ for (const [key, value] of Object.entries(patch)) {
+ if (!allowed.has(key)) continue
+ switch (key) {
+ case 'x':
+ out.x = clamp(asNumber(value, el.x), -pageW * 2, pageW * 2)
+ break
+ case 'y':
+ out.y = clamp(asNumber(value, el.y), -pageH * 2, pageH * 2)
+ break
+ case 'width':
+ case 'height':
+ out[key] = clamp(asNumber(value, (el as unknown as Record<string, number>)[key] ?? 100), 4, Math.max(pageW, pageH) * 2)
+ break
+ case 'rotation':
+ out.rotation = ((clamp(asNumber(value, 0), -3600, 3600) % 360) + 360) % 360
+ break
+ case 'opacity':
+ out.opacity = clamp(asNumber(value, 1), 0, 1)
+ break
+ case 'fontSize':
+ out.fontSize = clamp(asNumber(value, 32), 6, 400)
+ break
+ case 'curve':
+ out.curve = clamp(asNumber(value, 0), -180, 180)
+ break
+ case 'text':
+ case 'name':
+ case 'title':
+ out[key] = asString(value).slice(0, 500)
+ break
+ case 'fill':
+ case 'stroke':
+ case 'borderColor':
+ case 'headerFill':
+ case 'textColor':
+ case 'tint':
+ out[key] = asHex(value, '#000000')
+ break
+ case 'src':
+ out.src = isHttpsUrl(value) || (typeof value === 'string' && value.startsWith('data:image/')) ? value : ((el as { src?: string }).src ?? '')
+ break
+ case 'url':
+ out.url = isHttpsUrl(value) ? value : ((el as { url?: string }).url ?? '')
+ break
+ case 'fontFamily': {
+ const f = asString(value, '')
+ out.fontFamily = FONTS.some((x) => (typeof x === "string" ? x : x.family) === f) ? f : 'Inter'
+ break
+ }
+ case 'align':
+ out.align = asEnum(value, ['left', 'center', 'right', 'justify'] as const, 'left')
+ break
+ default:
+ if (typeof value === 'boolean') out[key] = value
+ else if (typeof value === 'number' && Number.isFinite(value)) out[key] = clamp(value, 0, 5000)
+ break
+ }
+ }
+ return out
+}
+
+// ── AI design spec normalizer ─────────────────────────────────
+
+/** Ask the model for the design JSON; repair common JSON flaws and retry once. */
+async function completeGeneration(
+ zai: NonNullable<Awaited<ReturnType<typeof getZAI>>>,
+ system: string,
+ user: string
+): Promise<Record<string, unknown> | null> {
+ const ask = async (extra: string) => {
+ const messages = [
+ { role: 'system' as const, content: system },
+ { role: 'user' as const, content: extra ? `${user}\n\n${extra}` : user },
+ ]
+ // strict JSON mode (supported by the provider); fall back to plain text on error
+ try {
+ const completion = await zai.chat.completions.create({
+ messages,
+ thinking: { type: 'disabled' },
+ response_format: { type: 'json_object' },
+ } as never)
+ return completion.choices[0]?.message?.content ?? ''
+ } catch {
+ const completion = await zai.chat.completions.create({
+ messages,
+ thinking: { type: 'disabled' },
+ })
+ return completion.choices[0]?.message?.content ?? ''
+ }
+ }
+
+ const parseAttempt = (raw: string): Record<string, unknown> | null => {
+ const start = raw.indexOf('{')
+ const end = raw.lastIndexOf('}')
+ if (start === -1 || end <= start) return null
+ const candidate = raw.slice(start, end + 1)
+ try {
+ return JSON.parse(candidate) as Record<string, unknown>
+ } catch {
+ // repair pass: strip trailing commas + markdown remnants, normalize smart quotes
+ const repaired = candidate
+ .replace(/,\s*([}\]])/g, '$1')
+ .replace(/[\u201c\u201d]/g, '"')
+ .replace(/[\u2018\u2019]/g, "'")
+ try {
+ return JSON.parse(repaired) as Record<string, unknown>
+ } catch {
+ return null
+ }
+ }
+ }
+
+ const first = await ask('')
+ const parsed = parseAttempt(first)
+ if (parsed) return parsed
+ // one retry with explicit feedback
+ const second = await ask('Your previous reply was not valid JSON. Reply with ONLY the raw JSON object — no markdown fences, no commentary.')
+ return parseAttempt(second)
+}
+
+function normalizeGeneratedDesign(spec: Record<string, unknown>, width: number, height: number): { width: number; height: number; pages: PageData[] } {
+ const pagesRaw = Array.isArray(spec.pages) ? spec.pages.slice(0, 1) : []
+ const pages: PageData[] = pagesRaw.map((p) => {
+ const page = (p ?? {}) as Record<string, unknown>
+ const elementsRaw = Array.isArray(page.elements) ? page.elements.slice(0, 25) : []
+ const elements: AnyElement[] = []
+ for (const e of elementsRaw) {
+ const el = (e ?? {}) as Record<string, unknown>
+ const type = asString(el.type, 'text')
+ if (type === 'text') {
+ elements.push(
+ createTextElement({
+ text: asString(el.text, 'Text').slice(0, 300),
+ x: clamp(asNumber(el.x, 60), 0, width),
+ y: clamp(asNumber(el.y, 60), 0, height),
+ width: clamp(asNumber(el.width, width - 120), 40, width * 1.2),
+ fontSize: clamp(asNumber(el.fontSize, 40), 8, 300),
+ fontFamily: FONTS.some((f) => (typeof f === "string" ? f : f.family) === asString(el.fontFamily, '')) ? asString(el.fontFamily) : 'Poppins',
+ bold: asBool(el.bold, false),
+ fill: asHex(el.fill, '#1F2226'),
+ align: asEnum(el.align, ['left', 'center', 'right'] as const, 'center'),
+ ...(Math.abs(asNumber(el.curve, 0)) > 2 ? { curve: clamp(asNumber(el.curve, 0), -180, 180) } : {}),
+ })
+ )
+ } else if (type === 'rect' || type === 'ellipse' || type === 'triangle') {
+ elements.push(
+ createShapeElement(type, {
+ x: clamp(asNumber(el.x, 40), 0, width),
+ y: clamp(asNumber(el.y, 40), 0, height),
+ width: clamp(asNumber(el.width, 300), 8, width * 1.5),
+ height: clamp(asNumber(el.height, 200), 8, height * 1.5),
+ fill: asHex(el.fill, '#00C4CC'),
+ ...(type === 'rect' ? { cornerRadius: clamp(asNumber(el.cornerRadius, 0), 0, 400) } : {}),
+ })
+ )
+ } else if (type === 'table') {
+ const header = Array.isArray(el.header) ? el.header.map((h) => asString(h).slice(0, 40)).slice(0, 6) : undefined
+ const cells = Array.isArray(el.cells)
+ ? (el.cells as Record<string, unknown>[]).slice(0, 120).map((c) => ({ text: asString(c.text).slice(0, 60) }))
+ : undefined
+ const cols = header?.length ?? 3
+ const rows = clamp(asInt(el.rows, 3), 1, 12)
+ elements.push(
+ createTableElement({
+ x: clamp(asNumber(el.x, 60), 0, width),
+ y: clamp(asNumber(el.y, height * 0.5), 0, height),
+ width: clamp(asNumber(el.width, Math.min(560, width * 0.7)), 120, width),
+ rows,
+ cols,
+ rowHeight: 44,
+ ...(header ? { header } : {}),
+ ...(cells ? { cells } : {}),
+ })
+ )
+ }
+ }
+ const bg = (page.background ?? {}) as Record<string, unknown>
+ const background =
+ asString(bg.type, 'solid') === 'gradient'
+ ? {
+ type: 'gradient' as const,
+ from: asHex(bg.from, '#7630D7'),
+ to: asHex(bg.to, '#02C0CC'),
+ angle: clamp(asNumber(bg.angle, 135), 0, 360),
+ }
+ : { type: 'solid' as const, color: asHex(bg.color, '#FFFFFF') }
+ return { id: `page_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 5)}`, background, elements }
+ })
+ if (!pages.length) {
+ pages.push({ id: `page_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 5)}`, background: { type: 'solid', color: '#FFFFFF' }, elements: [] })
+ }
+ return { width, height, pages }
+}
diff --git a/src/lib/svg-export.ts b/src/lib/svg-export.ts
index da0aa76..b403b97 100644
--- a/src/lib/svg-export.ts
+++ b/src/lib/svg-export.ts
@@ -14,6 +14,8 @@
import type {
AnyElement,
+ EmbedElement,
+ FrameElement,
GradientFill,
ImageElement,
LineElement,
@@ -21,9 +23,11 @@ import type {
ShapeElement,
StrokeElement,
StickerElement,
+ TableElement,
TextElement,
GroupElement,
} from '@/lib/types'
+import { arcForCurve, embedLayout, frameClipPathD, hostOf, tableGeometry, youtubeThumbUrl } from '@/lib/v06-geometry'
// ── escaping ─────────────────────────────────────────────────
@@ -170,6 +174,31 @@ function serializeElement(el: AnyElement, ctx: SvgContext): string {
case 'text': {
const t = el as TextElement
const rendered = t.uppercase ? t.text.toUpperCase() : t.text
+
+ // v0.6: curved text → textPath on an arc (path def carries the translate)
+ const arc = arcForCurve(t.curve ?? 0, t.width)
+ if (arc) {
+ const pathId = refId('arc')
+ ctx.defs.push(` <path id="${pathId}" transform="translate(${t.x} ${t.y})" d="${arc.data}" fill="none" />`)
+ const fill = t.fillGradient ? gradientRefFor(t, ctx) : t.fill
+ 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}"` : '',
+ `fill="${fill}"`,
+ opacityAttr(t),
+ shadowAttrs(t, ctx),
+ ]
+ .filter(Boolean)
+ .join(' ')
+ const transform = t.rotation ? ` transform="rotate(${t.rotation} ${t.x} ${t.y})"` : ''
+ return ` <text ${attrs}${transform} xml:space="preserve"><textPath href="#${pathId}" xlink:href="#${pathId}">${esc(rendered)}</textPath></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
@@ -304,6 +333,100 @@ function serializeElement(el: AnyElement, ctx: SvgContext): string {
return ` <g transform="translate(${g.x} ${g.y})${g.rotation ? ` rotate(${g.rotation})` : ''}"${opacityAttr(g)}>\n${children}\n </g>`
}
+ case 'table': {
+ const tb = el as TableElement
+ const geo = tableGeometry(tb)
+ const parts: string[] = []
+ for (let idx = 0; idx < tb.rows * tb.cols; idx += 1) {
+ const r = Math.floor(idx / tb.cols)
+ const c = idx % tb.cols
+ const cell = tb.cells[idx] ?? { text: '' }
+ const isHeader = r === 0
+ const cellFill = cell.fill ?? (isHeader ? tb.headerFill : tb.fill)
+ const x = tb.x + geo.colX[c]
+ const y = tb.y + r * geo.rowH
+ const w = geo.colW[c]
+ const h = geo.rowH
+ parts.push(` <rect x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${w.toFixed(1)}" height="${h.toFixed(1)}"${cellFill !== 'transparent' ? ` fill="${cellFill}"` : ' fill="none"'} stroke="${tb.borderColor}" stroke-width="${tb.borderWidth}" />`)
+ if (cell.text) {
+ const textColor = isHeader ? (tb.headerTextColor ?? '#FFFFFF') : tb.textColor
+ const baseline = y + h / 2 + tb.fontSize * 0.35
+ parts.push(` <text x="${(x + 10).toFixed(1)}" y="${baseline.toFixed(1)}" font-family="${esc(tb.fontFamily)}" font-size="${tb.fontSize}" font-weight="${cell.bold || isHeader ? 700 : 400}" fill="${textColor}">${esc(cell.text)}</text>`)
+ }
+ }
+ const transform = tb.rotation ? ` transform="rotate(${tb.rotation} ${tb.x} ${tb.y})"` : ''
+ const open = `<g${transform}${opacityAttr(tb)}${shadowAttrs(tb, ctx)}>`
+ return `${open}\n${parts.join('\n')}\n </g>`
+ }
+
+ case 'frame': {
+ const fr = el as FrameElement
+ const clipId = refId('fclip')
+ const d = frameClipPathD(fr.frameShape, fr.width, fr.height, fr.radius)
+ ctx.defs.push(` <clipPath id="${clipId}"><path transform="translate(${fr.x} ${fr.y})" d="${d}" /></clipPath>`)
+ const rotate = fr.rotation ? ` transform="rotate(${fr.rotation} ${fr.x} ${fr.y})"` : ''
+ const href = fr.src ? safeHref(fr.src) : null
+ let content = ''
+ if (href && fr.naturalWidth > 0 && fr.naturalHeight > 0) {
+ // cover-fit like the canvas renderer
+ const scale = Math.max(fr.width / fr.naturalWidth, fr.height / fr.naturalHeight)
+ const dw = fr.naturalWidth * scale
+ const dh = fr.naturalHeight * scale
+ const dx = fr.x + (fr.width - dw) / 2
+ const dy = fr.y + (fr.height - dh) / 2
+ content = ` <image href="${esc(href)}" x="${dx.toFixed(1)}" y="${dy.toFixed(1)}" width="${dw.toFixed(1)}" height="${dh.toFixed(1)}" clip-path="url(#${clipId})" preserveAspectRatio="none" />`
+ } else {
+ // empty frame placeholder — tinted shape + dashed outline
+ content = ` <path transform="translate(${fr.x} ${fr.y})" d="${d}" fill="${fr.fill}" fill-opacity="0.16" stroke="rgba(255,255,255,0.85)" stroke-width="2" stroke-dasharray="8 6" />`
+ }
+ const open = `<g${rotate}${opacityAttr(fr)}${shadowAttrs(fr, ctx)}>`
+ return `${open}\n${content}\n </g>`
+ }
+
+ case 'embed': {
+ const em = el as EmbedElement
+ const { bandH, iconR } = embedLayout(em.width, em.height)
+ const x = em.x
+ const y = em.y
+ const w = em.width
+ const h = em.height
+ const cx = x + w / 2
+ const cy = y + bandH / 2
+ const parts: string[] = []
+ parts.push(` <rect x="${x}" y="${y}" width="${w}" height="${h}" rx="14" fill="#15171C" />`)
+ const thumb = em.kind === 'youtube' ? youtubeThumbUrl(em.url) : null
+ // top-rounded media band path (bottom edge straight, meets the label area)
+ const bandPath = `M ${x + 14} ${y} H ${x + w - 14} Q ${x + w} ${y} ${x + w} ${y + 14} V ${y + bandH} H ${x} V ${y + 14} Q ${x} ${y} ${x + 14} ${y} Z`
+ if (thumb) {
+ const clipId = refId('eclip')
+ ctx.defs.push(` <clipPath id="${clipId}"><path d="${bandPath}" /></clipPath>`)
+ parts.push(` <image href="${esc(thumb)}" x="${x}" y="${y}" width="${w}" height="${bandH}" preserveAspectRatio="xMidYMid slice" clip-path="url(#${clipId})" />`)
+ } else {
+ parts.push(` <path d="${bandPath}" fill="${em.tint}" fill-opacity="0.28" />`)
+ }
+ // icon glyph
+ if (em.kind === 'youtube') {
+ parts.push(` <circle cx="${cx}" cy="${cy}" r="${iconR}" fill="rgba(255,255,255,0.92)" />`)
+ parts.push(` <polygon points="${cx - iconR * 0.32},${cy - iconR * 0.42} ${cx - iconR * 0.32},${cy + iconR * 0.42} ${cx + iconR * 0.46},${cy}" fill="#FF0033" />`)
+ } else if (em.kind === 'map') {
+ parts.push(` <circle cx="${cx}" cy="${cy}" r="${iconR}" fill="rgba(255,255,255,0.95)" />`)
+ parts.push(` <ellipse cx="${cx}" cy="${cy - iconR * 0.12}" rx="${iconR * 0.34}" ry="${iconR * 0.46}" fill="#34A853" />`)
+ parts.push(` <polygon points="${cx - iconR * 0.24},${cy + iconR * 0.1} ${cx},${cy + iconR * 0.58} ${cx + iconR * 0.24},${cy + iconR * 0.1}" fill="#34A853" />`)
+ } else {
+ const s = iconR * 0.8
+ parts.push(` <circle cx="${cx}" cy="${cy}" r="${iconR}" fill="rgba(255,255,255,0.14)" stroke="rgba(255,255,255,0.9)" stroke-width="2.5" />`)
+ parts.push(` <path d="M ${cx - s * 0.4} ${cy + s * 0.4} L ${cx + s * 0.42} ${cy - s * 0.42} M ${cx - s * 0.05} ${cy - s * 0.42} L ${cx + s * 0.42} ${cy - s * 0.42} L ${cx + s * 0.42} ${cy + s * 0.05}" stroke="#FFFFFF" stroke-width="${Math.max(2, iconR * 0.16)}" stroke-linecap="round" stroke-linejoin="round" fill="none" />`)
+ }
+ // labels
+ const host = hostOf(em.url).toUpperCase()
+ const title = em.title ?? em.url
+ parts.push(` <text x="${x + 14}" y="${y + bandH + 24}" font-family="Inter" font-size="${Math.max(9, Math.round(h * 0.055))}" letter-spacing="1.2" fill="rgba(255,255,255,0.55)">${esc(host)}</text>`)
+ parts.push(` <text x="${x + 14}" y="${y + bandH + 44}" font-family="Inter" font-size="${Math.max(11, Math.round(h * 0.07))}" font-weight="600" fill="#FFFFFF">${esc(title.length > 46 ? title.slice(0, 46) + '…' : title)}</text>`)
+ const rotate = em.rotation ? ` transform="rotate(${em.rotation} ${x} ${y})"` : ''
+ const open = `<g${rotate}${opacityAttr(em)}${shadowAttrs(em, ctx)}>`
+ return `${open}\n${parts.join('\n')}\n </g>`
+ }
+
default:
return ''
}
diff --git a/src/lib/types.ts b/src/lib/types.ts
index 9869201..3982aa9 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -14,6 +14,9 @@ export type ElementType =
| 'image'
| 'sticker'
| 'group'
+ | 'table'
+ | 'frame'
+ | 'embed'
export type TextAlign = 'left' | 'center' | 'right' | 'justify'
@@ -121,6 +124,8 @@ export interface TextElement extends BaseElement {
align: TextAlign
lineHeight: number
letterSpacing: number
+ /** v0.6 canva curved text — arc angle in degrees (−180..180, 0 = straight) */
+ curve?: number
/** text background block colour (canva "Background" effect) */
effectBackground?: string
/** canva-style effect preset */
@@ -184,6 +189,75 @@ export interface StrokeElement extends BaseElement {
strokeWidth: number
}
+// ── v0.6: canva-parity elements (tables, frames, embeds) ─────
+
+/** One cell of a table. Missing text = empty string. */
+export interface TableCell {
+ text: string
+ /** cell fill — undefined = transparent (table bg shows) */
+ fill?: string
+ bold?: boolean
+}
+
+/** Canva-style native table — rendered as rect + text per cell, every cell editable. */
+export interface TableElement extends BaseElement {
+ type: 'table'
+ rows: number
+ cols: number
+ /** row-major cells, length = rows × cols */
+ cells: TableCell[]
+ /** per-column widths in px — must sum to element width */
+ colWidths: number[]
+ /** uniform row height in px (rows × rowHeight ≈ element height) */
+ rowHeight: number
+ borderColor: string
+ borderWidth: number
+ /** first row fill (header band) */
+ headerFill: string
+ headerTextColor?: string
+ fill: string
+ textColor: string
+ fontSize: number
+ fontFamily: string
+}
+
+export const FRAME_SHAPES = ['rect', 'ellipse', 'triangle', 'hexagon', 'circle'] as const
+export type FrameShape = (typeof FRAME_SHAPES)[number]
+
+export const FRAME_SHAPE_LABELS: Record<FrameShape, string> = {
+ rect: 'Rectangle',
+ ellipse: 'Ellipse',
+ triangle: 'Triangle',
+ hexagon: 'Hexagon',
+ circle: 'Circle',
+}
+
+/** Canva-style frame — an image clipped inside a shape. `src` empty = placeholder. */
+export interface FrameElement extends BaseElement {
+ type: 'frame'
+ frameShape: FrameShape
+ /** image source (dataURL or https) — when unset the frame renders a dashed placeholder */
+ src: string
+ naturalWidth: number
+ naturalHeight: number
+ /** placeholder / empty-frame tint */
+ fill: string
+ radius: number
+}
+
+export type EmbedKind = 'youtube' | 'map' | 'link'
+
+/** Canva-style embed card — a native vector link card (YouTube / Maps / generic).
+ * Honest scope: a *card* that opens the target in a browser, not an iframe. */
+export interface EmbedElement extends BaseElement {
+ type: 'embed'
+ url: string
+ kind: EmbedKind
+ title?: string
+ /** dominant card tint */
+ tint: string
+}
+
/** Brand kit — persisted per browser (localStorage) */
export interface BrandKit {
colors: string[]
@@ -215,6 +289,9 @@ export type AnyElement =
| ImageElement
| StickerElement
| GroupElement
+ | TableElement
+ | FrameElement
+ | EmbedElement
export type Background =
| { type: 'solid'; color: string }
@@ -418,6 +495,114 @@ export function createStickerElement(char: string, init: BaseInit & Partial<Stic
}
}
+/** v0.6: table factory — cells default to empty, header row pre-filled from `header?`. */
+export function createTableElement(
+ init: BaseInit & Partial<TableElement> & { header?: string[] } = {}
+): TableElement {
+ const { header, cells: cellsInit, colWidths: colWidthsInit, ...rest } = init
+ const rows = rest.rows ?? 3
+ const cols = rest.cols ?? 3
+ const width = rest.width ?? 420
+ const rowHeight = rest.rowHeight ?? 44
+ const cells: TableCell[] = []
+ for (let r = 0; r < rows; r += 1) {
+ for (let c = 0; c < cols; c += 1) {
+ const provided = cellsInit?.[r * cols + c]
+ if (r === 0) {
+ const headerText = header ? (header[c] ?? '') : ''
+ cells.push({ text: headerText, bold: true, fill: rest.headerFill ?? '#1F142E', ...provided })
+ } else {
+ cells.push(provided ?? { text: '' })
+ }
+ }
+ }
+ const colWidths = colWidthsInit ?? Array.from({ length: cols }, () => Math.round(width / cols))
+ return {
+ ...baseElement('table', { width, height: rows * rowHeight, ...rest }),
+ type: 'table',
+ borderColor: '#E0E1E6',
+ borderWidth: 1.5,
+ headerFill: '#1F142E',
+ headerTextColor: '#FFFFFF',
+ fill: 'transparent',
+ textColor: '#1F2226',
+ fontSize: 14,
+ fontFamily: 'Inter',
+ ...rest,
+ rows,
+ cols,
+ cells,
+ colWidths,
+ rowHeight,
+ width,
+ height: rest.height ?? rows * rowHeight,
+ }
+}
+
+/** v0.6: frame factory */
+export function createFrameElement(
+ frameShape: FrameShape,
+ init: BaseInit & Partial<FrameElement> = {}
+): FrameElement {
+ const size = init.width ?? 320
+ return {
+ ...baseElement('frame', { width: size, height: init.height ?? Math.round(size * 0.66), ...init }),
+ type: 'frame',
+ frameShape,
+ src: '',
+ naturalWidth: 0,
+ naturalHeight: 0,
+ fill: '#8B5CF6',
+ radius: 0,
+ ...init,
+ }
+}
+
+/** v0.6: embed card factory — kind is auto-detected from the URL when omitted. */
+export function createEmbedElement(url: string, init: BaseInit & Partial<EmbedElement> = {}): EmbedElement {
+ const { kind: kindInit, title, tint, ...rest } = init
+ const kind: EmbedKind = kindInit ?? detectEmbedKind(url)
+ return {
+ ...baseElement('embed', { width: 320, height: 200, ...rest }),
+ type: 'embed',
+ url,
+ title: title ?? embedTitleFrom(url, kind),
+ tint: tint ?? (kind === 'youtube' ? '#FF0033' : kind === 'map' ? '#34A853' : '#7630D7'),
+ ...rest,
+ kind,
+ }
+}
+
+export function detectEmbedKind(url: string): EmbedKind {
+ try {
+ const u = new URL(url)
+ const host = u.hostname.replace(/^www\./, '')
+ if (host === 'youtu.be' || host === 'youtube.com' || host === 'm.youtube.com') return 'youtube'
+ if (host === 'maps.google.com') return 'map'
+ if (host === 'google.com' && u.pathname.startsWith('/maps')) return 'map'
+ return 'link'
+ } catch {
+ return 'link'
+ }
+}
+
+function embedTitleFrom(url: string, kind: EmbedKind): string {
+ try {
+ const u = new URL(url)
+ if (kind === 'youtube') {
+ const v = u.searchParams.get('v') || u.pathname.split('/').pop() || ''
+ return v ? `YouTube video · ${v.slice(0, 20)}` : 'YouTube video'
+ }
+ if (kind === 'map') {
+ const q = u.searchParams.get('q') || u.searchParams.get('query')
+ return q ? `Google Maps · ${q}` : 'Google Maps'
+ }
+ return u.hostname.replace(/^www\./, '')
+ } catch {
+ return 'Link'
+ }
+}
+
export function createStrokeElement(init: BaseInit & Partial<StrokeElement>): StrokeElement {
return {
...baseElement('stroke', init),
@@ -470,3 +655,12 @@ export function isSticker(el: AnyElement): el is StickerElement {
export function isGroup(el: AnyElement): el is GroupElement {
return el.type === 'group'
}
+export function isTable(el: AnyElement): el is TableElement {
+ return el.type === 'table'
+}
+export function isFrame(el: AnyElement): el is FrameElement {
+ return el.type === 'frame'
+}
+export function isEmbed(el: AnyElement): el is EmbedElement {
+ return el.type === 'embed'
+}
diff --git a/src/lib/v06-geometry.ts b/src/lib/v06-geometry.ts
new file mode 100644
index 0000000..f8d1238
--- /dev/null
+++ b/src/lib/v06-geometry.ts
@@ -0,0 +1,121 @@
+// ─────────────────────────────────────────────────────────────
+// v0.6 shared geometry — pure functions used by BOTH the Konva
+// renderers (client) and the SVG exporter (server-safe). No DOM,
+// no Konva imports allowed in this file.
+// ─────────────────────────────────────────────────────────────
+
+import type { EmbedKind, FrameShape, TableElement } from '@/lib/types'
+
+// ── curved text ──────────────────────────────────────────────
+
+/** Arc geometry for a curved text element (local coords, origin = element x/y).
+ * curve: −180..180 (0 = straight). Positive = arch up, negative = valley.
+ * Returns the SVG path data + the arc's visual height. */
+export function arcForCurve(curve: number, width: number): { data: string; height: number } | null {
+ const deg = Math.max(-180, Math.min(180, Math.abs(curve)))
+ if (deg < 2 || width < 12) return null
+ const a = (deg * Math.PI) / 180 // total sweep (radians)
+ const r = Math.max(10, width / 2 / Math.sin(a / 2))
+ const sag = r - r * Math.cos(a / 2) // peak height of the arc
+ if (!Number.isFinite(r) || !Number.isFinite(sag)) return null
+ const largeArc = a > Math.PI ? 1 : 0
+ if (curve > 0) {
+ // arch up: baseline peaks at y=0, ends dip to y=sag
+ return {
+ data: `M 0 ${sag.toFixed(2)} A ${r.toFixed(2)} ${r.toFixed(2)} 0 ${largeArc} 1 ${width.toFixed(2)} ${sag.toFixed(2)}`,
+ height: sag,
+ }
+ }
+ // valley: starts at y=0, dips to y=sag
+ return {
+ data: `M 0 0 A ${r.toFixed(2)} ${r.toFixed(2)} 0 ${largeArc} 0 ${width.toFixed(2)} 0`,
+ height: sag,
+ }
+}
+
+// ── tables ───────────────────────────────────────────────────
+
+/** Effective column/row geometry (proportional when el.width ≠ ΣcolWidths). */
+export function tableGeometry(el: TableElement): { colX: number[]; colW: number[]; rowH: number } {
+ const sum = el.colWidths.reduce((a, b) => a + b, 0)
+ const scale = sum > 0 ? el.width / sum : 1
+ const colW = el.colWidths.map((w) => w * scale)
+ const colX: number[] = []
+ let acc = 0
+ for (const w of colW) {
+ colX.push(acc)
+ acc += w
+ }
+ const rowH = el.rows > 0 ? el.height / el.rows : el.rowHeight
+ return { colX, colW, rowH }
+}
+
+// ── frames ───────────────────────────────────────────────────
+
+export function hexPoints(w: number, h: number): [number, number][] {
+ return [
+ [w, h / 2],
+ [w * 0.75, h],
+ [w * 0.25, h],
+ [0, h / 2],
+ [w * 0.25, 0],
+ [w * 0.75, 0],
+ ]
+}
+
+/** SVG path data for a frame clip shape (local coords, origin = element x/y). */
+export function frameClipPathD(shape: FrameShape, w: number, h: number, r: number): string {
+ switch (shape) {
+ case 'ellipse':
+ case 'circle': {
+ const rx = shape === 'circle' ? Math.min(w, h) / 2 : w / 2
+ const ry = shape === 'circle' ? Math.min(w, h) / 2 : h / 2
+ // approximate an ellipse with two arcs
+ return `M 0 ${h / 2} A ${rx} ${ry} 0 0 1 ${w} ${h / 2} A ${rx} ${ry} 0 0 1 0 ${h / 2} Z`
+ }
+ case 'triangle':
+ return `M 0 ${h} L ${w / 2} 0 L ${w} ${h} Z`
+ case 'hexagon':
+ return hexPoints(w, h).map((p, i) => `${i === 0 ? 'M' : 'L'} ${p[0].toFixed(2)} ${p[1].toFixed(2)}`).join(' ') + ' Z'
+ default: {
+ const rr = Math.min(r, w / 2, h / 2)
+ if (rr <= 0) return `M 0 0 H ${w} V ${h} H 0 Z`
+ return `M ${rr} 0 H ${w - rr} Q ${w} 0 ${w} ${rr} V ${h - rr} Q ${w} ${h} ${w - rr} ${h} H ${rr} Q 0 ${h} 0 ${h - rr} V ${rr} Q 0 0 ${rr} 0 Z`
+ }
+ }
+}
+
+// ── embeds ───────────────────────────────────────────────────
+
+export function youtubeThumbUrl(url: string): string | null {
+ try {
+ const u = new URL(url)
+ const host = u.hostname.replace(/^www\./, '')
+ if (host !== 'youtube.com' && host !== 'm.youtube.com' && host !== 'youtu.be') return null
+ const v = u.searchParams.get('v') || (host === 'youtu.be' ? u.pathname.split('/').pop() : '') || ''
+ return v ? `https://i.ytimg.com/vi/${v}/hqdefault.jpg` : null
+ } catch {
+ return null
+ }
+}
+
+export function hostOf(url: string): string {
+ try {
+ return new URL(url).hostname.replace(/^www\./, '')
+ } catch {
+ return 'link'
+ }
+}
+
+export function embedTintFor(kind: EmbedKind): string {
+ if (kind === 'youtube') return '#FF0033'
+ if (kind === 'map') return '#34A853'
+ return '#7630D7'
+}
+
+/** embed card layout metrics */
+export function embedLayout(w: number, h: number): { bandH: number; iconR: number } {
+ const bandH = Math.round(h * 0.62)
+ const iconR = Math.max(18, Math.min(34, Math.round(Math.min(w, bandH) * 0.18)))
+ return { bandH, iconR }
+}