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.4): the Magic Suite — AI editing, Magic Resize, Translate, Postgres infra
Ashiq Hussain Mir386e12fa40a0
diff --git a/README.md b/README.mdindex c7058d9..121f265 100644--- a/README.md+++ b/README.md@@ -30,6 +30,38 @@ watermarks, no paywalls.## 🎨 Features+### v0.4.0 — the Magic Suite: AI editing, PostgreSQL & infrastructure++- **PostgreSQL database** — Prisma migrated from SQLite to Postgres (native `jsonb`+ documents); one database technology everywhere, local & serverless-ready+ (Neon / Supabase / RDS). Includes the `.env.example` Postgres URL guide+- **Magic Resize** — Canva Magic-Switch-style resize dialog: check any of 12+ channel presets (Story / Reels / posts / A4 / poster / business card…), then+ **resize in place** or **Copy & resize** — every copy gets an automatic+ smart re-layout (elements scale, keep their relative positions, fonts &+ strokes re-proportion)+- **BG Remover** — one-click background removal on any selected image, powered+ by an in-browser ONNX segmentation model (real alpha cut-outs, first use+ downloads the model once, then it's cached)+- **Magic Eraser** — describe an unwanted object ("the person in the+ background") and AI removes it, reconstructing the background behind it+- **Enhance image** — one-click AI photo cleanup: sharpening, lighting and+ colour balance while keeping the framing identical+- **Translate design** — File → Translate: pick from 24 languages, and every+ text across all pages is AI-translated in place (layout intact, one undo)+- **Canvix AI assistant** — a chat copilot app (Canva AI-style) that sees your+ design: ask for headlines, palettes or taglines and tap the suggested+ actions to add text, generate images, save palettes or translate the design+- **Live photo search** — the Photos panel now searches real web photos (not+ just the bundled library) with debounced live results+- **Server-side version history** — snapshots now persist in Postgres+ (30 per design, cascade-deleted), with localStorage as an offline fallback+- **Dashboard trash** — deleting a design moves it to a Trash section+ (restore / delete forever), plus a Recent/Name sort control+- **5 new document templates** — Minimal Resume, Certificate of Achievement,+ Clean Invoice, Monthly Calendar and Business Card under a new+ "Docs & office" category (21 templates total)+### v0.3.2 — fonts, gradients, PDF, photos & AI- **63-font library** — 15 → **63 families** across five categories (sans / serif /diff --git a/bun.lock b/bun.lockindex f412c93..cc5acb5 100644--- a/bun.lock+++ b/bun.lock@@ -9,6 +9,7 @@"@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2","@hookform/resolvers": "^5.1.1",+ "@imgly/background-removal": "^1.7.0","@mdxeditor/editor": "^3.39.1","@prisma/client": "^6.11.1","@radix-ui/react-accordion": "^1.2.11",@@ -309,6 +310,8 @@"@img/sharp-win32-x64": ["@img/[email protected]", "https://registry.npmjs.com/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],+ "@imgly/background-removal": ["@imgly/[email protected]", "", { "dependencies": { "lodash-es": "^4.17.21", "ndarray": "~1.0.0", "zod": "^3.23.8" }, "peerDependencies": { "onnxruntime-web": "1.21.0" } }, "sha512-/1ZryrMYg2ckIvJKoTu5Np50JfYMVffDMlVmppw/BdbN3pBTN7e6stI5/7E/LVh9DDzz6J588s7sWqul3fy5wA=="],+"@jridgewell/gen-mapping": ["@jridgewell/[email protected]", "https://registry.npmjs.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],"@jridgewell/remapping": ["@jridgewell/[email protected]", "https://registry.npmjs.com/@jridgewell/remapping/-/remapping-2.3.5.tgz", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],@@ -479,6 +482,24 @@"@prisma/get-platform": ["@prisma/[email protected]", "https://registry.npmjs.com/@prisma/get-platform/-/get-platform-6.19.2.tgz", { "dependencies": { "@prisma/debug": "6.19.2" } }, "sha512-PGLr06JUSTqIvztJtAzIxOwtWKtJm5WwOG6xpsgD37Rc84FpfUBGLKz65YpJBGtkRQGXTYEFie7pYALocC3MtA=="],+ "@protobufjs/aspromise": ["@protobufjs/[email protected]", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="],++ "@protobufjs/base64": ["@protobufjs/[email protected]", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="],++ "@protobufjs/codegen": ["@protobufjs/[email protected]", "", {}, "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g=="],++ "@protobufjs/eventemitter": ["@protobufjs/[email protected]", "", {}, "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg=="],++ "@protobufjs/fetch": ["@protobufjs/[email protected]", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1" } }, "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw=="],++ "@protobufjs/float": ["@protobufjs/[email protected]", "", {}, "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ=="],++ "@protobufjs/path": ["@protobufjs/[email protected]", "", {}, "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA=="],++ "@protobufjs/pool": ["@protobufjs/[email protected]", "", {}, "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw=="],++ "@protobufjs/utf8": ["@protobufjs/[email protected]", "", {}, "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug=="],+"@radix-ui/colors": ["@radix-ui/[email protected]", "https://registry.npmjs.com/@radix-ui/colors/-/colors-3.0.0.tgz", {}, "sha512-FUOsGBkHrYJwCSEtWRCIfQbZG7q1e6DgxCIOe1SUQzDe/7rXXeA47s8yCn6fuTNQAj1Zq4oTFi9Yjp3wzElcxg=="],"@radix-ui/number": ["@radix-ui/[email protected]", "https://registry.npmjs.com/@radix-ui/number/-/number-1.1.1.tgz", {}, "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g=="],@@ -1137,6 +1158,8 @@"flat-cache": ["[email protected]", "https://registry.npmjs.com/flat-cache/-/flat-cache-4.0.1.tgz", { "dependencies": { "flatted": "^3.2.9", "keyv": "^4.5.4" } }, "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw=="],+ "flatbuffers": ["[email protected]", "", {}, "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ=="],+"flatted": ["[email protected]", "https://registry.npmjs.com/flatted/-/flatted-3.3.3.tgz", {}, "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg=="],"for-each": ["[email protected]", "https://registry.npmjs.com/for-each/-/for-each-0.3.5.tgz", { "dependencies": { "is-callable": "^1.2.7" } }, "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg=="],@@ -1179,6 +1202,8 @@"graceful-fs": ["[email protected]", "https://registry.npmjs.com/graceful-fs/-/graceful-fs-4.2.11.tgz", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],+ "guid-typescript": ["[email protected]", "", {}, "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ=="],+"has-bigints": ["[email protected]", "https://registry.npmjs.com/has-bigints/-/has-bigints-1.1.0.tgz", {}, "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg=="],"has-flag": ["[email protected]", "https://registry.npmjs.com/has-flag/-/has-flag-4.0.0.tgz", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],@@ -1237,6 +1262,8 @@"iobuffer": ["[email protected]", "", {}, "sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA=="],+ "iota-array": ["[email protected]", "", {}, "sha512-pZ2xT+LOHckCatGQ3DcG/a+QuEqvoxqkiL7tvE8nn3uuu+f6i1TtpB5/FtWFbxUuVr5PZCx8KskuGatbJDXOWA=="],+"is-alphabetical": ["[email protected]", "https://registry.npmjs.com/is-alphabetical/-/is-alphabetical-2.0.1.tgz", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="],"is-alphanumerical": ["[email protected]", "https://registry.npmjs.com/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz", { "dependencies": { "is-alphabetical": "^2.0.0", "is-decimal": "^2.0.0" } }, "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw=="],@@ -1249,6 +1276,8 @@"is-boolean-object": ["[email protected]", "https://registry.npmjs.com/is-boolean-object/-/is-boolean-object-1.2.2.tgz", { "dependencies": { "call-bound": "^1.0.3", "has-tostringtag": "^1.0.2" } }, "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A=="],+ "is-buffer": ["[email protected]", "", {}, "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w=="],+"is-bun-module": ["[email protected]", "https://registry.npmjs.com/is-bun-module/-/is-bun-module-2.0.0.tgz", { "dependencies": { "semver": "^7.7.1" } }, "sha512-gNCGbnnnnFAUGKeZ9PdbyeGYJqewpmc2aKHUEMO5nQPWU9lOmv7jcmQIv+qHD8fXW6W7qfuCwX4rY9LNRjXrkQ=="],"is-callable": ["[email protected]", "https://registry.npmjs.com/is-callable/-/is-callable-1.2.7.tgz", {}, "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA=="],@@ -1383,6 +1412,8 @@"lodash.merge": ["[email protected]", "https://registry.npmjs.com/lodash.merge/-/lodash.merge-4.6.2.tgz", {}, "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ=="],+ "long": ["[email protected]", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="],+"longest-streak": ["[email protected]", "https://registry.npmjs.com/longest-streak/-/longest-streak-3.1.0.tgz", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="],"loose-envify": ["[email protected]", "https://registry.npmjs.com/loose-envify/-/loose-envify-1.4.0.tgz", { "dependencies": { "js-tokens": "^3.0.0 || ^4.0.0" }, "bin": { "loose-envify": "cli.js" } }, "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q=="],@@ -1523,6 +1554,8 @@"natural-compare": ["[email protected]", "https://registry.npmjs.com/natural-compare/-/natural-compare-1.4.0.tgz", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="],+ "ndarray": ["[email protected]", "", { "dependencies": { "iota-array": "^1.0.0", "is-buffer": "^1.0.2" } }, "sha512-B4JHA4vdyZU30ELBw3g7/p9bZupyew5a7tX1Y/gGeF2hafrPaQZhgrGQfsvgfYbgdFZjYwuEcnaobeM/WMW+HQ=="],+"negotiator": ["[email protected]", "https://registry.npmjs.com/negotiator/-/negotiator-1.0.0.tgz", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],"next": ["[email protected]", "https://registry.npmjs.com/next/-/next-16.1.3.tgz", { "dependencies": { "@next/env": "16.1.3", "@swc/helpers": "0.5.15", "baseline-browser-mapping": "^2.8.3", "caniuse-lite": "^1.0.30001579", "postcss": "8.4.31", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.1.3", "@next/swc-darwin-x64": "16.1.3", "@next/swc-linux-arm64-gnu": "16.1.3", "@next/swc-linux-arm64-musl": "16.1.3", "@next/swc-linux-x64-gnu": "16.1.3", "@next/swc-linux-x64-musl": "16.1.3", "@next/swc-win32-arm64-msvc": "16.1.3", "@next/swc-win32-x64-msvc": "16.1.3", "sharp": "^0.34.4" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-gthG3TRD+E3/mA0uDQb9lqBmx1zVosq5kIwxNN6+MRNd085GzD+9VXMPUs+GGZCbZ+GDZdODUq4Pm7CTXK6ipw=="],@@ -1569,6 +1602,10 @@"oidc-token-hash": ["[email protected]", "https://registry.npmjs.com/oidc-token-hash/-/oidc-token-hash-5.2.0.tgz", {}, "sha512-6gj2m8cJZ+iSW8bm0FXdGF0YhIQbKrfP4yWTNzxc31U6MOjfEmB1rHvlYvxI1B7t7BCi1F2vYTT6YhtQRG4hxw=="],+ "onnxruntime-common": ["[email protected]", "", {}, "sha512-Q632iLLrtCAVOTO65dh2+mNbQir/QNTVBG3h/QdZBpns7mZ0RYbLRBgGABPbpU9351AgYy7SJf1WaeVwMrBFPQ=="],++ "onnxruntime-web": ["[email protected]", "", { "dependencies": { "flatbuffers": "^25.1.24", "guid-typescript": "^1.0.9", "long": "^5.2.3", "onnxruntime-common": "1.21.0", "platform": "^1.3.6", "protobufjs": "^7.2.4" } }, "sha512-adzOe+7uI7lKz6pQNbAsLMQd2Fq5Jhmoxd8LZjJr8m3KvbFyiYyRxRiC57/XXD+jb18voppjeGAjoZmskXG+7A=="],+"openid-client": ["[email protected]", "https://registry.npmjs.com/openid-client/-/openid-client-5.7.1.tgz", { "dependencies": { "jose": "^4.15.9", "lru-cache": "^6.0.0", "object-hash": "^2.2.0", "oidc-token-hash": "^5.0.3" } }, "sha512-jDBPgSVfTnkIh71Hg9pRvtJc6wTwqjRkN88+gCFtYWrlP4Yx2Dsrow8uPi3qLr/aeymPF3o2+dS+wOpglK04ew=="],"optionator": ["[email protected]", "https://registry.npmjs.com/optionator/-/optionator-0.9.4.tgz", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="],@@ -1607,6 +1644,8 @@"pkg-types": ["[email protected]", "https://registry.npmjs.com/pkg-types/-/pkg-types-2.3.0.tgz", { "dependencies": { "confbox": "^0.2.2", "exsolve": "^1.0.7", "pathe": "^2.0.3" } }, "sha512-SIqCzDRg0s9npO5XQ3tNZioRY1uK06lA41ynBC1YmFTmnY6FjUjVt6s4LoADmwoig1qqD0oK8h1p/8mlMx8Oig=="],+ "platform": ["[email protected]", "", {}, "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg=="],+"pngjs": ["[email protected]", "", {}, "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw=="],"po-parser": ["[email protected]", "https://registry.npmjs.com/po-parser/-/po-parser-2.1.1.tgz", {}, "sha512-ECF4zHLbUItpUgE3OTtLKlPjeBN+fKEczj2zYjDfCGOzicNs0GK3Vg2IoAYwx7LH/XYw43fZQP6xnZ4TkNxSLQ=="],@@ -1631,6 +1670,8 @@"property-information": ["[email protected]", "https://registry.npmjs.com/property-information/-/property-information-7.1.0.tgz", {}, "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ=="],+ "protobufjs": ["[email protected]", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.5", "@protobufjs/eventemitter": "^1.1.1", "@protobufjs/fetch": "^1.1.1", "@protobufjs/float": "^1.0.2", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.1", "@types/node": ">=13.7.0", "long": "^5.3.2" } }, "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg=="],+"punycode": ["[email protected]", "https://registry.npmjs.com/punycode/-/punycode-2.3.1.tgz", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],"pure-rand": ["[email protected]", "https://registry.npmjs.com/pure-rand/-/pure-rand-6.1.0.tgz", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],@@ -1953,6 +1994,8 @@"@formatjs/ecma402-abstract/@formatjs/intl-localematcher": ["@formatjs/[email protected]", "https://registry.npmjs.com/@formatjs/intl-localematcher/-/intl-localematcher-0.6.2.tgz", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-XOMO2Hupl0wdd172Y06h6kLpBz6Dv+J4okPLl4LPtzbr8f66WbIoy4ev98EBuZ6ZK4h5ydTN6XneT4QVpD7cdA=="],+ "@imgly/background-removal/zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],+"@radix-ui/react-alert-dialog/@radix-ui/react-slot": ["@radix-ui/[email protected]", "https://registry.npmjs.com/@radix-ui/react-slot/-/react-slot-1.2.3.tgz", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],"@radix-ui/react-aspect-ratio/@radix-ui/react-primitive": ["@radix-ui/[email protected]", "https://registry.npmjs.com/@radix-ui/react-primitive/-/react-primitive-2.1.4.tgz", { "dependencies": { "@radix-ui/react-slot": "1.2.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg=="],diff --git a/package.json b/package.jsonindex 9a9140c..c873640 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.3.2",+ "version": "0.4.0","private": false,"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.","scripts": {@@ -19,6 +19,7 @@"@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2","@hookform/resolvers": "^5.1.1",+ "@imgly/background-removal": "^1.7.0","@mdxeditor/editor": "^3.39.1","@prisma/client": "^6.11.1","@radix-ui/react-accordion": "^1.2.11",diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 86d1dbe..f75caff 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -9,16 +9,34 @@ datasource db {// A user design / project — the core artifact of Canvix.model Design {- id String @id @default(cuid())- name String @default("Untitled design")- width Int @default(1080)- height Int @default(1080)+ id String @id @default(cuid())+ name String @default("Untitled design")+ width Int @default(1080)+ height Int @default(1080)// Structured document: { pages: PageData[], ... } — stored as native jsonb- pages Json @default("[]")- thumbnail String? // small dataURL preview- source String @default("blank") // blank | template:<id> | duplicate:<id>- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt+ pages Json @default("[]")+ thumbnail String? // small dataURL preview+ source String @default("blank") // blank | template:<id> | duplicate:<id> | resize:<id>+ // soft delete (dashboard Trash) — null = live design+ deletedAt DateTime?+ versions DesignVersion[]+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+}++// Server-side version snapshots for a design (Canva "Version history").+model DesignVersion {+ id String @id @default(cuid())+ designId String+ design Design @relation(fields: [designId], references: [id], onDelete: Cascade)+ label String @default("Version")+ name String+ width Int+ height Int+ pages Json+ createdAt DateTime @default(now())++ @@index([designId, createdAt(sort: Desc)])}// Built-in starter templates rendered in the dashboard & editor.diff --git a/research/CANVA-V04-RESEARCH.md b/research/CANVA-V04-RESEARCH.mdnew file mode 100644index 0000000..3fd0ef2--- /dev/null+++ b/research/CANVA-V04-RESEARCH.md@@ -0,0 +1,72 @@+# Canva research — v0.4.0 fresh pass (2026-09-03, session 3)++> Method: stealth Playwright (Chrome 152, automation flags stripped, warmed-up+> Cloudflare clearance) over canva.com public pages. Captures in+> `research/fresh-capture/` (gitignored). The editor itself stays behind login;+> editor facts come from the earlier v0.3 research passes.++## 1. Landing page (2026 re-design)+- H1: "What will you design today?" — CTA "Start designing"+- Tagline: "Make AI-powered social posts, videos, presentations, and more"+- Hero feature tiles (order matters — it's their marketing priority):+ Magic Layers → Magic Eraser → Background Remover → Magic Write →+ Presentations → Templates → Brand Kit → Animations → Video editor →+ Background Remover (again) → Image Upscaler → Magic Resize → Video editor →+ Video templates → Stock videos → AI Captions → Print Shop → Magic Resize+ (again) → Invitations → AI Image Generator+- Visual Suite nav: Sheets, Docs, Whiteboards, Presentations, Social, Photo+ Editor, Videos, Print, Websites, PDF Editor+- "Unlock Canva's creative ecosystem" → Disney & Marvel templates++## 2. canva.com/canva-ai (Canva AI 2.0)+- "Coming Soon" banner: conversational creation — start with an idea (text or+ voice), connect to your world (pulls context from connected tools), edit+ your way (chat or manual), generate elements (image/chart/headline on+ request), brand-aware outputs, run web research, learns over time,+ scheduled tasks+- → Canvix answer: **Canvix AI assistant app** (chat copilot that sees the+ design, with add-text / generate-image / palette / translate actions)++## 3. Feature pages studied+- **Magic Resize** (canva.com/pro/magic-resize): "Use Magic Resize™ to resize,+ transform, and translate your designs" — Magic Switch resizes one design+ into many for all channels. → Canvix: multi-select presets + Copy & resize+ + in-place smart re-layout (v0.4 implemented)+- **Magic Layers** (canva.com/magic-layers, Beta): "Turn your flat design into+ an editable layout" — upload a flat design, get selectable/movable/editable+ elements. → Canvix: deferred (needs image→elements decomposition)+- **Background Remover** (canva.com/features/background-remover): one-click,+ drag-drop upload or in-editor "BG Remover" toolbar button, PNG download.+ → Canvix v0.4: in-browser ONNX segmentation (true alpha)+- **Translate** (canva.com/translate): AI translation of designs into 134+ languages, Pro feature, per-page translation, LTR↔RTL support.+ → Canvix v0.4: 24 languages, all pages at once, layout preserved+- **Templates** (canva.com/templates): categories — Presentations, Instagram+ Posts, Flyers, Websites, Logos, Posters, Facebook Posts, Resumes, Instagram+ Stories, Docs, Invitations, Whiteboard, Desktop Wallpapers, Business Cards,+ Calendars, Certificates, T-Shirts, Cards, Worksheets, Invoices.+ → Canvix v0.4: + "Docs & office" category (resume, certificate, invoice,+ calendar, business card)++## 4. Deferred gaps (v0.5+ backlog)+- Magic Layers (flat-design → editable elements)+- Real-time collaboration & comments (presence backend)+- Animations (Magic Animate — preview-time element/page animations)+- SVG export; video/MP4 export+- Whiteboards / Docs / Sheets editors (separate apps)+- Canva AI 2.0's connected-context + scheduled tasks (needs accounts)++## 5. v0.4.0 implementation summary+| Canva feature | Canvix v0.4 implementation | Status |+|---|---|---|+| Magic Resize / Magic Switch | ResizeDialog: 12 presets, in-place or copy&resize, smart re-layout (lib/magic.ts) | ✅ |+| Background Remover | In-browser ONNX (`@imgly/background-removal`), true alpha PNG | ✅ |+| Magic Eraser | `/api/ai/image-edit` mode=erase (generative object removal) | ✅ |+| Image Upscaler | `/api/ai/image-edit` mode=enhance (sharpen/clean) | ✅ |+| Translate (134 langs) | `/api/ai/translate` + TranslateDialog, 24 languages, all pages | ✅ (24 langs) |+| Canva AI 2.0 assistant | `/api/ai/assistant` + AssistantApp chat with action chips | ✅ (local design context) |+| Photo search (millions) | `/api/photos/search` (z-ai image search) + live Photos panel results | ✅ (web-scale) |+| Version history (server) | DesignVersion model on Postgres + versions API + sync | ✅ |+| Trash | Design.deletedAt soft delete + restore/delete-forever UI | ✅ |+| Template categories | +5 docs/office templates (21 total) | ✅ |+| Magic Layers | — | ⏳ v0.5 |diff --git a/src/app/api/ai/assistant/route.ts b/src/app/api/ai/assistant/route.tsnew file mode 100644index 0000000..e0c3eb1--- /dev/null+++ b/src/app/api/ai/assistant/route.ts@@ -0,0 +1,130 @@+import { NextRequest, NextResponse } from 'next/server'++export const runtime = 'nodejs'+export const maxDuration = 60++interface ChatMessage {+ role: 'user' | 'assistant'+ content: string+}++interface AssistantBody {+ message?: string+ history?: ChatMessage[]+ design?: {+ name?: string+ width?: number+ height?: number+ pageCount?: number+ currentPageElements?: number+ textContents?: string[]+ }+}++type AssistantAction =+ | { type: 'addText'; text: string; fontSize?: number; bold?: boolean }+ | { type: 'generateImage'; prompt: string }+ | { type: 'suggestPalette'; colors: string[] }+ | { type: 'translate'; language: string }++interface AssistantReply {+ reply: string+ actions: AssistantAction[]+}++/** Robust JSON object extraction from an LLM reply (handles trailing junk). */+function parseReply(raw: string): AssistantReply | null {+ const cleaned = raw.replace(/```(?:json)?/gi, '').trim()+ const start = cleaned.indexOf('{')+ if (start === -1) return null+ // walk closing braces backwards — LLMs sometimes emit trailing "}"/junk+ let end = cleaned.lastIndexOf('}')+ while (end > start) {+ let obj: AssistantReply | null = null+ try {+ obj = JSON.parse(cleaned.slice(start, end + 1)) as AssistantReply+ } catch {+ obj = null+ }+ if (obj && typeof obj.reply === 'string') {+ const actions = Array.isArray(obj.actions) ? obj.actions : []+ const valid: AssistantAction[] = []+ for (const a of actions) {+ if (!a || typeof a !== 'object' || typeof a.type !== 'string') continue+ if (a.type === 'addText' && typeof a.text === 'string' && a.text.trim()) {+ valid.push({ type: 'addText', text: a.text.slice(0, 400), fontSize: Number(a.fontSize) || undefined, bold: Boolean(a.bold) })+ } else if (a.type === 'generateImage' && typeof a.prompt === 'string' && a.prompt.trim()) {+ valid.push({ type: 'generateImage', prompt: a.prompt.slice(0, 400) })+ } else if (a.type === 'suggestPalette' && Array.isArray(a.colors)) {+ const colors = a.colors.filter((c) => typeof c === 'string' && /^#[0-9a-fA-F]{6}$/.test(c)).slice(0, 5)+ if (colors.length >= 3) valid.push({ type: 'suggestPalette', colors })+ } else if (a.type === 'translate' && typeof a.language === 'string' && a.language.trim()) {+ valid.push({ type: 'translate', language: a.language.slice(0, 40) })+ }+ }+ return { reply: obj.reply.slice(0, 1500), actions: valid.slice(0, 4) }+ }+ end = cleaned.lastIndexOf('}', end - 1)+ }+ return null+}++/** POST /api/ai/assistant — Canva AI-style conversational design assistant. */+export async function POST(req: NextRequest) {+ try {+ const body = (await req.json()) as AssistantBody+ const message = (body.message ?? '').trim().slice(0, 1500)+ if (!message) return NextResponse.json({ error: 'A message is required.' }, { status: 400 })++ const d = body.design ?? {}+ const texts = (d.textContents ?? []).slice(0, 40).map((t) => JSON.stringify(t.slice(0, 120))).join(', ')+ const designSummary = [+ `Design name: ${d.name ?? 'Untitled'}`,+ `Canvas: ${d.width ?? '?'}x${d.height ?? '?'}px`,+ `Pages: ${d.pageCount ?? 1} (assistant sees page ${1})`,+ `Elements on the current page: ${d.currentPageElements ?? 0}`,+ texts ? `Text content in the design: ${texts}` : 'No text yet',+ ].join('\n')++ const system =+ 'You are the Canvix AI assistant — a friendly, expert graphic-design copilot embedded in a ' ++ 'design editor (similar to Canva AI). You help users ideate copy, pick colours, plan layouts, and ' ++ 'improve designs. You are concise (max 120 words), warm and practical.\n' ++ 'You can attach actions the app will offer as one-tap buttons. Respond ONLY with a JSON object: ' ++ '{"reply": string, "actions": [{"type": "addText", "text": string, "fontSize"?: number, "bold"?: boolean} | ' ++ '{"type": "generateImage", "prompt": string} | {"type": "suggestPalette", "colors": string[] (3-5 hex)} | ' ++ '{"type": "translate", "language": string}]}\n' ++ 'Rules: attach at most 2 actions and only when clearly useful (e.g. the user asks for a headline -> addText; ' ++ 'asks for visuals -> generateImage; asks about colours -> suggestPalette). If no action applies, use an empty array. ' ++ 'addText text should be short & design-ready. generateImage prompt must be a rich visual description. ' ++ 'No markdown in "reply" — plain text only.'++ const history = (body.history ?? []).slice(-8)+ .filter((m) => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string')+ .map((m) => ({ role: m.role, content: m.content.slice(0, 1000) }))++ const { default: ZAI } = await import('z-ai-web-dev-sdk')+ const zai = await ZAI.create()++ const completion = await zai.chat.completions.create({+ messages: [+ { role: 'assistant', content: system },+ { role: 'assistant', content: `Current design context:\n${designSummary}` },+ ...history,+ { role: 'user', content: message },+ ],+ thinking: { type: 'disabled' },+ })++ const raw = completion.choices[0]?.message?.content ?? ''+ const parsed = parseReply(raw)+ if (!parsed) {+ // graceful fallback: treat the whole reply as plain text+ return NextResponse.json({ reply: raw.slice(0, 1200) || 'Sorry, I could not answer that. Try rephrasing.', actions: [] })+ }+ return NextResponse.json(parsed)+ } catch (err) {+ console.error('[api/ai/assistant]', err)+ return NextResponse.json({ error: 'The AI assistant is unavailable right now. Please try again.' }, { status: 502 })+ }+}diff --git a/src/app/api/ai/image-edit/route.ts b/src/app/api/ai/image-edit/route.tsnew file mode 100644index 0000000..5de73d7--- /dev/null+++ b/src/app/api/ai/image-edit/route.ts@@ -0,0 +1,99 @@+import { NextRequest, NextResponse } from 'next/server'++export const runtime = 'nodejs'+export const maxDuration = 60++const SUPPORTED_SIZES = ['1024x1024', '1344x768', '768x1344', '1152x864', '864x1152', '1440x720', '720x1440'] as const+type ImgSize = (typeof SUPPORTED_SIZES)[number]++interface EditBody {+ image?: string // dataURL or remote URL+ prompt?: string // edit instruction+ mode?: 'edit' | 'bg-remove' | 'erase' | 'enhance'+ eraseTarget?: string // for mode=erase: what to remove+ naturalWidth?: number+ naturalHeight?: number+}++/** Pick the SDK output size whose aspect ratio is closest to the source image. */+function bestSize(w: number, h: number): ImgSize {+ const ratio = w / h+ let best: ImgSize = '1024x1024'+ let bestDiff = Infinity+ for (const s of SUPPORTED_SIZES) {+ const [sw, sh] = s.split('x').map(Number)+ const diff = Math.abs(Math.log(sw / sh) - Math.log(ratio))+ if (diff < bestDiff) {+ bestDiff = diff+ best = s+ }+ }+ return best+}++const MODE_PROMPTS: Record<string, string> = {+ 'bg-remove':+ 'Remove the background completely and isolate the main subject. Keep the subject pixel-identical ' ++ 'with full detail, lighting and edges. Make the entire background fully transparent (alpha 0). ' ++ 'Output a PNG with transparency. Do not add any new background, shadow, border or watermark.',+ erase:+ 'Remove the described object cleanly and reconstruct the background behind it so the area looks ' ++ 'natural and continuous. Keep everything else pixel-identical. Output a PNG. No text or watermarks.',+ enhance:+ 'Enhance this photo: increase sharpness and clarity, improve lighting and color balance, reduce noise. ' ++ 'Keep the composition, subject and framing exactly the same. Natural, professional result.',+}++/** POST /api/ai/image-edit — Canva-style AI image tools (BG remover, Magic eraser, enhance). */+export async function POST(req: NextRequest) {+ try {+ const body = (await req.json()) as EditBody+ const image = (body.image ?? '').trim()+ if (!image || !/^(data:image\/|https?:\/\/)/.test(image)) {+ return NextResponse.json({ error: 'A valid image is required.' }, { status: 400 })+ }++ const mode = body.mode ?? 'edit'+ let prompt: string+ if (mode === 'erase') {+ const target = (body.eraseTarget ?? body.prompt ?? '').trim().slice(0, 300)+ if (!target) return NextResponse.json({ error: 'Describe what to remove.' }, { status: 400 })+ prompt = `${MODE_PROMPTS.erase} Object to remove: ${target}`+ } else if (mode === 'edit') {+ prompt = (body.prompt ?? '').trim().slice(0, 600)+ if (!prompt) return NextResponse.json({ error: 'A prompt is required.' }, { status: 400 })+ } else {+ prompt = MODE_PROMPTS[mode]+ }++ const w = Number(body.naturalWidth) || 0+ const h = Number(body.naturalHeight) || 0+ const size: ImgSize = w && h ? bestSize(w, h) : '1024x1024'++ const { default: ZAI } = await import('z-ai-web-dev-sdk')+ const zai = await ZAI.create()++ // NOTE: the SDK's TS type declares `image`, but the backend API requires+ // `images: [{ url }]` (verified — API error 1210 "must provide images").+ // The SDK forwards the body verbatim, so we send the correct runtime shape.+ const response = await zai.images.generations.edit({+ prompt,+ images: [{ url: image }],+ size,+ } as unknown as Parameters<typeof zai.images.generations.edit>[0])++ const base64 = response.data[0]?.base64+ if (!base64) {+ return NextResponse.json({ error: 'The image service returned no image. Try again.' }, { status: 502 })+ }++ const [outW, outH] = size.split('x').map(Number)+ return NextResponse.json({ dataUrl: `data:image/png;base64,${base64}`, width: outW, height: outH })+ } catch (err) {+ console.error('[api/ai/image-edit]', err)+ return NextResponse.json(+ { error: 'AI image editing is unavailable right now. Please try again.' },+ { status: 502 }+ )+ }+}diff --git a/src/app/api/ai/translate/route.ts b/src/app/api/ai/translate/route.tsnew file mode 100644index 0000000..b60d99e--- /dev/null+++ b/src/app/api/ai/translate/route.ts@@ -0,0 +1,78 @@+import { NextRequest, NextResponse } from 'next/server'++export const runtime = 'nodejs'+export const maxDuration = 60++interface TranslateBody {+ texts?: string[]+ language?: string+}++/** Robustly extract the first JSON array of strings from an LLM reply+ * (walks closing brackets backwards to tolerate trailing junk). */+function parseTranslations(raw: string, expected: number): string[] | null {+ // strip code fences if present+ const cleaned = raw.replace(/```(?:json)?/gi, '').trim()+ const start = cleaned.indexOf('[')+ if (start === -1) return null+ let end = cleaned.lastIndexOf(']')+ while (end > start) {+ try {+ const arr = JSON.parse(cleaned.slice(start, end + 1))+ if (Array.isArray(arr) && arr.every((x) => typeof x === 'string') && arr.length === expected) {+ return arr+ }+ } catch {+ /* try an earlier closing bracket */+ }+ end = cleaned.lastIndexOf(']', end - 1)+ }+ return null+}++/** POST /api/ai/translate — Canva "Translate": translate an array of design texts. */+export async function POST(req: NextRequest) {+ try {+ const body = (await req.json()) as TranslateBody+ const language = (body.language ?? '').trim()+ const texts = Array.isArray(body.texts) ? body.texts.filter((t) => typeof t === 'string') : []++ if (!language) return NextResponse.json({ error: 'A target language is required.' }, { status: 400 })+ if (!texts.length) return NextResponse.json({ error: 'No texts to translate.' }, { status: 400 })+ if (texts.length > 300) return NextResponse.json({ error: 'Too many texts (max 300).' }, { status: 400 })+ if (texts.some((t) => t.length > 2000)) {+ return NextResponse.json({ error: 'One of the texts is too long (max 2000 chars).' }, { status: 400 })+ }++ const numbered = texts.map((t, i) => `${i + 1}. ${JSON.stringify(t)}`).join('\n')+ const system =+ 'You are a professional design translator for a graphic-design tool. ' ++ 'Translate each numbered text into the requested language, keeping the meaning, tone and style. ' ++ 'Preserve line breaks, emoji and placeholders. Keep brand names, URLs and proper nouns untranslated. ' ++ 'Adapt naturally (idiomatic), do not transliterate unless the language requires it. ' ++ 'Respond ONLY with a JSON array of strings in the same order and same length as the input. No markdown, no numbering.'++ const user = `Target language: ${language}\n\nTexts:\n${numbered}\n\nRespond with a JSON array of ${texts.length} translated strings, same order.`++ const { default: ZAI } = await import('z-ai-web-dev-sdk')+ const zai = await ZAI.create()++ const completion = await zai.chat.completions.create({+ messages: [+ { role: 'assistant', content: system },+ { role: 'user', content: user },+ ],+ thinking: { type: 'disabled' },+ })++ const reply = completion.choices[0]?.message?.content ?? ''+ const translations = parseTranslations(reply, texts.length)+ if (!translations) {+ return NextResponse.json({ error: 'Translation failed — please try again.' }, { status: 502 })+ }+ return NextResponse.json({ language, translations })+ } catch (err) {+ console.error('[api/ai/translate]', err)+ return NextResponse.json({ error: 'Translate is unavailable right now. Please try again.' }, { status: 502 })+ }+}diff --git a/src/app/api/designs/[id]/restore/route.ts b/src/app/api/designs/[id]/restore/route.tsnew file mode 100644index 0000000..70d7747--- /dev/null+++ b/src/app/api/designs/[id]/restore/route.ts@@ -0,0 +1,17 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'++// POST /api/designs/[id]/restore — restore a design from the Trash+export async function POST(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {+ try {+ const { id } = await params+ const design = await db.design.update({+ where: { id },+ data: { deletedAt: null },+ })+ return NextResponse.json({ ok: true, id: design.id })+ } catch (error) {+ console.error('POST /api/designs/[id]/restore failed', error)+ return NextResponse.json({ error: 'Failed to restore design' }, { status: 500 })+ }+}diff --git a/src/app/api/designs/[id]/route.ts b/src/app/api/designs/[id]/route.tsindex ff6c559..3ee136e 100644--- a/src/app/api/designs/[id]/route.ts+++ b/src/app/api/designs/[id]/route.ts@@ -45,12 +45,17 @@ export async function PUT(req: NextRequest, { params }: { params: Promise<{ id:}}-// DELETE /api/designs/[id]-export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {+// DELETE /api/designs/[id] — move to Trash (soft delete).+// ?permanent=1 → delete permanently (also removes version snapshots).+export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {try {const { id } = await params- await db.design.delete({ where: { id } })- return NextResponse.json({ ok: true })+ if (req.nextUrl.searchParams.get('permanent') === '1') {+ await db.design.delete({ where: { id } })+ return NextResponse.json({ ok: true, permanent: true })+ }+ await db.design.update({ where: { id }, data: { deletedAt: new Date() } })+ return NextResponse.json({ ok: true, trashed: true })} catch (error) {console.error('DELETE /api/designs/[id] failed', error)return NextResponse.json({ error: 'Failed to delete design' }, { status: 500 })diff --git a/src/app/api/designs/[id]/versions/route.ts b/src/app/api/designs/[id]/versions/route.tsnew file mode 100644index 0000000..f813863--- /dev/null+++ b/src/app/api/designs/[id]/versions/route.ts@@ -0,0 +1,82 @@+import { NextRequest, NextResponse } from 'next/server'+import { Prisma } from '@prisma/client'+import { db } from '@/lib/db'++// GET /api/designs/[id]/versions — list server-side version snapshots (newest first)+export async function GET(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {+ try {+ const { id } = await params+ const versions = await db.designVersion.findMany({+ where: { designId: id },+ orderBy: { createdAt: 'desc' },+ take: 30,+ })+ return NextResponse.json(+ versions.map((v) => ({+ id: v.id,+ label: v.label,+ name: v.name,+ width: v.width,+ height: v.height,+ pages: v.pages ?? [],+ createdAt: v.createdAt.toISOString(),+ server: true,+ }))+ )+ } catch (error) {+ console.error('GET /api/designs/[id]/versions failed', error)+ return NextResponse.json({ error: 'Failed to list versions' }, { status: 500 })+ }+}++// POST /api/designs/[id]/versions — save a new version snapshot+export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {+ try {+ const { id } = await params+ const body = await req.json()++ const exists = await db.design.findUnique({ where: { id }, select: { id: true } })+ if (!exists) return NextResponse.json({ error: 'Design not found' }, { status: 404 })++ const version = await db.designVersion.create({+ data: {+ designId: id,+ label: typeof body.label === 'string' && body.label.trim() ? body.label.trim().slice(0, 120) : 'Version',+ name: typeof body.name === 'string' ? body.name.slice(0, 120) : 'Untitled design',+ width: Number.isFinite(body.width) ? Math.round(body.width) : 1080,+ height: Number.isFinite(body.height) ? Math.round(body.height) : 1080,+ pages: (body.pages ?? []) as Prisma.InputJsonValue,+ },+ })++ // prune: keep the 30 most recent per design+ const keep = await db.designVersion.findMany({+ where: { designId: id },+ orderBy: { createdAt: 'desc' },+ take: 30,+ select: { id: true },+ })+ if (keep.length === 30) {+ await db.designVersion.deleteMany({+ where: { designId: id, id: { notIn: keep.map((k) => k.id) } },+ })+ }++ return NextResponse.json(+ {+ id: version.id,+ label: version.label,+ name: version.name,+ width: version.width,+ height: version.height,+ pages: version.pages ?? [],+ createdAt: version.createdAt.toISOString(),+ server: true,+ },+ { status: 201 }+ )+ } catch (error) {+ console.error('POST /api/designs/[id]/versions failed', error)+ return NextResponse.json({ error: 'Failed to save version' }, { status: 500 })+ }+}diff --git a/src/app/api/designs/route.ts b/src/app/api/designs/route.tsindex a0ed2bc..a5b6c53 100644--- a/src/app/api/designs/route.ts+++ b/src/app/api/designs/route.ts@@ -11,10 +11,13 @@ function toPages(value: unknown): Prisma.InputJsonValue {return (value ?? []) as Prisma.InputJsonValue}-// GET /api/designs — list all designs (metadata only, newest first)-export async function GET() {+// GET /api/designs — list designs (metadata only, newest first)+// ?trash=1 → only soft-deleted designs; default → only live designs+export async function GET(req: NextRequest) {try {+ const trash = req.nextUrl.searchParams.get('trash') === '1'const designs = await db.design.findMany({+ where: { deletedAt: trash ? { not: null } : null },orderBy: { updatedAt: 'desc' },select: {id: true,@@ -23,6 +26,7 @@ export async function GET() {height: true,thumbnail: true,source: true,+ deletedAt: true,createdAt: true,updatedAt: true,},diff --git a/src/app/api/photos/search/route.ts b/src/app/api/photos/search/route.tsnew file mode 100644index 0000000..7e70051--- /dev/null+++ b/src/app/api/photos/search/route.ts@@ -0,0 +1,37 @@+import { NextRequest, NextResponse } from 'next/server'++export const runtime = 'nodejs'+export const maxDuration = 30++interface SearchBody {+ query?: string+ count?: number+}++/** POST /api/photos/search — runtime stock-photo search (Canva-like photo search). */+export async function POST(req: NextRequest) {+ try {+ const body = (await req.json()) as SearchBody+ const query = (body.query ?? '').trim().slice(0, 120)+ if (!query) return NextResponse.json({ error: 'A query is required.' }, { status: 400 })+ const count = Math.min(Math.max(Number(body.count) || 24, 1), 40)++ const { default: ZAI } = await import('z-ai-web-dev-sdk')+ const zai = await ZAI.create()++ const response = await zai.images.search.create({ query, count })++ const results = (response.results ?? []).map((r) => ({+ url: r.original_url,+ caption: r.caption ?? '',+ source: r.source ?? '',+ width: Number(r.original_width) || 0,+ height: Number(r.original_height) || 0,+ })).filter((r) => r.url)++ return NextResponse.json({ query, count: results.length, results })+ } catch (err) {+ console.error('[api/photos/search]', err)+ return NextResponse.json({ error: 'Photo search is unavailable right now.' }, { status: 502 })+ }+}diff --git a/src/app/api/versions/[id]/route.ts b/src/app/api/versions/[id]/route.tsnew file mode 100644index 0000000..f12f663--- /dev/null+++ b/src/app/api/versions/[id]/route.ts@@ -0,0 +1,14 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'++// DELETE /api/versions/[id] — remove one saved version snapshot+export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {+ try {+ const { id } = await params+ await db.designVersion.delete({ where: { id } })+ return NextResponse.json({ ok: true })+ } catch (error) {+ console.error('DELETE /api/versions/[id] failed', error)+ return NextResponse.json({ error: 'Failed to delete version' }, { status: 500 })+ }+}diff --git a/src/components/dashboard/Dashboard.tsx b/src/components/dashboard/Dashboard.tsxindex 07cf665..df3dd2d 100644--- a/src/components/dashboard/Dashboard.tsx+++ b/src/components/dashboard/Dashboard.tsx@@ -1,6 +1,6 @@'use client'-import { useMemo, useState } from 'react'+import { useCallback, useMemo, useState } from 'react'import {Search,Plus,@@ -8,6 +8,8 @@ import {Pencil,Copy,Trash2,+ RotateCcw,+ ChevronDown,Presentation,Instagram,Printer,@@ -37,11 +39,15 @@ import { cn } from '@/lib/utils'import {createDesign,deleteDesign,+ deleteDesignForever,duplicateDesign,fetchDesign,+ listTrash,renameDesign,+ restoreDesign,timeAgo,useDesigns,+ type DesignMeta,} from './hooks'import {Dialog,@@ -64,6 +70,7 @@ const CATEGORY_ICONS: Record<string, typeof Presentation> = {social: Instagram,presentation: Presentation,print: Printer,+ document: FileImage,logo: BadgeCheck,thumbnail: Video,}@@ -91,6 +98,43 @@ export function Dashboard() {const [renameTarget, setRenameTarget] = useState<{ id: string; name: string } | null>(null)const [renameValue, setRenameValue] = useState('')const [deleteTarget, setDeleteTarget] = useState<string | null>(null)+ // v0.4: trash + sort+ const [trashOpen, setTrashOpen] = useState(false)+ const [trash, setTrash] = useState<DesignMeta[] | null>(null)+ const [sort, setSort] = useState<'recent' | 'name'>('recent')++ const refreshTrash = useCallback(async () => {+ try {+ setTrash(await listTrash())+ } catch {+ setTrash([])+ }+ }, [])++ const toggleTrash = (open: boolean) => {+ setTrashOpen(open)+ if (open && trash === null) void refreshTrash()+ }++ const doRestore = async (id: string, name: string) => {+ try {+ await restoreDesign(id)+ await Promise.all([refresh(), refreshTrash()])+ toast({ title: `“${name}” restored` })+ } catch {+ toast({ title: 'Could not restore', variant: 'destructive' })+ }+ }++ const doDeleteForever = async (id: string, name: string) => {+ try {+ await deleteDesignForever(id)+ await refreshTrash()+ toast({ title: `“${name}” deleted forever` })+ } catch {+ toast({ title: 'Could not delete', variant: 'destructive' })+ }+ }const filteredTemplates = useMemo<TemplateRecord[]>(() =>@@ -108,8 +152,15 @@ export function Dashboard() {)const filteredDesigns = useMemo(- () => (designs ?? []).filter((d) => d.name.toLowerCase().includes(query.toLowerCase())),- [designs, query]+ () =>+ (designs ?? [])+ .filter((d) => d.name.toLowerCase().includes(query.toLowerCase()))+ .sort((a, b) =>+ sort === 'name'+ ? a.name.localeCompare(b.name)+ : new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()+ ),+ [designs, query, sort])// ── actions ─────────────────────────────────────────────────@@ -438,7 +489,25 @@ export function Dashboard() {{/* ── Recent designs ── */}<section id="cv-recents" className="pt-12 scroll-mt-20">- <h2 className="text-xl font-bold">Recent designs</h2>+ <div className="flex items-center justify-between flex-wrap gap-3">+ <h2 className="text-xl font-bold">Recent designs</h2>+ {/* v0.4: canva-style sort control */}+ <div className="flex items-center gap-1 rounded-full border border-white/10 p-0.5" role="group" aria-label="Sort designs">+ {(['recent', 'name'] as const).map((mode) => (+ <button+ key={mode}+ onClick={() => setSort(mode)}+ className={cn(+ 'h-7 px-3 rounded-full text-[11.5px] font-semibold transition-colors',+ sort === mode ? 'bg-[#7630D7] text-white' : 'text-white/55 hover:text-white'+ )}+ aria-pressed={sort === mode}+ >+ {mode === 'recent' ? 'Recent' : 'Name'}+ </button>+ ))}+ </div>+ </div>{loading ? (<div className="mt-4 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">{Array.from({ length: 5 }).map((_, i) => (@@ -507,6 +576,89 @@ export function Dashboard() {</div>)}</section>+ {/* ── Trash (v0.4 — soft-deleted designs) ── */}+ <section id="cv-trash" className="pt-12 scroll-mt-20">+ <button+ onClick={() => toggleTrash(!trashOpen)}+ className="flex items-center gap-2 w-full text-left group"+ aria-expanded={trashOpen}+ aria-controls="trash-list"+ >+ <ChevronDown size={18} className={cn('text-white/50 transition-transform', trashOpen ? '' : '-rotate-90')} />+ <h2 className="text-xl font-bold group-hover:text-[#A78BFA] transition-colors">Trash</h2>+ {trash !== null && (+ <span className="text-xs text-white/40 font-medium">· {trash.length} item{trash.length === 1 ? '' : 's'}</span>+ )}+ </button>++ {trashOpen && (+ <div id="trash-list" className="mt-4">+ {trash === null ? (+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">+ {Array.from({ length: 3 }).map((_, i) => (+ <div key={i}>+ <div className="cv-skeleton w-full aspect-[4/3]" />+ <div className="cv-skeleton h-3.5 w-2/3 mt-2.5" />+ </div>+ ))}+ </div>+ ) : trash.length === 0 ? (+ <div className="rounded-2xl border border-dashed border-white/12 p-8 text-center text-sm text-white/45">+ Trash is empty. Deleted designs land here first — nothing is lost forever.+ </div>+ ) : (+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">+ {trash.map((d) => (+ <div key={d.id} className="group opacity-80 hover:opacity-100 transition-opacity">+ <div+ className="relative rounded-xl overflow-hidden border border-white/10 bg-[#0F1015] grayscale group-hover:grayscale-0 transition-all"+ style={{ aspectRatio: `${d.width} / ${d.height}` }}+ >+ {d.thumbnail ? (+ <img src={d.thumbnail} alt={d.name} className="w-full h-full object-cover" />+ ) : (+ <span className="absolute inset-0 flex items-center justify-center text-white/30 text-xs font-medium">+ {d.width} × {d.height}+ </span>+ )}+ </div>+ <div className="mt-2 flex items-start justify-between gap-1">+ <div className="min-w-0">+ <div className="text-sm font-medium truncate text-white/85">{d.name}</div>+ <div className="text-xs text-white/40">+ deleted {timeAgo(d.deletedAt ?? d.updatedAt)}+ </div>+ </div>+ <div className="flex gap-0.5 shrink-0">+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7 rounded-lg text-white/60 hover:bg-white/10 hover:text-white"+ onClick={() => void doRestore(d.id, d.name)}+ aria-label={`Restore ${d.name}`}+ title="Restore"+ >+ <RotateCcw size={14} />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7 rounded-lg text-white/60 hover:bg-red-500/15 hover:text-red-400"+ onClick={() => void doDeleteForever(d.id, d.name)}+ aria-label={`Delete ${d.name} forever`}+ title="Delete forever"+ >+ <Trash2 size={14} />+ </Button>+ </div>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ )}+ </section></main>{/* ── Footer ── */}@@ -650,16 +802,18 @@ export function Dashboard() {</DialogContent></Dialog>- {/* ── Delete confirm dialog ── */}+ {/* ── Delete confirm dialog (moves to Trash) ── */}<Dialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}><DialogContent className="rounded-[28px] sm:max-w-sm bg-[#16181D] border-white/10 text-white"><DialogHeader><DialogTitle>Delete this design?</DialogTitle>- <DialogDescription className="text-white/55">This action can't be undone.</DialogDescription>+ <DialogDescription className="text-white/55">+ It will move to your Trash. You can restore it anytime — or delete it forever from there.+ </DialogDescription></DialogHeader><DialogFooter><Button variant="outline" className="border-white/15 bg-transparent text-white hover:bg-white/10 hover:text-white" onClick={() => setDeleteTarget(null)}>Cancel</Button>- <Button variant="destructive" onClick={() => deleteTarget && doDelete(deleteTarget)}>Delete</Button>+ <Button variant="destructive" onClick={() => deleteTarget && doDelete(deleteTarget)}>Move to Trash</Button></DialogFooter></DialogContent></Dialog>diff --git a/src/components/dashboard/hooks.ts b/src/components/dashboard/hooks.tsindex 623daf0..7a9860a 100644--- a/src/components/dashboard/hooks.ts+++ b/src/components/dashboard/hooks.ts@@ -10,6 +10,7 @@ export interface DesignMeta {height: numberthumbnail: string | nullsource: string+ deletedAt: string | nullcreatedAt: stringupdatedAt: string}@@ -81,10 +82,27 @@ export async function duplicateDesign(id: string): Promise<DesignRecord> {}export async function deleteDesign(id: string): Promise<void> {- const res = await fetch(`/api/designs/${id}`, { method: 'DELETE' })+ const res = await fetch(`/api/designs/${id}`, { method: 'DELETE' }) // soft delete -> Trashif (!res.ok) throw new Error('Failed to delete design')}+/** v0.4: trash list / restore / permanent delete */+export async function listTrash(): Promise<DesignMeta[]> {+ const res = await fetch('/api/designs?trash=1', { cache: 'no-store' })+ if (!res.ok) throw new Error('Failed to list trash')+ return res.json()+}++export async function restoreDesign(id: string): Promise<void> {+ const res = await fetch(`/api/designs/${id}/restore`, { method: 'POST' })+ if (!res.ok) throw new Error('Failed to restore design')+}++export async function deleteDesignForever(id: string): Promise<void> {+ const res = await fetch(`/api/designs/${id}?permanent=1`, { method: 'DELETE' })+ if (!res.ok) throw new Error('Failed to delete design permanently')+}+export async function renameDesign(id: string, name: string): Promise<void> {const res = await fetch(`/api/designs/${id}`, {method: 'PUT',diff --git a/src/components/editor/ImageAI.tsx b/src/components/editor/ImageAI.tsxnew file mode 100644index 0000000..e33aaef--- /dev/null+++ b/src/components/editor/ImageAI.tsx@@ -0,0 +1,222 @@+'use client'++import { useState } from 'react'+import { Eraser, Wand2, Loader2, Sparkles } from 'lucide-react'+import { useEditorStore } from '@/store/editor-store'+import type { ImageElement } from '@/lib/types'+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { toast } from '@/hooks/use-toast'++interface EditResponse {+ dataUrl?: string+ width?: number+ height?: number+ error?: string+}++/** Normalise an element src into something the AI service can consume:+ * dataURLs and absolute http(s) URLs pass through; relative paths+ * (bundled /photos/*.jpg) are fetched and converted to dataURLs. */+async function toSendableImage(src: string): Promise<string> {+ if (src.startsWith('data:') || /^https?:\/\//.test(src)) return src+ const res = await fetch(src)+ if (!res.ok) throw new Error('Could not load the image')+ const blob = await res.blob()+ return await new Promise<string>((resolve, reject) => {+ const fr = new FileReader()+ fr.onload = () => resolve(String(fr.result))+ fr.onerror = () => reject(new Error('Could not read the image'))+ fr.readAsDataURL(blob)+ })+}++/**+ * Shared AI image-edit runner — calls /api/ai/image-edit and swaps the+ * element's image in place, preserving the on-canvas width and adapting+ * the height to the new aspect ratio.+ */+async function runImageAI(+ el: ImageElement,+ payload: Record<string, unknown>,+ onDone: (msg: string) => void+): Promise<boolean> {+ const update = useEditorStore.getState().updateElements+ try {+ const image = await toSendableImage(el.src)+ const res = await fetch('/api/ai/image-edit', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ image, naturalWidth: el.naturalWidth, naturalHeight: el.naturalHeight, ...payload }),+ })+ const data = (await res.json()) as EditResponse+ if (!res.ok || !data.dataUrl) {+ onDone(data.error ?? 'The edit failed. Please try again.')+ return false+ }+ const w = data.width || el.naturalWidth+ const h = data.height || el.naturalHeight+ // keep on-canvas width; adapt height to the new aspect ratio+ const newHeight = Math.max(4, Math.round(el.width * (h / Math.max(1, w))))+ update([el.id], {+ src: data.dataUrl,+ naturalWidth: w,+ naturalHeight: h,+ height: newHeight,+ })+ return true+ } catch {+ onDone('AI image editing is unavailable right now.')+ return false+ }+}++const btnBase =+ 'cv-tbtn gap-1 !px-2.5 disabled:opacity-60'++/** Blob → dataURL */+function blobToDataURL(blob: Blob): Promise<string> {+ return new Promise((resolve, reject) => {+ const fr = new FileReader()+ fr.onload = () => resolve(String(fr.result))+ fr.onerror = () => reject(new Error('Could not read the result'))+ fr.readAsDataURL(blob)+ })+}++/** natural pixel size of a dataURL image */+function imageSize(dataUrl: string): Promise<{ w: number; h: number }> {+ return new Promise((resolve) => {+ const img = new window.Image()+ img.onload = () => resolve({ w: img.naturalWidth || 1024, h: img.naturalHeight || 1024 })+ img.onerror = () => resolve({ w: 1024, h: 1024 })+ img.src = dataUrl+ })+}++/** Canva "BG Remover" — one-click background removal on the selected image.+ * Runs a local ONNX segmentation model in the browser (true alpha cut-out);+ * the first use downloads the model (~40 MB) once, then it is cached. */+export function BgRemoverButton({ el }: { el: ImageElement }) {+ const [busy, setBusy] = useState(false)+ const [phase, setPhase] = useState<'idle' | 'model' | 'removing'>('idle')+ const run = async () => {+ if (busy) return+ setBusy(true)+ setPhase('model')+ const update = useEditorStore.getState().updateElements+ try {+ const { removeBackground } = await import('@imgly/background-removal')+ const sendable = await toSendableImage(el.src)+ const blob = await (await fetch(sendable)).blob()+ setPhase('removing')+ const result = await removeBackground(blob, {+ output: { format: 'image/png' },+ progress: (key) => {+ if (key === 'fetch:network' || key.startsWith('fetch:')) setPhase('model')+ },+ })+ const dataUrl = await blobToDataURL(result)+ const dims = await imageSize(dataUrl)+ const newHeight = Math.max(4, Math.round(el.width * (dims.h / Math.max(1, dims.w))))+ update([el.id], {+ src: dataUrl,+ naturalWidth: dims.w,+ naturalHeight: dims.h,+ height: newHeight,+ })+ toast({ title: 'Background removed', description: 'The cut-out replaced your image. Ctrl+Z to undo.' })+ } catch (e) {+ toast({+ title: 'Background remover',+ description: e instanceof Error ? e.message : 'Could not remove the background. Please try again.',+ variant: 'destructive',+ })+ } finally {+ setBusy(false)+ setPhase('idle')+ }+ }+ const label = busy ? (phase === 'model' ? 'Loading model…' : 'Removing…') : 'BG Remover'+ return (+ <button className={btnBase} onClick={() => void run()} disabled={busy} title="BG Remover — remove the image background" aria-label="Remove background">+ {busy ? <Loader2 size={14} className="animate-spin" /> : <Eraser size={14} />}+ <span className="text-[12px] hidden lg:inline">{label}</span>+ </button>+ )+}++/** Canva "Magic Eraser" — describe an object to wipe from the photo. */+export function MagicEraserPopover({ el }: { el: ImageElement }) {+ const [target, setTarget] = useState('')+ const [busy, setBusy] = useState(false)+ const [open, setOpen] = useState(false)++ const run = async () => {+ if (!target.trim()) return+ setBusy(true)+ const ok = await runImageAI(el, { mode: 'erase', eraseTarget: target.trim() }, (msg) =>+ toast({ title: 'Magic eraser', description: msg, variant: 'destructive' })+ )+ setBusy(false)+ if (ok) {+ toast({ title: 'Erased', description: `"${target.trim()}" was removed. Ctrl+Z to undo.` })+ setTarget('')+ setOpen(false)+ }+ }++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <button className={btnBase} data-active={open} title="Magic eraser — remove unwanted objects" aria-label="Magic eraser">+ <Sparkles size={14} />+ <span className="text-[12px] hidden lg:inline">Magic eraser</span>+ </button>+ </PopoverTrigger>+ <PopoverContent align="center" side="bottom" className="w-[300px] rounded-2xl bg-[#1A1C22] border-white/10 text-white p-3.5">+ <div className="text-[13px] font-bold mb-1 flex items-center gap-1.5">+ <Wand2 size={13} className="text-[#02C0CC]" /> Magic eraser+ </div>+ <p className="text-[11px] text-white/55 mb-2.5 leading-snug">+ Remove an unwanted object from this photo. Describe it — e.g. "the person in the+ background" or "the trash can on the left".+ </p>+ <div className="flex gap-1.5">+ <Input+ value={target}+ onChange={(e) => setTarget(e.target.value)}+ onKeyDown={(e) => e.key === 'Enter' && !busy && void run()}+ placeholder="What should disappear?"+ className="h-9 bg-white/5 border-white/10 text-white text-[12px]"+ aria-label="Object to remove"+ maxLength={200}+ />+ <Button className="btn-cv h-9 px-3 shrink-0 text-[12px]" onClick={() => void run()} disabled={busy || !target.trim()}>+ {busy ? <Loader2 size={13} className="animate-spin" /> : 'Erase'}+ </Button>+ </div>+ </PopoverContent>+ </Popover>+ )+}++/** Canva "Image Upscaler / enhancer" — one-click AI photo enhance. */+export function EnhanceButton({ el }: { el: ImageElement }) {+ const [busy, setBusy] = useState(false)+ const run = async () => {+ setBusy(true)+ const ok = await runImageAI(el, { mode: 'enhance' }, (msg) =>+ toast({ title: 'Enhance image', description: msg, variant: 'destructive' })+ )+ setBusy(false)+ if (ok) toast({ title: 'Image enhanced', description: 'Sharper, cleaner photo swapped in. Ctrl+Z to undo.' })+ }+ return (+ <button className={btnBase} onClick={() => void run()} disabled={busy} title="Enhance image — sharpen & clean up with AI" aria-label="Enhance image">+ {busy ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}+ <span className="text-[12px] hidden lg:inline">{busy ? 'Enhancing…' : 'Enhance'}</span>+ </button>+ )+}diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsxindex d0d41d2..9713b50 100644--- a/src/components/editor/PropertiesBar.tsx+++ b/src/components/editor/PropertiesBar.tsx@@ -18,6 +18,7 @@ import { cn } from '@/lib/utils'import { FontDropdown } from './toolbar/FontDropdown'import { ColorMenu } from './toolbar/ColorMenu'import { ToolbarPopover, SliderRow, IconTile } from './toolbar/popover-kit'+import { BgRemoverButton, MagicEraserPopover, EnhanceButton } from './ImageAI'const ALIGN_ICONS = {left: AlignLeft,@@ -301,6 +302,10 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm<Crop size={14} /></TBtn><ImageAdjustPopover el={image} ids={ids} />+ {/* v0.4 Canva AI image tools */}+ <BgRemoverButton el={image} />+ <MagicEraserPopover el={image} />+ <EnhanceButton el={image} /><Divider /><ColorMenu value="#FFFFFF" onChange={() => undefined} title="Filter tint (soon)" /><ToolbarPopover trigger={(open) => (diff --git a/src/components/editor/ResizeDialog.tsx b/src/components/editor/ResizeDialog.tsxindex c0b1a0b..bf1c54f 100644--- a/src/components/editor/ResizeDialog.tsx+++ b/src/components/editor/ResizeDialog.tsx@@ -1,49 +1,49 @@'use client'import { useState } from 'react'-import { Presentation, Instagram, Youtube, FileText, Square, RectangleHorizontal, RectangleVertical, Smartphone } from 'lucide-react'+import { Wand2, Copy, Loader2, Square } from 'lucide-react'import { useEditorStore } from '@/store/editor-store'+import { createDesign } from '@/components/dashboard/hooks'+import { magicRelayoutPages, RESIZE_PRESETS, type ResizePreset } from '@/lib/magic'import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'import { cn } from '@/lib/utils'import { toast } from '@/hooks/use-toast'+import { useAppStore } from '@/store/app-store'-const SIZE_GROUPS: { label: string; sizes: { name: string; w: number; h: number; icon: typeof Square }[] }[] = [- {- label: 'Story & Reels',- sizes: [- { name: 'Instagram Story', w: 1080, h: 1920, icon: Smartphone },- { name: 'YouTube Short', w: 1080, h: 1920, icon: Youtube },- ],- },- {- label: 'Posts',- sizes: [- { name: 'Instagram Post', w: 1080, h: 1080, icon: Square },- { name: 'Landscape Post', w: 1920, h: 1080, icon: RectangleHorizontal },- { name: 'Portrait Post', w: 1080, h: 1350, icon: RectangleVertical },- ],- },- {- label: 'Docs & Decks',- sizes: [- { name: 'Presentation 16:9', w: 1920, h: 1080, icon: Presentation },- { name: 'Document A4', w: 1240, h: 1754, icon: FileText },- ],- },-]+const GROUP_LABELS: Record<ResizePreset['group'], string> = {+ story: 'Story & vertical video',+ post: 'Social posts',+ doc: 'Docs & decks',+ print: 'Print',+}-/** Canva-style Resize dialog — change canvas size; elements stay centered. */+/** Canva Magic Resize dialog — re-layout the current design for any channel,+ * in place or as copies (Magic Switch "Copy & resize"). */export function ResizeDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (v: boolean) => void }) {const width = useEditorStore((s) => s.width)const height = useEditorStore((s) => s.height)+ const pages = useEditorStore((s) => s.pages)+ const designName = useEditorStore((s) => s.designName)+ const designId = useEditorStore((s) => s.designId)const resizeDesign = useEditorStore((s) => s.resizeDesign)const [custom, setCustom] = useState({ w: '', h: '' })+ const [checked, setChecked] = useState<Record<string, boolean>>({})+ const [busy, setBusy] = useState(false)+ const goDashboard = useAppStore((s) => s.goDashboard)++ const groups = (['story', 'post', 'doc', 'print'] as const).map((g) => ({+ label: GROUP_LABELS[g],+ sizes: RESIZE_PRESETS.filter((p) => p.group === g),+ }))+ const selected = RESIZE_PRESETS.filter((p) => checked[p.name])++ const toggle = (name: string) => setChecked((c) => ({ ...c, [name]: !c[name] }))- const apply = (w: number, h: number) => {+ const applyInPlace = (w: number, h: number) => {resizeDesign(w, h)- toast({ title: `Design resized to ${w}×${h}` })+ toast({ title: `Magic-resized to ${w}×${h}`, description: 'Elements re-laid-out to fit the new canvas.' })onOpenChange(false)}@@ -54,39 +54,93 @@ export function ResizeDialog({ open, onOpenChange }: { open: boolean; onOpenChantoast({ title: 'Enter a size between 50 and 8000 px', variant: 'destructive' })return}- apply(w, h)+ applyInPlace(w, h)+ }++ /** Magic Switch: create a resized COPY for every checked channel. */+ const copyAndResize = async () => {+ if (!selected.length || !designId) return+ setBusy(true)+ let made = 0+ try {+ for (const preset of selected) {+ const relaid = magicRelayoutPages(pages, width, height, preset.w, preset.h)+ try {+ await createDesign({+ name: `${designName} (${preset.short})`,+ width: preset.w,+ height: preset.h,+ pages: relaid,+ source: `resize:${designId}`,+ })+ made += 1+ } catch {+ // keep going — partial success is better than aborting+ }+ }+ toast({+ title: made ? `Created ${made} resized cop${made === 1 ? 'y' : 'ies'}` : 'Could not create copies',+ description: made ? 'Find them in your recent designs.' : 'Please try again.',+ })+ if (made) goDashboard()+ onOpenChange(false)+ } finally {+ setBusy(false)+ }}return (<Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="rounded-[28px] bg-[#16181D] border-white/10 text-white sm:max-w-md">+ <DialogContent className="rounded-[28px] bg-[#16181D] border-white/10 text-white sm:max-w-lg"><DialogHeader>- <DialogTitle className="text-lg font-bold">Resize design</DialogTitle>+ <DialogTitle className="text-lg font-bold flex items-center gap-2">+ <Wand2 size={17} className="text-[#02C0CC]" /> Magic Resize+ </DialogTitle><DialogDescription className="text-white/60">- Current size: {width} × {height} px. Your elements stay centered on the new canvas.+ Resize this design for every channel. Pick sizes, then copy & resize — your elements are+ re-laid-out automatically.</DialogDescription></DialogHeader>- <div className="space-y-4 max-h-[55vh] overflow-y-auto cv-scroll pr-1">- {SIZE_GROUPS.map((g) => (+ <div className="space-y-4 max-h-[52vh] overflow-y-auto cv-scroll pr-1">+ {groups.map((g) => (<div key={g.label}><h3 className="text-xs font-semibold text-white/50 uppercase tracking-wide mb-2">{g.label}</h3><div className="grid grid-cols-2 gap-2">- {g.sizes.map((s) => (- <button- key={s.name}- onClick={() => apply(s.w, s.h)}- className="flex items-center gap-2.5 rounded-xl bg-white/5 hover:bg-[#7630D7] border border-white/10 hover:border-transparent px-3 py-2.5 text-left transition-colors group"- >- <s.icon size={18} className="text-white/70 group-hover:text-white shrink-0" />- <span className="min-w-0">- <span className="block text-[13px] font-semibold truncate">{s.name}</span>- <span className="block text-[11px] text-white/50 group-hover:text-white/80">- {s.w} × {s.h}+ {g.sizes.map((s) => {+ const active = checked[s.name]+ const isCurrent = s.w === width && s.h === height+ return (+ <button+ key={s.name}+ onClick={() => toggle(s.name)}+ aria-pressed={active}+ className={cn(+ 'flex items-center gap-2.5 rounded-xl bg-white/5 border border-white/10 px-3 py-2.5 text-left transition-colors group',+ active ? 'bg-[#7630D7] border-transparent' : 'hover:bg-white/10'+ )}+ >+ <span+ className={cn(+ 'w-4 h-4 rounded-[5px] border flex items-center justify-center shrink-0',+ active ? 'border-white bg-white/90' : 'border-white/30'+ )}+ >+ {active && (+ <svg viewBox="0 0 12 12" className="w-3 h-3">+ <path d="M2 6l2.5 2.5L10 3" fill="none" stroke="#7630D7" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />+ </svg>+ )}+ </span>+ <span className="min-w-0">+ <span className="block text-[13px] font-semibold truncate">{s.name}</span>+ <span className={cn('block text-[11px]', active ? 'text-white/85' : 'text-white/50')}>+ {s.w} × {s.h}{isCurrent ? ' · current' : ''}+ </span></span>- </span>- </button>- ))}+ </button>+ )+ })}</div></div>))}@@ -112,14 +166,33 @@ export function ResizeDialog({ open, onOpenChange }: { open: boolean; onOpenChanaria-label="Custom height"/><Button className="btn-cv h-10 px-4 shrink-0" onClick={applyCustom}>- Apply+ Resize</Button></div></div></div>++ {/* footer actions */}+ <div className="flex items-center gap-2 pt-1">+ <Button+ variant="outline"+ className="h-11 flex-1 rounded-xl border-white/15 bg-white/5 hover:bg-white/10 hover:text-white"+ disabled={selected.length !== 1}+ onClick={() => applyInPlace(selected[0].w, selected[0].h)}+ title={selected.length === 1 ? `Resize this design to ${selected[0].w}×${selected[0].h}` : 'Check exactly one size to resize in place'}+ >+ <Square size={15} className="mr-1.5" /> Resize in place+ </Button>+ <Button+ className="btn-cv h-11 flex-1 rounded-xl"+ disabled={!selected.length || busy}+ onClick={() => void copyAndResize()}+ >+ {busy ? <Loader2 size={15} className="mr-1.5 animate-spin" /> : <Copy size={15} className="mr-1.5" />}+ Copy & resize {selected.length > 1 ? `(${selected.length})` : ''}+ </Button>+ </div></DialogContent></Dialog>)}--void Instagramdiff --git a/src/components/editor/TopBar.tsx b/src/components/editor/TopBar.tsxindex 002d949..5d9a516 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 } from 'lucide-react'+import { Home, MessageCircle, Play, Share2, ChevronDown, Undo2, Redo2, Download, Github, Cloud, Check, Loader2, Ruler, History, Languages } from 'lucide-react'import { useAppStore } from '@/store/app-store'import { useEditorStore } from '@/store/editor-store'import { Button } from '@/components/ui/button'@@ -11,6 +11,7 @@ import { ExportDialog } from './ExportDialog'import { ResizeDialog } from './ResizeDialog'import { ShareDialog } from './ShareDialog'import { VersionHistoryDialog } from './VersionHistoryDialog'+import { TranslateDialog } from './TranslateDialog'import { ContextToolbar } from './PropertiesBar'/** Canva-2026 editor topbar: 56px cyan→purple gradient, white text, File/Resize/Editing left, Preview/Share right. */@@ -37,6 +38,7 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; oconst [resizeOpen, setResizeOpen] = useState(false)const [shareOpen, setShareOpen] = useState(false)const [versionsOpen, setVersionsOpen] = useState(false)+ const [translateOpen, setTranslateOpen] = useState(false)const item = 'h-10 px-3 rounded-xl text-white/95 hover:bg-white/15 transition-colors text-sm font-semibold flex items-center gap-1.5 select-none'@@ -71,7 +73,10 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; o<Cloud size={15} /> Save changes</DropdownMenuItem><DropdownMenuItem className="gap-2" onClick={() => setResizeOpen(true)}>- <Play size={15} /> Resize design+ <Play size={15} /> Magic Resize+ </DropdownMenuItem>+ <DropdownMenuItem className="gap-2" onClick={() => setTranslateOpen(true)}>+ <Languages size={15} /> Translate design…</DropdownMenuItem><DropdownMenuItem className="gap-2" onClick={toggleRulers}><Ruler size={15} /> {showRulers ? 'Hide rulers' : 'Show rulers'}@@ -96,9 +101,9 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; o</DropdownMenuContent></DropdownMenu>- {/* Resize */}- <button className={cn(item, 'hidden sm:flex')} onClick={() => setResizeOpen(true)} aria-label="Resize design">- Resize+ {/* Magic Resize */}+ <button className={cn(item, 'hidden sm:flex')} onClick={() => setResizeOpen(true)} aria-label="Magic Resize">+ Magic Resize</button>{/* Editing / Viewing mode */}@@ -170,6 +175,7 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; o<ResizeDialog open={resizeOpen} onOpenChange={setResizeOpen} /><ShareDialog open={shareOpen} onOpenChange={setShareOpen} /><VersionHistoryDialog open={versionsOpen} onOpenChange={setVersionsOpen} />+ <TranslateDialog open={translateOpen} onOpenChange={setTranslateOpen} /></header>)}diff --git a/src/components/editor/TranslateDialog.tsx b/src/components/editor/TranslateDialog.tsxnew file mode 100644index 0000000..90aa8a1--- /dev/null+++ b/src/components/editor/TranslateDialog.tsx@@ -0,0 +1,143 @@+'use client'++import { useMemo, useState } from 'react'+import { Languages, Loader2, Globe, ArrowRight } from 'lucide-react'+import { useEditorStore } from '@/store/editor-store'+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { cn } from '@/lib/utils'+import { toast } from '@/hooks/use-toast'+import type { AnyElement, TextElement } from '@/lib/types'++const LANGUAGES: { name: string; native: string; code: string }[] = [+ { name: 'Spanish', native: 'Español', code: 'es' },+ { name: 'French', native: 'Français', code: 'fr' },+ { name: 'German', native: 'Deutsch', code: 'de' },+ { name: 'Portuguese', native: 'Português', code: 'pt' },+ { name: 'Italian', native: 'Italiano', code: 'it' },+ { name: 'Dutch', native: 'Nederlands', code: 'nl' },+ { name: 'Polish', native: 'Polski', code: 'pl' },+ { name: 'Swedish', native: 'Svenska', code: 'sv' },+ { name: 'Turkish', native: 'Türkçe', code: 'tr' },+ { name: 'Russian', native: 'Русский', code: 'ru' },+ { name: 'Ukrainian', native: 'Українська', code: 'uk' },+ { name: 'Arabic', native: 'العربية', code: 'ar' },+ { name: 'Hebrew', native: 'עברית', code: 'he' },+ { name: 'Hindi', native: 'हिन्दी', code: 'hi' },+ { name: 'Bengali', native: 'বাংলা', code: 'bn' },+ { name: 'Tamil', native: 'தமிழ்', code: 'ta' },+ { name: 'Thai', native: 'ไทย', code: 'th' },+ { name: 'Vietnamese', native: 'Tiếng Việt', code: 'vi' },+ { name: 'Indonesian', native: 'Bahasa Indonesia', code: 'id' },+ { name: 'Chinese (Simplified)', native: '简体中文', code: 'zh' },+ { name: 'Chinese (Traditional)', native: '繁體中文', code: 'zh-TW' },+ { name: 'Japanese', native: '日本語', code: 'ja' },+ { name: 'Korean', native: '한국어', code: 'ko' },+ { name: 'Greek', native: 'Ελληνικά', code: 'el' },+]++/** Collect every text element in the design (top-level + inside groups). */+function collectTexts(els: AnyElement[], out: TextElement[] = []): TextElement[] {+ for (const el of els) {+ if (el.type === 'text') out.push(el)+ else if (el.type === 'group') collectTexts(el.children, out)+ }+ return out+}++/** Canva "Translate" — AI-translate every text element in the design. */+export function TranslateDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (v: boolean) => void }) {+ const pages = useEditorStore((s) => s.pages)+ const translateTexts = useEditorStore((s) => s.translateTexts)+ const [lang, setLang] = useState<string | null>(null)+ const [busy, setBusy] = useState(false)++ const texts = useMemo(() => collectTexts(pages.flatMap((p) => p.elements)), [pages])+ const picked = LANGUAGES.find((l) => l.code === lang) ?? null++ const run = async () => {+ if (!picked || !texts.length || busy) return+ setBusy(true)+ try {+ const res = await fetch('/api/ai/translate', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ language: `${picked.name} (${picked.native})`,+ texts: texts.map((t) => t.text),+ }),+ })+ const data = (await res.json()) as { translations?: string[]; error?: string }+ if (!res.ok || !Array.isArray(data.translations) || data.translations.length !== texts.length) {+ toast({ title: 'Translate failed', description: data.error ?? 'Please try again.', variant: 'destructive' })+ return+ }+ translateTexts(texts.map((t, i) => ({ id: t.id, text: data.translations![i] })))+ toast({ title: `Translated to ${picked.native}`, description: `${texts.length} text${texts.length === 1 ? '' : 's'} updated. Ctrl+Z to undo.` })+ onOpenChange(false)+ } catch {+ toast({ title: 'Translate is unavailable right now.', variant: 'destructive' })+ } finally {+ setBusy(false)+ }+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="rounded-[28px] bg-[#16181D] border-white/10 text-white sm:max-w-md">+ <DialogHeader>+ <DialogTitle className="text-lg font-bold flex items-center gap-2">+ <Languages size={17} className="text-[#02C0CC]" /> Translate design+ </DialogTitle>+ <DialogDescription className="text-white/60">+ {texts.length+ ? `Translate all ${texts.length} text${texts.length === 1 ? '' : 's'} across ${pages.length} page${pages.length === 1 ? '' : 's'} with AI. Your layout stays intact.`+ : 'This design has no text to translate yet.'}+ </DialogDescription>+ </DialogHeader>++ <div className="max-h-[46vh] overflow-y-auto cv-scroll pr-1">+ <div className="grid grid-cols-2 gap-1.5">+ {LANGUAGES.map((l) => {+ const active = lang === l.code+ return (+ <button+ key={l.code}+ onClick={() => setLang(active ? null : l.code)}+ aria-pressed={active}+ className={cn(+ 'flex items-center justify-between gap-2 rounded-xl px-3 py-2.5 border text-left transition-colors',+ active+ ? 'bg-[#7630D7] border-transparent'+ : 'bg-white/5 border-white/10 hover:bg-white/10'+ )}+ >+ <span className="min-w-0">+ <span className="block text-[13px] font-semibold truncate">{l.native}</span>+ <span className={cn('block text-[10.5px] truncate', active ? 'text-white/80' : 'text-white/45')}>{l.name}</span>+ </span>+ {active && <ArrowRight size={13} className="shrink-0 text-white/90" />}+ </button>+ )+ })}+ </div>+ </div>++ <div className="flex items-center gap-2 pt-1">+ <span className="text-[11px] text-white/45 flex items-center gap-1.5 min-w-0">+ <Globe size={12} className="shrink-0" />+ {picked ? `Target: ${picked.native}` : 'Pick a language'}+ </span>+ <Button+ className="btn-cv h-11 rounded-xl ml-auto px-5"+ disabled={!picked || !texts.length || busy}+ onClick={() => void run()}+ >+ {busy ? <Loader2 size={15} className="mr-1.5 animate-spin" /> : <Languages size={15} className="mr-1.5" />}+ {busy ? 'Translating…' : 'Translate'}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ )+}diff --git a/src/components/editor/apps/AssistantApp.tsx b/src/components/editor/apps/AssistantApp.tsxnew file mode 100644index 0000000..4033020--- /dev/null+++ b/src/components/editor/apps/AssistantApp.tsx@@ -0,0 +1,305 @@+'use client'++import { useEffect, useMemo, useRef, useState } from 'react'+import { Bot, Loader2, Plus, Send, Sparkles, User, Palette, Languages, Type, ImageIcon } from 'lucide-react'+import { createImageElement, createTextElement, type AnyElement, type TextElement } from '@/lib/types'+import { useEditorStore } from '@/store/editor-store'+import { AppHeader, type AppPanelProps } from './registry'+import { cn } from '@/lib/utils'+import { toast } from '@/hooks/use-toast'++type AssistantAction =+ | { type: 'addText'; text: string; fontSize?: number; bold?: boolean }+ | { type: 'generateImage'; prompt: string }+ | { type: 'suggestPalette'; colors: string[] }+ | { type: 'translate'; language: string }++interface Turn {+ role: 'user' | 'assistant'+ content: string+ actions?: AssistantAction[]+ done?: { action: string; msg: string }+}++const SUGGESTIONS = [+ 'Write a bold headline for a coffee shop sale',+ 'Suggest a colour palette for a beach party poster',+ 'Give me 3 tagline ideas for a fitness app',+ 'What visual should I generate for a tech launch?',+]++/** Collect text contents for design context (flattens groups). */+function collectTexts(els: AnyElement[], out: TextElement[] = []): TextElement[] {+ for (const el of els) {+ if (el.type === 'text') out.push(el)+ else if (el.type === 'group') collectTexts(el.children, out)+ }+ return out+}++const ACTION_META: Record<AssistantAction['type'], { icon: typeof Plus; label: (a: never) => string }> = {+ addText: { icon: Type, label: (a: AssistantAction & { type: 'addText' }) => `Add text: "${a.text.slice(0, 42)}${a.text.length > 42 ? '…' : ''}"` },+ generateImage: { icon: ImageIcon, label: (a: AssistantAction & { type: 'generateImage' }) => `Generate image: ${a.prompt.slice(0, 48)}${a.prompt.length > 48 ? '…' : ''}` },+ suggestPalette: { icon: Palette, label: (a: AssistantAction & { type: 'suggestPalette' }) => `Use these colours` },+ translate: { icon: Languages, label: (a: AssistantAction & { type: 'translate' }) => `Translate design to ${a.language}` },+}++export function AssistantApp({ onClose }: AppPanelProps) {+ const store = useEditorStore()+ const [turns, setTurns] = useState<Turn[]>([])+ const [input, setInput] = useState('')+ const [busy, setBusy] = useState(false)+ const scrollRef = useRef<HTMLDivElement>(null)++ useEffect(() => {+ scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' })+ }, [turns, busy])++ const send = async (message: string) => {+ const text = message.trim()+ if (!text || busy) return+ setInput('')+ const history = turns.slice(-8).map((t) => ({ role: t.role, content: t.content }))+ setTurns((ts) => [...ts, { role: 'user', content: text }])+ setBusy(true)+ try {+ const texts = collectTexts(store.pages.flatMap((p) => p.elements))+ const res = await fetch('/api/ai/assistant', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ message: text,+ history,+ design: {+ name: store.designName,+ width: store.width,+ height: store.height,+ pageCount: store.pages.length,+ currentPageElements: store.pages[store.currentPage]?.elements.length ?? 0,+ textContents: texts.map((t) => t.text).slice(0, 40),+ },+ }),+ })+ const data = (await res.json()) as { reply?: string; actions?: AssistantAction[]; error?: string }+ if (!res.ok || !data.reply) throw new Error(data.error ?? 'The assistant could not answer.')+ setTurns((ts) => [...ts, { role: 'assistant', content: data.reply!, actions: data.actions ?? [] }])+ } catch (e) {+ setTurns((ts) => [...ts, { role: 'assistant', content: e instanceof Error ? e.message : 'Something went wrong.' }])+ } finally {+ setBusy(false)+ }+ }++ /** run an attached action; mark it done on its turn */+ const runAction = async (turnIndex: number, action: AssistantAction) => {+ const { pages, designName, designId, width, height } = store+ let msg = ''+ if (action.type === 'addText') {+ const el = createTextElement({+ text: action.text,+ fontSize: action.fontSize ?? (action.bold ? 72 : 42),+ bold: action.bold ?? false,+ x: width * 0.1,+ y: height * 0.4,+ width: width * 0.8,+ align: 'center',+ })+ store.addElement(el)+ msg = 'Text added to the canvas'+ } else if (action.type === 'generateImage') {+ msg = 'Image generated and added'+ try {+ const res = await fetch('/api/ai/image', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ prompt: action.prompt }),+ })+ const data = (await res.json()) as { dataUrl?: string; width?: number; height?: number; error?: string }+ if (!res.ok || !data.dataUrl) throw new Error(data.error ?? 'Generation failed')+ const iw = data.width ?? 1024+ const ih = data.height ?? 1024+ const scale = Math.min((width * 0.7) / iw, (height * 0.7) / ih, 1)+ store.addElement(+ createImageElement(data.dataUrl, iw, ih, {+ x: (width - iw * scale) / 2,+ y: (height - ih * scale) / 2,+ width: Math.round(iw * scale),+ height: Math.round(ih * scale),+ })+ )+ } catch (e) {+ msg = e instanceof Error ? e.message : 'Image generation failed'+ }+ } else if (action.type === 'suggestPalette') {+ // apply as the page's Brand Kit palette + toast+ const brand = { ...store.brand, palettes: [action.colors, ...(store.brand.palettes ?? [])].slice(0, 4) }+ store.setBrand(brand)+ msg = 'Palette saved to your Brand Kit'+ } else if (action.type === 'translate') {+ const texts = collectTexts(pages.flatMap((p) => p.elements))+ if (!texts.length) {+ msg = 'No text to translate'+ } else {+ msg = `Translated ${texts.length} text${texts.length === 1 ? '' : 's'} to ${action.language}`+ try {+ const res = await fetch('/api/ai/translate', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ language: action.language, texts: texts.map((t) => t.text) }),+ })+ const data = (await res.json()) as { translations?: string[]; error?: string }+ if (!res.ok || !Array.isArray(data.translations) || data.translations.length !== texts.length) {+ throw new Error(data.error ?? 'Translation failed')+ }+ store.translateTexts(texts.map((t, i) => ({ id: t.id, text: data.translations![i] })))+ } catch (e) {+ msg = e instanceof Error ? e.message : 'Translation failed'+ }+ }+ }+ toast({ title: 'Canvix AI', description: msg })+ setTurns((ts) => ts.map((t, i) => (i === turnIndex ? { ...t, done: { action: action.type, msg } } : t)))+ }++ const empty = turns.length === 0 && !busy++ return (+ <div className="flex flex-col">+ <AppHeader icon={Bot} title="Canvix AI assistant" onClose={onClose} />++ {/* chat log */}+ <div ref={scrollRef} className="h-[340px] overflow-y-auto cv-scroll rounded-xl border border-white/10 bg-white/[0.03] p-2.5 space-y-2.5 mb-2.5">+ {empty && (+ <div className="h-full flex flex-col items-center justify-center gap-3 text-center px-3">+ <div className="w-11 h-11 rounded-2xl bg-gradient-to-br from-[#7630D7] to-[#02C0CC] flex items-center justify-center shadow-lg">+ <Sparkles size={20} className="text-white" />+ </div>+ <p className="text-[13px] font-bold text-white">Your creative copilot</p>+ <p className="text-[11px] text-white/50 leading-snug">+ Ask for headline ideas, colour palettes, taglines — or let it generate images and+ translate the whole design. It sees your current design.+ </p>+ </div>+ )}++ {turns.map((t, i) => (+ <div key={i} className={cn('flex gap-2', t.role === 'user' && 'flex-row-reverse')}>+ <div+ className={cn(+ 'w-6 h-6 rounded-lg flex items-center justify-center shrink-0 mt-0.5',+ t.role === 'user' ? 'bg-white/12 text-white/80' : 'bg-gradient-to-br from-[#7630D7] to-[#9B6BFF] text-white'+ )}+ aria-hidden+ >+ {t.role === 'user' ? <User size={12} /> : <Bot size={12} />}+ </div>+ <div className="min-w-0 max-w-[85%]">+ <div+ className={cn(+ 'rounded-2xl px-3 py-2 text-[12px] leading-relaxed whitespace-pre-wrap',+ t.role === 'user' ? 'bg-[#7630D7] text-white rounded-tr-sm' : 'bg-white/[0.07] text-white/90 rounded-tl-sm border border-white/[0.06]'+ )}+ >+ {t.content}+ </div>++ {/* action chips */}+ {t.actions && t.actions.length > 0 && (+ <div className="mt-1.5 space-y-1">+ {t.actions.map((a, j) => {+ const meta = ACTION_META[a.type]+ const done = t.done?.action === a.type+ const Icon = meta.icon+ return (+ <button+ key={j}+ disabled={done}+ onClick={() => void runAction(i, a)}+ className={cn(+ 'w-full flex items-center gap-2 rounded-xl border px-2.5 py-2 text-left text-[11px] font-semibold transition-colors',+ done+ ? 'border-[#02C0CC]/30 bg-[#02C0CC]/10 text-[#7BE8EC]'+ : 'border-[#7630D7]/40 bg-[#7630D7]/15 text-white hover:bg-[#7630D7]/30'+ )}+ >+ <Icon size={13} className="shrink-0" />+ <span className="min-w-0 truncate">{done ? t.done?.msg : meta.label(a as never)}</span>+ {!done && <Plus size={11} className="ml-auto shrink-0" />}+ </button>+ )+ })}+ {a_chipSwatches(t)}+ </div>+ )}+ </div>+ </div>+ ))}++ {busy && (+ <div className="flex gap-2">+ <div className="w-6 h-6 rounded-lg bg-gradient-to-br from-[#7630D7] to-[#9B6BFF] flex items-center justify-center shrink-0 mt-0.5">+ <Bot size={12} className="text-white" />+ </div>+ <div className="rounded-2xl rounded-tl-sm bg-white/[0.07] border border-white/[0.06] px-3 py-2.5 flex items-center gap-1.5">+ <span className="w-1.5 h-1.5 rounded-full bg-white/60 animate-bounce" style={{ animationDelay: '0ms' }} />+ <span className="w-1.5 h-1.5 rounded-full bg-white/60 animate-bounce" style={{ animationDelay: '120ms' }} />+ <span className="w-1.5 h-1.5 rounded-full bg-white/60 animate-bounce" style={{ animationDelay: '240ms' }} />+ </div>+ </div>+ )}+ </div>++ {/* suggestions */}+ {empty && (+ <div className="space-y-1 mb-2.5">+ {SUGGESTIONS.map((s) => (+ <button+ key={s}+ onClick={() => void send(s)}+ className="block w-full text-left text-[11px] text-white/55 hover:text-white rounded-lg border border-white/[0.07] hover:border-white/20 px-2.5 py-1.5 transition-colors"+ >+ “{s}”+ </button>+ ))}+ </div>+ )}++ {/* input */}+ <div className="flex gap-1.5">+ <div className="flex-1 rounded-xl border border-white/10 bg-white/[0.04] focus-within:border-[#7630D7] transition-colors px-3 flex items-center">+ <input+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onKeyDown={(e) => e.key === 'Enter' && void send(input)}+ placeholder="Ask your copilot…"+ maxLength={800}+ className="w-full bg-transparent outline-none text-[12.5px] text-white placeholder:text-white/35 h-10"+ aria-label="Message the Canvix AI assistant"+ />+ </div>+ <button+ onClick={() => void send(input)}+ disabled={busy || !input.trim()}+ className="w-10 h-10 rounded-xl bg-gradient-to-r from-[#7630D7] to-[#9B6BFF] text-white flex items-center justify-center disabled:opacity-40 hover:brightness-110 transition-all shrink-0"+ aria-label="Send message"+ >+ {busy ? <Loader2 size={14} className="animate-spin" /> : <Send size={14} />}+ </button>+ </div>+ </div>+ )+}++/** inline palette preview for suggestPalette actions */+function a_chipSwatches(turn: Turn) {+ const palette = turn.actions?.find((a) => a.type === 'suggestPalette') as { colors: string[] } | undefined+ if (!palette) return null+ const done = turn.done?.action === 'suggestPalette'+ return (+ <div className="flex gap-1 pt-0.5" aria-hidden={done}>+ {palette.colors.map((c) => (+ <span key={c} className="flex-1 h-4 rounded-md border border-white/15" style={{ background: c }} title={c} />+ ))}+ </div>+ )+}diff --git a/src/components/editor/apps/registry.tsx b/src/components/editor/apps/registry.tsxindex 32c192e..259ce63 100644--- a/src/components/editor/apps/registry.tsx+++ b/src/components/editor/apps/registry.tsx@@ -1,6 +1,6 @@'use client'-import { BarChart3, QrCode, Smile, Shapes, Palette, Type, Wand2, ImageIcon } from 'lucide-react'+import { BarChart3, QrCode, Smile, Shapes, Palette, Type, Wand2, ImageIcon, Bot } from 'lucide-react'import type { LucideIcon } from 'lucide-react'/** ── Canvix app registry ─────────────────────────────────────@@ -32,9 +32,11 @@ import { LoremApp } from './LoremApp'import { StickersApp } from './StickersApp'import { MagicWriteApp } from './MagicWriteApp'import { AIImageApp } from './AIImageApp'+import { AssistantApp } from './AssistantApp'export const CANVIX_APPS: CanvixApp[] = [// AI apps first (canva 2026: “Canva AI” is the flagship surface)+ { id: 'assistant', name: 'Canvix AI', desc: 'Chat copilot — copy, palettes, images, translate', icon: Bot, color: '#7630D7', content: AssistantApp },{ id: 'magic-write', name: 'Magic Write', desc: 'AI copy — headlines, taglines & captions', icon: Wand2, color: '#9B6BFF', content: MagicWriteApp },{ id: 'ai-image', name: 'AI image generator', desc: 'Turn a prompt into a design-ready image', icon: ImageIcon, color: '#02C0CC', content: AIImageApp },{ id: 'charts', name: 'Charts', desc: 'Bar, line & donut charts as editable shapes', icon: BarChart3, color: '#7630D7', content: ChartsApp },diff --git a/src/components/editor/panels/PhotosPanel.tsx b/src/components/editor/panels/PhotosPanel.tsxindex 026b44c..5d3c2ab 100644--- a/src/components/editor/panels/PhotosPanel.tsx+++ b/src/components/editor/panels/PhotosPanel.tsx@@ -1,7 +1,7 @@'use client'-import { useMemo, useState } from 'react'-import { Plus, ImageDown } from 'lucide-react'+import { useEffect, useMemo, useRef, useState } from 'react'+import { Plus, ImageDown, Loader2, Globe } from 'lucide-react'import { PanelShell } from './panel-shell'import { addImageFromSrc } from '../add-element'import { cn } from '@/lib/utils'@@ -14,6 +14,15 @@ interface StockPhoto {tags: string[]}+/** web search result — real photos from the z-ai image search service */+interface WebPhoto {+ url: string+ caption: string+ source: string+ width: number+ height: number+}+const CATEGORIES = [{ id: 'all', label: 'All photos' },{ id: 'nature', label: 'Nature' },@@ -48,6 +57,42 @@ export function PhotosPanel() {// resilient to not-yet-bundled photos: broken tiles hide themselvesconst [hidden, setHidden] = useState<Record<string, boolean>>({})+ // v0.4: live web search (debounced)+ const [webResults, setWebResults] = useState<WebPhoto[] | null>(null)+ const [webBusy, setWebBusy] = useState(false)+ const lastQuery = useRef('')++ useEffect(() => {+ const q = query.trim()+ const run = async () => {+ if (q.length < 2) {+ setWebResults(null)+ return+ }+ setWebBusy(true)+ try {+ const res = await fetch('/api/photos/search', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ query: q, count: 24 }),+ })+ const data = (await res.json()) as { results?: WebPhoto[] }+ setWebResults(res.ok && Array.isArray(data.results) ? data.results : [])+ } catch {+ setWebResults([])+ } finally {+ setWebBusy(false)+ }+ }+ const t = setTimeout(() => {+ if (q !== lastQuery.current) {+ lastQuery.current = q+ void run()+ }+ }, 600)+ return () => clearTimeout(t)+ }, [query])+const photos = useMemo(() => {const q = query.trim().toLowerCase()return PHOTOS.filter((p) => {@@ -65,11 +110,20 @@ export function PhotosPanel() {toast({ title: 'Photo added' })}+ const addWeb = (p: WebPhoto) => {+ const w = p.width || 1200+ const h = p.height || 800+ addImageFromSrc(p.url, w, h)+ toast({ title: 'Photo added', description: p.source ? `From ${p.source}` : undefined })+ }++ const showWeb = query.trim().length >= 2 && (webResults !== null || webBusy)+return (<PanelShelltitle="Photos"- subtitle="Free stock library — search or browse"- searchPlaceholder="Search photos (e.g. nature, coffee, beach)"+ subtitle="Search millions of photos or browse the free library"+ searchPlaceholder="Search photos (e.g. mountain, coffee, beach)"onSearch={setQuery}belowSearch={<div className="flex gap-1.5 flex-wrap mt-2.5">@@ -91,13 +145,53 @@ export function PhotosPanel() {</div>}>- {photos.length === 0 ? (- <div className="py-16 text-center">- <ImageDown size={28} className="mx-auto text-white/25 mb-3" />- <p className="text-[13px] text-white/50 font-medium">No photos match “{query}”</p>- <p className="text-[11.5px] text-white/35 mt-1">Try a different keyword or category.</p>+ {/* ── live web results (canva-style photo search) ── */}+ {showWeb && (+ <div className="mb-4">+ <div className="flex items-center gap-1.5 mb-2">+ <Globe size={12} className="text-[#02C0CC]" />+ <span className="text-[10.5px] font-bold text-white/55 uppercase tracking-wide">+ Web results {webResults ? `(${webResults.length})` : ''}+ </span>+ {webBusy && <Loader2 size={11} className="animate-spin text-white/40 ml-1" />}+ </div>+ {webResults && webResults.length === 0 && !webBusy ? (+ <p className="text-[11.5px] text-white/40 py-2">No web photos matched — try other keywords.</p>+ ) : (+ <div className="grid grid-cols-2 gap-2.5">+ {(webResults ?? []).map((p) => (+ <button+ key={p.url}+ onClick={() => addWeb(p)}+ className="group relative aspect-[7/5] rounded-xl overflow-hidden border border-white/10 hover:border-[#7630D7] transition-colors bg-[#0F1015]"+ aria-label={`Add web photo ${p.caption || 'result'}`}+ title={p.caption}+ >+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img+ src={p.url}+ alt={p.caption || 'web photo'}+ loading="lazy"+ className="absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-300"+ />+ <span className="absolute inset-0 bg-black/0 group-hover:bg-black/25 transition-colors" />+ <span className="absolute inset-0 hidden group-hover:flex items-center justify-center">+ <span className="h-8 px-3 rounded-full bg-[#7630D7] text-white text-[11.5px] font-bold flex items-center gap-1.5 shadow-lg">+ <Plus size={12} /> Add+ </span>+ </span>+ </button>+ ))}+ {webBusy && Array.from({ length: 4 }).map((_, i) => (+ <div key={i} className="aspect-[7/5] rounded-xl cv-skeleton" />+ ))}+ </div>+ )}</div>- ) : (+ )}++ {/* ── bundled library ── */}+ {photos.length > 0 && (<div className="grid grid-cols-2 gap-2.5">{photos.map((p) => (<button@@ -127,8 +221,17 @@ export function PhotosPanel() {</div>)}+ {photos.length === 0 && !showWeb && (+ <div className="py-16 text-center">+ <ImageDown size={28} className="mx-auto text-white/25 mb-3" />+ <p className="text-[13px] text-white/50 font-medium">No photos match “{query}”</p>+ <p className="text-[11.5px] text-white/35 mt-1">Try a different keyword or category.</p>+ </div>+ )}+<p className="text-[10.5px] text-white/30 mt-3 leading-relaxed">- All photos are AI-generated for Canvix and free to use in your designs.+ Web results come from a live image search; bundled photos are AI-generated for Canvix. Check+ photo licenses before commercial use of web results.</p></PanelShell>)diff --git a/src/lib/magic.ts b/src/lib/magic.tsnew file mode 100644index 0000000..8c23885--- /dev/null+++ b/src/lib/magic.ts@@ -0,0 +1,123 @@+// ─────────────────────────────────────────────────────────────+// Canvix "Magic" engine — pure functions for Magic Resize+// (Canva Magic Switch: resize one design into many channels)+// ─────────────────────────────────────────────────────────────+import type { AnyElement, GroupElement, PageData, ImageElement } from './types'++export interface ResizePreset {+ name: string+ short: string+ w: number+ h: number+ group: 'story' | 'post' | 'doc' | 'print'+}++/** Canva Magic-Resize channel presets (2026 set). */+export const RESIZE_PRESETS: ResizePreset[] = [+ { name: 'Instagram Story', short: 'Story', w: 1080, h: 1920, group: 'story' },+ { name: 'YouTube Short', short: 'Short', w: 1080, h: 1920, group: 'story' },+ { name: 'TikTok', short: 'TikTok', w: 1080, h: 1920, group: 'story' },+ { name: 'Instagram Post', short: 'Post', w: 1080, h: 1080, group: 'post' },+ { name: 'Instagram Portrait', short: 'Portrait', w: 1080, h: 1350, group: 'post' },+ { name: 'Facebook Post', short: 'Facebook', w: 1200, h: 630, group: 'post' },+ { name: 'X / Twitter Post', short: 'X post', w: 1600, h: 900, group: 'post' },+ { name: 'Presentation 16:9', short: 'Deck', w: 1920, h: 1080, group: 'doc' },+ { name: 'A4 Document', short: 'A4', w: 1240, h: 1754, group: 'doc' },+ { name: 'Poster A3', short: 'Poster', w: 1587, h: 2245, group: 'print' },+ { name: 'Business Card', short: 'Card', w: 1050, h: 600, group: 'print' },+ { name: 'YouTube Thumbnail', short: 'Thumb', w: 1280, h: 720, group: 'post' },+]++const relCenter = (pos: number, size: number, oldTotal: number) => (pos + size / 2) / oldTotal++/** Re-layout a single element for a new canvas size. */+export function magicRelayoutElement<T extends AnyElement>(el: T, oldW: number, oldH: number, newW: number, newH: number): T {+ const s = Math.min(newW / oldW, newH / oldH)+ const next: AnyElement = { ...el }++ // size scales by the conservative factor+ next.width = Math.max(4, Math.round(el.width * s))+ next.height = Math.max(4, Math.round(el.height * s))++ // position: preserve the element's RELATIVE centre on the page —+ // same-aspect resizes behave like a plain scale, orientation flips+ // keep content anchored at its relative position instead of overflowing.+ const cx = relCenter(el.x, el.width, oldW)+ const cy = relCenter(el.y, el.height, oldH)+ next.x = Math.round(cx * newW - next.width / 2)+ next.y = Math.round(cy * newH - next.height / 2)++ switch (el.type) {+ case 'text':+ case 'sticker': {+ const t = el as { fontSize: number; letterSpacing?: number }+ const scaled = next as { fontSize: number; letterSpacing?: number }+ scaled.fontSize = Math.max(6, Math.round(t.fontSize * s))+ if (el.type === 'text') scaled.letterSpacing = Math.round((t.letterSpacing ?? 0) * s)+ break+ }+ case 'rect':+ case 'ellipse':+ case 'triangle':+ case 'star':+ case 'path': {+ const sh = el as { strokeWidth: number; cornerRadius: number }+ const scaled = next as { strokeWidth: number; cornerRadius: number }+ scaled.strokeWidth = Math.max(0, Math.round(sh.strokeWidth * s * 100) / 100)+ scaled.cornerRadius = Math.max(0, Math.round(sh.cornerRadius * s))+ break+ }+ case 'line': {+ const ln = el as { strokeWidth: number }+ const scaled = next as { strokeWidth: number }+ scaled.strokeWidth = Math.max(0.5, Math.round(ln.strokeWidth * s * 100) / 100)+ next.height = 0+ break+ }+ case 'stroke': {+ const st = el as { strokeWidth: number; points: number[] }+ const scaled = next as { strokeWidth: number; points: number[] }+ scaled.strokeWidth = Math.max(0.5, Math.round(st.strokeWidth * s * 100) / 100)+ const pts = st.points ?? []+ const out: number[] = []+ for (let i = 0; i < pts.length; i += 2) {+ out.push(Math.round(pts[i] * s), Math.round(pts[i + 1] * s))+ }+ scaled.points = out+ break+ }+ case 'group': {+ const g = el as GroupElement+ // children are stored in page coords — relayout each, then rebuild the bbox+ const children = g.children.map((c) => magicRelayoutElement(c, oldW, oldH, newW, newH))+ const x1 = Math.min(...children.map((c) => c.x))+ const y1 = Math.min(...children.map((c) => c.y))+ const x2 = Math.max(...children.map((c) => c.x + c.width))+ const y2 = Math.max(...children.map((c) => c.y + c.height))+ ;(next as GroupElement).children = children+ next.x = x1+ next.y = y1+ next.width = Math.max(4, x2 - x1)+ next.height = Math.max(4, y2 - y1)+ break+ }+ case 'image': {+ // keep aspect from natural size after box scaling+ const im = el as ImageElement+ const ratio = im.naturalHeight / Math.max(1, im.naturalWidth)+ next.height = Math.max(4, Math.round(next.width * ratio))+ break+ }+ default:+ break+ }+ return next as T+}++/** Re-layout every page of a design for a new canvas size. */+export function magicRelayoutPages(pages: PageData[], oldW: number, oldH: number, newW: number, newH: number): PageData[] {+ return pages.map((p) => ({+ ...p,+ elements: p.elements.map((el) => magicRelayoutElement(el, oldW, oldH, newW, newH)),+ }))+}diff --git a/src/lib/templates.ts b/src/lib/templates.tsindex ec1f066..fc7d81d 100644--- a/src/lib/templates.ts+++ b/src/lib/templates.ts@@ -454,6 +454,196 @@ export const TEMPLATES: TemplateDef[] = [},],},++ // ── Documents & office (v0.4 — canva.com/templates categories) ──+ {+ slug: 'minimal-resume',+ name: 'Minimal Resume',+ category: 'document',+ width: 1240,+ height: 1754,+ accent: '#1F2937',+ pages: [+ {+ id: 'p1',+ background: { type: 'solid', color: '#FFFFFF' },+ elements: [+ // sidebar+ sh('rect', { x: 0, y: 0, width: 420, height: 1754, fill: '#1F2937' }),+ tx({ x: 60, y: 120, width: 300, height: 70, text: 'ALEX MORGAN', fontFamily: 'Archivo', bold: true, fontSize: 40, fill: '#FFFFFF', align: 'left', letterSpacing: 2 }),+ tx({ x: 60, y: 200, width: 300, height: 50, text: 'Product Designer', fontFamily: 'Inter', fontSize: 22, fill: '#9CA3AF', align: 'left' }),+ ln({ x: 60, y: 300, width: 80, height: 0, stroke: '#02C0CC', strokeWidth: 4 }),+ tx({ x: 60, y: 340, width: 300, height: 40, text: 'CONTACT', fontFamily: 'Inter', bold: true, fontSize: 16, fill: '#02C0CC', align: 'left', letterSpacing: 3 }),+ tx({ x: 60, y: 390, width: 300, height: 160, text: '[email protected]\n+1 555 0100\nBrooklyn, NY', fontFamily: 'Inter', fontSize: 17, fill: '#D1D5DB', align: 'left', lineHeight: 1.7 }),+ tx({ x: 60, y: 620, width: 300, height: 40, text: 'SKILLS', fontFamily: 'Inter', bold: true, fontSize: 16, fill: '#02C0CC', align: 'left', letterSpacing: 3 }),+ tx({ x: 60, y: 670, width: 300, height: 260, text: 'UI / UX Design\nDesign Systems\nPrototyping\nFigma\nUser Research\nMotion Design', fontFamily: 'Inter', fontSize: 17, fill: '#D1D5DB', align: 'left', lineHeight: 1.9 }),+ // main column+ tx({ x: 480, y: 120, width: 700, height: 50, text: 'EXPERIENCE', fontFamily: 'Archivo', bold: true, fontSize: 26, fill: '#1F2937', align: 'left' }),+ tx({ x: 480, y: 190, width: 700, height: 40, text: 'Senior Product Designer — Nova Labs', fontFamily: 'Inter', bold: true, fontSize: 19, fill: '#111827', align: 'left' }),+ tx({ x: 480, y: 230, width: 700, height: 30, text: '2022 – present', fontFamily: 'Inter', fontSize: 15, fill: '#6B7280', align: 'left' }),+ tx({ x: 480, y: 270, width: 700, height: 110, text: 'Led the redesign of the flagship analytics suite; shipped a design system used by 40+ engineers.', fontFamily: 'Inter', fontSize: 16, fill: '#374151', align: 'left', lineHeight: 1.6 }),+ tx({ x: 480, y: 420, width: 700, height: 40, text: 'Product Designer — Loop', fontFamily: 'Inter', bold: true, fontSize: 19, fill: '#111827', align: 'left' }),+ tx({ x: 480, y: 460, width: 700, height: 30, text: '2019 – 2022', fontFamily: 'Inter', fontSize: 15, fill: '#6B7280', align: 'left' }),+ tx({ x: 480, y: 500, width: 700, height: 110, text: 'Owned onboarding flows end-to-end; lifted activation by 24% through iterative testing.', fontFamily: 'Inter', fontSize: 16, fill: '#374151', align: 'left', lineHeight: 1.6 }),+ tx({ x: 480, y: 680, width: 700, height: 50, text: 'EDUCATION', fontFamily: 'Archivo', bold: true, fontSize: 26, fill: '#1F2937', align: 'left' }),+ tx({ x: 480, y: 750, width: 700, height: 90, text: 'B.A. Interaction Design\nRhode Island School of Design · 2019', fontFamily: 'Inter', fontSize: 16, fill: '#374151', align: 'left', lineHeight: 1.7 }),+ ],+ },+ ],+ },+ {+ slug: 'elegant-certificate',+ name: 'Certificate of Achievement',+ category: 'document',+ width: 1754,+ height: 1240,+ accent: '#C9A24B',+ pages: [+ {+ id: 'p1',+ background: { type: 'solid', color: '#FBF7EF' },+ elements: [+ // ornamental double border+ sh('rect', { x: 50, y: 50, width: 1654, height: 1140, fill: 'transparent', stroke: '#C9A24B', strokeWidth: 8, cornerRadius: 0 }),+ sh('rect', { x: 80, y: 80, width: 1594, height: 1080, fill: 'transparent', stroke: '#C9A24B', strokeWidth: 2, cornerRadius: 0 }),+ gr('badge', { x: 777, y: 150, width: 200, height: 200, fill: '#C9A24B' }),+ tx({ x: 277, y: 400, width: 1200, height: 90, text: 'CERTIFICATE', fontFamily: 'Cinzel', bold: true, fontSize: 72, fill: '#1F2937', align: 'center', letterSpacing: 12 }),+ tx({ x: 277, y: 490, width: 1200, height: 60, text: 'OF ACHIEVEMENT', fontFamily: 'Cinzel', fontSize: 36, fill: '#6B7280', align: 'center', letterSpacing: 10 }),+ tx({ x: 377, y: 610, width: 1000, height: 50, text: 'This certificate is proudly presented to', fontFamily: 'Cormorant Garamond', italic: true, fontSize: 30, fill: '#6B7280', align: 'center' }),+ tx({ x: 277, y: 680, width: 1200, height: 100, text: 'Jordan Reyes', fontFamily: 'Great Vibes', fontSize: 84, fill: '#8E2A3C', align: 'center' }),+ ln({ x: 657, y: 810, width: 440, height: 0, stroke: '#C9A24B', strokeWidth: 3 }),+ tx({ x: 377, y: 850, width: 1000, height: 90, text: 'for outstanding performance and dedication\nin the Design Excellence Program', fontFamily: 'Cormorant Garamond', fontSize: 28, fill: '#374151', align: 'center', lineHeight: 1.6 }),+ tx({ x: 400, y: 1040, width: 360, height: 40, text: '____________________', fontFamily: 'Inter', fontSize: 24, fill: '#6B7280', align: 'center' }),+ tx({ x: 400, y: 1080, width: 360, height: 30, text: 'Program Director', fontFamily: 'Inter', bold: true, fontSize: 16, fill: '#6B7280', align: 'center', letterSpacing: 2 }),+ tx({ x: 994, y: 1040, width: 360, height: 40, text: '____________________', fontFamily: 'Inter', fontSize: 24, fill: '#6B7280', align: 'center' }),+ tx({ x: 994, y: 1080, width: 360, height: 30, text: 'Date', fontFamily: 'Inter', bold: true, fontSize: 16, fill: '#6B7280', align: 'center', letterSpacing: 2 }),+ ],+ },+ ],+ },+ {+ slug: 'clean-invoice',+ name: 'Clean Invoice',+ category: 'document',+ width: 1240,+ height: 1754,+ accent: '#0EA5E9',+ pages: [+ {+ id: 'p1',+ background: { type: 'solid', color: '#FFFFFF' },+ elements: [+ sh('rect', { x: 0, y: 0, width: 1240, height: 20, fill: '#0EA5E9' }),+ tx({ x: 70, y: 80, width: 500, height: 70, text: 'INVOICE', fontFamily: 'Archivo', bold: true, fontSize: 52, fill: '#0F172A', align: 'left', letterSpacing: 4 }),+ tx({ x: 70, y: 160, width: 500, height: 40, text: '# INV-2026-014', fontFamily: 'DM Mono', fontSize: 22, fill: '#64748B', align: 'left' }),+ tx({ x: 770, y: 90, width: 400, height: 120, text: 'Studio Canvix\n42 Design Lane\[email protected]', fontFamily: 'Inter', fontSize: 16, fill: '#334155', align: 'right', lineHeight: 1.6 }),+ ln({ x: 70, y: 260, width: 1100, height: 0, stroke: '#E2E8F0', strokeWidth: 2 }),+ tx({ x: 70, y: 300, width: 250, height: 30, text: 'BILLED TO', fontFamily: 'Inter', bold: true, fontSize: 14, fill: '#94A3B8', align: 'left', letterSpacing: 2 }),+ tx({ x: 70, y: 335, width: 400, height: 100, text: 'Acme Corporation\n200 Sunrise Blvd\nAustin, TX', fontFamily: 'Inter', fontSize: 16, fill: '#334155', align: 'left', lineHeight: 1.6 }),+ tx({ x: 820, y: 300, width: 350, height: 30, text: 'DUE DATE', fontFamily: 'Inter', bold: true, fontSize: 14, fill: '#94A3B8', align: 'left', letterSpacing: 2 }),+ tx({ x: 820, y: 335, width: 350, height: 40, text: 'March 31, 2026', fontFamily: 'Inter', bold: true, fontSize: 20, fill: '#0F172A', align: 'left' }),+ // line items header+ sh('rect', { x: 70, y: 470, width: 1100, height: 56, fill: '#F1F5F9', cornerRadius: 8 }),+ tx({ x: 90, y: 487, width: 500, height: 30, text: 'DESCRIPTION', fontFamily: 'Inter', bold: true, fontSize: 13, fill: '#64748B', align: 'left', letterSpacing: 2 }),+ tx({ x: 640, y: 487, width: 150, height: 30, text: 'QTY', fontFamily: 'Inter', bold: true, fontSize: 13, fill: '#64748B', align: 'center', letterSpacing: 2 }),+ tx({ x: 850, y: 487, width: 300, height: 30, text: 'AMOUNT', fontFamily: 'Inter', bold: true, fontSize: 13, fill: '#64748B', align: 'right', letterSpacing: 2 }),+ tx({ x: 90, y: 560, width: 500, height: 36, text: 'Brand identity design', fontFamily: 'Inter', fontSize: 17, fill: '#0F172A', align: 'left' }),+ tx({ x: 640, y: 560, width: 150, height: 36, text: '1', fontFamily: 'Inter', fontSize: 17, fill: '#334155', align: 'center' }),+ tx({ x: 850, y: 560, width: 300, height: 36, text: '$2,400', fontFamily: 'DM Mono', fontSize: 17, fill: '#0F172A', align: 'right' }),+ tx({ x: 90, y: 620, width: 500, height: 36, text: 'Landing page design', fontFamily: 'Inter', fontSize: 17, fill: '#0F172A', align: 'left' }),+ tx({ x: 640, y: 620, width: 150, height: 36, text: '1', fontFamily: 'Inter', fontSize: 17, fill: '#334155', align: 'center' }),+ tx({ x: 850, y: 620, width: 300, height: 36, text: '$1,800', fontFamily: 'DM Mono', fontSize: 17, fill: '#0F172A', align: 'right' }),+ ln({ x: 70, y: 700, width: 1100, height: 0, stroke: '#E2E8F0', strokeWidth: 2 }),+ tx({ x: 850, y: 730, width: 300, height: 36, text: 'Subtotal', fontFamily: 'Inter', fontSize: 17, fill: '#64748B', align: 'right' }),+ tx({ x: 850, y: 766, width: 300, height: 36, text: '$4,200', fontFamily: 'DM Mono', fontSize: 17, fill: '#0F172A', align: 'right' }),+ tx({ x: 850, y: 802, width: 300, height: 36, text: 'Tax (8%)', fontFamily: 'Inter', fontSize: 17, fill: '#64748B', align: 'right' }),+ tx({ x: 850, y: 838, width: 300, height: 36, text: '$336', fontFamily: 'DM Mono', fontSize: 17, fill: '#0F172A', align: 'right' }),+ sh('rect', { x: 790, y: 900, width: 380, height: 70, fill: '#0EA5E9', cornerRadius: 12 }),+ tx({ x: 810, y: 920, width: 180, height: 36, text: 'TOTAL', fontFamily: 'Inter', bold: true, fontSize: 17, fill: '#FFFFFF', align: 'left' }),+ tx({ x: 990, y: 920, width: 160, height: 36, text: '$4,536', fontFamily: 'DM Mono', bold: true, fontSize: 19, fill: '#FFFFFF', align: 'right' }),+ tx({ x: 70, y: 1000, width: 600, height: 60, text: 'Thank you for your business!', fontFamily: 'Caveat', fontSize: 30, fill: '#0EA5E9', align: 'left' }),+ ],+ },+ ],+ },+ {+ slug: 'monthly-calendar',+ name: 'Monthly Calendar',+ category: 'document',+ width: 1240,+ height: 1754,+ accent: '#F97316',+ pages: [+ {+ id: 'p1',+ background: { type: 'solid', color: '#FFFFFF' },+ elements: [+ sh('rect', { x: 0, y: 0, width: 1240, height: 300, fill: '#F97316' }),+ tx({ x: 70, y: 90, width: 800, height: 110, text: 'MARCH', fontFamily: 'Archivo Black', fontSize: 88, fill: '#FFFFFF', align: 'left' }),+ tx({ x: 74, y: 205, width: 800, height: 60, text: '2026 · spring into it', fontFamily: 'Inter', fontSize: 26, fill: '#FFEDD5', align: 'left', letterSpacing: 3 }),+ st('🌸', { x: 1020, y: 80, width: 160, height: 160, fontSize: 110 }),+ // weekday header+ { ...tx({ x: 70, y: 330, width: 160, height: 40, text: 'MON', fontFamily: 'Inter', bold: true, fontSize: 15, fill: '#9A3412', align: 'center', letterSpacing: 1 }) },+ tx({ x: 246, y: 330, width: 160, height: 40, text: 'TUE', fontFamily: 'Inter', bold: true, fontSize: 15, fill: '#9A3412', align: 'center' }),+ tx({ x: 422, y: 330, width: 160, height: 40, text: 'WED', fontFamily: 'Inter', bold: true, fontSize: 15, fill: '#9A3412', align: 'center' }),+ tx({ x: 598, y: 330, width: 160, height: 40, text: 'THU', fontFamily: 'Inter', bold: true, fontSize: 15, fill: '#9A3412', align: 'center' }),+ tx({ x: 774, y: 330, width: 160, height: 40, text: 'FRI', fontFamily: 'Inter', bold: true, fontSize: 15, fill: '#9A3412', align: 'center' }),+ tx({ x: 950, y: 330, width: 160, height: 40, text: 'SAT · SUN', fontFamily: 'Inter', bold: true, fontSize: 15, fill: '#9A3412', align: 'center' }),+ // week rows (grid separators)+ ln({ x: 70, y: 395, width: 1040, height: 0, stroke: '#FED7AA', strokeWidth: 2 }),+ ln({ x: 70, y: 560, width: 1040, height: 0, stroke: '#FFEDD5', strokeWidth: 2 }),+ ln({ x: 70, y: 725, width: 1040, height: 0, stroke: '#FFEDD5', strokeWidth: 2 }),+ ln({ x: 70, y: 890, width: 1040, height: 0, stroke: '#FFEDD5', strokeWidth: 2 }),+ ln({ x: 70, y: 1055, width: 1040, height: 0, stroke: '#FFEDD5', strokeWidth: 2 }),+ ln({ x: 218, y: 390, width: 0, height: 670, stroke: '#FFEDD5', strokeWidth: 2 }),+ ln({ x: 394, y: 390, width: 0, height: 670, stroke: '#FFEDD5', strokeWidth: 2 }),+ ln({ x: 570, y: 390, width: 0, height: 670, stroke: '#FFEDD5', strokeWidth: 2 }),+ ln({ x: 746, y: 390, width: 0, height: 670, stroke: '#FFEDD5', strokeWidth: 2 }),+ ln({ x: 922, y: 390, width: 0, height: 670, stroke: '#FFEDD5', strokeWidth: 2 }),+ // a few day numbers+ tx({ x: 90, y: 420, width: 80, height: 36, text: '2', fontFamily: 'Inter', bold: true, fontSize: 22, fill: '#1C1917', align: 'left' }),+ tx({ x: 266, y: 420, width: 80, height: 36, text: '3', fontFamily: 'Inter', bold: true, fontSize: 22, fill: '#1C1917', align: 'left' }),+ tx({ x: 442, y: 420, width: 80, height: 36, text: '4', fontFamily: 'Inter', bold: true, fontSize: 22, fill: '#1C1917', align: 'left' }),+ tx({ x: 618, y: 420, width: 80, height: 36, text: '5', fontFamily: 'Inter', bold: true, fontSize: 22, fill: '#1C1917', align: 'left' }),+ tx({ x: 794, y: 420, width: 80, height: 36, text: '6', fontFamily: 'Inter', bold: true, fontSize: 22, fill: '#1C1917', align: 'left' }),+ tx({ x: 970, y: 420, width: 140, height: 36, text: '7 / 8', fontFamily: 'Inter', bold: true, fontSize: 22, fill: '#A8A29E', align: 'left' }),+ // highlight a special day+ sh('ellipse', { x: 630, y: 590, width: 60, height: 60, fill: '#F97316' }),+ tx({ x: 640, y: 604, width: 44, height: 36, text: '14', fontFamily: 'Inter', bold: true, fontSize: 20, fill: '#FFFFFF', align: 'center' }),+ tx({ x: 610, y: 662, width: 180, height: 30, text: 'launch day ✦', fontFamily: 'Caveat', bold: true, fontSize: 24, fill: '#9A3412', align: 'center' }),+ tx({ x: 90, y: 585, width: 80, height: 36, text: '9', fontFamily: 'Inter', bold: true, fontSize: 22, fill: '#1C1917', align: 'left' }),+ tx({ x: 90, y: 750, width: 80, height: 36, text: '16', fontFamily: 'Inter', bold: true, fontSize: 22, fill: '#1C1917', align: 'left' }),+ tx({ x: 90, y: 915, width: 80, height: 36, text: '23', fontFamily: 'Inter', bold: true, fontSize: 22, fill: '#1C1917', align: 'left' }),+ tx({ x: 90, y: 1080, width: 80, height: 36, text: '30', fontFamily: 'Inter', bold: true, fontSize: 22, fill: '#1C1917', align: 'left' }),+ // footer note+ ln({ x: 70, y: 1230, width: 1040, height: 0, stroke: '#FED7AA', strokeWidth: 2 }),+ tx({ x: 70, y: 1260, width: 1040, height: 44, text: 'notes — · ideas — · reminders —', fontFamily: 'Caveat', fontSize: 26, fill: '#78716C', align: 'left' }),+ ],+ },+ ],+ },+ {+ slug: 'business-card',+ name: 'Business Card',+ category: 'document',+ width: 1050,+ height: 600,+ accent: '#7630D7',+ pages: [+ {+ id: 'p1',+ background: { type: 'solid', color: '#0F1015' },+ elements: [+ sh('ellipse', { x: -260, y: -220, width: 560, height: 560, fill: '#7630D7' }),+ sh('ellipse', { x: 820, y: 380, width: 400, height: 400, fill: '#02C0CC' }),+ tx({ x: 80, y: 210, width: 600, height: 60, text: 'JORDAN REYES', fontFamily: 'Archivo', bold: true, fontSize: 40, fill: '#FFFFFF', align: 'left', letterSpacing: 2 }),+ tx({ x: 82, y: 275, width: 600, height: 40, text: 'Creative Director', fontFamily: 'Inter', fontSize: 20, fill: '#02C0CC', align: 'left' }),+ ln({ x: 82, y: 345, width: 70, height: 0, stroke: '#7630D7', strokeWidth: 4 }),+ tx({ x: 82, y: 380, width: 640, height: 130, text: '[email protected]\n+1 555 0199\njordanreyes.co', fontFamily: 'DM Mono', fontSize: 16, fill: '#D1D5DB', align: 'left', lineHeight: 1.8 }),+ ],+ },+ ],+ },]export function templatesAsRecords(): TemplateRecord[] {diff --git a/src/lib/types.ts b/src/lib/types.tsindex f435eca..50e9870 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -235,6 +235,7 @@ export const TEMPLATE_CATEGORIES = [{ id: 'social', label: 'Social media', icon: 'instagram' },{ id: 'presentation', label: 'Presentation', icon: 'presentation' },{ id: 'print', label: 'Print', icon: 'printer' },+ { id: 'document', label: 'Docs & office', icon: 'file-text' },{ id: 'logo', label: 'Logos', icon: 'badge' },{ id: 'thumbnail', label: 'Video & thumbnails', icon: 'video' },] as constdiff --git a/src/store/editor-store.ts b/src/store/editor-store.tsindex 27c1623..045e779 100644--- a/src/store/editor-store.ts+++ b/src/store/editor-store.ts@@ -14,6 +14,7 @@ import {type PageData,} from '@/lib/types'import type { TemplateDef } from '@/lib/templates'+import { magicRelayoutPages } from '@/lib/magic'export type PanelId =| 'templates'@@ -73,7 +74,7 @@ interface EditorState {removeManualGuide: (id: string) => voidclearManualGuides: () => void- // v0.3.1: version history (per design, localStorage-persisted)+ // v0.3.1: version history (server-backed on Postgres since v0.4; localStorage fallback)versions: DesignVersion[]saveVersion: (label?: string) => voidrestoreVersion: (id: string) => void@@ -143,6 +144,9 @@ interface EditorState {setBrand: (b: BrandKit) => voidresizeDesign: (width: number, height: number) => void+ // v0.4: magic translate — batch-update text elements across ALL pages+ translateTexts: (updates: { id: string; text: string }[]) => void+// panels & savesetPanel: (p: PanelId) => voidmarkSaving: () => void@@ -203,8 +207,27 @@ export const useEditorStore = create<EditorState>((set, get) => ({tool: 'select',cropTargetId: null,})- // v0.3.1: load any locally-persisted versions for this design- set({ versions: loadVersions(d.id) })+ // v0.4: load server-side versions (Postgres); local list is the offline fallback+ const local = loadVersions(d.id)+ set({ versions: local })+ fetch(`/api/designs/${d.id}/versions`)+ .then((r) => (r.ok ? r.json() : []))+ .then((list: unknown) => {+ if (Array.isArray(list) && list.length) {+ set({+ versions: list.map((v: Record<string, unknown>) => ({+ id: String(v.id),+ label: String(v.label ?? 'Version'),+ at: Date.parse(String(v.createdAt ?? '')) || Date.now(),+ name: String(v.name ?? d.name),+ width: Number(v.width) || d.width,+ height: Number(v.height) || d.height,+ pages: (v.pages ?? []) as PageData[],+ })),+ })+ }+ })+ .catch(() => { /* offline — keep local list */ })},rename: (name) => set({ designName: name, dirty: true }),@@ -525,7 +548,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({set({ manualGuides: get().manualGuides.filter((g) => g.pageId !== pageId) })},- // ── v0.3.1: version history ────────────────────────────+ // ── version history (server-backed; localStorage fallback) ─saveVersion: (label) => {const { designId, designName, width, height, pages, versions } = get()if (!designId) return@@ -541,6 +564,19 @@ export const useEditorStore = create<EditorState>((set, get) => ({const next = [v, ...versions].slice(0, 30) // keep the 30 most recentset({ versions: next })persistVersions(designId, next)+ // server snapshot (best-effort; replaces the optimistic entry on success)+ fetch(`/api/designs/${designId}/versions`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ label: v.label, name: designName, width, height, pages }),+ })+ .then((r) => (r.ok ? r.json() : null))+ .then((saved: { id?: string } | null) => {+ if (!saved?.id) return+ set({ versions: [{ ...v, id: saved.id }, ...get().versions.filter((x) => x.id !== v.id)].slice(0, 30) })+ persistVersions(designId, get().versions)+ })+ .catch(() => { /* offline — local entry already stored */ })},restoreVersion: (id) => {const v = get().versions.find((x) => x.id === id)@@ -561,6 +597,10 @@ export const useEditorStore = create<EditorState>((set, get) => ({const next = versions.filter((v) => v.id !== id)set({ versions: next })if (designId) persistVersions(designId, next)+ // server snapshots have cuid ids; local ones use the ver_ prefix+ if (!id.startsWith('ver_')) {+ fetch(`/api/versions/${id}`, { method: 'DELETE' }).catch(() => {})+ }},// v0.3.1: image crop dialog@@ -569,18 +609,28 @@ export const useEditorStore = create<EditorState>((set, get) => ({resizeDesign: (width, height) => {get().pushHistory()- const { pages } = get()- const next = clone(pages)- // keep elements centered when canvas size changes- for (const page of next) {- for (const el of page.elements) {- el.x = Math.round((width - el.width) / 2)- el.y = Math.round((height - el.height) / 2)- }- }+ const { pages, width: oldW, height: oldH } = get()+ // v0.4 magic resize: smart re-layout — elements scale & keep their relative+ // position instead of all being dumped in the centre+ const next = magicRelayoutPages(clone(pages), oldW, oldH, width, height)set({ width, height, pages: next, selectedIds: [], zoom: 1 })},+ // ── v0.4: magic translate ────────────────────────────+ translateTexts: (updates) => {+ if (!updates.length) return+ get().pushHistory()+ const { pages, version } = get()+ const map = new Map(updates.map((u) => [u.id, u.text]))+ const applyTexts = (els: AnyElement[]): AnyElement[] =>+ els.map((el) => {+ if (el.type === 'group') return { ...el, children: applyTexts(el.children) }+ return map.has(el.id) ? ({ ...el, text: map.get(el.id)! } as AnyElement) : el+ })+ const next = clone(pages).map((p) => ({ ...p, elements: applyTexts(p.elements) }))+ set({ pages: next, version: version + 1, dirty: true })+ },+setPanel: (p) => set({ panel: get().panel === p ? null : p }),markSaving: () => set({ saving: true }),