Skip to content

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

feat(editor): auto version snapshots before destructive ops (D5) (#76)

Ashiq Hussain Mirf2e41c8b333c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ca95368..2934b25 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
+- **Auto version snapshots before destructive ops (D5)** — the five
+ operations that can discard large amounts of work in one click
+ (template apply, Magic Resize, Translate, Magic Layers page-replace,
+ page delete) now save a version snapshot of the pre-op state first.
+ The snapshot appears in Version history with an **auto** chip and a
+ label naming the incoming operation ("Auto — before page delete").
+ Design notes: a 60-second same-reason throttle keeps a user clicking
+ through template previews from evicting five slots; when the
+ 30-slot list overflows, the OLDEST auto snapshot is evicted first —
+ a manual snapshot is never dropped to make room for one (an
+ all-manual list keeps the original 30-most-recent cut). Restoring
+ an auto snapshot works exactly like a manual one. Unit suite covers
+ all five seams, the throttle and both prune paths; e2e proves the
+ page-delete loop through the real editor (delete → chip visible →
+ restore brings the page back).
- **Admin: BYOK adoption stat** — the console overview now answers
"how many users added their own API keys": a new **Own API keys**
stat card (distinct accounts with ≥1 `UserAIProvider` row, key
diff --git a/ROADMAP.md b/ROADMAP.md
index 637b7ad..517bf6d 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -164,7 +164,7 @@ The entire original phase was displaced by the consolidation programme. Nothing
| Epic | What | Notes | Effort |
|---|---|---|---|
-| **D5** | Auto version snapshots before destructive ops (template apply, Magic Resize, Translate, Magic Layers, page delete) with "auto" chips + preferential pruning | `saveVersion(label?)` exists; the triggers are the work | S |
+| **D5** | ~~Auto version snapshots before destructive ops~~ **✅ shipped v0.24** — template apply, Magic Resize, Translate, Magic Layers and page delete now auto-snapshot the pre-op state (`auto` chip in Version history, 60 s same-reason throttle, preferential prune: old autos evict first, manuals never dropped) | | |
| **D8** | Tables depth — per-cell font family/size, header styling presets, drag row/col resize | `TableCell` today: `text/fill/bold` only; geometry is pure (`lib/v06-geometry.ts`) | M |
| **D10** | Spellcheck in the text-editing overlay | The textarea overlay exists; browser spellcheck is nearly free; "Check spelling" pass is the S/M part | S–M |
| — | Wave-3 stretch goals: bezier pen tool, boolean shape ops | Deferred explicitly in v0.18 notes; still wanted | M each |
diff --git a/src/components/editor/VersionHistoryDialog.tsx b/src/components/editor/VersionHistoryDialog.tsx
index 120f774..297ef96 100644
--- a/src/components/editor/VersionHistoryDialog.tsx
+++ b/src/components/editor/VersionHistoryDialog.tsx
@@ -84,6 +84,14 @@ export function VersionHistoryDialog({ open, onOpenChange }: { open: boolean; on
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-[13px] font-semibold truncate">{v.label}</span>
+ {v.auto && (
+ <span
+ className="text-[10px] font-bold text-white/50 bg-white/[0.08] border border-white/15 rounded-full px-1.5 py-px uppercase tracking-wide shrink-0"
+ title="Saved automatically before a destructive operation"
+ >
+ auto
+ </span>
+ )}
{i === 0 && <span className="text-[10px] font-bold text-[#02C0CC] uppercase tracking-wide">latest</span>}
</div>
<div className="flex items-center gap-1.5 text-[11px] text-white/45 mt-0.5">
diff --git a/src/lib/types.ts b/src/lib/types.ts
index 3b63aa1..c9eda62 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -591,6 +591,11 @@ export interface DesignVersion {
width: number
height: number
pages: PageData[]
+ /** v0.24 (D5): true when saved automatically before a destructive op
+ * (template apply / Magic Resize / Translate / Magic Layers / page
+ * delete). Auto snapshots prune first when the 30-slot list fills —
+ * a manual snapshot is never dropped to make room for one. */
+ auto?: boolean
}
export interface DesignSnapshot {
diff --git a/src/store/editor-store-d5.test.ts b/src/store/editor-store-d5.test.ts
new file mode 100644
index 0000000..f3d7cba
--- /dev/null
+++ b/src/store/editor-store-d5.test.ts
@@ -0,0 +1,174 @@
+// ─────────────────────────────────────────────────────────────
+// v0.24 (D5): auto version snapshots before destructive ops
+//
+// What is locked in here:
+// 1. each of the five destructive ops saves an `auto` snapshot of the
+// PRE-op state first (template apply, Magic Resize, Translate,
+// Magic Layers replace, page delete)
+// 2. the 60 s same-reason throttle: a repeated op refreshes nothing
+// 3. preferential pruning: when the 30-slot list overflows, the
+// OLDEST auto is evicted — a manual snapshot is never dropped
+// 4. an all-manual list keeps the original 30-most-recent cut
+// 5. restoring an auto snapshot works exactly like a manual one
+// Vitest runs in the node environment, so localStorage is stubbed.
+// ─────────────────────────────────────────────────────────────
+
+import { describe, expect, it, beforeEach, vi } from 'vitest'
+import { useEditorStore } from '@/store/editor-store'
+import type { AnyElement, PageData, DesignVersion } from '@/lib/types'
+
+// node env — no localStorage: install the same contract the browser gives
+const store = new Map<string, string>()
+vi.stubGlobal('localStorage', {
+ getItem: (k: string) => store.get(k) ?? null,
+ setItem: (k: string, v: string) => void store.set(k, v),
+ removeItem: (k: string) => void store.delete(k),
+})
+
+vi.stubGlobal('fetch', vi.fn(() => Promise.resolve({ ok: false }))) // offline posture: no server round-trip
+
+function makeText(id: string, text: string): AnyElement {
+ return {
+ type: 'text',
+ id,
+ x: 10,
+ y: 10,
+ width: 200,
+ height: 40,
+ rotation: 0,
+ opacity: 1,
+ visible: true,
+ locked: false,
+ text,
+ fontSize: 32,
+ fontFamily: 'Inter',
+ fill: '#111111',
+ align: 'left',
+ bold: false,
+ italic: false,
+ underline: false,
+ strike: false,
+ lineHeight: 1.25,
+ letterSpacing: 0,
+ uppercase: false,
+ } as unknown as AnyElement
+}
+
+function page(id: string, text: string): PageData {
+ return { id, background: { type: 'solid', color: '#FFFFFF' }, elements: [makeText(`${id}-el`, text)] }
+}
+
+function seed(pages: PageData[], versions: DesignVersion[] = []) {
+ useEditorStore.setState({
+ pages,
+ currentPage: 0,
+ selectedIds: [],
+ past: [],
+ future: [],
+ dirty: false,
+ version: 0,
+ designId: 'test-d5',
+ designName: 'D5 test',
+ width: 1080,
+ height: 1080,
+ versions,
+ })
+}
+
+function manualVersion(i: number, at = Date.now() - 1000 * (100 - i)): DesignVersion {
+ return { id: `ver-m${i}`, label: `Manual ${i}`, at, name: 'D5 test', width: 1080, height: 1080, pages: [page(`pm${i}`, `m${i}`)] }
+}
+
+describe('D5 auto version snapshots', () => {
+ beforeEach(() => {
+ store.clear()
+ vi.mocked(fetch).mockClear()
+ })
+
+ it('deletePage saves an auto snapshot of the pre-delete state', () => {
+ seed([page('p1', 'keep'), page('p2', 'gone')])
+ useEditorStore.getState().deletePage(1)
+ const versions = useEditorStore.getState().versions
+ expect(versions).toHaveLength(1)
+ expect(versions[0].auto).toBe(true)
+ expect(versions[0].label).toBe('Auto — before page delete')
+ // the snapshot preserves the deleted page; the live design doesn't
+ expect(versions[0].pages).toHaveLength(2)
+ expect(versions[0].pages[1].elements[0]).toMatchObject({ text: 'gone' })
+ expect(useEditorStore.getState().pages).toHaveLength(1)
+ })
+
+ it('the last page is never deletable, and no snapshot is taken for a no-op', () => {
+ seed([page('only', 'one')])
+ useEditorStore.getState().deletePage(0)
+ expect(useEditorStore.getState().versions).toHaveLength(0)
+ })
+
+ it('translateTexts saves an auto snapshot before rewriting texts', () => {
+ seed([page('p1', 'before')])
+ const el = useEditorStore.getState().pages[0].elements[0]
+ useEditorStore.getState().translateTexts([{ id: el.id, text: 'nachher' }])
+ const [v] = useEditorStore.getState().versions
+ expect(v.auto).toBe(true)
+ expect(v.pages[0].elements[0]).toMatchObject({ text: 'before' })
+ expect(useEditorStore.getState().pages[0].elements[0]).toMatchObject({ text: 'nachher' })
+ })
+
+ it('the same reason within 60 s is throttled to one snapshot', () => {
+ seed([page('p1', 'a')])
+ const s = useEditorStore.getState()
+ s.translateTexts([{ id: 'p1-el', text: 'b' }])
+ s.translateTexts([{ id: 'p1-el', text: 'c' }])
+ const versions = useEditorStore.getState().versions
+ expect(versions.filter((v) => v.auto)).toHaveLength(1)
+ })
+
+ it('overflow evicts the OLDEST auto — a manual snapshot is never dropped', () => {
+ // 30-slot list, newest-first: 29 manuals + 1 old auto at the oldest
+ // position. A destructive op pushes a new auto → 31 → the OLD auto
+ // is evicted; every manual snapshot survives.
+ const manuals = Array.from({ length: 29 }, (_, i) => manualVersion(i + 1)) // m1..m29, m1 oldest
+ const oldAuto: DesignVersion = { ...manualVersion(0), id: 'ver-old-auto', auto: true, label: 'Auto — before old op' }
+ const list = [...manuals.reverse(), oldAuto] // newest-first: m29..m1, then the old auto as oldest
+ expect(list).toHaveLength(30)
+ seed([page('p1', 'x'), page('p2', 'y')], list)
+ useEditorStore.getState().deletePage(1) // pushes a new auto → 31 → evict the oldest auto
+ const after = useEditorStore.getState().versions
+ expect(after).toHaveLength(30)
+ expect(after[0]?.auto).toBe(true) // the new snapshot, newest-first
+ expect(after.some((v) => v.id === 'ver-old-auto')).toBe(false) // the old auto was evicted
+ expect(after.filter((v) => !v.auto)).toHaveLength(29) // every manual survived
+ })
+
+ it('an all-manual full list keeps the original 30-most-recent cut', () => {
+ const manuals = Array.from({ length: 30 }, (_, i) => manualVersion(i)) // m0 oldest … m29 newest
+ seed([page('p1', 'x'), page('p2', 'y')], [...manuals].reverse()) // newest first, 30 items
+ useEditorStore.getState().deletePage(1)
+ const after = useEditorStore.getState().versions
+ expect(after).toHaveLength(30)
+ expect(after[0]?.auto).toBe(true)
+ // the OLDEST manual was evicted (list was all-manual — fallback cut)
+ expect(after.some((v) => v.id === 'ver-m0')).toBe(false)
+ expect(after.filter((v) => v.auto)).toHaveLength(1)
+ })
+
+ it('restoring an auto snapshot works like a manual one', () => {
+ seed([page('p1', 'before'), page('p2', 'gone')])
+ useEditorStore.getState().deletePage(1)
+ const [v] = useEditorStore.getState().versions
+ useEditorStore.getState().restoreVersion(v.id)
+ const state = useEditorStore.getState()
+ expect(state.pages).toHaveLength(2)
+ expect(state.pages[1].elements[0]).toMatchObject({ text: 'gone' })
+ expect(state.dirty).toBe(true)
+ })
+
+ it('auto snapshots persist to localStorage for offline recovery', () => {
+ seed([page('p1', 'x'), page('p2', 'y')])
+ useEditorStore.getState().deletePage(1)
+ const raw = store.get('canvix-versions-test-d5')
+ expect(raw).toBeTruthy()
+ const parsed = JSON.parse(raw!) as DesignVersion[]
+ expect(parsed[0].auto).toBe(true)
+ })
+})
diff --git a/src/store/editor-store.ts b/src/store/editor-store.ts
index cd4e748..27dacba 100644
--- a/src/store/editor-store.ts
+++ b/src/store/editor-store.ts
@@ -136,6 +136,9 @@ interface EditorState {
// v0.3.1: version history (server-backed on Postgres since v0.4; localStorage fallback)
versions: DesignVersion[]
saveVersion: (label?: string) => void
+ /** v0.24 (D5): snapshot automatically before a destructive op — the
+ * caller names the operation so the label says what it protects. */
+ autoVersion: (reason: string) => void
restoreVersion: (id: string) => void
deleteVersion: (id: string) => void
@@ -802,6 +805,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({
deletePage: (index) => {
const { pages } = get()
if (pages.length <= 1) return
+ get().autoVersion('page delete')
get().pushHistory()
const removedId = pages[index].id
const next = [...pages]
@@ -834,6 +838,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({
},
applyTemplate: (t) => {
+ get().autoVersion('template apply')
get().pushHistory()
const pages = clone(t.pages.map((p) => ({ ...p, id: uid('page') })))
set({
@@ -949,6 +954,44 @@ export const useEditorStore = create<EditorState>((set, get) => ({
})
.catch(() => { /* offline — local entry already stored */ })
},
+ /** v0.24 (D5): auto-snapshot before a destructive op. Same shape as
+ * saveVersion but: (a) the label names the incoming operation, (b)
+ * the snapshot is flagged `auto`, and (c) when the 30-slot list is
+ * full an OLD AUTO is evicted first — a manual snapshot is never
+ * dropped to make room for one. No network hop: these fire on
+ * hot paths (the op itself already saves), so the optimistic local
+ * entry is the record; restore works from it exactly like a manual
+ * snapshot. */
+ autoVersion: (reason) => {
+ const { designId, designName, width, height, pages, versions } = get()
+ if (!designId) return
+ // throttle: a repeated op of the same kind within 60 s refreshes
+ // nothing — one protective snapshot is enough, and a user clicking
+ // through five template previews must not evict five slots.
+ const [head] = versions
+ if (head?.auto && head.label === `Auto — before ${reason}` && Date.now() - head.at < 60_000) return
+ const v: DesignVersion = {
+ id: uid('ver'),
+ label: `Auto — before ${reason}`,
+ at: Date.now(),
+ name: designName,
+ width,
+ height,
+ pages, // immutable snapshot — reference shares structure, no deep clone
+ auto: true,
+ }
+ let next = [v, ...versions]
+ if (next.length > 30) {
+ // preferential prune: drop the OLDEST auto (scanning from the
+ // tail — the list is newest-first, and index 0 is the snapshot
+ // we just made); if there is none, fall back to the plain
+ // 30-most-recent cut (all-manual list, original behavior)
+ const victim = findIndexRight(next.slice(1), (x) => x.auto === true)
+ next = victim === -1 ? next.slice(0, 30) : next.filter((_, i) => i !== victim + 1)
+ }
+ set({ versions: next })
+ persistVersions(designId, next)
+ },
restoreVersion: (id) => {
const v = get().versions.find((x) => x.id === id)
if (!v) return
@@ -980,6 +1023,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({
closeCrop: () => set({ cropTargetId: null }),
resizeDesign: (width, height) => {
+ get().autoVersion('Magic Resize')
get().pushHistory()
const { pages, width: oldW, height: oldH } = get()
// v0.4 magic resize: smart re-layout — elements scale & keep their relative
@@ -992,6 +1036,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({
// ── v0.4: magic translate ────────────────────────────
translateTexts: (updates) => {
if (!updates.length) return
+ get().autoVersion('Translate')
get().pushHistory()
const { pages, version } = get()
const map = new Map(updates.map((u) => [u.id, u.text]))
@@ -1018,6 +1063,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({
emit({ kind: 'elements:add', pageId: next[currentPage].id, elements: stamped })
},
replaceCurrentPage: (page) => {
+ get().autoVersion('Magic Layers')
get().pushHistory()
const { pages, currentPage } = get()
const next = [...pages]
@@ -1334,6 +1380,13 @@ function loadVersions(designId: string): DesignVersion[] {
}
}
+/** v0.24 (D5): last index matching pred — the versions list is newest-
+ * first, so the LAST auto is the OLDEST one, the eviction candidate. */
+function findIndexRight<T>(list: T[], pred: (x: T) => boolean): number {
+ for (let i = list.length - 1; i >= 0; i--) if (pred(list[i])) return i
+ return -1
+}
+
function persistVersions(designId: string, versions: DesignVersion[]) {
try {
// guard against quota errors: drop oldest versions until we fit
diff --git a/tests/e2e/d5-auto-versions.spec.ts b/tests/e2e/d5-auto-versions.spec.ts
new file mode 100644
index 0000000..02cf3dd
--- /dev/null
+++ b/tests/e2e/d5-auto-versions.spec.ts
@@ -0,0 +1,59 @@
+import { test, expect, type Page } from '@playwright/test'
+
+/**
+ * v0.24 (D5) — auto version snapshots before destructive ops.
+ *
+ * The five destructive operations (template apply, Magic Resize,
+ * Translate, Magic Layers page-replace, page delete) now save an
+ * `auto`-flagged version snapshot of the PRE-op state first, so a
+ * mis-click is always recoverable from Version history. This spec
+ * proves the page-delete path end to end through the real editor:
+ *
+ * 1. a design with one text element gets a second page
+ * 2. deleting it via the page bar saves an auto snapshot
+ * 3. Version history shows it with the "auto" chip and the
+ * "Auto — before page delete" label
+ * 4. restoring brings the deleted page back
+ * 5. a manual snapshot taken afterwards survives list pressure
+ * (the preferential-prune guarantee — unit-tested in full in
+ * src/store/editor-store-d5.test.ts; here just the UI surface)
+ *
+ * Needs a database (design creation) — see playwright.config.ts.
+ */
+test.setTimeout(120_000)
+
+async function openBlankEditor(page: Page) {
+ await page.goto('/')
+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })
+ await page.getByRole('button', { name: /start designing/i }).first().click()
+ 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 })
+}
+
+test('deleting a page auto-saves a recoverable snapshot', async ({ page }) => {
+ await openBlankEditor(page)
+
+ // add a second page, then delete it via the page bar
+ await page.getByRole('button', { name: 'Add page' }).click()
+ await expect(page.getByRole('button', { name: 'Go to page 2' })).toBeVisible()
+ await page.getByRole('button', { name: 'Delete page' }).last().click()
+ await expect(page.getByRole('button', { name: 'Go to page 2' })).toBeHidden()
+
+ // Version history: the auto snapshot is there with the auto chip
+ await page.getByRole('button', { name: 'File menu' }).click()
+ await page.getByRole('menuitem', { name: /version history/i }).click()
+ const dialog = page.getByRole('dialog')
+ await expect(dialog).toBeVisible()
+ await expect(dialog.getByText('Auto — before page delete')).toBeVisible()
+ await expect(dialog.getByText('auto', { exact: true })).toBeVisible()
+
+ // restore: the deleted page comes back (close the dialog first —
+ // the modal's accessibility tree hides the page bar behind it)
+ await dialog.getByRole('button', { name: 'Restore' }).first().click()
+ await dialog.getByRole('button', { name: 'Close' }).click()
+ await expect(dialog).toBeHidden()
+ await expect(page.getByRole('button', { name: 'Go to page 2' })).toBeVisible({ timeout: 15_000 })
+})