Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

fix(v0.26): performance + AI reliability — assistant auto-apply, AI tool progress, landing v2

Ashiq Hussain Mir7a4b2c3bff73
diff --git a/docs/screenshots/03-editor.png b/docs/screenshots/03-editor.png
index 67303ad..334d5f6 100644
Binary files a/docs/screenshots/03-editor.png and b/docs/screenshots/03-editor.png differ
diff --git a/next.config.ts b/next.config.ts
index c1c21ba..af4ed16 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -28,7 +28,15 @@ const CSP_REPORT_ONLY = [
// thumbnails, blob: covers canvas exports
"img-src 'self' data: blob: https:",
"media-src 'self' data: blob:",
- "connect-src 'self' blob: data:",
+ // connect-src (v0.26 AI-tools fix): the two remote hosts are load-bearing
+ // for the AI image tools —
+ // - https://staticimgly.com — the on-device BG-Remover engine downloads
+ // its ONNX model from there on first use (a CSP block makes the
+ // removal hang forever with "Loading model…")
+ // - https://images.pexels.com + https://pixabay.com — stock photos are
+ // inserted by remote URL; the AI tools (brush eraser, magic eraser,
+ // upscale, alt-text) fetch those bytes client-side to build dataURLs
+ "connect-src 'self' blob: data: https://staticimgly.com https://images.pexels.com https://pixabay.com",
"worker-src 'self' blob:",
// embed cards (YouTube, Maps, …) frame out over TLS; enforcement
// will tighten this to the embed allowlist
diff --git a/src/app/api/ai/assistant/route.ts b/src/app/api/ai/assistant/route.ts
index e682417..a57c7ce 100644
--- a/src/app/api/ai/assistant/route.ts
+++ b/src/app/api/ai/assistant/route.ts
@@ -58,6 +58,8 @@ export type DesignAction =
| { type: 'setBackground'; kind: 'solid' | 'gradient'; from: string; to?: string; angle?: number }
| { type: 'alignElements'; ids: string[]; mode: 'left' | 'cx' | 'right' | 'top' | 'cy' | 'bottom' }
| { type: 'distributeElements'; ids: string[]; axis: 'x' | 'y' }
+ /** v0.26: nudge overlapping elements apart / pull off-canvas elements back in */
+ | { type: 'fixOverlaps' }
| { type: 'addPage' }
| { type: 'duplicatePage' }
| { type: 'generateImage'; prompt: string }
@@ -197,6 +199,7 @@ function sanitizeActions(input: unknown): DesignAction[] {
case 'magicAnimate':
case 'magicLayout':
case 'balanceLayout':
+ case 'fixOverlaps': // v0.26 — no parameters; operates on the current page
out.push({ type })
break
case 'generateImage': {
@@ -248,6 +251,46 @@ async function __canvix_post(req: NextRequest) {
.join('\n')
const selection = (d.selectedIds ?? []).slice(0, 20)
+
+ // ── v0.26 spatial awareness: precomputed overlap + bounds analysis ──
+ // Text elements over their own background/frame pairs are usual in
+ // design (that's composition, not a bug), so a pair only counts as an
+ // overlap when BOTH boxes are substantive and neither contains the
+ // other's center (the "text sits on a card" pattern). Keep it compact —
+ // this is model context, not a debug dump.
+ const boxes = els
+ .filter((e) => Number.isFinite(e.x) && Number.isFinite(e.y) && (e.width ?? 0) > 0 && (e.height ?? 0) > 0)
+ .map((e) => ({ id: e.id, type: e.type, x: e.x!, y: e.y!, w: e.width ?? 0, h: e.height ?? 0 }))
+ const overlaps: string[] = []
+ for (let i = 0; i < boxes.length; i++) {
+ for (let j = i + 1; j < boxes.length; j++) {
+ const a = boxes[i]
+ const b = boxes[j]
+ const ix = Math.max(0, Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x))
+ const iy = Math.max(0, Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y))
+ const inter = ix * iy
+ if (inter <= 0) continue
+ const minArea = Math.min(a.w * a.h, b.w * b.h)
+ if (minArea > 0 && inter / minArea > 0.55) {
+ // one box mostly inside the other — the text-on-card pattern,
+ // only report when the SMALLER element is not a text box
+ const smallerIsText = (a.w * a.h <= b.w * b.h ? a : b).type === 'text'
+ if (smallerIsText) continue
+ }
+ if (minArea > 0 && inter / minArea > 0.08) {
+ overlaps.push(`${a.type}#${a.id} × ${b.type}#${b.id} (${Math.round((inter / minArea) * 100)}% of the smaller)`)
+ }
+ if (overlaps.length >= 12) break
+ }
+ if (overlaps.length >= 12) break
+ }
+ const pw = Number(d.width) || 0
+ const ph = Number(d.height) || 0
+ const offCanvas = boxes
+ .filter((b) => pw > 0 && ph > 0 && (b.x < -8 || b.y < -8 || b.x + b.w > pw + 8 || b.y + b.h > ph + 8))
+ .slice(0, 8)
+ .map((b) => `${b.type}#${b.id} @(${Math.round(b.x)},${Math.round(b.y)}) ${Math.round(b.w)}x${Math.round(b.h)} outside the ${pw}x${ph} page`)
+
const designContext = [
`Design: "${d.name ?? 'Untitled'}" — ${d.width ?? '?'}x${d.height ?? '?'}px (${d.templateType ?? 'custom'}), ${d.pageCount ?? 1} page(s), currently editing page ${(d.currentPageIndex ?? 0) + 1}.`,
`Selected element ids: ${selection.length ? selection.join(', ') : 'none'}.`,
@@ -255,10 +298,12 @@ async function __canvix_post(req: NextRequest) {
elementSummary || '(empty page)',
`Colors in use: ${(d.colorsInUse ?? []).slice(0, 12).join(', ') || 'none'}`,
`Fonts in use: ${(d.fontsInUse ?? []).slice(0, 8).join(', ') || 'none'}`,
+ `Overlapping element pairs (spatial analysis): ${overlaps.length ? overlaps.join('; ') : 'none detected'}`,
+ `Off-canvas elements (partly outside the page): ${offCanvas.length ? offCanvas.join('; ') : 'none detected'}`,
].join('\n')
const system =
- 'You are the Canvix AI assistant 2.0 — a design-aware copilot embedded in a graphic-design editor ' +
+ 'You are the Canvix AI assistant — a design-aware copilot embedded in a graphic-design editor ' +
'(similar to Canva AI). You understand the CURRENT design: its elements, colors, typography, layout and page size. ' +
'You help users improve their design through STRUCTURED EDITOR ACTIONS, not code.\n\n' +
'Respond ONLY with a JSON object: {"reply": string, "actions": DesignAction[]}\n\n' +
@@ -274,19 +319,26 @@ async function __canvix_post(req: NextRequest) {
'- {"type":"setBackground","kind":"solid|gradient","from":"#hex","to":"#hex","angle":deg}\n' +
'- {"type":"alignElements","ids":[...],"mode":"left|cx|right|top|cy|bottom"}\n' +
'- {"type":"distributeElements","ids":[...],"axis":"x|y"}\n' +
+ '- {"type":"fixOverlaps"} — automatically separates overlapping elements and pulls off-canvas elements back onto the page (v0.26)\n' +
'- {"type":"addPage"} / {"type":"duplicatePage"}\n' +
'- {"type":"generateImage","prompt":str} — generates an AI image and adds it\n' +
'- {"type":"suggestPalette","colors":["#hex",...3-5]}\n' +
'- {"type":"translate","language":str}\n' +
'- {"type":"magicAnimate"} — one-click tasteful animations\n' +
'- {"type":"balanceLayout"} / {"type":"magicLayout"} — improve spacing/alignment/balance\n\n' +
+ 'SPATIAL AWARENESS (v0.26): the context includes each element\'s box `@(x,y) WxH` on a page of the given size, ' +
+ 'plus a precomputed list of overlapping pairs and off-canvas elements. USE IT:\n' +
+ '- When elements overlap unintentionally or sit off the page edge, prefer {"type":"fixOverlaps"} (it handles both).\n' +
+ '- For precise fixes, use updateElements/moveElements with exact pixel coordinates that respect the page bounds and avoid other elements\' boxes.\n' +
+ '- When the user asks to "move X next to Y", compute coordinates from the listed boxes (e.g. below Y: y = Y.y + Y.height + 24).\n' +
+ 'If the context says overlaps/offCanvas lists are empty, the layout is already clean — do not emit fixOverlaps.\n\n' +
'RULES:\n' +
'1. Only reference element ids that exist in the provided context. Use the ids of SELECTED elements when the user says "this/these/the title".\n' +
'2. "Make this more modern" → setFont (heading font), maybe setTextColor + balanceLayout. "Move the title to the top" → moveElements {to:"top"} on the title id.\n' +
'3. "Change all heading colors to purple" → setHeadingsColor. "Replace the background" → setBackground (or generateImage when they want a photo).\n' +
'4. "Add a CTA" → addText with bold + short text. "Instagram-ready" → suggest a 1080x1350 resize + magicAnimate in the reply (resize is manual).\n' +
'5. Create a second variation → duplicatePage + updateElements recolor on the duplicated page is NOT possible (actions apply to the current page) — explain instead.\n' +
- '6. At most 3 actions per reply, only when clearly useful. Empty array otherwise.\n' +
+ '6. At most 3 actions per reply, only when clearly useful. Empty array otherwise. Actions are applied automatically (v0.26) — only emit them when the user clearly asked for a change; otherwise describe the plan in "reply" and emit [].\n' +
'7. Never invent element ids. Never output code. Plain text in "reply".'
const history = (body.history ?? [])
@@ -294,11 +346,14 @@ async function __canvix_post(req: NextRequest) {
.filter((m) => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string')
.map((m) => ({ role: m.role, content: m.content.slice(0, 1000) }))
+ // v0.26 fix: the system prompt + design context used to ride as TWO
+ // extra `assistant` messages (pre-API-normalization leftovers) — most
+ // OpenAI-compatible providers ignore instructions that arrive as
+ // assistant turns. They are now a single proper system message.
const completion = await ctx.zai.chat.completions.create({
model: ctx.model,
messages: [
- { role: 'assistant', content: system },
- { role: 'assistant', content: `Current design context:\n${designContext}` },
+ { role: 'system', content: `${system}\n\nCurrent design context:\n${designContext}` },
...history,
{ role: 'user', content: message },
],
diff --git a/src/components/dashboard/Dashboard.tsx b/src/components/dashboard/Dashboard.tsx
index 736eed8..eeb3bf4 100644
--- a/src/components/dashboard/Dashboard.tsx
+++ b/src/components/dashboard/Dashboard.tsx
@@ -1,6 +1,6 @@
'use client'
-import { useCallback, useMemo, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
Search,
Plus,
@@ -107,6 +107,41 @@ const CATEGORY_ICONS: Record<string, typeof Presentation> = {
const PRESET_ICONS = [Instagram, Instagram, Presentation, Printer, BadgeCheck, Video, Square, FileImage]
+/** v0.26 performance: render children only once the placeholder scrolls
+ * near the viewport. The home page mounts ~370 template cards, each a
+ * full Konva stage — mounting them all at once was the 5–6 s "template
+ * grid takes forever" jank. One shared IntersectionObserver, a cheap
+ * div placeholder, and a generous 600 px rootMargin so cards are ready
+ * BEFORE the user scrolls to them (no visible pop-in on normal scroll
+ * speeds). Falls back to eager rendering when IO is unavailable. */
+function LazyCard({ children, minHeight = 180 }: { children: React.ReactNode; minHeight?: number }) {
+ const ref = useRef<HTMLDivElement>(null)
+ // lazy init in the state ctor — renders eagerly when IO is unavailable;
+ // otherwise starts hidden and flips visible from the observer callback
+ const [visible, setVisible] = useState(() => typeof IntersectionObserver === 'undefined')
+ useEffect(() => {
+ if (visible) return
+ const el = ref.current
+ if (!el) return
+ const io = new IntersectionObserver(
+ (entries) => {
+ if (entries.some((e) => e.isIntersecting)) {
+ setVisible(true)
+ io.disconnect()
+ }
+ },
+ { rootMargin: '600px 0px' },
+ )
+ io.observe(el)
+ return () => io.disconnect()
+ }, [visible])
+ return (
+ <div ref={ref} style={!visible ? { minHeight } : undefined}>
+ {visible ? children : null}
+ </div>
+ )
+}
+
// v0.17 (Wave 2): icon per preset group in the “More sizes” browser
const GROUP_ICONS: Record<string, typeof Instagram> = {
social: Smartphone,
@@ -536,6 +571,16 @@ export function Dashboard() {
className="h-10 w-10 rounded-full bg-gradient-to-br from-[#02C0CC] to-[#7630D7] text-white text-[13px] font-extrabold flex items-center justify-center shrink-0 hover:brightness-110 transition-all"
aria-label="Account menu"
title={user ? `Signed in as ${user.username}` : 'Sign in — free forever'}
+ // v0.26 perf: warm the profile dialog's two API calls the
+ // moment the user shows intent (menu open) — the dialog
+ // itself then renders from the prefetched data instead of
+ // starting its requests on click (~2 network round-trips
+ // saved on the reported "5–6 s to open profile")
+ onPointerEnter={() => {
+ if (!user) return
+ void fetch('/api/profile/ai-providers', { cache: 'no-store' }).then((r) => (r.ok ? r.json() : null)).catch(() => {})
+ void fetch('/api/keys', { cache: 'no-store' }).then((r) => (r.ok ? r.json() : null)).catch(() => {})
+ }}
>
{user ? user.username.slice(0, 2).toUpperCase() : 'CV'}
</button>
@@ -727,39 +772,40 @@ export function Dashboard() {
</div>
<div className="mt-4 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6 gap-4">
{filteredTemplates.map((t) => (
- <button
- key={t.slug}
- onClick={() => startFromTemplate(t)}
- disabled={creating}
- className="group text-left"
- aria-label={`Open template ${t.name}`}
- >
- <div
- className="relative rounded-xl overflow-hidden border border-white/10 shadow-lg shadow-black/30 group-hover:shadow-xl group-hover:-translate-y-0.5 transition-all bg-[#0F1015]"
- style={{ aspectRatio: `${t.width} / ${t.height}` }}
+ <LazyCard key={t.slug}>
+ <button
+ onClick={() => startFromTemplate(t)}
+ disabled={creating}
+ className="group text-left w-full"
+ aria-label={`Open template ${t.name}`}
>
- <DesignPreview page={t.pages[0]} width={t.width} height={t.height} />
- <div className="absolute inset-0 bg-[#7630D7]/0 group-hover:bg-[#7630D7]/15 transition-colors" />
- <span className="absolute top-2 right-2 h-6 w-6 rounded-full bg-[#7630D7] text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
- <Plus size={14} />
- </span>
- {/* v0.17 (Wave 2): smart templates offer CSV bulk fill */}
- {t.fields?.length ? (
- <span
- role="button"
- tabIndex={0}
- onClick={(e) => { e.stopPropagation(); setCsvTarget(t); setCsvText('') }}
- onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.stopPropagation(); setCsvTarget(t); setCsvText('') } }}
- className="absolute top-2 left-2 h-7 px-2 rounded-full bg-[#02C0CC] text-[#083344] text-[10px] font-bold flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
- title="Bulk-fill with CSV"
- >
- <FileSpreadsheet size={12} /> CSV
+ <div
+ className="relative rounded-xl overflow-hidden border border-white/10 shadow-lg shadow-black/30 group-hover:shadow-xl group-hover:-translate-y-0.5 transition-all bg-[#0F1015]"
+ style={{ aspectRatio: `${t.width} / ${t.height}` }}
+ >
+ <DesignPreview page={t.pages[0]} width={t.width} height={t.height} />
+ <div className="absolute inset-0 bg-[#7630D7]/0 group-hover:bg-[#7630D7]/15 transition-colors" />
+ <span className="absolute top-2 right-2 h-6 w-6 rounded-full bg-[#7630D7] text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
+ <Plus size={14} />
</span>
- ) : null}
- </div>
- <div className="mt-2 text-sm font-medium truncate text-white/85 group-hover:text-[#A78BFA] transition-colors">{t.name}</div>
- <div className="text-xs text-white/40">{t.width} × {t.height}</div>
- </button>
+ {/* v0.17 (Wave 2): smart templates offer CSV bulk fill */}
+ {t.fields?.length ? (
+ <span
+ role="button"
+ tabIndex={0}
+ onClick={(e) => { e.stopPropagation(); setCsvTarget(t); setCsvText('') }}
+ onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.stopPropagation(); setCsvTarget(t); setCsvText('') } }}
+ className="absolute top-2 left-2 h-7 px-2 rounded-full bg-[#02C0CC] text-[#083344] text-[10px] font-bold flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
+ title="Bulk-fill with CSV"
+ >
+ <FileSpreadsheet size={12} /> CSV
+ </span>
+ ) : null}
+ </div>
+ <div className="mt-2 text-sm font-medium truncate text-white/85 group-hover:text-[#A78BFA] transition-colors">{t.name}</div>
+ <div className="text-xs text-white/40">{t.width} × {t.height}</div>
+ </button>
+ </LazyCard>
))}
</div>
</section>
diff --git a/src/components/dashboard/ProfilePanel.tsx b/src/components/dashboard/ProfilePanel.tsx
index 37d85d7..615129e 100644
--- a/src/components/dashboard/ProfilePanel.tsx
+++ b/src/components/dashboard/ProfilePanel.tsx
@@ -118,10 +118,12 @@ export function ProfilePanel({ open, onOpenChange, user }: { open: boolean; onOp
}
}, [])
- // Load when the dialog opens. The fetch is kicked off in a microtask
- // so the effect body itself never calls setState synchronously
- // (react-hooks/set-state-in-effect — same pattern as useDesigns);
- // load() only sets state after its awaits resolve anyway.
+ // Load when the dialog opens. v0.26 perf: when the account-menu hover
+ // already warmed the request (in-flight or HTTP-cached), the fetch rides
+ // the same connection — and keep the PREVIOUS data visible during a
+ // reload instead of flashing a spinner on every open. The fetch is
+ // kicked off in a microtask so the effect body itself never calls
+ // setState synchronously (react-hooks/set-state-in-effect).
useEffect(() => {
if (!open) return
void Promise.resolve().then(() => load())
diff --git a/src/components/editor/ImageAI.tsx b/src/components/editor/ImageAI.tsx
index 6e051a4..0722116 100644
--- a/src/components/editor/ImageAI.tsx
+++ b/src/components/editor/ImageAI.tsx
@@ -43,17 +43,53 @@ function providerReason(detail?: string): 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. */
+ * (bundled /photos/*.jpg) are fetched and converted to dataURLs.
+ * v0.26: a 20 s timeout replaces the old unbounded fetch — a stalled
+ * remote (or a CSP/CORS block) now surfaces an error toast instead of
+ * hanging the tool at "Decoding image…" forever. */
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)
+ const ctrl = new AbortController()
+ const timer = setTimeout(() => ctrl.abort(), 20_000)
+ try {
+ const res = await fetch(src, { signal: ctrl.signal })
+ 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)
+ })
+ } catch (err) {
+ if (err instanceof DOMException && err.name === 'AbortError') {
+ throw new Error('Loading the image timed out — check your connection and try again.')
+ }
+ throw err
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
+/** v0.26: decode with a hard timeout. `new Image()` + onload can hang
+ * indefinitely on corrupted/oversized remote sources (the brush eraser
+ * used to sit at "Decoding image…" forever); this always settles. */
+function loadImage(src: string, timeoutMs = 15_000): Promise<HTMLImageElement> {
+ return new Promise((resolve, reject) => {
+ const img = new window.Image()
+ const timer = setTimeout(() => {
+ img.src = ''
+ reject(new Error('Decoding the image timed out — try a different image.'))
+ }, timeoutMs)
+ img.onload = () => {
+ clearTimeout(timer)
+ resolve(img)
+ }
+ img.onerror = () => {
+ clearTimeout(timer)
+ reject(new Error('Could not decode the image (it may be CORS-blocked) — try re-uploading it.'))
+ }
+ img.src = src
})
}
@@ -208,6 +244,8 @@ export function BgRemoverPopover({ el }: { el: ImageElement }) {
const [open, setOpen] = useState(false)
const [busy, setBusy] = useState(false)
const [phase, setPhase] = useState<'idle' | 'model' | 'removing' | 'provider'>('idle')
+ /** v0.26: 0–100 for the local engine's download/compute progress */
+ const [progress, setProgress] = useState(0)
const [engine, setEngine] = useState<ImageToolsEngine>('provider')
const [error, setError] = useState('')
@@ -222,20 +260,30 @@ export function BgRemoverPopover({ el }: { el: ImageElement }) {
}
}
- /** The on-device path — ONNX segmentation cut-out. */
+ /** The on-device path — ONNX segmentation cut-out. v0.26: real progress
+ * (model download % / compute phases) instead of a frozen "Loading…" —
+ * the first use downloads ~40 MB, and users need to see it moving. */
const runDevice = async () => {
const update = useEditorStore.getState().updateElements
setPhase('model')
+ setProgress(0)
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')
+ progress: (key, current, total) => {
+ if (key.startsWith('fetch:')) {
+ setPhase('model')
+ if (total > 0) setProgress(Math.round((current / total) * 100))
+ } else if (key.startsWith('compute:')) {
+ setPhase('removing')
+ setProgress(Math.round((current / Math.max(1, total)) * 100))
+ }
},
})
+ setProgress(100)
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))))
@@ -330,6 +378,25 @@ export function BgRemoverPopover({ el }: { el: ImageElement }) {
{error}
</p>
)}
+ {/* v0.26: live progress for the local engine (model download / compute) */}
+ {busy && engine === 'device' && (
+ <div className="mb-2.5" data-testid="bg-remover-progress">
+ <div className="h-1.5 rounded-full bg-white/10 overflow-hidden">
+ <div
+ className="h-full rounded-full bg-gradient-to-r from-[#02C0CC] to-[#7630D7] transition-[width] duration-300"
+ style={{ width: `${progress}%` }}
+ />
+ </div>
+ <div className="mt-1 text-[10px] text-white/50">
+ {phase === 'model' ? `Downloading model… ${progress}% (first use only, ~40 MB)` : `Removing background… ${progress}%`}
+ </div>
+ </div>
+ )}
+ {busy && engine === 'provider' && (
+ <div className="mb-2.5 text-[10px] text-white/50 flex items-center gap-1.5">
+ <Loader2 size={11} className="animate-spin" /> Sending the image to the AI provider — larger images can take up to a minute…
+ </div>
+ )}
<Button className="btn-cv w-full h-9 text-[12px]" onClick={() => void run()} disabled={busy}>
{busy ? <Loader2 size={13} className="animate-spin" /> : 'Remove background'}
</Button>
@@ -393,10 +460,22 @@ export function MagicEraserPopover({ el }: { el: ImageElement }) {
)
}
-/** Canva "Image Upscaler / enhancer" — one-click AI photo enhance. */
+/** Canva "Image Upscaler / enhancer" — one-click AI photo enhance.
+ * v0.26: shows elapsed time while the provider works — big photos can
+ * take 30 s+, and a bare spinner with no signal reads as "stuck". */
export function EnhanceButton({ el }: { el: ImageElement }) {
const [busy, setBusy] = useState(false)
+ const [elapsed, setElapsed] = useState(0)
+ useEffect(() => {
+ if (!busy) return
+ // no sync setState in the effect body — the tick callback is the
+ // only setter, and `run()` resets elapsed before flipping busy
+ const started = Date.now()
+ const t = setInterval(() => setElapsed(Math.round((Date.now() - started) / 1000)), 1000)
+ return () => clearInterval(t)
+ }, [busy])
const run = async () => {
+ setElapsed(0)
setBusy(true)
const ok = await runImageAI(el, { mode: 'enhance' }, (msg) =>
toast({ title: 'Enhance image', description: msg, variant: 'destructive' })
@@ -405,9 +484,101 @@ export function EnhanceButton({ el }: { el: ImageElement }) {
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">
+ <button className={btnBase} onClick={() => void run()} disabled={busy} title="Enhance image — sharpen & clean up with AI" aria-label="Enhance image" data-testid="enhance-button">
{busy ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}
- <span className="text-[12px] hidden lg:inline">{busy ? 'Enhancing…' : 'Enhance'}</span>
+ <span className="text-[12px] hidden lg:inline">{busy ? `Enhancing… ${elapsed}s` : 'Enhance'}</span>
+ {busy && <span className="text-[12px] lg:hidden">{elapsed}s</span>}
+ </button>
+ )
+}
+
+/** ── v0.26: "Auto adjust" — instant, local histogram auto-correction ──
+ * Canva's one-click "Auto" in the Adjust panel. Pure pixel math on a
+ * downscaled sample (fast on any image, no provider, no model): a
+ * percentile stretch on the luma histogram + gentle saturation lift.
+ * Writes ordinary brightness/contrast/saturation element props, so it
+ * stays undoable, animatable and export-safe like a manual adjust. */
+export function AutoAdjustButton({ el, ids }: { el: ImageElement; ids: string[] }) {
+ const [busy, setBusy] = useState(false)
+ const run = async () => {
+ if (busy) return
+ setBusy(true)
+ try {
+ const sendable = await toSendableImage(el.src)
+ const img = await loadImage(sendable)
+ // sample at most ~200px on the long edge — enough for a histogram
+ const s = Math.min(1, 200 / Math.max(img.naturalWidth, img.naturalHeight))
+ const w = Math.max(2, Math.round(img.naturalWidth * s))
+ const h = Math.max(2, Math.round(img.naturalHeight * s))
+ const c = document.createElement('canvas')
+ c.width = w
+ c.height = h
+ const ctx = c.getContext('2d', { willReadFrequently: true })
+ if (!ctx) throw new Error('Canvas is unavailable')
+ ctx.drawImage(img, 0, 0, w, h)
+ const data = ctx.getImageData(0, 0, w, h).data
+ // luma histogram + saturation stats
+ const hist = new Array<number>(256).fill(0)
+ let satSum = 0
+ let n = 0
+ for (let i = 0; i < data.length; i += 4) {
+ const r = data[i]
+ const g = data[i + 1]
+ const b = data[i + 2]
+ const luma = Math.round(0.2126 * r + 0.7152 * g + 0.0722 * b)
+ hist[luma]++
+ const mx = Math.max(r, g, b)
+ const mn = Math.min(r, g, b)
+ if (mx > 0) satSum += (mx - mn) / mx
+ n++
+ }
+ // 1st/99th percentile stretch → brightness/contrast in the element's
+ // -100..100 scale (0.5% clip on each end, like photo editors)
+ const loTarget = n * 0.005
+ const hiTarget = n * 0.995
+ let acc = 0
+ let lo = 0
+ let hi = 255
+ for (let v = 0; v < 256; v++) {
+ acc += hist[v]
+ if (acc <= loTarget) lo = v
+ if (acc <= hiTarget) hi = v
+ }
+ // map [lo, hi] → [0, 255]: brightness shifts the midpoint, contrast
+ // scales the span — both clamped to the panel's -100..100 range
+ const mid = (lo + hi) / 2
+ const brightness = Math.round(Math.max(-100, Math.min(100, ((128 - mid) / 128) * 60)))
+ const span = Math.max(16, hi - lo)
+ const contrast = Math.round(Math.max(-100, Math.min(100, ((255 / span - 1) * 100) / 1.6)))
+ const avgSat = n > 0 ? satSum / n : 0
+ const saturation = Math.round(Math.max(0, Math.min(100, (0.32 - avgSat) * 160)))
+ const update = useEditorStore.getState().updateElements
+ update(ids, { brightness, contrast, saturation })
+ toast({
+ title: 'Auto-adjusted',
+ description: `Brightness ${brightness >= 0 ? '+' : ''}${brightness}, contrast ${contrast >= 0 ? '+' : ''}${contrast}, saturation ${saturation >= 0 ? '+' : ''}${saturation}. Ctrl+Z to undo.`,
+ })
+ } catch (e) {
+ toast({
+ title: 'Auto adjust',
+ description: e instanceof Error ? e.message : 'Could not analyze this image.',
+ variant: 'destructive',
+ })
+ } finally {
+ setBusy(false)
+ }
+ }
+ return (
+ <button
+ className={btnBase}
+ onClick={() => void run()}
+ disabled={busy}
+ title="Auto adjust — instant brightness, contrast & saturation correction"
+ aria-label="Auto adjust image"
+ data-testid="auto-adjust-button"
+ >
+ {busy ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}
+ <span className="text-[12px] hidden lg:inline">{busy ? 'Adjusting…' : 'Auto'}</span>
</button>
)
}
@@ -418,15 +589,9 @@ export function EnhanceButton({ el }: { el: ImageElement }) {
* download. This is the universal path: VibesAI-class edit providers
* only edit images they generated themselves (422 otherwise). */
-/** dataURL → HTMLImageElement (decoded) */
-function loadImage(src: string): Promise<HTMLImageElement> {
- return new Promise((resolve, reject) => {
- const img = new window.Image()
- img.onload = () => resolve(img)
- img.onerror = () => reject(new Error('Could not decode the image'))
- img.src = src
- })
-}
+/** dataURL → HTMLImageElement (decoded) — v0.26: the guarded variant
+ * above (with timeout) replaced the raw onload promise; kept only as
+ * the load step shared by the dialog paths. */
/** Raster bytes → ImageData. TS's ImageData ctor wants
* Uint8ClampedArray<ArrayBuffer>; a fresh copy satisfies it on every
@@ -644,12 +809,15 @@ export function BrushEraserDialog({ el }: { el: ImageElement }) {
const lastPt = useRef<{ x: number; y: number } | null>(null)
/** display geometry, set when the image decodes */
const [disp, setDisp] = useState<{ w: number; h: number } | null>(null)
+ /** v0.26: surface decode failures instead of sitting on the hint forever */
+ const [decodeError, setDecodeError] = useState<string | null>(null)
// (re)draw the base image whenever the dialog opens / element changes
useEffect(() => {
if (!open || !baseRef.current || !maskRef.current) return
let cancelled = false
setPainted(false)
+ setDecodeError(null)
;(async () => {
try {
const sendable = await toSendableImage(el.src)
@@ -674,8 +842,9 @@ export function BrushEraserDialog({ el }: { el: ImageElement }) {
bctx.clearRect(0, 0, w, h)
bctx.drawImage(img, 0, 0, w, h)
mctx.clearRect(0, 0, w, h)
- } catch {
- /* decode failure leaves disp null → the hint stays visible */
+ } catch (err) {
+ /* decode failure → show the reason, not an eternal hint */
+ if (!cancelled) setDecodeError(err instanceof Error ? err.message : 'Could not decode the image.')
}
})()
return () => {
@@ -834,8 +1003,25 @@ export function BrushEraserDialog({ el }: { el: ImageElement }) {
lastPt.current = null
}}
/>
- {!disp && (
- <div className="flex items-center justify-center h-56 text-[12px] text-white/45">Decoding image…</div>
+ {!disp && !decodeError && (
+ <div className="flex items-center justify-center h-56 text-[12px] text-white/45">
+ <Loader2 size={13} className="animate-spin mr-2" /> Decoding image…
+ </div>
+ )}
+ {decodeError && (
+ <div className="flex flex-col items-center justify-center h-56 gap-2 text-[12px] text-[#FF8A8A] px-6 text-center" data-testid="brush-eraser-decode-error" role="alert">
+ {decodeError}
+ <button
+ className="text-[11px] font-semibold text-white/70 hover:text-white underline underline-offset-2"
+ onClick={() => {
+ // nudge the effect to re-run by toggling open off/on
+ setOpen(false)
+ setTimeout(() => setOpen(true), 60)
+ }}
+ >
+ Try again
+ </button>
+ </div>
)}
</div>
<div className="flex items-center gap-3 mt-1">
diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsx
index 3862a8b..d39af58 100644
--- a/src/components/editor/PropertiesBar.tsx
+++ b/src/components/editor/PropertiesBar.tsx
@@ -29,7 +29,7 @@ import { IMAGE_FILTER_PRESETS, applyPresetToImageData, isImageFilterId, clampFil
import { MASK_SHAPES, MASK_SHAPE_LABELS, isMaskShape, maskPolygon } from '@/lib/shapes'
import { useLoadedImage } from './canvas/use-loaded-image'
import { ToolbarPopover, SliderRow, IconTile } from './toolbar/popover-kit'
-import { BgRemoverPopover, MagicEraserPopover, EnhanceButton, UpscaleButton, BrushEraserDialog, AltTextPopover } from './ImageAI'
+import { BgRemoverPopover, MagicEraserPopover, EnhanceButton, UpscaleButton, BrushEraserDialog, AltTextPopover, AutoAdjustButton } from './ImageAI'
const ALIGN_ICONS = {
left: AlignLeft,
@@ -446,6 +446,8 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm
<BgRemoverPopover el={image} />
<MagicEraserPopover el={image} />
<EnhanceButton el={image} />
+ {/* v0.26: instant local auto-adjust (brightness/contrast/saturation) */}
+ <AutoAdjustButton el={image} ids={ids} />
{/* v0.19 (Wave 4): local image power tools — any image, offline */}
<UpscaleButton el={image} />
<BrushEraserDialog el={image} />
diff --git a/src/components/editor/apps/AssistantApp.tsx b/src/components/editor/apps/AssistantApp.tsx
index f752a29..1a48824 100644
--- a/src/components/editor/apps/AssistantApp.tsx
+++ b/src/components/editor/apps/AssistantApp.tsx
@@ -1,7 +1,7 @@
'use client'
import { useEffect, useRef, useState } from 'react'
-import { Bot, Loader2, Plus, Send, Sparkles, User, Wand2 } from 'lucide-react'
+import { Bot, Loader2, Play, Send, Sparkles, User, Wand2, Zap } from 'lucide-react'
import type { AnyElement, TextElement } from '@/lib/types'
import { useEditorStore } from '@/store/editor-store'
import { AppHeader, type AppPanelProps } from './registry'
@@ -14,17 +14,32 @@ interface Turn {
content: string
actions?: DesignAction[]
done?: { index: number; msg: string }
+ /** v0.26: actions this turn ran automatically (marks chips as done) */
+ autoRan?: boolean
}
const SUGGESTIONS = [
'Make this design more modern',
'Move the title to the top',
'Change all heading colors to purple',
+ 'Fix anything that overlaps',
'Make the layout more balanced',
'Add a CTA button text',
- 'Magic animate this page',
]
+/** v0.26: the auto-apply preference — persisted per browser. Default ON:
+ * the assistant now executes its actions right away (the Canva Magic
+ * Studio behaviour) instead of making the user click each chip. */
+const AUTO_APPLY_KEY = 'canvix-assistant-auto-apply'
+function readAutoApply(): boolean {
+ try {
+ const v = localStorage.getItem(AUTO_APPLY_KEY)
+ return v === null ? true : v === '1'
+ } catch {
+ return true
+ }
+}
+
/** Flatten elements (groups included). */
function flatElements(els: AnyElement[], out: AnyElement[] = []): AnyElement[] {
for (const el of els) {
@@ -84,6 +99,12 @@ export function AssistantApp({ onClose }: AppPanelProps) {
const scrollRef = useRef<HTMLDivElement>(null)
const { configured: aiConfigured, loaded: aiLoaded } = useAICapabilities()
const canUndo = useEditorStore((s) => s.past.length > 0)
+ // v0.26: auto-apply (default on) — flipped by the toggle in the header.
+ // localStorage is read lazily in the state ctor (client components
+ // render on the server first, so SSR falls back to `true` and the
+ // client picks the stored value on hydration — same pattern as a
+ // media-query hook).
+ const [autoApply, setAutoApply] = useState(() => readAutoApply())
useEffect(() => {
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' })
@@ -104,7 +125,24 @@ export function AssistantApp({ onClose }: AppPanelProps) {
})
const data = (await res.json()) as { reply?: string; actions?: DesignAction[]; error?: string; code?: string }
if (!res.ok || !data.reply) throw new Error(data.error ?? 'The assistant could not answer.')
- setTurns((ts) => [...ts, { role: 'assistant', content: data.reply!, actions: data.actions ?? [] }])
+ const actions = data.actions ?? []
+ const turnIndex = turns.length + 1 // index this new turn will occupy
+ setTurns((ts) => [...ts, { role: 'assistant', content: data.reply!, actions, autoRan: autoApply && actions.length > 0 }])
+ // v0.26: execute every returned action immediately when auto-apply
+ // is on — sequentially, so multi-action plans compose in order
+ if (autoApply && actions.length) {
+ void (async () => {
+ for (let j = 0; j < actions.length; j++) {
+ let msg: string
+ try {
+ msg = await applyDesignAction(actions[j])
+ } catch (e) {
+ msg = e instanceof Error ? e.message : 'Action failed'
+ }
+ setTurns((ts) => ts.map((t, i) => (i === turnIndex ? { ...t, done: { index: j, msg } } : t)))
+ }
+ })()
+ }
} catch (e) {
const message = e instanceof Error ? e.message : 'Something went wrong.'
// v0.23.1: assistant failures are often "no text-slot key" — nudge
@@ -115,7 +153,7 @@ export function AssistantApp({ onClose }: AppPanelProps) {
}
}
- /** Execute one attached action (undoable via Ctrl+Z). */
+ /** Execute one attached action manually (undoable via Ctrl+Z). */
const runAction = async (turnIndex: number, actionIndex: number, action: DesignAction) => {
let msg: string
try {
@@ -128,9 +166,35 @@ export function AssistantApp({ onClose }: AppPanelProps) {
const empty = turns.length === 0 && !busy
+ const toggleAutoApply = () => {
+ const next = !autoApply
+ setAutoApply(next)
+ try {
+ localStorage.setItem(AUTO_APPLY_KEY, next ? '1' : '0')
+ } catch {
+ /* storage unavailable — session-only preference */
+ }
+ }
+
return (
<div className="flex flex-col">
- <AppHeader icon={Bot} title="Canvix AI assistant" onClose={onClose} />
+ <AppHeader icon={Bot} title="Canvix AI assistant" onClose={onClose}>
+ {/* v0.26: auto-apply toggle — on = actions run the moment they arrive */}
+ <button
+ onClick={toggleAutoApply}
+ className={cn(
+ 'flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[10.5px] font-bold transition-colors',
+ autoApply
+ ? 'border-[#02C0CC]/40 bg-[#02C0CC]/15 text-[#7BE8EC]'
+ : 'border-white/12 bg-white/[0.04] text-white/55 hover:text-white/80'
+ )}
+ title={autoApply ? 'Auto-apply ON — actions run automatically. Click to review them manually instead.' : 'Auto-apply OFF — click each action to run it. Click to enable auto-apply.'}
+ aria-pressed={autoApply}
+ data-testid="assistant-auto-apply"
+ >
+ <Zap size={11} /> Auto-apply {autoApply ? 'on' : 'off'}
+ </button>
+ </AppHeader>
{/* AI provider missing — honest notice */}
{aiLoaded && !aiConfigured && (
@@ -176,15 +240,20 @@ export function AssistantApp({ onClose }: AppPanelProps) {
{t.content}
</div>
- {/* action chips */}
+ {/* action chips — v0.26: with auto-apply on these arrive
+ already-applied (chips show the result); with it off they
+ stay clickable run buttons */}
{t.actions && t.actions.length > 0 && (
<div className="mt-1.5 space-y-1">
+ <div className="text-[10px] font-semibold text-white/35 uppercase tracking-wide">
+ {t.autoRan ? 'Applied automatically' : 'Click to apply'}
+ </div>
{t.actions.map((a, j) => {
const done = t.done?.index === j
return (
<div key={j} className="flex gap-1.5">
<button
- disabled={done}
+ disabled={done || t.autoRan}
onClick={() => void runAction(i, j, a)}
className={cn(
'flex-1 flex items-center gap-2 rounded-xl border px-2.5 py-2 text-left text-[11px] font-semibold transition-colors',
@@ -193,9 +262,9 @@ export function AssistantApp({ onClose }: AppPanelProps) {
: 'border-[#7630D7]/40 bg-[#7630D7]/15 text-white hover:bg-[#7630D7]/30 cursor-pointer'
)}
>
- <Wand2 size={12} className="shrink-0" />
+ {done ? <Sparkles size={12} className="shrink-0" /> : <Wand2 size={12} className="shrink-0" />}
<span className="min-w-0 truncate">{done ? t.done?.msg : describeAction(a)}</span>
- {!done && <Plus size={11} className="ml-auto shrink-0" />}
+ {!done && !t.autoRan && <Play size={11} className="ml-auto shrink-0" />}
</button>
</div>
)
diff --git a/src/components/editor/toolbar/popover-kit.tsx b/src/components/editor/toolbar/popover-kit.tsx
index a00e492..702c2ec 100644
--- a/src/components/editor/toolbar/popover-kit.tsx
+++ b/src/components/editor/toolbar/popover-kit.tsx
@@ -1,9 +1,15 @@
'use client'
-import { useRef, useState, ReactNode } from 'react'
+import { useRef, useState, ReactNode, useEffect } from 'react'
import { cn } from '@/lib/utils'
-/** shared anchored popover for the context toolbar (canva .cv-pop style) */
+/** shared anchored popover for the context toolbar (canva .cv-pop style).
+ * v0.26 reliability fix: the position is now computed at OPEN time inside
+ * a layout effect (after the trigger re-renders with data-active), not
+ * inside the click handler — the old code could read a null/stale rect
+ * (e.g. right after selection changes re-mount the toolbar), leaving
+ * `pos` null so the popover silently never appeared ("Mask/Adjust do
+ * nothing on click"). It also clamps inside the viewport every time. */
export function ToolbarPopover({
children,
trigger,
@@ -19,21 +25,25 @@ export function ToolbarPopover({
const [pos, setPos] = useState<{ x: number; y: number } | null>(null)
const ref = useRef<HTMLDivElement>(null)
- const toggle = () => {
- if (!open) {
+ // position (or reposition) whenever the popover is open — also keeps it
+ // on screen across window resizes while open
+ useEffect(() => {
+ if (!open) return
+ const place = () => {
const r = ref.current?.getBoundingClientRect()
- if (r) {
- const x = Math.min(r.left, window.innerWidth - width - 12)
- const y = r.bottom + 6 > window.innerHeight - 300 ? Math.max(8, r.top - 306) : r.bottom + 6
- setPos({ x, y })
- }
+ if (!r) return
+ const x = Math.max(8, Math.min(r.left, window.innerWidth - width - 12))
+ const y = r.bottom + 6 > window.innerHeight - 300 ? Math.max(8, r.top - 306) : r.bottom + 6
+ setPos({ x, y })
}
- setOpen(!open)
- }
+ place()
+ window.addEventListener('resize', place)
+ return () => window.removeEventListener('resize', place)
+ }, [open, width])
return (
<div ref={ref} className="relative shrink-0">
- <span onClick={toggle}>{trigger(open)}</span>
+ <span onClick={() => setOpen((v) => !v)}>{trigger(open)}</span>
{open && pos && (
<>
<div className="fixed inset-0 z-[60]" onClick={() => setOpen(false)} onContextMenu={(e) => { e.preventDefault(); setOpen(false) }} />
diff --git a/src/components/landing/Landing.tsx b/src/components/landing/Landing.tsx
index 36f0e0a..e7c20aa 100644
--- a/src/components/landing/Landing.tsx
+++ b/src/components/landing/Landing.tsx
@@ -20,6 +20,11 @@ import {
BadgeCheck,
Heart,
Star,
+ Users,
+ Bot,
+ Server,
+ ChevronDown,
+ Check,
} from 'lucide-react'
import { useAppStore } from '@/store/app-store'
import { Logo } from '@/components/logo'
@@ -112,7 +117,7 @@ const FEATURES = [
{
icon: Download,
title: 'Export anywhere',
- text: 'Download crisp PNG and JPG files up to 3× resolution. Your designs, your files — no watermarks, ever.',
+ text: 'PNG, JPG, WebP, SVG, PDF, PPTX, even GIF and video — crisp up to 3× resolution. No watermarks, ever.',
},
{
icon: Smartphone,
@@ -126,6 +131,30 @@ const FEATURES = [
},
]
+/** v0.26: the three big differentiators — real-time collab, AI with your
+ * own key, and one-command self-hosting. Each maps to something the
+ * commercial tools charge for or lock away. */
+const BIG_FEATURES = [
+ {
+ icon: Users,
+ title: 'Real-time collaboration',
+ text: 'Invite anyone with a link and design together live — cursors, selections and edits sync instantly. No seat pricing, no viewer limits, no “upgrade to invite more editors”.',
+ accent: 'from-[#02C0CC] to-[#0090AA]',
+ },
+ {
+ icon: Bot,
+ title: 'AI that works for you',
+ text: 'A design-aware assistant that fixes overlaps and balances layouts automatically, background remover, magic eraser, auto-adjust and more. Bring your own API key — or run the local on-device engines with zero setup.',
+ accent: 'from-[#7630D7] to-[#9B6BFF]',
+ },
+ {
+ icon: Server,
+ title: 'Self-host in one command',
+ text: 'Your designs live in your own Postgres. One docker compose command and the whole platform — editor, collab, templates — runs on your hardware, forever.',
+ accent: 'from-[#FF5C8A] to-[#FF8A5C]',
+ },
+]
+
const TEMPLATE_SHOWCASE = [
{ label: 'Instagram post', from: '#FF5C8A', to: '#FFB84C', icon: Instagram, title: 'MEGA SALE' },
{ label: 'Story', from: '#B8E986', to: '#7ED957', icon: Instagram, title: 'NEW DROP' },
@@ -135,6 +164,51 @@ const TEMPLATE_SHOWCASE = [
{ label: 'Logo', from: '#FFFFFF', to: '#F4F5F7', icon: BadgeCheck, title: 'NOVA', dark: true },
]
+/** v0.26: short FAQ answering the questions new visitors actually ask. */
+const FAQ = [
+ {
+ q: 'Is it really free? What’s the catch?',
+ a: 'Really free, MIT licensed. There is no paid tier — no watermarks, no export limits, no locked elements. The hosted instance at canvix.app is the same code you can self-host.',
+ },
+ {
+ q: 'Do I need an account?',
+ a: 'No. You can open the editor and start designing immediately. Accounts are free and optional — they just keep your designs private and sync-able across devices.',
+ },
+ {
+ q: 'How does the AI work without spying on me?',
+ a: 'Every AI feature has an on-device engine that runs entirely in your browser. The provider-backed engines run server-side, and you can plug in your own API key so your work never spends anyone else’s quota.',
+ },
+ {
+ q: 'Can AI agents use Canvix?',
+ a: 'Yes — Canvix ships an MCP server. Connect Claude, Cursor or any MCP client to your account and let the agent create and edit designs for you, scoped to your designs only.',
+ },
+ {
+ q: 'What formats can I export?',
+ a: 'PNG, JPG, WebP, SVG, PDF, PPTX, GIF and video — at up to 3× resolution, with no watermarks on any of them.',
+ },
+ {
+ q: 'How do I self-host it?',
+ a: 'git clone, one docker compose command, done. Designs are stored in your own Postgres database; everything else runs statelessly in the container.',
+ },
+]
+
+function FaqItem({ q, a, defaultOpen = false }: { q: string; a: string; defaultOpen?: boolean }) {
+ const [open, setOpen] = useState(defaultOpen)
+ return (
+ <div className="rounded-2xl border border-black/8 bg-white overflow-hidden">
+ <button
+ className="w-full flex items-center justify-between gap-4 px-5 py-4 text-left"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ >
+ <span className="text-[15px] font-bold">{q}</span>
+ <ChevronDown size={17} className={`shrink-0 text-muted-foreground transition-transform duration-200 ${open ? 'rotate-180' : ''}`} />
+ </button>
+ {open && <p className="px-5 pb-5 text-sm text-muted-foreground leading-relaxed">{a}</p>}
+ </div>
+ )
+}
+
export function Landing() {
const goDashboard = useAppStore((s) => s.goDashboard)
const { user } = useAuth()
@@ -149,7 +223,9 @@ export function Landing() {
</button>
<div className="hidden md:flex items-center gap-1 text-sm font-medium text-muted-foreground">
<a href="#features" className="px-3 py-2 rounded-lg hover:bg-black/5 hover:text-foreground transition">Features</a>
+ <a href="#collab" className="px-3 py-2 rounded-lg hover:bg-black/5 hover:text-foreground transition">Collaborate</a>
<a href="#templates" className="px-3 py-2 rounded-lg hover:bg-black/5 hover:text-foreground transition">Templates</a>
+ <a href="#faq" className="px-3 py-2 rounded-lg hover:bg-black/5 hover:text-foreground transition">FAQ</a>
<a href="#opensource" className="px-3 py-2 rounded-lg hover:bg-black/5 hover:text-foreground transition">Open source</a>
</div>
<div className="flex items-center gap-2">
@@ -174,11 +250,12 @@ export function Landing() {
{/* ── Hero ── */}
<section className="relative overflow-hidden">
<div className="absolute inset-0 bg-brand-gradient-soft" aria-hidden="true" />
- <div className="absolute -top-32 -right-32 h-96 w-96 rounded-full blur-3xl opacity-20 bg-[#7D2AE8]" aria-hidden="true" />
- <div className="absolute -bottom-40 -left-32 h-96 w-96 rounded-full blur-3xl opacity-20 bg-[#00C4CC]" aria-hidden="true" />
+ {/* aurora blobs — subtle, GPU-cheap */}
+ <div className="absolute -top-32 -right-32 h-96 w-96 rounded-full blur-3xl opacity-20 bg-[#7D2AE8] animate-float" aria-hidden="true" />
+ <div className="absolute -bottom-40 -left-32 h-96 w-96 rounded-full blur-3xl opacity-20 bg-[#00C4CC] animate-float" style={{ animationDelay: '2s' }} aria-hidden="true" />
<div className="relative mx-auto max-w-7xl px-4 sm:px-6 pt-16 pb-20 sm:pt-24 sm:pb-28 text-center">
<div className="inline-flex items-center gap-2 rounded-full border border-black/10 bg-white px-4 py-1.5 text-xs font-semibold text-[#7D2AE8] shadow-sm animate-fade-up">
- <Sparkles size={14} /> Free forever · No account needed · MIT licensed
+ <Sparkles size={14} /> Free forever · No account needed · MIT licensed · Self-hostable
</div>
<h1 className="mt-6 text-4xl sm:text-6xl lg:text-7xl font-extrabold tracking-tight leading-[1.05] animate-fade-up delay-100">
Design anything.
@@ -187,7 +264,8 @@ export function Landing() {
</h1>
<p className="mx-auto mt-6 max-w-2xl text-base sm:text-lg text-muted-foreground animate-fade-up delay-200">
Canvix is the open-source design tool for social posts, presentations, posters, logos and
- more. Drag, drop, export — right in your browser, on any device.
+ more — with real-time collaboration and AI that works for you, not against you.
+ Drag, drop, export — right in your browser, on any device.
</p>
<div className="mt-8 flex flex-col sm:flex-row items-center justify-center gap-3 animate-fade-up delay-300">
<Button size="lg" className="btn-brand-gradient rounded-full px-8 text-base h-12 gap-2" onClick={goDashboard}>
@@ -199,6 +277,14 @@ export function Landing() {
</Button>
</a>
</div>
+ {/* hero proof line */}
+ <div className="mt-6 flex flex-wrap items-center justify-center gap-x-5 gap-y-2 text-xs text-muted-foreground animate-fade-up delay-300">
+ {['No credit card, ever', 'No watermarks, ever', 'Export in 8 formats', 'Runs on your server too'].map((t) => (
+ <span key={t} className="inline-flex items-center gap-1.5">
+ <Check size={13} className="text-[#12A594]" /> {t}
+ </span>
+ ))}
+ </div>
<div className="mt-14 sm:mt-20 animate-fade-up delay-300">
<EditorMockup />
</div>
@@ -223,40 +309,71 @@ export function Landing() {
</div>
</section>
- {/* ── Features ── */}
- <section id="features" className="mx-auto max-w-7xl px-4 sm:px-6 py-20 sm:py-28">
- <h2 className="text-center text-3xl sm:text-4xl font-extrabold tracking-tight">
- Everything you need to <span className="text-brand-gradient">create</span>
- </h2>
- <p className="mt-4 text-center text-muted-foreground max-w-2xl mx-auto">
- A serious editor, not a toy. Canvix packs the features people actually use from
- commercial design tools — minus the price tag.
- </p>
- <div className="mt-12 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
- {FEATURES.map((f) => (
+ {/* ── Big differentiators: collab / AI / self-host ── */}
+ <section id="collab" className="mx-auto max-w-7xl px-4 sm:px-6 py-20 sm:py-28">
+ <div className="text-center">
+ <h2 className="text-3xl sm:text-4xl font-extrabold tracking-tight">
+ What the paid tools charge for,{' '}
+ <span className="text-brand-gradient">Canvix gives away</span>
+ </h2>
+ <p className="mt-4 text-muted-foreground max-w-2xl mx-auto">
+ The features that cost the most elsewhere — collaboration seats, AI credits, team
+ workspaces — are core parts of Canvix, free and open.
+ </p>
+ </div>
+ <div className="mt-12 grid grid-cols-1 lg:grid-cols-3 gap-5">
+ {BIG_FEATURES.map((f) => (
<div
key={f.title}
- className="group rounded-2xl border border-black/8 bg-white p-6 hover:shadow-lg hover:shadow-black/5 hover:border-[#00C4CC]/40 transition-all"
+ className="group rounded-3xl border border-black/8 bg-white p-7 hover:shadow-xl hover:shadow-black/5 transition-all hover:-translate-y-1"
>
- <div className="h-11 w-11 rounded-xl flex items-center justify-center bg-brand-gradient-soft text-[#7D2AE8] group-hover:scale-105 transition-transform">
- <f.icon size={20} />
+ <div className={`h-12 w-12 rounded-2xl flex items-center justify-center text-white shadow-lg bg-gradient-to-br ${f.accent} group-hover:scale-105 transition-transform`}>
+ <f.icon size={22} />
</div>
- <h3 className="mt-4 font-bold">{f.title}</h3>
- <p className="mt-2 text-sm text-muted-foreground leading-relaxed">{f.text}</p>
+ <h3 className="mt-5 text-lg font-bold">{f.title}</h3>
+ <p className="mt-2.5 text-sm text-muted-foreground leading-relaxed">{f.text}</p>
</div>
))}
</div>
</section>
+ {/* ── Features grid ── */}
+ <section id="features" className="bg-[#FAFAFC] border-y border-black/5">
+ <div className="mx-auto max-w-7xl px-4 sm:px-6 py-20 sm:py-28">
+ <h2 className="text-center text-3xl sm:text-4xl font-extrabold tracking-tight">
+ Everything you need to <span className="text-brand-gradient">create</span>
+ </h2>
+ <p className="mt-4 text-center text-muted-foreground max-w-2xl mx-auto">
+ A serious editor, not a toy. Canvix packs the features people actually use from
+ commercial design tools — minus the price tag.
+ </p>
+ <div className="mt-12 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
+ {FEATURES.map((f) => (
+ <div
+ key={f.title}
+ className="group rounded-2xl border border-black/8 bg-white p-6 hover:shadow-lg hover:shadow-black/5 hover:border-[#00C4CC]/40 transition-all"
+ >
+ <div className="h-11 w-11 rounded-xl flex items-center justify-center bg-brand-gradient-soft text-[#7D2AE8] group-hover:scale-105 transition-transform">
+ <f.icon size={20} />
+ </div>
+ <h3 className="mt-4 font-bold">{f.title}</h3>
+ <p className="mt-2 text-sm text-muted-foreground leading-relaxed">{f.text}</p>
+ </div>
+ ))}
+ </div>
+ </div>
+ </section>
+
{/* ── Templates ── */}
- <section id="templates" className="bg-[#FAFAFC] border-y border-black/5 py-20 sm:py-28">
+ <section id="templates" className="py-20 sm:py-28">
<div className="mx-auto max-w-7xl px-4 sm:px-6">
<div className="text-center">
<h2 className="text-3xl sm:text-4xl font-extrabold tracking-tight">
Start from a <span className="text-brand-gradient">template</span>
</h2>
<p className="mt-4 text-muted-foreground max-w-2xl mx-auto">
- Sized and styled for every platform. Open one, tweak everything.
+ Sized and styled for every platform. Open one, tweak everything — every template is
+ free, forever.
</p>
</div>
<div className="mt-12 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
@@ -284,12 +401,26 @@ export function Landing() {
</div>
<div className="mt-10 text-center">
<Button variant="outline" className="rounded-full px-6 gap-2" onClick={goDashboard}>
- Browse all templates <ArrowRight size={16} />
+ Browse all 366 templates <ArrowRight size={16} />
</Button>
</div>
</div>
</section>
+ {/* ── FAQ (v0.26) ── */}
+ <section id="faq" className="bg-[#FAFAFC] border-y border-black/5 py-20 sm:py-28">
+ <div className="mx-auto max-w-3xl px-4 sm:px-6">
+ <h2 className="text-center text-3xl sm:text-4xl font-extrabold tracking-tight">
+ Questions, <span className="text-brand-gradient">answered</span>
+ </h2>
+ <div className="mt-10 space-y-3">
+ {FAQ.map((f, i) => (
+ <FaqItem key={f.q} q={f.q} a={f.a} defaultOpen={i === 0} />
+ ))}
+ </div>
+ </div>
+ </section>
+
{/* ── Open source ── */}
<section id="opensource" className="mx-auto max-w-7xl px-4 sm:px-6 py-20 sm:py-28">
<div className="grid lg:grid-cols-2 gap-10 lg:gap-14 items-center">
@@ -340,6 +471,22 @@ export function Landing() {
</div>
</div>
</section>
+
+ {/* ── Final CTA (v0.26) ── */}
+ <section className="relative overflow-hidden border-t border-black/5">
+ <div className="absolute inset-0 bg-brand-gradient-soft" aria-hidden="true" />
+ <div className="relative mx-auto max-w-3xl px-4 sm:px-6 py-20 sm:py-24 text-center">
+ <h2 className="text-3xl sm:text-4xl font-extrabold tracking-tight">
+ Your next design is <span className="text-brand-gradient">one click away</span>
+ </h2>
+ <p className="mt-4 text-muted-foreground">
+ No signup, no credit card, no watermark. Open the editor and start creating right now.
+ </p>
+ <Button size="lg" className="btn-brand-gradient rounded-full px-10 text-base h-13 gap-2 mt-8 py-3.5" onClick={goDashboard}>
+ Start designing <ArrowRight size={18} />
+ </Button>
+ </div>
+ </section>
</main>
{/* ── Footer ── */}
@@ -357,7 +504,7 @@ export function Landing() {
</a>
<a href="https://github.com/mir-ashiq/canvix#-ai--development-disclosure" target="_blank" rel="noreferrer" className="hover:text-foreground transition-colors">AI Disclosure</a>
<a href="#features" className="hover:text-foreground transition-colors">Features</a>
- <a href="#templates" className="hover:text-foreground transition-colors">Templates</a>
+ <a href="#faq" className="hover:text-foreground transition-colors">FAQ</a>
</div>
</div>
</footer>
diff --git a/src/lib/design-actions.ts b/src/lib/design-actions.ts
index bbfabbf..b03eeee 100644
--- a/src/lib/design-actions.ts
+++ b/src/lib/design-actions.ts
@@ -410,11 +410,99 @@ export async function applyDesignAction(action: DesignAction, caller?: ActionCal
return msg
}
+ case 'fixOverlaps': {
+ const msg = fixOverlaps()
+ return msg
+ }
+
default:
return 'Unsupported action'
}
}
+/** v0.26: separate overlapping elements + pull off-canvas elements back.
+ * Deterministic geometry pass over the current page:
+ * 1. Off-canvas boxes snap back inside the safe margin.
+ * 2. True overlaps (both boxes substantive, neither a text-on-card
+ * pattern — the text-inside-frame composition is legitimate) get
+ * pushed apart along the axis with the smallest required shift,
+ * iterating until stable (or a bounded pass count).
+ * All moves ride the ordinary updateElements store action → one undo
+ * step each, collab ops included. */
+function fixOverlaps(): string {
+ const s = useEditorStore.getState()
+ const page = s.pages[s.currentPage]
+ if (!page) return 'No page to fix'
+ const { width, height } = s
+ const margin = Math.round(Math.min(width, height) * 0.04)
+ // working copies (mutated, then committed in one batch at the end)
+ const boxes = flatElements(page.elements)
+ .filter((e) => !e.locked)
+ .map((e) => ({ id: e.id, type: e.type, x: e.x, y: e.y, w: e.width, h: e.height }))
+ if (!boxes.length) return 'Nothing to fix'
+
+ let moved = 0
+
+ // 1. off-canvas → clamp back inside the safe area
+ for (const b of boxes) {
+ const nx = Math.min(Math.max(b.x, margin), Math.max(margin, width - margin - b.w))
+ const ny = Math.min(Math.max(b.y, margin), Math.max(margin, height - margin - b.h))
+ if (nx !== b.x || ny !== b.y) {
+ b.x = nx
+ b.y = ny
+ moved++
+ }
+ }
+
+ // 2. iterative overlap separation (max 4 sweeps)
+ const overlapArea = (a: typeof boxes[number], b: typeof boxes[number]) => {
+ const ix = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x)
+ const iy = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y)
+ return ix > 0 && iy > 0 ? ix * iy : 0
+ }
+ const smallArea = (a: typeof boxes[number], b: typeof boxes[number]) => Math.min(a.w * a.h, b.w * b.h)
+
+ for (let sweep = 0; sweep < 4; sweep++) {
+ let touched = false
+ for (let i = 0; i < boxes.length; i++) {
+ for (let j = i + 1; j < boxes.length; j++) {
+ const a = boxes[i]
+ const b = boxes[j]
+ const inter = overlapArea(a, b)
+ if (inter <= 0) continue
+ const small = smallArea(a, b)
+ if (small <= 0 || inter / small < 0.1) continue // touching edges are fine
+ // skip the legitimate text-on-card composition: one box mostly
+ // inside the other AND the smaller is a text element
+ const smaller = a.w * a.h <= b.w * b.h ? a : b
+ if (inter / small > 0.55 && smaller.type === 'text') continue
+
+ // push apart along the cheaper axis (smallest shift), then clamp
+ const shiftX = Math.min(a.x + a.w - b.x, b.x + b.w - a.x) + 12
+ const shiftY = Math.min(a.y + a.h - b.y, b.y + b.h - a.y) + 12
+ if (shiftX <= shiftY) {
+ // a goes left, b goes right (keep order stable)
+ a.x = Math.max(margin, a.x - shiftX / 2)
+ b.x = Math.min(width - margin - b.w, b.x + shiftX / 2)
+ } else {
+ a.y = Math.max(margin, a.y - shiftY / 2)
+ b.y = Math.min(height - margin - b.h, b.y + shiftY / 2)
+ }
+ touched = true
+ moved++
+ }
+ }
+ if (!touched) break
+ }
+
+ if (!moved) return 'No overlaps or off-canvas elements found — the layout is clean'
+
+ // commit: one update per element (undo-friendly, collab-synced)
+ const update = useEditorStore.getState().updateElements
+ for (const b of boxes) update([b.id], { x: Math.round(b.x), y: Math.round(b.y) })
+ return `Layout fixed — ${moved} placement${moved > 1 ? 's' : ''} adjusted (overlaps separated, everything back on the page). Ctrl+Z to undo.`
+}
+
/** Deterministic layout balance: margins, centering, spacing (no AI needed). */
function balanceLayout(): string {
const s = useEditorStore.getState()
@@ -477,6 +565,7 @@ export function describeAction(action: DesignAction): string {
case 'suggestPalette': return 'Use this palette'
case 'translate': return `Translate to ${action.language}`
case 'magicAnimate': return 'Magic Animate this page'
+ case 'fixOverlaps': return 'Fix overlaps & off-canvas elements'
case 'balanceLayout':
case 'magicLayout': return 'Balance the layout'
default: return action.type