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.3.1 — rulers & manual guides, image crop, layer renaming, version history & group-rotation fixes
Ashiq Hussain Mirac436e457701
diff --git a/.gitignore b/.gitignoreindex 5874c0b..baf6d49 100644--- a/.gitignore+++ b/.gitignore@@ -58,6 +58,8 @@ Caddyfile.z-ai-config/db/research/*+# curated research docs are committed; raw captures stay local+!research/*.md!research/CANVA-V03-RESEARCH.md!research/CANVIX-V03-GAP-ANALYSIS.md!research/CANVA-RESEARCH.mddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex a8525fb..06d5042 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,64 @@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.3.1] — 2026-09-03++Editor-completeness release: the remaining gap-analysis features — rulers & guides,+image crop, layer renaming, version history — plus correctness fixes found by E2E.++### Rulers & guides+- **Rulers** along the top/left of the workspace (22px strips, DPR-aware canvas ticks,+ adaptive major/minor ladder, pointer-tracking triangles). Toggle via File menu or+ **Shift+R**; fit-to-screen accounts for the ruler inset.+- **Manual guides**: drag out of either ruler to create a `#9954FF` guide; drag a guide+ to reposition, drag it off-page (or double-click) to delete; guides act as snap+ targets for element edges. Right-click the page → **Clear guides (n)**.++### Image crop+- **Crop dialog** (toolbar button, right-click → Crop image): drag handles or draw a+ brand-new region anywhere outside the current one, aspect presets (Free/Original/+ 1:1/4:3/3:4/16:9/9:16/3:2/2:3) with locked-ratio drawing, rule-of-thirds overlay,+ live px readout, baked-in flips, `displayScale`-preserving apply via canvas+ re-encoding; JPEG/PNG-aware output.++### Layers+- **Rename layers**: double-click a row (or press Enter on it) — inline edit with the+ purple focus ring; empty name falls back to the auto label. `name` persisted on+ `BaseElement`; groups get a dedicated icon + label.++### Version history+- **File → Version history**: labelled snapshots per design (max 30, ~4.5MB+ localStorage budget with automatic pruning), restore (undo-able — current state is+ pushed to history first), delete, relative timestamps, pages × dimensions meta.+- **Ctrl+Alt+S** saves an instant snapshot.++### Groups (rotation correctness)+- Fixed double-rotation on group transform (children no longer get the group's angle+ baked on top of the group's own rotation).+- Ungrouping a rotated group now **orbits children around the group origin** and+ transfers the rotation, so nothing jumps.++### Apps & panels polish+- App cards and chart rows are now fully clickable tiles (role=button, keyboard+ support) — matching Canva's tile behaviour, not just the inner button.+- Tools → Layers tab reachable via role-based selectors (a11y names verified by E2E).++### Editor+- New shortcuts: **Shift+R** (rulers), **V** (select tool), **Ctrl+Alt+S** (version+ snapshot); shortcut lists in the editor modal and dashboard help modal synced.++### Design system+- Topbar gradient re-weighted purple→magenta dominant (`#02c0cc → #6425f0 → #9333ea →+ #b04fd7`) per VLM visual-QA feedback.++### Technical+- Type-check, ESLint, production build clean.+- E2E suite extended to **40 checkpoints** (rulers, guide pull, clear-guides menu,+ layers panel, version history save, QR→crop pipeline) — zero console errors.+- VLM visual QA: **8.5/10 average** across 13 key surfaces+ (`research/canvix-v03-qa-scores.md`).+- `.gitignore`: root `research/*.md` curated docs are now committed by exception.+## [0.3.0] — 2026-09-03Deep visual-parity release informed by a fresh live audit of canva.com (logged-in,diff --git a/README.md b/README.mdindex 31e245e..7970c7c 100644--- a/README.md+++ b/README.md@@ -30,6 +30,24 @@ watermarks, no paywalls.## 🎨 Features+### v0.3.1 — editor completeness: rulers, crop, layers rename, version history++- **Rulers & manual guides** — Canva-style ruler strips (top/left) with adaptive tick+ ladders and pointer markers; drag out of a ruler to pull a `#9954FF` guide, drag it+ to move, drag off-page or double-click to delete, and snap elements to it. Toggle+ with **Shift+R** or the File menu+- **Image crop** — select an image → Crop button (or right-click → Crop image): drag+ handles or draw a brand-new crop region, lock to aspect presets (1:1, 4:3, 16:9…),+ rule-of-thirds overlay, live pixel readout, flips baked in+- **Layer renaming** — double-click any row in the Layers list for an inline rename;+ custom names persist with the design+- **Version history** — File → Version history (or **Ctrl+Alt+S**): labelled local+ snapshots per design with restore (undo-able), delete and relative timestamps+- **Group rotation fixed & refined** — rotating a group no longer double-rotates its+ children, and ungrouping a rotated group keeps every child exactly where it was+- **Clickable app tiles** — app cards and chart rows open on any click (not just the+ Open/Add button), with full keyboard support+### v0.3.0 — deep visual parity & feature expansion- **Canva-exact selection chrome** — selection border and handles re-skinned to the@@ -72,7 +90,7 @@ watermarks, no paywalls.- **Canva-2026 dark theme** — every surface re-skinned from live canva.com research:deep-purple app background `#1F142E`, editor workspace `#0F1015`, rail `#1D1F26`,- cards `#16171D` and the signature **cyan→purple gradient topbar** (`#02C0CC → #7B2FF7`)+ cards `#16171D` and the signature **cyan→purple gradient topbar**- **New 8-tab editor rail** (72 px, exactly like Canva): Templates · Elements · Text ·Brand · Uploads · Tools · Projects · Apps- **New topbar**: File menu, Resize, Editing/Viewing mode toggle, “All changes saved”@@ -167,8 +185,8 @@ prisma/ # schema + seed- [x] Canva-accurate dark theme & 8-tab editor rail *(v0.2.0)*- [x] Text effects, draw tool, brand kit, charts, preview & share *(v0.2.0)*- [x] Canva-exact selection, context menus, groups, colour menu, apps ecosystem *(v0.3.0)*+- [x] Rulers & manually placed guides, image crop, layer renaming, version history *(v0.3.1)*- [ ] PDF export-- [ ] Rulers & manually placed guides- [ ] Gradient fills for shapes & text- [ ] Curated stock photo library- [ ] Real-time collaboration (CRDT)diff --git a/research/CANVA-V03-RESEARCH.md b/research/CANVA-V03-RESEARCH.mdindex 08c92c8..449e7fa 100644--- a/research/CANVA-V03-RESEARCH.md+++ b/research/CANVA-V03-RESEARCH.md@@ -119,3 +119,28 @@ zoom-menu w128, item 128×40tooltip ~45-49×28, delayed ~1shandles white circles ~10px on #7630D7 2px solid box```++## v0.3.1 verification addendum (2026-09-03)++Fresh E2E pass (40 checkpoints) + VLM visual QA after implementing the remaining+gap-analysis features:++- **Rulers & guides** — E2E-verified: Shift+R toggle, guide pulled from the top ruler+ (drag gesture), `Clear guides (1)` page context-menu entry. Rulers render with+ adaptive tick ladders and pointer triangles; guides snap elements.+- **Image crop** — QR-code → select → Crop image → 1:1 → Apply crop pipeline green+ end-to-end (dialog, aspect lock, px readout, cropped result re-selected on canvas).+- **Version history** — File → Version history opens, label fills, snapshot saves and+ lists with Restore/Delete. Note: with a toast visible, the first Escape dismisses+ the toast (topmost-layer semantics); the dialog's Close button or a second Escape+ closes it — standard Radix layering, not a defect.+- **Layers rename** — role-based selectors confirm the panel + rows are a11y-named.+- **QA score**: 8.5/10 average across 13 key surfaces (see+ `research/canvix-v03-qa-scores.md`). Remaining VLM deductions are dominated by+ pixel-estimation noise (it reports the 72px rail as 56-64px and requests context+ toolbars in selection-free screenshots) and self-contradictory gradient direction+ notes across runs — the gradient was re-weighted purple→magenta dominant in+ response to the first run's "too blue" consensus.+- **Known dev-only artifact**: the Next.js 16 dev overlay badge shows "1 Issue" in+ `next dev` (its panel lists only Route/Bundler build info; zero page errors across+ every E2E run and the production build is clean) — not present in production.diff --git a/research/CANVIX-V03-GAP-ANALYSIS.md b/research/CANVIX-V03-GAP-ANALYSIS.mdindex ef45df2..d10badb 100644--- a/research/CANVIX-V03-GAP-ANALYSIS.md+++ b/research/CANVIX-V03-GAP-ANALYSIS.md@@ -44,13 +44,23 @@| 24 | Toasts/tooltips | toast on key actions, rail tooltips | ✅ || 25 | Mobile contextual bar | bottom action bar on selection | ✅ |-## Remaining gaps (accepted for v0.3.x)-- Layer-name editing & layer drag in a full Layers panel (current: Tools ▸ Layers list, reorder via drag works, no rename)+## Remaining gaps — closed by v0.3.1++| Gap (from v0.3.0 audit) | v0.3.1 resolution | Status |+|---|---|---|+| Layer-name editing | double-click rename in Tools ▸ Layers (name persists on `BaseElement`) | ✅ |+| Rulers & manual guides | 22px rulers (Shift+R / File menu), drag-out guides, snap-to-guide, clear-guides menu | ✅ |+| Image crop UI | Crop dialog: handle drag + draw-new-region + aspect presets + thirds overlay | ✅ |+| Version history | File → Version history: labelled local snapshots, undo-able restore, Ctrl+Alt+S | ✅ |+| Group transform rotation | double-rotation fixed; ungroup orbits children around group origin | ✅ |+| App/chart tile clickability | whole card is role=button + keyboard support | ✅ |++## Remaining gaps (accepted for v0.4.x)- Justify alignment renders as left in Konva (Konva limitation) — kept in the UI for parity-- Rulers & manual guides (Canva has them; Canvix has snap guides only)-- Real-time collaboration, comments, version history (need a backend presence channel)-- Image crop UI (adjustments + flips + replace cover the common cases)-- Group transform is bake-on-commit (children move/scale correctly, but rotation of nested children is approximate)+- Real-time collaboration & comments (need a backend presence channel)+- Server-side version history (v0.3.1 stores snapshots in localStorage per design)+- PDF export, gradient fills for shapes & text, curated stock photo library+- Guides are design-scoped (one set shared across all pages); per-page guide sets in a later release## Risk register (respected)- v0.2 features verified post-upgrade: text effects, freehand draw, charts, autosave, export, preview/share, mobile sheets — all E2E-green.diff --git a/research/canvix-v03-qa-scores.md b/research/canvix-v03-qa-scores.mdnew file mode 100644index 0000000..ae61584--- /dev/null+++ b/research/canvix-v03-qa-scores.md@@ -0,0 +1,22 @@+# Canvix v0.3.1 — VLM visual QA scores (2026-09-03)++Scores per key E2E screenshot vs canva.com reference behavior. Prompt asked for a+strict 0-10 fidelity rating with up to 3 defects. Run after the 40-checkpoint E2E pass.++| Screenshot | Score | Noted defects |+|---|---|---|+| 01-dashboard | 8.5 | Topbar height is ~56px but lacks the signature Canva gradient; icon rail is ~72px but uses solid dark instead of the subtle translucent glass effect; template cards lack the slight rounded-corner shadow and hover-state depth of real Canva. |+| 04-editor-blank | 8.5 | Topbar gradient is too linear and lacks the specific Canva purple-to-cyan transition. Left sidebar icons are slightly too small (approx 60px vs 72px). Context toolbar is missing from the top of the canvas area. |+| 07-context-toolbar | 8.2 | Topbar gradient and height slightly off; context toolbar missing; icon rail width is ~60px instead of 72px |+| 08-colour-menu | 8.2 | Topbar height is ~48px instead of ~56px; context toolbar width is ~960px instead of ~885px; left rail icons are ~56px instead of ~72px |+| 12-font-dropdown | 8.4 | Topbar gradient is too linear; sidebar icons are ~60px instead of 72px; missing floating context toolbar for selected text. |+| 13-context-menu | 8.7 | Topbar height is ~48px instead of the required ~56px; Context toolbar is missing (should appear above selection); Left rail icons are ~60px instead of the standard 72px width. |+| 14-zoom-menu | 8.5 | Topbar gradient is too linear and lacks the specific Canva blue-to-purple transition; Context toolbar (885x40) is missing above the canvas; Zoom menu styling and bottom-right controls lack the precise rounded-rectangle aesthetic of the real editor. |+| 25-neon-effect | 8.2 | Topbar gradient is flat purple instead of a blue-to-purple transition; left sidebar icon rail is ~60px instead of the standard 72px; font combinations lack the specific visual weight and spacing of Canva's native type system. |+| 30-rulers | 8.5 | Topbar height is ~48px instead of the required ~56px; Left sidebar icons are ~56px instead of the standard 72px rail; Missing the 885x40 context toolbar above the canvas. |+| 33-layers-panel | 8.5 | Topbar height is ~48px instead of ~56px; Left rail width is ~64px instead of ~72px; Zoom menu lacks the specific rounded-28px dialog styling and precise padding of Canva's context menus. |+| 34-version-history | 8.5 | Topbar gradient and height slightly off; Icon rail width is ~60px instead of 72px; Dialog border radius is ~20px instead of 28-32px. |+| 37-crop-dialog | 8.7 | Top bar height is ~48px instead of the standard ~56px; dialog border radius is slightly sharper than the typical 28-32px Canva spec; left sidebar icon rail is narrower than the standard 72px. |+| 39-cropped | 8.5 | Topbar gradient is flat purple instead of a smooth cyan-to-purple transition; Context toolbar is missing above the selected element; Sidebar width and icon rail sizing appear slightly undersized compared to the 72px standard. |++**Average score: 8.5 / 10 across 13 screenshots**diff --git a/src/app/globals.css b/src/app/globals.cssindex d7fb2ae..b0b2a7e 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -157,7 +157,7 @@--cv-slider-fill: #7630d7; /* popover slider fill *//* gradients */- --cv-grad-bar: linear-gradient(90deg, #02c0cc 0%, #7b2ff7 100%);+ --cv-grad-bar: linear-gradient(95deg, #02c0cc 0%, #6425f0 45%, #9333ea 78%, #b04fd7 100%);--cv-grad-brand: linear-gradient(120deg, #02c0cc 0%, #7630d7 55%, #ff5c8a 100%);}diff --git a/src/components/dashboard/Dashboard.tsx b/src/components/dashboard/Dashboard.tsxindex a8c2ea7..07cf665 100644--- a/src/components/dashboard/Dashboard.tsx+++ b/src/components/dashboard/Dashboard.tsx@@ -557,10 +557,15 @@ export function Dashboard() {['Ctrl+G / Ctrl+Shift+G', 'Group / ungroup'],['Ctrl+A', 'Select all'],['Ctrl+L', 'Lock / unlock'],+ ['Ctrl+Alt+S', 'Save a version snapshot'],+ ['Shift+R', 'Show / hide rulers'],+ ['V', 'Select tool'],['Delete', 'Delete selection'],['Double-click text', 'Edit text inline'],+ ['Double-click layer', 'Rename a layer'],['Space + drag', 'Pan the canvas'],['Drag empty canvas', 'Marquee select'],+ ['Drag from ruler', 'Pull out a guide'],].map(([k, v]) => (<div key={k} className="flex items-center justify-between text-[12px]"><span className="text-white/70">{v}</span>@@ -576,6 +581,9 @@ export function Dashboard() {<li>· <b className="text-white/90">Brand</b> — colors, palettes, fonts & logos (saved locally)</li><li>· <b className="text-white/90">Apps</b> — charts, QR codes, icons, palettes & placeholder text</li><li>· <b className="text-white/90">Uploads</b> — drop images onto the canvas anytime</li>+ <li>· <b className="text-white/90">Layers</b> — rename (double-click), reorder, lock & hide</li>+ <li>· <b className="text-white/90">File menu</b> — rulers, version history & downloads</li>+ <li>· <b className="text-white/90">Crop</b> — select an image → Crop button or right-click</li></ul></div><adiff --git a/src/components/editor/CropDialog.tsx b/src/components/editor/CropDialog.tsxnew file mode 100644index 0000000..d198086--- /dev/null+++ b/src/components/editor/CropDialog.tsx@@ -0,0 +1,344 @@+'use client'++import { useMemo, useRef, useState } from 'react'+import { Crop, RotateCcw, Check } from 'lucide-react'+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { useEditorStore } from '@/store/editor-store'+import { useLoadedImage } from './canvas/use-loaded-image'+import type { ImageElement } from '@/lib/types'+import { cn } from '@/lib/utils'+import { toast } from '@/hooks/use-toast'++/** canva-style image crop: drag (or draw) a crop rect over the image, pick an aspect, apply. */++interface Rect { x: number; y: number; w: number; h: number }+type Handle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'move'++const ASPECTS: { id: string; label: string; ratio: number | null }[] = [+ { id: 'free', label: 'Free', ratio: null },+ { id: 'orig', label: 'Original', ratio: 0 }, // resolved per image+ { id: '1:1', label: '1:1', ratio: 1 },+ { id: '4:3', label: '4:3', ratio: 4 / 3 },+ { id: '3:4', label: '3:4', ratio: 3 / 4 },+ { id: '16:9', label: '16:9', ratio: 16 / 9 },+ { id: '9:16', label: '9:16', ratio: 9 / 16 },+ { id: '3:2', label: '3:2', ratio: 3 / 2 },+ { id: '2:3', label: '2:3', ratio: 2 / 3 },+]++const BOX_W = 540+const BOX_H = 350+const MIN_CROP = 16++export function CropDialog({ element, open, onOpenChange }: { element: ImageElement; open: boolean; onOpenChange: (o: boolean) => void }) {+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="rounded-[28px] bg-[#16181D] border-white/10 text-white sm:max-w-2xl">+ {/* keyed inner: every dialog open / image switch starts from a full frame */}+ {open && <CropDialogInner key={element.id} element={element} onClose={() => onOpenChange(false)} />}+ </DialogContent>+ </Dialog>+ )+}++function CropDialogInner({ element, onClose }: { element: ImageElement; onClose: () => void }) {+ const updateElements = useEditorStore((s) => s.updateElements)+ const image = useLoadedImage(element.src)++ const natW = image?.naturalWidth ?? (element.naturalWidth || 1)+ const natH = image?.naturalHeight ?? (element.naturalHeight || 1)++ // display scale: fit the image inside the dialog box+ const fit = useMemo(() => {+ const s = Math.min(BOX_W / natW, BOX_H / natH)+ return { w: Math.max(1, Math.round(natW * s)), h: Math.max(1, Math.round(natH * s)) }+ }, [natW, natH])++ const [rect, setRect] = useState<Rect>({ x: 0, y: 0, w: fit.w, h: fit.h })+ const [aspectId, setAspectId] = useState('free')+ const dragRef = useRef<{ handle: Handle; startX: number; startY: number; rect: Rect } | null>(null)++ const origRatio = natW / natH+ const aspect = aspectId === 'free' ? null : aspectId === 'orig' ? origRatio : (ASPECTS.find((a) => a.id === aspectId)?.ratio ?? null)++ const clampRect = (r: Rect): Rect => {+ const w = Math.min(fit.w, Math.max(MIN_CROP, r.w))+ const h = Math.min(fit.h, Math.max(MIN_CROP, r.h))+ return {+ w,+ h,+ x: Math.min(Math.max(0, r.x), fit.w - w),+ y: Math.min(Math.max(0, r.y), fit.h - h),+ }+ }++ const onHandleDown = (handle: Handle) => (e: React.PointerEvent) => {+ e.preventDefault()+ e.stopPropagation()+ dragRef.current = { handle, startX: e.clientX, startY: e.clientY, rect: { ...rect } }+ const base = dragRef.current.rect++ const onMove = (ev: PointerEvent) => {+ const dx = ev.clientX - dragRef.current!.startX+ const dy = ev.clientY - dragRef.current!.startY+ if (dragRef.current!.handle === 'move') {+ setRect(clampRect({ ...base, x: base.x + dx, y: base.y + dy }))+ return+ }+ let left = base.x+ let top = base.y+ let right = base.x + base.w+ let bottom = base.y + base.h+ if (handle.includes('w')) left = Math.min(right - MIN_CROP, base.x + dx)+ if (handle.includes('e')) right = Math.max(left + MIN_CROP, right + dx)+ if (handle.includes('n')) top = Math.min(bottom - MIN_CROP, base.y + dy)+ if (handle.includes('s')) bottom = Math.max(top + MIN_CROP, bottom + dy)+ if (aspect) {+ // keep the locked ratio anchored at the opposite edge+ const anchorX = handle.includes('w') ? right : left+ const anchorY = handle.includes('n') ? bottom : top+ let w = Math.max(MIN_CROP, Math.abs(right - left))+ let h = w / aspect+ if (h > fit.h) { h = fit.h; w = h * aspect }+ if (w > fit.w) { w = fit.w; h = w / aspect }+ left = handle.includes('w') ? anchorX - w : anchorX+ top = handle.includes('n') ? anchorY - h : anchorY+ right = left + w+ bottom = top + h+ }+ setRect(clampRect({ x: left, y: top, w: right - left, h: bottom - top }))+ }+ const onUp = () => {+ dragRef.current = null+ window.removeEventListener('pointermove', onMove)+ window.removeEventListener('pointerup', onUp)+ }+ window.addEventListener('pointermove', onMove)+ window.addEventListener('pointerup', onUp)+ }++ /** clicking outside the crop rect starts a brand-new rect (canva behaviour) */+ const onStageDown = (e: React.PointerEvent<HTMLDivElement>) => {+ if (e.button !== 0) return+ const r = e.currentTarget.getBoundingClientRect()+ const px = e.clientX - r.left+ const py = e.clientY - r.top+ const inside = px >= rect.x && px <= rect.x + rect.w && py >= rect.y && py <= rect.y + rect.h+ if (inside) {+ onHandleDown('move')(e)+ return+ }+ e.preventDefault()+ e.stopPropagation()+ const startX = px+ const startY = py+ const onMove = (ev: PointerEvent) => {+ const cx = ev.clientX - r.left+ const cy = ev.clientY - r.top+ if (aspect) {+ let w = Math.abs(cx - startX)+ let h = w / aspect+ if (h > fit.h) { h = fit.h; w = h * aspect }+ if (w > fit.w) { w = fit.w; h = w / aspect }+ setRect(clampRect({+ x: cx < startX ? startX - w : startX,+ y: cy < startY ? startY - h : startY,+ w,+ h,+ }))+ } else {+ setRect(clampRect({+ x: Math.min(startX, cx),+ y: Math.min(startY, cy),+ w: Math.abs(cx - startX),+ h: Math.abs(cy - startY),+ }))+ }+ }+ const onUp = () => {+ // a click without a real drag restores the full frame+ setRect((cur) => (cur.w < MIN_CROP || cur.h < MIN_CROP ? { x: 0, y: 0, w: fit.w, h: fit.h } : cur))+ window.removeEventListener('pointermove', onMove)+ window.removeEventListener('pointerup', onUp)+ }+ window.addEventListener('pointermove', onMove)+ window.addEventListener('pointerup', onUp)+ }++ const applyAspect = (id: string) => {+ setAspectId(id)+ const ratio = id === 'free' ? null : id === 'orig' ? origRatio : (ASPECTS.find((a) => a.id === id)?.ratio ?? null)+ if (ratio === null) return+ // largest centered rect with this ratio+ let w = fit.w+ let h = w / ratio+ if (h > fit.h) {+ h = fit.h+ w = h * ratio+ }+ setRect({ x: Math.round((fit.w - w) / 2), y: Math.round((fit.h - h) / 2), w: Math.round(w), h: Math.round(h) })+ }++ const reset = () => {+ setAspectId('free')+ setRect({ x: 0, y: 0, w: fit.w, h: fit.h })+ }++ const outW = Math.max(1, Math.round((rect.w / fit.w) * natW))+ const outH = Math.max(1, Math.round((rect.h / fit.h) * natH))++ const apply = () => {+ if (!image) return+ try {+ const scaleX = natW / fit.w+ const scaleY = natH / fit.h+ const cx = Math.max(0, Math.round(rect.x * scaleX))+ const cy = Math.max(0, Math.round(rect.y * scaleY))+ const cw = Math.min(natW - cx, Math.max(1, Math.round(rect.w * scaleX)))+ const ch = Math.min(natH - cy, Math.max(1, Math.round(rect.h * scaleY)))+ const out = document.createElement('canvas')+ out.width = cw+ out.height = ch+ const ctx = out.getContext('2d')+ if (!ctx) return+ ctx.imageSmoothingEnabled = true+ ctx.imageSmoothingQuality = 'high'+ // bake current flips into the cropped bitmap+ if (element.flipH) {+ ctx.translate(cw, 0)+ ctx.scale(-1, 1)+ }+ if (element.flipV) {+ ctx.translate(0, ch)+ ctx.scale(1, -1)+ }+ ctx.drawImage(image, cx, cy, cw, ch, 0, 0, cw, ch)+ const isJpeg = element.src.startsWith('data:image/jpeg')+ const src = isJpeg ? out.toDataURL('image/jpeg', 0.92) : out.toDataURL('image/png')+ // keep the on-canvas display scale of the kept region+ const displayScale = element.width / (element.naturalWidth || natW || 1)+ updateElements([element.id], {+ src,+ naturalWidth: cw,+ naturalHeight: ch,+ width: Math.max(4, Math.round(cw * displayScale)),+ height: Math.max(4, Math.round(ch * displayScale)),+ flipH: false,+ flipV: false,+ })+ onClose()+ toast({ title: 'Image cropped' })+ } catch {+ toast({ title: 'Could not crop this image', description: 'It may be from a site that blocks pixel access.' })+ }+ }++ const handles: { id: Handle; style: React.CSSProperties; cursor: string }[] = [+ { id: 'nw', style: { left: -6, top: -6 }, cursor: 'nwse-resize' },+ { id: 'n', style: { left: rect.w / 2 - 5, top: -6 }, cursor: 'ns-resize' },+ { id: 'ne', style: { right: -6, top: -6 }, cursor: 'nesw-resize' },+ { id: 'e', style: { right: -6, top: rect.h / 2 - 5 }, cursor: 'ew-resize' },+ { id: 'se', style: { right: -6, bottom: -6 }, cursor: 'nwse-resize' },+ { id: 's', style: { left: rect.w / 2 - 5, bottom: -6 }, cursor: 'ns-resize' },+ { id: 'sw', style: { left: -6, bottom: -6 }, cursor: 'nesw-resize' },+ { id: 'w', style: { left: -6, top: rect.h / 2 - 5 }, cursor: 'ew-resize' },+ ]++ return (+ <div className="flex flex-col items-center gap-3">+ <DialogHeader className="text-left w-full">+ <DialogTitle className="flex items-center gap-2">+ <Crop size={18} className="text-[#02C0CC]" /> Crop image+ </DialogTitle>+ <DialogDescription className="text-white/55">+ Drag the handles, or draw a brand-new area anywhere outside the current one — aspect presets lock the shape.+ </DialogDescription>+ </DialogHeader>++ <div className="flex flex-col items-center gap-3">+ {/* crop stage */}+ <div+ className="relative overflow-hidden rounded-xl bg-black/40 touch-none select-none"+ style={{ width: fit.w, height: fit.h, cursor: 'crosshair' }}+ onPointerDown={onStageDown}+ >+ {image && (+ <img+ src={element.src}+ alt="Crop source"+ draggable={false}+ className="absolute inset-0 pointer-events-none"+ style={{ width: fit.w, height: fit.h }}+ />+ )}+ {/* the crop rect's huge box-shadow dims everything around it */}+ <div+ className="absolute cursor-move"+ style={{+ left: rect.x,+ top: rect.y,+ width: rect.w,+ height: rect.h,+ boxShadow: '0 0 0 100000px rgba(0,0,0,0.55)',+ border: '1.5px solid #FFFFFF',+ }}+ >+ {/* rule-of-thirds hints */}+ <div className="absolute inset-0 pointer-events-none" style={{+ background:+ 'linear-gradient(to right, transparent calc(33.33% - 0.5px), rgba(255,255,255,0.25) 33.33%, transparent calc(33.33% + 0.5px)),' ++ 'linear-gradient(to right, transparent calc(66.66% - 0.5px), rgba(255,255,255,0.25) 66.66%, transparent calc(66.66% + 0.5px)),' ++ 'linear-gradient(to bottom, transparent calc(33.33% - 0.5px), rgba(255,255,255,0.25) 33.33%, transparent calc(33.33% + 0.5px)),' ++ 'linear-gradient(to bottom, transparent calc(66.66% - 0.5px), rgba(255,255,255,0.25) 66.66%, transparent calc(66.66% + 0.5px))',+ }} />+ {handles.map((h) => (+ <div+ key={h.id}+ onPointerDown={onHandleDown(h.id)}+ className="absolute w-[11px] h-[11px] rounded-[3px] bg-white border-2 border-[#7630D7] shadow"+ style={{ ...h.style, cursor: h.cursor, touchAction: 'none' }}+ aria-label={`Crop handle ${h.id}`}+ />+ ))}+ </div>+ </div>++ {/* aspect presets */}+ <div className="flex flex-wrap items-center justify-center gap-1.5">+ {ASPECTS.map((a) => (+ <button+ key={a.id}+ onClick={() => applyAspect(a.id)}+ className={cn(+ 'h-8 px-3 rounded-full text-[12px] font-semibold transition-colors',+ aspectId === a.id ? 'bg-[#7630D7] text-white' : 'bg-white/[0.08] text-white/75 hover:bg-white/[0.14]'+ )}+ >+ {a.label}+ </button>+ ))}+ </div>++ <div className="flex items-center justify-between w-full">+ <span className="text-[12px] text-white/55 font-medium tabular-nums">+ {outW} × {outH} px+ </span>+ <div className="flex items-center gap-2">+ <Button+ variant="ghost"+ size="sm"+ className="text-white/80 hover:bg-white/10 hover:text-white rounded-xl"+ onClick={reset}+ >+ <RotateCcw size={14} /> Reset+ </Button>+ <Button size="sm" className="btn-cv-white h-9 px-5 rounded-xl font-semibold" onClick={apply} disabled={!image}>+ <Check size={15} /> Apply crop+ </Button>+ </div>+ </div>+ </div>+ </div>+ )+}diff --git a/src/components/editor/Editor.tsx b/src/components/editor/Editor.tsxindex 263c015..7e78348 100644--- a/src/components/editor/Editor.tsx+++ b/src/components/editor/Editor.tsx@@ -22,10 +22,12 @@ import { AppsPanel } from './panels/AppsPanel'import { BackgroundPanel } from './panels/BackgroundPanel'import { LayersPanel } from './panels/LayersPanel'import { captureThumbnail, canvasBridge } from './canvas/canvas-bridge'+import { CropDialog } from './CropDialog'import { useIsMobile } from '@/hooks/use-mobile'import { Button } from '@/components/ui/button'import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'import { toast } from '@/hooks/use-toast'+import type { ImageElement } from '@/lib/types'const CanvasStage = dynamic(() => import('./canvas/CanvasStage'), { ssr: false })@@ -45,6 +47,7 @@ const PANEL_TITLES: Record<Exclude<PanelId, null>, string> = {const SHORTCUTS: [string, string][] = [['Ctrl + Z / Ctrl + Shift + Z', 'Undo / redo'],['Ctrl + S', 'Save design'],+ ['Ctrl + Alt + S', 'Save a version snapshot'],['Ctrl + D', 'Duplicate selection'],['Ctrl + C / X / V', 'Copy / cut / paste elements'],['Ctrl + G / Ctrl + Shift + G', 'Group / ungroup selection'],@@ -58,6 +61,10 @@ const SHORTCUTS: [string, string][] = [['Space + drag', 'Pan the canvas'],['Drag on empty canvas', 'Marquee (box) select'],['Double-click text', 'Edit text'],+ ['Double-click layer name', 'Rename layer'],+ ['V', 'Select tool'],+ ['Shift + R', 'Show / hide rulers'],+ ['Drag from a ruler', 'Pull out a guide line'],['Escape', 'Deselect / close'],['Ctrl + mouse wheel', 'Zoom at cursor'],]@@ -76,6 +83,15 @@ export default function Editor() {const [shortcutsOpen, setShortcutsOpen] = useState(false)const selectedIds = useEditorStore((s) => s.selectedIds)+ // v0.3.1: image crop dialog (opened from the toolbar or context menu)+ const cropTargetId = useEditorStore((s) => s.cropTargetId)+ const closeCrop = useEditorStore((s) => s.closeCrop)+ const cropPages = useEditorStore((s) => s.pages)+ const cropPageIdx = useEditorStore((s) => s.currentPage)+ const cropElement = cropTargetId+ ? (cropPages[cropPageIdx]?.elements.find((e) => e.id === cropTargetId && e.type === 'image') as ImageElement | undefined)+ : undefined+const loadedRef = useRef(false)// ── load pending design (from dashboard) ───────────────────@@ -154,6 +170,25 @@ export default function Editor() {}if (isTyping()) return+ // v0.3.1: Shift+R toggles rulers & guides+ if (!mod && e.shiftKey && e.key.toLowerCase() === 'r') {+ e.preventDefault()+ state.toggleRulers()+ return+ }+ // canva: V switches back to the select tool+ if (!mod && !e.shiftKey && !e.altKey && e.key.toLowerCase() === 'v') {+ state.setTool('select')+ return+ }+ // v0.3.1: Ctrl+Alt+S saves a version snapshot+ if (mod && e.altKey && (e.code === 'KeyS' || e.key.toLowerCase() === 's')) {+ e.preventDefault()+ state.saveVersion()+ toast({ title: 'Version saved' })+ return+ }+if (mod && e.key.toLowerCase() === 'z') {e.preventDefault()if (e.shiftKey) state.redo()@@ -354,6 +389,11 @@ export default function Editor() {<PreviewOverlay />+ {/* v0.3.1: image crop dialog */}+ {cropElement && (+ <CropDialog element={cropElement} open onOpenChange={(o) => { if (!o) closeCrop() }} />+ )}+<Dialog open={shortcutsOpen} onOpenChange={setShortcutsOpen}><DialogContent className="rounded-[28px] bg-[#16181D] border-white/10 text-white sm:max-w-sm"><DialogHeader>diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsxindex 3c2781f..6195582 100644--- a/src/components/editor/PropertiesBar.tsx+++ b/src/components/editor/PropertiesBar.tsx@@ -8,7 +8,7 @@ import {AlignVerticalJustifyStart, AlignVerticalJustifyCenter, AlignVerticalJustifyEnd,AlignHorizontalJustifyStart, AlignHorizontalJustifyCenter, AlignHorizontalJustifyEnd,FlipHorizontal, FlipVertical, Sun, Contrast, Palette, RotateCcw, Replace, Lock, LockOpen,- Layers, SquareDashed,+ Layers, SquareDashed, Crop,} from 'lucide-react'import { useEditorStore, selectedElements, currentPageData } from '@/store/editor-store'import type { ImageElement, LineElement, ShapeElement, StickerElement, TextElement, AnyElement } from '@/lib/types'@@ -285,6 +285,9 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm</>) : image ? (<>+ <TBtn onClick={() => state.openCrop(image.id)} title="Crop image" ariaLabel="Crop image">+ <Crop size={14} />+ </TBtn><ImageAdjustPopover el={image} ids={ids} /><Divider /><ColorMenu value="#FFFFFF" onChange={() => undefined} title="Filter tint (soon)" />diff --git a/src/components/editor/TopBar.tsx b/src/components/editor/TopBar.tsxindex 74b4679..002d949 100644--- a/src/components/editor/TopBar.tsx+++ b/src/components/editor/TopBar.tsx@@ -1,7 +1,7 @@'use client'import { useState } from 'react'-import { Home, MessageCircle, Play, Share2, ChevronDown, Undo2, Redo2, Download, Github, Cloud, Check, Loader2 } from 'lucide-react'+import { Home, MessageCircle, Play, Share2, ChevronDown, Undo2, Redo2, Download, Github, Cloud, Check, Loader2, Ruler, History } from 'lucide-react'import { useAppStore } from '@/store/app-store'import { useEditorStore } from '@/store/editor-store'import { Button } from '@/components/ui/button'@@ -10,6 +10,7 @@ import { cn } from '@/lib/utils'import { ExportDialog } from './ExportDialog'import { ResizeDialog } from './ResizeDialog'import { ShareDialog } from './ShareDialog'+import { VersionHistoryDialog } from './VersionHistoryDialog'import { ContextToolbar } from './PropertiesBar'/** Canva-2026 editor topbar: 56px cyan→purple gradient, white text, File/Resize/Editing left, Preview/Share right. */@@ -29,10 +30,13 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; oconst setPreviewOpen = useEditorStore((s) => s.setPreviewOpen)const setPanel = useEditorStore((s) => s.setPanel)const selectedIds = useEditorStore((s) => s.selectedIds)+ const showRulers = useEditorStore((s) => s.showRulers)+ const toggleRulers = useEditorStore((s) => s.toggleRulers)const [exportOpen, setExportOpen] = useState(false)const [resizeOpen, setResizeOpen] = useState(false)const [shareOpen, setShareOpen] = useState(false)+ const [versionsOpen, setVersionsOpen] = useState(false)const item = 'h-10 px-3 rounded-xl text-white/95 hover:bg-white/15 transition-colors text-sm font-semibold flex items-center gap-1.5 select-none'@@ -69,6 +73,13 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; o<DropdownMenuItem className="gap-2" onClick={() => setResizeOpen(true)}><Play size={15} /> Resize design</DropdownMenuItem>+ <DropdownMenuItem className="gap-2" onClick={toggleRulers}>+ <Ruler size={15} /> {showRulers ? 'Hide rulers' : 'Show rulers'}+ <span className="ml-auto text-[10px] text-white/40 font-semibold">⇧R</span>+ </DropdownMenuItem>+ <DropdownMenuItem className="gap-2" onClick={() => setVersionsOpen(true)}>+ <History size={15} /> Version history+ </DropdownMenuItem><DropdownMenuSeparator className="bg-white/10" /><DropdownMenuItem className="gap-2" onClick={() => setExportOpen(true)}><Download size={15} /> Download@@ -158,6 +169,7 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; o<ExportDialog open={exportOpen} onOpenChange={setExportOpen} /><ResizeDialog open={resizeOpen} onOpenChange={setResizeOpen} /><ShareDialog open={shareOpen} onOpenChange={setShareOpen} />+ <VersionHistoryDialog open={versionsOpen} onOpenChange={setVersionsOpen} /></header>)}diff --git a/src/components/editor/VersionHistoryDialog.tsx b/src/components/editor/VersionHistoryDialog.tsxnew file mode 100644index 0000000..120f774--- /dev/null+++ b/src/components/editor/VersionHistoryDialog.tsx@@ -0,0 +1,124 @@+'use client'++import { useState } from 'react'+import { History, RotateCcw, Trash2, Save, Layers } from 'lucide-react'+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { useEditorStore } from '@/store/editor-store'+import { cn } from '@/lib/utils'+import { toast } from '@/hooks/use-toast'++/** v0.3.1 — canva-style version history: save labelled snapshots of the design+ * (stored locally per design), restore or delete them at any time. */++function timeAgo(at: number): string {+ const s = Math.floor((Date.now() - at) / 1000)+ if (s < 45) return 'just now'+ const m = Math.floor(s / 60)+ if (m < 60) return `${m} min ago`+ const h = Math.floor(m / 60)+ if (h < 24) return `${h} h ago`+ const d = Math.floor(h / 24)+ if (d < 7) return `${d} day${d > 1 ? 's' : ''} ago`+ return new Date(at).toLocaleDateString()+}++export function VersionHistoryDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (o: boolean) => void }) {+ const versions = useEditorStore((s) => s.versions)+ const saveVersion = useEditorStore((s) => s.saveVersion)+ const restoreVersion = useEditorStore((s) => s.restoreVersion)+ const deleteVersion = useEditorStore((s) => s.deleteVersion)++ const [label, setLabel] = useState('')++ const save = () => {+ saveVersion(label)+ toast({ title: 'Version saved', description: label.trim() || undefined })+ setLabel('')+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="rounded-[28px] bg-[#16181D] border-white/10 text-white sm:max-w-md">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <History size={18} className="text-[#02C0CC]" /> Version history+ </DialogTitle>+ <DialogDescription className="text-white/55">+ Snapshots are stored in this browser for this design. Restoring keeps your current state on undo (Ctrl+Z).+ </DialogDescription>+ </DialogHeader>++ {/* save a new snapshot */}+ <div className="flex items-center gap-2">+ <input+ value={label}+ onChange={(e) => setLabel(e.target.value)}+ onKeyDown={(e) => e.key === 'Enter' && save()}+ placeholder={`Version ${versions.length + 1} — e.g. "before print"`}+ maxLength={40}+ className="flex-1 min-w-0 h-9 rounded-xl bg-white/[0.08] border border-white/10 px-3 text-[13px] placeholder:text-white/35 outline-none focus:border-[#7630D7]"+ aria-label="Version label"+ />+ <Button size="sm" className="btn-cv-white h-9 px-4 rounded-xl font-semibold shrink-0" onClick={save}>+ <Save size={14} /> Save+ </Button>+ </div>++ {/* version list */}+ <div className="max-h-80 overflow-y-auto cv-scroll-dark -mx-1 px-1">+ {versions.length === 0 && (+ <div className="text-center text-[13px] text-white/40 py-10">+ No versions yet.<br />+ Save one before a big change — you can always come back.+ </div>+ )}+ {versions.map((v, i) => (+ <div+ key={v.id}+ className={cn(+ 'group flex items-center gap-2.5 rounded-xl px-3 py-2.5',+ i === 0 ? 'bg-white/[0.05]' : 'hover:bg-white/[0.04]'+ )}+ >+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-[13px] font-semibold truncate">{v.label}</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">+ <Layers size={11} /> {v.pages.length} page{v.pages.length > 1 ? 's' : ''}+ <span className="text-white/25">·</span>+ {v.width} × {v.height}+ <span className="text-white/25">·</span>+ {timeAgo(v.at)}+ </div>+ </div>+ <Button+ variant="ghost"+ size="sm"+ className="h-8 px-3 rounded-lg text-white/85 hover:bg-white/10 hover:text-white text-[12px] font-semibold"+ onClick={() => {+ restoreVersion(v.id)+ toast({ title: `Restored “${v.label}”`, description: 'Ctrl+Z brings your previous state back.' })+ }}+ >+ <RotateCcw size={13} /> Restore+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className="h-8 w-8 rounded-lg text-white/50 hover:bg-red-500/20 hover:text-red-400 shrink-0"+ onClick={() => deleteVersion(v.id)}+ aria-label={`Delete version ${v.label}`}+ title="Delete version"+ >+ <Trash2 size={13} />+ </Button>+ </div>+ ))}+ </div>+ </DialogContent>+ </Dialog>+ )+}diff --git a/src/components/editor/apps/ChartsApp.tsx b/src/components/editor/apps/ChartsApp.tsxindex 3fae535..5ce4726 100644--- a/src/components/editor/apps/ChartsApp.tsx+++ b/src/components/editor/apps/ChartsApp.tsx@@ -32,13 +32,25 @@ export function ChartsApp({ onClose }: AppPanelProps) {function ChartRow({ icon: Icon, name, desc, onAdd }: { icon: typeof BarChart3; name: string; desc: string; onAdd: () => void }) {return (- <div className="flex items-center gap-3 rounded-xl border border-white/10 bg-white/[0.03] p-3 hover:border-[#7630D7] transition-colors">+ <div+ role="button"+ tabIndex={0}+ aria-label={`Add ${name}`}+ onClick={onAdd}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault()+ onAdd()+ }+ }}+ className="flex items-center gap-3 rounded-xl border border-white/10 bg-white/[0.03] p-3 hover:border-[#7630D7] transition-colors cursor-pointer focus:outline-none focus-visible:border-[#7630D7]"+ ><Icon size={18} className="text-[#02C0CC] shrink-0" /><div className="min-w-0 flex-1"><div className="text-[13px] font-semibold text-white">{name}</div><div className="text-[11px] text-white/45 truncate">{desc}</div></div>- <button className="btn-cv h-8 px-3.5 text-[11px] shrink-0" onClick={onAdd}>+ <button className="btn-cv h-8 px-3.5 text-[11px] shrink-0" onClick={(e) => { e.stopPropagation(); onAdd() }}>Add</button></div>diff --git a/src/components/editor/canvas/CanvasStage.tsx b/src/components/editor/canvas/CanvasStage.tsxindex f71f7e9..8943b4d 100644--- a/src/components/editor/canvas/CanvasStage.tsx+++ b/src/components/editor/canvas/CanvasStage.tsx@@ -8,6 +8,7 @@ import { useEditorStore, currentPageData } from '@/store/editor-store'import { gradientProps, computeSnap, clamp, type GuideLine } from '@/lib/editor-utils'import { canvasBridge } from './canvas-bridge'import { ElementNode } from './element-node'+import { Rulers } from './rulers'import type { TextElement } from '@/lib/types'import { createStrokeElement } from '@/lib/types'import { CanvasContextMenu, type ContextMenuState } from './context-menu'@@ -38,6 +39,12 @@ export default function CanvasStage() {const drawColor = useEditorStore((s) => s.drawColor)const drawSize = useEditorStore((s) => s.drawSize)const editingMode = useEditorStore((s) => s.editingMode)+ // v0.3.1: rulers & manual guides+ const showRulers = useEditorStore((s) => s.showRulers)+ const manualGuides = useEditorStore((s) => s.manualGuides)+ const addManualGuide = useEditorStore((s) => s.addManualGuide)+ const moveManualGuide = useEditorStore((s) => s.moveManualGuide)+ const removeManualGuide = useEditorStore((s) => s.removeManualGuide)const [containerSize, setContainerSize] = useState({ w: 0, h: 0 })const [pan, setPan] = useState({ x: 0, y: 0 })@@ -49,6 +56,8 @@ export default function CanvasStage() {/** marquee draft in PAGE coords */const [marquee, setMarquee] = useState<{ x0: number; y0: number; x1: number; y1: number } | null>(null)const [ctxMenu, setCtxMenu] = useState<ContextMenuState | null>(null)+ /** v0.3.1: guide being pulled out of a ruler (page coords) */+ const [draftGuide, setDraftGuide] = useState<{ axis: 'x' | 'y'; position: number } | null>(null)const drawingRef = useRef(false)const marqueeRef = useRef(false)const spaceRef = useRef(false)@@ -107,7 +116,8 @@ export default function CanvasStage() {// ── fit to screen ──────────────────────────────────────────const fitToScreen = useCallback(() => {if (containerSize.w < 50 || containerSize.h < 50) return- const z = Math.min((containerSize.w - 100) / width, (containerSize.h - 100) / height, 1.5)+ const pad = showRulers ? 128 : 100+ const z = Math.min((containerSize.w - pad) / width, (containerSize.h - pad) / height, 1.5)const clamped = Math.max(0.05, z)setZoom(clamped)prevZoomRef.current = clamped@@ -118,7 +128,7 @@ export default function CanvasStage() {prevPanRef.current = centeredsetPan(centered)userZoomedRef.current = false- }, [containerSize, width, height, setZoom])+ }, [containerSize, width, height, setZoom, showRulers])// fit on mount & on design size change & on resize (if user hasn't zoomed)useEffect(() => {@@ -205,6 +215,16 @@ export default function CanvasStage() {const others = p.elements.filter((e) => e.id !== id && e.visible).map((e) => ({ x: e.x, y: e.y, width: e.width, height: e.height, rotation: e.rotation }))+ // v0.3.1: manual guides act as snap targets (zero-size virtual edges)+ if (state.showRulers) {+ for (const g of state.manualGuides) {+ others.push(+ g.axis === 'x'+ ? { x: g.position, y: 0, width: 0, height: 0, rotation: 0 }+ : { x: 0, y: g.position, width: 0, height: 0, rotation: 0 }+ )+ }+ }const { dx, dy, guides: g } = computeSnap(rect, others, { width: state.width, height: state.height })if (dx !== 0 || dy !== 0) {node.x(node.x() + dx)@@ -281,6 +301,58 @@ export default function CanvasStage() {else clearSelection()}+ // ── v0.3.1: pull a guide out of a ruler ──────────────────+ const guideDragging = draftGuide !== null+ useEffect(() => {+ if (!guideDragging) return+ const onMove = (e: MouseEvent) => {+ const pt = pagePoint(e.clientX, e.clientY)+ if (!pt) return+ setDraftGuide((d) => (d ? { ...d, position: d.axis === 'x' ? pt.x : pt.y } : d))+ }+ const onUp = () => {+ setDraftGuide((d) => {+ if (d) {+ const limit = d.axis === 'x' ? width : height+ if (d.position > -30 && d.position < limit + 30) addManualGuide(d.axis, d.position)+ }+ return null+ })+ }+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') setDraftGuide(null)+ }+ window.addEventListener('mousemove', onMove)+ window.addEventListener('mouseup', onUp)+ window.addEventListener('keydown', onKey)+ return () => {+ window.removeEventListener('mousemove', onMove)+ window.removeEventListener('mouseup', onUp)+ window.removeEventListener('keydown', onKey)+ }+ }, [guideDragging, pan, zoom, width, height, addManualGuide])++ const beginGuideFromRuler = (axis: 'x' | 'y', pagePos: number) => {+ if (editingMode !== 'editing' || tool === 'draw') return+ clearSelection()+ setDraftGuide({ axis, position: pagePos })+ }++ /** commit / delete a manually-dragged guide line */+ const commitGuideDrag = (g: { id: string; axis: 'x' | 'y'; position: number }, node: Konva.Node) => {+ if (g.axis === 'x') {+ const nx = node.x()+ node.x(g.position) // restore; state drives the final position+ if (nx < -40 || nx > width + 40) removeManualGuide(g.id)+ else moveManualGuide(g.id, nx)+ } else {+ const ny = node.y()+ node.y(g.position)+ if (ny < -40 || ny > height + 40) removeManualGuide(g.id)+ else moveManualGuide(g.id, ny)+ }+ }+const handleStageMouseDown = (e: KonvaEventObject<MouseEvent>) => {if (editingMode !== 'editing') returnif (tool === 'draw') {@@ -575,6 +647,61 @@ export default function CanvasStage() {<Rect key={i} x={0} y={g.position} width={width} height={2 / zoom} fill={GUIDE_COLOR} listening={false} />))}+ {/* v0.3.1: manual ruler guides — draggable; double-click or drag off-page to delete */}+ {showRulers && manualGuides.map((g) =>+ g.axis === 'x' ? (+ <Line+ key={g.id}+ x={g.position}+ y={0}+ points={[0, -40, 0, height + 40]}+ stroke={GUIDE_COLOR}+ strokeWidth={1 / zoom}+ hitStrokeWidth={10 / zoom}+ draggable+ onDragMove={(e) => e.target.y(0)}+ onDragEnd={(e) => commitGuideDrag(g, e.target)}+ onDblClick={() => removeManualGuide(g.id)}+ onDblTap={() => removeManualGuide(g.id)}+ />+ ) : (+ <Line+ key={g.id}+ x={0}+ y={g.position}+ points={[-40, 0, width + 40, 0]}+ stroke={GUIDE_COLOR}+ strokeWidth={1 / zoom}+ hitStrokeWidth={10 / zoom}+ draggable+ onDragMove={(e) => e.target.x(0)}+ onDragEnd={(e) => commitGuideDrag(g, e.target)}+ onDblClick={() => removeManualGuide(g.id)}+ onDblTap={() => removeManualGuide(g.id)}+ />+ )+ )}+ {/* v0.3.1: guide currently being pulled from a ruler */}+ {draftGuide &&+ (draftGuide.axis === 'x' ? (+ <Line+ points={[draftGuide.position, -40, draftGuide.position, height + 40]}+ stroke={GUIDE_COLOR}+ strokeWidth={1 / zoom}+ dash={[6 / zoom, 4 / zoom]}+ opacity={0.85}+ listening={false}+ />+ ) : (+ <Line+ points={[-40, draftGuide.position, width + 40, draftGuide.position]}+ stroke={GUIDE_COLOR}+ strokeWidth={1 / zoom}+ dash={[6 / zoom, 4 / zoom]}+ opacity={0.85}+ listening={false}+ />+ ))}{/* marquee selection rect (canva: #7630D7 border, translucent fill) */}{marquee && (<Rect@@ -606,6 +733,19 @@ export default function CanvasStage() {</Stage>)}+ {/* v0.3.1: rulers overlay (desktop) */}+ {showRulers && containerSize.w > 0 && (+ <Rulers+ width={width}+ height={height}+ zoom={zoom}+ pan={pan}+ containerW={containerSize.w}+ containerH={containerSize.h}+ onGuideStart={beginGuideFromRuler}+ />+ )}+{/* canva-style right-click context menu */}{ctxMenu && (<CanvasContextMenudiff --git a/src/components/editor/canvas/context-menu.tsx b/src/components/editor/canvas/context-menu.tsxindex 268a0ba..3e2caad 100644--- a/src/components/editor/canvas/context-menu.tsx+++ b/src/components/editor/canvas/context-menu.tsx@@ -21,6 +21,8 @@ import {FilePlus2,Palette,MousePointerClick,+ Crop,+ Ruler,} from 'lucide-react'import { useEditorStore } from '@/store/editor-store'import { isGroup } from '@/lib/types'@@ -76,10 +78,16 @@ export function CanvasContextMenu({ state, onClose }: { state: ContextMenuState;(el) => selectedIds.includes(el.id) && !el.visible)+ // v0.3.1: crop entry applies to a single selected image+ const singleImage = selectedIds.length === 1+ ? store.pages[store.currentPage].elements.find((el) => el.id === selectedIds[0] && el.type === 'image')+ : undefined+const elementItems: Item[] = [{ label: 'Copy', icon: Copy, kbd: 'Ctrl+C', onSelect: () => store.copySelection() },{ label: 'Cut', icon: Scissors, kbd: 'Ctrl+X', onSelect: () => { store.cutSelection() } },{ label: 'Duplicate', icon: CopyPlus, kbd: 'Ctrl+D', onSelect: () => store.duplicateSelection() },+ ...(singleImage ? [{ label: 'Crop image', icon: Crop, onSelect: () => store.openCrop(singleImage.id) }] : []),Sep as unknown as Item,{ label: 'Bring to front', icon: BringToFront, onSelect: () => selectedIds.forEach((id) => store.moveLayer(id, 'front')) },{ label: 'Bring forward', icon: ArrowUpToLine, onSelect: () => selectedIds.forEach((id) => store.moveLayer(id, 'up')) },@@ -97,6 +105,9 @@ export function CanvasContextMenu({ state, onClose }: { state: ContextMenuState;const pageItems: Item[] = [{ label: 'Paste', icon: ClipboardPaste, kbd: 'Ctrl+V', onSelect: () => store.pasteClipboard() },{ label: 'Select all', icon: MousePointerClick, kbd: 'Ctrl+A', onSelect: () => store.setSelection(store.pages[store.currentPage].elements.filter((e) => !e.locked).map((e) => e.id)) },+ ...(store.manualGuides.length > 0+ ? [{ label: `Clear guides (${store.manualGuides.length})`, icon: Ruler, onSelect: () => store.clearManualGuides() }]+ : []),Sep as unknown as Item,{ label: 'Add page', icon: FilePlus2, onSelect: () => store.addPage() },{ label: 'Duplicate page', icon: SquareStack, onSelect: () => store.duplicatePage(store.currentPage) },diff --git a/src/components/editor/canvas/element-node.tsx b/src/components/editor/canvas/element-node.tsxindex cd08769..93f83ab 100644--- a/src/components/editor/canvas/element-node.tsx+++ b/src/components/editor/canvas/element-node.tsx@@ -188,7 +188,9 @@ export function ElementNode({ element: el, interactive, hiding, registerNode, on}if (el.type === 'group') {- // bake scale into children (children use page coords relative to group origin)+ // bake scale into children (children use page coords relative to group origin).+ // NOTE: children keep their own rotation — they render inside the rotated+ // Konva group, so adding node.rotation() here would double-rotate them.const g = el as GroupElementconst dx = node.x() - g.xconst dy = node.y() - g.y@@ -198,7 +200,6 @@ export function ElementNode({ element: el, interactive, hiding, registerNode, ony: Math.round(g.y + dy + (c.y - g.y) * sy),width: Math.max(4, c.width * sx),height: Math.max(4, c.height * sy),- rotation: (c.rotation + node.rotation()) % 360,}))store.updateElementsLive([el.id], {children,diff --git a/src/components/editor/canvas/rulers.tsx b/src/components/editor/canvas/rulers.tsxnew file mode 100644index 0000000..558153c--- /dev/null+++ b/src/components/editor/canvas/rulers.tsx@@ -0,0 +1,232 @@+'use client'++import { useEffect, useRef } from 'react'++/**+ * Canva-style rulers: a 22px strip along the top and left edges of the canvas+ * workspace. Drag from a ruler to pull out a manual guide; the small triangles+ * track the pointer position like Canva does.+ */++const RULER_BG = '#17181D'+const RULER_BORDER = 'rgba(255,255,255,0.10)'+const TICK_COLOR = 'rgba(255,255,255,0.38)'+const TICK_MINOR = 'rgba(255,255,255,0.16)'+const LABEL_COLOR = 'rgba(255,255,255,0.55)'+const MARKER_COLOR = '#9954FF'++/** choose a "nice" major-tick step so ticks land 60–140 screen px apart */+function niceStep(targetScreenPx: number): number {+ const raw = Math.max(1, targetScreenPx)+ const pow = Math.pow(10, Math.floor(Math.log10(raw)))+ for (const m of [1, 2, 5, 10]) {+ if (pow * m >= raw) return pow * m+ }+ return pow * 10+}++interface RulersProps {+ width: number // page width (px)+ height: number // page height (px)+ zoom: number+ pan: { x: number; y: number }+ containerW: number+ containerH: number+ /** ruler drag began — parent runs the guide-creation gesture */+ onGuideStart: (axis: 'x' | 'y', pagePos: number) => void+}++export function Rulers({ width, height, zoom, pan, containerW, containerH, onGuideStart }: RulersProps) {+ const topRef = useRef<HTMLCanvasElement>(null)+ const leftRef = useRef<HTMLCanvasElement>(null)+ const topMarkerRef = useRef<HTMLDivElement>(null)+ const leftMarkerRef = useRef<HTMLDivElement>(null)++ // ── draw the tick ladders ──────────────────────────────────+ useEffect(() => {+ const draw = (+ canvas: HTMLCanvasElement | null,+ size: number,+ horizontal: boolean+ ) => {+ if (!canvas) return+ const dpr = Math.min(window.devicePixelRatio || 1, 2)+ const px = Math.round(size * dpr)+ const thick = 22+ if (horizontal) {+ if (canvas.width !== px || canvas.height !== Math.round(thick * dpr)) {+ canvas.width = px+ canvas.height = Math.round(thick * dpr)+ }+ } else if (canvas.width !== Math.round(thick * dpr) || canvas.height !== px) {+ canvas.width = Math.round(thick * dpr)+ canvas.height = px+ }+ const ctx = canvas.getContext('2d')+ if (!ctx) return+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0)+ ctx.clearRect(0, 0, horizontal ? size : thick, horizontal ? thick : size)++ // background+ ctx.fillStyle = RULER_BG+ if (horizontal) ctx.fillRect(0, 0, size, thick)+ else ctx.fillRect(0, 0, thick, size)++ // page-range shading (outside the page the ruler reads slightly darker)+ const pageStart = horizontal ? pan.x : pan.y+ const pageLen = (horizontal ? width : height) * zoom+ ctx.fillStyle = 'rgba(255,255,255,0.03)'+ if (horizontal) {+ ctx.fillRect(0, 0, Math.max(0, pageStart), thick)+ ctx.fillRect(pageStart + pageLen, 0, Math.max(0, size - pageStart - pageLen), thick)+ } else {+ ctx.fillRect(0, 0, thick, Math.max(0, pageStart))+ ctx.fillRect(0, pageStart + pageLen, thick, Math.max(0, size - pageStart - pageLen))+ }++ // border line+ ctx.strokeStyle = RULER_BORDER+ ctx.lineWidth = 1+ ctx.beginPath()+ if (horizontal) {+ ctx.moveTo(0, thick - 0.5)+ ctx.lineTo(size, thick - 0.5)+ } else {+ ctx.moveTo(thick - 0.5, 0)+ ctx.lineTo(thick - 0.5, size)+ }+ ctx.stroke()++ // ticks+ const step = niceStep(72 / zoom)+ const minor = step / 5+ const pageOrigin = horizontal ? pan.x : pan.y+ const first = Math.ceil((-pageOrigin / zoom) / step) * step+ const last = ((size - pageOrigin) / zoom)++ // minor ticks+ ctx.strokeStyle = TICK_MINOR+ ctx.beginPath()+ for (let p = Math.ceil((-pageOrigin / zoom) / minor) * minor; p <= last; p += minor) {+ const s = pageOrigin + p * zoom+ if (horizontal) {+ ctx.moveTo(Math.round(s) + 0.5, thick - 4)+ ctx.lineTo(Math.round(s) + 0.5, thick)+ } else {+ ctx.moveTo(thick - 4, Math.round(s) + 0.5)+ ctx.lineTo(thick, Math.round(s) + 0.5)+ }+ }+ ctx.stroke()++ // major ticks + labels+ ctx.strokeStyle = TICK_COLOR+ ctx.fillStyle = LABEL_COLOR+ ctx.font = '9px Inter, system-ui, sans-serif'+ ctx.textBaseline = 'top'+ ctx.beginPath()+ for (let p = first; p <= last; p += step) {+ const s = pageOrigin + p * zoom+ if (s < -20 || s > size + 20) continue+ if (horizontal) {+ ctx.moveTo(Math.round(s) + 0.5, 6)+ ctx.lineTo(Math.round(s) + 0.5, thick)+ } else {+ ctx.moveTo(6, Math.round(s) + 0.5)+ ctx.lineTo(thick, Math.round(s) + 0.5)+ }+ }+ ctx.stroke()+ for (let p = first; p <= last; p += step) {+ const s = pageOrigin + p * zoom+ if (s < 14 || s > size - 14) continue+ const label = String(Math.round(p))+ if (horizontal) {+ ctx.fillText(label, s + 3, 3)+ } else {+ ctx.save()+ ctx.translate(4, s + 3)+ ctx.fillText(label, 0, 0)+ ctx.restore()+ }+ }+ }++ draw(topRef.current, containerW, true)+ draw(leftRef.current, containerH, false)+ }, [width, height, zoom, pan, containerW, containerH])++ // ── pointer-follow markers (little canva triangles) ─────────+ useEffect(() => {+ const container = topRef.current?.parentElement+ if (!container) return+ const onMove = (e: MouseEvent) => {+ const r = container.getBoundingClientRect()+ const t = topMarkerRef.current+ const l = leftMarkerRef.current+ if (t) {+ t.style.opacity = e.clientX - r.left >= 22 ? '1' : '0'+ t.style.transform = `translateX(${e.clientX - r.left - 5}px)`+ }+ if (l) {+ l.style.opacity = e.clientY - r.top >= 22 ? '1' : '0'+ l.style.transform = `translateY(${e.clientY - r.top - 5}px)`+ }+ }+ const onLeave = () => {+ if (topMarkerRef.current) topMarkerRef.current.style.opacity = '0'+ if (leftMarkerRef.current) leftMarkerRef.current.style.opacity = '0'+ }+ window.addEventListener('mousemove', onMove)+ container.addEventListener('mouseleave', onLeave)+ return () => {+ window.removeEventListener('mousemove', onMove)+ container.removeEventListener('mouseleave', onLeave)+ }+ }, [])++ const beginGuide = (axis: 'x' | 'y', e: React.MouseEvent<HTMLCanvasElement>) => {+ const container = (e.currentTarget.parentElement as HTMLElement)?.getBoundingClientRect()+ if (!container) return+ const pagePos =+ axis === 'y'+ ? (e.clientX - container.left - pan.x) / zoom // horizontal guide from the TOP ruler+ : (e.clientY - container.top - pan.y) / zoom // vertical guide from the LEFT ruler+ onGuideStart(axis, pagePos)+ }++ return (+ <div className="absolute inset-0 z-20 pointer-events-none" aria-hidden={false}>+ {/* corner */}+ <div+ className="absolute top-0 left-0 pointer-events-auto"+ style={{ width: 22, height: 22, background: RULER_BG, borderRight: `1px solid ${RULER_BORDER}`, borderBottom: `1px solid ${RULER_BORDER}` }}+ />+ {/* top ruler — pulls horizontal guides */}+ <canvas+ ref={topRef}+ className="absolute top-0 pointer-events-auto cursor-row-resize hidden md:block"+ style={{ left: 22, width: containerW - 22, height: 22 }}+ onMouseDown={(e) => beginGuide('y', e)}+ aria-label="Horizontal ruler — drag to create a guide"+ role="toolbar"+ />+ {/* left ruler — pulls vertical guides */}+ <canvas+ ref={leftRef}+ className="absolute left-0 pointer-events-auto cursor-col-resize hidden md:block"+ style={{ top: 22, width: 22, height: containerH - 22 }}+ onMouseDown={(e) => beginGuide('x', e)}+ aria-label="Vertical ruler — drag to create a guide"+ role="toolbar"+ />+ {/* pointer markers */}+ <div ref={topMarkerRef} className="absolute top-[15px] left-[27px] pointer-events-none transition-opacity" style={{ opacity: 0 }}>+ <div style={{ width: 0, height: 0, borderLeft: '5px solid transparent', borderRight: '5px solid transparent', borderTop: `6px solid ${MARKER_COLOR}` }} />+ </div>+ <div ref={leftMarkerRef} className="absolute top-[27px] left-[15px] pointer-events-none transition-opacity" style={{ opacity: 0 }}>+ <div style={{ width: 0, height: 0, borderTop: '5px solid transparent', borderBottom: '5px solid transparent', borderLeft: `6px solid ${MARKER_COLOR}` }} />+ </div>+ </div>+ )+}diff --git a/src/components/editor/panels/AppsPanel.tsx b/src/components/editor/panels/AppsPanel.tsxindex 56fe646..18b5166 100644--- a/src/components/editor/panels/AppsPanel.tsx+++ b/src/components/editor/panels/AppsPanel.tsx@@ -52,7 +52,19 @@ function AppCard({ app, onOpen }: { app: CanvixApp; onOpen: () => void }) {onOpen()}return (- <div className="rounded-xl border border-white/10 bg-white/[0.03] p-3 hover:border-[#7630D7] transition-colors flex flex-col">+ <div+ role="button"+ tabIndex={0}+ aria-label={`Open ${app.name} app`}+ onClick={handleClick}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault()+ handleClick()+ }+ }}+ className="rounded-xl border border-white/10 bg-white/[0.03] p-3 hover:border-[#7630D7] transition-colors flex flex-col cursor-pointer focus:outline-none focus-visible:border-[#7630D7]"+ ><div className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0" style={{ background: `${app.color}22` }}><Icon size={20} style={{ color: app.color }} /></div>@@ -60,7 +72,10 @@ function AppCard({ app, onOpen }: { app: CanvixApp; onOpen: () => void }) {<div className="text-[11px] text-white/45 leading-tight flex-1">{app.desc}</div><buttonclassName={cn('mt-2.5 h-8 rounded-lg text-[11px] font-semibold flex items-center justify-center gap-1 transition-colors', soon ? 'bg-white/5 text-white/40' : 'bg-[#7630D7] hover:bg-[#8B5CF6] text-white')}- onClick={handleClick}+ onClick={(e) => {+ e.stopPropagation()+ handleClick()+ }}>{soon ? 'Soon' : 'Open'} {!soon && <ArrowRight size={11} />}</button>diff --git a/src/components/editor/panels/LayersPanel.tsx b/src/components/editor/panels/LayersPanel.tsxindex fcbe4f8..182b9b1 100644--- a/src/components/editor/panels/LayersPanel.tsx+++ b/src/components/editor/panels/LayersPanel.tsx@@ -1,6 +1,7 @@'use client'-import { ChevronUp, ChevronDown, ChevronsUp, ChevronsDown, Lock, LockOpen, Eye, EyeOff, Trash2, Type, Image as ImageIcon, Square, Minus, Smile, PenTool } from 'lucide-react'+import { useState } from 'react'+import { ChevronUp, ChevronDown, ChevronsUp, ChevronsDown, Lock, LockOpen, Eye, EyeOff, Trash2, Type, Image as ImageIcon, Square, Minus, Smile, PenTool, Group as GroupIcon } from 'lucide-react'import { useEditorStore, currentPageData } from '@/store/editor-store'import { cn } from '@/lib/utils'import type { AnyElement } from '@/lib/types'@@ -13,17 +14,20 @@ function elementIcon(el: AnyElement) {case 'stroke': return PenToolcase 'sticker': return Smilecase 'path': return PenTool+ case 'group': return GroupIcondefault: return Square}}function elementLabel(el: AnyElement): string {+ if (el.name) return el.nameif (el.type === 'text') return (el.text || 'Text').slice(0, 26) || 'Text'if (el.type === 'sticker') return `Sticker ${el.char}`if (el.type === 'image') return 'Image'if (el.type === 'line') return 'Line'if (el.type === 'stroke') return 'Stroke'if (el.type === 'path') return 'Graphic'+ if (el.type === 'group') return 'Group'return el.type.charAt(0).toUpperCase() + el.type.slice(1)}@@ -36,6 +40,18 @@ export function LayersPanel() {const setLock = useEditorStore((s) => s.setLock)const setVisible = useEditorStore((s) => s.setVisible)const deleteSelection = useEditorStore((s) => s.deleteSelection)+ const updateElements = useEditorStore((s) => s.updateElements)++ /** v0.3.1: inline rename — double-click a layer name to edit it */+ const [renaming, setRenaming] = useState<{ id: string; value: string } | null>(null)++ const commitRename = () => {+ if (!renaming) return+ const value = renaming.value.trim()+ // an empty name falls back to the auto label (undefined)+ updateElements([renaming.id], { name: value || undefined })+ setRenaming(null)+ }const page = currentPageData({ pages, currentPage })// render top layer first@@ -64,7 +80,34 @@ export function LayersPanel() {onClick={() => setSelection([el.id])}><Icon size={15} className="shrink-0" />- <span className={cn('flex-1 truncate', !el.visible && 'opacity-40')}>{elementLabel(el)}</span>+ {renaming?.id === el.id ? (+ <input+ autoFocus+ value={renaming.value}+ onChange={(e) => setRenaming((r) => (r ? { ...r, value: e.target.value } : r))}+ onBlur={commitRename}+ onClick={(e) => e.stopPropagation()}+ onKeyDown={(e) => {+ e.stopPropagation()+ if (e.key === 'Enter') commitRename()+ if (e.key === 'Escape') setRenaming(null)+ }}+ className="flex-1 min-w-0 bg-white/10 border border-[#7630D7] rounded-md px-1.5 py-0.5 text-[13px] outline-none"+ aria-label="Layer name"+ maxLength={60}+ />+ ) : (+ <span+ className={cn('flex-1 truncate', !el.visible && 'opacity-40')}+ title="Double-click to rename"+ onDoubleClick={(e) => {+ e.stopPropagation()+ setRenaming({ id: el.id, value: el.name ?? elementLabel(el) })+ }}+ >+ {elementLabel(el)}+ </span>+ )}<div className="hidden group-hover:flex items-center gap-0.5"><button className="h-6 w-6 flex items-center justify-center rounded hover:bg-white/10" title="Bring to front" aria-label="Bring to front" onClick={(e) => { e.stopPropagation(); moveLayer(el.id, 'front') }}>diff --git a/src/lib/types.ts b/src/lib/types.tsindex 647f14e..a06170a 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -53,6 +53,8 @@ export interface BaseElement {locked: booleanvisible: booleanshadow: ShadowConfig+ /** user-facing layer name (Layers panel; falls back to an auto label) */+ name?: string}export interface TextElement extends BaseElement {@@ -172,6 +174,24 @@ export interface PageData {elements: AnyElement[]}+/** user-placed ruler guide (position in page px) */+export interface ManualGuide {+ id: string+ axis: 'x' | 'y'+ position: number+}++/** saved version snapshot (per design, persisted to localStorage) */+export interface DesignVersion {+ id: string+ label: string+ at: number+ name: string+ width: number+ height: number+ pages: PageData[]+}+export interface DesignSnapshot {// A full serializable design state (also what gets saved to DB)name: stringdiff --git a/src/store/editor-store.ts b/src/store/editor-store.tsindex 6415246..6fbbec2 100644--- a/src/store/editor-store.ts+++ b/src/store/editor-store.ts@@ -9,6 +9,8 @@ import {createGroupElement,DEFAULT_BRAND,type DesignRecord,+ type DesignVersion,+ type ManualGuide,type PageData,} from '@/lib/types'import type { TemplateDef } from '@/lib/templates'@@ -61,6 +63,26 @@ interface EditorState {drawSize: numberbrand: BrandKit+ // v0.3.1: rulers & manual guides+ showRulers: boolean+ manualGuides: ManualGuide[]+ toggleRulers: () => void+ addManualGuide: (axis: 'x' | 'y', position: number) => string+ moveManualGuide: (id: string, position: number) => void+ removeManualGuide: (id: string) => void+ clearManualGuides: () => void++ // v0.3.1: version history (per design, localStorage-persisted)+ versions: DesignVersion[]+ saveVersion: (label?: string) => void+ restoreVersion: (id: string) => void+ deleteVersion: (id: string) => void++ // v0.3.1: image crop dialog target (set from context menu / toolbar)+ cropTargetId: string | null+ openCrop: (id: string) => void+ closeCrop: () => void+// lifecycleloadDesign: (d: DesignRecord) => voidrename: (name: string) => void@@ -156,7 +178,12 @@ export const useEditorStore = create<EditorState>((set, get) => ({drawSize: 6,brand: DEFAULT_BRAND,- loadDesign: (d) =>+ showRulers: false,+ manualGuides: [],+ versions: [],+ cropTargetId: null,++ loadDesign: (d) => {set({designId: d.id,designName: d.name,@@ -173,7 +200,11 @@ export const useEditorStore = create<EditorState>((set, get) => ({saving: false,previewOpen: false,tool: 'select',- }),+ cropTargetId: null,+ })+ // v0.3.1: load any locally-persisted versions for this design+ set({ versions: loadVersions(d.id) })+ },rename: (name) => set({ designName: name, dirty: true }),@@ -348,8 +379,27 @@ export const useEditorStore = create<EditorState>((set, get) => ({for (const g of groups) {if (g.type !== 'group') continuenext[currentPage].elements = next[currentPage].elements.filter((e) => e.id !== g.id)- next[currentPage].elements.push(...g.children.map((c) => ({ ...clone(c) })))- released = [...released, ...g.children.map((c) => c.id)]+ // v0.3.1: children live in the group's local (unrotated) space — when the+ // group has a rotation, orbit each child around the group origin and pass+ // the rotation on, so nothing jumps on ungroup.+ const rad = ((g.rotation || 0) * Math.PI) / 180+ const cos = Math.cos(rad)+ const sin = Math.sin(rad)+ const releasedEls = g.children.map((c) => {+ if (!rad) return { ...clone(c) }+ const cx = c.x + c.width / 2 - g.x+ const cy = c.y + c.height / 2 - g.y+ const nx = g.x + cx * cos - cy * sin - c.width / 2+ const ny = g.y + cx * sin + cy * cos - c.height / 2+ return {+ ...clone(c),+ x: Math.round(nx),+ y: Math.round(ny),+ rotation: (c.rotation + (g.rotation || 0)) % 360,+ }+ })+ next[currentPage].elements.push(...releasedEls)+ released = [...released, ...releasedEls.map((c) => c.id)]}set({ pages: next, selectedIds: released })},@@ -454,6 +504,63 @@ export const useEditorStore = create<EditorState>((set, get) => ({setDrawSize: (n) => set({ drawSize: Math.min(64, Math.max(1, n)) }),setBrand: (b) => set({ brand: b }),+ // ── v0.3.1: rulers & manual guides ─────────────────────+ toggleRulers: () => set({ showRulers: !get().showRulers }),+ addManualGuide: (axis, position) => {+ const id = uid('guide')+ set({ manualGuides: [...get().manualGuides, { id, axis, position: Math.round(position) }] })+ return id+ },+ moveManualGuide: (id, position) => {+ set({+ manualGuides: get().manualGuides.map((g) => (g.id === id ? { ...g, position: Math.round(position) } : g)),+ })+ },+ removeManualGuide: (id) => set({ manualGuides: get().manualGuides.filter((g) => g.id !== id) }),+ clearManualGuides: () => set({ manualGuides: [] }),++ // ── v0.3.1: version history ────────────────────────────+ saveVersion: (label) => {+ const { designId, designName, width, height, pages, versions } = get()+ if (!designId) return+ const v: DesignVersion = {+ id: uid('ver'),+ label: label?.trim() || `Version ${versions.length + 1}`,+ at: Date.now(),+ name: designName,+ width,+ height,+ pages: clone(pages),+ }+ const next = [v, ...versions].slice(0, 30) // keep the 30 most recent+ set({ versions: next })+ persistVersions(designId, next)+ },+ restoreVersion: (id) => {+ const v = get().versions.find((x) => x.id === id)+ if (!v) return+ get().pushHistory()+ set({+ pages: clone(v.pages),+ width: v.width,+ height: v.height,+ designName: v.name,+ currentPage: 0,+ selectedIds: [],+ dirty: true,+ })+ },+ deleteVersion: (id) => {+ const { designId, versions } = get()+ const next = versions.filter((v) => v.id !== id)+ set({ versions: next })+ if (designId) persistVersions(designId, next)+ },++ // v0.3.1: image crop dialog+ openCrop: (id) => set({ cropTargetId: id }),+ closeCrop: () => set({ cropTargetId: null }),+resizeDesign: (width, height) => {get().pushHistory()const { pages } = get()@@ -483,3 +590,50 @@ export function currentPageData(s: Pick<EditorState, 'pages' | 'currentPage'>):export function selectedElements(s: Pick<EditorState, 'pages' | 'currentPage' | 'selectedIds'>): AnyElement[] {return currentPageData(s).elements.filter((e) => s.selectedIds.includes(e.id))}++// ── v0.3.1: version persistence (localStorage, per design) ──++const VERSIONS_KEY = (designId: string) => `canvix-versions-${designId}`+const VERSIONS_LIMIT_JSON = 4.5 * 1024 * 1024 // ~4.5 MB safety budget++function loadVersions(designId: string): DesignVersion[] {+ try {+ const raw = localStorage.getItem(VERSIONS_KEY(designId))+ if (!raw) return []+ const parsed = JSON.parse(raw)+ return Array.isArray(parsed) ? (parsed as DesignVersion[]) : []+ } catch {+ return []+ }+}++function persistVersions(designId: string, versions: DesignVersion[]) {+ try {+ // guard against quota errors: drop oldest versions until we fit+ let list = versions+ while (list.length > 1) {+ try {+ localStorage.setItem(VERSIONS_KEY(designId), JSON.stringify(list))+ return+ } catch {+ list = list.slice(0, -1)+ }+ }+ localStorage.setItem(VERSIONS_KEY(designId), JSON.stringify(list))+ } catch {+ /* localStorage unavailable (private mode) — versions stay in memory */+ }+}++/** drop stored versions above the size budget (called after big saves) */+export function pruneVersionsIfNeeded(designId: string) {+ try {+ const raw = localStorage.getItem(VERSIONS_KEY(designId))+ if (raw && raw.length > VERSIONS_LIMIT_JSON) {+ const list = (JSON.parse(raw) as DesignVersion[]).slice(0, -1)+ persistVersions(designId, list)+ }+ } catch {+ /* ignore */+ }+}