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.12): error boundaries — top-level + per-surface recovery UI with copyable diagnostics, dev crash probe, reactStrictMode re-enabled (H4) (#13)
Ashiq Hussain Mird07d1c9ae2c7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b27344d..77b5c80 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,49 @@All notable changes to Canvix will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).+## [0.12.2] — 2026-11-02++### Added++- **Error boundaries — a crash is never a white screen anymore (H4).**+ The v1.0 roadmap research flagged this as tech-debt #4: any+ render-time throw in the editor tree unmounted React root-down —+ a blank page, no recovery, no diagnostics. Now three boundaries+ guard the app: a top-level one around `AppShell` on both routes+ (`/` and `/design/<id>`), plus per-surface ones around the editor+ and the dashboard. The recovery UI offers the three escapes that+ actually help — **Reload editor** (fresh mount, URL and design id+ preserved), **Back to dashboard** (switches the app-store view and+ remounts the crashed surface from scratch, no reload needed) and+ **Copy diagnostics** — and the diagnostics carry exactly what a+ bug report needs: the design id, the last saved collab seq+ (from the replay cursor), save state (savedAt/saving/dirty), page+ and element counts, the error and its stack head, URL, timestamp+ and user agent. Honest scope note: boundaries catch render/lifecycle+ errors; event-handler and async errors were already contained by the+ validated-collab and db-error paths.+- **Dev-only crash probe** (`DevCrashProbe` in+ `src/components/ErrorBoundary.tsx`) — throws during render when+ `window.__canvixRequestDevCrash()` is called, which is the only+ class of error a boundary can catch. `NODE_ENV`-gated, so the+ throw branch is dead code that production builds drop entirely.+- **Playwright spec** `tests/e2e/error-boundary.spec.ts` — forces a+ crash in a child of the editor boundary, asserts the recovery UI+ renders (never a white screen), that the clipboard diagnostics+ parse as JSON with the design id + last-saved-seq fields, that+ “Back to dashboard” recovers without a reload, and that the+ editor still opens afterwards with no collateral page errors.++### Changed++- **`reactStrictMode` re-enabled** (was `false` since the+ pre-accounts era). The H4 epic called for a re-evaluation, and the+ current codebase tolerates double-invoked effects: the full+ Playwright suite passes unchanged under strict mode (dev server,+ which is where the double-invocation happens). This surfaces+ effect-cleanup bugs at development time instead of in production+ remounts.+## [0.12.1] — 2026-11-02### Addeddiff --git a/README.md b/README.mdindex a2dbeac..a314014 100644--- a/README.md+++ b/README.md@@ -795,6 +795,12 @@ tool descriptions so agents pick the right format.+ blob workers, and the strict per-manifest CSP the v0.13 pluginserve route will use, drafted and unit-tested in`src/lib/security/plugin-csp.ts` *(v0.12.1)*+- [x] Error boundaries — a top-level boundary around the app shell plus+ per-surface boundaries around the editor and dashboard: a render-time+ crash now shows a recovery UI (reload editor / back to dashboard /+ copy diagnostics with design id + last saved seq) instead of a white+ screen; `reactStrictMode` re-enabled after a full-suite re-evaluation+ *(v0.12.2)*- [ ] Plugin system (external, installable apps) — sandboxed-iframe MVPper `research/PLUGIN-SYSTEM.md`: manifest + permission model, iframesandbox with postMessage bridge, an “Apps” panel store, and 2–3diff --git a/next.config.ts b/next.config.tsindex d12a216..c1c21ba 100644--- a/next.config.ts+++ b/next.config.ts@@ -68,7 +68,14 @@ const nextConfig: NextConfig = {// v0.6.1: strict again — the codebase typechecks clean; keep it that way.ignoreBuildErrors: false,},- reactStrictMode: false,+ // v0.12.2 (H4): strict mode re-enabled. It was disabled in the+ // pre-accounts era (double-invoked effects broke the first collab+ // prototype); the v0.12 codebase now tolerates it — the full+ // Playwright suite passes unchanged under double-invoked effects+ // on the dev server (one ERR_CONNECTION_REFUSED infra flake,+ // green on re-run). This surfaces effect-cleanup bugs early+ // instead of in production remounts.+ reactStrictMode: true,// v0.9.3: two trace pins for cross-runtime packages that Next's module// graph cannot see on its own:// - sharp: loaded via a non-literal specifier in the MCP tools (thatdiff --git a/package.json b/package.jsonindex 9494e4d..fc7f4de 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.12.1",+ "version": "0.12.2","private": false,"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/src/app/design/[id]/page.tsx b/src/app/design/[id]/page.tsxindex 213aae4..ff8c8f8 100644--- a/src/app/design/[id]/page.tsx+++ b/src/app/design/[id]/page.tsx@@ -1,6 +1,7 @@'use client'import { AppShell } from '@/components/AppShell'+import { ErrorBoundary } from '@/components/ErrorBoundary'/*** v0.11.4: canonical design URLs — /design/<id>.@@ -8,7 +9,12 @@ import { AppShell } from '@/components/AppShell'* The shell is the same single-page app as /; the DeepLinkHandler inside* AppShell resolves the id from the path, fetches the design and opens the* editor. Unknown ids fall back to the landing page with the URL reset.+ * v0.12.2 (H4): wrapped in the top-level error boundary like /.*/export default function DesignPage() {- return <AppShell />+ return (+ <ErrorBoundary label="app">+ <AppShell />+ </ErrorBoundary>+ )}diff --git a/src/app/page.tsx b/src/app/page.tsxindex 311e511..c980872 100644--- a/src/app/page.tsx+++ b/src/app/page.tsx@@ -1,7 +1,15 @@'use client'import { AppShell } from '@/components/AppShell'+import { ErrorBoundary } from '@/components/ErrorBoundary'export default function Page() {- return <AppShell />+ // v0.12.2 (H4): the top-level boundary — catches anything the+ // per-surface boundaries inside AppShell do not (the landing view,+ // DeepLinkHandler, the shell itself).+ return (+ <ErrorBoundary label="app">+ <AppShell />+ </ErrorBoundary>+ )}diff --git a/src/components/AppShell.tsx b/src/components/AppShell.tsxindex 9cf19fb..81ad4a5 100644--- a/src/components/AppShell.tsx+++ b/src/components/AppShell.tsx@@ -5,6 +5,7 @@ import { useEffect } from 'react'import { useAppStore } from '@/store/app-store'import { Landing } from '@/components/landing/Landing'import { Dashboard } from '@/components/dashboard/Dashboard'+import { ErrorBoundary, DevCrashHook, DevCrashProbe } from '@/components/ErrorBoundary'import { readDesignIdFromLocation, isDesignPath, replaceUrl } from '@/lib/design-url'const Editor = dynamic(() => import('@/components/editor/Editor'), {@@ -59,15 +60,30 @@ function DeepLinkHandler() {export function AppShell() {const view = useAppStore((s) => s.view)+ // v0.12.2 (H4): per-surface error boundaries — a render-time crash+ // in the editor (or dashboard) shows the recovery UI instead of a+ // white screen; “Back to dashboard” remounts the crashed surface.+ // The dev-only crash probe lives inside the editor boundary (the+ // e2e target); production builds compile it out entirely.if (view === 'editor') {- return <Editor />+ return (+ <ErrorBoundary label="editor">+ <Editor />+ <DevCrashProbe />+ </ErrorBoundary>+ )}if (view === 'dashboard') {- return <Dashboard />+ return (+ <ErrorBoundary label="dashboard">+ <Dashboard />+ </ErrorBoundary>+ )}return (<><DeepLinkHandler />+ <DevCrashHook /><Landing /></>)diff --git a/src/components/ErrorBoundary.tsx b/src/components/ErrorBoundary.tsxnew file mode 100644index 0000000..bd39f1b--- /dev/null+++ b/src/components/ErrorBoundary.tsx@@ -0,0 +1,274 @@+'use client'++import { Component, type ErrorInfo, type ReactNode, useSyncExternalStore } from 'react'+import { useAppStore } from '@/store/app-store'+import { useEditorStore } from '@/store/editor-store'++// ─────────────────────────────────────────────────────────────+// Error boundaries (v0.12.2, roadmap H4 — research/V0118-ROADMAP-+// RESEARCH.md §3.9 debt #4). Until now a single render-time throw+// anywhere in the editor tree unmounted React root-down: a white+// screen with no recovery and no diagnostics. These boundaries+// catch render/lifecycle errors per surface and offer the three+// recoveries that actually help:+//+// Reload editor — fresh mount, browser state (URL, design id)+// preserved+// Back to dashboard — switches the app-store view and remounts+// the crashed surface from scratch+// Copy diagnostics — design id, last-saved seq, save state,+// page/element counts, the error itself;+// paste-ready for a bug report+//+// A boundary only helps for errors DURING render/lifecycle of its+// children — event-handler and async errors were already handled+// by the validated-collab / db-error paths. That split is honest+// and documented in the README.+// ─────────────────────────────────────────────────────────────++export interface CrashDiagnostics {+ surface: string+ at: string+ url: string+ designId: string | null+ designName: string | null+ savedAt: number | null+ saving: boolean+ dirty: boolean+ lastSavedSeq: number | null+ pages: number | null+ elements: number | null+ userAgent: string+ error: string+ stackHead: string+}++/** Read editor state at crash time — never during render, never throwing. */+function collectDiagnostics(surface: string, error: unknown): CrashDiagnostics {+ const err = error instanceof Error ? error : new Error(String(error))+ // getState() is side-effect free; wrapped so a store-level failure can+ // never break the boundary itself.+ let editor: {+ designId: string | null+ designName: string+ savedAt: number | null+ saving: boolean+ dirty: boolean+ pages?: unknown[]+ } | null = null+ try {+ editor = useEditorStore.getState()+ } catch {+ /* store unavailable — the dashboard boundary, usually */+ }+ let lastSavedSeq: number | null = null+ try {+ const designId = editor?.designId+ if (designId && typeof localStorage !== 'undefined') {+ const raw = localStorage.getItem(`canvix-seq-${designId}`)+ const n = raw === null ? NaN : Number(raw)+ if (Number.isFinite(n)) lastSavedSeq = n+ }+ } catch {+ /* storage unavailable */+ }+ const pages = Array.isArray(editor?.pages) ? editor!.pages!.length : null+ return {+ surface,+ at: new Date().toISOString(),+ url: typeof location !== 'undefined' ? location.href : '',+ designId: editor?.designId ?? null,+ designName: editor?.designName ?? null,+ savedAt: editor?.savedAt ?? null,+ saving: editor?.saving ?? false,+ dirty: editor?.dirty ?? false,+ lastSavedSeq,+ pages,+ elements:+ pages !== null+ ? (editor!.pages as { elements?: unknown[] }[]).reduce(+ (n, p) => n + (Array.isArray(p?.elements) ? p.elements.length : 0),+ 0,+ )+ : null,+ userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : '',+ error: `${err.name}: ${err.message}`,+ stackHead: (err.stack ?? '').split('\n').slice(0, 6).join('\n'),+ }+}++interface ErrorBoundaryProps {+ /** which surface is guarded — shown in the recovery UI */+ label: string+ children: ReactNode+}++interface ErrorBoundaryState {+ error: Error | null+ diagnostics: CrashDiagnostics | null+ copied: boolean+}++export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {+ state: ErrorBoundaryState = { error: null, diagnostics: null, copied: false }++ static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {+ return { error, copied: false }+ }++ componentDidCatch(error: Error, info: ErrorInfo) {+ // visible in dev/console + captured for the copy button+ const diagnostics = collectDiagnostics(this.props.label, error)+ this.setState({ diagnostics })+ console.error(`[canvix] ${this.props.label} crashed`, error, info.componentStack)+ // one-shot: if this was the dev crash probe, rearm it so a+ // recovered boundary remounts clean instead of re-throwing+ clearDevCrashProbe()+ }++ private reload = () => {+ location.reload()+ }++ private backToDashboard = () => {+ // remount the guarded surface from a clean slate+ this.setState({ error: null, diagnostics: null, copied: false })+ useAppStore.getState().goDashboard()+ }++ private copyDiagnostics = async () => {+ if (!this.state.diagnostics) return+ const text = JSON.stringify(this.state.diagnostics, null, 2)+ try {+ await navigator.clipboard.writeText(text)+ this.setState({ copied: true })+ } catch {+ // clipboard unavailable (permissions) — fall back to console+ console.info('[canvix] crash diagnostics (copy from console):', text)+ this.setState({ copied: true })+ }+ }++ render() {+ if (this.state.error) {+ return (+ <div+ role="alert"+ aria-label={`${this.props.label} crashed`}+ className="flex h-screen w-full items-center justify-center bg-[#0D0F14] p-6"+ >+ <div className="w-full max-w-md rounded-xl border border-white/10 bg-[#181B23] p-6 text-white shadow-2xl">+ <div className="mb-1 flex items-center gap-2">+ <span aria-hidden className="text-xl">+ ⚠️+ </span>+ <h2 className="text-lg font-semibold">Something went wrong</h2>+ </div>+ <p className="mb-4 text-sm text-white/60">+ The {this.props.label} hit an unexpected error and was stopped+ safely. Your design is saved on the server up to the last+ autosave.+ </p>+ <div className="mb-4 rounded-lg bg-black/40 p-3 font-mono text-xs text-red-300">+ {this.state.error.message || 'Unknown error'}+ </div>+ <div className="flex flex-wrap gap-2">+ <button+ onClick={this.reload}+ className="rounded-lg bg-[#00C4CC] px-4 py-2 text-sm font-semibold text-black hover:bg-[#00b3ba]"+ >+ Reload editor+ </button>+ <button+ onClick={this.backToDashboard}+ className="rounded-lg bg-white/10 px-4 py-2 text-sm font-semibold text-white hover:bg-white/20"+ >+ Back to dashboard+ </button>+ <button+ onClick={this.copyDiagnostics}+ className="rounded-lg bg-white/10 px-4 py-2 text-sm font-semibold text-white hover:bg-white/20"+ >+ {this.state.copied ? 'Diagnostics copied ✓' : 'Copy diagnostics'}+ </button>+ </div>+ {this.state.diagnostics?.designId ? (+ <p className="mt-4 text-xs text-white/40">+ design {this.state.diagnostics.designId} · last saved seq{' '}+ {this.state.diagnostics.lastSavedSeq ?? 'unknown'}+ </p>+ ) : null}+ </div>+ </div>+ )+ }+ return this.props.children+ }+}++// ─────────────────────────────────────────────────────────────+// Dev-only crash probe — the e2e suite's way of proving a forced+// crash in a child renders the boundary instead of a white screen+// (the H4 acceptance criterion). It throws DURING RENDER, which is+// the only class of error a boundary can catch, so no event-hook+// tricks. Compiled out of production builds: NODE_ENV is inlined,+// making the throw branch dead code that minifiers drop.+// ─────────────────────────────────────────────────────────────++const probeListeners = new Set<() => void>()+let probeRequested = false++/** Flip the probe; exposed as window.__canvixRequestDevCrash in dev. */+function requestDevCrash(): void {+ probeRequested = true+ probeListeners.forEach((l) => l())+}++/** Rearm the probe once its crash has been delivered to a boundary. */+function clearDevCrashProbe(): void {+ if (!probeRequested) return+ probeRequested = false+ probeListeners.forEach((l) => l())+}++function InnerDevCrashProbe(): null {+ const requested = useSyncExternalStore(+ (cb) => {+ probeListeners.add(cb)+ return () => probeListeners.delete(cb)+ },+ () => probeRequested,+ () => false,+ )+ if (process.env.NODE_ENV !== 'production' && requested) {+ throw new Error(+ 'Canvix dev crash probe — intentional (e2e: proves the error boundary renders)',+ )+ }+ return null+}++/**+ * The crash probe as an explicit child — mount it inside exactly ONE+ * boundary per test target (AppShell mounts it inside the editor+ * boundary). Rendering it from every boundary would make every probe+ * throw in the same render pass, and the outermost boundary's fallback+ * would replace the inner one's — the wrong surface would “catch”.+ */+export function DevCrashProbe() {+ return <InnerDevCrashProbe />+}++declare global {+ interface Window {+ __canvixRequestDevCrash?: typeof requestDevCrash+ }+}++// mounted once per boundary; dev only (the probe itself no-ops in prod)+export function DevCrashHook(): null {+ if (process.env.NODE_ENV !== 'production' && typeof window !== 'undefined') {+ window.__canvixRequestDevCrash = requestDevCrash+ }+ return null+}diff --git a/tests/e2e/error-boundary.spec.ts b/tests/e2e/error-boundary.spec.tsnew file mode 100644index 0000000..bd80180--- /dev/null+++ b/tests/e2e/error-boundary.spec.ts@@ -0,0 +1,65 @@+import { test, expect } from '@playwright/test'++/**+ * H4 (v0.12.2): error boundaries — a forced render-time crash in a+ * child of the editor boundary must render the recovery UI (never a+ * white screen), offer working recoveries, and include the design id+ * + last saved seq in copyable diagnostics.+ *+ * The crash is forced through the dev-only crash probe compiled into+ * ErrorBoundary (NODE_ENV-gated, dropped from production builds).+ */++test.use({ permissions: ['clipboard-read', 'clipboard-write'] })++test('a forced render crash shows the boundary UI, not a white screen', async ({ page }) => {+ const pageErrors: string[] = []+ page.on('pageerror', (err) => pageErrors.push(err.message))++ // open a blank editor like the smoke spec does+ await page.goto('/')+ await page.getByRole('button', { name: /start designing/i }).first().click()+ await expect(page.getByLabel('Create a design')).toBeVisible()+ await page+ .locator('section:has(h2:text("Start a new design")) [aria-label^="Create "]')+ .first()+ .click()+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })++ // force a render-time crash inside the editor boundary+ await page.evaluate(() => window.__canvixRequestDevCrash?.())++ // the recovery UI renders — never an unmounted white screen.+ // (role+name: Next's route announcer is also role=alert)+ await expect(page.getByRole('alert', { name: 'editor crashed' })).toBeVisible({+ timeout: 10_000,+ })+ await expect(page.getByText('Something went wrong')).toBeVisible()+ await expect(page.getByRole('button', { name: 'Reload editor' })).toBeVisible()+ await expect(page.getByRole('button', { name: 'Back to dashboard' })).toBeVisible()++ // diagnostics are copyable and carry the acceptance-criteria fields+ await page.getByRole('button', { name: 'Copy diagnostics' }).click()+ await expect(page.getByText('Diagnostics copied ✓')).toBeVisible()+ const raw = await page.evaluate(() => navigator.clipboard.readText())+ const diag = JSON.parse(raw) as Record<string, unknown>+ expect(diag.surface).toBe('editor')+ expect(typeof diag.designId).toBe('string')+ expect(diag.designId).not.toBe('')+ expect('lastSavedSeq' in diag).toBe(true)+ expect(String(diag.error)).toContain('dev crash probe')++ // “Back to dashboard” recovers without a page reload+ await page.getByRole('button', { name: 'Back to dashboard' }).click()+ await expect(page.getByLabel('Create a design')).toBeVisible()++ // the editor still opens after recovery (boundary state reset)+ await page+ .locator('section:has(h2:text("Start a new design")) [aria-label^="Create "]')+ .first()+ .click()+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })++ // the only uncaught error is the probe itself — nothing else broke+ expect(pageErrors.filter((m) => !m.includes('dev crash probe'))).toEqual([])+})