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.14): even distribution — one pure geometry module (src/lib/distribute.ts) + a real store action (single undo step, fresh HLC stamps, one collab page:replace), Position popover Spacing H/V tiles for >=3 selections, assistant/plugin path now rides the same action (old inline math measured the span off by the last box's size and refused overlapping selections — Canva/Figma distribute those), 9 geometry unit tests + 2 anonymous e2e specs, README gains the missing D4 filters checkbox too (D3)
Ashiq Hussain Mirf398550bfdee
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 867d587..c6eaf04 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,47 @@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.14.5] — 2026-11-05++### Added++- **Daily-driver depth, part 6 — even distribution (D3).** Select+ three or more elements and space them evenly, the Canva/Figma+ "spacing" behaviour: equal gaps between element edges, the outermost+ elements stay exactly where they were.+ - **One pure geometry module** — `src/lib/distribute.ts` holds the+ distribution math (edge-gap semantics, floats walked with integer+ output so rounding never drifts); the store action, the AI+ assistant path and the unit tests all share it. Geometry uses the+ element's local box, the same documented simplification the+ page-align modes use.+ - **A real store action** — `distributeElements` follows the+ `alignElements` house pattern: ONE history entry (one undo step —+ the old assistant path did one `updateElements` per element),+ fresh HLC stamps on touched elements only, one collab+ `page:replace` broadcast.+ - **Position popover tiles** — a "Distribute" section with+ Spacing H / Spacing V appears when three or more elements are+ selected (hidden below the threshold where there is nothing to+ space evenly).+ - **Assistant + plugin parity** — the `distributeElements` agent+ action (already in the Assistant vocabulary and the plugin+ allowlist) now rides the same store action and geometry. Two+ honest fixes came with it: the old inline math measured the span+ to the last box's *leading* edge (off by its size — gaps were+ uneven for unequal elements), and it refused overlapping+ selections outright; Canva and Figma distribute those (the+ overlap is evened out), and now Canvix does too.+ - **Fixed** while auditing the README roadmap: the v0.14 checklist+ was missing its image-filters entry (shipped as 0.14.3) — added.++### Changed++- The `distributeElements` AI/plugin action no longer refuses+ overlapping selections with "Elements overlap — no distribution+ applied"; it distributes them evenly (Canva/Figma behaviour) and+ reports success.+## [0.14.4] — 2026-11-05### Addeddiff --git a/README.md b/README.mdindex 3ed6895..67ec6d7 100644--- a/README.md+++ b/README.md@@ -992,6 +992,27 @@ tool descriptions so agents pick the right format.`update_element`. While wiring the video exporter, tables,frames and embed cards stopped vanishing from video exports(a pre-existing parity gap) *(v0.14.4)*+- [x] Image filters (v0.14 D4) — a preset gallery on every image:+ grayscale / warm / cool / vintage / blur / sharpen / vignette+ with an intensity slider and live thumbnail previews. One pure+ pixel pipeline feeds the editor (Konva filters on the existing+ cache rail), the video exporter (bit-exact pre-bake + images+ finally export flip/rotation) and the SVG exporter+ (feComponentTransfer / feColorMatrix / feConvolveMatrix / exact-+ variance feGaussianBlur equivalents, approximations documented).+ Adjustments and filters persist in the element, pasted images+ validate filter ids + clamp intensity, and MCP image patches+ accept the new fields *(v0.14.3)*+- [x] Even distribute (v0.14 D3) — select ≥ 3 elements and space+ them evenly (Canva/Figma "spacing"): equal gaps between edges,+ extremes fixed, one undo step. One pure geometry module+ (`src/lib/distribute.ts`) powers the Position popover's new+ Spacing H/V tiles, the store action (fresh HLC stamps on+ touched elements only, one collab `page:replace`) and the+ AI/plugin `distributeElements` action — whose old inline math+ measured the span off by the last box's size and refused+ overlapping selections (Canva/Figma distribute those; now so+ does Canvix) *(v0.14.5)*- [ ] Mobile editor polish — touch-first selection handles, gesturezoom/pan without modifier keys, bottom-sheet property panels(the responsive groundwork from v0.11.3 makes this tractable)@@ -1001,7 +1022,8 @@ landscape research, prioritized epics with effort estimates, riskregister) lives in `research/V0118-ROADMAP-RESEARCH.md`. The arc:**v0.12** trust & rails (CI gate, security headers, rate limits, opsrunbook) → **v0.13** plugin system MVP → **v0.14** daily-driver editor-depth (persistent uploads, clipboard, folders, filters, charts) →+depth (persistent uploads, clipboard, folders, filters, charts,+distribute) →**v0.15** rich content & export (rich text, WebCodecs video, vectorPDF) → **v0.16** mobile & collaboration scale (touch-first editing,LISTEN/NOTIFY fan-out) → **v1.0** = every promise on this page shippeddiff --git a/package.json b/package.jsonindex 9b5dd92..d417e33 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.14.4",+ "version": "0.14.5","private": false,"description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsxindex a9cf4b8..4ce21e6 100644--- a/src/components/editor/PropertiesBar.tsx+++ b/src/components/editor/PropertiesBar.tsx@@ -7,6 +7,7 @@ import {Group, Ungroup, ArrowUpToLine, ArrowDownToLine, BringToFront, SendToBack,AlignVerticalJustifyStart, AlignVerticalJustifyCenter, AlignVerticalJustifyEnd,AlignHorizontalJustifyStart, AlignHorizontalJustifyCenter, AlignHorizontalJustifyEnd,+ AlignHorizontalDistributeCenter, AlignVerticalDistributeCenter,FlipHorizontal, FlipVertical, Sun, Contrast, Palette, RotateCcw, Replace, Lock, LockOpen,Layers, SquareDashed, Crop, Spline, Table2, Rows3, Columns3, Trash, Upload, ExternalLink,Music, Film, Play, Repeat, Volume2, VolumeX, SlidersHorizontal, Activity, Puzzle, LayoutGrid, Wand2,@@ -753,6 +754,16 @@ function PositionPopover({ ids, count, element }: { ids: string[]; count: number</div></div>+ {count >= 3 && (+ <div className="border-t border-white/[0.08] pt-2 mb-2.5">+ <div className="text-[10px] font-semibold text-white/45 uppercase tracking-wide mb-1.5">Distribute</div>+ <div className="grid grid-cols-3 gap-1">+ <IconTile icon={<AlignHorizontalDistributeCenter size={15} />} label="Spacing H" onClick={() => store.distributeElements(ids, 'x')} />+ <IconTile icon={<AlignVerticalDistributeCenter size={15} />} label="Spacing V" onClick={() => store.distributeElements(ids, 'y')} />+ </div>+ </div>+ )}+{count === 1 && el && (<div className="border-t border-white/[0.08] pt-2"><div className="text-[10px] font-semibold text-white/45 uppercase tracking-wide mb-1.5">Advanced</div>diff --git a/src/lib/design-actions.ts b/src/lib/design-actions.tsindex 26a11d2..bbfabbf 100644--- a/src/lib/design-actions.ts+++ b/src/lib/design-actions.ts@@ -323,22 +323,16 @@ export async function applyDesignAction(action: DesignAction, caller?: ActionCalconst ids = resolveIds(action.ids)if (ids.length < 3) return 'Needs at least 3 elements'const axis = String(action.axis) === 'y' ? 'y' : 'x'+ // v0.14 (D3): one store action = one undo step + one collab+ // broadcast, sharing the same pure geometry as the toolbar+ // tiles. The old inline loop did N updateElements (N undo+ // steps), computed the span against the last box's LEADING+ // edge (off by its size) and refused overlapping selections —+ // Canva/Figma distribute those; now we do too.+ useEditorStore.getState().distributeElements(ids, axis)const page = currentPageElements()- const els = page.filter((e) => ids.includes(e.id)).sort((a, b) => (axis === 'x' ? a.x - b.x : a.y - b.y))- const first = els[0]- const last = els[els.length - 1]- const start = axis === 'x' ? first.x : first.y- const end = axis === 'x' ? last.x : last.y- const sizes = els.reduce((sum, e) => sum + (axis === 'x' ? e.width : e.height), 0)- const gap = (end - start - sizes) / (els.length - 1)- if (gap < 0) return 'Elements overlap — no distribution applied'- let cursor = start- for (const el of els) {- const patch = axis === 'x' ? { x: Math.round(cursor) } : { y: Math.round(cursor) }- useEditorStore.getState().updateElements([el.id], patch)- cursor += (axis === 'x' ? el.width : el.height) + gap- }- return `Distributed ${els.length} elements evenly`+ const moved = page.filter((e) => ids.includes(e.id)).length+ return moved < 3 ? 'Needs at least 3 elements on this page' : `Distributed ${moved} elements evenly`}case 'addPage':diff --git a/src/lib/distribute.test.ts b/src/lib/distribute.test.tsnew file mode 100644index 0000000..985d0ba--- /dev/null+++ b/src/lib/distribute.test.ts@@ -0,0 +1,122 @@+// ─────────────────────────────────────────────────────────────+// v0.14 (D3): even-distribution geometry — the acceptance suite.+//+// 1. < 3 boxes = no-op (nothing to space evenly)+// 2. equal boxes: gaps come out equal, extremes stay fixed+// 3. unequal boxes: gaps still equal (that IS the contract)+// 4. output is in INPUT order, patching only the distributed axis+// 5. vertical axis mirrors horizontal exactly+// 6. overlapping boxes still distribute (gap < 0, no refusal)+// 7. integer positions, no drift, span preserved, no NaN+// 8. degenerate input (all stacked, zero size) stays finite+// ─────────────────────────────────────────────────────────────++import { describe, expect, it } from 'vitest'+import { distributeEvenly, type DistributableBox } from '@/lib/distribute'++const box = (x: number, y: number, w = 100, h = 50): DistributableBox => ({ x, y, width: w, height: h })++function gapsX(boxes: DistributableBox[]): number[] {+ const sorted = [...boxes].sort((a, b) => a.x - b.x)+ const gaps: number[] = []+ for (let i = 1; i < sorted.length; i++) gaps.push(sorted[i].x - (sorted[i - 1].x + sorted[i - 1].width))+ return gaps+}++describe('distributeEvenly', () => {+ it('is a no-op for fewer than 3 boxes (positions returned verbatim)', () => {+ const one = [box(10, 20)]+ expect(distributeEvenly(one, 'x')).toEqual([{ x: 10, y: 20 }])+ const two = [box(0, 0), box(500, 300)]+ expect(distributeEvenly(two, 'x')).toEqual([{ x: 0, y: 0 }, { x: 500, y: 300 }])+ expect(distributeEvenly(two, 'y')).toEqual([{ x: 0, y: 0 }, { x: 500, y: 300 }])+ })++ it('equalizes gaps and keeps the extremes exactly where they were', () => {+ const boxes = [box(0, 0), box(400, 0), box(500, 0)] // gaps 300, 0+ const out = distributeEvenly(boxes, 'x')+ expect(out[0].x).toBe(0) // first fixed+ expect(out[2].x).toBe(500) // last fixed+ const moved = [+ { ...boxes[0], x: out[0].x },+ { ...boxes[1], x: out[1].x },+ { ...boxes[2], x: out[2].x },+ ]+ const gaps = gapsX(moved)+ expect(gaps[0]).toBe(gaps[1]) // 150 each+ expect(gaps[0]).toBe(150)+ expect(out.every((p) => p.y === 0)).toBe(true) // other axis untouched+ })++ it('equalizes gaps for UNEQUAL box sizes (the real contract)', () => {+ const boxes = [box(0, 0, 100), box(350, 0, 200), box(600, 0, 50), box(1400, 0, 300)]+ const out = distributeEvenly(boxes, 'x')+ expect(out[0].x).toBe(0)+ expect(out[3].x).toBe(1400) // last leading edge fixed+ const moved = boxes.map((b, i) => ({ ...b, x: out[i].x }))+ const gaps = gapsX(moved)+ // span 1700, sizes 650 → gap = (1700-650)/3 = 350 exactly+ expect(gaps).toEqual([350, 350, 350])+ })++ it('returns positions in INPUT order and only moves the distributed axis', () => {+ const boxes = [box(900, 7, 40), box(0, 3, 60), box(300, 11, 80)] // deliberately unsorted input+ const outX = distributeEvenly(boxes, 'x')+ expect(outX.map((p) => p.y)).toEqual([7, 3, 11]) // y passed through+ const outY = distributeEvenly(boxes, 'y')+ expect(outY.map((p) => p.x)).toEqual([900, 0, 300]) // x passed through+ // the input array itself is never mutated+ expect(boxes[1].x).toBe(0)+ })++ it('mirrors the geometry exactly on the vertical axis', () => {+ const hBoxes = [box(0, 0, 100, 40), box(400, 0, 100, 40), box(500, 0, 100, 40)]+ const vBoxes = [box(0, 0, 40, 100), box(0, 400, 40, 100), box(0, 500, 40, 100)]+ const hOut = distributeEvenly(hBoxes, 'x')+ const vOut = distributeEvenly(vBoxes, 'y')+ expect(vOut.map((p) => p.y)).toEqual(hOut.map((p) => p.x))+ expect(vOut.map((p) => p.x)).toEqual([0, 0, 0])+ })++ it('still distributes when boxes overlap (negative gap, no refusal)', () => {+ // three 200-wide boxes stacked on nearly the same spot+ const boxes = [box(0, 0, 200), box(10, 0, 200), box(20, 0, 200)]+ const out = distributeEvenly(boxes, 'x')+ expect(out[0].x).toBe(0)+ expect(out[2].x).toBe(20)+ const moved = boxes.map((b, i) => ({ ...b, x: out[i].x }))+ const gaps = gapsX(moved)+ expect(gaps[0]).toBe(gaps[1]) // evenly MORE overlapped — still even+ expect(gaps[0]).toBeLessThan(0)+ })++ it('produces integer positions with no drift and preserves the span', () => {+ const boxes = [box(0, 0, 33), box(111, 0, 77), box(222, 0, 11), box(333, 0, 99), box(444, 0, 55)]+ const out = distributeEvenly(boxes, 'x')+ for (const p of out) expect(Number.isInteger(p.x)).toBe(true)+ const minX = Math.min(...out.map((p) => p.x))+ const maxFar = Math.max(...out.map((p, i) => p.x + boxes[i].width))+ expect(minX).toBe(0)+ expect(maxFar).toBe(499) // 444 + 55 — the span is invariant+ const moved = boxes.map((b, i) => ({ ...b, x: out[i].x }))+ const gaps = gapsX(moved)+ for (const g of gaps) expect(Math.abs(g - gaps[0])).toBeLessThanOrEqual(1) // ≤ 1px rounding+ })++ it('is finite and gap-free on degenerate stacked zero-size input', () => {+ const boxes = [box(10, 10, 0, 0), box(10, 10, 0, 0), box(10, 10, 0, 0)]+ const out = distributeEvenly(boxes, 'x')+ for (const p of out) {+ expect(Number.isFinite(p.x)).toBe(true)+ expect(Number.isFinite(p.y)).toBe(true)+ }+ // zero span + zero sizes → gap 0 → everyone stays+ expect(out.map((p) => p.x)).toEqual([10, 10, 10])+ })++ it('handles zero-gap perfect input without moving anything', () => {+ const boxes = [box(0, 0, 100), box(100, 0, 100), box(200, 0, 100), box(300, 0, 100)]+ const out = distributeEvenly(boxes, 'x')+ expect(out.map((p) => p.x)).toEqual([0, 100, 200, 300])+ })+})diff --git a/src/lib/distribute.ts b/src/lib/distribute.tsnew file mode 100644index 0000000..ea1406a--- /dev/null+++ b/src/lib/distribute.ts@@ -0,0 +1,71 @@+// ─────────────────────────────────────────────────────────────+// v0.14 (D3): even distribution — pure geometry.+//+// Shared by the store action (editor toolbar + undo/collab), the AI+// assistant / plugin path and the unit tests. No DOM, no store+// imports allowed in this file (the v06-geometry contract).+//+// Semantics = Canva/Figma "spacing": equal GAPS between element+// EDGES; the leftmost/topmost and rightmost/bottommost elements stay+// exactly where they are. Boxes already overlapping still distribute+// (the overlap is evened out) — we refuse nothing, matching the+// behaviour users know from Canva and Figma.+//+// Geometry uses the element's local box (x/y/width/height), the same+// simplification the page-align modes use; rotation is ignored for+// distribute exactly as it is for align (documented honestly here).+// Positions are rounded to integers per element (the document model+// is integer coordinates); the cursor walks in floats so rounding+// never accumulates drift — adjacent gaps may differ by ≤ 1 px.+// ─────────────────────────────────────────────────────────────++export type DistributeAxis = 'x' | 'y'++export interface DistributableBox {+ x: number+ y: number+ width: number+ height: number+}++/**+ * Evenly distribute `boxes` along `axis`, keeping the extremes fixed+ * and equalizing the edge gaps between neighbours.+ *+ * Returns one {x, y} per input box, in INPUT order (patch only the+ * axis you distributed; the other coordinate is passed through+ * unchanged). For fewer than 3 boxes distribution is a no-op — the+ * input positions are returned verbatim (nothing to space evenly).+ */+export function distributeEvenly<T extends DistributableBox>(boxes: T[], axis: DistributeAxis): { x: number; y: number }[] {+ const n = boxes.length+ if (n < 3) return boxes.map((b) => ({ x: b.x, y: b.y }))++ const lead = (b: DistributableBox): number => (axis === 'x' ? b.x : b.y)+ const size = (b: DistributableBox): number => (axis === 'x' ? b.width : b.height)++ // sort indices by leading edge; ties keep input order (stable intent)+ const order = boxes+ .map((b, i) => ({ i, lead: lead(b), size: size(b) }))+ .sort((a, b) => a.lead - b.lead || a.i - b.i)++ const first = order[0]+ const last = order[n - 1]+ // span = leading edge of the last box to the FAR edge of the last box+ const span = last.lead + last.size - first.lead+ const sizes = order.reduce((s, e) => s + e.size, 0)+ // may be negative when the boxes overlap — that still distributes+ // (the overlap is evened out); NaN only if callers feed NaN boxes+ const gap = (span - sizes) / (n - 1)++ const out = boxes.map((b) => ({ x: b.x, y: b.y }))+ let cursor = first.lead+ for (const e of order) {+ out[e.i] =+ axis === 'x'+ ? { x: Math.round(cursor), y: boxes[e.i].y }+ : { x: boxes[e.i].x, y: Math.round(cursor) }+ cursor += e.size + gap+ }+ return out+}diff --git a/src/store/editor-store.ts b/src/store/editor-store.tsindex 411bf31..26c0c2b 100644--- a/src/store/editor-store.ts+++ b/src/store/editor-store.ts@@ -22,6 +22,7 @@ import {import type { ElementAnimation, PageTransition } from '@/lib/types'import type { CollabOp, DesignEventRow } from '@/lib/collab/protocol'import type { Collaborator, CollabStatus } from '@/lib/collab/protocol'+import { distributeEvenly } from '@/lib/distribute'export type PanelId =| 'templates'@@ -169,6 +170,7 @@ interface EditorState {groupSelection: () => voidungroupSelection: () => voidalignElements: (ids: string[], mode: 'left' | 'cx' | 'right' | 'top' | 'cy' | 'bottom') => void+ distributeElements: (ids: string[], axis: 'x' | 'y') => voidflipSelection: (axis: 'h' | 'v') => void// page ops@@ -700,6 +702,38 @@ export const useEditorStore = create<EditorState>((set, get) => ({emit({ kind: 'page:replace', pageId: next[currentPage].id, page: next[currentPage] })},+ // v0.14 (D3): even distribution — Canva/Figma "spacing". Equal gaps+ // between element edges, extremes stay fixed; ONE history entry and+ // one collab page:replace (the assistant path used to do N separate+ // updateElements calls = N undo steps — this is the house pattern).+ distributeElements: (ids, axis) => {+ if (ids.length < 3) return+ get().pushHistory()+ const { pages, currentPage, version } = get()+ const h = nowHlc()+ const next = pages.map((p, i) =>+ i !== currentPage+ ? p+ : {+ ...p,+ elements: (() => {+ const targets = p.elements.filter((el) => ids.includes(el.id))+ if (targets.length < 3) return p.elements+ const positions = distributeEvenly(targets, axis)+ const byId = new Map(targets.map((el, idx) => [el.id, positions[idx]]))+ return p.elements.map((el) => {+ const pos = byId.get(el.id)+ // v0.10: only the DISTRIBUTED elements get a fresh stamp —+ // untouched elements keep theirs so concurrent remote edits win+ return pos ? ({ ...el, ...pos, _m: h } as AnyElement) : el+ })+ })(),+ }+ )+ set({ pages: next, dirty: true, version: version + 1 })+ emit({ kind: 'page:replace', pageId: next[currentPage].id, page: next[currentPage] })+ },+flipSelection: (axis) => {const { selectedIds, pages, currentPage, version } = get()if (!selectedIds.length) returndiff --git a/tests/e2e/distribute.spec.ts b/tests/e2e/distribute.spec.tsnew file mode 100644index 0000000..94d0f51--- /dev/null+++ b/tests/e2e/distribute.spec.ts@@ -0,0 +1,276 @@+import { test, expect, type Page } from '@playwright/test'++/**+ * v0.14 (D3): even distribution — acceptance.+ *+ * 1. four shapes at uneven gaps (incl. one overlapping pair): a+ * marquee selection shows the Position popover's Distribute+ * section (≥ 3 selected); Spacing H equalizes the edge GAPS in+ * the SAVED document (API truth) with the extremes fixed, the+ * exact integer positions the pure geometry predicts, and y+ * untouched+ * 2. Spacing V (same open popover, same selection) mirrors the+ * geometry vertically — the initial y's overlap, and Canva/Figma+ * distribute those instead of refusing (the behavior this slice+ * changed)+ * 3. ONE undo reverts ONLY the V distribution (x's stay spaced,+ * y's return to their originals) and a second undoes the H —+ * each distribute is exactly ONE history entry (the old+ * assistant path spent one undo step PER ELEMENT)+ * 4. two selected → the Distribute section is not offered+ *+ * Race notes (why the flow is ordered this way):+ * - the marquee waits for the shapes to be PIXEL-rendered first:+ * "Design canvas" visible ≠ design data loaded — an early drag+ * selects nothing (observed flake)+ * - both distributes share ONE selection + ONE open popover, and+ * the undos need neither: undo's own `pages:replace` broadcast+ * echoes back over SSE and the receive side clears the selection+ * (editor-store) — nothing after this point depends on it+ *+ * Register budget: ZERO — anonymous anon-commons designs, fresh+ * browser context per test (the PR #26/#30 lesson: the suite-wide+ * register budget is saturated; this spec must not spend any of it).+ */++interface DistRect {+ id: string+ type: string+ x: number+ y: number+}++function rect(id: string, x: number, y: number, w = 120, h = 90) {+ return {+ id,+ type: 'rect',+ name: `dist ${id}`,+ x,+ y,+ width: w,+ height: h,+ rotation: 0,+ opacity: 1,+ locked: false,+ visible: true,+ fill: '#00C4CC',+ stroke: 'transparent',+ strokeWidth: 0,+ cornerRadius: 24,+ shadow: { enabled: false, color: '#000000', blur: 0, offsetX: 0, offsetY: 0 },+ }+}++async function createDesign(page: Page, name: string, elements: unknown[]): Promise<string> {+ const res = await page.request.post('/api/designs', {+ data: { name, width: 1080, height: 720, pages: [{ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements }] },+ })+ expect(res.status(), `create design: ${await res.text()}`).toBeLessThan(300)+ return ((await res.json()) as { id: string }).id+}++async function openEditor(page: Page, designId: string) {+ await page.goto(`/design/${designId}`)+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })+}++/** the shapes are actually ON the stage (pixel truth — the fill colour+ * #00C4CC present on the biggest canvas in the workspace; scoped so+ * toolbar thumbnails never fool it). Guards the design-load race. */+async function waitForShapesRendered(page: Page) {+ await page.waitForFunction(+ () => {+ const scope = document.querySelector('main[aria-label="Design canvas"]')+ const canvases = Array.from((scope ?? document).querySelectorAll('canvas'))+ const biggest = canvases.reduce<HTMLCanvasElement | null>(+ (best, c) => (!best || c.width * c.height > best.width * best.height ? c : best),+ null+ )+ if (!biggest) return false+ try {+ const ctx = biggest.getContext('2d')+ if (!ctx) return false+ const data = ctx.getImageData(0, 0, biggest.width, biggest.height).data+ for (let i = 0; i < data.length; i += 16) {+ if (data[i] === 0x00 && data[i + 1] === 0xc4 && data[i + 2] === 0xcc) return true+ }+ return false+ } catch {+ return false+ }+ },+ undefined,+ { timeout: 30_000, polling: 250 }+ )+}++async function docRectsById(page: Page, designId: string): Promise<Map<string, DistRect>> {+ const res = await page.request.get(`/api/designs/${designId}`)+ expect(res.status()).toBe(200)+ const doc = (await res.json()) as { pages: { elements: DistRect[] }[] }+ return new Map(doc.pages[0].elements.filter((e) => e.type === 'rect').map((r) => [r.id, r]))+}++/** poll the saved document until pred holds (observed end state — the+ * PR #23 lesson: never sleep a fixed time and hope) */+async function waitForRects(+ page: Page,+ designId: string,+ pred: (m: Map<string, DistRect>) => boolean,+ what: string+): Promise<Map<string, DistRect>> {+ const start = Date.now()+ for (;;) {+ const m = await docRectsById(page, designId)+ if (pred(m)) return m+ if (Date.now() - start > 45_000) {+ throw new Error(`distribute: ${what} — document never reached the expected state (got ${[...m.values()].map((r) => `${r.id}@${r.x},${r.y}`).join(' ')})`)+ }+ await page.waitForTimeout(600)+ }+}++/** edge gaps along an axis (rects are all 120×90 in this spec) */+function gapsOf(ids: string[], m: Map<string, DistRect>, axis: 'x' | 'y', size: number): number[] {+ const sorted = ids.map((id) => m.get(id)![axis]).sort((a, b) => a - b)+ const out: number[] = []+ for (let i = 1; i < sorted.length; i++) out.push(sorted[i] - (sorted[i - 1] + size))+ return out+}++async function marqueeSelectAll(page: Page) {+ // elements live in the page's middle band (x 240..960, y 280..470),+ // so a drag from the empty area above-left of the band to below-+ // right of it intersects all four (marquee hits are intersections;+ // the page bar / zoom controls hug the bottom corners and stay+ // clear of the end point)+ const box = (await page.getByLabel('Design canvas').boundingBox())!+ await page.mouse.move(box.x + box.width * 0.15, box.y + box.height * 0.18)+ await page.mouse.down()+ await page.mouse.move(box.x + box.width * 0.95, box.y + box.height * 0.83, { steps: 8 })+ await page.mouse.up()+}++async function openPosition(page: Page) {+ await page.getByRole('button', { name: 'Position', exact: true }).click()+ await expect(page.getByText('Align to page')).toBeVisible()+}++test.describe('Even distribute (v0.14 D3)', () => {+ test.setTimeout(150_000)++ test('marquee 4 shapes → Spacing H → Spacing V → each undoes in ONE step', async ({ page }) => {+ // x gaps: 40, −60 (b/c overlap), 260 → distribute → 80, 80, 80+ // y gaps (sorted c,a,d,b): −80, −50, −50 → distribute → −57, −56, −57+ const design = await createDesign(page, `cvx_d3_${Date.now().toString(36)}`, [+ rect('dist_a', 240, 300),+ rect('dist_b', 400, 380),+ rect('dist_c', 460, 280),+ rect('dist_d', 840, 340),+ ])+ await openEditor(page, design)+ await waitForShapesRendered(page)++ const ids = ['dist_a', 'dist_b', 'dist_c', 'dist_d']++ await marqueeSelectAll(page)+ await openPosition(page)++ // the Distribute section exists for a 4-selection+ await expect(page.getByRole('button', { name: 'Spacing H', exact: true })).toBeVisible()+ await expect(page.getByRole('button', { name: 'Spacing V', exact: true })).toBeVisible()++ // ── Spacing H: equal gaps, extremes fixed, y untouched ──+ await page.getByRole('button', { name: 'Spacing H', exact: true }).click()++ const afterH = await waitForRects(+ page,+ design,+ (m) => m.get('dist_a')!.x === 240 && m.get('dist_b')!.x === 440 && m.get('dist_c')!.x === 640 && m.get('dist_d')!.x === 840,+ 'Spacing H positions'+ )+ // the pure geometry's exact integer prediction+ expect(afterH.get('dist_a')!.x).toBe(240) // first stays+ expect(afterH.get('dist_b')!.x).toBe(440)+ expect(afterH.get('dist_c')!.x).toBe(640)+ expect(afterH.get('dist_d')!.x).toBe(840) // last stays+ expect(gapsOf(ids, afterH, 'x', 120)).toEqual([80, 80, 80])+ // the other axis is passed through untouched+ expect(afterH.get('dist_a')!.y).toBe(300)+ expect(afterH.get('dist_b')!.y).toBe(380)+ expect(afterH.get('dist_c')!.y).toBe(280)+ expect(afterH.get('dist_d')!.y).toBe(340)++ // ── Spacing V: same selection, same open popover ──+ await page.getByRole('button', { name: 'Spacing V', exact: true }).click()+ const afterV = await waitForRects(+ page,+ design,+ (m) => m.get('dist_a')!.y === 313 && m.get('dist_b')!.y === 380 && m.get('dist_c')!.y === 280 && m.get('dist_d')!.y === 347,+ 'Spacing V positions'+ )+ expect(afterV.get('dist_c')!.y).toBe(280) // topmost stays+ expect(afterV.get('dist_b')!.y).toBe(380) // bottom-most stays+ expect(afterV.get('dist_a')!.y).toBe(313)+ expect(afterV.get('dist_d')!.y).toBe(347)+ // the overlapping input was distributed (even negative gaps), not refused+ const gv = gapsOf(ids, afterV, 'y', 90)+ expect(Math.abs(gv[0] - gv[1])).toBeLessThanOrEqual(1)+ expect(Math.abs(gv[1] - gv[2])).toBeLessThanOrEqual(1)+ // and the x's keep their distributed values+ expect(afterV.get('dist_a')!.x).toBe(240)+ expect(afterV.get('dist_b')!.x).toBe(440)+ expect(afterV.get('dist_c')!.x).toBe(640)+ expect(afterV.get('dist_d')!.x).toBe(840)++ // ── ONE undo reverts ONLY the V distribution ──+ // (undo broadcasts pages:replace, whose SSE echo clears the+ // selection — nothing below depends on it)+ await page.keyboard.press('Control+z')+ const afterUndoV = await waitForRects(+ page,+ design,+ (m) => m.get('dist_a')!.y === 300 && m.get('dist_b')!.y === 380 && m.get('dist_c')!.y === 280 && m.get('dist_d')!.y === 340,+ 'first undo reverts only Spacing V'+ )+ // x's still distributed from Spacing H…+ expect(afterUndoV.get('dist_b')!.x).toBe(440)+ expect(afterUndoV.get('dist_c')!.x).toBe(640)+ // …y's back to the originals+ expect(afterUndoV.get('dist_a')!.y).toBe(300)+ expect(afterUndoV.get('dist_d')!.y).toBe(340)++ // ── a second undo reverts the H distribution ──+ await page.keyboard.press('Control+z')+ const afterUndoH = await waitForRects(+ page,+ design,+ (m) => m.get('dist_b')!.x === 400 && m.get('dist_c')!.x === 460,+ 'second undo reverts Spacing H'+ )+ expect(afterUndoH.get('dist_a')!.x).toBe(240)+ expect(afterUndoH.get('dist_d')!.x).toBe(840)+ expect(afterUndoH.get('dist_b')!.x).toBe(400)+ expect(afterUndoH.get('dist_c')!.x).toBe(460)+ })++ test('two selected → no Distribute section offered', async ({ page }) => {+ const design = await createDesign(page, `cvx_d3_pair_${Date.now().toString(36)}`, [+ rect('pair_a', 300, 300),+ rect('pair_b', 600, 400),+ ])+ await openEditor(page, design)+ await waitForShapesRendered(page)++ await marqueeSelectAll(page)+ await openPosition(page)++ // the align grid is there for any multi-selection…+ await expect(page.getByText('Align to page')).toBeVisible()+ // …but distribute needs ≥ 3 — nothing to space evenly with two+ await expect(page.getByRole('button', { name: 'Spacing H', exact: true })).toBeHidden()+ await expect(page.getByRole('button', { name: 'Spacing V', exact: true })).toBeHidden()+ await expect(page.getByText('Distribute')).toBeHidden()+ })+})