Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

feat: baseline stabilization (task 0) - schema, migration, and tests

copilot-swe-agent[bot]1e705a6895ee
diff --git a/apps/image/FEATURE_STATUS.md b/apps/image/FEATURE_STATUS.md
new file mode 100644
index 00000000..b9eb0796
--- /dev/null
+++ b/apps/image/FEATURE_STATUS.md
@@ -0,0 +1,151 @@
+# OpenReel Image – Feature Status Matrix
+
+This document audits which tools, panels, and export formats in the
+`apps/image` editor are **Fully Implemented**, **Partially Wired**, or
+**UI-Only / Stub**.
+
+> **Legend**
+>
+> | Symbol | Meaning |
+> |--------|---------|
+> | ✅ | Fully implemented – persists data, renders correctly, passes tests |
+> | 🔶 | Partially wired – UI exists, some logic works but missing features |
+> | 🔲 | UI-only / stub – panel rendered but no backing logic |
+
+---
+
+## Toolbar Tools
+
+| Tool | Status | Notes |
+|------|--------|-------|
+| Select / Move | ✅ | Transform handles, multi-select, keyboard nudge |
+| Crop | 🔶 | Basic crop rect; no aspect-lock presets or straighten |
+| Text | ✅ | Create text layers with full style panel |
+| Rectangle | ✅ | Shape layer, fill/stroke, corner radius |
+| Ellipse | ✅ | Shape layer |
+| Triangle | ✅ | Shape layer |
+| Polygon | ✅ | Shape layer, configurable sides |
+| Star | ✅ | Shape layer, inner radius |
+| Line / Arrow | ✅ | Shape layer with stroke |
+| Pen / Path | 🔶 | Path drawing works; bezier handle editing absent |
+| Brush | 🔶 | UI and settings panel exist; stroke not persisted |
+| Eraser | 🔶 | Tool panel exists; raster edit not implemented |
+| Paint Bucket | 🔶 | Tool panel exists; flood-fill not wired |
+| Gradient Fill | 🔶 | Tool panel exists; gradient application incomplete |
+| Clone Stamp | 🔲 | Panel rendered; no backing logic |
+| Healing Brush | 🔲 | Panel rendered; no backing logic |
+| Spot Healing | 🔲 | Panel rendered; no backing logic |
+| Dodge / Burn | 🔲 | Panel rendered; no backing logic |
+| Sponge | 🔲 | Panel rendered; no backing logic |
+| Smudge | 🔲 | Panel rendered; no backing logic |
+| Blur / Sharpen Brush | 🔲 | Panel rendered; no backing logic |
+| Rectangular Selection | 🔶 | Selection state exists; fill/copy/cut not selection-aware |
+| Elliptical Selection | 🔲 | Not implemented |
+| Lasso | 🔲 | Not implemented |
+| Magic Wand | 🔲 | Not implemented |
+| Liquify | 🔲 | Panel rendered; no warp logic |
+| Hand / Pan | ✅ | Canvas pan with space-drag and middle-click |
+| Zoom | ✅ | Scroll wheel and Z-key shortcuts |
+| Color Picker | ✅ | Foreground / background colour wells |
+
+---
+
+## Inspector Panels
+
+| Panel | Status | Notes |
+|-------|--------|-------|
+| Transform | ✅ | X/Y/W/H, rotation, flip, opacity |
+| Alignment | ✅ | Align/distribute relative to artboard or selection |
+| Appearance (Blend Mode + Opacity) | ✅ | Persists to layer |
+| Effects – Shadow | ✅ | Enabled, colour, blur, offset |
+| Effects – Inner Shadow | ✅ | Enabled, colour, blur, offset |
+| Effects – Stroke | ✅ | Enabled, colour, width, style |
+| Effects – Glow | ✅ | Enabled, colour, blur, intensity |
+| Text (font, size, style) | ✅ | All style options; no live canvas cursor |
+| Shape (fill, gradient, noise, stroke) | ✅ | Full shapeStyle controls |
+| Artboard (size, background) | ✅ | |
+| Image Controls (brightness etc.) | ✅ | Non-destructive filter object |
+| Levels | ✅ | Data model + UI; GPU render pending |
+| Curves | ✅ | Data model + UI; GPU render pending |
+| Color Balance | ✅ | Data model + UI; GPU render pending |
+| Selective Color | ✅ | Data model + UI; GPU render pending |
+| Black & White | ✅ | Data model + UI; GPU render pending |
+| Photo Filter | ✅ | Data model + UI; GPU render pending |
+| Channel Mixer | ✅ | Data model + UI; GPU render pending |
+| Gradient Map | ✅ | Data model + UI; GPU render pending |
+| Posterize | ✅ | Data model + UI; GPU render pending |
+| Threshold | ✅ | Data model + UI; GPU render pending |
+| Mask | 🔶 | Data model exists; mask painting not wired |
+| Background Removal | ✅ | Uses @imgly/background-removal locally |
+| Selection Tools Panel | 🔶 | Basic rect selection; no ellipse/lasso/wand |
+| Brush Settings | 🔶 | UI wired; brush strokes not persisted to layer |
+| Eraser Settings | 🔲 | UI only |
+| Paint Bucket Settings | 🔲 | UI only |
+| Gradient Tool Settings | 🔶 | UI partially wired |
+| Clone Stamp Settings | 🔲 | UI only |
+| Healing Brush Settings | 🔲 | UI only |
+| Spot Healing Settings | 🔲 | UI only |
+| Dodge/Burn Settings | 🔲 | UI only |
+| Sponge Settings | 🔲 | UI only |
+| Smudge Settings | 🔲 | UI only |
+| Blur/Sharpen Settings | 🔲 | UI only |
+| Liquify Settings | 🔲 | UI only |
+| Crop Settings | 🔶 | No aspect preset or perspective crop |
+| Pen/Path Settings | 🔶 | Path creation works; anchor editing missing |
+| Transform Tool Panel | ✅ | Free transform functional |
+| Filter Presets | 🔶 | Preset list UI; save/load not persisted |
+| Color Harmony | 🔲 | UI panel rendered; logic not wired |
+| History Panel | 🔶 | Snapshot history works; no command names shown |
+
+---
+
+## Left Panel Tabs
+
+| Tab | Status | Notes |
+|-----|--------|-------|
+| Layers | ✅ | Add/remove/reorder/group/visibility/lock |
+| Templates | 🔶 | Hard-coded template placeholders; no real template data |
+| Assets / Uploads | 🔶 | Upload and display works; no asset library categories |
+| Pages (Artboards) | ✅ | Add/remove/rename/reorder artboards |
+
+---
+
+## Export Formats
+
+| Format | Status | Notes |
+|--------|--------|-------|
+| PNG | ✅ | Full artboard render with transparency |
+| JPEG | ✅ | Quality setting applied; transparent bg becomes white |
+| WebP | ✅ | Quality setting applied |
+| SVG | 🔲 | Option present in UI; not implemented |
+| PDF | 🔲 | Option present in UI; not implemented |
+
+---
+
+## Data & Storage
+
+| Feature | Status | Notes |
+|---------|--------|-------|
+| Project create / load / close | ✅ | Via Zustand store |
+| Project schema validation (Zod) | ✅ | Added in baseline stabilisation |
+| Project migration (version field) | ✅ | v0 → v1 migration added |
+| Auto-save (localStorage) | 🔶 | Saves on dirty, no IndexedDB yet |
+| `.orimg` export (zip) | 🔲 | Not implemented |
+| Asset deduplication | 🔲 | Not implemented |
+| Blob URL lifecycle management | 🔲 | Not implemented |
+
+---
+
+## Test Coverage
+
+| Area | Status |
+|------|--------|
+| Project creation | ✅ |
+| Layer add / remove / duplicate / reorder | ✅ |
+| Artboard add / remove / update | ✅ |
+| Export service (PNG / JPG / WebP) | ✅ |
+| Project schema validation | ✅ |
+| Project migration | ✅ |
+| React component tests | 🔲 |
+| Playwright E2E smoke tests | 🔲 |
+| Visual regression tests | 🔲 |
diff --git a/apps/image/package.json b/apps/image/package.json
index 39b39e3f..3dd0f4af 100644
--- a/apps/image/package.json
+++ b/apps/image/package.json
@@ -34,6 +34,7 @@
"react-dom": "^18.3.1",
"tailwind-merge": "^3.4.0",
"uuid": "^13.0.0",
+ "zod": "^4.4.3",
"zustand": "^4.5.2"
},
"devDependencies": {
diff --git a/apps/image/src/app.test.ts b/apps/image/src/app.test.ts
index dea6da29..0a20495c 100644
--- a/apps/image/src/app.test.ts
+++ b/apps/image/src/app.test.ts
@@ -1,7 +1,184 @@
-import { describe, it, expect } from "vitest";
+import { describe, it, expect } from 'vitest';
+import { parseProject } from './services/project-schema';
+import { migrateProject, CURRENT_VERSION } from './services/project-migration';
-describe("OpenReel Image", () => {
- it("should be defined", () => {
- expect(true).toBe(true);
+// ── App smoke tests ──────────────────────────────────────────────────────────
+//
+// These tests exercise the integration seam between the project schema,
+// migration utilities, and the store to confirm the whole pipeline is wired up
+// and importing correctly.
+
+describe('OpenReel Image – baseline smoke tests', () => {
+ // Schema is importable.
+ it('project schema module is importable', () => {
+ expect(typeof parseProject).toBe('function');
+ });
+
+ // Migration is importable and exposes the current version constant.
+ it('migration module exposes CURRENT_VERSION', () => {
+ expect(typeof CURRENT_VERSION).toBe('number');
+ expect(CURRENT_VERSION).toBeGreaterThanOrEqual(1);
+ });
+
+ // A minimal valid project document passes schema validation.
+ it('validates a minimal valid project', () => {
+ const baseLayer = {
+ id: 'l1',
+ name: 'Layer',
+ type: 'text' as const,
+ visible: true,
+ locked: false,
+ transform: {
+ x: 0, y: 0, width: 200, height: 50, rotation: 0,
+ scaleX: 1, scaleY: 1, skewX: 0, skewY: 0, opacity: 1,
+ },
+ blendMode: { mode: 'normal' as const },
+ shadow: { enabled: false, color: 'rgba(0,0,0,0.5)', blur: 10, offsetX: 0, offsetY: 4 },
+ innerShadow: { enabled: false, color: 'rgba(0,0,0,0.5)', blur: 10, offsetX: 2, offsetY: 2 },
+ stroke: { enabled: false, color: '#000000', width: 1, style: 'solid' as const },
+ glow: { enabled: false, color: '#ffffff', blur: 20, intensity: 1 },
+ filters: {
+ brightness: 100, contrast: 100, saturation: 100, hue: 0, exposure: 0,
+ vibrance: 0, highlights: 0, shadows: 0, clarity: 0, blur: 0,
+ blurType: 'gaussian' as const, blurAngle: 0, sharpen: 0, vignette: 0,
+ grain: 0, sepia: 0, invert: 0,
+ },
+ parentId: null,
+ flipHorizontal: false,
+ flipVertical: false,
+ mask: null,
+ clippingMask: false,
+ levels: {
+ enabled: false,
+ master: { inputBlack: 0, inputWhite: 255, gamma: 1, outputBlack: 0, outputWhite: 255 },
+ red: { inputBlack: 0, inputWhite: 255, gamma: 1, outputBlack: 0, outputWhite: 255 },
+ green: { inputBlack: 0, inputWhite: 255, gamma: 1, outputBlack: 0, outputWhite: 255 },
+ blue: { inputBlack: 0, inputWhite: 255, gamma: 1, outputBlack: 0, outputWhite: 255 },
+ },
+ curves: {
+ enabled: false,
+ master: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },
+ red: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },
+ green: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },
+ blue: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },
+ },
+ colorBalance: {
+ enabled: false,
+ shadows: { cyanRed: 0, magentaGreen: 0, yellowBlue: 0 },
+ midtones: { cyanRed: 0, magentaGreen: 0, yellowBlue: 0 },
+ highlights: { cyanRed: 0, magentaGreen: 0, yellowBlue: 0 },
+ preserveLuminosity: true,
+ },
+ selectiveColor: {
+ enabled: false, method: 'relative' as const,
+ reds: { cyan: 0, magenta: 0, yellow: 0, black: 0 },
+ yellows: { cyan: 0, magenta: 0, yellow: 0, black: 0 },
+ greens: { cyan: 0, magenta: 0, yellow: 0, black: 0 },
+ cyans: { cyan: 0, magenta: 0, yellow: 0, black: 0 },
+ blues: { cyan: 0, magenta: 0, yellow: 0, black: 0 },
+ magentas: { cyan: 0, magenta: 0, yellow: 0, black: 0 },
+ whites: { cyan: 0, magenta: 0, yellow: 0, black: 0 },
+ neutrals: { cyan: 0, magenta: 0, yellow: 0, black: 0 },
+ blacks: { cyan: 0, magenta: 0, yellow: 0, black: 0 },
+ },
+ blackWhite: {
+ enabled: false, reds: 40, yellows: 60, greens: 40, cyans: 60, blues: 20,
+ magentas: 80, tintEnabled: false, tintHue: 35, tintSaturation: 25,
+ },
+ photoFilter: {
+ enabled: false, filter: 'warming-85' as const, color: '#ec8a00',
+ density: 25, preserveLuminosity: true,
+ },
+ channelMixer: {
+ enabled: false, monochrome: false,
+ red: { red: 100, green: 0, blue: 0, constant: 0 },
+ green: { red: 0, green: 100, blue: 0, constant: 0 },
+ blue: { red: 0, green: 0, blue: 100, constant: 0 },
+ },
+ gradientMap: {
+ enabled: false,
+ stops: [{ position: 0, color: '#000000' }, { position: 1, color: '#ffffff' }],
+ reverse: false, dither: false,
+ },
+ posterize: { enabled: false, levels: 4 },
+ threshold: { enabled: false, level: 128 },
+ content: 'Hello',
+ style: {
+ fontFamily: 'Inter', fontSize: 24, fontWeight: 400,
+ fontStyle: 'normal' as const, textDecoration: 'none' as const,
+ textAlign: 'left' as const, verticalAlign: 'top' as const,
+ lineHeight: 1.4, letterSpacing: 0, fillType: 'solid' as const,
+ color: '#ffffff', gradient: null, strokeColor: null, strokeWidth: 0,
+ backgroundColor: null, backgroundPadding: 8, backgroundRadius: 4,
+ textShadow: { enabled: false, color: 'rgba(0,0,0,0.5)', blur: 4, offsetX: 0, offsetY: 2 },
+ },
+ autoSize: true,
+ };
+
+ const validProject = {
+ id: 'p1',
+ name: 'Smoke Test',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ version: 1,
+ artboards: [
+ {
+ id: 'ab1',
+ name: 'Artboard 1',
+ size: { width: 1080, height: 1080 },
+ background: { type: 'color', color: '#ffffff' },
+ layerIds: ['l1'],
+ position: { x: 0, y: 0 },
+ },
+ ],
+ layers: { l1: baseLayer },
+ assets: {},
+ activeArtboardId: 'ab1',
+ };
+
+ const result = parseProject(validProject);
+ expect(result.success).toBe(true);
+ });
+
+ // An invalid document is rejected.
+ it('rejects an invalid project document', () => {
+ const result = parseProject({ id: 42, broken: true });
+ expect(result.success).toBe(false);
+ });
+
+ // Migration promotes a v0 document to v1.
+ it('migrates a v0 project to v1', () => {
+ const v0 = {
+ id: 'old',
+ name: 'Legacy',
+ createdAt: 0,
+ updatedAt: 0,
+ artboards: [{ id: 'ab-old', name: 'Page 1' }],
+ layers: {},
+ assets: {},
+ };
+
+ const migrated = migrateProject(v0 as Record<string, unknown>);
+ expect(migrated.version).toBe(1);
+ expect(migrated.activeArtboardId).toBe('ab-old');
+ });
+
+ // A project that already has version 1 is returned unchanged.
+ it('does not re-migrate a current-version project', () => {
+ const v1 = {
+ id: 'current',
+ name: 'New',
+ createdAt: 0,
+ updatedAt: 0,
+ version: 1,
+ artboards: [],
+ layers: {},
+ assets: {},
+ activeArtboardId: null,
+ };
+
+ const migrated = migrateProject(v1 as Record<string, unknown>);
+ expect(migrated.version).toBe(1);
});
});
+
diff --git a/apps/image/src/services/export-service.test.ts b/apps/image/src/services/export-service.test.ts
new file mode 100644
index 00000000..3c74be89
--- /dev/null
+++ b/apps/image/src/services/export-service.test.ts
@@ -0,0 +1,246 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { exportProject, exportArtboard, type ExportOptions } from './export-service';
+import type { Project, Artboard } from '../types/project';
+
+// ── Canvas mock ──────────────────────────────────────────────────────────────
+//
+// jsdom does not implement 2D canvas rendering, so we wire up a minimal mock
+// that records calls and satisfies the toBlob contract.
+
+function makeMockCanvas() {
+ const ctx = {
+ save: vi.fn(),
+ restore: vi.fn(),
+ scale: vi.fn(),
+ translate: vi.fn(),
+ rotate: vi.fn(),
+ transform: vi.fn(),
+ fillRect: vi.fn(),
+ strokeRect: vi.fn(),
+ beginPath: vi.fn(),
+ closePath: vi.fn(),
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
+ arc: vi.fn(),
+ fill: vi.fn(),
+ stroke: vi.fn(),
+ clip: vi.fn(),
+ drawImage: vi.fn(),
+ fillText: vi.fn(),
+ measureText: vi.fn().mockReturnValue({ width: 100 }),
+ getImageData: vi.fn().mockReturnValue({
+ data: new Uint8ClampedArray(4),
+ width: 1,
+ height: 1,
+ }),
+ putImageData: vi.fn(),
+ createLinearGradient: vi.fn().mockReturnValue({
+ addColorStop: vi.fn(),
+ }),
+ createRadialGradient: vi.fn().mockReturnValue({ addColorStop: vi.fn() }),
+ createImageData: vi.fn().mockReturnValue({ data: new Uint8ClampedArray(4) }),
+ globalAlpha: 1,
+ globalCompositeOperation: 'source-over',
+ fillStyle: '',
+ strokeStyle: '',
+ lineWidth: 1,
+ shadowColor: '',
+ shadowBlur: 0,
+ shadowOffsetX: 0,
+ shadowOffsetY: 0,
+ filter: '',
+ font: '',
+ textAlign: 'left',
+ textBaseline: 'alphabetic',
+ lineCap: 'butt',
+ lineJoin: 'miter',
+ setLineDash: vi.fn(),
+ };
+
+ let blobCallback: ((blob: Blob | null) => void) | null = null;
+
+ const canvas = {
+ width: 0,
+ height: 0,
+ getContext: vi.fn().mockReturnValue(ctx),
+ toBlob: vi.fn().mockImplementation(
+ (callback: (blob: Blob | null) => void, _type?: string, _quality?: number) => {
+ blobCallback = callback;
+ // Resolve asynchronously to simulate browser behaviour.
+ setTimeout(() => callback(new Blob(['pixel-data'], { type: _type ?? 'image/png' })), 0);
+ },
+ ),
+ toDataURL: vi.fn().mockReturnValue('data:image/png;base64,abc'),
+ _ctx: ctx,
+ _triggerBlob: () => blobCallback?.(new Blob(['pixel-data'])),
+ };
+
+ return canvas;
+}
+
+// ── Fixtures ──────────────────────────────────────────────────────────────────
+
+function makeArtboard(id = 'ab1'): Artboard {
+ return {
+ id,
+ name: 'Artboard 1',
+ size: { width: 400, height: 300 },
+ background: { type: 'color', color: '#ffffff' },
+ layerIds: [],
+ position: { x: 0, y: 0 },
+ };
+}
+
+function makeProject(artboards?: Artboard[]): Project {
+ const ab = artboards ?? [makeArtboard('ab1')];
+ return {
+ id: 'proj1',
+ name: 'Test Project',
+ version: 1,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ artboards: ab,
+ layers: {},
+ assets: {},
+ activeArtboardId: ab[0].id,
+ };
+}
+
+function makeOptions(overrides: Partial<ExportOptions> = {}): ExportOptions {
+ return {
+ format: 'png',
+ quality: 'high',
+ scale: 1,
+ background: 'include',
+ ...overrides,
+ };
+}
+
+// ── Tests ─────────────────────────────────────────────────────────────────────
+
+describe('export-service', () => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ let createElementSpy: any;
+
+ beforeEach(() => {
+ // Intercept canvas creation and substitute the mock.
+ createElementSpy = vi.spyOn(document, 'createElement').mockImplementation((tag: string) => {
+ if (tag === 'canvas') {
+ return makeMockCanvas() as unknown as HTMLCanvasElement;
+ }
+ // Fall through for other tags (e.g. img).
+ return document.createElement.call(document, tag);
+ });
+ });
+
+ afterEach(() => {
+ createElementSpy.mockRestore();
+ });
+
+ // ── exportArtboard ──────────────────────────────────────────────────────
+
+ describe('exportArtboard', () => {
+ it('returns a Blob for PNG format', async () => {
+ const project = makeProject();
+ const blob = await exportArtboard(project, project.artboards[0], makeOptions({ format: 'png' }));
+ expect(blob).toBeInstanceOf(Blob);
+ });
+
+ it('returns a Blob for JPEG format', async () => {
+ const project = makeProject();
+ const blob = await exportArtboard(
+ project,
+ project.artboards[0],
+ makeOptions({ format: 'jpg' }),
+ );
+ expect(blob).toBeInstanceOf(Blob);
+ });
+
+ it('returns a Blob for WebP format', async () => {
+ const project = makeProject();
+ const blob = await exportArtboard(
+ project,
+ project.artboards[0],
+ makeOptions({ format: 'webp' }),
+ );
+ expect(blob).toBeInstanceOf(Blob);
+ });
+
+ it('creates a canvas with the artboard dimensions × scale', async () => {
+ const project = makeProject();
+ await exportArtboard(project, project.artboards[0], makeOptions({ scale: 2 }));
+
+ // The canvas created by exportArtboard should have been given the scaled dimensions.
+ const mockCanvas = (createElementSpy.mock.results[0].value as ReturnType<typeof makeMockCanvas>);
+ expect(mockCanvas.width).toBe(800); // 400 × 2
+ expect(mockCanvas.height).toBe(600); // 300 × 2
+ });
+
+ it('fills background colour for include mode', async () => {
+ const project = makeProject();
+ const artboard = project.artboards[0];
+ await exportArtboard(project, artboard, makeOptions({ background: 'include', format: 'png' }));
+
+ const mockCanvas = createElementSpy.mock.results[0].value as ReturnType<typeof makeMockCanvas>;
+ expect(mockCanvas._ctx.fillRect).toHaveBeenCalled();
+ });
+
+ it('does not fill background for transparent mode (PNG)', async () => {
+ const project = makeProject();
+ await exportArtboard(
+ project,
+ project.artboards[0],
+ makeOptions({ background: 'transparent', format: 'png' }),
+ );
+
+ const mockCanvas = createElementSpy.mock.results[0].value as ReturnType<typeof makeMockCanvas>;
+ expect(mockCanvas._ctx.fillRect).not.toHaveBeenCalled();
+ });
+
+ it('always fills background for JPEG (no transparency)', async () => {
+ const project = makeProject([
+ { ...makeArtboard(), background: { type: 'transparent' } },
+ ]);
+ await exportArtboard(
+ project,
+ project.artboards[0],
+ makeOptions({ background: 'transparent', format: 'jpg' }),
+ );
+
+ const mockCanvas = createElementSpy.mock.results[0].value as ReturnType<typeof makeMockCanvas>;
+ expect(mockCanvas._ctx.fillRect).toHaveBeenCalled();
+ });
+ });
+
+ // ── exportProject ───────────────────────────────────────────────────────
+
+ describe('exportProject', () => {
+ it('returns one blob per artboard', async () => {
+ const project = makeProject([makeArtboard('a1'), makeArtboard('a2')]);
+ const blobs = await exportProject(project, makeOptions());
+ expect(blobs).toHaveLength(2);
+ });
+
+ it('filters artboards when artboardIds is provided', async () => {
+ const project = makeProject([makeArtboard('a1'), makeArtboard('a2'), makeArtboard('a3')]);
+ const blobs = await exportProject(project, makeOptions({ artboardIds: ['a1', 'a3'] }));
+ expect(blobs).toHaveLength(2);
+ });
+
+ it('calls onProgress with 100% at the end', async () => {
+ const project = makeProject();
+ const onProgress = vi.fn();
+ await exportProject(project, makeOptions(), onProgress);
+ const lastCall = onProgress.mock.calls[onProgress.mock.calls.length - 1];
+ expect(lastCall[0]).toBe(100);
+ });
+
+ it('reports progress for each artboard', async () => {
+ const project = makeProject([makeArtboard('a1'), makeArtboard('a2')]);
+ const onProgress = vi.fn();
+ await exportProject(project, makeOptions(), onProgress);
+ // At minimum one intermediate progress call before the final 100.
+ expect(onProgress.mock.calls.length).toBeGreaterThanOrEqual(2);
+ });
+ });
+});
diff --git a/apps/image/src/services/project-migration.ts b/apps/image/src/services/project-migration.ts
new file mode 100644
index 00000000..94fba62f
--- /dev/null
+++ b/apps/image/src/services/project-migration.ts
@@ -0,0 +1,50 @@
+import type { Project } from '../types/project';
+
+/** The current document format version. Increment when the schema changes. */
+export const CURRENT_VERSION = 1;
+
+/**
+ * Apply all pending migrations to bring `raw` up to the current version.
+ * Unknown versions are returned as-is so callers can fail validation instead.
+ */
+export function migrateProject(raw: Record<string, unknown>): Record<string, unknown> {
+ let doc = { ...raw };
+ const version = typeof doc.version === 'number' ? doc.version : 0;
+
+ // Version 0 → 1: add explicit `version` field and `activeArtboardId` if missing.
+ if (version < 1) {
+ doc = migrateV0ToV1(doc);
+ }
+
+ // Future migrations go here, e.g.:
+ // if (doc.version < 2) { doc = migrateV1ToV2(doc); }
+
+ return doc;
+}
+
+function migrateV0ToV1(doc: Record<string, unknown>): Record<string, unknown> {
+ const updated: Record<string, unknown> = { ...doc };
+
+ updated.version = 1;
+
+ // Ensure activeArtboardId exists.
+ if (updated.activeArtboardId === undefined) {
+ const artboards = Array.isArray(updated.artboards) ? updated.artboards : [];
+ updated.activeArtboardId =
+ artboards.length > 0 && typeof artboards[0] === 'object' && artboards[0] !== null
+ ? (artboards[0] as Record<string, unknown>).id ?? null
+ : null;
+ }
+
+ return updated;
+}
+
+/**
+ * Convenience wrapper used by the project store.
+ * Migrates the raw object and returns it cast to `Project`.
+ * Always run `parseProject` on the result to verify correctness.
+ */
+export function migrateAndCast(raw: unknown): Project {
+ const migrated = migrateProject(raw as Record<string, unknown>);
+ return migrated as unknown as Project;
+}
diff --git a/apps/image/src/services/project-schema.ts b/apps/image/src/services/project-schema.ts
new file mode 100644
index 00000000..8433cc66
--- /dev/null
+++ b/apps/image/src/services/project-schema.ts
@@ -0,0 +1,414 @@
+import { z } from 'zod';
+
+// ── Primitives ──────────────────────────────────────────────────────────────
+
+const TransformSchema = z.object({
+ x: z.number(),
+ y: z.number(),
+ width: z.number(),
+ height: z.number(),
+ rotation: z.number(),
+ scaleX: z.number(),
+ scaleY: z.number(),
+ skewX: z.number(),
+ skewY: z.number(),
+ opacity: z.number(),
+});
+
+const BlendModeSchema = z.object({
+ mode: z.enum([
+ 'normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten',
+ 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion',
+ ]),
+});
+
+const ShadowSchema = z.object({
+ enabled: z.boolean(),
+ color: z.string(),
+ blur: z.number(),
+ offsetX: z.number(),
+ offsetY: z.number(),
+});
+
+const InnerShadowSchema = z.object({
+ enabled: z.boolean(),
+ color: z.string(),
+ blur: z.number(),
+ offsetX: z.number(),
+ offsetY: z.number(),
+});
+
+const StrokeSchema = z.object({
+ enabled: z.boolean(),
+ color: z.string(),
+ width: z.number(),
+ style: z.enum(['solid', 'dashed', 'dotted']),
+});
+
+const GlowSchema = z.object({
+ enabled: z.boolean(),
+ color: z.string(),
+ blur: z.number(),
+ intensity: z.number(),
+});
+
+const FilterSchema = z.object({
+ brightness: z.number(),
+ contrast: z.number(),
+ saturation: z.number(),
+ hue: z.number(),
+ exposure: z.number(),
+ vibrance: z.number(),
+ highlights: z.number(),
+ shadows: z.number(),
+ clarity: z.number(),
+ blur: z.number(),
+ blurType: z.enum(['gaussian', 'motion', 'radial']),
+ blurAngle: z.number(),
+ sharpen: z.number(),
+ vignette: z.number(),
+ grain: z.number(),
+ sepia: z.number(),
+ invert: z.number(),
+});
+
+// ── Adjustments ──────────────────────────────────────────────────────────────
+
+const LevelsChannelSchema = z.object({
+ inputBlack: z.number(),
+ inputWhite: z.number(),
+ gamma: z.number(),
+ outputBlack: z.number(),
+ outputWhite: z.number(),
+});
+
+const LevelsSchema = z.object({
+ enabled: z.boolean(),
+ master: LevelsChannelSchema,
+ red: LevelsChannelSchema,
+ green: LevelsChannelSchema,
+ blue: LevelsChannelSchema,
+});
+
+const CurvePointSchema = z.object({ input: z.number(), output: z.number() });
+
+const CurvesChannelSchema = z.object({ points: z.array(CurvePointSchema) });
+
+const CurvesSchema = z.object({
+ enabled: z.boolean(),
+ master: CurvesChannelSchema,
+ red: CurvesChannelSchema,
+ green: CurvesChannelSchema,
+ blue: CurvesChannelSchema,
+});
+
+const ColorBalanceValuesSchema = z.object({
+ cyanRed: z.number(),
+ magentaGreen: z.number(),
+ yellowBlue: z.number(),
+});
+
+const ColorBalanceSchema = z.object({
+ enabled: z.boolean(),
+ shadows: ColorBalanceValuesSchema,
+ midtones: ColorBalanceValuesSchema,
+ highlights: ColorBalanceValuesSchema,
+ preserveLuminosity: z.boolean(),
+});
+
+const SelectiveColorValuesSchema = z.object({
+ cyan: z.number(),
+ magenta: z.number(),
+ yellow: z.number(),
+ black: z.number(),
+});
+
+const SelectiveColorSchema = z.object({
+ enabled: z.boolean(),
+ method: z.enum(['relative', 'absolute']),
+ reds: SelectiveColorValuesSchema,
+ yellows: SelectiveColorValuesSchema,
+ greens: SelectiveColorValuesSchema,
+ cyans: SelectiveColorValuesSchema,
+ blues: SelectiveColorValuesSchema,
+ magentas: SelectiveColorValuesSchema,
+ whites: SelectiveColorValuesSchema,
+ neutrals: SelectiveColorValuesSchema,
+ blacks: SelectiveColorValuesSchema,
+});
+
+const BlackWhiteSchema = z.object({
+ enabled: z.boolean(),
+ reds: z.number(),
+ yellows: z.number(),
+ greens: z.number(),
+ cyans: z.number(),
+ blues: z.number(),
+ magentas: z.number(),
+ tintEnabled: z.boolean(),
+ tintHue: z.number(),
+ tintSaturation: z.number(),
+});
+
+const PhotoFilterSchema = z.object({
+ enabled: z.boolean(),
+ filter: z.enum(['warming-85', 'warming-81', 'cooling-80', 'cooling-82', 'custom']),
+ color: z.string(),
+ density: z.number(),
+ preserveLuminosity: z.boolean(),
+});
+
+const ChannelMixerChannelSchema = z.object({
+ red: z.number(),
+ green: z.number(),
+ blue: z.number(),
+ constant: z.number(),
+});
+
+const ChannelMixerSchema = z.object({
+ enabled: z.boolean(),
+ monochrome: z.boolean(),
+ red: ChannelMixerChannelSchema,
+ green: ChannelMixerChannelSchema,
+ blue: ChannelMixerChannelSchema,
+});
+
+const GradientMapStopSchema = z.object({ position: z.number(), color: z.string() });
+
+const GradientMapSchema = z.object({
+ enabled: z.boolean(),
+ stops: z.array(GradientMapStopSchema),
+ reverse: z.boolean(),
+ dither: z.boolean(),
+});
+
+const PosterizeSchema = z.object({
+ enabled: z.boolean(),
+ levels: z.number(),
+});
+
+const ThresholdSchema = z.object({
+ enabled: z.boolean(),
+ level: z.number(),
+});
+
+// ── Mask ──────────────────────────────────────────────────────────────────────
+
+const LayerMaskSchema = z.object({
+ id: z.string(),
+ type: z.enum(['pixel', 'vector']),
+ enabled: z.boolean(),
+ linked: z.boolean(),
+ density: z.number(),
+ feather: z.number(),
+ invert: z.boolean(),
+ data: z.string().nullable(),
+ vectorPath: z.array(z.object({ x: z.number(), y: z.number() })).nullable(),
+});
+
+// ── Layer base ────────────────────────────────────────────────────────────────
+
+const BaseLayerSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ type: z.enum(['image', 'text', 'shape', 'group']),
+ visible: z.boolean(),
+ locked: z.boolean(),
+ transform: TransformSchema,
+ blendMode: BlendModeSchema,
+ shadow: ShadowSchema,
+ innerShadow: InnerShadowSchema,
+ stroke: StrokeSchema,
+ glow: GlowSchema,
+ filters: FilterSchema,
+ parentId: z.string().nullable(),
+ flipHorizontal: z.boolean(),
+ flipVertical: z.boolean(),
+ mask: LayerMaskSchema.nullable(),
+ clippingMask: z.boolean(),
+ levels: LevelsSchema,
+ curves: CurvesSchema,
+ colorBalance: ColorBalanceSchema,
+ selectiveColor: SelectiveColorSchema,
+ blackWhite: BlackWhiteSchema,
+ photoFilter: PhotoFilterSchema,
+ channelMixer: ChannelMixerSchema,
+ gradientMap: GradientMapSchema,
+ posterize: PosterizeSchema,
+ threshold: ThresholdSchema,
+});
+
+// ── Layer variants ────────────────────────────────────────────────────────────
+
+const ImageLayerSchema = BaseLayerSchema.extend({
+ type: z.literal('image'),
+ sourceId: z.string(),
+ cropRect: z
+ .object({ x: z.number(), y: z.number(), width: z.number(), height: z.number() })
+ .nullable(),
+});
+
+const GradientStopSchema = z.object({ offset: z.number(), color: z.string() });
+
+const GradientSchema = z.object({
+ type: z.enum(['linear', 'radial']),
+ angle: z.number(),
+ stops: z.array(GradientStopSchema),
+});
+
+const TextShadowSchema = z.object({
+ enabled: z.boolean(),
+ color: z.string(),
+ blur: z.number(),
+ offsetX: z.number(),
+ offsetY: z.number(),
+});
+
+const TextStyleSchema = z.object({
+ fontFamily: z.string(),
+ fontSize: z.number(),
+ fontWeight: z.number(),
+ fontStyle: z.enum(['normal', 'italic']),
+ textDecoration: z.enum(['none', 'underline', 'line-through']),
+ textAlign: z.enum(['left', 'center', 'right', 'justify']),
+ verticalAlign: z.enum(['top', 'middle', 'bottom']),
+ lineHeight: z.number(),
+ letterSpacing: z.number(),
+ fillType: z.enum(['solid', 'gradient']),
+ color: z.string(),
+ gradient: GradientSchema.nullable(),
+ strokeColor: z.string().nullable(),
+ strokeWidth: z.number(),
+ backgroundColor: z.string().nullable(),
+ backgroundPadding: z.number(),
+ backgroundRadius: z.number(),
+ textShadow: TextShadowSchema,
+});
+
+const TextLayerSchema = BaseLayerSchema.extend({
+ type: z.literal('text'),
+ content: z.string(),
+ style: TextStyleSchema,
+ autoSize: z.boolean(),
+});
+
+const CornerRadiusSchema = z.object({
+ topLeft: z.number(),
+ topRight: z.number(),
+ bottomRight: z.number(),
+ bottomLeft: z.number(),
+});
+
+const NoiseFillSchema = z.object({
+ baseColor: z.string(),
+ noiseColor: z.string(),
+ density: z.number(),
+ size: z.number(),
+});
+
+const ShapeStyleSchema = z.object({
+ fillType: z.enum(['solid', 'gradient', 'noise']),
+ fill: z.string().nullable(),
+ gradient: GradientSchema.nullable(),
+ noise: NoiseFillSchema.nullable(),
+ fillOpacity: z.number(),
+ stroke: z.string().nullable(),
+ strokeWidth: z.number(),
+ strokeOpacity: z.number(),
+ strokeDash: z.enum(['solid', 'dashed', 'dotted', 'dash-dot', 'long-dash']),
+ cornerRadius: z.number(),
+ individualCorners: z.boolean(),
+ corners: CornerRadiusSchema,
+});
+
+const ShapeLayerSchema = BaseLayerSchema.extend({
+ type: z.literal('shape'),
+ shapeType: z.enum([
+ 'rectangle', 'ellipse', 'triangle', 'polygon', 'star', 'line', 'arrow', 'path',
+ ]),
+ shapeStyle: ShapeStyleSchema,
+ points: z.array(z.object({ x: z.number(), y: z.number() })).optional(),
+ sides: z.number().optional(),
+ innerRadius: z.number().optional(),
+});
+
+const GroupLayerSchema = BaseLayerSchema.extend({
+ type: z.literal('group'),
+ childIds: z.array(z.string()),
+ expanded: z.boolean(),
+});
+
+export const LayerSchema = z.discriminatedUnion('type', [
+ ImageLayerSchema,
+ TextLayerSchema,
+ ShapeLayerSchema,
+ GroupLayerSchema,
+]);
+
+// ── Project types ─────────────────────────────────────────────────────────────
+
+const CanvasSizeSchema = z.object({ width: z.number(), height: z.number() });
+
+const CanvasBackgroundSchema = z.object({
+ type: z.enum(['color', 'gradient', 'image', 'transparent']),
+ color: z.string().optional(),
+ gradient: z
+ .object({
+ type: z.enum(['linear', 'radial']),
+ angle: z.number(),
+ stops: z.array(z.object({ offset: z.number(), color: z.string() })),
+ })
+ .optional(),
+ imageId: z.string().optional(),
+});
+
+export const ArtboardSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ size: CanvasSizeSchema,
+ background: CanvasBackgroundSchema,
+ layerIds: z.array(z.string()),
+ position: z.object({ x: z.number(), y: z.number() }),
+});
+
+const MediaAssetSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ type: z.enum(['image', 'svg']),
+ mimeType: z.string(),
+ size: z.number(),
+ width: z.number(),
+ height: z.number(),
+ thumbnailUrl: z.string(),
+ dataUrl: z.string().optional(),
+ blobUrl: z.string().optional(),
+});
+
+/** Current project schema (version 1). */
+export const ProjectSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ createdAt: z.number(),
+ updatedAt: z.number(),
+ version: z.number(),
+ artboards: z.array(ArtboardSchema),
+ layers: z.record(z.string(), LayerSchema),
+ assets: z.record(z.string(), MediaAssetSchema),
+ activeArtboardId: z.string().nullable(),
+});
+
+export type ParsedProject = z.infer<typeof ProjectSchema>;
+
+/**
+ * Validate an unknown value against the Project schema.
+ * Returns `{ success: true, data }` on success or `{ success: false, error }` on failure.
+ */
+export function parseProject(
+ raw: unknown,
+): { success: true; data: ParsedProject } | { success: false; error: string } {
+ const result = ProjectSchema.safeParse(raw);
+ if (result.success) {
+ return { success: true, data: result.data };
+ }
+ return { success: false, error: result.error.message };
+}
diff --git a/apps/image/src/stores/project-store.test.ts b/apps/image/src/stores/project-store.test.ts
new file mode 100644
index 00000000..a504fbb3
--- /dev/null
+++ b/apps/image/src/stores/project-store.test.ts
@@ -0,0 +1,393 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { useProjectStore } from './project-store';
+
+const DEFAULT_SIZE = { width: 1080, height: 1080 };
+const DEFAULT_BG = { type: 'color' as const, color: '#ffffff' };
+
+/**
+ * Reset the store to a pristine state before each test so tests are isolated.
+ */
+function resetStore() {
+ useProjectStore.setState({
+ project: null,
+ selectedLayerIds: [],
+ selectedArtboardId: null,
+ copiedLayers: [],
+ copiedStyle: null,
+ isDirty: false,
+ });
+}
+
+// ── Helpers ──────────────────────────────────────────────────────────────────
+
+function createProject(name = 'Test') {
+ useProjectStore.getState().createProject(name, DEFAULT_SIZE, DEFAULT_BG);
+ return useProjectStore.getState();
+}
+
+// ── Tests ────────────────────────────────────────────────────────────────────
+
+describe('project-store', () => {
+ beforeEach(resetStore);
+
+ // ── Project lifecycle ───────────────────────────────────────────────────
+
+ describe('createProject', () => {
+ it('creates a project with the given name', () => {
+ createProject('My Design');
+ const { project } = useProjectStore.getState();
+ expect(project).not.toBeNull();
+ expect(project?.name).toBe('My Design');
+ });
+
+ it('initialises project with version 1', () => {
+ createProject();
+ expect(useProjectStore.getState().project?.version).toBe(1);
+ });
+
+ it('creates one default artboard', () => {
+ createProject();
+ const { project } = useProjectStore.getState();
+ expect(project?.artboards).toHaveLength(1);
+ });
+
+ it('sets the active artboard to the initial artboard', () => {
+ createProject();
+ const { project, selectedArtboardId } = useProjectStore.getState();
+ expect(project?.activeArtboardId).toBe(selectedArtboardId);
+ });
+
+ it('starts with an empty layers map', () => {
+ createProject();
+ expect(useProjectStore.getState().project?.layers).toEqual({});
+ });
+
+ it('marks the project as dirty', () => {
+ createProject();
+ expect(useProjectStore.getState().isDirty).toBe(true);
+ });
+
+ it('applies a custom background colour', () => {
+ useProjectStore.getState().createProject('bg-test', DEFAULT_SIZE, {
+ type: 'color',
+ color: '#ff0000',
+ });
+ const artboard = useProjectStore.getState().project?.artboards[0];
+ expect(artboard?.background).toEqual({ type: 'color', color: '#ff0000' });
+ });
+ });
+
+ describe('loadProject', () => {
+ it('loads a valid project', () => {
+ createProject('Original');
+ const snapshot = useProjectStore.getState().project!;
+
+ resetStore();
+ useProjectStore.getState().loadProject(snapshot);
+
+ expect(useProjectStore.getState().project?.name).toBe('Original');
+ expect(useProjectStore.getState().isDirty).toBe(false);
+ });
+
+ it('rejects a project with missing required fields and keeps state null', () => {
+ resetStore();
+ // Supply an invalid/incomplete object – loadProject should reject it.
+ useProjectStore
+ .getState()
+ .loadProject({ id: 'bad', name: 'broken' } as never);
+ expect(useProjectStore.getState().project).toBeNull();
+ });
+ });
+
+ describe('closeProject', () => {
+ it('clears the project', () => {
+ createProject();
+ useProjectStore.getState().closeProject();
+ expect(useProjectStore.getState().project).toBeNull();
+ expect(useProjectStore.getState().isDirty).toBe(false);
+ });
+ });
+
+ describe('setProjectName', () => {
+ it('updates the project name', () => {
+ createProject('Old');
+ useProjectStore.getState().setProjectName('New');
+ expect(useProjectStore.getState().project?.name).toBe('New');
+ expect(useProjectStore.getState().isDirty).toBe(true);
+ });
+ });
+
+ // ── Artboard operations ──────────────────────────────────────────────────
+
+ describe('addArtboard', () => {
+ it('adds a second artboard', () => {
+ createProject();
+ useProjectStore.getState().addArtboard('Page 2', DEFAULT_SIZE);
+ expect(useProjectStore.getState().project?.artboards).toHaveLength(2);
+ });
+
+ it('returns the new artboard id', () => {
+ createProject();
+ const id = useProjectStore.getState().addArtboard('Page 2', DEFAULT_SIZE);
+ expect(typeof id).toBe('string');
+ expect(id.length).toBeGreaterThan(0);
+ });
+
+ it('uses the provided position', () => {
+ createProject();
+ const id = useProjectStore
+ .getState()
+ .addArtboard('Pos', DEFAULT_SIZE, { x: 200, y: 300 });
+ const artboard = useProjectStore
+ .getState()
+ .project?.artboards.find((a) => a.id === id);
+ expect(artboard?.position).toEqual({ x: 200, y: 300 });
+ });
+ });
+
+ describe('removeArtboard', () => {
+ it('removes an artboard when more than one exists', () => {
+ createProject();
+ const id = useProjectStore.getState().addArtboard('Extra', DEFAULT_SIZE);
+ useProjectStore.getState().removeArtboard(id);
+ expect(
+ useProjectStore.getState().project?.artboards.find((a) => a.id === id),
+ ).toBeUndefined();
+ });
+
+ it('does not remove the last artboard', () => {
+ createProject();
+ const { project } = useProjectStore.getState();
+ const onlyId = project!.artboards[0].id;
+ useProjectStore.getState().removeArtboard(onlyId);
+ expect(useProjectStore.getState().project?.artboards).toHaveLength(1);
+ });
+ });
+
+ describe('updateArtboard', () => {
+ it('updates the artboard name', () => {
+ createProject();
+ const { selectedArtboardId } = useProjectStore.getState();
+ useProjectStore
+ .getState()
+ .updateArtboard(selectedArtboardId!, { name: 'Renamed' });
+ const updated = useProjectStore
+ .getState()
+ .project?.artboards.find((a) => a.id === selectedArtboardId);
+ expect(updated?.name).toBe('Renamed');
+ });
+
+ it('updates the artboard size', () => {
+ createProject();
+ const { selectedArtboardId } = useProjectStore.getState();
+ const newSize = { width: 800, height: 600 };
+ useProjectStore
+ .getState()
+ .updateArtboard(selectedArtboardId!, { size: newSize });
+ const updated = useProjectStore
+ .getState()
+ .project?.artboards.find((a) => a.id === selectedArtboardId);
+ expect(updated?.size).toEqual(newSize);
+ });
+ });
+
+ // ── Layer operations ──────────────────────────────────────────────────────
+
+ describe('addTextLayer', () => {
+ it('adds a text layer to the active artboard', () => {
+ createProject();
+ useProjectStore.getState().addTextLayer('Hello');
+ const { project, selectedArtboardId } = useProjectStore.getState();
+ const artboard = project?.artboards.find((a) => a.id === selectedArtboardId);
+ expect(artboard?.layerIds).toHaveLength(1);
+ });
+
+ it('returns the new layer id', () => {
+ createProject();
+ const id = useProjectStore.getState().addTextLayer('Hi');
+ expect(typeof id).toBe('string');
+ });
+
+ it('stores the layer in the layers map', () => {
+ createProject();
+ const id = useProjectStore.getState().addTextLayer('World');
+ const layer = useProjectStore.getState().project?.layers[id];
+ expect(layer?.type).toBe('text');
+ expect((layer as { content: string })?.content).toBe('World');
+ });
+ });
+
+ describe('addShapeLayer', () => {
+ it('adds a shape layer with the given shape type', () => {
+ createProject();
+ const id = useProjectStore.getState().addShapeLayer('rectangle');
+ const layer = useProjectStore.getState().project?.layers[id];
+ expect(layer?.type).toBe('shape');
+ });
+ });
+
+ describe('removeLayer', () => {
+ it('removes the layer from the artboard', () => {
+ createProject();
+ const id = useProjectStore.getState().addTextLayer('Delete me');
+ useProjectStore.getState().removeLayer(id);
+ const { project, selectedArtboardId } = useProjectStore.getState();
+ const artboard = project?.artboards.find((a) => a.id === selectedArtboardId);
+ expect(artboard?.layerIds).not.toContain(id);
+ expect(project?.layers[id]).toBeUndefined();
+ });
+
+ it('deselects the removed layer', () => {
+ createProject();
+ const id = useProjectStore.getState().addTextLayer('Remove select');
+ useProjectStore.getState().selectLayer(id);
+ useProjectStore.getState().removeLayer(id);
+ expect(useProjectStore.getState().selectedLayerIds).not.toContain(id);
+ });
+ });
+
+ describe('duplicateLayer', () => {
+ it('creates a copy of the layer', () => {
+ createProject();
+ const id = useProjectStore.getState().addTextLayer('Original');
+ const newId = useProjectStore.getState().duplicateLayer(id);
+ expect(newId).not.toBeNull();
+ expect(newId).not.toBe(id);
+ const copy = useProjectStore.getState().project?.layers[newId!];
+ expect(copy?.type).toBe('text');
+ });
+
+ it('names the copy with " copy" suffix', () => {
+ createProject();
+ const id = useProjectStore.getState().addTextLayer('Layer');
+ const newId = useProjectStore.getState().duplicateLayer(id);
+ const copy = useProjectStore.getState().project?.layers[newId!];
+ expect(copy?.name.endsWith('copy')).toBe(true);
+ });
+
+ it('offsets the duplicate position by 20', () => {
+ createProject();
+ const id = useProjectStore.getState().addTextLayer('Offset');
+ const orig = useProjectStore.getState().project?.layers[id];
+ const newId = useProjectStore.getState().duplicateLayer(id);
+ const copy = useProjectStore.getState().project?.layers[newId!];
+ expect(copy?.transform.x).toBe(orig!.transform.x + 20);
+ expect(copy?.transform.y).toBe(orig!.transform.y + 20);
+ });
+
+ it('adds the duplicate to the artboard layer list', () => {
+ createProject();
+ const id = useProjectStore.getState().addTextLayer('Dup');
+ const newId = useProjectStore.getState().duplicateLayer(id);
+ const { project, selectedArtboardId } = useProjectStore.getState();
+ const artboard = project?.artboards.find((a) => a.id === selectedArtboardId);
+ expect(artboard?.layerIds).toContain(newId!);
+ });
+ });
+
+ describe('reorder layers', () => {
+ it('moveLayerDown moves the layer one position down in the list', () => {
+ createProject();
+ const id1 = useProjectStore.getState().addTextLayer('A');
+ const id2 = useProjectStore.getState().addTextLayer('B');
+
+ // After adding, order is [id2, id1] (newest on top).
+ const { project, selectedArtboardId } = useProjectStore.getState();
+ const artboard = project!.artboards.find((a) => a.id === selectedArtboardId)!;
+ expect(artboard.layerIds[0]).toBe(id2);
+
+ useProjectStore.getState().moveLayerDown(id2);
+ const updated = useProjectStore
+ .getState()
+ .project!.artboards.find((a) => a.id === selectedArtboardId)!;
+ expect(updated.layerIds[0]).toBe(id1);
+ expect(updated.layerIds[1]).toBe(id2);
+ });
+
+ it('moveLayerUp moves the layer one position up in the list', () => {
+ createProject();
+ const id1 = useProjectStore.getState().addTextLayer('A');
+ const id2 = useProjectStore.getState().addTextLayer('B');
+
+ // order: [id2, id1]
+ useProjectStore.getState().moveLayerUp(id1);
+ const updated = useProjectStore
+ .getState()
+ .project!.artboards.find(
+ (a) => a.id === useProjectStore.getState().selectedArtboardId,
+ )!;
+ expect(updated.layerIds[0]).toBe(id1);
+ expect(updated.layerIds[1]).toBe(id2);
+ });
+
+ it('moveLayerToTop moves the layer to position 0', () => {
+ createProject();
+ const id1 = useProjectStore.getState().addTextLayer('A');
+ useProjectStore.getState().addTextLayer('B');
+ useProjectStore.getState().addTextLayer('C');
+
+ useProjectStore.getState().moveLayerToTop(id1);
+ const artboard = useProjectStore
+ .getState()
+ .project!.artboards.find(
+ (a) => a.id === useProjectStore.getState().selectedArtboardId,
+ )!;
+ expect(artboard.layerIds[0]).toBe(id1);
+ });
+
+ it('moveLayerToBottom moves the layer to the last position', () => {
+ createProject();
+ useProjectStore.getState().addTextLayer('A');
+ useProjectStore.getState().addTextLayer('B');
+ const id3 = useProjectStore.getState().addTextLayer('C');
+
+ useProjectStore.getState().moveLayerToBottom(id3);
+ const artboard = useProjectStore
+ .getState()
+ .project!.artboards.find(
+ (a) => a.id === useProjectStore.getState().selectedArtboardId,
+ )!;
+ expect(artboard.layerIds[artboard.layerIds.length - 1]).toBe(id3);
+ });
+
+ it('reorderLayers replaces the full layer order', () => {
+ createProject();
+ const id1 = useProjectStore.getState().addTextLayer('A');
+ const id2 = useProjectStore.getState().addTextLayer('B');
+
+ useProjectStore.getState().reorderLayers([id1, id2]);
+ const artboard = useProjectStore
+ .getState()
+ .project!.artboards.find(
+ (a) => a.id === useProjectStore.getState().selectedArtboardId,
+ )!;
+ expect(artboard.layerIds).toEqual([id1, id2]);
+ });
+ });
+
+ describe('groupLayers / ungroupLayers', () => {
+ it('groups two layers into a group layer', () => {
+ createProject();
+ const id1 = useProjectStore.getState().addShapeLayer('rectangle');
+ const id2 = useProjectStore.getState().addShapeLayer('ellipse');
+ const groupId = useProjectStore.getState().groupLayers([id1, id2]);
+ expect(groupId).not.toBeNull();
+ const group = useProjectStore.getState().project?.layers[groupId!];
+ expect(group?.type).toBe('group');
+ });
+
+ it('ungroups a group layer and restores children to the artboard', () => {
+ createProject();
+ const id1 = useProjectStore.getState().addShapeLayer('rectangle');
+ const id2 = useProjectStore.getState().addShapeLayer('ellipse');
+ const groupId = useProjectStore.getState().groupLayers([id1, id2])!;
+ useProjectStore.getState().ungroupLayers(groupId);
+
+ const { project, selectedArtboardId } = useProjectStore.getState();
+ const artboard = project!.artboards.find((a) => a.id === selectedArtboardId)!;
+ expect(artboard.layerIds).toContain(id1);
+ expect(artboard.layerIds).toContain(id2);
+ expect(project?.layers[groupId]).toBeUndefined();
+ });
+ });
+});
diff --git a/apps/image/src/stores/project-store.ts b/apps/image/src/stores/project-store.ts
index 9fcd4278..cc96394b 100644
--- a/apps/image/src/stores/project-store.ts
+++ b/apps/image/src/stores/project-store.ts
@@ -1,6 +1,8 @@
import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
+import { parseProject } from '../services/project-schema';
+import { migrateProject } from '../services/project-migration';
import {
Project,
Layer,
@@ -142,10 +144,17 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
},
loadProject: (project) => {
+ const migrated = migrateProject(project as unknown as Record<string, unknown>);
+ const parsed = parseProject(migrated);
+ if (!parsed.success) {
+ console.error('[project-store] Invalid project:', parsed.error);
+ return;
+ }
+ const validated = parsed.data;
set({
- project,
+ project: validated,
selectedLayerIds: [],
- selectedArtboardId: project.activeArtboardId,
+ selectedArtboardId: validated.activeArtboardId,
isDirty: false,
});
},
diff --git a/apps/image/src/test/setup.ts b/apps/image/src/test/setup.ts
new file mode 100644
index 00000000..7b0828bf
--- /dev/null
+++ b/apps/image/src/test/setup.ts
@@ -0,0 +1 @@
+import '@testing-library/jest-dom';
diff --git a/apps/image/vitest.config.ts b/apps/image/vitest.config.ts
new file mode 100644
index 00000000..18888e9d
--- /dev/null
+++ b/apps/image/vitest.config.ts
@@ -0,0 +1,27 @@
+import { defineConfig } from 'vitest/config';
+import react from '@vitejs/plugin-react';
+import path from 'path';
+
+export default defineConfig({
+ plugins: [react()],
+ test: {
+ globals: true,
+ environment: 'jsdom',
+ include: [
+ 'src/**/*.test.ts',
+ 'src/**/*.test.tsx',
+ 'src/**/*.spec.ts',
+ 'src/**/*.spec.tsx',
+ ],
+ setupFiles: ['./src/test/setup.ts'],
+ coverage: {
+ provider: 'v8',
+ reporter: ['text', 'json', 'html'],
+ },
+ },
+ resolve: {
+ alias: {
+ '@': path.resolve(__dirname, './src'),
+ },
+ },
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ccf15bde..4de476d9 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -90,6 +90,9 @@ importers:
uuid:
specifier: ^13.0.0
version: 13.0.0
+ zod:
+ specifier: ^4.4.3
+ version: 4.4.3
zustand:
specifier: ^4.5.2
@@ -3701,8 +3704,8 @@ packages:
resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}
- resolution: {integrity: sha512-k7Nwx6vuWx1IJ9Bjuf4Zt1PEllcwe7cls3VNzm4CQ1/hgtFUK2bRNG3rvnpPUhFjmqJKAKtjV576KnUkHocg/g==}
+ resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}
resolution: {integrity: sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==}
@@ -5569,8 +5572,8 @@ snapshots:
'@babel/parser': 7.28.5
eslint: 9.39.2([email protected])
hermes-parser: 0.25.1
- zod: 4.3.5
- zod-validation-error: 4.0.2([email protected])
+ zod: 4.4.3
+ zod-validation-error: 4.0.2([email protected])
transitivePeerDependencies:
- supports-color
@@ -6865,15 +6868,15 @@ snapshots:
mustache: 4.2.0
stacktracey: 2.1.8
dependencies:
- zod: 4.3.5
+ zod: 4.4.3
dependencies: