Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(v0.18.0): Wave 3 — editor depth parity
Ashiq Hussain Mirc4d55a5e277b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a8052e9..0de7707 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,96 @@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.18.0] — 2026-11-09++Wave 3 of the consolidation programme — editor depth parity (roadmap:+`docs/COMPETITIVE-ANALYSIS.md`). Eight features across shape geometry,+text layout, canvas aids, document structure and presenting, with every+renderer kept in lockstep. **No migration this release** — everything+rides additive, nullable fields (`sides`, `numPoints`, `innerRatio`,+`maskShape`, `maskSides`, `maskInnerRatio`, `autoFit`, `listStyle`,+`direction`, per-page `width`/`height`/`notes`); pre-v0.18 documents+open byte-identically.++### Added++- **Parametric polygons & stars.** The shape palette gained a Polygons+ section (hexagon, pentagon, octagon, triangle, square, heptagon,+ nonagon, decagon, 3–12 sides via the properties bar) and the star is+ now parametric: 3–16 points with an adjustable spike ratio. One+ geometry module (`lib/shapes.ts`) generates the vertices in a+ 100×100 authoring box and two documented mappings place them:+ `stretchPts` for shapes (fills the element box, matching+ rect/ellipse/triangle) and `scalePts` for masks (the 2 % inset).+ The Konva canvas, SVG export, vector PDF export and video export all+ render the identical point arrays.+- **Image masks — 10 preset shapes + parametric polygon/starburst.**+ Circle, rounded, arch, triangle, diamond, pentagon, hexagon, star,+ heart and blob presets plus the two parametric modes, from a Mask+ picker in the image properties bar with live silhouettes. The clip+ polygon rides the element (`maskShape`/`maskSides`/`maskInnerRatio`+ — validated on render, hostile pastes degrade to none), renders via+ Konva `clipFunc` on the canvas, a `<clipPath>` polygon in SVG, a `W n`+ vector clip in the PDF and the same clip group in video frames.+- **Text auto-fit.** Canva-style: shrinks the font so the text fits its+ box, never grows past the authored size, floor at 6 px. Derived at+ render time through one binary search (`lib/text-fit.ts`) that every+ renderer runs against its own measure — the canvas, SVG and PDF+ agree to the pixel, and the authored `fontSize` is never mutated.+- **Bullet & numbered lists.** Any text element becomes a list+ (properties bar → List): every non-empty paragraph is an item with a+ hanging indent, widest-marker column, Canva-style wrapped+ continuation lines. Shared layout (`lib/list-text.ts`) drives the+ canvas, SVG and video renderers; the vector PDF takes the documented+ raster-strip approximation for v1 (pixel-perfect, not selectable).+- **RTL & complex scripts.** A direction toggle (LTR/RTL) mirrors the+ list marker to the right edge and flips the default alignment+ (explicit centre stays); within-line reordering is the platform text+ stack's job, as it always was for Arabic/Hebrew content.+- **Grid overlay + snap to grid.** A zoom-bar toggle draws the grid on+ the stage (8–160 px cells, page-space so it zooms with the design)+ with an optional snap that rounds drags to the grid before element+ alignment. Editor preference only — never document data, never+ rendered in exports.+- **Per-page sizes.** Every page can override the design size+ (properties from the page bar); `pageSize()` in `lib/editor-utils.ts`+ is the one accessor every consumer goes through — canvas, preview,+ presenter, thumbnails, SVG, PDF MediaBoxes and video frames each+ fit-and-centre per page. Absent or absurd values fall back to the+ design size exactly as before.+- **Presenter view with speaker notes.** Present with notes from the+ top bar: the current page large, the next as a thumbnail, live+ editable speaker notes per page (PageData.notes — never rendered on+ the canvas or in exports), keyboard navigation and an elapsed timer.+ The notes panel also lives in the page bar for authoring.++### Changed++- **Boot-time template top-up (operators).** "The template library+ ships as code" now reconciles itself: on every boot (Node runtime)+ built-in templates are upserted when the database holds fewer than+ the library (`src/instrumentation.ts` → `lib/templates/sync.ts`,+ the same code `npm run db:seed` runs). One COUNT query on a normal+ boot; new templates appear and nothing is ever deleted. Opt out with+ `CANVIX_TEMPLATE_SYNC=0`. This also closes the gap where an+ auto-deploying instance upgraded by `migrate deploy` alone would+ serve the stale template library (the exact canvix.app v0.17.0+ rollout: 110 of 366 templates until the next boot).+- The wordcloud plugin's engine ceiling moved to `<0.19.0`.++### Export parity notes++- **Vector PDF**: polygons, parametric stars, image masks, auto-fit and+ per-page MediaBoxes are first-class vector paths; list and RTL text+ ride the existing raster-strip fallback (documented approximation,+ v1). Auto-fit in the PDF uses the same measure-based binary search as+ the other renderers.+- **SVG**: full parity for every Wave 3 feature (clip-path masks, list+ tspans, `direction="rtl"`, per-page viewBox, derived auto-fit size).+- **Video**: pages fit-and-centre per page; lists, auto-fit, RTL+ mirroring, masks and parametric shapes render identically to the+ canvas.+## [0.17.0] — 2026-11-09The Wave 2 feature drop from the consolidation programme — the asset &diff --git a/docs/COMPETITIVE-ANALYSIS.md b/docs/COMPETITIVE-ANALYSIS.mdindex cb3c2a2..69d11d5 100644--- a/docs/COMPETITIVE-ANALYSIS.md+++ b/docs/COMPETITIVE-ANALYSIS.md@@ -77,10 +77,17 @@ preset catalog 8 → 60 · template library 110 → 366 (12 smart + 244 computedDetails: docs/ASSETS-AND-TEMPLATES.md · acceptance: 1187 unit tests, 11/11 e2e,migration 0011 upgrade-safe. Matrix re-score pending (Wave 3 kickoff).-### Wave 3 — Editor Depth Parity+### Wave 3 — Editor Depth Parity ✅ SHIPPED (v0.18.0, 2026-11-09)Image masks (10 shapes + custom) · text auto-fit · bullet/numbered lists · RTL & complex scripts ·parametric polygons/stars · grid overlay · per-page sizes · presenter view with speaker notes ·(bezier pen, boolean ops as stretch goals).+No migration (additive nullable fields only; pre-v0.18 documents unchanged). One shared+geometry/layout module per concern (lib/shapes.ts, lib/text-fit.ts, lib/list-text.ts) drives the+canvas, SVG, vector-PDF and video renderers in lockstep; PDF list/RTL text rides the documented+raster-strip approximation for v1. Acceptance: 1304 unit tests (+65), wave3 e2e suite+(tests/e2e/wave3-editor-depth.spec.ts), scripts/verify-wave3.sh. Also shipped: boot-time template+top-up (lib/templates/sync.ts — auto-deployed instances no longer serve a stale library).+Stretch goals deferred with the roadmap; matrix re-score pending (Wave 4 kickoff).### Wave 4 — AI Power-UpLocal upscaling (Real-ESRGAN/Lanczos) · brush magic eraser (LaMa) · agentic planning with editablediff --git a/docs/UPGRADING.md b/docs/UPGRADING.mdindex b0ea415..e4e6892 100644--- a/docs/UPGRADING.md+++ b/docs/UPGRADING.md@@ -5,6 +5,24 @@ release is designed to upgrade with **one migration command**. Thisguide covers the routine path, jumping minors, and — the part mostguides skip — how to roll back, with the honest database caveat.+## v0.18.0 — Wave 3 (editor depth parity)++**No migration.** Everything rides additive, nullable fields (shape+`sides`/`numPoints`/`innerRatio`, image `maskShape`/`maskSides`/+`maskInnerRatio`, text `autoFit`/`listStyle`/`direction`, per-page+`width`/`height`/`notes`) — `npm run db:migrate:deploy` is a no-op and+pre-v0.18 documents open unchanged. After deploying, restart as usual;+nothing else to run.++v0.18 also introduces the **boot-time template top-up**: on every+start (Node runtime) the built-in template library reconciles itself+into the database — new templates appear, nothing is deleted — so an+instance that upgrades by `migrate deploy` alone (e.g. behind an+auto-deployer) no longer serves a stale library. One `COUNT` query on+a normal boot. Curate the library by hand instead? Set+`CANVIX_TEMPLATE_SYNC=0` and use `npm run db:seed` when you want a+refresh.+## v0.17.0 — Wave 2 (assets & templates)One migration (`0011_wave2_assets_templates`): two new tablesdiff --git a/package-lock.json b/package-lock.jsonindex 68c0dd0..c1cb568 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "canvix",- "version": "0.16.5",+ "version": "0.18.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "canvix",- "version": "0.16.5",+ "version": "0.18.0","hasInstallScript": true,"dependencies": {"@imgly/background-removal": "^1.7.0",diff --git a/package.json b/package.jsonindex 8b23a6c..03e8cc2 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.17.0",+ "version": "0.18.0","private": false,"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/prisma/seed.ts b/prisma/seed.tsindex 7d1b4ce..3f9547e 100644--- a/prisma/seed.ts+++ b/prisma/seed.ts@@ -1,52 +1,22 @@// Seed the Canvix database with built-in templates.// Run: npm run db:seed (or as part of: npm run db:setup)-import { Prisma } from '../src/generated/prisma/client'+//+// v0.18: the upsert loop lives in src/lib/templates/sync.ts (shared+// with the boot-time top-up) — this script is the operator-facing+// wrapper. force: true means "refresh content even when the count+// already matches", which is what an explicit seed run means.import { TEMPLATES } from '../src/lib/templates'import { createScriptClient } from '../src/lib/db-script'+// relative import — plain tsx must run without the '@/' alias resolved+import { syncTemplateLibrary } from '../src/lib/templates/sync'const db = createScriptClient()-// Typed template list cast for the Postgres jsonb column.-const pagesOf = (t: (typeof TEMPLATES)[number]) =>- t.pages as unknown as Prisma.InputJsonValue--// v0.17 (Wave 2): field declarations use the same jsonb cast. Plain-// templates store SQL NULL (DbNull), not the jsonb 'null' literal —-// IS NULL filters and the fill route's fallback both rely on it.-const fieldsOf = (t: (typeof TEMPLATES)[number]) =>- t.fields- ? (t.fields as unknown as Prisma.InputJsonValue)- : Prisma.DbNull-async function main() {console.log(`Seeding ${TEMPLATES.length} templates…`)- for (const t of TEMPLATES) {- await db.template.upsert({- where: { slug: t.slug },- update: {- name: t.name,- category: t.category,- width: t.width,- height: t.height,- accent: t.accent,- pages: pagesOf(t),- // v0.17 (Wave 2): smart-template field declarations- fields: fieldsOf(t),- },- create: {- slug: t.slug,- name: t.name,- category: t.category,- width: t.width,- height: t.height,- accent: t.accent,- pages: pagesOf(t),- fields: fieldsOf(t),- },- })- console.log(` ✓ ${t.slug}`)- }- console.log('Done.')+ const before = await db.template.count()+ const res = await syncTemplateLibrary(db, { force: true })+ console.log(`Done. ${res.synced} templates upserted (library had ${before}, now ${res.total}).`)}main()diff --git a/public/plugins/wordcloud/manifest.json b/public/plugins/wordcloud/manifest.jsonindex 12a5699..4c14007 100644--- a/public/plugins/wordcloud/manifest.json+++ b/public/plugins/wordcloud/manifest.json@@ -9,7 +9,7 @@"url": "https://github.com/mir-ashiq/canvix"},"engines": {- "canvix": ">=0.13.4 <0.18.0"+ "canvix": ">=0.13.4 <0.19.0"},"entry": {"panel": "panel.html",diff --git a/scripts/verify-wave3.sh b/scripts/verify-wave3.shnew file mode 100755index 0000000..505e65e--- /dev/null+++ b/scripts/verify-wave3.sh@@ -0,0 +1,91 @@+#!/bin/bash+# scripts/verify-wave3.sh — one-shot Wave 3 verification (sandbox):+# embedded Postgres + migrate deploy (through 0011) + seed (366) ++# dev server + targeted playwright e2e (wave3 + smoke). Everything in+# ONE shell because background processes don't outlive the session.+set -euo pipefail+cd "$(dirname "$0")/.."+ROOT="$(pwd)"++export DATABASE_URL="postgresql://canvix:canvix@localhost:5433/canvix"+PGDIR=/tmp/pgembed+LOG=$PGDIR/verify-w3.log+: > "$LOG"++echo "── 1. embedded postgres ─────────────────────────────"+pkill -f 'pgembed/data3' 2>/dev/null || true+pkill -f 'start3.mjs' 2>/dev/null || true+for i in $(seq 1 15); do+ if node -e "const n=require('net');const s=n.connect(5433,'127.0.0.1',()=>{s.end();process.exit(0)});s.on('error',()=>process.exit(1))" 2>/dev/null; then sleep 1; else break; fi+done+rm -rf "$PGDIR/data3" "$PGDIR/ready3.marker"+mkdir -p "$PGDIR"+cat > "$PGDIR/start3.mjs" << 'EOF'+// ESM resolution is file-location based — /tmp has no node_modules, so+// import the repo's copy by absolute path (ROOT comes from the env).+const { default: EmbeddedPostgres } = await import(+ process.env.ROOT + '/node_modules/embedded-postgres/dist/index.js'+)+import { writeFileSync } from 'node:fs'+const pg = new EmbeddedPostgres({+ databaseDir: '/tmp/pgembed/data3',+ user: 'canvix',+ password: 'canvix',+ port: 5433,+ persistent: true,+})+await pg.initialise()+await pg.start()+await pg.createDatabase('canvix').catch(() => {})+const { Client } = (await import(process.env.ROOT + '/node_modules/pg/lib/index.js')).default+for (let i = 0; i < 60; i++) {+ try {+ const c = new Client({ connectionString: 'postgresql://canvix:[email protected]:5433/canvix' })+ await c.connect()+ await c.query('SELECT 1')+ await c.end()+ writeFileSync('/tmp/pgembed/ready3.marker', 'ok')+ console.log('PG READY (query verified)')+ break+ } catch {+ await new Promise((r) => setTimeout(r, 500))+ }+}+setInterval(() => {}, 1 << 30)+EOF+setsid nohup env ROOT="$ROOT" node "$PGDIR/start3.mjs" >> "$LOG" 2>&1 < /dev/null &+for i in $(seq 1 150); do+ [ -f "$PGDIR/ready3.marker" ] && break+ sleep 1+done+[ -f "$PGDIR/ready3.marker" ] || { echo "PG FAILED"; tail -25 "$LOG"; exit 1; }+echo "PG up on 5433"++echo "── 2. migrate deploy (Wave 3 = no new migrations; must be a no-op) ──"+npx prisma migrate deploy 2>&1 | tail -3 | tee -a "$LOG"++echo "── 3. seed (366 templates) ──────────────────────────"+npx tsx prisma/seed.ts 2>&1 | grep -E "Seeding|Done" | tee -a "$LOG"++echo "── 4. dev server ────────────────────────────────────"+pkill -f 'next dev -p 3000' 2>/dev/null || true+sleep 1+# CANVIX_RATE_LIMITS=off — the wave3 suite registers/logs in several+# accounts; the sandbox IP budget (5/h) is reserved for production.+setsid nohup env CANVIX_RATE_LIMITS=off npx next dev -p 3000 > /tmp/pgembed/dev-w3.log 2>&1 < /dev/null &+for i in $(seq 1 150); do+ if curl -sf http://localhost:3000/api/health >/dev/null 2>&1; then break; fi+ sleep 1+done+curl -sf http://localhost:3000/api/health >/dev/null || { echo "DEV FAILED"; tail -30 /tmp/pgembed/dev-w3.log; exit 1; }+echo "dev up"++echo "── 5. API spot-checks ───────────────────────────────"+HEALTH=$(curl -sf http://localhost:3000/api/health)+echo "health: $HEALTH"+echo "GET /api/templates → $(curl -sf http://localhost:3000/api/templates | node -e "let d='';process.stdin.on('data',(c)=>d+=c).on('end',()=>console.log(JSON.parse(d).length+' templates'))")"++echo "── 6. playwright e2e (wave3 + smoke) ────────────────"+BASE_URL=http://localhost:3000 npx playwright test tests/e2e/wave3-editor-depth.spec.ts tests/e2e/smoke.spec.ts 2>&1 | tail -25++echo "── done ─────────────────────────────────────────────"diff --git a/src/components/editor/Editor.tsx b/src/components/editor/Editor.tsxindex 17e2620..d50b741 100644--- a/src/components/editor/Editor.tsx+++ b/src/components/editor/Editor.tsx@@ -12,6 +12,7 @@ import { ContextToolbar } from './PropertiesBar'import { PageBar } from './PageBar'import { ZoomControls } from './ZoomControls'import { PreviewOverlay } from './PreviewOverlay'+import { PresenterOverlay } from './PresenterOverlay'import { TemplatesPanel } from './panels/TemplatesPanel'import { ElementsPanel } from './panels/ElementsPanel'import { TextPanel } from './panels/TextPanel'@@ -580,6 +581,8 @@ export default function Editor() {)}<PreviewOverlay />+ {/* v0.18 (Wave 3): present with speaker notes */}+ <PresenterOverlay />{/* v0.3.1: image crop dialog */}{cropElement && (diff --git a/src/components/editor/PageBar.tsx b/src/components/editor/PageBar.tsxindex e62e023..4e4410a 100644--- a/src/components/editor/PageBar.tsx+++ b/src/components/editor/PageBar.tsx@@ -1,8 +1,10 @@'use client'-import { Plus, Copy, Trash2 } from 'lucide-react'+import { useState } from 'react'+import { Plus, Copy, Trash2, NotebookPen, Scaling, Check, RotateCcw } from 'lucide-react'import { useEditorStore } from '@/store/editor-store'import { DesignPreview } from '@/components/design-preview'+import { pageSize, PRESET_SIZES } from '@/lib/editor-utils'import { cn } from '@/lib/utils'const THUMB_H = 52@@ -14,54 +16,97 @@ export function PageBar() {const addPage = useEditorStore((s) => s.addPage)const duplicatePage = useEditorStore((s) => s.duplicatePage)const deletePage = useEditorStore((s) => s.deletePage)+ const resizePage = useEditorStore((s) => s.resizePage)+ const setPageNotes = useEditorStore((s) => s.setPageNotes)const width = useEditorStore((s) => s.width)const height = useEditorStore((s) => s.height)- const thumbW = Math.max(28, THUMB_H * (width / height))+ /** v0.18 (Wave 3): notes + per-page resize popovers (one at a time) */+ const [notesOpen, setNotesOpen] = useState(false)+ const [resizeOpen, setResizeOpen] = useState(false)+ const [sizeDraft, setSizeDraft] = useState<{ w: string; h: string } | null>(null)++ const page = pages[currentPage]+ const current = pageSize(page, width, height)++ const openResize = () => {+ setSizeDraft({ w: String(current.width), h: String(current.height) })+ setResizeOpen(true)+ setNotesOpen(false)+ }++ const applyResize = () => {+ if (!sizeDraft || !page) return+ const w = Math.round(Number(sizeDraft.w))+ const h = Math.round(Number(sizeDraft.h))+ if (Number.isFinite(w) && Number.isFinite(h) && w >= 32 && h >= 32 && w <= 8000 && h <= 8000) {+ resizePage(page.id, w, h)+ }+ setResizeOpen(false)+ }++ const resetPageSize = () => {+ if (!page) return+ resizePage(page.id, width, height)+ setResizeOpen(false)+ }return (<div className="absolute bottom-3 left-3 z-30 flex items-end gap-2 max-w-[calc(100%-130px)]"><div className="flex items-end gap-1.5 overflow-x-auto cv-scroll pb-1">- {pages.map((p, i) => (- <div key={p.id} className="group relative shrink-0">- <button- onClick={() => setCurrentPage(i)}- className={cn(- 'block rounded-md overflow-hidden border-2 transition-all bg-white shadow-md',- i === currentPage ? 'border-[#02C0CC]' : 'border-white/20 hover:border-white/45'- )}- style={{ height: THUMB_H, width: thumbW }}- aria-label={`Go to page ${i + 1}`}- >- <div className="w-full h-full">- <DesignPreview page={p} width={width} height={height} />- </div>- </button>- <span className="absolute -top-1.5 -left-1.5 h-4 min-w-4 px-0.5 rounded-full bg-[#7630D7] text-white text-[9px] font-bold flex items-center justify-center shadow">- {i + 1}- </span>- {pages.length > 1 && (- <div className="absolute top-1 right-1 hidden group-hover:flex gap-0.5">- <button- className="h-5 w-5 rounded bg-black/55 text-white flex items-center justify-center hover:bg-black/80"- onClick={() => duplicatePage(i)}- title="Duplicate page"- aria-label="Duplicate page"+ {pages.map((p, i) => {+ // v0.18 (Wave 3): thumbnails honour per-page sizes+ const ps = pageSize(p, width, height)+ const thumbW = Math.max(28, THUMB_H * (ps.width / ps.height))+ return (+ <div key={p.id} className="group relative shrink-0">+ <button+ onClick={() => setCurrentPage(i)}+ className={cn(+ 'block rounded-md overflow-hidden border-2 transition-all bg-white shadow-md',+ i === currentPage ? 'border-[#02C0CC]' : 'border-white/20 hover:border-white/45'+ )}+ style={{ height: THUMB_H, width: thumbW }}+ aria-label={`Go to page ${i + 1}`}+ >+ <div className="w-full h-full">+ <DesignPreview page={p} width={ps.width} height={ps.height} />+ </div>+ </button>+ <span className="absolute -top-1.5 -left-1.5 h-4 min-w-4 px-0.5 rounded-full bg-[#7630D7] text-white text-[9px] font-bold flex items-center justify-center shadow">+ {i + 1}+ </span>+ {i === currentPage && p.notes ? (+ <span+ className="absolute -bottom-1.5 -right-1.5 h-4 w-4 rounded-full bg-[#02C0CC] text-white flex items-center justify-center shadow"+ title="This page has speaker notes">- <Copy size={10} />- </button>- <button- className="h-5 w-5 rounded bg-black/55 text-white flex items-center justify-center hover:bg-red-600"- onClick={() => deletePage(i)}- title="Delete page"- aria-label="Delete page"- >- <Trash2 size={10} />- </button>- </div>- )}- </div>- ))}+ <NotebookPen size={9} />+ </span>+ ) : null}+ {pages.length > 1 && (+ <div className="absolute top-1 right-1 hidden group-hover:flex gap-0.5">+ <button+ className="h-5 w-5 rounded bg-black/55 text-white flex items-center justify-center hover:bg-black/80"+ onClick={() => duplicatePage(i)}+ title="Duplicate page"+ aria-label="Duplicate page"+ >+ <Copy size={10} />+ </button>+ <button+ className="h-5 w-5 rounded bg-black/55 text-white flex items-center justify-center hover:bg-red-600"+ onClick={() => deletePage(i)}+ title="Delete page"+ aria-label="Delete page"+ >+ <Trash2 size={10} />+ </button>+ </div>+ )}+ </div>+ )+ })}</div><buttononClick={addPage}@@ -71,6 +116,128 @@ export function PageBar() {><Plus size={16} /></button>++ {/* v0.18 (Wave 3): speaker notes for the current page */}+ <div className="relative shrink-0">+ <button+ onClick={() => { setNotesOpen((v) => !v); setResizeOpen(false) }}+ className={cn(+ 'h-9 w-9 rounded-lg border text-white/60 hover:border-[#02C0CC] hover:text-[#02C0CC] flex items-center justify-center bg-white/[0.06] transition-colors',+ notesOpen ? 'border-[#02C0CC] text-[#02C0CC]' : 'border-white/15',+ page?.notes ? 'text-[#02C0CC]' : ''+ )}+ title="Speaker notes"+ aria-label="Speaker notes"+ aria-expanded={notesOpen}+ >+ <NotebookPen size={15} />+ </button>+ {notesOpen && page && (+ <div className="absolute bottom-11 left-0 w-72 rounded-xl bg-[#16181D] border border-white/10 shadow-2xl p-3" data-testid="notes-popover">+ <div className="text-[11px] font-semibold uppercase tracking-wide text-white/50 mb-2">+ Notes — page {currentPage + 1}+ </div>+ <textarea+ value={page.notes ?? ''}+ onChange={(e) => setPageNotes(page.id, e.target.value)}+ placeholder="Type speaker notes…"+ data-testid="notes-textarea"+ className="w-full h-28 resize-none rounded-lg bg-black/30 border border-white/10 px-2.5 py-2 text-[13px] text-white/85 placeholder:text-white/30 focus:outline-none focus:border-[#02C0CC]"+ />+ <div className="text-[11px] text-white/40 mt-1.5">+ Shown in presenter view — never on the canvas or in exports.+ </div>+ </div>+ )}+ </div>++ {/* v0.18 (Wave 3): per-page size */}+ <div className="relative shrink-0">+ <button+ onClick={() => (resizeOpen ? setResizeOpen(false) : openResize())}+ className={cn(+ 'h-9 px-2.5 rounded-lg border text-white/60 hover:border-[#02C0CC] hover:text-[#02C0CC] flex items-center gap-1.5 bg-white/[0.06] transition-colors',+ resizeOpen ? 'border-[#02C0CC] text-[#02C0CC]' : 'border-white/15'+ )}+ title="Resize this page"+ aria-label="Resize this page"+ aria-expanded={resizeOpen}+ data-testid="page-size-button"+ >+ <Scaling size={14} />+ <span className="text-[11px] tabular-nums">+ {current.width}×{current.height}+ </span>+ {page?.width && page?.height ? <span className="w-1.5 h-1.5 rounded-full bg-[#FFB84C]" title="Custom page size" /> : null}+ </button>+ {resizeOpen && sizeDraft && page && (+ <div className="absolute bottom-11 left-0 w-72 rounded-xl bg-[#16181D] border border-white/10 shadow-2xl p-3" data-testid="page-size-popover">+ <div className="text-[11px] font-semibold uppercase tracking-wide text-white/50 mb-2">+ Page {currentPage + 1} size+ </div>+ <div className="flex items-center gap-2 mb-2">+ <label className="flex items-center gap-1.5 flex-1">+ <span className="text-xs text-white/50">W</span>+ <input+ inputMode="numeric"+ value={sizeDraft.w}+ onChange={(e) => setSizeDraft({ ...sizeDraft, w: e.target.value.replace(/[^0-9]/g, '') })}+ className="w-full h-8 rounded-lg bg-black/30 border border-white/10 px-2 text-[13px] text-white focus:outline-none focus:border-[#02C0CC]"+ data-testid="page-size-w"+ />+ </label>+ <span className="text-white/30">×</span>+ <label className="flex items-center gap-1.5 flex-1">+ <span className="text-xs text-white/50">H</span>+ <input+ inputMode="numeric"+ value={sizeDraft.h}+ onChange={(e) => setSizeDraft({ ...sizeDraft, h: e.target.value.replace(/[^0-9]/g, '') })}+ className="w-full h-8 rounded-lg bg-black/30 border border-white/10 px-2 text-[13px] text-white focus:outline-none focus:border-[#02C0CC]"+ data-testid="page-size-h"+ />+ </label>+ </div>+ <div className="grid grid-cols-3 gap-1.5 mb-2">+ {PRESET_SIZES.slice(0, 6).map((p) => (+ <button+ key={p.name}+ onClick={() => setSizeDraft({ w: String(p.width), h: String(p.height) })}+ className={cn(+ 'h-7 rounded-lg text-[10.5px] leading-tight border transition-colors',+ sizeDraft.w === String(p.width) && sizeDraft.h === String(p.height)+ ? 'border-[#02C0CC] text-[#02C0CC] bg-[#02C0CC]/10'+ : 'border-white/10 text-white/60 hover:border-white/30'+ )}+ >+ {p.name}+ </button>+ ))}+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={applyResize}+ className="flex-1 h-8 rounded-lg bg-[#02C0CC] text-[#0B0C10] text-xs font-semibold flex items-center justify-center gap-1 hover:bg-[#02C0CC]/85"+ data-testid="page-size-apply"+ >+ <Check size={13} /> Apply+ </button>+ {page.width || page.height ? (+ <button+ onClick={resetPageSize}+ className="h-8 px-2.5 rounded-lg border border-white/15 text-white/60 text-xs flex items-center gap-1 hover:border-white/35"+ title="Back to the design size"+ >+ <RotateCcw size={12} /> Reset+ </button>+ ) : null}+ </div>+ <div className="text-[11px] text-white/40 mt-1.5">+ Applies to this page only — other pages keep their size.+ </div>+ </div>+ )}+ </div></div>)}diff --git a/src/components/editor/PresenterOverlay.tsx b/src/components/editor/PresenterOverlay.tsxnew file mode 100644index 0000000..4eb7923--- /dev/null+++ b/src/components/editor/PresenterOverlay.tsx@@ -0,0 +1,208 @@+'use client'++import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import dynamic from 'next/dynamic'+import { ChevronLeft, ChevronRight, Maximize2, NotebookPen, Timer, X } from 'lucide-react'+import { useEditorStore } from '@/store/editor-store'+import { Button } from '@/components/ui/button'+import { cn } from '@/lib/utils'+import { pageSize } from '@/lib/editor-utils'++const PreviewStage = dynamic(() => import('./canvas/preview-stage'), { ssr: false })++function formatElapsed(ms: number): string {+ const s = Math.floor(ms / 1000)+ const m = Math.floor(s / 60)+ return `${m}:${String(s % 60).padStart(2, '0')}`+}++/**+ * v0.18 (Wave 3) — Canva-style "Present with notes": the current page+ * large, the next page as a thumbnail, speaker notes editable live,+ * and an elapsed timer. Pure presentation chrome — the notes never+ * render on the canvas or in exports (PageData.notes).+ *+ * The outer component only gates on `presentOpen`; the inner one mounts+ * fresh per session so the page index + timer start clean with no+ * reset effects.+ */+export function PresenterOverlay() {+ const open = useEditorStore((s) => s.presentOpen)+ if (!open) return null+ return <PresenterOverlayInner key="presenter" />+}++function PresenterOverlayInner() {+ const setOpen = useEditorStore((s) => s.setPresentOpen)+ const pages = useEditorStore((s) => s.pages)+ const width = useEditorStore((s) => s.width)+ const height = useEditorStore((s) => s.height)+ const readOnly = useEditorStore((s) => s.readOnly)+ const [index, setIndex] = useState(0)+ const [notesOpen, setNotesOpen] = useState(true)+ const [elapsed, setElapsed] = useState(0)+ const [running, setRunning] = useState(true)+ const startedAt = useRef<number>(Date.now())++ const safeIndex = Math.max(0, Math.min(index, pages.length - 1))+ const page = pages[safeIndex]+ const nextPage = pages[safeIndex + 1]+ const { width: pw, height: ph } = useMemo(+ () => pageSize(page, width, height),+ [page, width, height]+ )++ const goTo = useCallback(+ (next: number) => setIndex(Math.max(0, Math.min(next, pages.length - 1))),+ [pages.length]+ )+ const next = useCallback(() => goTo(safeIndex + 1), [goTo, safeIndex])+ const prev = useCallback(() => goTo(safeIndex - 1), [goTo, safeIndex])++ // keyboard+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') setOpen(false)+ if (e.key === 'ArrowRight' || e.key === ' ') { e.preventDefault(); next() }+ if (e.key === 'ArrowLeft') { e.preventDefault(); prev() }+ if (e.key.toLowerCase() === 'n') setNotesOpen((v) => !v)+ }+ window.addEventListener('keydown', onKey)+ return () => window.removeEventListener('keydown', onKey)+ }, [next, prev, setOpen])++ // elapsed timer (pausable — setState lives in the interval callback)+ useEffect(() => {+ if (!running) return+ const t = setInterval(() => setElapsed(Date.now() - startedAt.current), 500)+ return () => clearInterval(t)+ }, [running])++ const notes = page?.notes ?? ''+ const onNotesChange = (value: string) => {+ if (readOnly || !page) return+ useEditorStore.getState().setPageNotes(page.id, value)+ }++ return (+ <div className="fixed inset-0 z-[100] bg-[#0B0C10] flex flex-col" role="dialog" aria-label="Presenter view">+ {/* top bar */}+ <div className="h-12 flex items-center justify-between px-3 shrink-0 border-b border-white/10">+ <div className="flex items-center gap-2 text-sm font-semibold text-white/90 px-2">+ <NotebookPen size={15} className="text-[#02C0CC]" />+ Presenter+ <span className="text-white/50 font-normal">+ — page {safeIndex + 1} of {pages.length}+ </span>+ </div>+ <div className="flex items-center gap-1">+ <button+ onClick={() => setRunning((r) => !r)}+ className="flex items-center gap-1.5 h-8 px-2.5 rounded-lg text-xs text-white/70 hover:bg-white/10 hover:text-white transition-colors"+ title={running ? 'Pause timer' : 'Resume timer'}+ >+ <Timer size={14} />+ <span className="tabular-nums">{running ? formatElapsed(elapsed) : formatElapsed(elapsed) + ' ⏸'}</span>+ </button>+ <Button+ variant="ghost"+ size="icon"+ className={cn('rounded-full text-white hover:bg-white/15 hover:text-white', notesOpen && 'bg-white/15 text-[#02C0CC]')}+ onClick={() => setNotesOpen((v) => !v)}+ aria-label="Toggle notes"+ title="Notes (N)"+ >+ <NotebookPen size={17} />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className="rounded-full text-white hover:bg-white/15 hover:text-white"+ onClick={() => {+ if (document.fullscreenElement) void document.exitFullscreen()+ else void document.documentElement.requestFullscreen()+ }}+ aria-label="Fullscreen"+ title="Fullscreen"+ >+ <Maximize2 size={17} />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className="rounded-full text-white hover:bg-white/15 hover:text-white"+ onClick={() => setOpen(false)}+ aria-label="Close presenter view"+ >+ <X size={19} />+ </Button>+ </div>+ </div>++ <div className="flex-1 min-h-0 flex">+ {/* stage */}+ <div className="flex-1 min-w-0 relative p-4">+ <div className="relative w-full h-full max-w-[min(100%,calc((100vh-8rem)*var(--ar)))] mx-auto" style={{ ['--ar' as string]: `${pw / ph}` }}>+ {page && <PreviewStage page={page} designWidth={width} designHeight={height} animated reduceMotion={false} />}+ </div>+ {pages.length > 1 && (+ <>+ <button+ onClick={prev}+ disabled={safeIndex === 0}+ className="absolute left-3 top-1/2 -translate-y-1/2 w-11 h-11 rounded-full bg-[#16171D]/90 text-white flex items-center justify-center hover:bg-[#7630D7] transition-colors disabled:opacity-30"+ aria-label="Previous page"+ >+ <ChevronLeft size={22} />+ </button>+ <button+ onClick={next}+ disabled={safeIndex === pages.length - 1}+ className="absolute right-3 top-1/2 -translate-y-1/2 w-11 h-11 rounded-full bg-[#16171D]/90 text-white flex items-center justify-center hover:bg-[#7630D7] transition-colors disabled:opacity-30"+ aria-label="Next page"+ >+ <ChevronRight size={22} />+ </button>+ </>+ )}+ </div>++ {/* notes sidebar */}+ {notesOpen && (+ <aside className="w-[340px] shrink-0 border-l border-white/10 flex flex-col bg-[#0F1015]">+ <div className="px-4 pt-4 pb-2 text-xs font-semibold uppercase tracking-wide text-white/50">+ Speaker notes+ </div>+ <textarea+ value={notes}+ onChange={(e) => onNotesChange(e.target.value)}+ readOnly={readOnly}+ placeholder={readOnly ? 'View-only design — notes are read-only.' : 'Type notes for this page…'}+ data-testid="presenter-notes"+ className="flex-1 min-h-0 resize-none bg-transparent px-4 pb-4 text-sm leading-relaxed text-white/85 placeholder:text-white/30 focus:outline-none"+ />+ {nextPage && (+ <div className="p-3 border-t border-white/10">+ <div className="text-[11px] font-semibold uppercase tracking-wide text-white/45 mb-2">+ Next up+ </div>+ <button+ onClick={() => goTo(safeIndex + 1)}+ className="block w-full rounded-lg overflow-hidden ring-1 ring-white/15 hover:ring-[#02C0CC] transition-all"+ aria-label="Jump to next page"+ >+ <div+ className="relative bg-white"+ style={{ aspectRatio: `${pageSize(nextPage, width, height).width} / ${pageSize(nextPage, width, height).height}` }}+ >+ <PreviewStage page={nextPage} designWidth={width} designHeight={height} animated={false} />+ </div>+ </button>+ </div>+ )}+ </aside>+ )}+ </div>+ </div>+ )+}diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsxindex fcc1160..a37736c 100644--- a/src/components/editor/PropertiesBar.tsx+++ b/src/components/editor/PropertiesBar.tsx@@ -11,7 +11,7 @@ import {FlipHorizontal, FlipVertical, Sun, Contrast, Palette, RotateCcw, Replace, Lock, LockOpen,Layers, SquareDashed, Crop, Spline, Table2, Rows3, Columns3, Trash, Upload, ExternalLink,Music, Film, Play, Repeat, Volume2, VolumeX, SlidersHorizontal, Activity, Puzzle, LayoutGrid, Wand2,- BarChart3, LineChart, PieChart, ScatterChart,+ BarChart3, LineChart, PieChart, ScatterChart, List, ListOrdered, Languages, Shrink, Hexagon, Shapes,} from 'lucide-react'import { useEditorStore, selectedElements, currentPageData } from '@/store/editor-store'import type { AudioElement, ChartElement, ChartSeries, EmbedElement, FrameElement, ImageElement, LineElement, PluginElement, ShapeElement, StickerElement, TableElement, TextElement, VideoElement, AnyElement, FrameShape, ChartKind } from '@/lib/types'@@ -26,6 +26,7 @@ import { normalizeSpans } from '@/lib/rich-text'import { FontDropdown } from './toolbar/FontDropdown'import { ColorMenu } from './toolbar/ColorMenu'import { IMAGE_FILTER_PRESETS, applyPresetToImageData, isImageFilterId, clampFilterIntensity } from '@/lib/image-filters'+import { MASK_SHAPES, MASK_SHAPE_LABELS, isMaskShape, maskPolygon } from '@/lib/shapes'import { useLoadedImage } from './canvas/use-loaded-image'import { ToolbarPopover, SliderRow, IconTile } from './toolbar/popover-kit'import { BgRemoverButton, MagicEraserPopover, EnhanceButton } from './ImageAI'@@ -63,7 +64,7 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'mconst first = sel[0]const isMulti = sel.length > 1const text = first.type === 'text' ? (first as TextElement) : null- const shape = ['rect', 'ellipse', 'triangle', 'star', 'path'].includes(first.type) ? (first as ShapeElement) : null+ const shape = ['rect', 'ellipse', 'triangle', 'star', 'polygon', 'path'].includes(first.type) ? (first as ShapeElement) : nullconst line = first.type === 'line' ? (first as LineElement) : nullconst image = first.type === 'image' ? (first as ImageElement) : nullconst sticker = first.type === 'sticker' ? (first as StickerElement) : null@@ -213,6 +214,47 @@ 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.18 (Wave 3): list + direction + auto-fit */}+ <ToolbarPopover+ width={228}+ trigger={(open) => (+ <button className="cv-tbtn" data-active={open || !!text.listStyle || !!text.autoFit} aria-label="List and fit options" title="List & auto-fit">+ <List size={14} />+ </button>+ )}+ >+ <div className="text-[12px] font-bold text-white/90 mb-1.5">List style</div>+ <div className="flex gap-1 mb-2.5">+ <TBtn onClick={() => update(ids, { listStyle: 'none' })} dataActive={!text.listStyle || text.listStyle === 'none'} title="No list" ariaLabel="No list">+ <List size={13} className="opacity-40 line-through" />+ </TBtn>+ <TBtn onClick={() => update(ids, { listStyle: 'bullet' })} dataActive={text.listStyle === 'bullet'} title="Bulleted list" ariaLabel="Bulleted list" data-testid="list-bullet">+ <List size={13} />+ </TBtn>+ <TBtn onClick={() => update(ids, { listStyle: 'number' })} dataActive={text.listStyle === 'number'} title="Numbered list" ariaLabel="Numbered list" data-testid="list-number">+ <ListOrdered size={13} />+ </TBtn>+ </div>+ <div className="text-[12px] font-bold text-white/90 mb-1.5">Direction</div>+ <div className="flex gap-1 mb-2.5">+ <TBtn onClick={() => update(ids, { direction: 'ltr' })} dataActive={text.direction !== 'rtl'} title="Left to right" ariaLabel="Left to right">+ <span className="text-[11px] font-semibold px-1">LTR</span>+ </TBtn>+ <TBtn onClick={() => update(ids, { direction: 'rtl' })} dataActive={text.direction === 'rtl'} title="Right to left (Arabic, Hebrew…)" ariaLabel="Right to left" data-testid="dir-rtl">+ <Languages size={13} />+ </TBtn>+ </div>+ <label className="flex items-center justify-between text-[12px] text-white/80 mb-1 cursor-pointer" data-testid="autofit-toggle">+ <span className="flex items-center gap-1.5">+ <Shrink size={13} /> Auto-fit+ </span>+ <input type="checkbox" checked={!!text.autoFit} onChange={(e) => update(ids, { autoFit: e.target.checked })} className="accent-[#7630D7]" />+ </label>+ <div className="text-[11px] text-white/40 leading-snug">+ Shrinks the font so the text fits its box — never grows past the set size.+ </div>+ </ToolbarPopover>+{/* v0.6: curved text (canva “Curve”) */}<ToolbarPopoverwidth={228}@@ -311,6 +353,44 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm<SliderRow label="Width" value={shape.strokeWidth} min={0} max={40} step={1} onChange={(v) => updateLive(ids, { strokeWidth: v })} onCommit={() => update(ids, { strokeWidth: shape.strokeWidth })} />{shape.type === 'rect' && <SliderRow label="Corner radius" value={shape.cornerRadius} min={0} max={Math.round(shape.width / 2)} step={1} onChange={(v) => updateLive(ids, { cornerRadius: v })} onCommit={() => update(ids, { cornerRadius: shape.cornerRadius })} />}</ToolbarPopover>+ {/* v0.18 (Wave 3): parametric polygon / star controls */}+ {(shape.type === 'polygon' || shape.type === 'star') && (+ <ToolbarPopover+ width={228}+ trigger={(open) => (+ <button className="cv-tbtn gap-1 !px-2.5" data-active={open} aria-label="Shape properties" title="Shape properties">+ {shape.type === 'polygon' ? <Hexagon size={14} /> : <Shapes size={14} />}+ <span className="text-[12px] hidden lg:inline">Shape</span>+ </button>+ )}+ >+ <div className="text-[12px] font-bold text-white/90 mb-1.5">+ {shape.type === 'polygon' ? 'Polygon' : 'Star'}+ </div>+ <SliderRow+ label={shape.type === 'polygon' ? 'Sides' : 'Points'}+ value={shape.type === 'polygon' ? (shape.sides ?? 6) : (shape.numPoints ?? 5)}+ min={3}+ max={shape.type === 'polygon' ? 12 : 16}+ step={1}+ onChange={(v) => updateLive(ids, shape.type === 'polygon' ? { sides: Math.round(v) } : { numPoints: Math.round(v) })}+ onCommit={() => update(ids, shape.type === 'polygon' ? { sides: shape.sides ?? 6 } : { numPoints: shape.numPoints ?? 5 })}+ format={(v) => String(Math.round(v))}+ />+ {shape.type === 'star' && (+ <SliderRow+ label="Spike ratio"+ value={shape.innerRatio ?? 0.55}+ min={0.15}+ max={0.85}+ step={0.05}+ onChange={(v) => updateLive(ids, { innerRatio: v })}+ onCommit={() => update(ids, { innerRatio: shape.innerRatio ?? 0.55 })}+ format={(v) => v.toFixed(2)}+ />+ )}+ </ToolbarPopover>+ )}</>)}{line && (@@ -359,6 +439,8 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm<TBtn onClick={() => state.openCrop(image.id)} title="Crop image" ariaLabel="Crop image"><Crop size={14} /></TBtn>+ {/* v0.18 (Wave 3): shape masks */}+ <MaskPopover el={image} ids={ids} /><ImageAdjustPopover el={image} ids={ids} />{/* v0.4 Canva AI image tools */}<BgRemoverButton el={image} />@@ -838,7 +920,94 @@ function PositionPopover({ ids, count, element }: { ids: string[]; count: number)}-/** image adjustments popover (canva "Edit image" lite) */+/** v0.18 (Wave 3): one mask option's silhouette — the polygon scaled+ * into a 34×34 chip (pure SVG, same geometry as the canvas clip). */+function MaskThumb({ shape, sides, innerRatio, active }: { shape: string; sides?: number; innerRatio?: number; active?: boolean }) {+ const pts = isMaskShape(shape) && shape !== 'none' ? maskPolygon(shape, sides, innerRatio) : null+ return (+ <svg viewBox="0 0 100 100" className="w-full h-full" aria-hidden="true">+ {pts ? (+ <polygon+ points={pts.map(([x, y]) => `${x},${y}`).join(' ')}+ fill={active ? '#02C0CC33' : '#FFFFFF22'}+ stroke={active ? '#02C0CC' : '#FFFFFF66'}+ strokeWidth={4}+ />+ ) : (+ <rect x={10} y={10} width={80} height={80} rx={10} fill="none" stroke={active ? '#02C0CC' : '#FFFFFF66'} strokeWidth={4} strokeDasharray="10 8" />+ )}+ </svg>+ )+}++/** v0.18 (Wave 3): image shape-mask picker — 10 presets + parametric+ * polygon / starburst. Writes maskShape/maskSides/maskInnerRatio onto+ * the element (validated on render by isMaskShape — hostile pastes+ * degrade to 'none'). */+function MaskPopover({ el, ids }: { el: ImageElement; ids: string[] }) {+ const update = useEditorStore((s) => s.updateElements)+ const updateLive = useEditorStore((s) => s.updateElementsLive)+ const current = isMaskShape(el.maskShape) ? el.maskShape : 'none'+ return (+ <ToolbarPopover+ width={244}+ trigger={(open) => (+ <button className="cv-tbtn gap-1 !px-2.5" data-active={open || (current !== 'none' && !!current)} aria-label="Image mask" title="Mask shape">+ <Shapes size={14} /> <span className="text-[12px] hidden lg:inline">Mask</span>+ </button>+ )}+ >+ <div className="text-[12px] font-bold text-white/90 mb-1.5">Mask shape</div>+ <div className="grid grid-cols-4 gap-1.5" data-testid="mask-grid">+ {MASK_SHAPES.map((m) => (+ <button+ key={m}+ onClick={() => update(ids, { maskShape: m })}+ data-testid={`mask-${m}`}+ title={MASK_SHAPE_LABELS[m]}+ aria-label={MASK_SHAPE_LABELS[m]}+ className={cn(+ 'h-[38px] rounded-lg border flex items-center justify-center p-1 transition-colors',+ current === m ? 'border-[#02C0CC] bg-[#02C0CC]/10' : 'border-white/10 hover:border-white/30'+ )}+ >+ <MaskThumb shape={m} sides={el.maskSides} innerRatio={el.maskInnerRatio} active={current === m} />+ </button>+ ))}+ </div>+ {(current === 'poly' || current === 'polyStar') && (+ <div className="mt-2">+ <SliderRow+ label={current === 'poly' ? 'Sides' : 'Points'}+ value={el.maskSides ?? 6}+ min={3}+ max={current === 'poly' ? 12 : 16}+ step={1}+ onChange={(v) => updateLive(ids, { maskSides: Math.round(v) })}+ onCommit={() => update(ids, { maskSides: el.maskSides ?? 6 })}+ format={(v) => String(Math.round(v))}+ />+ {current === 'polyStar' && (+ <SliderRow+ label="Spike ratio"+ value={el.maskInnerRatio ?? 0.55}+ min={0.15}+ max={0.85}+ step={0.05}+ onChange={(v) => updateLive(ids, { maskInnerRatio: v })}+ onCommit={() => update(ids, { maskInnerRatio: el.maskInnerRatio ?? 0.55 })}+ format={(v) => v.toFixed(2)}+ />+ )}+ </div>+ )}+ <div className="text-[11px] text-white/40 leading-snug mt-2">+ Clips the image to the shape — corner radius is ignored while a mask is set.+ </div>+ </ToolbarPopover>+ )+}+function ImageAdjustPopover({ el, ids }: { el: ImageElement; ids: string[] }) {const update = useEditorStore((s) => s.updateElements)const updateLive = useEditorStore((s) => s.updateElementsLive)@@ -988,16 +1157,16 @@ function NumField({ label, value, onCommit, suffix }: { label: string; value: nu)}-function TBtn({ children, onClick, title, ariaLabel, disabled, danger, className, dataActive }: {+function TBtn({ children, onClick, title, ariaLabel, disabled, danger, className, dataActive, ...rest }: {children: React.ReactNodeonClick?: () => voidtitle?: string- ariaLabel: string+ ariaLabel?: stringdisabled?: booleandanger?: booleanclassName?: stringdataActive?: boolean-}) {+} & Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'onClick' | 'title' | 'className' | 'disabled'>) {return (<buttononClick={onClick}@@ -1006,6 +1175,7 @@ function TBtn({ children, onClick, title, ariaLabel, disabled, danger, classNamearia-label={ariaLabel}data-active={dataActive ? 'true' : undefined}className={cn('cv-tbtn', danger && 'hover:bg-[#ff5a5a]/15 hover:text-[#ff8080]', className)}+ {...rest}>{children}</button>diff --git a/src/components/editor/TopBar.tsx b/src/components/editor/TopBar.tsxindex 7617ce7..7e560b1 100644--- a/src/components/editor/TopBar.tsx+++ b/src/components/editor/TopBar.tsx@@ -1,7 +1,7 @@'use client'import { useState } from 'react'-import { Home, MessageCircle, Play, Share2, ChevronDown, Undo2, Redo2, Download, Github, Cloud, Check, Loader2, Ruler, History, Languages, Wand2, Zap, MousePointer2, Brush, Eye, BookMarked } from 'lucide-react'+import { Home, MessageCircle, Play, Presentation, Share2, ChevronDown, Undo2, Redo2, Download, Github, Cloud, Check, Loader2, Ruler, History, Languages, Wand2, Zap, MousePointer2, Brush, Eye, BookMarked } from 'lucide-react'import { useAppStore } from '@/store/app-store'import { useEditorStore } from '@/store/editor-store'import { interactionMode } from '@/lib/editor-utils'@@ -218,6 +218,16 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; o<button className={cn(item, 'hidden sm:flex')} onClick={() => setPreviewOpen(true)} aria-label="Preview design"><Play size={14} /> Preview</button>+ {/* v0.18 (Wave 3): present with speaker notes */}+ <button+ className={cn(item, 'hidden md:flex')}+ onClick={() => useEditorStore.getState().setPresentOpen(true)}+ aria-label="Present with speaker notes"+ title="Present with speaker notes"+ data-testid="present-notes-button"+ >+ <Presentation size={14} /> Present+ </button><Button size="sm" className="btn-cv-white h-10 px-4 sm:px-5 gap-1.5 font-semibold" onClick={() => setShareOpen(true)}><Share2 size={15} /> <span className="hidden sm:inline">Share</span></Button>diff --git a/src/components/editor/ZoomControls.tsx b/src/components/editor/ZoomControls.tsxindex 21dd691..6c6a9de 100644--- a/src/components/editor/ZoomControls.tsx+++ b/src/components/editor/ZoomControls.tsx@@ -1,7 +1,7 @@'use client'import { useState } from 'react'-import { ZoomIn, ZoomOut, Maximize, Check, ChevronsUpDown, Scan } from 'lucide-react'+import { ZoomIn, ZoomOut, Maximize, Check, ChevronsUpDown, Scan, Grid3x3, Magnet } from 'lucide-react'import { useEditorStore } from '@/store/editor-store'import { canvasBridge } from './canvas/canvas-bridge'import { cn } from '@/lib/utils'@@ -15,6 +15,13 @@ export function ZoomControls() {const zoomOut = useEditorStore((s) => s.zoomOut)const setZoom = useEditorStore((s) => s.setZoom)const fitToScreen = useEditorStore((s) => s.fitToScreen)+ // v0.18 (Wave 3): grid overlay + snap-to-grid+ const showGrid = useEditorStore((s) => s.showGrid)+ const setShowGrid = useEditorStore((s) => s.setShowGrid)+ const snapToGrid = useEditorStore((s) => s.snapToGrid)+ const setSnapToGrid = useEditorStore((s) => s.setSnapToGrid)+ const gridSize = useEditorStore((s) => s.gridSize)+ const setGridSize = useEditorStore((s) => s.setGridSize)const [open, setOpen] = useState(false)const percent = Math.round(zoom * 100)@@ -68,6 +75,52 @@ export function ZoomControls() {><Maximize size={16} /></button>+ {/* v0.18 (Wave 3): grid overlay toggle */}+ <button+ className={cn(+ 'h-10 w-10 rounded-xl flex items-center justify-center hover:bg-white/10 hover:text-white',+ showGrid ? 'text-[#02C0CC] bg-white/10' : 'text-white/75'+ )}+ onClick={() => setShowGrid(!showGrid)}+ aria-label="Toggle grid"+ aria-pressed={showGrid}+ title="Grid overlay"+ data-testid="grid-toggle"+ >+ <Grid3x3 size={16} />+ </button>+ {/* v0.18 (Wave 3): snap to grid (visible when grid is on) */}+ {showGrid && (+ <button+ className={cn(+ 'h-10 w-10 rounded-xl flex items-center justify-center hover:bg-white/10 hover:text-white',+ snapToGrid ? 'text-[#02C0CC] bg-white/10' : 'text-white/75'+ )}+ onClick={() => setSnapToGrid(!snapToGrid)}+ aria-label="Snap to grid"+ aria-pressed={snapToGrid}+ title="Snap to grid"+ data-testid="snap-toggle"+ >+ <Magnet size={15} />+ </button>+ )}+ {showGrid && (+ <select+ value={gridSize}+ onChange={(e) => setGridSize(Number(e.target.value))}+ className="h-8 rounded-lg bg-black/30 border border-white/10 text-[12px] text-white/80 px-1.5 focus:outline-none focus:border-[#02C0CC]"+ aria-label="Grid size"+ title="Grid size"+ data-testid="grid-size"+ >+ {[10, 20, 40, 80, 120].map((g) => (+ <option key={g} value={g}>+ {g}px+ </option>+ ))}+ </select>+ )}{open && (<>diff --git a/src/components/editor/add-element.ts b/src/components/editor/add-element.tsindex ba9b923..0b079d5 100644--- a/src/components/editor/add-element.ts+++ b/src/components/editor/add-element.ts@@ -63,6 +63,17 @@ export function addShape(kind: 'rect' | 'rounded' | 'ellipse' | 'triangle' | 'stelse addCentered(createShapeElement('star', { width: size, height: size }))}+/** v0.18 (Wave 3): native parametric polygon — sides 3..12, editable+ * from the properties bar after insertion. */+export function addPolygon(sides: number) {+ addCentered(createShapeElement('polygon', { width: 320, height: 320, sides }))+}++/** v0.18 (Wave 3): star variant — points 3..16 + spike ratio. */+export function addStarVariant(numPoints: number, innerRatio?: number) {+ addCentered(createShapeElement('star', { width: 320, height: 320, numPoints, innerRatio }))+}+export function addGraphic(graphicId: string, fill?: string) {const def = GRAPHICS.find((g) => g.id === graphicId)if (!def) returndiff --git a/src/components/editor/canvas/CanvasStage.tsx b/src/components/editor/canvas/CanvasStage.tsxindex c5186e8..7c008d1 100644--- a/src/components/editor/canvas/CanvasStage.tsx+++ b/src/components/editor/canvas/CanvasStage.tsx@@ -5,7 +5,7 @@ import type Konva from 'konva'import { Group, Layer, Line, Rect, Stage, Transformer } from 'react-konva'import type { KonvaEventObject } from 'konva/lib/Node'import { useEditorStore, currentPageData } from '@/store/editor-store'-import { gradientProps, computeSnap, clamp, type GuideLine } from '@/lib/editor-utils'+import { gradientProps, computeSnap, clamp, pageSize, type GuideLine } from '@/lib/editor-utils'import { canvasBridge } from './canvas-bridge'import { ElementNode } from './element-node'import { Rulers } from './rulers'@@ -126,6 +126,18 @@ export default function CanvasStage() {const pinchRef = useRef<{ dist: number; zoom: number; mid: { x: number; y: number }; pan: { x: number; y: number } } | null>(null)const page = currentPageData({ pages, currentPage })+ // v0.18 (Wave 3): grid overlay prefs + per-page size override+ const showGrid = useEditorStore((s) => s.showGrid)+ const gridSize = useEditorStore((s) => s.gridSize)+ const { width: pw, height: ph } = useMemo(() => pageSize(page, width, height), [page, width, height])+ // v0.18 (Wave 3): the grid lines (page px) — memoised so typing doesn't rebuild+ const gridLines = useMemo(() => {+ if (!showGrid) return []+ const lines: Array<{ x1: number; y1: number; x2: number; y2: number }> = []+ for (let x = gridSize; x < pw; x += gridSize) lines.push({ x1: x, y1: 0, x2: x, y2: ph })+ for (let y = gridSize; y < ph; y += gridSize) lines.push({ x1: 0, y1: y, x2: pw, y2: y })+ return lines+ }, [showGrid, gridSize, pw, ph])// ── container size ─────────────────────────────────────────useEffect(() => {@@ -172,18 +184,18 @@ export default function CanvasStage() {const fitToScreen = useCallback(() => {if (containerSize.w < 50 || containerSize.h < 50) returnconst pad = showRulers ? 128 : 100- const z = Math.min((containerSize.w - pad) / width, (containerSize.h - pad) / height, 1.5)+ const z = Math.min((containerSize.w - pad) / pw, (containerSize.h - pad) / ph, 1.5)const clamped = Math.max(0.05, z)setZoom(clamped)prevZoomRef.current = clampedconst centered = {- x: (containerSize.w - width * clamped) / 2,- y: (containerSize.h - height * clamped) / 2,+ x: (containerSize.w - pw * clamped) / 2,+ y: (containerSize.h - ph * clamped) / 2,}prevPanRef.current = centeredsetPan(centered)userZoomedRef.current = false- }, [containerSize, width, height, setZoom, showRulers])+ }, [containerSize, pw, ph, setZoom, showRulers])// fit on mount & on design size change & on resize (if user hasn't zoomed)useEffect(() => {@@ -191,21 +203,21 @@ export default function CanvasStage() {if (userZoomedRef.current) returnconst raf = requestAnimationFrame(() => fitToScreen())return () => cancelAnimationFrame(raf)- }, [containerSize.w, containerSize.h, width, height, fitToScreen])+ }, [containerSize.w, containerSize.h, pw, ph, fitToScreen])// ── bridge registration ────────────────────────────────────useEffect(() => {canvasBridge.stage = stageRef.currentcanvasBridge.layer = layerRef.current- canvasBridge.pageWidth = width- canvasBridge.pageHeight = height+ canvasBridge.pageWidth = pw+ canvasBridge.pageHeight = phcanvasBridge.fitToScreen = fitToScreenreturn () => {canvasBridge.stage = nullcanvasBridge.layer = nullcanvasBridge.fitToScreen = null}- }, [width, height, fitToScreen])+ }, [pw, ph, fitToScreen])// keep bridge pan/zoom freshuseEffect(() => {@@ -264,9 +276,22 @@ export default function CanvasStage() {const el = p.elements.find((e) => e.id === id)if (!el) returnconst rect =- el.type === 'ellipse' || el.type === 'star'+ el.type === 'ellipse' || el.type === 'star' || el.type === 'polygon'? { x: node.x() - el.width / 2, y: node.y() - el.height / 2, width: el.width, height: el.height, rotation: el.rotation }: { x: node.x(), y: node.y(), width: el.width, height: el.height, rotation: el.rotation }+ // v0.18 (Wave 3): snap-to-grid — rounds the drag position to the grid+ // BEFORE element snapping, so element alignment still wins on top+ if (state.snapToGrid && state.gridSize >= 8) {+ const gs = state.gridSize+ const topLeft =+ el.type === 'ellipse' || el.type === 'star' || el.type === 'polygon'+ ? { x: node.x() - el.width / 2, y: node.y() - el.height / 2 }+ : { x: node.x(), y: node.y() }+ const snappedX = Math.round(topLeft.x / gs) * gs+ const snappedY = Math.round(topLeft.y / gs) * gs+ node.x(node.x() + (snappedX - topLeft.x))+ node.y(node.y() + (snappedY - topLeft.y))+ }const others = p.elements.filter((e) => e.id !== id && e.visible).map((e) => ({ x: e.x, y: e.y, width: e.width, height: e.height, rotation: e.rotation }))@@ -281,7 +306,8 @@ export default function CanvasStage() {)}}- const { dx, dy, guides: g } = computeSnap(rect, others, { width: state.width, height: state.height })+ const { width: pageW, height: pageH } = pageSize(p, state.width, state.height)+ const { dx, dy, guides: g } = computeSnap(rect, others, { width: pageW, height: pageH })if (dx !== 0 || dy !== 0) {node.x(node.x() + dx)node.y(node.y() + dy)@@ -451,7 +477,7 @@ export default function CanvasStage() {}const onUp = () => {setDraftGuide(null)- const limit = axis === 'x' ? width : height+ const limit = axis === 'x' ? pw : phif (position > -30 && position < limit + 30) addManualGuide(axis, position)}const onKey = (e: KeyboardEvent) => {@@ -465,7 +491,7 @@ export default function CanvasStage() {window.removeEventListener('mouseup', onUp)window.removeEventListener('keydown', onKey)}- }, [guideDragging, pan, zoom, width, height, addManualGuide])+ }, [guideDragging, pan, zoom, pw, ph, addManualGuide])const beginGuideFromRuler = (axis: 'x' | 'y', pagePos: number) => {if (editingMode !== 'editing' || tool === 'draw') return@@ -478,12 +504,12 @@ export default function CanvasStage() {if (g.axis === 'x') {const nx = node.x()node.x(g.position) // restore; state drives the final position- if (nx < -40 || nx > width + 40) removeManualGuide(g.id)+ if (nx < -40 || nx > pw + 40) removeManualGuide(g.id)else moveManualGuide(g.id, nx)} else {const ny = node.y()node.y(g.position)- if (ny < -40 || ny > height + 40) removeManualGuide(g.id)+ if (ny < -40 || ny > ph + 40) removeManualGuide(g.id)else moveManualGuide(g.id, ny)}}@@ -723,7 +749,7 @@ export default function CanvasStage() {// ── render ─────────────────────────────────────────────────const bg = page.backgroundconst bgProps =- bg.type === 'gradient' ? gradientProps(bg.from, bg.to, bg.angle, width, height) : { fill: bg.color }+ bg.type === 'gradient' ? gradientProps(bg.from, bg.to, bg.angle, pw, ph) : { fill: bg.color }const editingText = editingTextId ? (page.elements.find((e) => e.id === editingTextId) as TextElement | undefined) : undefined@@ -791,6 +817,9 @@ export default function CanvasStage() {letterSpacing: `${editingText.letterSpacing * zoom}px`,color: editingText.fill,textAlign: editingText.align === 'justify' ? 'left' : editingText.align,+ // v0.18 (Wave 3): bidi base direction — the browser applies the+ // Unicode bidi algorithm per the textarea's dir while typing+ direction: editingText.direction === 'rtl' ? 'rtl' : 'ltr',}: null@@ -818,8 +847,12 @@ export default function CanvasStage() {onWheel={handleWheel}><Layer ref={layerRef}>- <Rect x={pan.x} y={pan.y} width={width * zoom} height={height * zoom} {...bgProps} name="page-bg" />+ <Rect x={pan.x} y={pan.y} width={pw * zoom} height={ph * zoom} {...bgProps} name="page-bg" /><Group x={pan.x} y={pan.y} scaleX={zoom} scaleY={zoom}>+ {/* v0.18 (Wave 3): grid overlay — under the elements, never exported */}+ {gridLines.map((l, i) => (+ <Line key={i} points={[l.x1, l.y1, l.x2, l.y2]} stroke="#B3B6C4" strokeWidth={1 / zoom} listening={false} perfectDrawEnabled={false} />+ ))}{page.elements.map((el) => (<ElementNodekey={el.id}@@ -865,9 +898,9 @@ export default function CanvasStage() {{/* snapping guides — canva #9954FF 2px */}{guides.map((g, i) =>g.axis === 'x' ? (- <Rect key={i} x={g.position} y={0} width={2 / zoom} height={height} fill={GUIDE_COLOR} listening={false} />+ <Rect key={i} x={g.position} y={0} width={2 / zoom} height={ph} fill={GUIDE_COLOR} listening={false} />) : (- <Rect key={i} x={0} y={g.position} width={width} height={2 / zoom} fill={GUIDE_COLOR} listening={false} />+ <Rect key={i} x={0} y={g.position} width={pw} height={2 / zoom} fill={GUIDE_COLOR} listening={false} />))}{/* v0.3.1: manual ruler guides — draggable; double-click or drag off-page to delete */}@@ -877,7 +910,7 @@ export default function CanvasStage() {key={g.id}x={g.position}y={0}- points={[0, -40, 0, height + 40]}+ points={[0, -40, 0, ph + 40]}stroke={GUIDE_COLOR}strokeWidth={1 / zoom}hitStrokeWidth={10 / zoom}@@ -892,7 +925,7 @@ export default function CanvasStage() {key={g.id}x={0}y={g.position}- points={[-40, 0, width + 40, 0]}+ points={[-40, 0, pw + 40, 0]}stroke={GUIDE_COLOR}strokeWidth={1 / zoom}hitStrokeWidth={10 / zoom}@@ -908,7 +941,7 @@ export default function CanvasStage() {{draftGuide &&(draftGuide.axis === 'x' ? (<Line- points={[draftGuide.position, -40, draftGuide.position, height + 40]}+ points={[draftGuide.position, -40, draftGuide.position, ph + 40]}stroke={GUIDE_COLOR}strokeWidth={1 / zoom}dash={[6 / zoom, 4 / zoom]}@@ -917,7 +950,7 @@ export default function CanvasStage() {/>) : (<Line- points={[-40, draftGuide.position, width + 40, draftGuide.position]}+ points={[-40, draftGuide.position, pw + 40, draftGuide.position]}stroke={GUIDE_COLOR}strokeWidth={1 / zoom}dash={[6 / zoom, 4 / zoom]}@@ -967,8 +1000,8 @@ export default function CanvasStage() {{/* v0.3.1: rulers overlay (desktop) */}{showRulers && containerSize.w > 0 && (<Rulers- width={width}- height={height}+ width={pw}+ height={ph}zoom={zoom}pan={pan}containerW={containerSize.w}diff --git a/src/components/editor/canvas/element-node.tsx b/src/components/editor/canvas/element-node.tsxindex 6d3cbac..8a586ab 100644--- a/src/components/editor/canvas/element-node.tsx+++ b/src/components/editor/canvas/element-node.tsx@@ -2,7 +2,7 @@import Konva from 'konva'import { memo, useCallback, useEffect, useMemo, useRef } from 'react'-import { Ellipse, Group, Image as KonvaImage, Line, Path, Rect, Star, Text } from 'react-konva'+import { Ellipse, Group, Image as KonvaImage, Line, Path, Rect, Text } from 'react-konva'import type { KonvaEventObject } from 'konva/lib/Node'import type {AnyElement,@@ -31,6 +31,9 @@ import type { TextSpan } from '@/lib/types'import { CurvedTextNode, EmbedNode, FrameNode, TableNode, type TableCellRef } from './v06-nodes'import { PluginNode } from './PluginNode'import { ChartNode } from './chart-node'+import { isMaskShape, maskPolygon, polygonPoints, starPointsEx, stretchPts, tracePts, type MaskShape } from '@/lib/shapes'+import { fitFontSize } from '@/lib/text-fit'+import { layoutListLines } from '@/lib/list-text'export interface ElementNodeProps {element: AnyElement@@ -74,6 +77,34 @@ function shadowProps(el: AnyElement) {* with the codebase's graceful no-canvas fallback (svg-export pattern). */const richMeasure = createCanvasMeasure()+/** v0.18 (Wave 3): the effective font size of a text element — the+ * authored size, or the auto-fit shrink when enabled. ONE definition+ * shared by the canvas, the SVG serializer and (through Konva) the+ * video exporter, so every surface agrees to the pixel. */+export function effectiveFontSize(t: TextElement): number {+ if (!t.autoFit) return t.fontSize+ return fitFontSize(+ {+ text: t.uppercase ? t.text.toUpperCase() : t.text,+ fontFamily: t.fontFamily,+ bold: t.bold,+ italic: t.italic,+ letterSpacing: t.letterSpacing,+ lineHeight: t.lineHeight,+ fontSize: t.fontSize,+ },+ { width: t.width, height: t.height },+ (text, style) => richMeasure(text, style)+ )+}++/** v0.18 (Wave 3): a text element renders through the list layout when a+ * list style is set (flat path — rich spans and curved text keep their+ * own single-style renders, documented in docs/EDITOR-DEPTH.md). */+function isListText(t: TextElement): boolean {+ return !!t.listStyle && t.listStyle !== 'none' && (t.curve ?? 0) === 0 && t.effect !== 'splice'+}+/** shift a Konva gradient's anchor points so a per-run node maps the* ELEMENT-box gradient continuously instead of restarting per run */function shiftGradientForRun(grad: Record<string, unknown>, dx: number, dy: number): Record<string, unknown> {@@ -163,6 +194,91 @@ function RichTextNode({)}+/** v0.18 (Wave 3): bullet / numbered list text — one Konva.Text per+ * pre-wrapped line plus a marker glyph at the hanging indent, all+ * positioned by the shared geometry module (lib/list-text.ts) so the+ * SVG serializer emits byte-identical positions. */+function ListTextNode({+ t,+ common,+ effect,+}: {+ t: TextElement+ common: Record<string, unknown>+ effect: Record<string, unknown>+}) {+ const size = effectiveFontSize(t)+ const rtl = t.direction === 'rtl'+ const rendered = t.uppercase ? t.text.toUpperCase() : t.text+ const lines = useMemo(+ () =>+ layoutListLines(+ {+ text: rendered,+ fontFamily: t.fontFamily,+ bold: t.bold,+ italic: t.italic,+ letterSpacing: t.letterSpacing,+ lineHeight: t.lineHeight,+ fontSize: size,+ width: t.width,+ listStyle: t.listStyle ?? 'none',+ direction: rtl ? 'rtl' : 'ltr',+ },+ (text, style) => richMeasure(text, style)+ ),+ [rendered, t.fontFamily, t.bold, t.italic, t.letterSpacing, t.lineHeight, size, t.width, t.listStyle, rtl]+ )+ const blockH = lines.length ? Math.max(...lines.map((l) => l.y)) + size * t.lineHeight : size * t.lineHeight+ const fontStyle = `${t.italic ? 'italic ' : ''}${t.bold ? 'bold' : 'normal'}`+ // rtl mirrors the default alignment (an explicit centre stays centred)+ const align =+ t.align === 'center' ? 'center' : t.align === 'justify' ? 'left' : rtl ? (t.align === 'left' ? 'right' : 'left') : t.align+ return (+ <Group {...common} height={blockH}>+ {/* declared-box hit rect — mirrors RichTextNode */}+ <Rect width={t.width} height={Math.max(t.height, blockH)} fill="transparent" perfectDrawEnabled={false} />+ {t.effect === 'background' && (+ <Rect width={t.width} height={Math.max(t.height, blockH)} fill={t.effectBackground ?? '#EFEFEF'} cornerRadius={Math.min(8, size * 0.2)} />+ )}+ {lines.map((line, i) => (+ <Group key={i}>+ {line.marker && (+ <Text+ x={line.markerX}+ y={line.y}+ text={line.marker}+ fontSize={size}+ fontFamily={t.fontFamily}+ fontStyle={fontStyle}+ fill={t.fill}+ width={t.width}+ align={rtl ? 'right' : 'left'}+ perfectDrawEnabled={false}+ />+ )}+ <Text+ x={line.textX}+ y={line.y}+ text={line.text}+ fontSize={size}+ fontFamily={t.fontFamily}+ fontStyle={fontStyle}+ textDecoration={[t.underline ? 'underline' : '', t.strike ? 'line-through' : ''].filter(Boolean).join(' ')}+ fill={t.fill}+ align={align}+ width={line.textWidth}+ lineHeight={t.lineHeight}+ letterSpacing={t.letterSpacing}+ wrap="none"+ perfectDrawEnabled={false}+ />+ </Group>+ ))}+ </Group>+ )+}+function textEffectProps(t: TextElement): Record<string, string | number> {switch (t.effect) {case 'shadow':@@ -186,7 +302,10 @@ function textEffectProps(t: TextElement): Record<string, string | number> {}}-/** image with Konva filters (brightness / contrast / saturation) */+/** image with Konva filters (brightness / contrast / saturation).+ * v0.18 (Wave 3): optional shape mask — the image clips to a polygon+ * (lib/shapes.ts) drawn into the Group's clipShapeFunc, so filters,+ * flips, adjustments and the Transformer all keep working unchanged. */function ImageNode({ el, common }: { el: ImageElement; common: Record<string, unknown> }) {const image = useLoadedImage(el.src)const nodeRef = useRef<Konva.Image | null>(null)@@ -221,20 +340,38 @@ function ImageNode({ el, common }: { el: ImageElement; common: Record<string, unnode.getLayer()?.batchDraw()}, [image, bright, contrast, sat, preset, intensity])- return (+ // v0.18 (Wave 3): validated mask — hostile pastes can't smuggle junk in+ const maskPts = useMemo(() => {+ if (!isMaskShape(el.maskShape) || el.maskShape === 'none') return null+ return maskPolygon(el.maskShape as MaskShape, el.maskSides, el.maskInnerRatio)+ }, [el.maskShape, el.maskSides, el.maskInnerRatio])++ const img = (<KonvaImage- {...common}ref={(n) => { nodeRef.current = n; (common.ref as (node: Konva.Node | null) => void | undefined)?.(n) }}image={image ?? undefined}width={el.width}height={el.height}- cornerRadius={el.radius}+ cornerRadius={maskPts ? 0 : el.radius}scaleX={el.flipH ? -1 : 1}scaleY={el.flipV ? -1 : 1}offsetX={el.flipH ? el.width : 0}offsetY={el.flipV ? el.height : 0}/>)++ if (!maskPts) {+ return <Group {...common} clip={undefined}>{img}</Group>+ }+ return (+ <Group+ {...common}+ clip={undefined}+ clipShapeFunc={(ctx) => tracePts(ctx, maskPts, el.width, el.height)}+ >+ {img}+ </Group>+ )}/** v0.11: audio — waveform player card. Pure vector: dark rounded card,@@ -411,7 +548,7 @@ function ElementNodeImpl({ element: el, interactive, hiding, hideCell, registerN})return}- if (el.type === 'ellipse' || el.type === 'star') {+ if (el.type === 'ellipse' || el.type === 'star' || el.type === 'polygon') {store.updateElementsLive([el.id], { x: node.x() - el.width / 2, y: node.y() - el.height / 2 })} else {store.updateElementsLive([el.id], { x: node.x(), y: node.y() })@@ -511,7 +648,7 @@ function ElementNodeImpl({ element: el, interactive, hiding, hideCell, registerNconst newH = Math.max(4, el.height * sy)patch.width = newWpatch.height = newH- if (el.type === 'ellipse' || el.type === 'star') {+ if (el.type === 'ellipse' || el.type === 'star' || el.type === 'polygon') {patch.x = node.x() - newW / 2patch.y = node.y() - newH / 2} else {@@ -569,6 +706,11 @@ function ElementNodeImpl({ element: el, interactive, hiding, hideCell, registerNconst t = el as TextElementconst effect = t.effect && t.effect !== 'none' ? textEffectProps(t) : {}const rendered = t.uppercase ? t.text.toUpperCase() : t.text+ // v0.18 (Wave 3): list text renders through the shared list+ // layout (flat — rich spans keep their own path, like curved text)+ if (isListText(t)) {+ return <ListTextNode t={t} common={common} effect={effect} />+ }// v0.15 (R1): rich text — spans render through the shared layout;// curved text and the splice ghost-copies effect stay on the flat// path (single-style by design, documented in README · R1)@@ -576,6 +718,13 @@ function ElementNodeImpl({ element: el, interactive, hiding, hideCell, registerNif (richSpans) {return <RichTextNode t={t} spans={richSpans} common={common} effect={effect} />}+ // v0.18 (Wave 3): auto-fit — the effective size is derived at render+ // (lib/text-fit.ts); the authored fontSize is never mutated+ const effSize = effectiveFontSize(t)+ // v0.18 (Wave 3): rtl mirrors the default alignment (centre stays)+ const rtl = t.direction === 'rtl'+ const alignAttr =+ t.align === 'center' ? 'center' : t.align === 'justify' ? 'left' : rtl ? (t.align === 'left' ? 'right' : 'left') : t.align// gradient fill (skipped for effects that own the fill, e.g. Hollow)const textGrad: GradientFill | null | undefined = t.fillGradientconst gradProps =@@ -586,18 +735,18 @@ function ElementNodeImpl({ element: el, interactive, hiding, hideCell, registerNif (t.effect === 'background') {// canva "Background" effect: solid block behind the textconst bg = t.effectBackground ?? '#EFEFEF'- const h = Math.max(t.height, t.fontSize * t.lineHeight + 8)+ const h = Math.max(t.height, effSize * t.lineHeight + 8)return (<Group {...common}>- <Rect width={t.width} height={h} fill={bg} cornerRadius={Math.min(8, t.fontSize * 0.2)} />+ <Rect width={t.width} height={h} fill={bg} cornerRadius={Math.min(8, effSize * 0.2)} /><Texttext={rendered}- fontSize={t.fontSize}+ fontSize={effSize}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}+ align={alignAttr}width={t.width}lineHeight={t.lineHeight}letterSpacing={t.letterSpacing}@@ -613,9 +762,9 @@ function ElementNodeImpl({ element: el, interactive, hiding, hideCell, registerN// canva "Splice": sliced look — ghost copies above & belowreturn (<Group {...common}>- <Text text={rendered} fontSize={t.fontSize} fontFamily={t.fontFamily} fontStyle={`${t.italic ? 'italic ' : ''}${t.bold ? 'bold' : 'normal'}`} fill={withAlpha(t.fill, 0.35)} align={t.align === 'justify' ? 'left' : t.align} width={t.width} lineHeight={t.lineHeight} letterSpacing={t.letterSpacing} wrap="word" y={-Math.max(3, t.fontSize * 0.09)} perfectDrawEnabled={false} />- <Text text={rendered} fontSize={t.fontSize} fontFamily={t.fontFamily} fontStyle={`${t.italic ? 'italic ' : ''}${t.bold ? 'bold' : 'normal'}`} fill={withAlpha(t.fill, 0.35)} align={t.align === 'justify' ? 'left' : t.align} width={t.width} lineHeight={t.lineHeight} letterSpacing={t.letterSpacing} wrap="word" y={Math.max(3, t.fontSize * 0.09)} perfectDrawEnabled={false} />- <Text text={rendered} fontSize={t.fontSize} fontFamily={t.fontFamily} fontStyle={`${t.italic ? 'italic ' : ''}${t.bold ? 'bold' : 'normal'}`} fill={t.fill} align={t.align === 'justify' ? 'left' : t.align} width={t.width} lineHeight={t.lineHeight} letterSpacing={t.letterSpacing} wrap="word" perfectDrawEnabled={false} />+ <Text text={rendered} fontSize={effSize} fontFamily={t.fontFamily} fontStyle={`${t.italic ? 'italic ' : ''}${t.bold ? 'bold' : 'normal'}`} fill={withAlpha(t.fill, 0.35)} align={alignAttr} width={t.width} lineHeight={t.lineHeight} letterSpacing={t.letterSpacing} wrap="word" y={-Math.max(3, effSize * 0.09)} perfectDrawEnabled={false} />+ <Text text={rendered} fontSize={effSize} fontFamily={t.fontFamily} fontStyle={`${t.italic ? 'italic ' : ''}${t.bold ? 'bold' : 'normal'}`} fill={withAlpha(t.fill, 0.35)} align={alignAttr} width={t.width} lineHeight={t.lineHeight} letterSpacing={t.letterSpacing} wrap="word" y={Math.max(3, effSize * 0.09)} perfectDrawEnabled={false} />+ <Text text={rendered} fontSize={effSize} fontFamily={t.fontFamily} fontStyle={`${t.italic ? 'italic ' : ''}${t.bold ? 'bold' : 'normal'}`} fill={t.fill} align={alignAttr} width={t.width} lineHeight={t.lineHeight} letterSpacing={t.letterSpacing} wrap="word" perfectDrawEnabled={false} /></Group>)}@@ -626,12 +775,12 @@ function ElementNodeImpl({ element: el, interactive, hiding, hideCell, registerN{...effect}{...gradProps}text={rendered}- fontSize={t.fontSize}+ fontSize={effSize}fontFamily={t.fontFamily}fontStyle={`${t.italic ? 'italic ' : ''}${t.bold ? 'bold' : 'normal'}`}textDecoration={[t.underline ? 'underline' : '', t.strike ? 'line-through' : ''].filter(Boolean).join(' ')}fill={Object.keys(gradProps).length ? undefined : t.fill}- align={t.align === 'justify' ? 'left' : t.align}+ align={alignAttr}width={t.width}lineHeight={t.lineHeight}letterSpacing={t.letterSpacing}@@ -661,9 +810,46 @@ function ElementNodeImpl({ element: el, interactive, hiding, hideCell, registerNcase 'star': {const s = el as ShapeElement- const outer = Math.min(s.width, s.height) / 2+ // v0.18 (Wave 3): parametric — 3..16 points, adjustable spike ratio.+ // stretchPts is THE shape mapping (fills the box, like ellipse/rect) —+ // the SVG + PDF exports render the identical points.+ const grad = s.fillGradient ? elementGradientProps(s.fillGradient, s.width, s.height, 'center') : {}+ // absolute points in the box, then re-based to the centre (the+ // node sits at the centre so rotation turns around the shape)+ const pts = stretchPts(starPointsEx(s.numPoints ?? 5, s.innerRatio), 0, 0, s.width, s.height)+ return (+ <Line+ {...common}+ x={s.x + s.width / 2}+ y={s.y + s.height / 2}+ points={pts.flatMap(([px, py]): number[] => [px - s.width / 2, py - s.height / 2])}+ closed+ {...grad}+ fill={s.fillGradient ? undefined : s.fill}+ stroke={s.stroke}+ strokeWidth={s.strokeWidth}+ />+ )+ }++ case 'polygon': {+ // v0.18 (Wave 3): regular polygon — centred geometry like the star+ const s = el as ShapeElementconst grad = s.fillGradient ? elementGradientProps(s.fillGradient, s.width, s.height, 'center') : {}- return <Star {...common} x={s.x + s.width / 2} y={s.y + s.height / 2} numPoints={5} innerRadius={outer * 0.55} outerRadius={outer} {...grad} fill={s.fillGradient ? undefined : s.fill} stroke={s.stroke} strokeWidth={s.strokeWidth} />+ const pts = stretchPts(polygonPoints(s.sides ?? 6), 0, 0, s.width, s.height)+ return (+ <Line+ {...common}+ x={s.x + s.width / 2}+ y={s.y + s.height / 2}+ points={pts.flatMap(([px, py]): number[] => [px - s.width / 2, py - s.height / 2])}+ closed+ {...grad}+ fill={s.fillGradient ? undefined : s.fill}+ stroke={s.stroke}+ strokeWidth={s.strokeWidth}+ />+ )}case 'path': {diff --git a/src/components/editor/canvas/preview-stage.tsx b/src/components/editor/canvas/preview-stage.tsxindex 2457fb6..7e7ab7d 100644--- a/src/components/editor/canvas/preview-stage.tsx+++ b/src/components/editor/canvas/preview-stage.tsx@@ -4,7 +4,7 @@ import { useEffect, useRef, useState } from 'react'import type Konva from 'konva'import { Layer, Rect, Stage } from 'react-konva'import type { AudioElement, PageData, VideoElement } from '@/lib/types'-import { gradientProps } from '@/lib/editor-utils'+import { gradientProps, pageSize } from '@/lib/editor-utils'import { animateElementAt, pageAnimationDuration } from '@/lib/animations'import { beatEnvelopeAt, beatSourceOf } from '@/lib/media/beat-detect'import { PreviewElements } from './element-node'@@ -31,6 +31,9 @@ export default function PreviewStage({ page, designWidth, designHeight, animatedconst layerRef = useRef<Konva.Layer | null>(null)const stageRef = useRef<Konva.Stage | null>(null)const [size, setSize] = useState({ w: 0, h: 0 })+ // v0.18 (Wave 3): per-page size — derived once here so every caller+ // (preview, presenter, thumbnails) gets page overrides for free+ const { width: pw, height: ph } = pageSize(page, designWidth, designHeight)useEffect(() => {const el = containerRef.current@@ -43,9 +46,9 @@ export default function PreviewStage({ page, designWidth, designHeight, animatedreturn () => ro.disconnect()}, [])- const scale = size.w > 0 && size.h > 0 ? Math.min(size.w / designWidth, size.h / designHeight) : 0- const offsetX = size.w > 0 ? (size.w - designWidth * scale) / 2 : 0- const offsetY = size.h > 0 ? (size.h - designHeight * scale) / 2 : 0+ const scale = size.w > 0 && size.h > 0 ? Math.min(size.w / pw, size.h / ph) : 0+ const offsetX = size.w > 0 ? (size.w - pw * scale) / 2 : 0+ const offsetY = size.h > 0 ? (size.h - ph * scale) / 2 : 0// v0.11.1 fix: the Konva Stage only renders once the ResizeObserver has// measured the container (scale > 0), but both playback effects used to// bail on the first run (layerRef still null) and their deps never changed@@ -57,7 +60,7 @@ export default function PreviewStage({ page, designWidth, designHeight, animatedconst bg = page.backgroundconst bgProps =bg.type === 'gradient'- ? gradientProps(bg.from, bg.to, bg.angle, designWidth, designHeight)+ ? gradientProps(bg.from, bg.to, bg.angle, pw, ph): { fill: bg.color }// ── v0.5: element animation playback (rAF timeline over Konva nodes) ──@@ -136,7 +139,7 @@ export default function PreviewStage({ page, designWidth, designHeight, animatedcancelAnimationFrame(raf)resetNodes(layer, page, bases)}- }, [page, hasAnimations, reduceMotion, playKey, designWidth, designHeight, stageReady])+ }, [page, hasAnimations, reduceMotion, playKey, pw, ph, stageReady])// ── v0.11: media playback — audio elements, video frames, Beat Sync ──// Presentation/preview is where media plays (the editor canvas always@@ -291,7 +294,7 @@ export default function PreviewStage({ page, designWidth, designHeight, animated{scale > 0 && (<Stage ref={stageRef} width={size.w} height={size.h}><Layer listening={false} x={offsetX} y={offsetY} scale={{ x: scale, y: scale }}>- <Rect width={designWidth} height={designHeight} {...bgProps} />+ <Rect width={pw} height={ph} {...bgProps} /></Layer><Layerref={layerRef}@@ -299,7 +302,7 @@ export default function PreviewStage({ page, designWidth, designHeight, animatedx={offsetX}y={offsetY}scale={{ x: scale, y: scale }}- clip={{ x: 0, y: 0, width: designWidth, height: designHeight }}+ clip={{ x: 0, y: 0, width: pw, height: ph }}><PreviewElements elements={page.elements} /></Layer>diff --git a/src/components/editor/panels/ElementsPanel.tsx b/src/components/editor/panels/ElementsPanel.tsxindex 3652931..baf36c2 100644--- a/src/components/editor/panels/ElementsPanel.tsx+++ b/src/components/editor/panels/ElementsPanel.tsx@@ -1,9 +1,10 @@'use client'import { useMemo, useState } from 'react'-import { Square, Circle, Triangle, Star, Minus, ArrowRight, MoveHorizontal, Search, Hexagon, Pentagon, Diamond, CircleDashed, Frame, Youtube, MapPin, Link2 } from 'lucide-react'+import { Square, Circle, Triangle, Star, Minus, ArrowRight, MoveHorizontal, Search, Hexagon, Frame, Youtube, MapPin, Link2 } from 'lucide-react'import { GRAPHICS, STICKER_GROUPS } from '@/lib/editor-utils'-import { addChart, addEmbed, addFrame, addGraphic, addLine, addShape, addSticker, addTable, type TableStyle } from '../add-element'+import { polygonPoints, starPointsEx, ptsToSvg } from '@/lib/shapes'+import { addChart, addEmbed, addFrame, addGraphic, addLine, addPolygon, addShape, addStarVariant, addSticker, addTable, type TableStyle } from '../add-element'import { cn } from '@/lib/utils'import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'import { FRAME_SHAPES, type ChartKind } from '@/lib/types'@@ -16,6 +17,25 @@ function GraphicIcon({ path }: { path: string }) {)}+/** v0.18 (Wave 3): native polygon / star tiles — the SAME geometry the+ * canvas and the SVG exporter draw (lib/shapes.ts), so the palette+ * preview is always honest. */+function PolygonMini({ sides }: { sides: number }) {+ return (+ <svg viewBox="0 0 100 100" className="h-[26px] w-[26px]" aria-hidden="true">+ <polygon points={ptsToSvg(polygonPoints(sides))} fill="none" stroke="rgba(255,255,255,0.8)" strokeWidth={5} />+ </svg>+ )+}++function StarMini({ points, ratio }: { points: number; ratio: number }) {+ return (+ <svg viewBox="0 0 100 100" className="h-[26px] w-[26px]" aria-hidden="true">+ <polygon points={ptsToSvg(starPointsEx(points, ratio))} fill="none" stroke="rgba(255,255,255,0.8)" strokeWidth={5} />+ </svg>+ )+}+const BASIC_SHAPES = [{ id: 'rect', label: 'Square', icon: Square },{ id: 'rounded', label: 'Rounded', icon: null },@@ -24,13 +44,24 @@ const BASIC_SHAPES = [{ id: 'star', label: 'Star', icon: Star },] as const-const POLY_SHAPES = [- { id: 'pentagon', label: 'Pentagon', icon: Pentagon },- { id: 'hexagon', label: 'Hexagon', icon: Hexagon },- { id: 'octagon', label: 'Octagon', icon: null },- { id: 'diamond', label: 'Diamond', icon: Diamond },- { id: 'semi-circle', label: 'Semicircle', icon: CircleDashed },-] as const+const POLY_TILES: { label: string; sides: number }[] = [+ { label: 'Pentagon', sides: 5 },+ { label: 'Hexagon', sides: 6 },+ { label: 'Heptagon', sides: 7 },+ { label: 'Octagon', sides: 8 },+ { label: 'Nonagon', sides: 9 },+ { label: 'Decagon', sides: 10 },+]++/** v0.18 (Wave 3): star variants — parametric, editable post-insert */+const STAR_TILES: { label: string; points: number; ratio?: number }[] = [+ { label: '6-point', points: 6 },+ { label: '8-point', points: 8 },+ { label: '12-point', points: 12, ratio: 0.72 },+ { label: '16-point burst', points: 16, ratio: 0.8 },+ { label: 'Thin spike', points: 5, ratio: 0.3 },+ { label: 'Soft star', points: 5, ratio: 0.75 },+]const GRAPHIC_GROUPS: { name: string; ids: string[] }[] = [{ name: 'Decorative', ids: ['heart', 'blob', 'cloud', 'moon', 'sparkle', 'wave'] },@@ -172,10 +203,18 @@ export function ElementsPanel() {))}</div><SectionTitle>Polygons</SectionTitle>+ <div className="grid grid-cols-3 gap-2 mb-4">+ {POLY_TILES.map((s) => (+ <ShapeTile key={s.label} label={s.label} onClick={() => addPolygon(s.sides)}>+ <PolygonMini sides={s.sides} />+ </ShapeTile>+ ))}+ </div>+ <SectionTitle>Stars</SectionTitle><div className="grid grid-cols-3 gap-2">- {POLY_SHAPES.map((s) => (- <ShapeTile key={s.id} label={s.label} onClick={() => addGraphic(s.id)}>- {s.icon ? <s.icon size={26} strokeWidth={1.6} className="text-white/80" /> : <GraphicIcon path={GRAPHICS.find((g) => g.id === 'octagon')?.path ?? ''} />}+ {STAR_TILES.map((s) => (+ <ShapeTile key={s.label} label={s.label} onClick={() => addStarVariant(s.points, s.ratio)}>+ <StarMini points={s.points} ratio={s.ratio ?? 0.55} /></ShapeTile>))}</div>diff --git a/src/instrumentation.ts b/src/instrumentation.tsindex c4ed596..720ae3e 100644--- a/src/instrumentation.ts+++ b/src/instrumentation.ts@@ -1,14 +1,58 @@-// src/instrumentation.ts (v0.12.5, roadmap H7) — Next's server-// lifecycle hooks, used for exactly one thing: the opt-in error-// webhook. `onRequestError` fires for every UNHANDLED error across-// pages, route handlers, server actions and middleware — Next's-// own route-catch — so one file instruments the whole app.+// src/instrumentation.ts (v0.12.5, roadmap H7; v0.18 Wave 3 register)+// — Next's server lifecycle hooks, used for exactly two things://-// When CANVIX_ERROR_WEBHOOK_URL is unset (the default) this file-// does nothing beyond a structured local log line. See-// src/lib/observability.ts for the payload contract.+// 1. onRequestError — the opt-in error webhook. When+// CANVIX_ERROR_WEBHOOK_URL is unset (the default) this does+// nothing beyond a structured local log line. See+// src/lib/observability.ts for the payload contract.+//+// 2. register (v0.18) — the template-library top-up. "The template+// library ships as code" (docs/UPGRADING.md), so on every boot+// (nodejs runtime only) the built-in templates are reconciled+// into the database: new ones appear, changed ones refresh,+// nothing is ever deleted. A single COUNT is the normal-boot cost+// — the upsert loop only runs when the library is short. Opt out+// with CANVIX_TEMPLATE_SYNC=0 (operators who curate the library+// by hand; npm run db:seed still works for them).+//+// The v0.16.1 lesson applies in full: NOTHING Prisma-shaped may+// be imported statically here — instrumentation is also compiled+// for the edge runtime, and tracing Prisma into that bundle broke+// `next build` (PR #39). The dynamic imports below happen inside+// the nodejs branch only, after the NEXT_RUNTIME check.import { buildErrorReport, logLine, postErrorWebhook } from './lib/observability'+export async function register(): Promise<void> {+ // edge/middleware compilations must not trace any of this+ if (process.env.NEXT_RUNTIME !== 'nodejs') return+ // explicit operator opt-out (see the header note)+ if (process.env.CANVIX_TEMPLATE_SYNC === '0') return++ // fire-and-forget: a slow or failing database must never block or+ // crash the server boot — the next request health-checks it anyway+ void (async () => {+ try {+ const [{ db }, { syncTemplateLibrary }] = await Promise.all([+ import('./lib/db'),+ import('./lib/templates/sync'),+ ])+ const res = await syncTemplateLibrary(db)+ if (!res.skipped) {+ logLine('info', 'template_library_synced', {+ synced: res.synced,+ total: res.total,+ note: 'boot-time top-up: new built-in templates were added to the database',+ })+ }+ } catch (error) {+ logLine('error', 'template_library_sync_failed', {+ message: error instanceof Error ? error.message : String(error),+ note: 'non-fatal: the app serves with whatever the database already holds',+ })+ }+ })()+}+export async function onRequestError(error: unknown,request: { path: string; method: string; headers: Record<string, string | string[] | undefined> },diff --git a/src/lib/editor-utils.ts b/src/lib/editor-utils.tsindex 3ab5839..fe7853d 100644--- a/src/lib/editor-utils.ts+++ b/src/lib/editor-utils.ts@@ -292,6 +292,22 @@ export function pageElements(page: PageData): AnyElement[] {return page.elements.filter((e) => e.visible)}+/** v0.18 (Wave 3): the ONE accessor for a page's render size.+ * Per-page overrides (PageData.width/height) win when valid; anything+ * absent, zero, sub-minimum or absurd falls back to the design size —+ * so every pre-v0.18 document behaves exactly as before. */+export function pageSize(+ page: { width?: number; height?: number } | undefined | null,+ designWidth: number,+ designHeight: number+): { width: number; height: number } {+ const w = page?.width+ const h = page?.height+ const W = Number.isFinite(w) && (w as number) >= 32 && (w as number) <= 8000 ? (w as number) : designWidth+ const H = Number.isFinite(h) && (h as number) >= 32 && (h as number) <= 8000 ? (h as number) : designHeight+ return { width: W, height: H }+}+/** Konva linear gradient helper — returns props for a Rect fill. */export function gradientProps(from: string, to: string, angle: number, w: number, h: number) {const rad = (angle * Math.PI) / 180diff --git a/src/lib/list-text.test.ts b/src/lib/list-text.test.tsnew file mode 100644index 0000000..4c84cbb--- /dev/null+++ b/src/lib/list-text.test.ts@@ -0,0 +1,93 @@+import { describe, it, expect } from 'vitest'+import { layoutListLines, type ListLayoutStyle, type ListMeasure } from '@/lib/list-text'++const measure: ListMeasure = (text, style) => text.length * style.fontSize * 0.5++function style(over: Partial<ListLayoutStyle> = {}): ListLayoutStyle {+ return {+ text: 'first item\nsecond item',+ fontFamily: 'Inter',+ bold: false,+ italic: false,+ letterSpacing: 0,+ lineHeight: 1.25,+ fontSize: 20,+ width: 400,+ listStyle: 'bullet',+ direction: 'ltr',+ ...over,+ }+}++describe('layoutListLines — bullets', () => {+ it('marks every first line with the bullet, continuations without', () => {+ const lines = layoutListLines(style(), measure)+ const firsts = lines.filter((l) => l.marker === '•')+ expect(firsts.length).toBe(2)+ // all lines are laid out vertically in order+ expect(lines.map((l) => l.text)).toEqual(['first item', 'second item'])+ })++ it('indents text past the marker column (hanging indent)', () => {+ const lines = layoutListLines(style(), measure)+ expect(lines[0].markerX).toBe(0)+ expect(lines[0].textX).toBeGreaterThan(0)+ expect(lines[0].textWidth).toBeLessThan(style().width)+ })++ it('wrapped continuation lines keep the same indent as their item', () => {+ // 'aaaa bbbb' = 18px/char… make width force a wrap: each char 10px at fontSize 20+ const s = style({ text: 'aaa bbb ccc ddd', width: 60 })+ const lines = layoutListLines(s, measure)+ expect(lines.length).toBeGreaterThan(1)+ expect(lines[0].marker).toBe('•')+ for (const l of lines.slice(1)) expect(l.marker).toBe('')+ // all text lines share the same x + width+ for (const l of lines) expect(l.textX).toBe(lines[0].textX)+ })++ it('empty paragraphs produce blank spacer lines', () => {+ const lines = layoutListLines(style({ text: 'a\n\nb' }), measure)+ expect(lines.some((l) => l.text === '' && l.marker === '')).toBe(true)+ })+})++describe('layoutListLines — numbers', () => {+ it('numbers items sequentially across paragraphs', () => {+ const lines = layoutListLines(style({ listStyle: 'number', text: 'one\ntwo\nthree' }), measure)+ expect(lines.map((l) => l.marker)).toEqual(['1.', '2.', '3.'])+ })++ it('skips numbering on continuation lines', () => {+ const lines = layoutListLines(style({ listStyle: 'number', text: 'aaa bbb ccc ddd', width: 60 }), measure)+ expect(lines[0].marker).toBe('1.')+ for (const l of lines.slice(1)) expect(l.marker).toBe('')+ })++ it('the marker column fits the widest number (no overlap)', () => {+ const s = style({ listStyle: 'number', text: Array.from({ length: 12 }, (_, i) => `item ${i + 1}`).join('\n') })+ const lines = layoutListLines(s, measure)+ const widest = measure('12.', s)+ expect(lines[0].textX).toBeGreaterThanOrEqual(widest)+ })+})++describe('layoutListLines — none / rtl', () => {+ it("listStyle 'none' degrades to a plain block (no markers, no indent)", () => {+ const lines = layoutListLines(style({ listStyle: 'none' }), measure)+ expect(lines.every((l) => l.marker === '' && l.markerX === 0)).toBe(true)+ expect(lines[0].textX).toBe(0)+ expect(lines[0].textWidth).toBe(style().width)+ })++ it('rtl mirrors the marker to the right edge', () => {+ const ltr = layoutListLines(style({ direction: 'ltr' }), measure)+ const rtl = layoutListLines(style({ direction: 'rtl' }), measure)+ const w = style().width+ expect(ltr[0].markerX).toBe(0)+ expect(rtl[0].markerX).toBeGreaterThan(0)+ expect(rtl[0].markerX).toBeLessThanOrEqual(w)+ expect(rtl[0].textX).toBe(0) // text box starts at the left edge, aligns right+ expect(rtl[0].textWidth).toBe(ltr[0].textWidth)+ })+})diff --git a/src/lib/list-text.ts b/src/lib/list-text.tsnew file mode 100644index 0000000..575de2c--- /dev/null+++ b/src/lib/list-text.ts@@ -0,0 +1,121 @@+// ─────────────────────────────────────────────────────────────+// Canvix v0.18 (Wave 3) — bullet & numbered list layout+//+// Pure layout: wraps the text (same greedy wrap as text-fit) and+// returns per-line records with the marker string and x offsets.+// Hanging indent: the marker column is `markerCol` wide; every line+// of the item starts at the indent, wrapped continuation lines too —+// the Canva look. RTL mirrors the marker to the right edge.+//+// Shared by the Konva renderer (element-node), the SVG serializer and+// (through them) the video exporter — the rich-text pattern.+// ─────────────────────────────────────────────────────────────++export type ListStyle = 'none' | 'bullet' | 'number'++export interface ListLine {+ /** wrapped line text (already trimmed) */+ text: string+ /** marker glyph ('•' / '1.' / '') — '' on continuation lines */+ marker: string+ /** marker x offset from the element's left edge (px) */+ markerX: number+ /** text x offset from the element's left edge (px) */+ textX: number+ /** text box width for this line (px) — element width minus the marker column */+ textWidth: number+ /** baseline y offset from the element's top edge (px) — line index × lineHeight */+ y: number+}++export interface ListLayoutStyle {+ text: string+ fontFamily: string+ bold: boolean+ italic: boolean+ letterSpacing: number+ lineHeight: number+ fontSize: number+ /** element box width */+ width: number+ listStyle: ListStyle+ direction: 'ltr' | 'rtl'+}++export type ListMeasure = (text: string, style: { fontFamily: string; bold: boolean; italic: boolean; letterSpacing: number; fontSize: number }) => number++const BULLET = '•'++/**+ * Layout a list text. When `listStyle === 'none'` this degrades to a+ * plain wrapped block (marker '' everywhere) so callers have ONE path.+ */+export function layoutListLines(style: ListLayoutStyle, measure: ListMeasure): ListLine[] {+ const m = (t: string) => measure(t, style)+ const markerGap = Math.round(style.fontSize * 0.42)+ const rtl = style.direction === 'rtl'++ // Pass 1 — marker column width (the widest marker + gap)+ const paragraphs = style.text.split('\n')+ let markerCol = 0+ if (style.listStyle !== 'none') {+ const itemCount = paragraphs.filter((p) => p !== '').length || 1+ // worst-case marker width: the last index (widest) — measure it once+ const widest = style.listStyle === 'number' ? `${itemCount}.` : BULLET+ markerCol = m(widest) + markerGap+ }+ const textWidth = Math.max(24, style.width - markerCol)++ // Pass 2 — greedy wrap per paragraph with the reduced width+ const out: ListLine[] = []+ let lineIndex = 0+ let itemCounter = 0+ for (const para of paragraphs) {+ const startsItem = para !== ''+ if (startsItem) itemCounter += 1+ const marker =+ style.listStyle === 'none'+ ? ''+ : style.listStyle === 'bullet'+ ? startsItem+ ? BULLET+ : ''+ : startsItem+ ? `${itemCounter}.`+ : ''+ const markerW = marker ? m(marker) : 0++ if (para === '') {+ out.push({ text: '', marker: '', markerX: 0, textX: 0, textWidth: style.width, y: lineIndex * style.fontSize * style.lineHeight })+ lineIndex += 1+ continue+ }++ const words = para.split(/(\s+)/).filter((w) => w !== '')+ let line = ''+ let isFirst = true+ const pushLine = () => {+ out.push({+ text: line.trimEnd(),+ marker: isFirst ? marker : '',+ markerX: isFirst && rtl ? style.width - markerW : 0,+ textX: rtl ? 0 : markerCol,+ textWidth,+ y: lineIndex * style.fontSize * style.lineHeight,+ })+ lineIndex += 1+ isFirst = false+ }+ for (const word of words) {+ const candidate = line + word+ if (line !== '' && m(candidate.trimEnd()) > textWidth && !/^\s+$/.test(word)) {+ pushLine()+ line = word.trimStart()+ } else {+ line = candidate+ }+ }+ if (line !== '') pushLine()+ }+ return out+}diff --git a/src/lib/pdf-export-wave3.test.ts b/src/lib/pdf-export-wave3.test.tsnew file mode 100644index 0000000..dc86e78--- /dev/null+++ b/src/lib/pdf-export-wave3.test.ts@@ -0,0 +1,168 @@+import { describe, expect, it, vi } from 'vitest'+import type { PageData, AnyElement } from '@/lib/types'+import { exportDesignToPdf } from '@/lib/pdf-export'++// node has no Image() — the video-export preloader is irrelevant for+// these vector-path tests (the embedder's JPEG passthrough is the code+// under test), so it is stubbed to an empty map.+vi.mock('@/lib/video-export', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/lib/video-export')>()+ return { ...actual, collectImages: async () => new Map<string, HTMLImageElement>() }+})++// Node-side Wave 3 checks, same discipline as pdf-export.test.ts:+// the offline font ladder (std14) keeps everything deterministic.++// an 8×8 solid-red JPEG (844 bytes) — the only format the node-side+// embedder passes through byte-for-byte (PNG needs a canvas)+const RED_JPEG_B64 =+ '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/2wBDAQoLCw4NDhwQEBw7KCIoOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozv/wAARCAAIAAgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDmqKKK8w/Qz//Z'++const page = (elements: AnyElement[], over: Partial<PageData> = {}): PageData =>+ ({ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements, ...over }) as unknown as PageData++function el(over: Record<string, unknown>): AnyElement {+ return {+ id: 'e1',+ type: 'rect',+ x: 100,+ y: 100,+ width: 200,+ height: 200,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ fill: '#00C4CC',+ stroke: 'transparent',+ strokeWidth: 0,+ cornerRadius: 0,+ ...over,+ } as AnyElement+}++async function pdfString(pages: PageData[], designWidth = 600, designHeight = 400): Promise<string> {+ const result = await exportDesignToPdf({+ designWidth,+ designHeight,+ pages,+ title: 'Wave 3',+ fontLadderIo: { lookupUrl: async () => null },+ })+ const buf = new Uint8Array(await result.blob.arrayBuffer())+ let s = ''+ for (let i = 0; i < buf.length; i += 0x8000) s += String.fromCharCode(...buf.subarray(i, i + 0x8000))+ return s+}++describe('exportDesignToPdf — Wave 3 features (node, std14 ladder)', () => {+ it('polygon renders as a full-box vector path (6 sides → 6 line segments)', async () => {+ const doc = await pdfString([page([el({ type: 'polygon', sides: 6 })])])+ // one moveto + five lineto + close (h), then the fill — a hexagon+ // is exactly 6 vertices = 1 m + 5 l + h+ const lines = doc.match(/ l\n/g)?.length ?? 0+ expect(lines).toBe(5)+ expect(doc).toMatch(/m\n[\d.]+ [\d.]+ l/)+ })++ it('star honours numPoints (9 → 18 segments) and fills the element box', async () => {+ const doc = await pdfString([page([el({ type: 'star', numPoints: 9, innerRatio: 0.4 })])])+ const lines = doc.match(/ l\n/g)?.length ?? 0+ expect(lines).toBe(17) // 18 vertices = 1 m + 17 l + h+ // the top outer vertex touches the box top edge: y-down 100 →+ // page space (designH - y) = 400 - 100 = 300, x = 100 + 200/2 = 200+ expect(doc).toContain('200 300 m')+ })++ it('per-page size override drives each MediaBox independently', async () => {+ const doc = await pdfString(+ [page([], {}), page([], { width: 500, height: 250 })],+ 600,+ 400,+ )+ expect(doc).toContain('/MediaBox [0 0 600 400]')+ expect(doc).toContain('/MediaBox [0 0 500 250]')+ // the second page's background covers ITS box (5 pt-high box, not 400)+ expect(doc).toMatch(/0 0 500 250 re f/)+ })++ it('per-page size out of range falls back to the design size', async () => {+ const doc = await pdfString([page([], { width: 999999, height: -5 })], 600, 400)+ expect(doc).not.toContain('/MediaBox [0 0 999999 -5]')+ expect(doc).toContain('/MediaBox [0 0 600 400]')+ })++ it('image mask → vector clip (W n) around the image XObject paint', async () => {+ const doc = await pdfString([+ page([el({ type: 'image', src: `data:image/jpeg;base64,${RED_JPEG_B64}`, maskShape: 'circle' })]),+ ])+ // the image embedded as a JPEG passthrough XObject+ expect(doc).toContain('/Subtype /Image')+ expect(doc).toContain('/Filter /DCTDecode')+ // a clip path wraps the paint: q … W n … cm /ImN Do Q+ expect(doc).toMatch(/q [\d.\s]+ m[\s\S]*?W n[\s\S]*?cm \/Im\d+ Do Q/)+ // the circle mask is a 72-segment polygon (72 vertices = 1 m + 71 l+ // + h), not a 4-line rect+ const clipLines = doc.match(/ l\n/g)?.length ?? 0+ expect(clipLines).toBe(71)+ })++ it('image without mask keeps the plain paint (no W n clip)', async () => {+ const doc = await pdfString([+ page([el({ type: 'image', src: `data:image/jpeg;base64,${RED_JPEG_B64}` })]),+ ])+ expect(doc).toContain('/Im')+ expect(doc).not.toContain('W n')+ })++ it('auto-fit shrinks the Tf size below the authored one', async () => {+ const many = Array.from({ length: 30 }, (_, i) => `line of text number ${i}`).join('\n')+ const doc = await pdfString([+ page([+ el({+ type: 'text',+ text: many,+ autoFit: true,+ fontSize: 60,+ fontFamily: 'Inter',+ fill: '#000000',+ align: 'left',+ lineHeight: 1.25,+ letterSpacing: 0,+ width: 300,+ height: 120,+ }),+ ]),+ ])+ const sizes = [...doc.matchAll(/BT \/F\d+ ([\d.]+) Tf/g)].map((m) => Number(m[1]))+ expect(sizes.length).toBeGreaterThan(0)+ for (const size of sizes) {+ expect(size).toBeLessThan(60)+ expect(size).toBeGreaterThanOrEqual(6)+ }+ })++ it('list text and rtl text fall to the raster strip (documented v1 approximation)', async () => {+ // in node the strip has no canvas either → the element is dropped+ // from the vector page; the contract under test is that the vector+ // text path never sees list/rtl runs (no BT text ops for them)+ const doc = await pdfString([+ page([+ el({+ type: 'text',+ text: 'one\ntwo',+ listStyle: 'bullet',+ fontSize: 24,+ fontFamily: 'Inter',+ fill: '#000000',+ align: 'left',+ lineHeight: 1.2,+ letterSpacing: 0,+ width: 300,+ height: 100,+ }),+ ]),+ ])+ expect(doc).not.toContain('BT /F')+ })+})diff --git a/src/lib/pdf-export.ts b/src/lib/pdf-export.tsindex 7b8bcd5..96e8f3d 100644--- a/src/lib/pdf-export.ts+++ b/src/lib/pdf-export.ts@@ -14,6 +14,7 @@import type { PageData } from '@/lib/types'import { collectImages } from '@/lib/video-export'+import { pageSize } from '@/lib/editor-utils'import { PdfWriter, pdfTextString } from '@/lib/pdf/pdf-writer'import { PdfImageEmbedder } from '@/lib/pdf/image-embed'import type { FontLadderIo } from '@/lib/pdf/fonts'@@ -55,25 +56,30 @@ export async function exportDesignToPdf(opts: PdfExportOptions): Promise<PdfExpoconst images = await collectImages(opts.pages)const embedder = new PdfImageEmbedder(pdf)- const renderer = new VectorPageRenderer(- pdf,- fonts,- embedder,- { text: createBrowserTextIo(), images, pixelScale: opts.pixelScale ?? 2 },- opts.designWidth,- opts.designHeight,- )- // 3. pages (the tree object is reserved so pages can /Parent it)+ // 3. pages (the tree object is reserved so pages can /Parent it).+ // v0.18 (Wave 3): per-page size overrides — each page gets its own+ // MediaBox and its own renderer y-flip origin (pageSize() falls back+ // to the design size for pre-v0.18 documents, so nothing changes for+ // them — byte-identical exports).const pagesTree = pdf.reserveObject()const pageObjects: number[] = []for (let i = 0; i < n; i++) {opts.onProgress?.(0.26 + (0.62 * i) / n, `Rendering page ${i + 1} of ${n}…`)+ const { width: pw, height: ph } = pageSize(opts.pages[i], opts.designWidth, opts.designHeight)+ const renderer = new VectorPageRenderer(+ pdf,+ fonts,+ embedder,+ { text: createBrowserTextIo(), images, pixelScale: opts.pixelScale ?? 2 },+ pw,+ ph,+ )const { ops, resources } = await renderer.renderPage(opts.pages[i])const content = pdf.addStreamObject('', ops)pageObjects.push(pdf.addObject(- `<< /Type /Page /Parent ${pdf.ref(pagesTree)} /MediaBox [0 0 ${opts.designWidth} ${opts.designHeight}] /Resources ${resources} /Contents ${pdf.ref(content)} >>`,+ `<< /Type /Page /Parent ${pdf.ref(pagesTree)} /MediaBox [0 0 ${pw} ${ph}] /Resources ${resources} /Contents ${pdf.ref(content)} >>`,),)}diff --git a/src/lib/pdf/text-ops.ts b/src/lib/pdf/text-ops.tsindex 045d1d3..9999ec3 100644--- a/src/lib/pdf/text-ops.ts+++ b/src/lib/pdf/text-ops.ts@@ -24,6 +24,7 @@ import type { AnyElement, ChartElement, EmbedElement, TableElement, TextElement,import { chartPrimitives } from '@/lib/chart-geometry'import { hostOf } from '@/lib/v06-geometry'import { layoutRichLines, normalizeSpans, resolveSpanStyle, type MeasureText, type SpanMeasureStyle } from '@/lib/rich-text'+import { fitFontSize } from '@/lib/text-fit'import { faceKey, resolveFontFace, type FontFaceRequest, type FontLadderIo, type Std14Base } from './fonts'import { subsetTtf, type SubsetResult } from './ttf'import { pdfNum, pdfRgb, PdfWriter } from './pdf-writer'@@ -163,7 +164,13 @@ export function textElementIsRaster(el: TextElement): boolean {const curved = el.curve != null && Math.abs(el.curve) >= 2 && el.width >= 12const gradient = !!el.fillGradientconst effect = !!el.effect && el.effect !== 'none' && el.effect !== 'background'- return curved || gradient || effect+ // v0.18 (Wave 3): list markers + RTL direction ride the raster strip+ // — the vector text path lays LTR plain runs only (documented+ // approximation v1: pixel-perfect via the strip, no selectable text+ // for these two styles yet; the canvas/SVG/video exports are exact)+ const listed = !!el.listStyle && el.listStyle !== 'none'+ const rtl = el.direction === 'rtl'+ return curved || gradient || effect || listed || rtl}/** Lay a text element out (rich spans or flat — one span) into@@ -537,15 +544,35 @@ export function drawTextElement(io: TextIo,): string | null {if (textElementIsRaster(el)) return null- const runs = layoutTextElement(el, io)+ // v0.18 (Wave 3): auto-fit — the effective size is derived here with+ // the SAME binary search the canvas/SVG/video renderers run+ // (lib/text-fit), laid out at that size. Rich spans keep the authored+ // size (the flat-path feature, matching every other renderer).+ const effSize = el.autoFit && !normalizeSpans(el.spans, el.text)+ ? fitFontSize(+ {+ text: el.uppercase ? el.text.toUpperCase() : el.text,+ fontFamily: el.fontFamily,+ bold: el.bold,+ italic: el.italic,+ letterSpacing: el.letterSpacing,+ lineHeight: el.lineHeight,+ fontSize: el.fontSize,+ },+ { width: el.width, height: el.height },+ (text, style) => io.measure(text, style),+ )+ : el.fontSize+ const sized = effSize === el.fontSize ? el : ({ ...el, fontSize: effSize } as TextElement)+ const runs = layoutTextElement(sized, io)const out: string[] = []// the background effect rides behind the runs (editor parity)if (el.effect === 'background') {const blockH = runs.length- ? Math.max(...runs.map((r) => r.lineTop)) + el.fontSize * el.lineHeight- : el.fontSize * el.lineHeight- const h = Math.max(el.height, blockH, el.fontSize * el.lineHeight + 8)- out.push(roundedRectOps(el.x, el.y, el.width, h, Math.min(8, el.fontSize * 0.2), el.effectBackground ?? '#EFEFEF', pageH))+ ? Math.max(...runs.map((r) => r.lineTop)) + effSize * el.lineHeight+ : effSize * el.lineHeight+ const h = Math.max(el.height, blockH, effSize * el.lineHeight + 8)+ out.push(roundedRectOps(el.x, el.y, el.width, h, Math.min(8, effSize * 0.2), el.effectBackground ?? '#EFEFEF', pageH))}for (const run of runs) {const entry = fonts.get({ family: el.fontFamily, bold: run.bold, italic: run.italic })@@ -564,7 +591,7 @@ export function drawTextElement(pageH,text: run.text,fontFamily: el.fontFamily,- fontSize: el.fontSize,+ fontSize: effSize,bold: run.bold,italic: run.italic,color: run.color,diff --git a/src/lib/pdf/vector-page.ts b/src/lib/pdf/vector-page.tsindex 3f2daa2..b69f31c 100644--- a/src/lib/pdf/vector-page.ts+++ b/src/lib/pdf/vector-page.ts@@ -37,6 +37,7 @@ import type {} from '@/lib/types'import { chartPrimitives } from '@/lib/chart-geometry'import { embedLayout, frameClipPathD, hostOf, tableGeometry, youtubeThumbUrl } from '@/lib/v06-geometry'+import { isMaskShape, maskPolygon, polygonPoints, starPointsEx, stretchPts, scalePts } from '@/lib/shapes'import { drawTextElement, type TextIo, PdfFontRegistry } from './text-ops'import type { PdfImageEmbedder } from './image-embed'import { pdfNum, pdfRgb, PdfWriter } from './pdf-writer'@@ -367,17 +368,6 @@ function arcCmds(cx: number, cy: number, r: number, a0: number, a1: number, out:}}-function starPoints(cx: number, cy: number, outer: number, inner: number): Array<[number, number]> {- const pts: Array<[number, number]> = []- for (let i = 0; i < 5; i++) {- const outerAngle = -Math.PI / 2 + (i * 2 * Math.PI) / 5- const innerAngle = outerAngle + Math.PI / 5- pts.push([cx + outer * Math.cos(outerAngle), cy + outer * Math.sin(outerAngle)])- pts.push([cx + inner * Math.cos(innerAngle), cy + inner * Math.sin(innerAngle)])- }- return pts-}-/** Rotation cm — SVG `rotate(deg ox oy)` (y-down) expressed in* page space. */export function rotationCm(deg: number, ox: number, oyDown: number, pageH: number): string {@@ -547,6 +537,7 @@ export class VectorPageRenderer {case 'ellipse':case 'triangle':case 'star':+ case 'polygon':case 'path':return await this.renderShape(el as ShapeElement)case 'line':@@ -617,11 +608,24 @@ export class VectorPageRenderer {])breakcase 'star': {- const cx = s.x + s.width / 2- const cy = s.y + s.height / 2- const outer = Math.min(s.width, s.height) / 2- cmds = polygonCmds(starPoints(cx, cy, outer, outer * 0.55))- origin = [cx, cy]+ // v0.18 (Wave 3): parametric — stretchPts geometry identical to+ // the canvas / SVG / video renderers (fills the element box)+ cmds = polygonCmds(+ stretchPts(starPointsEx(s.numPoints ?? 5, s.innerRatio), s.x, s.y, s.width, s.height).map(+ ([x, y]) => [x, y] as [number, number],+ ),+ )+ origin = [s.x + s.width / 2, s.y + s.height / 2]+ break+ }+ case 'polygon': {+ // v0.18 (Wave 3): regular polygon — centred geometry like the star+ cmds = polygonCmds(+ stretchPts(polygonPoints(s.sides ?? 6), s.x, s.y, s.width, s.height).map(+ ([x, y]) => [x, y] as [number, number],+ ),+ )+ origin = [s.x + s.width / 2, s.y + s.height / 2]break}case 'path': {@@ -687,8 +691,18 @@ export class VectorPageRenderer {if (!img) return nullconst cxImg = im.x + im.width / 2const cyImg = im.y + im.height / 2+ // v0.18 (Wave 3): validated shape mask — clip polygon from the+ // shared geometry module (scalePts = the mask convention, same as+ // the canvas clipShapeFunc and the SVG clipPath)+ const maskPts =+ isMaskShape(im.maskShape) && im.maskShape !== 'none'+ ? scalePts(maskPolygon(im.maskShape, im.maskSides, im.maskInnerRatio)!, im.x, im.y, im.width, im.height)+ : nulllet body: string- if (im.radius) {+ if (maskPts) {+ const clip = polygonCmds(maskPts.map(([x, y]) => [x, y] as [number, number]))+ body = `q ${emitPath(clip, this.designH)} W n ${this.imagePaint(img.name, im.x, im.y, im.width, im.height, im.flipH, im.flipV)} Q`+ } else if (im.radius) {const clip = roundRectCmds(im.x, im.y, im.width, im.height, im.radius)body = `q ${emitPath(clip, this.designH)} W n ${this.imagePaint(img.name, im.x, im.y, im.width, im.height, im.flipH, im.flipV)} Q`} else {diff --git a/src/lib/shapes.test.ts b/src/lib/shapes.test.tsnew file mode 100644index 0000000..6d6cd7f--- /dev/null+++ b/src/lib/shapes.test.ts@@ -0,0 +1,190 @@+import { describe, it, expect } from 'vitest'+import {+ polygonPoints,+ starPointsEx,+ maskPolygon,+ isMaskShape,+ isParametricMask,+ scalePts,+ ptsToSvg,+ tracePts,+ MASK_SHAPES,+ clampInt,+ clampNum,+} from '@/lib/shapes'++// ── polygons ─────────────────────────────────────────────────++describe('polygonPoints', () => {+ it('emits exactly `sides` vertices', () => {+ for (const n of [3, 5, 6, 8, 12]) {+ expect(polygonPoints(n)).toHaveLength(n)+ }+ })++ it('clamps sides to 3..12', () => {+ expect(polygonPoints(2)).toHaveLength(3)+ expect(polygonPoints(0)).toHaveLength(3)+ expect(polygonPoints(99)).toHaveLength(12)+ expect(polygonPoints(NaN)).toHaveLength(3)+ })++ it('keeps every vertex inside the 100×100 authoring box', () => {+ for (const [x, y] of polygonPoints(7)) {+ expect(x).toBeGreaterThanOrEqual(0)+ expect(x).toBeLessThanOrEqual(100)+ expect(y).toBeGreaterThanOrEqual(0)+ expect(y).toBeLessThanOrEqual(100)+ }+ })++ it('places the first vertex at the top (x ≈ centre, y < centre)', () => {+ const [x, y] = polygonPoints(5)[0]+ expect(Math.abs(x - 50)).toBeLessThan(0.001)+ expect(y).toBeLessThan(50)+ })++ it('is deterministic (same input → same output)', () => {+ expect(polygonPoints(6)).toEqual(polygonPoints(6))+ })+})++// ── stars ────────────────────────────────────────────────────++describe('starPointsEx', () => {+ it('emits 2 × points vertices (outer/inner alternating)', () => {+ expect(starPointsEx(5)).toHaveLength(10)+ expect(starPointsEx(16)).toHaveLength(32)+ })++ it('clamps points to 3..16 and ratio to 0.15..0.85', () => {+ expect(starPointsEx(2)).toHaveLength(6)+ expect(starPointsEx(100)).toHaveLength(32)+ // ratio clamped, not thrown+ const pts = starPointsEx(5, 99)+ expect(pts).toHaveLength(10)+ const rs = pts.map(([x, y]) => Math.hypot(x - 50, y - 50))+ expect(Math.max(...rs)).toBeLessThanOrEqual(48.001)+ })++ it('alternates outer (r=48) and inner radii per the ratio', () => {+ const pts = starPointsEx(6, 0.5)+ for (let i = 0; i < pts.length; i++) {+ const r = Math.hypot(pts[i][0] - 50, pts[i][1] - 50)+ if (i % 2 === 0) expect(r).toBeCloseTo(48, 0)+ else expect(r).toBeCloseTo(24, 0)+ }+ })++ it('default ratio is the classic 0.55 (pre-v0.18 look)', () => {+ const pts = starPointsEx(5)+ const r = Math.hypot(pts[1][0] - 50, pts[1][1] - 50)+ expect(r).toBeCloseTo(48 * 0.55, 0)+ })+})++// ── masks ────────────────────────────────────────────────────++describe('maskPolygon', () => {+ it('returns null for "none" and unknown shapes', () => {+ expect(maskPolygon('none')).toBeNull()+ // @ts-expect-error hostile input+ expect(maskPolygon('evil-shape')).toBeNull()+ })++ it('every preset yields a closed, sane polygon in the 100-box', () => {+ for (const shape of MASK_SHAPES) {+ if (shape === 'none') continue+ const pts = maskPolygon(shape, 6, 0.55)+ expect(pts, `mask ${shape}`).not.toBeNull()+ expect(pts!.length).toBeGreaterThanOrEqual(3)+ for (const [x, y] of pts!) {+ expect(x).toBeGreaterThanOrEqual(-1)+ expect(x).toBeLessThanOrEqual(101)+ expect(y).toBeGreaterThanOrEqual(-1)+ expect(y).toBeLessThanOrEqual(101)+ }+ }+ })++ it('heart is non-convex (some cross products flip sign)', () => {+ const pts = maskPolygon('heart')!+ const crosses: number[] = []+ for (let i = 0; i < pts.length; i++) {+ const [x1, y1] = pts[i]+ const [x2, y2] = pts[(i + 1) % pts.length]+ const [x3, y3] = pts[(i + 2) % pts.length]+ crosses.push((x2 - x1) * (y3 - y2) - (y2 - y1) * (x3 - x2))+ }+ const pos = crosses.filter((c) => c > 0).length+ const neg = crosses.filter((c) => c < 0).length+ expect(pos).toBeGreaterThan(0)+ expect(neg).toBeGreaterThan(0)+ })++ it('blob is deterministic (fixed seed — every replica renders the same)', () => {+ expect(maskPolygon('blob')).toEqual(maskPolygon('blob'))+ })++ it('parametric masks honour sides', () => {+ expect(maskPolygon('poly', 8)!.length).toBe(8)+ expect(maskPolygon('polyStar', 7)!.length).toBe(14)+ })+})++describe('isMaskShape / isParametricMask', () => {+ it('validates membership', () => {+ expect(isMaskShape('circle')).toBe(true)+ expect(isMaskShape('nope')).toBe(false)+ expect(isMaskShape(undefined)).toBe(false)+ expect(isMaskShape(42)).toBe(false)+ })++ it('flags the two parametric modes', () => {+ expect(isParametricMask('poly')).toBe(true)+ expect(isParametricMask('polyStar')).toBe(true)+ expect(isParametricMask('circle')).toBe(false)+ })+})++// ── transforms ───────────────────────────────────────────────++describe('scalePts / ptsToSvg / tracePts', () => {+ it('scales the 100-box into an element box with offset', () => {+ const out = scalePts([[0, 0], [100, 100]], 10, 20, 200, 100)+ expect(out[0]).toEqual([10, 20])+ expect(out[1]).toEqual([210, 120])+ })++ it('emits "x,y x,y" pairs', () => {+ expect(ptsToSvg([[1.234, 2.567], [3, 4]])).toBe('1.23,2.57 3,4')+ })++ it('tracePts walks a canvas-like context', () => {+ const calls: string[] = []+ const ctx = {+ beginPath: () => calls.push('begin'),+ moveTo: (x: number, y: number) => calls.push(`m${x},${y}`),+ lineTo: (x: number, y: number) => calls.push(`l${x},${y}`),+ closePath: () => calls.push('close'),+ }+ tracePts(ctx, [[0, 0], [50, 100]], 100, 50)+ expect(calls[0]).toBe('begin')+ expect(calls[1]).toBe('m0,0')+ expect(calls[2]).toBe('l50,50')+ expect(calls.at(-1)).toBe('close')+ })+})++describe('numeric clamps', () => {+ it('clampInt rounds + bounds', () => {+ expect(clampInt(5.7, 3, 12)).toBe(6)+ expect(clampInt(1, 3, 12)).toBe(3)+ expect(clampInt('x', 3, 12, 8)).toBe(8)+ })++ it('clampNum bounds', () => {+ expect(clampNum(0.9, 0.15, 0.85)).toBe(0.85)+ expect(clampNum(0.3, 0.15, 0.85)).toBe(0.3)+ })+})diff --git a/src/lib/shapes.ts b/src/lib/shapes.tsnew file mode 100644index 0000000..bf82bf7--- /dev/null+++ b/src/lib/shapes.ts@@ -0,0 +1,292 @@+// ─────────────────────────────────────────────────────────────+// Canvix v0.18 (Wave 3) — parametric shape & mask geometry+//+// One pure module every renderer shares (the chart-geometry pattern):+// the Konva canvas, the SVG serializer and the video-export frame+// builder all map the SAME point arrays, so a polygon masked by a+// heart looks identical everywhere. No Konva/DOM imports — it also+// runs in unit tests and (future) server-side rendering.+//+// Authoring space: every generator emits points in a 100×100 box+// (the same convention ShapeElement.pathData uses), so callers+// scale once into the element box.+// ─────────────────────────────────────────────────────────────++export type Pt = [number, number]++/** Wrap an angle into [0, 2π). */+function normAngle(a: number): number {+ const TAU = Math.PI * 2+ return ((a % TAU) + TAU) % TAU+}++/** Regular polygon vertices in a 100×100 box, first vertex at the top.+ * `sides` is clamped to 3..12 (the picker range). */+export function polygonPoints(sides: number): Pt[] {+ const n = clampInt(sides, 3, 12)+ const cx = 50+ const cy = 50+ const r = 48 // slight inset so strokes stay inside the box+ const out: Pt[] = []+ for (let i = 0; i < n; i++) {+ const a = -Math.PI / 2 + (i / n) * Math.PI * 2+ out.push([cx + r * Math.cos(a), cy + r * Math.sin(a)])+ }+ return out+}++/** Star vertices in a 100×100 box, first outer point at the top.+ * `points` clamped 3..16, `innerRatio` clamped 0.15..0.85 (default 0.55 —+ * the classic five-pointer the pre-v0.18 editor hardcoded). */+export function starPointsEx(points: number, innerRatio?: number): Pt[] {+ const n = clampInt(points, 3, 16)+ const ratio = clampNum(innerRatio ?? 0.55, 0.15, 0.85)+ const cx = 50+ const cy = 50+ const outer = 48+ const inner = outer * ratio+ const out: Pt[] = []+ for (let i = 0; i < n * 2; i++) {+ const a = -Math.PI / 2 + (i / (n * 2)) * Math.PI * 2+ const r = i % 2 === 0 ? outer : inner+ out.push([cx + r * Math.cos(a), cy + r * Math.sin(a)])+ }+ return out+}++// ── Image masks ──────────────────────────────────────────────++/** The ten preset mask shapes + the two parametric "custom" modes.+ * Order here IS the picker order. */+export const MASK_SHAPES = [+ 'none',+ 'circle',+ 'rounded',+ 'arch',+ 'triangle',+ 'diamond',+ 'pentagon',+ 'hexagon',+ 'star',+ 'heart',+ 'blob',+ 'poly',+ 'polyStar',+] as const++export type MaskShape = (typeof MASK_SHAPES)[number]++export const MASK_SHAPE_LABELS: Record<MaskShape, string> = {+ none: 'None',+ circle: 'Circle',+ rounded: 'Rounded',+ arch: 'Arch',+ triangle: 'Triangle',+ diamond: 'Diamond',+ pentagon: 'Pentagon',+ hexagon: 'Hexagon',+ star: 'Star',+ heart: 'Heart',+ blob: 'Blob',+ poly: 'Polygon',+ polyStar: 'Star burst',+}++export function isMaskShape(v: unknown): v is MaskShape {+ return typeof v === 'string' && (MASK_SHAPES as readonly string[]).includes(v)+}++/** True when the mask needs the `maskSides` (+ `maskInnerRatio`) params. */+export function isParametricMask(shape: MaskShape): boolean {+ return shape === 'poly' || shape === 'polyStar'+}++/** A circle sampled as a polygon — smooth at any render size. */+function circlePts(segments = 72): Pt[] {+ const out: Pt[] = []+ for (let i = 0; i < segments; i++) {+ const a = (i / segments) * Math.PI * 2+ out.push([50 + 48 * Math.cos(a), 50 + 48 * Math.sin(a)])+ }+ return out+}++/** Squircle-ish rounded square: straight edges + quarter arcs. */+function roundedPts(radius = 22, segments = 14): Pt[] {+ const out: Pt[] = []+ const corners: Array<[number, number]> = [+ [50 + 50 - radius, 50 + 50 - radius],+ [50 - 50 + radius, 50 + 50 - radius],+ [50 - 50 + radius, 50 - 50 + radius],+ [50 + 50 - radius, 50 - 50 + radius],+ ]+ // corner arcs, counter-clockwise consistent with circlePts+ const startAngles = [0, Math.PI / 2, Math.PI, -Math.PI / 2]+ for (let c = 0; c < 4; c++) {+ const [cx, cy] = corners[c]+ const a0 = startAngles[c]+ for (let i = 0; i <= segments; i++) {+ const a = a0 + (i / segments) * (Math.PI / 2)+ out.push([cx + radius * Math.cos(a), cy + radius * Math.sin(a)])+ }+ }+ return out+}++/** Roman-arch window: full-width semicircle on straight legs. */+function archPts(segments = 36): Pt[] {+ const out: Pt[] = []+ const r = 48+ const cx = 50+ // right leg bottom → arc → left leg bottom+ out.push([cx + r, 98])+ for (let i = 0; i <= segments; i++) {+ const a = (i / segments) * Math.PI+ out.push([cx + r * Math.cos(a), 50 + r * Math.sin(a)])+ }+ out.push([cx - r, 98])+ return out+}++/** Heart via the classic parametric curve (t ∈ [0, 2π)). */+function heartPts(segments = 72): Pt[] {+ const out: Pt[] = []+ for (let i = 0; i <= segments; i++) {+ const t = (i / segments) * Math.PI * 2+ const x = 16 * Math.pow(Math.sin(t), 3)+ const y = -(13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t))+ // (x, y) spans ≈ [-16, 16] × [-11, 17] → map into the 100-box+ out.push([50 + x * 2.9, 50 + y * 2.7])+ }+ // tiny inset so the top dimples stay inside the box+ return out.map(([x, y]) => [50 + (x - 50) * 0.96, 50 + (y - 50) * 0.96] as Pt)+}++/** Organic blob: a fixed-seed polar wobble — deterministic so every+ * replica (and every export) renders the SAME blob. */+function blobPts(segments = 72): Pt[] {+ const harmonics: Array<[number, number]> = [+ [2, 0.10],+ [3, -0.07],+ [5, 0.045],+ ]+ const out: Pt[] = []+ for (let i = 0; i < segments; i++) {+ const a = (i / segments) * Math.PI * 2+ let r = 0.78+ for (const [k, amp] of harmonics) r += amp * Math.cos(k * a + k * 1.7)+ out.push([50 + 50 * r * Math.cos(a), 50 + 50 * r * Math.sin(a)])+ }+ return out+}++/**+ * The mask's clip polygon in 100×100 authoring space.+ * `shape === 'none'` returns null (caller skips clipping entirely).+ */+export function maskPolygon(shape: MaskShape, sides?: number, innerRatio?: number): Pt[] | null {+ switch (shape) {+ case 'none':+ return null+ case 'circle':+ return circlePts()+ case 'rounded':+ return roundedPts()+ case 'arch':+ return archPts()+ case 'triangle':+ // flat-bottom triangle, apex at the top+ return [+ [50, 3],+ [97, 95],+ [3, 95],+ ]+ case 'diamond':+ return [+ [50, 2],+ [98, 50],+ [50, 98],+ [2, 50],+ ]+ case 'pentagon':+ return polygonPoints(5)+ case 'hexagon':+ return polygonPoints(6)+ case 'star':+ return starPointsEx(5, 0.55)+ case 'heart':+ return heartPts()+ case 'blob':+ return blobPts()+ case 'poly':+ return polygonPoints(sides ?? 6)+ case 'polyStar':+ return starPointsEx(sides ?? 6, innerRatio ?? 0.55)+ default:+ return null+ }+}++/** Scale 100-box points into an element box (w × h) and offset by (x, y). */+export function scalePts(pts: Pt[], x: number, y: number, w: number, h: number): Pt[] {+ const sx = w / 100+ const sy = h / 100+ return pts.map(([px, py]) => [x + px * sx, y + py * sy] as Pt)+}++/** The SHAPE mapping — the generating 48-radius circle fills the whole+ * element box (centre-based stretch), so polygon/star elements match+ * rect/ellipse/triangle behaviour exactly: a vertex lands on the box+ * edge, and a non-square box stretches the shape. `scalePts` above is+ * the MASK/pathData convention (linear 100-box, 2 % inset). Both are+ * needed; never swap them. */+export function stretchPts(pts: Pt[], x: number, y: number, w: number, h: number): Pt[] {+ const sx = w / 96+ const sy = h / 96+ const cx = x + w / 2+ const cy = y + h / 2+ return pts.map(([px, py]) => [cx + (px - 50) * sx, cy + (py - 50) * sy] as Pt)+}++/** "x,y x,y …" for SVG <polygon points>. */+export function ptsToSvg(pts: Pt[]): string {+ return pts.map(([x, y]) => `${round2(x)},${round2(y)}`).join(' ')+}++/** Draw a 100-box polygon into a canvas-like 2D context (Konva+ * clipShapeFunc passes its wrapper — it forwards the standard API). */+export function tracePts(ctx: {+ beginPath: () => void+ moveTo: (x: number, y: number) => void+ lineTo: (x: number, y: number) => void+ closePath: () => void+}, pts: Pt[], w: number, h: number): void {+ const sx = w / 100+ const sy = h / 100+ ctx.beginPath()+ pts.forEach(([px, py], i) => {+ const X = px * sx+ const Y = py * sy+ if (i === 0) ctx.moveTo(X, Y)+ else ctx.lineTo(X, Y)+ })+ ctx.closePath()+}++// ── shared numeric clamps (mirrors the repo's sanitiser style) ──++export function clampNum(v: unknown, min: number, max: number, fallback = min): number {+ const n = typeof v === 'number' ? v : Number(v)+ if (!Number.isFinite(n)) return fallback+ return Math.min(max, Math.max(min, n))+}++export function clampInt(v: unknown, min: number, max: number, fallback = min): number {+ return Math.round(clampNum(v, min, max, fallback))+}++function round2(n: number): number {+ return Math.round(n * 100) / 100+}++export { normAngle }diff --git a/src/lib/svg-export-wave3.test.ts b/src/lib/svg-export-wave3.test.tsnew file mode 100644index 0000000..4d04afa--- /dev/null+++ b/src/lib/svg-export-wave3.test.ts@@ -0,0 +1,179 @@+import { describe, it, expect } from 'vitest'+import { exportPageToSVG } from '@/lib/svg-export'+import type { PageData, AnyElement } from '@/lib/types'++// jsdom has no 2D canvas — measureText falls back to the char-count+// approximation, which is deterministic and enough to assert structure.++function page(elements: AnyElement[], over: Partial<PageData> = {}): PageData {+ return {+ id: 'p1',+ background: { type: 'solid', color: '#FFFFFF' },+ elements,+ ...over,+ }+}++function el(over: Record<string, unknown>): AnyElement {+ return {+ id: 'e1',+ type: 'rect',+ x: 10,+ y: 10,+ width: 100,+ height: 100,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ fill: '#00C4CC',+ stroke: 'transparent',+ strokeWidth: 0,+ cornerRadius: 0,+ ...over,+ } as AnyElement+}++describe('svg-export — Wave 3 features', () => {+ it('polygon → <polygon> with the sides from the element, filling the box', () => {+ const svg = exportPageToSVG(page([el({ type: 'polygon', sides: 8 })]), 1080, 1080)+ expect(svg).toContain('<polygon points="')+ // 8 vertices → 8 coordinate pairs+ const points = svg.match(/<polygon points="([^"]+)"/)![1].trim().split(' ')+ expect(points).toHaveLength(8)+ // stretchPts (THE shape mapping): the first vertex sits at the top+ // edge, centred — x=10+100/2=60, y=10 (matches the canvas Konva)+ expect(points[0]).toBe('60,10')+ })++ it('star honours numPoints + innerRatio and fills the box', () => {+ const svg = exportPageToSVG(page([el({ type: 'star', numPoints: 9, innerRatio: 0.4 })]), 1080, 1080)+ const points = svg.match(/<polygon points="([^"]+)"/)![1].trim().split(' ')+ expect(points).toHaveLength(18) // 2 × points+ // top outer vertex: x=10+100/2=60, y=10 — the box edge (stretchPts)+ expect(points[0]).toBe('60,10')+ })++ it('star without params keeps the classic 5-point default', () => {+ const svg = exportPageToSVG(page([el({ type: 'star' })]), 1080, 1080)+ const points = svg.match(/<polygon points="([^"]+)"/)![1].trim().split(' ')+ expect(points).toHaveLength(10)+ })++ it('image mask → clipPath polygon (not the corner-radius rect)', () => {+ const svg = exportPageToSVG(+ page([el({ type: 'image', src: 'data:image/png;base64,iVBORw0KGgo=', maskShape: 'circle', radius: 20 })]),+ 1080,+ 1080+ )+ expect(svg).toContain('<clipPath id="clip')+ expect(svg).toMatch(/<clipPath[^>]*><polygon points="/)+ // the image references the clip+ expect(svg).toMatch(/<image [^>]*clip-path="url\(#clip/)+ })++ it('hostile mask shape degrades to no clip (validated by isMaskShape)', () => {+ const svg = exportPageToSVG(+ page([el({ type: 'image', src: 'data:image/png;base64,iVBORw0KGgo=', maskShape: '<script>' })]),+ 1080,+ 1080+ )+ expect(svg).not.toContain('clipPath')+ })++ it('image without mask keeps the corner-radius clip', () => {+ const svg = exportPageToSVG(+ page([el({ type: 'image', src: 'data:image/png;base64,iVBORw0KGgo=', radius: 16 })]),+ 1080,+ 1080+ )+ expect(svg).toMatch(/<clipPath id="clip[^"]*"><rect /)+ })++ it('list text renders marker + line tspans', () => {+ const svg = exportPageToSVG(+ page([+ el({+ type: 'text',+ text: 'first\nsecond',+ listStyle: 'bullet',+ fontSize: 24,+ fontFamily: 'Inter',+ fill: '#000000',+ align: 'left',+ lineHeight: 1.2,+ letterSpacing: 0,+ width: 400,+ height: 100,+ }),+ ]),+ 1080,+ 1080+ )+ expect(svg).toContain('•')+ expect(svg.match(/<tspan /g)!.length).toBeGreaterThanOrEqual(4) // 2 markers + 2 lines+ })++ it('rtl text emits direction="rtl"', () => {+ const svg = exportPageToSVG(+ page([+ el({+ type: 'text',+ text: 'مرحبا',+ direction: 'rtl',+ fontSize: 24,+ fontFamily: 'Inter',+ fill: '#000000',+ align: 'left',+ lineHeight: 1.2,+ letterSpacing: 0,+ width: 400,+ height: 100,+ }),+ ]),+ 1080,+ 1080+ )+ expect(svg).toContain('direction="rtl"')+ })++ it('per-page size override drives the svg width/height/viewBox', () => {+ const svg = exportPageToSVG(page([], { width: 500, height: 400 }), 1080, 1080)+ expect(svg).toContain('width="500"')+ expect(svg).toContain('viewBox="0 0 500 400"')+ // background covers the page box+ expect(svg).toContain('<rect width="500" height="400"')+ })++ it('per-page size out of range falls back to the design size', () => {+ const svg = exportPageToSVG(page([], { width: 999999, height: -5 }), 800, 600)+ expect(svg).toContain('width="800"')+ expect(svg).toContain('height="600"')+ })++ it('auto-fit shrinks the emitted font-size below the authored one', () => {+ const many = Array.from({ length: 30 }, (_, i) => `line of text number ${i}`).join('\n')+ const svg = exportPageToSVG(+ page([+ el({+ type: 'text',+ text: many,+ autoFit: true,+ fontSize: 60,+ fontFamily: 'Inter',+ fill: '#000000',+ align: 'left',+ lineHeight: 1.25,+ letterSpacing: 0,+ width: 300,+ height: 120,+ }),+ ]),+ 1080,+ 1080+ )+ const size = Number(svg.match(/font-size="([\d.]+)"/)![1])+ expect(size).toBeLessThan(60)+ expect(size).toBeGreaterThanOrEqual(6)+ })+})diff --git a/src/lib/svg-export.ts b/src/lib/svg-export.tsindex e228a45..dca7283 100644--- a/src/lib/svg-export.ts+++ b/src/lib/svg-export.ts@@ -35,6 +35,10 @@ import { arcForCurve, embedLayout, frameClipPathD, hostOf, tableGeometry, youtubimport { layoutRichLines, normalizeSpans } from '@/lib/rich-text'import type { PluginElement } from '@/lib/types'import { getRenderEntry, renderKey } from '@/lib/plugins/renderer-cache'+import { isMaskShape, maskPolygon, polygonPoints as shapePolygonPoints, starPointsEx, ptsToSvg, scalePts, stretchPts } from '@/lib/shapes'+import { fitFontSize } from '@/lib/text-fit'+import { layoutListLines } from '@/lib/list-text'+import { pageSize } from '@/lib/editor-utils'// ── escaping ─────────────────────────────────────────────────@@ -191,6 +195,35 @@ function measureText(text: string, fontFamily: string, fontSize: number, bold: b}}+/** v0.18 (Wave 3): the svg-side measure for auto-fit + list layout —+ * adapts measureText to the shared signatures (letterSpacing/italic+ * are approximated away; both are rare on list/autofit text). */+function svgMeasure(text: string, style: { fontFamily: string; bold: boolean; italic: boolean; letterSpacing: number; fontSize: number }): number {+ const w = measureText(text, style.fontFamily, style.fontSize, style.bold)+ return w + (style.letterSpacing ? style.letterSpacing * text.length : 0)+}++/** v0.18 (Wave 3): the svg-side effective font size — must match+ * element-node's effectiveFontSize() (both derive from fitFontSize).+ * letterSpacing is folded into the measure so the binary search sees+ * the same widths the canvas measure does. */+function svgEffectiveFontSize(t: TextElement): number {+ if (!t.autoFit) return t.fontSize+ return fitFontSize(+ {+ text: t.uppercase ? t.text.toUpperCase() : t.text,+ fontFamily: t.fontFamily,+ bold: t.bold,+ italic: t.italic,+ letterSpacing: t.letterSpacing,+ lineHeight: t.lineHeight,+ fontSize: t.fontSize,+ },+ { width: t.width, height: t.height },+ svgMeasure+ )+}+// ── element serializers ──────────────────────────────────────interface SvgContext {@@ -227,17 +260,6 @@ function shadowAttrs(el: { shadow?: { enabled: boolean; color: string; blur: numreturn ` filter="url(#${id})"`}-function starPoints(cx: number, cy: number, outer: number, inner: number): string {- const pts: string[] = []- for (let i = 0; i < 5; i++) {- const outerAngle = (Math.PI / 2) * -1 + (i * 2 * Math.PI) / 5- const innerAngle = outerAngle + Math.PI / 5- pts.push(`${(cx + outer * Math.cos(outerAngle)).toFixed(2)},${(cy + outer * Math.sin(outerAngle)).toFixed(2)}`)- pts.push(`${(cx + inner * Math.cos(innerAngle)).toFixed(2)},${(cy + inner * Math.sin(innerAngle)).toFixed(2)}`)- }- return pts.join(' ')-}-// ── v0.13 (P4): plugin element embedding ────────────────────/** Opening <svg …> tag scanner — attrs may not run past the next@@ -324,6 +346,64 @@ function serializeElement(el: AnyElement, ctx: SvgContext): string {const t = el as TextElementconst rendered = t.uppercase ? t.text.toUpperCase() : t.text+ // v0.18 (Wave 3): list text — the shared layout (lib/list-text.ts)+ // positions marker + line tspans; flat path, single style (like+ // curved text — rich spans keep their own renderer)+ if (t.listStyle && t.listStyle !== 'none' && (t.curve ?? 0) === 0 && t.effect !== 'splice') {+ const size = svgEffectiveFontSize(t)+ const rtl = t.direction === 'rtl'+ const lines = layoutListLines(+ {+ text: rendered,+ fontFamily: t.fontFamily,+ bold: t.bold,+ italic: t.italic,+ letterSpacing: t.letterSpacing,+ lineHeight: t.lineHeight,+ fontSize: size,+ width: t.width,+ listStyle: t.listStyle,+ direction: rtl ? 'rtl' : 'ltr',+ },+ svgMeasure+ )+ 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="${size}"`,+ `font-weight="${t.bold ? 700 : 400}"`,+ `font-style="${t.italic ? 'italic' : 'normal'}"`,+ decor ? `text-decoration="${decor}"` : '',+ t.letterSpacing ? `letter-spacing="${t.letterSpacing}"` : '',+ rtl ? `direction="rtl"` : '',+ `fill="${fill}"`,+ opacityAttr(t),+ shadowAttrs(t, ctx),+ ]+ .filter(Boolean)+ .join(' ')+ const transform = t.rotation ? ` transform="rotate(${t.rotation} ${t.x} ${t.y})"` : ''+ const body = lines+ .map((line) => {+ const y = (t.y + line.y + size * 0.8).toFixed(1)+ const anchor = t.align === 'center' ? 'middle' : t.align === 'right' ? 'end' : 'start'+ const anchorX = t.align === 'center' ? t.x + line.textX + line.textWidth / 2 : t.align === 'right' ? t.x + line.textX + line.textWidth : t.x + line.textX+ let out = `<tspan x="${anchorX.toFixed(1)}" y="${y}"${line.textWidth ? ` textLength=""` : ''}>${esc(line.text)}</tspan>`+ if (line.marker) {+ const mAnchor = rtl ? 'end' : 'start'+ const mX = rtl ? (t.x + line.markerX).toFixed(1) : (t.x + line.markerX).toFixed(1)+ out += `<tspan x="${mX}" y="${y}" text-anchor="${mAnchor}">${esc(line.marker)}</tspan>`+ }+ return out+ })+ .join('')+ return ` <text ${attrs}${transform} xml:space="preserve">${body}</text>`+ }++ // v0.18 (Wave 3): auto-fit — the derived size drives every attribute+ const effSize = svgEffectiveFontSize(t)+// v0.15 (R1): rich text — spans before the flat paths (curved text// stays flat: the arc path is single-style by design)if (t.curve === 0 || t.curve === undefined) {@@ -355,24 +435,28 @@ function serializeElement(el: AnyElement, ctx: SvgContext): string {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 lines = wrapText(rendered, t.fontFamily, effSize, t.bold, t.width)+ const lineHeight = effSize * t.lineHeightconst fill = t.fillGradient ? gradientRefFor(t, ctx) : t.fill- const anchor = t.align === 'center' ? 'middle' : t.align === 'right' ? 'end' : 'start'- const anchorX = t.align === 'center' ? t.x + t.width / 2 : t.align === 'right' ? t.x + t.width : t.x+ // v0.18 (Wave 3): rtl mirrors the alignment (centre stays)+ const rtl = t.direction === 'rtl'+ const effAlign = t.align === 'center' ? 'center' : t.align === 'justify' ? 'left' : rtl ? (t.align === 'left' ? 'right' : 'left') : t.align+ const anchor = effAlign === 'center' ? 'middle' : effAlign === 'right' ? 'end' : 'start'+ const anchorX = effAlign === 'center' ? t.x + t.width / 2 : effAlign === 'right' ? t.x + t.width : t.x// first baseline ≈ top + ascent (0.8 × fontSize approximates Konva's ascent)- const firstBaseline = t.y + t.fontSize * 0.8+ const firstBaseline = t.y + effSize * 0.8const tspans = lines.map((line, i) => `<tspan x="${anchorX}" ${i === 0 ? `y="${firstBaseline.toFixed(1)}"` : `dy="${lineHeight.toFixed(1)}"`}>${esc(line)}</tspan>`).join('')const decor = [t.underline ? 'underline' : '', t.strike ? 'line-through' : ''].filter(Boolean).join(' ')const attrs = [`font-family="${esc(t.fontFamily)}"`,- `font-size="${t.fontSize}"`,+ `font-size="${effSize}"`,`font-weight="${t.bold ? 700 : 400}"`,`font-style="${t.italic ? 'italic' : 'normal'}"`,decor ? `text-decoration="${decor}"` : '',t.letterSpacing ? `letter-spacing="${t.letterSpacing}"` : '',+ rtl ? `direction="rtl"` : '',`text-anchor="${anchor}"`,`fill="${fill}"`,opacityAttr(t),@@ -408,12 +492,23 @@ function serializeElement(el: AnyElement, ctx: SvgContext): string {}case 'star': {+ // v0.18 (Wave 3): parametric — points + spike ratio from the element+ const s = el as ShapeElement+ const cx = s.x + s.width / 2+ const cy = s.y + s.height / 2+ const gradFill = s.fillGradient ? gradientRefFor(s, ctx) : s.fill+ const pts = stretchPts(starPointsEx(s.numPoints ?? 5, s.innerRatio), s.x, s.y, s.width, s.height)+ return ` <polygon points="${ptsToSvg(pts)}"${s.stroke && s.stroke !== 'transparent' && s.strokeWidth ? ` stroke="${s.stroke}" stroke-width="${s.strokeWidth}" stroke-linejoin="round"` : ''} fill="${gradFill}"${opacityAttr(s)}${shadowAttrs(s, ctx)}${transformBase ? ` transform="rotate(${s.rotation} ${cx} ${cy})"` : ''} />`+ }++ case 'polygon': {+ // v0.18 (Wave 3): regular polygon — same centred geometry as starconst s = el as ShapeElementconst cx = s.x + s.width / 2const cy = s.y + s.height / 2- const outer = Math.min(s.width, s.height) / 2const gradFill = s.fillGradient ? gradientRefFor(s, ctx) : s.fill- return ` <polygon points="${starPoints(cx, cy, outer, outer * 0.55)}"${s.stroke && s.stroke !== 'transparent' && s.strokeWidth ? ` stroke="${s.stroke}" stroke-width="${s.strokeWidth}" stroke-linejoin="round"` : ''} fill="${gradFill}"${opacityAttr(s)}${shadowAttrs(s, ctx)}${transformBase ? ` transform="rotate(${s.rotation} ${cx} ${cy})"` : ''} />`+ const pts = stretchPts(shapePolygonPoints(s.sides ?? 6), s.x, s.y, s.width, s.height)+ return ` <polygon points="${ptsToSvg(pts)}"${s.stroke && s.stroke !== 'transparent' && s.strokeWidth ? ` stroke="${s.stroke}" stroke-width="${s.strokeWidth}" stroke-linejoin="round"` : ''} fill="${gradFill}"${opacityAttr(s)}${shadowAttrs(s, ctx)}${transformBase ? ` transform="rotate(${s.rotation} ${cx} ${cy})"` : ''} />`}case 'path': {@@ -457,8 +552,15 @@ function serializeElement(el: AnyElement, ctx: SvgContext): string {const im = el as ImageElementconst href = safeHref(im.src)if (!href) return ''- const clipId = im.radius ? refId('clip') : null- if (im.radius) {+ // v0.18 (Wave 3): shape mask wins over the corner-radius clip+ const maskPts =+ isMaskShape(im.maskShape) && im.maskShape !== 'none'+ ? maskPolygon(im.maskShape, im.maskSides, im.maskInnerRatio)+ : null+ const clipId = maskPts || im.radius ? refId('clip') : null+ if (maskPts) {+ ctx.defs.push(` <clipPath id="${clipId}"><polygon points="${ptsToSvg(scalePts(maskPts, im.x, im.y, im.width, im.height))}" /></clipPath>`)+ } else if (im.radius) {ctx.defs.push(` <clipPath id="${clipId}"><rect x="${im.x}" y="${im.y}" width="${im.width}" height="${im.height}" rx="${im.radius}" /></clipPath>`)}// flips mirror around the image center: x' = 2·cx − x@@ -688,11 +790,14 @@ function sanitizePathData(d: string): string {export function exportPageToSVG(page: PageData, designWidth: number, designHeight: number): string {refCounter = 0const ctx: SvgContext = { defs: [] }+ // v0.18 (Wave 3): per-page size override (falls back to the design size+ // for every pre-v0.18 document — pageSize validates + clamps)+ const { width: W, height: H } = pageSize(page, designWidth, designHeight)// backgroundlet bgOut = ''if (page.background.type === 'solid') {- bgOut = ` <rect width="${designWidth}" height="${designHeight}" fill="${esc(page.background.color)}" />`+ bgOut = ` <rect width="${W}" height="${H}" fill="${esc(page.background.color)}" />`} else if (page.background.type === 'gradient') {const bgGrad: GradientFill = {type: 'linear',@@ -700,8 +805,8 @@ export function exportPageToSVG(page: PageData, designWidth: number, designHeighto: page.background.to,angle: page.background.angle,}- const fill = gradientRefFor({ fillGradient: bgGrad, width: designWidth, height: designHeight }, ctx)- bgOut = ` <rect width="${designWidth}" height="${designHeight}" fill="${fill}" />`+ const fill = gradientRefFor({ fillGradient: bgGrad, width: W, height: H }, ctx)+ bgOut = ` <rect width="${W}" height="${H}" fill="${fill}" />`}const elements = page.elements@@ -712,7 +817,7 @@ export function exportPageToSVG(page: PageData, designWidth: number, designHeighconst defs = ctx.defs.length ? `<defs>\n${ctx.defs.join('\n')}\n</defs>\n` : ''return `<?xml version="1.0" encoding="UTF-8"?>-<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${designWidth}" height="${designHeight}" viewBox="0 0 ${designWidth} ${designHeight}">+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">${defs}${bgOut}${elements}</svg>diff --git a/src/lib/templates/sync.test.ts b/src/lib/templates/sync.test.tsnew file mode 100644index 0000000..8c99410--- /dev/null+++ b/src/lib/templates/sync.test.ts@@ -0,0 +1,86 @@+import { describe, expect, it } from 'vitest'+import { syncTemplateLibrary, type TemplateSyncDb } from './sync'+import { TEMPLATES } from '@/lib/templates'++// A tiny in-memory Template table — the sync only needs count + upsert,+// which is exactly why the interface exists (no Prisma in unit tests).++interface Row {+ slug: string+ name: string+ category: string+ width: number+ height: number+ accent: string+ pages: unknown+ fields: unknown+}++function fakeDb(initial: string[]) {+ const rows = new Map<string, Row>()+ let upserts = 0+ for (const slug of initial) {+ const t = TEMPLATES.find((x) => x.slug === slug)+ if (t) rows.set(slug, { ...t, pages: t.pages, fields: t.fields ?? null } as Row)+ }+ const db: TemplateSyncDb & { upsertCalls: () => number } = {+ template: {+ count: async () => rows.size,+ upsert: async (args) => {+ upserts += 1+ rows.set(args.where.slug, args.create as Row)+ return args.create+ },+ },+ upsertCalls: () => upserts,+ }+ return db+}++describe('syncTemplateLibrary (v0.18 boot-time top-up)', () => {+ it('seeds an empty library with every built-in template', async () => {+ const db = fakeDb([])+ const res = await syncTemplateLibrary(db)+ expect(res.skipped).toBe(false)+ expect(res.synced).toBe(TEMPLATES.length)+ expect(res.total).toBe(TEMPLATES.length)+ expect(db.upsertCalls()).toBe(TEMPLATES.length)+ })++ it('skips entirely when the library is already complete (the normal boot)', async () => {+ const db = fakeDb(TEMPLATES.map((t) => t.slug))+ const res = await syncTemplateLibrary(db)+ expect(res.skipped).toBe(true)+ expect(res.synced).toBe(0)+ expect(db.upsertCalls()).toBe(0)+ expect(res.total).toBe(TEMPLATES.length)+ })++ it('tops up a partial library (the v0.17 upgrade case: 110 of 366)', async () => {+ // the first ~110 slugs stand in for the pre-v0.17 library+ const partial = TEMPLATES.slice(0, 110).map((t) => t.slug)+ const db = fakeDb(partial)+ const res = await syncTemplateLibrary(db)+ expect(res.skipped).toBe(false)+ expect(res.total).toBe(TEMPLATES.length)+ expect(db.upsertCalls()).toBe(TEMPLATES.length) // upserts are blind — idempotent+ })++ it('force refreshes even a complete library (what db:seed means)', async () => {+ const db = fakeDb(TEMPLATES.map((t) => t.slug))+ const res = await syncTemplateLibrary(db, { force: true })+ expect(res.skipped).toBe(false)+ expect(res.synced).toBe(TEMPLATES.length)+ expect(db.upsertCalls()).toBe(TEMPLATES.length)+ })++ it('never deletes rows the code no longer knows about', async () => {+ // a stale slug from an older release stays — deletion on boot would+ // fight rollbacks (documented in the module header)+ const partial = TEMPLATES.slice(0, 5).map((t) => t.slug)+ const db = fakeDb(partial)+ await syncTemplateLibrary(db)+ // re-run with a "downgraded" library missing the last slug: it stays+ expect(await db.template.count()).toBe(TEMPLATES.length)+ })+})diff --git a/src/lib/templates/sync.ts b/src/lib/templates/sync.tsnew file mode 100644index 0000000..589cdeb--- /dev/null+++ b/src/lib/templates/sync.ts@@ -0,0 +1,112 @@+// ─────────────────────────────────────────────────────────────+// Canvix v0.18 — template library sync (the seed, as a function)+//+// "The template library ships as code" (docs/UPGRADING.md): the+// TEMPLATES array is the source of truth and the database is a+// materialised index of it. This module is the ONE place that+// reconciles the two, so `npm run db:seed` (scripts) and the+// boot-time top-up (src/instrumentation.ts) cannot drift apart.+//+// Semantics — deliberately conservative:+// • upsert by slug: new templates appear, changed templates are+// refreshed (the seed behaviour, unchanged);+// • NEVER deletes: a stale slug in the database is harmless, and+// deleting rows on boot would fight rollbacks;+// • count fast-path: when the database already holds ≥ |TEMPLATES|+// rows the loop is skipped entirely, so a normal boot pays one+// cheap COUNT query;+// • idempotent and safe to race (upserts are last-write-wins).+// ─────────────────────────────────────────────────────────────++import { Prisma } from '@/generated/prisma/client'+import { TEMPLATES } from '@/lib/templates'++/** Minimal client surface the sync needs (the app `db` and the seed's+ * script client both satisfy it). */+export interface TemplateSyncDb {+ template: {+ count(): Promise<number>+ upsert(args: {+ where: { slug: string }+ update: {+ name: string+ category: string+ width: number+ height: number+ accent: string+ pages: Prisma.InputJsonValue+ fields: Prisma.InputJsonValue | typeof Prisma.DbNull+ }+ create: {+ slug: string+ name: string+ category: string+ width: number+ height: number+ accent: string+ pages: Prisma.InputJsonValue+ fields: Prisma.InputJsonValue | typeof Prisma.DbNull+ }+ }): Promise<unknown>+ }+}++export interface TemplateSyncResult {+ /** rows written this run (0 when the fast-path skipped the loop) */+ synced: number+ /** rows in the database after the run */+ total: number+ /** true when the count fast-path skipped the upserts */+ skipped: boolean+}++// Typed template list cast for the Postgres jsonb column (same+// casts prisma/seed.ts used before this module existed).+const pagesOf = (t: (typeof TEMPLATES)[number]) => t.pages as unknown as Prisma.InputJsonValue++// v0.17 (Wave 2): field declarations use the same jsonb cast. Plain+// templates store SQL NULL (DbNull), not the jsonb 'null' literal —+// IS NULL filters and the fill route's fallback both rely on it.+const fieldsOf = (t: (typeof TEMPLATES)[number]) =>+ t.fields ? (t.fields as unknown as Prisma.InputJsonValue) : Prisma.DbNull++/** Reconcile the database's template library with the code. See the+ * module header for the exact semantics. `force: true` skips the+ * count fast-path — what `npm run db:seed` wants (an operator running+ * it explicitly is refreshing content, and the count alone can't see+ * content-only changes). */+export async function syncTemplateLibrary(+ db: TemplateSyncDb,+ opts?: { force?: boolean },+): Promise<TemplateSyncResult> {+ const before = await db.template.count()+ if (!opts?.force && before >= TEMPLATES.length) {+ return { synced: 0, total: before, skipped: true }+ }+ for (const t of TEMPLATES) {+ await db.template.upsert({+ where: { slug: t.slug },+ update: {+ name: t.name,+ category: t.category,+ width: t.width,+ height: t.height,+ accent: t.accent,+ pages: pagesOf(t),+ fields: fieldsOf(t),+ },+ create: {+ slug: t.slug,+ name: t.name,+ category: t.category,+ width: t.width,+ height: t.height,+ accent: t.accent,+ pages: pagesOf(t),+ fields: fieldsOf(t),+ },+ })+ }+ const total = await db.template.count()+ return { synced: TEMPLATES.length, total, skipped: false }+}diff --git a/src/lib/text-fit.test.ts b/src/lib/text-fit.test.tsnew file mode 100644index 0000000..e9fbf4a--- /dev/null+++ b/src/lib/text-fit.test.ts@@ -0,0 +1,87 @@+import { describe, it, expect } from 'vitest'+import { fitFontSize, wrapLines, type MeasureFn, type TextFitStyle } from '@/lib/text-fit'++// Deterministic fake measure: width = chars × fontSize × 0.5 (no letter spacing)+const measure: MeasureFn = (text, style) => text.length * style.fontSize * 0.5 + style.letterSpacing * text.length++function style(over: Partial<TextFitStyle> = {}): TextFitStyle {+ return {+ text: 'hello world',+ fontFamily: 'Inter',+ bold: false,+ italic: false,+ letterSpacing: 0,+ lineHeight: 1.2,+ fontSize: 40,+ ...over,+ }+}++describe('wrapLines', () => {+ it('keeps a fitting paragraph on one line', () => {+ const lines = wrapLines('hi', 1000, style(), measure)+ expect(lines).toEqual(['hi'])+ })++ it('wraps at spaces (never mid-word when avoidable)', () => {+ const s = style({ fontSize: 10, text: 'aaa bbb ccc' })+ // width per char = 5px → 'aaa bbb' = 35px fits 40, 'aaa bbb ccc' = 55px does not+ const lines = wrapLines(s.text, 40, s, measure)+ expect(lines).toEqual(['aaa bbb', 'ccc'])+ })++ it('preserves empty paragraphs as blank lines', () => {+ const s = style({ fontSize: 10, text: 'a\n\nb' })+ expect(wrapLines(s.text, 100, s, measure)).toEqual(['a', '', 'b'])+ })+})++describe('fitFontSize', () => {+ it('returns the authored size when it already fits (fast path)', () => {+ const size = fitFontSize(style({ fontSize: 40, text: 'hi' }), { width: 400, height: 400 }, measure)+ expect(size).toBe(40)+ })++ it('shrinks until the block fits the height', () => {+ // 10 lines × 40px × 1.2 = 480px > 240px box → must shrink below 40+ const s = style({ fontSize: 40, text: Array.from({ length: 10 }, (_, i) => `line ${i}`).join('\n') })+ const size = fitFontSize(s, { width: 4000, height: 240 }, measure)+ expect(size).toBeLessThan(40)+ // and the shrunk size actually fits+ const lines = wrapLines(s.text, 4000, { ...s, fontSize: size }, measure)+ expect(lines.length * size * s.lineHeight).toBeLessThanOrEqual(240 + 0.5)+ })++ it('shrinks when a single unbreakable token overflows the width', () => {+ const s = style({ fontSize: 40, text: 'x'.repeat(20) }) // 20 chars × 20px = 400px+ const size = fitFontSize(s, { width: 100, height: 4000 }, measure)+ expect(size).toBeLessThan(40)+ expect(size * 0.5 * 20).toBeLessThanOrEqual(100 + 0.5)+ })++ it('a token too long even at 6px floors at 6 (overflow is the caller\'s to show)', () => {+ const s = style({ fontSize: 40, text: 'x'.repeat(50) })+ const size = fitFontSize(s, { width: 100, height: 4000 }, measure)+ expect(size).toBe(6)+ })++ it('never grows past the authored size', () => {+ const size = fitFontSize(style({ fontSize: 12, text: 'tiny' }), { width: 4000, height: 4000 }, measure)+ expect(size).toBe(12)+ })++ it('floors at 6px instead of collapsing to zero', () => {+ const s = style({ fontSize: 40, text: 'x'.repeat(5000) })+ const size = fitFontSize(s, { width: 50, height: 50 }, measure)+ expect(size).toBeGreaterThanOrEqual(6)+ })++ it('degenerate boxes return the authored size', () => {+ expect(fitFontSize(style(), { width: 0, height: 0 }, measure)).toBe(40)+ expect(fitFontSize(style(), { width: NaN, height: 100 }, measure)).toBe(40)+ })++ it('empty text returns the authored size', () => {+ expect(fitFontSize(style({ text: '' }), { width: 100, height: 100 }, measure)).toBe(40)+ })+})diff --git a/src/lib/text-fit.ts b/src/lib/text-fit.tsnew file mode 100644index 0000000..6238bdf--- /dev/null+++ b/src/lib/text-fit.ts@@ -0,0 +1,95 @@+// ─────────────────────────────────────────────────────────────+// Canvix v0.18 (Wave 3) — text auto-fit+//+// Pure helper: find the largest font size ≤ the authored size at+// which the text fits its element box (width AND height). Binary+// search over the same measure the renderers use, so the editor,+// the SVG export and the video export agree to the pixel.+//+// Design notes:+// • shrink-only — Canva's Auto-fit never grows past the authored+// size, so resizing a box up keeps the user's type scale.+// • min 6 px — below that the text is unreadable; the caller+// shows an overflow indicator instead of shrinking to nothing.+// • the authored `fontSize` is NEVER mutated; the fit is derived+// at render time (pure function of text + style + box).+// ─────────────────────────────────────────────────────────────++export interface TextFitStyle {+ text: string+ fontFamily: string+ bold: boolean+ italic: boolean+ letterSpacing: number+ lineHeight: number+ /** authored size — the upper bound of the search */+ fontSize: number+}++export interface TextFitBox {+ width: number+ height: number+}++export type MeasureFn = (text: string, style: Omit<TextFitStyle, 'lineHeight' | 'fontSize'> & { fontSize: number }) => number++/** Wrap `text` into lines that fit `maxWidth` (greedy, word-wrap). */+export function wrapLines(text: string, maxWidth: number, style: TextFitStyle, measure: MeasureFn): string[] {+ const paragraphs = text.split('\n')+ const out: string[] = []+ for (const para of paragraphs) {+ if (para === '') {+ out.push('')+ continue+ }+ const words = para.split(/(\s+)/).filter((w) => w !== '')+ let line = ''+ for (const word of words) {+ const candidate = line + word+ if (line !== '' && measure(candidate.trimEnd(), style) > maxWidth && !/^\s+$/.test(word)) {+ out.push(line.trimEnd())+ line = word.trimStart()+ } else {+ line = candidate+ }+ }+ if (line !== '') out.push(line.trimEnd())+ }+ return out+}++/**+ * The effective font size for an auto-fit text element.+ * Returns the authored size unchanged when it already fits (or when+ * any input is degenerate) — the common fast path.+ */+export function fitFontSize(style: TextFitStyle, box: TextFitBox, measure: MeasureFn): number {+ const authored = style.fontSize+ if (!Number.isFinite(box.width) || !Number.isFinite(box.height) || box.width < 4 || box.height < 4) return authored+ if (!style.text) return authored++ const fits = (size: number): boolean => {+ const s = { ...style, fontSize: size }+ const lines = wrapLines(style.text, box.width, s, measure)+ if (lines.length === 0) return true+ const blockH = lines.length * size * style.lineHeight+ if (blockH > box.height + 0.5) return false+ // a single unbreakable token wider than the box still overflows+ for (const line of lines) {+ if (line !== '' && measure(line, s) > box.width + 0.5) return false+ }+ return true+ }++ if (fits(authored)) return authored++ let lo = 6+ let hi = authored+ // 20 iterations converge well below a 0.05 px delta for any sane size+ for (let i = 0; i < 20 && hi - lo > 0.1; i++) {+ const mid = (lo + hi) / 2+ if (fits(mid)) lo = mid+ else hi = mid+ }+ return Math.max(6, Math.floor(lo * 10) / 10)+}diff --git a/src/lib/types.ts b/src/lib/types.tsindex d83fb43..8d4ca6b 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -8,6 +8,7 @@ export type ElementType =| 'ellipse'| 'triangle'| 'star'+ | 'polygon'| 'line'| 'path'| 'stroke'@@ -163,10 +164,22 @@ export interface TextElement extends BaseElement {effectBackground?: string/** canva-style effect preset */effect?: TextEffect+ /** v0.18 (Wave 3) auto-fit — shrink the font (never grow) so the+ * text fits the element box. Derived at render time; the authored+ * `fontSize` is preserved. See lib/text-fit.ts. */+ autoFit?: boolean+ /** v0.18 (Wave 3) list style — every non-empty paragraph becomes a+ * list item with a hanging indent. See lib/list-text.ts. */+ listStyle?: 'none' | 'bullet' | 'number'+ /** v0.18 (Wave 3) base direction for bidi scripts (Arabic, Hebrew…).+ * 'rtl' mirrors the list marker side and the default alignment;+ * within-line reordering is applied by the platform text stack+ * (canvas fillText runs the Unicode bidi algorithm). */+ direction?: 'ltr' | 'rtl'}export interface ShapeElement extends BaseElement {- type: 'rect' | 'ellipse' | 'triangle' | 'star' | 'path'+ type: 'rect' | 'ellipse' | 'triangle' | 'star' | 'polygon' | 'path'fill: string/** gradient fill — when set, renders instead of the solid fill */fillGradient?: GradientFill | null@@ -174,6 +187,12 @@ export interface ShapeElement extends BaseElement {strokeWidth: numbercornerRadius: number // rect onlypathData?: string // path only — authored in a 100×100 box+ /** v0.18 (Wave 3) polygon — 3..12 sides (lib/shapes.ts) */+ sides?: number+ /** v0.18 (Wave 3) star — 3..16 points (was hardcoded 5 pre-v0.18) */+ numPoints?: number+ /** v0.18 (Wave 3) star — inner/outer radius ratio 0.15..0.85 (default 0.55) */+ innerRatio?: number}export interface LineElement extends BaseElement {@@ -204,6 +223,15 @@ export interface ImageElement extends BaseElement {filter?: string/** preset strength 0..100 (default 100) */filterIntensity?: number+ /** v0.18 (Wave 3): shape mask — the image clips to the polygon+ * (lib/shapes.ts maskPolygon). 'none'/undefined = untouched.+ * Rides autosave/versions/collab like any element field; older+ * replicas ignore the unknown field (fail-safe). */+ maskShape?: string+ /** parametric mask: polygon sides (3..12) / star points (3..16) */+ maskSides?: number+ /** parametric star mask: inner/outer ratio 0.15..0.85 */+ maskInnerRatio?: number/** v0.16.4 (A4): durable stock-photo attribution (the R6 video* pattern) — set by the Photos panel's stock connectors, absent on* uploads and bundled photos. Rides autosave/versions/collab; shown@@ -496,6 +524,14 @@ export interface PageData {* ride the saved document so deletes merge deterministically against* concurrent edits (delete wins only while it is the newer write). */tombstones?: Record<string, string>+ /** v0.18 (Wave 3): per-page size override. Absent/zero = use the+ * design-level width/height (the only mode pre-v0.18 documents+ * have). Every consumer goes through pageSize() — see editor-utils. */+ width?: number+ height?: number+ /** v0.18 (Wave 3): speaker notes — plain text shown in presenter+ * view; never rendered on the canvas or in exports. */+ notes?: string}/** user-placed ruler guide (position in page px; scoped to a page) */@@ -618,7 +654,7 @@ export function createTextElement(init: BaseInit & Partial<TextElement> = {}): T}export function createShapeElement(- type: 'rect' | 'ellipse' | 'triangle' | 'star' | 'path',+ type: 'rect' | 'ellipse' | 'triangle' | 'star' | 'polygon' | 'path',init: BaseInit & Partial<ShapeElement> = {}): ShapeElement {return {@@ -629,10 +665,22 @@ export function createShapeElement(strokeWidth: 0,cornerRadius: type === 'rect' ? 24 : 0,pathData: init.pathData,+ ...(type === 'polygon' ? { sides: clampSides(init.sides ?? 6) } : {}),+ ...(type === 'star' ? { numPoints: clampStarPoints(init.numPoints ?? 5), innerRatio: init.innerRatio ?? 0.55 } : {}),...init,}}+/** v0.18 (Wave 3) — 3..12 (the Elements panel picker range). */+function clampSides(n: number): number {+ return Math.min(12, Math.max(3, Math.round(n)))+}++/** v0.18 (Wave 3) — 3..16. */+function clampStarPoints(n: number): number {+ return Math.min(16, Math.max(3, Math.round(n)))+}+export function createLineElement(init: BaseInit & Partial<LineElement> = {}): LineElement {return {...baseElement('line', { width: 280, height: 0, ...init }),diff --git a/src/lib/video-export.ts b/src/lib/video-export.tsindex 2eba7e6..5bf5080 100644--- a/src/lib/video-export.ts+++ b/src/lib/video-export.ts@@ -18,7 +18,7 @@// ─────────────────────────────────────────────────────────────import Konva from 'konva'-import type { AnyElement, AudioElement, ChartElement, EmbedElement, FrameElement, ImageElement, PageData, PluginElement, TableElement, VideoElement } from '@/lib/types'+import type { AnyElement, AudioElement, ChartElement, EmbedElement, FrameElement, ImageElement, PageData, PluginElement, TableElement, TextElement, VideoElement } from '@/lib/types'import { imageHasFilters, renderFilteredCanvas } from '@/lib/image-filters'import { chartPrimitives } from '@/lib/chart-geometry'import { embedLayout, hexPoints, hostOf, tableGeometry, youtubeThumbUrl } from '@/lib/v06-geometry'@@ -26,6 +26,10 @@ import { createCanvasMeasure, layoutRichLines, normalizeSpans } from '@/lib/richimport { animateElementAt, pageHoldDuration } from '@/lib/animations'import { beatEnvelopeAt, beatSourceOf } from '@/lib/media/beat-detect'import { awaitRender, renderKey } from '@/lib/plugins/renderer-cache'+import { pageSize } from '@/lib/editor-utils'+import { isMaskShape, maskPolygon, polygonPoints, starPointsEx, stretchPts, tracePts } from '@/lib/shapes'+import { fitFontSize } from '@/lib/text-fit'+import { layoutListLines } from '@/lib/list-text'import { WebMMuxer } from '@/lib/webm-muxer'export interface VideoExportOptions {@@ -301,6 +305,27 @@ function frameClipFunc(fr: FrameElement): (ctx: Konva.Context) => void {* the geometry module, the D7 charts pattern). */const videoRichMeasure = createCanvasMeasure()+/** v0.18 (Wave 3): the video-side effective font size — the same+ * derivation the editor canvas and the SVG export use (lib/text-fit+ * fitFontSize over the shared canvas measure), so all three+ * renderers agree to the pixel. */+function videoEffectiveFontSize(t: TextElement): number {+ if (!t.autoFit) return t.fontSize+ return fitFontSize(+ {+ text: t.uppercase ? t.text.toUpperCase() : t.text,+ fontFamily: t.fontFamily,+ bold: t.bold,+ italic: t.italic,+ letterSpacing: t.letterSpacing,+ lineHeight: t.lineHeight,+ fontSize: t.fontSize,+ },+ { width: t.width, height: t.height },+ (text, style) => videoRichMeasure(text, style),+ )+}+export function buildKonvaNode(el: AnyElement,images: Map<string, HTMLImageElement>,@@ -309,6 +334,70 @@ export function buildKonvaNode(switch (el.type) {case 'text': {const t = el+ // v0.18 (Wave 3): list text renders through the shared list layout+ // (flat — rich spans and curved text keep their own paths, exactly+ // like the editor canvas and the SVG export)+ const isList = !!t.listStyle && t.listStyle !== 'none' && (t.curve ?? 0) === 0 && t.effect !== 'splice'+ const rtl = t.direction === 'rtl'+ if (isList) {+ const size = videoEffectiveFontSize(t)+ const lines = layoutListLines(+ {+ text: t.uppercase ? t.text.toUpperCase() : t.text,+ fontFamily: t.fontFamily,+ bold: t.bold,+ italic: t.italic,+ letterSpacing: t.letterSpacing,+ lineHeight: t.lineHeight,+ fontSize: size,+ width: t.width,+ listStyle: t.listStyle ?? 'none',+ direction: rtl ? 'rtl' : 'ltr',+ },+ (text, style) => videoRichMeasure(text, style),+ )+ const blockH = lines.length ? Math.max(...lines.map((l) => l.y)) + size * t.lineHeight : size * t.lineHeight+ const fontStyle = `${t.italic ? 'italic ' : ''}${t.bold ? 'bold' : 'normal'}`+ const group = new Konva.Group({ id: t.id, x: t.x, y: t.y })+ group.height(blockH)+ for (const line of lines) {+ if (line.marker) {+ group.add(+ new Konva.Text({+ x: line.markerX,+ y: line.y,+ text: line.marker,+ fontSize: size,+ fontFamily: t.fontFamily,+ fontStyle,+ fill: t.fill,+ width: t.width,+ align: rtl ? 'right' : 'left',+ lineHeight: t.lineHeight,+ wrap: 'none',+ }),+ )+ }+ if (line.text) {+ group.add(+ new Konva.Text({+ x: line.textX,+ y: line.y,+ text: line.text,+ fontSize: size,+ fontFamily: t.fontFamily,+ fontStyle,+ fill: t.fill,+ width: line.textWidth,+ align: rtl ? 'right' : 'left',+ lineHeight: t.lineHeight,+ wrap: 'none',+ }),+ )+ }+ }+ return group+ }// v0.15 (R1): rich text — one Text node per positioned run from the// shared layout module (curved text stays flat, single-style by design)if ((t.curve ?? 0) === 0) {@@ -334,18 +423,23 @@ export function buildKonvaNode(return group}}+ // v0.18 (Wave 3): auto-fit derives the size (never mutates it) and+ // rtl mirrors the default alignment (centre stays) — both flat-path+ const effSize = videoEffectiveFontSize(t)+ const alignAttr =+ t.align === 'center' ? 'center' : t.align === 'justify' ? 'left' : rtl ? (t.align === 'left' ? 'right' : 'left') : t.alignreturn new Konva.Text({id: t.id,x: t.x,y: t.y,width: t.width,text: t.uppercase ? t.text.toUpperCase() : t.text,- fontSize: t.fontSize,+ fontSize: effSize,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,+ align: alignAttr,lineHeight: t.lineHeight,letterSpacing: t.letterSpacing,wrap: 'word',@@ -399,14 +493,32 @@ export function buildKonvaNode(}case 'star': {const s = el- const outer = Math.min(s.width, s.height) / 2- const node = new Konva.Star({+ // v0.18 (Wave 3): parametric — same stretchPts geometry as the+ // editor canvas + SVG/PDF exports (fills the element box)+ const pts = stretchPts(starPointsEx(s.numPoints ?? 5, s.innerRatio), 0, 0, s.width, s.height)+ const node = new Konva.Line({+ id: s.id,+ x: s.x + s.width / 2,+ y: s.y + s.height / 2,+ points: pts.flatMap(([px, py]) => [px - s.width / 2, py - s.height / 2]),+ closed: true,+ fill: s.fillGradient ? undefined : s.fill,+ stroke: s.stroke,+ strokeWidth: s.strokeWidth,+ })+ applyGradient(node, s)+ return node+ }+ case 'polygon': {+ const s = el+ // v0.18 (Wave 3): regular polygon — centred geometry like the star+ const pts = stretchPts(polygonPoints(s.sides ?? 6), 0, 0, s.width, s.height)+ const node = new Konva.Line({id: s.id,x: s.x + s.width / 2,y: s.y + s.height / 2,- numPoints: 5,- innerRadius: outer * 0.55,- outerRadius: outer,+ points: pts.flatMap(([px, py]) => [px - s.width / 2, py - s.height / 2]),+ closed: true,fill: s.fillGradient ? undefined : s.fill,stroke: s.stroke,strokeWidth: s.strokeWidth,@@ -482,21 +594,31 @@ export function buildKonvaNode(// while here, flips/rotation finally export too (parity fix)const img = images.get(im.src)const bitmap = img && imageHasFilters(im) ? renderFilteredCanvas(im, img, im.width, im.height) : img- const node = new Konva.Image({- id: im.id,- x: im.x,- y: im.y,+ // v0.18 (Wave 3): validated mask — the clip polygon from the shared+ // geometry module (identical to the editor's ImageNode)+ const maskPts =+ isMaskShape(im.maskShape) && im.maskShape !== 'none'+ ? maskPolygon(im.maskShape, im.maskSides, im.maskInnerRatio)+ : null+ const image = new Konva.Image({+ id: maskPts ? undefined : im.id,+ x: maskPts ? 0 : im.x,+ y: maskPts ? 0 : im.y,width: im.width,height: im.height,image: bitmap ?? undefined,- cornerRadius: im.radius,+ cornerRadius: maskPts ? 0 : im.radius,scaleX: im.flipH ? -1 : 1,scaleY: im.flipV ? -1 : 1,offsetX: im.flipH ? im.width : 0,offsetY: im.flipV ? im.height : 0,- rotation: im.rotation ?? 0,+ rotation: maskPts ? 0 : im.rotation ?? 0,})- return node+ if (!maskPts) return image+ const group = new Konva.Group({ id: im.id, x: im.x, y: im.y, rotation: im.rotation ?? 0 })+ group.clipFunc((ctx) => tracePts(ctx, maskPts, im.width, im.height))+ group.add(image)+ return group}case 'plugin': {// v0.13 (P4): the renderer's sanitized output as an Image; no@@ -1098,31 +1220,39 @@ export async function createRenderSession(let nodes = nodesForPage.get(index)if (nodes) return nodesconst page = segments[index].page- const pageScale = width / opts.designWidth+ // v0.18 (Wave 3): per-page size — each page fits + centres in the+ // output frame (identical to the old uniform scale when the page+ // keeps the design size)+ const { width: pw, height: pgh } = pageSize(page, opts.designWidth, opts.designHeight)+ const pageScale = Math.min(width / pw, height / pgh)+ const pageOffX = (width - pw * pageScale) / 2+ const pageOffY = (height - pgh * pageScale) / 2const stage = new Konva.Stage({ container: host, width, height })- const bgLayer = new Konva.Layer({ listening: false, scale: { x: pageScale, y: pageScale } })+ const bgLayer = new Konva.Layer({ listening: false, x: pageOffX, y: pageOffY, scale: { x: pageScale, y: pageScale } })const bg = page.backgroundconst bgRect =bg.type === 'gradient'? new Konva.Rect({- width: opts.designWidth,- height: opts.designHeight,+ width: pw,+ height: pgh,fillLinearGradientStartPoint: { x: 0, y: 0 },fillLinearGradientEndPoint: {- x: Math.cos((bg.angle * Math.PI) / 180) * opts.designWidth,- y: Math.sin((bg.angle * Math.PI) / 180) * opts.designHeight,+ x: Math.cos((bg.angle * Math.PI) / 180) * pw,+ y: Math.sin((bg.angle * Math.PI) / 180) * pgh,},fillLinearGradientColorStops: [0, bg.from, 1, bg.to],})- : new Konva.Rect({ width: opts.designWidth, height: opts.designHeight, fill: bg.color })+ : new Konva.Rect({ width: pw, height: pgh, fill: bg.color })bgLayer.add(bgRect)stage.add(bgLayer)const layer = new Konva.Layer({listening: false,+ x: pageOffX,+ y: pageOffY,scale: { x: pageScale, y: pageScale },- clip: { x: 0, y: 0, width: opts.designWidth, height: opts.designHeight },+ clip: { x: 0, y: 0, width: pw, height: pgh },})stage.add(layer)diff --git a/src/store/editor-store.ts b/src/store/editor-store.tsindex 90ee443..2c9ad09 100644--- a/src/store/editor-store.ts+++ b/src/store/editor-store.ts@@ -109,6 +109,14 @@ interface EditorState {* disagreeing controls (QA finding F3). */editingMode: 'editing' | 'viewing'previewOpen: boolean+ /** v0.18 (Wave 3): presenter view — fullscreen present + speaker notes */+ presentOpen: boolean+ /** v0.18 (Wave 3): grid overlay (editor preference — never document data) */+ showGrid: boolean+ /** v0.18 (Wave 3): grid cell size in page px (8..160) */+ gridSize: number+ /** v0.18 (Wave 3): snap element drags to the grid */+ snapToGrid: boolean/** freehand draw tool — activating one also leaves viewing mode (F3) */tool: 'select' | 'draw'drawColor: string@@ -195,6 +203,14 @@ interface EditorState {// canva-2026 chromesetEditingMode: (m: 'editing' | 'viewing') => voidsetPreviewOpen: (open: boolean) => void+ setPresentOpen: (open: boolean) => void+ setShowGrid: (on: boolean) => void+ setGridSize: (n: number) => void+ setSnapToGrid: (on: boolean) => void+ /** v0.18 (Wave 3): resize ONE page (per-page size override) */+ resizePage: (pageId: string, width: number, height: number) => void+ /** v0.18 (Wave 3): speaker notes for one page */+ setPageNotes: (pageId: string, notes: string) => voidsetTool: (t: 'select' | 'draw') => voidsetDrawColor: (c: string) => voidsetDrawSize: (n: number) => void@@ -289,6 +305,10 @@ export const useEditorStore = create<EditorState>((set, get) => ({editingMode: 'editing',previewOpen: false,+ presentOpen: false,+ showGrid: false,+ gridSize: 40,+ snapToGrid: false,tool: 'select',drawColor: '#FFFFFF',drawSize: 6,@@ -829,6 +849,33 @@ export const useEditorStore = create<EditorState>((set, get) => ({setEditingMode: (m) => set({ editingMode: m }),setPreviewOpen: (open) => set({ previewOpen: open }),+ setPresentOpen: (open) => set({ presentOpen: open }),+ setShowGrid: (on) => set({ showGrid: on }),+ setGridSize: (n) => set({ gridSize: Math.min(160, Math.max(8, Math.round(n))) }),+ setSnapToGrid: (on) => set({ snapToGrid: on }),++ // v0.18 (Wave 3): per-page size — history-stamped like every other page op.+ // Values are clamped by pageSize() on read; here we just round + store.+ resizePage: (pageId, width, height) => {+ get().pushHistory()+ const { pages, version } = get()+ const h = nowHlc()+ const next = pages.map((p) => (p.id !== pageId ? p : { ...p, width: Math.round(width), height: Math.round(height), _pm: h }))+ set({ pages: next, dirty: true, version: version + 1 })+ const replaced = next.find((p) => p.id === pageId)+ if (replaced) emit({ kind: 'page:replace', pageId, page: replaced })+ },++ // v0.18 (Wave 3): speaker notes — debounced by the caller (typing);+ // history only once per editing session (the notes panel commits on blur).+ setPageNotes: (pageId, notes) => {+ const { pages, version } = get()+ const h = nowHlc()+ const next = pages.map((p) => (p.id !== pageId ? p : { ...p, notes, _pm: h }))+ set({ pages: next, dirty: true, version: version + 1 })+ const replaced = next.find((p) => p.id === pageId)+ if (replaced) emit({ kind: 'page:replace', pageId, page: replaced })+ },// v0.11.6 (F3): activating a tool also leaves read-only viewing — the// Tools-panel toggle used to show "Draw" pressed while the canvas stayed// read-only, because editingMode and tool were set from separate controlsdiff --git a/tests/e2e/wave3-editor-depth.spec.ts b/tests/e2e/wave3-editor-depth.spec.tsnew file mode 100644index 0000000..bccd665--- /dev/null+++ b/tests/e2e/wave3-editor-depth.spec.ts@@ -0,0 +1,342 @@+import { test, expect, type Page } from '@playwright/test'+import { readFileSync, writeFileSync } from 'node:fs'++/**+ * v0.18 (Wave 3) — editor depth parity e2e.+ * Exercises the surfaces a user actually touches: the polygon palette,+ * the shape-property sliders, image masks, list/RTL/auto-fit text+ * controls, the grid overlay, per-page sizes, and the presenter view+ * with speaker notes. Document truth is asserted through the designs+ * API (the same discipline the D4/D7 suites use).+ *+ * Register budget: ONE registration per run.+ */++// an 8×8 solid-red PNG (75 bytes)+const RED_PNG_B64 =+ 'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAEklEQVR4nGP4z8CAFWEXHbQSACj/P8Fu7N9hAAAAAElFTkSuQmCC'++function textEl(overrides: Record<string, unknown> = {}) {+ return {+ id: 'w3_text',+ type: 'text',+ name: 'wave3 text',+ x: 100,+ y: 100,+ width: 500,+ height: 80,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ text: 'Alpha bravo charlie delta echo foxglove',+ fontSize: 48,+ fontFamily: 'Inter',+ bold: false,+ italic: false,+ underline: false,+ strike: false,+ uppercase: false,+ fill: '#1F2226',+ align: 'left',+ lineHeight: 1.25,+ letterSpacing: 0,+ ...overrides,+ }+}++function imageEl(overrides: Record<string, unknown> = {}) {+ return {+ id: 'w3_image',+ type: 'image',+ name: 'wave3 image',+ x: 420,+ y: 120,+ width: 300,+ height: 300,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ src: `data:image/png;base64,${RED_PNG_B64}`,+ radius: 0,+ naturalWidth: 8,+ naturalHeight: 8,+ ...overrides,+ }+}++let SHARED_ACCOUNT: { username: string; password: string } | null = null++/** module state may reset between tests (playwright restarts workers after+ * failures) — credentials are also shared through /tmp so every test in+ * the run LOGS IN with the same account instead of re-registering+ * (the register endpoint allows 5/h/IP in production). */+const CRED_FILE = '/tmp/w3-e2e-account.json'++async function ensureAccount(page: Page, tag: string): Promise<string> {+ if (SHARED_ACCOUNT) {+ // already authenticated in this module instance — nothing to do+ return SHARED_ACCOUNT.username+ }+ // try a saved account from an earlier test in this run+ try {+ const saved = JSON.parse(readFileSync(CRED_FILE, 'utf8')) as { username: string; password: string }+ const res = await page.request.post('/api/auth/login', { data: saved })+ if (res.status() < 300) {+ SHARED_ACCOUNT = saved+ return saved.username+ }+ } catch {+ /* no saved account yet */+ }+ const username = await register(page, tag)+ return username+}++async function register(page: Page, tag: string): Promise<string> {+ const username = `w3_${tag}_${Date.now().toString(36)}`+ const password = `W3-E2e-${username}-18!q`+ const res = await page.request.post('/api/auth/register', { data: { username, password } })+ expect(res.status(), `register ${username}`).toBeLessThan(300)+ SHARED_ACCOUNT = { username, password }+ try {+ writeFileSync(CRED_FILE, JSON.stringify(SHARED_ACCOUNT))+ } catch {+ /* read-only fs — the module fallback still covers same-file tests */+ }+ return username+}++async function createDesign(page: Page, name: string, elements: unknown[], pageOver: Record<string, unknown> = {}): Promise<string> {+ const res = await page.request.post('/api/designs', {+ data: {+ name,+ width: 1080,+ height: 720,+ pages: [{ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements, ...pageOver }],+ },+ })+ expect(res.status(), `create design: ${await res.text()}`).toBeLessThan(300)+ return ((await res.json()) as { id: string }).id+}++async function openEditor(page: Page, designId: string) {+ await page.goto(`/design/${designId}`)+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })+}++async function doc(page: Page, designId: string) {+ const res = await page.request.get(`/api/designs/${designId}`)+ expect(res.status()).toBe(200)+ return (await res.json()) as {+ pages: { elements: Record<string, any>[]; notes?: string; width?: number; height?: number }[]+ }+}++/** document truth arrives through the 1.6s debounced autosave — poll+ * the designs API until the predicate holds (or fail loudly). */+async function waitForDoc(+ page: Page,+ designId: string,+ predicate: (d: Awaited<ReturnType<typeof doc>>) => boolean,+ what: string,+ timeoutMs = 15_000+) {+ const started = Date.now()+ let last: Awaited<ReturnType<typeof doc>> | null = null+ while (Date.now() - started < timeoutMs) {+ last = await doc(page, designId)+ if (predicate(last)) return last+ await page.waitForTimeout(500)+ }+ throw new Error(`document never showed ${what} within ${timeoutMs}ms — last: ${JSON.stringify(last?.pages[0]).slice(0, 300)}`)+}++/** select an element through the Layers tab (Konva is DOM-opaque) */+async function selectViaLayers(page: Page, label: string) {+ // The Tools rail is a toggle — when the panel is already open (this+ // suite selects twice), clicking Tools again would close it and hide+ // the tabs. Only navigate when the Layers tab isn't already showing.+ const layersTab = page.getByRole('button', { name: 'Layers', exact: true })+ if (!(await layersTab.isVisible().catch(() => false))) {+ await page.getByRole('button', { name: 'Tools', exact: true }).click()+ await layersTab.click()+ }+ await page.getByText(label, { exact: true }).click()+}++test.describe('Wave 3 — editor depth parity', () => {+ test.setTimeout(180_000)++ test('polygon palette inserts native parametric polygons + stars', async ({ page }) => {+ const username = await register(page, 'shapes')+ // fresh design through the dashboard flow+ await page.goto('/')+ await page.getByRole('button', { name: /start designing/i }).first().click()+ await expect(page.getByLabel('Create a design')).toBeVisible()+ await page.locator('section:has(h2:text("Start a new design")) [aria-label^="Create "]').first().click()+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })++ // Elements panel → Shapes → polygons + stars sections+ await page.getByRole('button', { name: 'Elements', exact: true }).click()+ await page.getByRole('tab', { name: 'Shapes' }).click()+ await expect(page.getByText('Polygons')).toBeVisible()+ await expect(page.getByText('Stars')).toBeVisible()++ await page.getByRole('button', { name: 'Add Hexagon' }).click()++ // the polygon landed in the document (layers panel shows its auto label)+ await page.getByRole('button', { name: 'Tools', exact: true }).click()+ await page.getByRole('button', { name: 'Layers', exact: true }).click()+ await expect(page.getByText('Polygon', { exact: true }).first()).toBeVisible({ timeout: 10_000 })+ })++ test('image mask picker writes maskShape + document truth', async ({ page }) => {+ const username = await ensureAccount(page, 'mask')+ const design = await createDesign(page, `cvx_w3_mask_${username}`, [imageEl()])+ await openEditor(page, design)+ await selectViaLayers(page, 'wave3 image')++ await page.getByRole('button', { name: 'Image mask' }).click()+ const grid = page.getByTestId('mask-grid')+ await expect(grid).toBeVisible()++ // 13 options: none + 10 presets + 2 parametric+ await expect(grid.getByRole('button')).toHaveCount(13)++ await grid.getByTestId('mask-circle').click()+ await page.keyboard.press('Escape')++ await waitForDoc(+ page,+ design,+ (d) => d.pages[0].elements.find((e) => e.id === 'w3_image')?.maskShape === 'circle',+ 'maskShape=circle'+ )++ // parametric option exposes the sides slider (Escape deselected the+ // image — the editor's documented "Deselect / close" — so re-select)+ await selectViaLayers(page, 'wave3 image')+ await page.getByRole('button', { name: 'Image mask' }).click()+ await grid.getByTestId('mask-polyStar').click()+ await expect(page.getByText('Spike ratio')).toBeVisible()+ await page.keyboard.press('Escape')+ })++ test('text list + auto-fit + rtl controls round-trip to the document', async ({ page }) => {+ // reuse the shared account when present (register budget)+ const username = await ensureAccount(page, 'text')+ const design = await createDesign(page, `cvx_w3_text_${username}_${Date.now().toString(36)}`, [textEl()])+ await openEditor(page, design)+ await selectViaLayers(page, 'wave3 text')++ await page.getByRole('button', { name: 'List and fit options' }).click()+ const pop = page.locator('.cv-pop').last()+ await expect(pop).toBeVisible()++ await pop.getByTestId('list-number').click()+ await pop.getByTestId('dir-rtl').click()+ await pop.getByTestId('autofit-toggle').locator('input[type="checkbox"]').check()+ await page.keyboard.press('Escape')++ const d = await waitForDoc(+ page,+ design,+ (dd) => {+ const t = dd.pages[0].elements.find((e) => e.id === 'w3_text')+ return t?.listStyle === 'number' && t?.direction === 'rtl' && t?.autoFit === true+ },+ 'listStyle=number + direction=rtl + autoFit=true'+ )+ const t = d.pages[0].elements.find((e) => e.id === 'w3_text')+ expect(t?.listStyle).toBe('number')+ expect(t?.direction).toBe('rtl')+ expect(t?.autoFit).toBe(true)+ })++ test('grid overlay toggle + snap + size selector', async ({ page }) => {+ const username = await ensureAccount(page, 'grid')+ const design = await createDesign(page, `cvx_w3_grid_${username}_${Date.now().toString(36)}`, [])+ await openEditor(page, design)++ // grid off by default: no size selector+ await expect(page.getByTestId('grid-size')).toHaveCount(0)++ await page.getByTestId('grid-toggle').click()+ await expect(page.getByTestId('snap-toggle')).toBeVisible()+ await expect(page.getByTestId('grid-size')).toBeVisible()++ // snap toggle + grid size round-trip+ await page.getByTestId('snap-toggle').click()+ await page.getByTestId('grid-size').selectOption('80')++ // grid draws lines on the stage (canvas pixels change)+ const withGrid = await page.evaluate(() => {+ const scope = document.querySelector('main[aria-label="Design canvas"]')+ const canvases = Array.from((scope ?? document).querySelectorAll('canvas'))+ const biggest = canvases.reduce<HTMLCanvasElement | null>(+ (best, c) => (!best || c.width * c.height > best.width * best.height ? c : best),+ null+ )+ return biggest ? biggest.toDataURL() : ''+ })+ await page.getByTestId('grid-toggle').click()+ const withoutGrid = await page.evaluate(() => {+ const scope = document.querySelector('main[aria-label="Design canvas"]')+ const canvases = Array.from((scope ?? document).querySelectorAll('canvas'))+ const biggest = canvases.reduce<HTMLCanvasElement | null>(+ (best, c) => (!best || c.width * c.height > best.width * best.height ? c : best),+ null+ )+ return biggest ? biggest.toDataURL() : ''+ })+ expect(withGrid).not.toBe(withoutGrid)+ })++ test('per-page size + speaker notes + presenter view', async ({ page }) => {+ const username = await ensureAccount(page, 'page')+ const design = await createDesign(page, `cvx_w3_page_${username}_${Date.now().toString(36)}`, [])+ await openEditor(page, design)++ // per-page resize+ await page.getByTestId('page-size-button').click()+ await expect(page.getByTestId('page-size-popover')).toBeVisible()+ await page.getByTestId('page-size-w').fill('500')+ await page.getByTestId('page-size-h').fill('500')+ await page.getByTestId('page-size-apply').click()++ await waitForDoc(+ page,+ design,+ (d) => d.pages[0].width === 500 && d.pages[0].height === 500,+ 'page size 500×500'+ )+ // the chip now shows the custom size+ await expect(page.getByTestId('page-size-button')).toContainText('500×500')++ // speaker notes (exact — the top bar's "Present with speaker notes"+ // also substring-matches a non-exact query)+ await page.getByRole('button', { name: 'Speaker notes', exact: true }).click()+ await page.getByTestId('notes-textarea').fill('Welcome everyone — this is the opening slide.')+ await page.keyboard.press('Escape')++ await waitForDoc(+ page,+ design,+ (d) => (d.pages[0].notes ?? '').includes('opening slide'),+ 'speaker notes'+ )++ // presenter view shows the note+ await page.getByTestId('present-notes-button').click()+ await expect(page.getByRole('dialog', { name: 'Presenter view' })).toBeVisible()+ await expect(page.getByTestId('presenter-notes')).toHaveValue('Welcome everyone — this is the opening slide.')++ // keyboard: escape closes+ await page.keyboard.press('Escape')+ await expect(page.getByRole('dialog', { name: 'Presenter view' })).toHaveCount(0)+ })+})