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: implement command-based editing and history system

copilot-swe-agent[bot]d087aa46b882
diff --git a/apps/image/src/components/editor/panels/HistoryPanel.tsx b/apps/image/src/components/editor/panels/HistoryPanel.tsx
index 27369dc5..d8537b92 100644
--- a/apps/image/src/components/editor/panels/HistoryPanel.tsx
+++ b/apps/image/src/components/editor/panels/HistoryPanel.tsx
@@ -18,39 +18,30 @@ import { useProjectStore } from '../../../stores/project-store';
import { formatDistanceToNow } from '../../../utils/time';
export function HistoryPanel() {
- const {
- entries,
- currentIndex,
- snapshots,
- clear,
- canUndo,
- canRedo,
- goToEntry,
- createSnapshot,
- restoreSnapshot,
- deleteSnapshot,
- renameSnapshot,
- } = useHistoryStore();
- const { project, loadProject } = useProjectStore();
- const undo = useHistoryStore((s) => s.undo);
- const redo = useHistoryStore((s) => s.redo);
+ const entries = useHistoryStore((s) => s.getEntries());
+ const currentIndex = useHistoryStore((s) => s.getCurrentIndex());
+ const snapshots = useHistoryStore((s) => s.getSnapshots());
+ const clear = useHistoryStore((s) => s.clear);
+ const canUndo = useHistoryStore((s) => s.canUndo);
+ const canRedo = useHistoryStore((s) => s.canRedo);
+ const createSnapshot = useHistoryStore((s) => s.createSnapshot);
+ const restoreSnapshot = useHistoryStore((s) => s.restoreSnapshot);
+ const deleteSnapshot = useHistoryStore((s) => s.deleteSnapshot);
+ const renameSnapshot = useHistoryStore((s) => s.renameSnapshot);
+ const goToEntry = useHistoryStore((s) => s.goToEntry);
+
+ const { project, loadProject, undo, redo } = useProjectStore();
const [showSnapshots, setShowSnapshots] = useState(true);
const [editingSnapshotId, setEditingSnapshotId] = useState<string | null>(null);
const [editingName, setEditingName] = useState('');
const handleUndo = () => {
- const state = undo();
- if (state) {
- loadProject(state);
- }
+ undo();
};
const handleRedo = () => {
- const state = redo();
- if (state) {
- loadProject(state);
- }
+ redo();
};
const handleJumpToState = (index: number) => {
@@ -121,7 +112,7 @@ export function HistoryPanel() {
<Redo2 size={14} />
</button>
<button
- onClick={clear}
+ onClick={() => clear(project ?? undefined)}
disabled={entries.length === 0}
className="p-1.5 rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 disabled:opacity-40 disabled:hover:bg-transparent disabled:cursor-not-allowed transition-colors"
title="Clear history"
diff --git a/apps/image/src/components/editor/toolbar/Toolbar.tsx b/apps/image/src/components/editor/toolbar/Toolbar.tsx
index d9a86da3..bcdda1f8 100644
--- a/apps/image/src/components/editor/toolbar/Toolbar.tsx
+++ b/apps/image/src/components/editor/toolbar/Toolbar.tsx
@@ -39,7 +39,6 @@ import {
} from 'lucide-react';
import { useUIStore, Tool } from '../../../stores/ui-store';
import { useProjectStore } from '../../../stores/project-store';
-import { useHistoryStore } from '../../../stores/history-store';
import { ZoomControl } from './ZoomControl';
interface ToolItem {
@@ -247,21 +246,14 @@ export function Toolbar() {
openExportDialog,
} = useUIStore();
- const { project, setProjectName } = useProjectStore();
- const { canUndo, canRedo, undo, redo } = useHistoryStore();
+ const { project, setProjectName, undo, redo, canUndo, canRedo } = useProjectStore();
const handleUndo = () => {
- const state = undo();
- if (state) {
- useProjectStore.getState().loadProject(state);
- }
+ undo();
};
const handleRedo = () => {
- const state = redo();
- if (state) {
- useProjectStore.getState().loadProject(state);
- }
+ redo();
};
const handleSaveProject = () => {
diff --git a/apps/image/src/hooks/useAutoSave.ts b/apps/image/src/hooks/useAutoSave.ts
index 7e57ff6f..8b04f219 100644
--- a/apps/image/src/hooks/useAutoSave.ts
+++ b/apps/image/src/hooks/useAutoSave.ts
@@ -1,13 +1,11 @@
import { useEffect, useRef } from 'react';
import { useProjectStore } from '../stores/project-store';
-import { useHistoryStore } from '../stores/history-store';
const AUTO_SAVE_DELAY = 2000;
const STORAGE_KEY_PREFIX = 'openreel-image-project-';
export function useAutoSave() {
const { project, isDirty, markClean } = useProjectStore();
- const { pushState } = useHistoryStore();
const lastSavedRef = useRef<string>('');
const timeoutRef = useRef<number>();
@@ -26,8 +24,6 @@ export function useAutoSave() {
localStorage.setItem(`${STORAGE_KEY_PREFIX}${project.id}`, projectJson);
lastSavedRef.current = projectJson;
markClean();
-
- pushState(project, 'Auto-save');
} catch (error) {
console.error('Failed to auto-save:', error);
}
@@ -38,7 +34,7 @@ export function useAutoSave() {
clearTimeout(timeoutRef.current);
}
};
- }, [project, isDirty, markClean, pushState]);
+ }, [project, isDirty, markClean]);
}
export function loadSavedProject(projectId: string) {
diff --git a/apps/image/src/services/keyboard-service.ts b/apps/image/src/services/keyboard-service.ts
index d77defcb..fd084b0e 100644
--- a/apps/image/src/services/keyboard-service.ts
+++ b/apps/image/src/services/keyboard-service.ts
@@ -1,7 +1,6 @@
import { useEffect } from 'react';
import { useUIStore } from '../stores/ui-store';
import { useProjectStore } from '../stores/project-store';
-import { useHistoryStore } from '../stores/history-store';
export function useKeyboardShortcuts() {
const { setActiveTool, zoomIn, zoomOut, zoomToFit, toggleGrid, toggleGuides, toggleShortcutsPanel, openSettingsDialog } = useUIStore();
@@ -21,8 +20,11 @@ export function useKeyboardShortcuts() {
groupLayers,
ungroupLayers,
project,
+ undo,
+ redo,
+ canUndo,
+ canRedo,
} = useProjectStore();
- const { undo, redo, canUndo, canRedo } = useHistoryStore();
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
@@ -71,15 +73,9 @@ export function useKeyboardShortcuts() {
case 'z':
e.preventDefault();
if (e.shiftKey) {
- if (canRedo()) {
- const state = redo();
- if (state) useProjectStore.getState().loadProject(state);
- }
+ if (canRedo()) redo();
} else {
- if (canUndo()) {
- const state = undo();
- if (state) useProjectStore.getState().loadProject(state);
- }
+ if (canUndo()) undo();
}
break;
diff --git a/apps/image/src/stores/history-store.test.ts b/apps/image/src/stores/history-store.test.ts
new file mode 100644
index 00000000..19dc2cdb
--- /dev/null
+++ b/apps/image/src/stores/history-store.test.ts
@@ -0,0 +1,383 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { useHistoryStore } from './history-store';
+import { useProjectStore } from './project-store';
+import {
+ AddLayerCommand,
+ UpdateLayerTransformCommand,
+} from '@openreel/image-core/commands';
+
+const DEFAULT_SIZE = { width: 1080, height: 1080 };
+
+function resetStores() {
+ useHistoryStore.setState({
+ undoStack: [],
+ redoStack: [],
+ baseProject: null,
+ maxSize: 50,
+ snapshots: [],
+ });
+ useProjectStore.setState({
+ project: null,
+ selectedLayerIds: [],
+ selectedArtboardId: null,
+ copiedLayers: [],
+ copiedStyle: null,
+ isDirty: false,
+ });
+}
+
+function createProject() {
+ useProjectStore.getState().createProject('Test', DEFAULT_SIZE, { type: 'color', color: '#fff' });
+}
+
+function getProject() {
+ return useProjectStore.getState().project!;
+}
+
+function getArtboardId() {
+ return useProjectStore.getState().selectedArtboardId!;
+}
+
+describe('history-store (command-based)', () => {
+ beforeEach(resetStores);
+
+ // ── execute / canUndo / canRedo ──────────────────────────────────────────
+
+ describe('execute', () => {
+ it('executes a command and records it', () => {
+ createProject();
+ const project = getProject();
+ const artboardId = getArtboardId();
+
+ const layer = {
+ id: 'l-1',
+ name: 'T',
+ type: 'text' as const,
+ visible: true,
+ locked: false,
+ transform: { x: 0, y: 0, width: 100, height: 50, rotation: 0, scaleX: 1, scaleY: 1, skewX: 0, skewY: 0, opacity: 1 },
+ blendMode: { mode: 'normal' as const },
+ shadow: { enabled: false, color: '#000', blur: 10, offsetX: 0, offsetY: 4 },
+ innerShadow: { enabled: false, color: '#000', blur: 10, offsetX: 0, offsetY: 4 },
+ stroke: { enabled: false, color: '#000', width: 1, style: 'solid' as const },
+ glow: { enabled: false, color: '#fff', blur: 20, intensity: 1 },
+ filters: { brightness: 0, contrast: 0, saturation: 0, 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, inputBlack: 0, inputWhite: 255, gamma: 1, outputBlack: 0, outputWhite: 255 },
+ curves: { enabled: false, points: [] },
+ colorBalance: { enabled: false, shadows: [0,0,0] as [number,number,number], midtones: [0,0,0] as [number,number,number], highlights: [0,0,0] as [number,number,number], preserveLuminosity: true },
+ selectiveColor: { enabled: false, colors: {} },
+ blackWhite: { enabled: false, reds: 40, yellows: 60, greens: 40, cyans: 60, blues: 20, magentas: 80, tintEnabled: false, tintColor: '#e0c9a0' },
+ photoFilter: { enabled: false, color: '#f0a000', density: 25, luminosity: true },
+ channelMixer: { enabled: false, red: [100,0,0,0] as [number,number,number,number], green: [0,100,0,0] as [number,number,number,number], blue: [0,0,100,0] as [number,number,number,number], monochrome: false },
+ gradientMap: { enabled: false, stops: [] },
+ posterize: { enabled: false, levels: 4 },
+ threshold: { enabled: false, level: 128 },
+ content: 'T',
+ style: { fontFamily: 'Inter', fontSize: 16, 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: '#000000', gradient: null, strokeColor: null, strokeWidth: 0, backgroundColor: null, backgroundPadding: 4, backgroundRadius: 2, textShadow: { enabled: false, color: 'rgba(0,0,0,0.5)', blur: 4, offsetX: 2, offsetY: 2 } },
+ autoSize: true,
+ };
+ const cmd = new AddLayerCommand(artboardId, layer, 0);
+ useHistoryStore.getState().execute(cmd, project);
+
+ expect(useHistoryStore.getState().undoStack).toHaveLength(1);
+ expect(useHistoryStore.getState().redoStack).toHaveLength(0);
+ });
+
+ it('clears the redo stack on new command', () => {
+ createProject();
+ const project = getProject();
+ const artboardId = getArtboardId();
+
+ // Create a simple command, execute, undo, then execute another → redo should clear.
+ useProjectStore.getState().addTextLayer('A');
+ const hs = useHistoryStore.getState();
+ expect(hs.undoStack.length).toBeGreaterThanOrEqual(1);
+
+ useProjectStore.getState().undo();
+ expect(useHistoryStore.getState().redoStack.length).toBeGreaterThanOrEqual(1);
+
+ useProjectStore.getState().addTextLayer('B');
+ expect(useHistoryStore.getState().redoStack).toHaveLength(0);
+ });
+ });
+
+ describe('canUndo / canRedo', () => {
+ it('canUndo returns false when no commands have been executed', () => {
+ expect(useHistoryStore.getState().canUndo()).toBe(false);
+ });
+
+ it('canRedo returns false when no commands have been undone', () => {
+ expect(useHistoryStore.getState().canRedo()).toBe(false);
+ });
+
+ it('canUndo returns true after executing a command via project-store', () => {
+ createProject();
+ useProjectStore.getState().addTextLayer('Hello');
+ expect(useHistoryStore.getState().canUndo()).toBe(true);
+ });
+
+ it('canRedo returns true after undoing', () => {
+ createProject();
+ useProjectStore.getState().addTextLayer('Hello');
+ useProjectStore.getState().undo();
+ expect(useHistoryStore.getState().canRedo()).toBe(true);
+ });
+ });
+
+ // ── undo ─────────────────────────────────────────────────────────────────
+
+ describe('undo', () => {
+ it('undoes an add-layer command', () => {
+ createProject();
+ useProjectStore.getState().addTextLayer('Hello');
+ const idBefore = useProjectStore.getState().project!.artboards[0].layerIds;
+ expect(idBefore.length).toBe(1);
+
+ useProjectStore.getState().undo();
+ const idAfter = useProjectStore.getState().project!.artboards[0].layerIds;
+ expect(idAfter.length).toBe(0);
+ });
+
+ it('moves the command from undoStack to redoStack', () => {
+ createProject();
+ useProjectStore.getState().addTextLayer('Hello');
+ useProjectStore.getState().undo();
+ expect(useHistoryStore.getState().undoStack).toHaveLength(0);
+ expect(useHistoryStore.getState().redoStack).toHaveLength(1);
+ });
+
+ it('returns null when there is nothing to undo (via project-store)', () => {
+ createProject();
+ // No commands executed, undo should be no-op
+ const projectBefore = useProjectStore.getState().project;
+ useProjectStore.getState().undo();
+ // Project should remain unchanged
+ expect(useProjectStore.getState().project?.name).toBe(projectBefore?.name);
+ });
+ });
+
+ // ── redo ─────────────────────────────────────────────────────────────────
+
+ describe('redo', () => {
+ it('re-applies an undone command', () => {
+ createProject();
+ useProjectStore.getState().addTextLayer('Hello');
+ useProjectStore.getState().undo();
+ expect(useProjectStore.getState().project!.artboards[0].layerIds).toHaveLength(0);
+
+ useProjectStore.getState().redo();
+ expect(useProjectStore.getState().project!.artboards[0].layerIds).toHaveLength(1);
+ });
+
+ it('moves command back to undoStack', () => {
+ createProject();
+ useProjectStore.getState().addTextLayer('Hello');
+ useProjectStore.getState().undo();
+ useProjectStore.getState().redo();
+ expect(useHistoryStore.getState().undoStack).toHaveLength(1);
+ expect(useHistoryStore.getState().redoStack).toHaveLength(0);
+ });
+ });
+
+ // ── getEntries ────────────────────────────────────────────────────────────
+
+ describe('getEntries', () => {
+ it('returns an empty array initially', () => {
+ expect(useHistoryStore.getState().getEntries()).toHaveLength(0);
+ });
+
+ it('returns one entry per executed command', () => {
+ createProject();
+ useProjectStore.getState().addTextLayer('A');
+ useProjectStore.getState().addShapeLayer('rectangle');
+ const entries = useHistoryStore.getState().getEntries();
+ expect(entries).toHaveLength(2);
+ });
+
+ it('entries have meaningful descriptions', () => {
+ createProject();
+ useProjectStore.getState().addTextLayer('My Text');
+ const entries = useHistoryStore.getState().getEntries();
+ expect(entries[0].description).toBeTruthy();
+ expect(typeof entries[0].description).toBe('string');
+ });
+ });
+
+ // ── getUndoDescription / getRedoDescription ───────────────────────────────
+
+ describe('getUndoDescription / getRedoDescription', () => {
+ it('getUndoDescription returns the description of the last command', () => {
+ createProject();
+ useProjectStore.getState().addTextLayer('Hello');
+ const desc = useHistoryStore.getState().getUndoDescription();
+ expect(desc).toBeTruthy();
+ expect(typeof desc).toBe('string');
+ });
+
+ it('getRedoDescription returns null when nothing to redo', () => {
+ createProject();
+ expect(useHistoryStore.getState().getRedoDescription()).toBeNull();
+ });
+
+ it('getRedoDescription returns description after undo', () => {
+ createProject();
+ useProjectStore.getState().addTextLayer('Hello');
+ useProjectStore.getState().undo();
+ const desc = useHistoryStore.getState().getRedoDescription();
+ expect(desc).toBeTruthy();
+ });
+ });
+
+ // ── Command coalescing ────────────────────────────────────────────────────
+
+ describe('command coalescing', () => {
+ it('merges consecutive transform commands on the same layer into one undo step', () => {
+ createProject();
+ const id = useProjectStore.getState().addTextLayer('Drag me');
+
+ // Capture the initial x position (layer is centered in the 1080px artboard)
+ const initialX = useProjectStore.getState().project!.layers[id].transform.x;
+
+ // Simulate a drag: multiple transform updates
+ useProjectStore.getState().updateLayerTransform(id, { x: initialX + 10 });
+ useProjectStore.getState().updateLayerTransform(id, { x: initialX + 20 });
+ useProjectStore.getState().updateLayerTransform(id, { x: initialX + 30 });
+
+ // All three should have coalesced into one undo step
+ expect(useHistoryStore.getState().undoStack).toHaveLength(2); // 1 AddLayer + 1 merged Transform
+
+ // Undo once should get back to the state before any transform
+ useProjectStore.getState().undo();
+ const layer = useProjectStore.getState().project!.layers[id];
+ expect(layer.transform.x).toBe(initialX); // original x
+ });
+ });
+
+ // ── goToEntry ─────────────────────────────────────────────────────────────
+
+ describe('goToEntry', () => {
+ it('jumps to a specific history position', () => {
+ createProject();
+ useProjectStore.getState().addTextLayer('First');
+ useProjectStore.getState().addTextLayer('Second');
+ // undoStack should have 2 entries (index 0 and 1)
+ expect(useHistoryStore.getState().undoStack).toHaveLength(2);
+
+ // Jump to index 0 (after the first command)
+ const state = useHistoryStore.getState().goToEntry(0);
+ expect(state).not.toBeNull();
+ // Only the first layer should exist
+ if (state) {
+ const artboard = state.artboards[0];
+ expect(artboard.layerIds).toHaveLength(1);
+ }
+ });
+
+ it('returns null for an invalid index', () => {
+ createProject();
+ expect(useHistoryStore.getState().goToEntry(-1)).toBeNull();
+ expect(useHistoryStore.getState().goToEntry(999)).toBeNull();
+ });
+ });
+
+ // ── clear ─────────────────────────────────────────────────────────────────
+
+ describe('clear', () => {
+ it('clears the undo/redo stacks', () => {
+ createProject();
+ useProjectStore.getState().addTextLayer('A');
+ useProjectStore.getState().addTextLayer('B');
+ useHistoryStore.getState().clear();
+ expect(useHistoryStore.getState().undoStack).toHaveLength(0);
+ expect(useHistoryStore.getState().redoStack).toHaveLength(0);
+ });
+ });
+
+ // ── Snapshots ─────────────────────────────────────────────────────────────
+
+ describe('snapshots', () => {
+ it('creates a named snapshot', () => {
+ createProject();
+ useHistoryStore.getState().createSnapshot('My Snapshot', getProject());
+ expect(useHistoryStore.getState().getSnapshots()).toHaveLength(1);
+ expect(useHistoryStore.getState().getSnapshots()[0].name).toBe('My Snapshot');
+ });
+
+ it('restores a snapshot', () => {
+ createProject();
+ const snapshot = getProject();
+ useHistoryStore.getState().createSnapshot('Before changes', snapshot);
+
+ useProjectStore.getState().addTextLayer('Added after snapshot');
+
+ const snapId = useHistoryStore.getState().getSnapshots()[0].id;
+ const restored = useHistoryStore.getState().restoreSnapshot(snapId);
+ expect(restored).not.toBeNull();
+ // The restored project should have no layers (since snapshot was taken before adding)
+ if (restored) {
+ expect(restored.artboards[0].layerIds).toHaveLength(0);
+ }
+ });
+
+ it('deletes a snapshot', () => {
+ createProject();
+ useHistoryStore.getState().createSnapshot('Snap', getProject());
+ const snapId = useHistoryStore.getState().getSnapshots()[0].id;
+ useHistoryStore.getState().deleteSnapshot(snapId);
+ expect(useHistoryStore.getState().getSnapshots()).toHaveLength(0);
+ });
+
+ it('renames a snapshot', () => {
+ createProject();
+ useHistoryStore.getState().createSnapshot('Old Name', getProject());
+ const snapId = useHistoryStore.getState().getSnapshots()[0].id;
+ useHistoryStore.getState().renameSnapshot(snapId, 'New Name');
+ expect(useHistoryStore.getState().getSnapshots()[0].name).toBe('New Name');
+ });
+
+ it('returns null when restoring a non-existent snapshot', () => {
+ expect(useHistoryStore.getState().restoreSnapshot('no-such-id')).toBeNull();
+ });
+ });
+
+ // ── Multiple undo/redo operations ─────────────────────────────────────────
+
+ describe('multiple undo/redo', () => {
+ it('can undo and redo multiple steps in sequence', () => {
+ createProject();
+ const id1 = useProjectStore.getState().addTextLayer('First');
+ const id2 = useProjectStore.getState().addTextLayer('Second');
+
+ // Undo twice
+ useProjectStore.getState().undo();
+ useProjectStore.getState().undo();
+ expect(useProjectStore.getState().project!.artboards[0].layerIds).toHaveLength(0);
+
+ // Redo twice
+ useProjectStore.getState().redo();
+ useProjectStore.getState().redo();
+ expect(useProjectStore.getState().project!.artboards[0].layerIds).toHaveLength(2);
+ });
+
+ it('project-store undo/redo round-trip preserves layer content', () => {
+ createProject();
+ const id = useProjectStore.getState().addTextLayer('Original');
+ // addTextLayer uses content as name, so name is 'Original'
+ expect(useProjectStore.getState().project!.layers[id]?.name).toBe('Original');
+
+ useProjectStore.getState().updateLayer(id, { name: 'Updated' });
+ expect(useProjectStore.getState().project!.layers[id]?.name).toBe('Updated');
+
+ useProjectStore.getState().undo(); // undo rename
+ expect(useProjectStore.getState().project!.layers[id]?.name).toBe('Original');
+
+ useProjectStore.getState().redo(); // redo rename
+ expect(useProjectStore.getState().project!.layers[id]?.name).toBe('Updated');
+ });
+ });
+});
diff --git a/apps/image/src/stores/history-store.ts b/apps/image/src/stores/history-store.ts
index 9d76d02d..b6aef5d8 100644
--- a/apps/image/src/stores/history-store.ts
+++ b/apps/image/src/stores/history-store.ts
@@ -1,146 +1,263 @@
import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
+import type { Command } from '@openreel/image-core/commands';
import type { Project } from '../types/project';
-interface HistoryEntry {
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+
+export interface HistoryEntry {
id: string;
timestamp: number;
description: string;
- state: string;
- thumbnail?: string;
+}
+
+interface CommandRecord {
+ id: string;
+ timestamp: number;
+ command: Command;
}
interface Snapshot {
id: string;
name: string;
timestamp: number;
+ /** Serialised project state for this snapshot. */
state: string;
thumbnail?: string;
}
interface HistoryState {
- entries: HistoryEntry[];
- currentIndex: number;
- maxEntries: number;
- isUndoing: boolean;
- isRedoing: boolean;
+ undoStack: CommandRecord[];
+ redoStack: CommandRecord[];
+ /** Serialised project state captured before the first command was recorded. */
+ baseProject: string | null;
+ maxSize: number;
snapshots: Snapshot[];
}
interface HistoryActions {
- pushState: (project: Project, description: string, thumbnail?: string) => void;
- undo: () => Project | null;
- redo: () => Project | null;
+ /**
+ * Record and immediately apply `cmd` to `currentProject`.
+ * Returns the updated project that callers must set into the project store.
+ */
+ execute: (cmd: Command, currentProject: Project) => Project;
+
+ /**
+ * Undo the most recent command. Applies the inverse to `currentProject`
+ * and returns the restored project, or `null` when nothing can be undone.
+ */
+ undo: (currentProject: Project) => Project | null;
+
+ /**
+ * Re-apply the most recently undone command to `currentProject`.
+ * Returns the restored project or `null` when there is nothing to redo.
+ */
+ redo: (currentProject: Project) => Project | null;
+
canUndo: () => boolean;
canRedo: () => boolean;
- clear: () => void;
- setMaxEntries: (max: number) => void;
+
+ /**
+ * Human-readable description of the command that would be undone next.
+ */
getUndoDescription: () => string | null;
+
+ /**
+ * Human-readable description of the command that would be redone next.
+ */
getRedoDescription: () => string | null;
+
+ /**
+ * Jump to an arbitrary position in the undo stack (0 = oldest, length-1 = newest).
+ * Replays all commands from `baseProject` up to and including `index`.
+ * Returns the project at that point or `null` on failure.
+ */
+ goToEntry: (index: number) => Project | null;
+
+ /**
+ * Derived list of entries for the HistoryPanel (newest first when reversed by consumer).
+ */
+ getEntries: () => HistoryEntry[];
+
+ /** Current position: index of the entry that reflects the present project state. */
+ getCurrentIndex: () => number;
+
+ clear: (baseProject?: Project) => void;
+ setMaxSize: (max: number) => void;
+
+ // ── Named snapshots (checkpoint-style) ──────────────────────────────────
+
createSnapshot: (name: string, project: Project, thumbnail?: string) => void;
restoreSnapshot: (id: string) => Project | null;
deleteSnapshot: (id: string) => void;
renameSnapshot: (id: string, name: string) => void;
getSnapshots: () => Snapshot[];
- getEntries: () => HistoryEntry[];
- goToEntry: (index: number) => Project | null;
}
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
const generateId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
+// ---------------------------------------------------------------------------
+// Store
+// ---------------------------------------------------------------------------
+
export const useHistoryStore = create<HistoryState & HistoryActions>()(
subscribeWithSelector((set, get) => ({
- entries: [],
- currentIndex: -1,
- maxEntries: 50,
- isUndoing: false,
- isRedoing: false,
+ undoStack: [],
+ redoStack: [],
+ baseProject: null,
+ maxSize: 50,
snapshots: [],
- pushState: (project, description, thumbnail) => {
- const { entries, currentIndex, maxEntries, isUndoing, isRedoing } = get();
+ execute: (cmd, currentProject) => {
+ const { undoStack, maxSize, baseProject } = get();
- if (isUndoing || isRedoing) return;
+ // Capture base project on first command ever.
+ const base = baseProject ?? JSON.stringify(currentProject);
- const newEntry: HistoryEntry = {
+ // Attempt to coalesce with the most recent command via Command.merge.
+ if (undoStack.length > 0 && typeof cmd.merge === 'function') {
+ const last = undoStack[undoStack.length - 1];
+ const merged = cmd.merge.call(last.command, cmd);
+ if (merged !== null && merged !== undefined) {
+ const newProject = cmd.apply(currentProject);
+ const updatedStack = [
+ ...undoStack.slice(0, -1),
+ { ...last, command: merged },
+ ];
+ set({
+ undoStack: updatedStack,
+ redoStack: [],
+ baseProject: base,
+ });
+ return newProject;
+ }
+ }
+
+ const newProject = cmd.apply(currentProject);
+
+ const record: CommandRecord = {
id: generateId(),
timestamp: Date.now(),
- description,
- state: JSON.stringify(project),
- thumbnail,
+ command: cmd,
};
- let newEntries = entries.slice(0, currentIndex + 1);
- newEntries.push(newEntry);
-
- if (newEntries.length > maxEntries) {
- newEntries = newEntries.slice(newEntries.length - maxEntries);
+ let newStack = [...undoStack, record];
+ if (newStack.length > maxSize) {
+ // When we drop the oldest command we need to update baseProject to
+ // the state *after* that command would have been applied so that
+ // goToEntry remains correct. We approximate by re-serialising the
+ // project state that preceded the second-oldest command (i.e. we
+ // compute the new base by applying the dropped command to the old
+ // base and serialising that result).
+ const dropped = newStack[0];
+ let newBase: Project | null = null;
+ try {
+ const parsed = JSON.parse(base) as Project;
+ newBase = dropped.command.apply(parsed);
+ } catch {
+ newBase = null;
+ }
+ newStack = newStack.slice(1);
+ set({
+ undoStack: newStack,
+ redoStack: [],
+ baseProject: newBase ? JSON.stringify(newBase) : base,
+ });
+ } else {
+ set({ undoStack: newStack, redoStack: [], baseProject: base });
}
- set({
- entries: newEntries,
- currentIndex: newEntries.length - 1,
- });
+ return newProject;
},
- undo: () => {
- const { entries, currentIndex } = get();
- if (currentIndex <= 0) return null;
+ undo: (currentProject) => {
+ const { undoStack, redoStack } = get();
+ if (undoStack.length === 0) return null;
+
+ const record = undoStack[undoStack.length - 1];
+ const inverse = record.command.invert();
+ const restoredProject = inverse.apply(currentProject);
- set({ isUndoing: true });
- const newIndex = currentIndex - 1;
- const entry = entries[newIndex];
+ set({
+ undoStack: undoStack.slice(0, -1),
+ redoStack: [...redoStack, record],
+ });
- set({ currentIndex: newIndex, isUndoing: false });
- return JSON.parse(entry.state) as Project;
+ return restoredProject;
},
- redo: () => {
- const { entries, currentIndex } = get();
- if (currentIndex >= entries.length - 1) return null;
+ redo: (currentProject) => {
+ const { undoStack, redoStack } = get();
+ if (redoStack.length === 0) return null;
- set({ isRedoing: true });
- const newIndex = currentIndex + 1;
- const entry = entries[newIndex];
+ const record = redoStack[redoStack.length - 1];
+ const newProject = record.command.apply(currentProject);
- set({ currentIndex: newIndex, isRedoing: false });
- return JSON.parse(entry.state) as Project;
- },
+ set({
+ undoStack: [...undoStack, record],
+ redoStack: redoStack.slice(0, -1),
+ });
- canUndo: () => {
- const { currentIndex } = get();
- return currentIndex > 0;
+ return newProject;
},
- canRedo: () => {
- const { entries, currentIndex } = get();
- return currentIndex < entries.length - 1;
- },
+ canUndo: () => get().undoStack.length > 0,
+ canRedo: () => get().redoStack.length > 0,
- clear: () => {
- set({ entries: [], currentIndex: -1 });
+ getUndoDescription: () => {
+ const { undoStack } = get();
+ return undoStack.length > 0 ? undoStack[undoStack.length - 1].command.description : null;
},
- setMaxEntries: (max) => {
- set({ maxEntries: max });
+ getRedoDescription: () => {
+ const { redoStack } = get();
+ return redoStack.length > 0 ? redoStack[redoStack.length - 1].command.description : null;
},
- getUndoDescription: () => {
- const { entries, currentIndex } = get();
- if (currentIndex > 0) {
- return entries[currentIndex].description;
+ goToEntry: (index) => {
+ const { undoStack, baseProject } = get();
+ if (index < 0 || index >= undoStack.length) return null;
+ if (!baseProject) return null;
+
+ try {
+ let project = JSON.parse(baseProject) as Project;
+ for (let i = 0; i <= index; i++) {
+ project = undoStack[i].command.apply(project);
+ }
+ set({ undoStack: undoStack.slice(0, index + 1), redoStack: undoStack.slice(index + 1) });
+ return project;
+ } catch {
+ return null;
}
- return null;
},
- getRedoDescription: () => {
- const { entries, currentIndex } = get();
- if (currentIndex < entries.length - 1) {
- return entries[currentIndex + 1].description;
- }
- return null;
+ getEntries: () =>
+ get().undoStack.map((r) => ({
+ id: r.id,
+ timestamp: r.timestamp,
+ description: r.command.description,
+ })),
+
+ getCurrentIndex: () => get().undoStack.length - 1,
+
+ clear: (baseProject) => {
+ set({
+ undoStack: [],
+ redoStack: [],
+ baseProject: baseProject ? JSON.stringify(baseProject) : null,
+ });
},
+ setMaxSize: (max) => set({ maxSize: max }),
+
+ // ── Named snapshots ────────────────────────────────────────────────────
+
createSnapshot: (name, project, thumbnail) => {
const { snapshots } = get();
const snapshot: Snapshot = {
@@ -157,34 +274,23 @@ export const useHistoryStore = create<HistoryState & HistoryActions>()(
const { snapshots } = get();
const snapshot = snapshots.find((s) => s.id === id);
if (!snapshot) return null;
- return JSON.parse(snapshot.state) as Project;
+ try {
+ return JSON.parse(snapshot.state) as Project;
+ } catch {
+ return null;
+ }
},
deleteSnapshot: (id) => {
- const { snapshots } = get();
- set({ snapshots: snapshots.filter((s) => s.id !== id) });
+ set({ snapshots: get().snapshots.filter((s) => s.id !== id) });
},
renameSnapshot: (id, name) => {
- const { snapshots } = get();
set({
- snapshots: snapshots.map((s) => (s.id === id ? { ...s, name } : s)),
+ snapshots: get().snapshots.map((s) => (s.id === id ? { ...s, name } : s)),
});
},
- getSnapshots: () => {
- return get().snapshots;
- },
-
- getEntries: () => {
- return get().entries;
- },
-
- goToEntry: (index) => {
- const { entries } = get();
- if (index < 0 || index >= entries.length) return null;
- set({ currentIndex: index });
- return JSON.parse(entries[index].state) as Project;
- },
+ getSnapshots: () => get().snapshots,
}))
);
diff --git a/apps/image/src/stores/index.ts b/apps/image/src/stores/index.ts
index 591d4763..a2d770d5 100644
--- a/apps/image/src/stores/index.ts
+++ b/apps/image/src/stores/index.ts
@@ -4,6 +4,7 @@ export type { AppView, Tool, Panel, EraserSettings, SelectionToolSettings, Magic
export { useProjectStore } from './project-store';
export { useHistoryStore } from './history-store';
+export type { HistoryEntry } from './history-store';
export { useCanvasStore } from './canvas-store';
export type { Guide, SelectionRect, DragMode, ResizeHandle } from './canvas-store';
diff --git a/apps/image/src/stores/project-store.ts b/apps/image/src/stores/project-store.ts
index 033f2e11..49a6eb8b 100644
--- a/apps/image/src/stores/project-store.ts
+++ b/apps/image/src/stores/project-store.ts
@@ -2,15 +2,26 @@ import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import {
- addLayerToProject,
createProjectDocument,
deserializeProject,
duplicateLayerInProject,
- removeLayerFromProject,
- reorderArtboardLayers,
- updateLayerInProject,
- updateLayerTransformInProject,
} from '@openreel/image-core/operations';
+import {
+ AddArtboardCommand,
+ AddLayerCommand,
+ DuplicateLayerCommand,
+ GroupLayersCommand,
+ PasteLayersCommand,
+ RemoveArtboardCommand,
+ RemoveLayerCommand,
+ ReorderLayerCommand,
+ SetProjectNameCommand,
+ UngroupLayersCommand,
+ UpdateArtboardCommand,
+ UpdateLayerStyleCommand,
+ UpdateLayerTransformCommand,
+ UpdateTextCommand,
+} from '@openreel/image-core/commands';
import {
Project,
Layer,
@@ -43,6 +54,7 @@ import {
CanvasSize,
CanvasBackground,
} from '../types/project';
+import { useHistoryStore } from './history-store';
interface LayerStyle {
blendMode: Layer['blendMode'];
@@ -68,6 +80,12 @@ interface ProjectActions {
closeProject: () => void;
setProjectName: (name: string) => void;
+ // Convenience undo/redo that delegate to the history store.
+ undo: () => void;
+ redo: () => void;
+ canUndo: () => boolean;
+ canRedo: () => boolean;
+
addArtboard: (name: string, size: CanvasSize, position?: { x: number; y: number }) => string;
removeArtboard: (artboardId: string) => void;
updateArtboard: (artboardId: string, updates: Partial<Artboard>) => void;
@@ -116,6 +134,14 @@ interface ProjectActions {
const generateId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
+// Helper to apply a command and update the project in one shot.
+function execCmd(
+ project: Project,
+ command: Parameters<ReturnType<typeof useHistoryStore['getState']>['execute']>[0],
+): Project {
+ return useHistoryStore.getState().execute(command, project);
+}
+
export const useProjectStore = create<ProjectState & ProjectActions>()(
subscribeWithSelector(
immer((set, get) => ({
@@ -126,6 +152,8 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
copiedStyle: null,
isDirty: false,
+ // ── Project lifecycle ────────────────────────────────────────────────
+
createProject: (name, size, background) => {
const artboardId = generateId();
const project = createProjectDocument({
@@ -135,6 +163,7 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
size,
background,
});
+ useHistoryStore.getState().clear(project);
set({ project, selectedLayerIds: [], selectedArtboardId: artboardId, isDirty: true });
},
@@ -154,399 +183,429 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
},
closeProject: () => {
+ useHistoryStore.getState().clear();
set({ project: null, selectedLayerIds: [], selectedArtboardId: null, isDirty: false });
},
setProjectName: (name) => {
- set((state) => {
- if (state.project) {
- state.project.name = name;
- state.project.updatedAt = Date.now();
- state.isDirty = true;
+ const { project } = get();
+ if (!project) return;
+ const cmd = new SetProjectNameCommand(name, project.name);
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, isDirty: true });
+ },
+
+ // ── Undo / Redo ─────────────────────────────────────────────────────
+
+ undo: () => {
+ const { project } = get();
+ if (!project) return;
+ const histStore = useHistoryStore.getState();
+ const newProject = histStore.undo(project);
+ if (newProject) {
+ const parsed = deserializeProject(newProject as unknown as Record<string, unknown>);
+ if (parsed.success) {
+ set({
+ project: parsed.data,
+ selectedLayerIds: [],
+ selectedArtboardId: parsed.data.activeArtboardId,
+ isDirty: false,
+ });
}
- });
+ }
},
- addArtboard: (name, size, position) => {
- const id = generateId();
- set((state) => {
- if (state.project) {
- state.project.artboards.push({
- id,
- name,
- size,
- background: { type: 'color', color: '#ffffff' },
- layerIds: [],
- position: position ?? { x: (state.project.artboards.length % 3) * (size.width + 100), y: Math.floor(state.project.artboards.length / 3) * (size.height + 100) },
+ redo: () => {
+ const { project } = get();
+ if (!project) return;
+ const histStore = useHistoryStore.getState();
+ const newProject = histStore.redo(project);
+ if (newProject) {
+ const parsed = deserializeProject(newProject as unknown as Record<string, unknown>);
+ if (parsed.success) {
+ set({
+ project: parsed.data,
+ selectedLayerIds: [],
+ selectedArtboardId: parsed.data.activeArtboardId,
+ isDirty: false,
});
- state.project.updatedAt = Date.now();
- state.isDirty = true;
}
- });
+ }
+ },
+
+ canUndo: () => useHistoryStore.getState().canUndo(),
+ canRedo: () => useHistoryStore.getState().canRedo(),
+
+ // ── Artboard operations ──────────────────────────────────────────────
+
+ addArtboard: (name, size, position) => {
+ const { project } = get();
+ if (!project) return '';
+ const id = generateId();
+ const artboard: Artboard = {
+ id,
+ name,
+ size,
+ background: { type: 'color', color: '#ffffff' },
+ layerIds: [],
+ position: position ?? {
+ x: (project.artboards.length % 3) * (size.width + 100),
+ y: Math.floor(project.artboards.length / 3) * (size.height + 100),
+ },
+ };
+ const insertIndex = project.artboards.length;
+ const cmd = new AddArtboardCommand(artboard, insertIndex);
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, isDirty: true });
return id;
},
removeArtboard: (artboardId) => {
- set((state) => {
- if (state.project && state.project.artboards.length > 1) {
- const artboard = state.project.artboards.find((a) => a.id === artboardId);
- if (artboard) {
- artboard.layerIds.forEach((layerId) => {
- delete state.project!.layers[layerId];
- });
- state.project.artboards = state.project.artboards.filter((a) => a.id !== artboardId);
- if (state.selectedArtboardId === artboardId) {
- state.selectedArtboardId = state.project.artboards[0]?.id ?? null;
- }
- state.project.updatedAt = Date.now();
- state.isDirty = true;
- }
- }
+ const { project } = get();
+ if (!project || project.artboards.length <= 1) return;
+ const artboard = project.artboards.find((a) => a.id === artboardId);
+ if (!artboard) return;
+ const removedLayers: Record<string, Layer> = {};
+ artboard.layerIds.forEach((id) => {
+ if (project.layers[id]) removedLayers[id] = project.layers[id];
});
+ const originalIndex = project.artboards.findIndex((a) => a.id === artboardId);
+ const cmd = new RemoveArtboardCommand(artboardId, artboard, removedLayers, originalIndex);
+ const newProject = execCmd(project, cmd);
+ const { selectedArtboardId } = get();
+ const nextSelectedArtboard =
+ selectedArtboardId === artboardId
+ ? newProject.artboards[0]?.id ?? null
+ : selectedArtboardId;
+ set({ project: newProject, selectedArtboardId: nextSelectedArtboard, isDirty: true });
},
updateArtboard: (artboardId, updates) => {
- set((state) => {
- if (state.project) {
- const artboard = state.project.artboards.find((a) => a.id === artboardId);
- if (artboard) {
- Object.assign(artboard, updates);
- state.project.updatedAt = Date.now();
- state.isDirty = true;
- }
- }
+ const { project } = get();
+ if (!project) return;
+ const artboard = project.artboards.find((a) => a.id === artboardId);
+ if (!artboard) return;
+ const prevValues: Partial<Artboard> = {};
+ (Object.keys(updates) as (keyof Artboard)[]).forEach((k) => {
+ (prevValues as Record<string, unknown>)[k] = artboard[k];
});
+ const cmd = new UpdateArtboardCommand(artboardId, updates, prevValues);
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, isDirty: true });
},
selectArtboard: (artboardId) => {
set({ selectedArtboardId: artboardId, selectedLayerIds: [] });
},
+ // ── Layer add helpers ────────────────────────────────────────────────
+
addImageLayer: (sourceId, transform) => {
const id = generateId();
- const asset = get().project?.assets[sourceId];
- set((state) => {
- if (state.project && state.selectedArtboardId) {
- const artboard = state.project.artboards.find((a) => a.id === state.selectedArtboardId);
- if (artboard) {
- const layer: ImageLayer = {
- id,
- name: asset?.name ?? 'Image',
- type: 'image',
- visible: true,
- locked: false,
- transform: {
- ...DEFAULT_TRANSFORM,
- width: asset?.width ?? 200,
- height: asset?.height ?? 200,
- x: (artboard.size.width - (asset?.width ?? 200)) / 2,
- y: (artboard.size.height - (asset?.height ?? 200)) / 2,
- ...transform,
- },
- blendMode: DEFAULT_BLEND_MODE,
- shadow: DEFAULT_SHADOW,
- innerShadow: DEFAULT_INNER_SHADOW,
- stroke: DEFAULT_STROKE,
- glow: DEFAULT_GLOW,
- filters: DEFAULT_FILTER,
- parentId: null,
- sourceId,
- cropRect: null,
- flipHorizontal: false,
- flipVertical: false,
- mask: null,
- clippingMask: false,
- levels: { ...DEFAULT_LEVELS },
- curves: { ...DEFAULT_CURVES },
- colorBalance: { ...DEFAULT_COLOR_BALANCE },
- selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },
- blackWhite: { ...DEFAULT_BLACK_WHITE },
- photoFilter: { ...DEFAULT_PHOTO_FILTER },
- channelMixer: { ...DEFAULT_CHANNEL_MIXER },
- gradientMap: { ...DEFAULT_GRADIENT_MAP },
- posterize: { ...DEFAULT_POSTERIZE },
- threshold: { ...DEFAULT_THRESHOLD },
- };
- state.project = addLayerToProject(state.project, state.selectedArtboardId, layer);
- state.selectedLayerIds = [id];
- state.isDirty = true;
- }
- }
- });
+ const { project, selectedArtboardId } = get();
+ if (!project || !selectedArtboardId) return id;
+ const artboard = project.artboards.find((a) => a.id === selectedArtboardId);
+ if (!artboard) return id;
+ const asset = project.assets[sourceId];
+ const layer: ImageLayer = {
+ id,
+ name: asset?.name ?? 'Image',
+ type: 'image',
+ visible: true,
+ locked: false,
+ transform: {
+ ...DEFAULT_TRANSFORM,
+ width: asset?.width ?? 200,
+ height: asset?.height ?? 200,
+ x: (artboard.size.width - (asset?.width ?? 200)) / 2,
+ y: (artboard.size.height - (asset?.height ?? 200)) / 2,
+ ...transform,
+ },
+ blendMode: DEFAULT_BLEND_MODE,
+ shadow: DEFAULT_SHADOW,
+ innerShadow: DEFAULT_INNER_SHADOW,
+ stroke: DEFAULT_STROKE,
+ glow: DEFAULT_GLOW,
+ filters: DEFAULT_FILTER,
+ parentId: null,
+ sourceId,
+ cropRect: null,
+ flipHorizontal: false,
+ flipVertical: false,
+ mask: null,
+ clippingMask: false,
+ levels: { ...DEFAULT_LEVELS },
+ curves: { ...DEFAULT_CURVES },
+ colorBalance: { ...DEFAULT_COLOR_BALANCE },
+ selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },
+ blackWhite: { ...DEFAULT_BLACK_WHITE },
+ photoFilter: { ...DEFAULT_PHOTO_FILTER },
+ channelMixer: { ...DEFAULT_CHANNEL_MIXER },
+ gradientMap: { ...DEFAULT_GRADIENT_MAP },
+ posterize: { ...DEFAULT_POSTERIZE },
+ threshold: { ...DEFAULT_THRESHOLD },
+ };
+ const cmd = new AddLayerCommand(selectedArtboardId, layer, 0);
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, selectedLayerIds: [id], isDirty: true });
return id;
},
addTextLayer: (content, transform) => {
const id = generateId();
- set((state) => {
- if (state.project && state.selectedArtboardId) {
- const artboard = state.project.artboards.find((a) => a.id === state.selectedArtboardId);
- if (artboard) {
- const layer: TextLayer = {
- id,
- name: content.slice(0, 20) || 'Text',
- type: 'text',
- visible: true,
- locked: false,
- transform: {
- ...DEFAULT_TRANSFORM,
- width: 200,
- height: 50,
- x: (artboard.size.width - 200) / 2,
- y: (artboard.size.height - 50) / 2,
- ...transform,
- },
- blendMode: DEFAULT_BLEND_MODE,
- shadow: DEFAULT_SHADOW,
- innerShadow: DEFAULT_INNER_SHADOW,
- stroke: DEFAULT_STROKE,
- glow: DEFAULT_GLOW,
- filters: DEFAULT_FILTER,
- parentId: null,
- flipHorizontal: false,
- flipVertical: false,
- content,
- style: DEFAULT_TEXT_STYLE,
- autoSize: true,
- mask: null,
- clippingMask: false,
- levels: { ...DEFAULT_LEVELS },
- curves: { ...DEFAULT_CURVES },
- colorBalance: { ...DEFAULT_COLOR_BALANCE },
- selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },
- blackWhite: { ...DEFAULT_BLACK_WHITE },
- photoFilter: { ...DEFAULT_PHOTO_FILTER },
- channelMixer: { ...DEFAULT_CHANNEL_MIXER },
- gradientMap: { ...DEFAULT_GRADIENT_MAP },
- posterize: { ...DEFAULT_POSTERIZE },
- threshold: { ...DEFAULT_THRESHOLD },
- };
- state.project = addLayerToProject(state.project, state.selectedArtboardId, layer);
- state.selectedLayerIds = [id];
- state.isDirty = true;
- }
- }
- });
+ const { project, selectedArtboardId } = get();
+ if (!project || !selectedArtboardId) return id;
+ const artboard = project.artboards.find((a) => a.id === selectedArtboardId);
+ if (!artboard) return id;
+ const layer: TextLayer = {
+ id,
+ name: content.slice(0, 20) || 'Text',
+ type: 'text',
+ visible: true,
+ locked: false,
+ transform: {
+ ...DEFAULT_TRANSFORM,
+ width: 200,
+ height: 50,
+ x: (artboard.size.width - 200) / 2,
+ y: (artboard.size.height - 50) / 2,
+ ...transform,
+ },
+ blendMode: DEFAULT_BLEND_MODE,
+ shadow: DEFAULT_SHADOW,
+ innerShadow: DEFAULT_INNER_SHADOW,
+ stroke: DEFAULT_STROKE,
+ glow: DEFAULT_GLOW,
+ filters: DEFAULT_FILTER,
+ parentId: null,
+ flipHorizontal: false,
+ flipVertical: false,
+ content,
+ style: DEFAULT_TEXT_STYLE,
+ autoSize: true,
+ mask: null,
+ clippingMask: false,
+ levels: { ...DEFAULT_LEVELS },
+ curves: { ...DEFAULT_CURVES },
+ colorBalance: { ...DEFAULT_COLOR_BALANCE },
+ selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },
+ blackWhite: { ...DEFAULT_BLACK_WHITE },
+ photoFilter: { ...DEFAULT_PHOTO_FILTER },
+ channelMixer: { ...DEFAULT_CHANNEL_MIXER },
+ gradientMap: { ...DEFAULT_GRADIENT_MAP },
+ posterize: { ...DEFAULT_POSTERIZE },
+ threshold: { ...DEFAULT_THRESHOLD },
+ };
+ const cmd = new AddLayerCommand(selectedArtboardId, layer, 0);
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, selectedLayerIds: [id], isDirty: true });
return id;
},
addShapeLayer: (shapeType, transform) => {
const id = generateId();
- set((state) => {
- if (state.project && state.selectedArtboardId) {
- const artboard = state.project.artboards.find((a) => a.id === state.selectedArtboardId);
- if (artboard) {
- const layer: ShapeLayer = {
- id,
- name: shapeType.charAt(0).toUpperCase() + shapeType.slice(1),
- type: 'shape',
- visible: true,
- locked: false,
- transform: {
- ...DEFAULT_TRANSFORM,
- width: 100,
- height: 100,
- x: (artboard.size.width - 100) / 2,
- y: (artboard.size.height - 100) / 2,
- ...transform,
- },
- blendMode: DEFAULT_BLEND_MODE,
- shadow: DEFAULT_SHADOW,
- innerShadow: DEFAULT_INNER_SHADOW,
- stroke: DEFAULT_STROKE,
- glow: DEFAULT_GLOW,
- filters: DEFAULT_FILTER,
- parentId: null,
- flipHorizontal: false,
- flipVertical: false,
- shapeType,
- shapeStyle: DEFAULT_SHAPE_STYLE,
- mask: null,
- clippingMask: false,
- levels: { ...DEFAULT_LEVELS },
- curves: { ...DEFAULT_CURVES },
- colorBalance: { ...DEFAULT_COLOR_BALANCE },
- selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },
- blackWhite: { ...DEFAULT_BLACK_WHITE },
- photoFilter: { ...DEFAULT_PHOTO_FILTER },
- channelMixer: { ...DEFAULT_CHANNEL_MIXER },
- gradientMap: { ...DEFAULT_GRADIENT_MAP },
- posterize: { ...DEFAULT_POSTERIZE },
- threshold: { ...DEFAULT_THRESHOLD },
- };
- state.project = addLayerToProject(state.project, state.selectedArtboardId, layer);
- state.selectedLayerIds = [id];
- state.isDirty = true;
- }
- }
- });
+ const { project, selectedArtboardId } = get();
+ if (!project || !selectedArtboardId) return id;
+ const artboard = project.artboards.find((a) => a.id === selectedArtboardId);
+ if (!artboard) return id;
+ const layer: ShapeLayer = {
+ id,
+ name: shapeType.charAt(0).toUpperCase() + shapeType.slice(1),
+ type: 'shape',
+ visible: true,
+ locked: false,
+ transform: {
+ ...DEFAULT_TRANSFORM,
+ width: 100,
+ height: 100,
+ x: (artboard.size.width - 100) / 2,
+ y: (artboard.size.height - 100) / 2,
+ ...transform,
+ },
+ blendMode: DEFAULT_BLEND_MODE,
+ shadow: DEFAULT_SHADOW,
+ innerShadow: DEFAULT_INNER_SHADOW,
+ stroke: DEFAULT_STROKE,
+ glow: DEFAULT_GLOW,
+ filters: DEFAULT_FILTER,
+ parentId: null,
+ flipHorizontal: false,
+ flipVertical: false,
+ shapeType,
+ shapeStyle: DEFAULT_SHAPE_STYLE,
+ mask: null,
+ clippingMask: false,
+ levels: { ...DEFAULT_LEVELS },
+ curves: { ...DEFAULT_CURVES },
+ colorBalance: { ...DEFAULT_COLOR_BALANCE },
+ selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },
+ blackWhite: { ...DEFAULT_BLACK_WHITE },
+ photoFilter: { ...DEFAULT_PHOTO_FILTER },
+ channelMixer: { ...DEFAULT_CHANNEL_MIXER },
+ gradientMap: { ...DEFAULT_GRADIENT_MAP },
+ posterize: { ...DEFAULT_POSTERIZE },
+ threshold: { ...DEFAULT_THRESHOLD },
+ };
+ const cmd = new AddLayerCommand(selectedArtboardId, layer, 0);
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, selectedLayerIds: [id], isDirty: true });
return id;
},
addPathLayer: (points, strokeColor, strokeWidth) => {
const id = generateId();
- set((state) => {
- if (state.project && state.selectedArtboardId && points.length > 1) {
- const artboard = state.project.artboards.find((a) => a.id === state.selectedArtboardId);
- if (artboard) {
- const minX = Math.min(...points.map((p) => p.x));
- const minY = Math.min(...points.map((p) => p.y));
- const maxX = Math.max(...points.map((p) => p.x));
- const maxY = Math.max(...points.map((p) => p.y));
- const width = Math.max(maxX - minX, 1);
- const height = Math.max(maxY - minY, 1);
-
- const normalizedPoints = points.map((p) => ({
- x: p.x - minX,
- y: p.y - minY,
- }));
-
- const layer: ShapeLayer = {
- id,
- name: 'Drawing',
- type: 'shape',
- visible: true,
- locked: false,
- transform: {
- ...DEFAULT_TRANSFORM,
- x: minX,
- y: minY,
- width,
- height,
- },
- blendMode: DEFAULT_BLEND_MODE,
- shadow: DEFAULT_SHADOW,
- innerShadow: DEFAULT_INNER_SHADOW,
- stroke: DEFAULT_STROKE,
- glow: DEFAULT_GLOW,
- filters: DEFAULT_FILTER,
- parentId: null,
- flipHorizontal: false,
- flipVertical: false,
- shapeType: 'path',
- shapeStyle: {
- ...DEFAULT_SHAPE_STYLE,
- fill: null,
- stroke: strokeColor,
- strokeWidth,
- },
- points: normalizedPoints,
- mask: null,
- clippingMask: false,
- levels: { ...DEFAULT_LEVELS },
- curves: { ...DEFAULT_CURVES },
- colorBalance: { ...DEFAULT_COLOR_BALANCE },
- selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },
- blackWhite: { ...DEFAULT_BLACK_WHITE },
- photoFilter: { ...DEFAULT_PHOTO_FILTER },
- channelMixer: { ...DEFAULT_CHANNEL_MIXER },
- gradientMap: { ...DEFAULT_GRADIENT_MAP },
- posterize: { ...DEFAULT_POSTERIZE },
- threshold: { ...DEFAULT_THRESHOLD },
- };
- state.project = addLayerToProject(state.project, state.selectedArtboardId, layer);
- state.selectedLayerIds = [id];
- state.isDirty = true;
- }
- }
- });
+ const { project, selectedArtboardId } = get();
+ if (!project || !selectedArtboardId || points.length <= 1) return id;
+ const artboard = project.artboards.find((a) => a.id === selectedArtboardId);
+ if (!artboard) return id;
+ const minX = Math.min(...points.map((p) => p.x));
+ const minY = Math.min(...points.map((p) => p.y));
+ const maxX = Math.max(...points.map((p) => p.x));
+ const maxY = Math.max(...points.map((p) => p.y));
+ const width = Math.max(maxX - minX, 1);
+ const height = Math.max(maxY - minY, 1);
+ const normalizedPoints = points.map((p) => ({ x: p.x - minX, y: p.y - minY }));
+ const layer: ShapeLayer = {
+ id,
+ name: 'Drawing',
+ type: 'shape',
+ visible: true,
+ locked: false,
+ transform: { ...DEFAULT_TRANSFORM, x: minX, y: minY, width, height },
+ blendMode: DEFAULT_BLEND_MODE,
+ shadow: DEFAULT_SHADOW,
+ innerShadow: DEFAULT_INNER_SHADOW,
+ stroke: DEFAULT_STROKE,
+ glow: DEFAULT_GLOW,
+ filters: DEFAULT_FILTER,
+ parentId: null,
+ flipHorizontal: false,
+ flipVertical: false,
+ shapeType: 'path',
+ shapeStyle: { ...DEFAULT_SHAPE_STYLE, fill: null, stroke: strokeColor, strokeWidth },
+ points: normalizedPoints,
+ mask: null,
+ clippingMask: false,
+ levels: { ...DEFAULT_LEVELS },
+ curves: { ...DEFAULT_CURVES },
+ colorBalance: { ...DEFAULT_COLOR_BALANCE },
+ selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },
+ blackWhite: { ...DEFAULT_BLACK_WHITE },
+ photoFilter: { ...DEFAULT_PHOTO_FILTER },
+ channelMixer: { ...DEFAULT_CHANNEL_MIXER },
+ gradientMap: { ...DEFAULT_GRADIENT_MAP },
+ posterize: { ...DEFAULT_POSTERIZE },
+ threshold: { ...DEFAULT_THRESHOLD },
+ };
+ const cmd = new AddLayerCommand(selectedArtboardId, layer, 0, 'Draw path');
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, selectedLayerIds: [id], isDirty: true });
return id;
},
addGroupLayer: (childIds) => {
const id = generateId();
- set((state) => {
- if (state.project && state.selectedArtboardId) {
- const artboard = state.project.artboards.find((a) => a.id === state.selectedArtboardId);
- if (artboard && childIds.length > 0) {
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
- childIds.forEach((childId) => {
- const child = state.project!.layers[childId];
- if (child) {
- const { x, y, width, height } = child.transform;
- minX = Math.min(minX, x);
- minY = Math.min(minY, y);
- maxX = Math.max(maxX, x + width);
- maxY = Math.max(maxY, y + height);
- }
- });
-
- const groupX = minX;
- const groupY = minY;
- const groupWidth = maxX - minX;
- const groupHeight = maxY - minY;
-
- childIds.forEach((childId) => {
- const child = state.project!.layers[childId];
- if (child) {
- child.transform.x -= groupX;
- child.transform.y -= groupY;
- child.parentId = id;
- }
- });
-
- const layer: GroupLayer = {
- id,
- name: 'Group',
- type: 'group',
- visible: true,
- locked: false,
- transform: {
- ...DEFAULT_TRANSFORM,
- x: groupX,
- y: groupY,
- width: groupWidth,
- height: groupHeight,
- },
- blendMode: DEFAULT_BLEND_MODE,
- shadow: DEFAULT_SHADOW,
- innerShadow: DEFAULT_INNER_SHADOW,
- stroke: DEFAULT_STROKE,
- glow: DEFAULT_GLOW,
- filters: DEFAULT_FILTER,
- parentId: null,
- flipHorizontal: false,
- flipVertical: false,
- childIds,
- expanded: true,
- mask: null,
- clippingMask: false,
- levels: { ...DEFAULT_LEVELS },
- curves: { ...DEFAULT_CURVES },
- colorBalance: { ...DEFAULT_COLOR_BALANCE },
- selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },
- blackWhite: { ...DEFAULT_BLACK_WHITE },
- photoFilter: { ...DEFAULT_PHOTO_FILTER },
- channelMixer: { ...DEFAULT_CHANNEL_MIXER },
- gradientMap: { ...DEFAULT_GRADIENT_MAP },
- posterize: { ...DEFAULT_POSTERIZE },
- threshold: { ...DEFAULT_THRESHOLD },
- };
- const firstChildIndex = artboard.layerIds.findIndex((lid) => childIds.includes(lid));
- artboard.layerIds = artboard.layerIds.filter((lid) => !childIds.includes(lid));
- state.project = addLayerToProject(
- state.project,
- state.selectedArtboardId,
- layer,
- Math.max(firstChildIndex, 0),
- );
- state.selectedLayerIds = [id];
- state.isDirty = true;
- }
+ const { project, selectedArtboardId } = get();
+ if (!project || !selectedArtboardId || childIds.length === 0) return id;
+ const artboard = project.artboards.find((a) => a.id === selectedArtboardId);
+ if (!artboard) return id;
+
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
+ childIds.forEach((childId) => {
+ const child = project.layers[childId];
+ if (child) {
+ const { x, y, width, height } = child.transform;
+ minX = Math.min(minX, x);
+ minY = Math.min(minY, y);
+ maxX = Math.max(maxX, x + width);
+ maxY = Math.max(maxY, y + height);
}
});
+
+ const groupX = minX;
+ const groupY = minY;
+ const groupWidth = maxX - minX;
+ const groupHeight = maxY - minY;
+
+ // Capture children before state (with adjusted coordinates) for the group.
+ const childLayersBefore: Record<string, Layer> = {};
+ const adjustedChildren: Record<string, Layer> = {};
+ childIds.forEach((childId) => {
+ const child = project.layers[childId];
+ if (child) {
+ childLayersBefore[childId] = JSON.parse(JSON.stringify(child));
+ adjustedChildren[childId] = {
+ ...JSON.parse(JSON.stringify(child)),
+ transform: { ...child.transform, x: child.transform.x - groupX, y: child.transform.y - groupY },
+ parentId: id,
+ };
+ }
+ });
+
+ const groupLayer: GroupLayer = {
+ id,
+ name: 'Group',
+ type: 'group',
+ visible: true,
+ locked: false,
+ transform: { ...DEFAULT_TRANSFORM, x: groupX, y: groupY, width: groupWidth, height: groupHeight },
+ blendMode: DEFAULT_BLEND_MODE,
+ shadow: DEFAULT_SHADOW,
+ innerShadow: DEFAULT_INNER_SHADOW,
+ stroke: DEFAULT_STROKE,
+ glow: DEFAULT_GLOW,
+ filters: DEFAULT_FILTER,
+ parentId: null,
+ flipHorizontal: false,
+ flipVertical: false,
+ childIds,
+ expanded: true,
+ mask: null,
+ clippingMask: false,
+ levels: { ...DEFAULT_LEVELS },
+ curves: { ...DEFAULT_CURVES },
+ colorBalance: { ...DEFAULT_COLOR_BALANCE },
+ selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },
+ blackWhite: { ...DEFAULT_BLACK_WHITE },
+ photoFilter: { ...DEFAULT_PHOTO_FILTER },
+ channelMixer: { ...DEFAULT_CHANNEL_MIXER },
+ gradientMap: { ...DEFAULT_GRADIENT_MAP },
+ posterize: { ...DEFAULT_POSTERIZE },
+ threshold: { ...DEFAULT_THRESHOLD },
+ };
+
+ const firstChildIndex = artboard.layerIds.findIndex((lid) => childIds.includes(lid));
+ const prevArtboardLayerIds = [...artboard.layerIds];
+ const cmd = new GroupLayersCommand(
+ selectedArtboardId,
+ groupLayer,
+ Math.max(firstChildIndex, 0),
+ prevArtboardLayerIds,
+ adjustedChildren,
+ );
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, selectedLayerIds: [id], isDirty: true });
return id;
},
removeLayer: (layerId) => {
- set((state) => {
- if (state.project) {
- if (state.project.layers[layerId]) {
- state.project = removeLayerFromProject(state.project, layerId);
- state.selectedLayerIds = state.selectedLayerIds.filter((id) => id !== layerId);
- state.isDirty = true;
- }
- }
+ const { project, selectedArtboardId } = get();
+ if (!project || !project.layers[layerId]) return;
+ const layer = project.layers[layerId];
+ // Find which artboard owns this layer.
+ const ownerArtboard = project.artboards.find(
+ (a) => a.layerIds.includes(layerId) || Object.values(project.layers).some(
+ (l) => l.type === 'group' && (l as GroupLayer).childIds.includes(layerId) && a.layerIds.includes(l.id)
+ )
+ ) ?? project.artboards.find((a) => a.id === selectedArtboardId);
+ const artboardId = ownerArtboard?.id ?? selectedArtboardId ?? project.artboards[0]?.id ?? '';
+ const originalIndex = ownerArtboard?.layerIds.indexOf(layerId) ?? 0;
+ const cmd = new RemoveLayerCommand(layerId, artboardId, layer, Math.max(originalIndex, 0));
+ const newProject = execCmd(project, cmd);
+ set({
+ project: newProject,
+ selectedLayerIds: get().selectedLayerIds.filter((id) => id !== layerId),
+ isDirty: true,
});
},
@@ -555,46 +614,67 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
},
updateLayer: (layerId, updates) => {
- set((state) => {
- if (state.project) {
- if (state.project.layers[layerId]) {
- state.project = updateLayerInProject(state.project, layerId, updates);
- state.isDirty = true;
- }
- }
+ const { project } = get();
+ if (!project || !project.layers[layerId]) return;
+ const layer = project.layers[layerId];
+ // Build prevValues capturing only the keys being updated.
+ const prevValues: Partial<Layer> = {};
+ (Object.keys(updates) as (keyof Layer)[]).forEach((k) => {
+ (prevValues as Record<string, unknown>)[k] = layer[k];
});
+ let cmd;
+ const textLayer = layer as TextLayer;
+ const updatesTyped = updates as Record<string, unknown>;
+ if (layer.type === 'text' && ('content' in updates || 'style' in updates)) {
+ cmd = new UpdateTextCommand(
+ layerId,
+ (updatesTyped.content as string | undefined) ?? textLayer.content,
+ textLayer.content,
+ (updatesTyped.style as TextLayer['style'] | undefined) ?? null,
+ (updatesTyped.style !== undefined) ? textLayer.style : null,
+ );
+ } else {
+ cmd = new UpdateLayerStyleCommand(layerId, updates as Partial<Layer>, prevValues);
+ }
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, isDirty: true });
},
updateLayerTransform: (layerId, transform) => {
- set((state) => {
- if (state.project) {
- if (state.project.layers[layerId]) {
- state.project = updateLayerTransformInProject(state.project, layerId, transform);
- state.isDirty = true;
- }
- }
+ const { project } = get();
+ if (!project || !project.layers[layerId]) return;
+ const layer = project.layers[layerId];
+ const prevTransform: Partial<Transform> = {};
+ (Object.keys(transform) as (keyof Transform)[]).forEach((k) => {
+ (prevTransform as Record<string, unknown>)[k] = layer.transform[k];
});
+ const cmd = new UpdateLayerTransformCommand(layerId, transform, prevTransform);
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, isDirty: true });
},
duplicateLayer: (layerId) => {
const { project, selectedArtboardId } = get();
if (!project || !selectedArtboardId) return null;
-
const newId = generateId();
const duplicated = duplicateLayerInProject(project, selectedArtboardId, layerId, newId);
if (!duplicated) return null;
-
- set((state) => {
- state.project = duplicated.project;
- state.selectedLayerIds = [duplicated.duplicatedLayerId];
- state.isDirty = true;
- });
- return duplicated.duplicatedLayerId;
+ const artboard = project.artboards.find((a) => a.id === selectedArtboardId);
+ const originalIndex = artboard?.layerIds.indexOf(layerId) ?? 0;
+ const cmd = new DuplicateLayerCommand(
+ selectedArtboardId,
+ duplicated.project.layers[newId],
+ Math.max(originalIndex, 0),
+ );
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, selectedLayerIds: [newId], isDirty: true });
+ return newId;
},
- duplicateLayers: (layerIds) => {
- return layerIds.map((id) => get().duplicateLayer(id)).filter((id): id is string => id !== null);
- },
+ duplicateLayers: (layerIds) =>
+ layerIds.map((id) => get().duplicateLayer(id)).filter((id): id is string => id !== null),
+
+ // ── Selection (no commands needed, pure UI state) ────────────────────
selectLayer: (layerId, addToSelection = false) => {
set((state) => {
@@ -608,9 +688,7 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
});
},
- selectLayers: (layerIds) => {
- set({ selectedLayerIds: layerIds });
- },
+ selectLayers: (layerIds) => set({ selectedLayerIds: layerIds }),
deselectLayer: (layerId) => {
set((state) => {
@@ -618,91 +696,80 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
});
},
- deselectAllLayers: () => {
- set({ selectedLayerIds: [] });
- },
+ deselectAllLayers: () => set({ selectedLayerIds: [] }),
selectAllLayers: () => {
const { project, selectedArtboardId } = get();
if (project && selectedArtboardId) {
const artboard = project.artboards.find((a) => a.id === selectedArtboardId);
- if (artboard) {
- set({ selectedLayerIds: [...artboard.layerIds] });
- }
+ if (artboard) set({ selectedLayerIds: [...artboard.layerIds] });
}
},
+ // ── Layer reorder operations ─────────────────────────────────────────
+
moveLayerUp: (layerId) => {
- set((state) => {
- if (state.project && state.selectedArtboardId) {
- const artboard = state.project.artboards.find((a) => a.id === state.selectedArtboardId);
- if (artboard) {
- const index = artboard.layerIds.indexOf(layerId);
- if (index > 0) {
- const layerIds = [...artboard.layerIds];
- [layerIds[index - 1], layerIds[index]] = [layerIds[index], layerIds[index - 1]];
- state.project = reorderArtboardLayers(state.project, state.selectedArtboardId, layerIds);
- state.isDirty = true;
- }
- }
- }
- });
+ const { project, selectedArtboardId } = get();
+ if (!project || !selectedArtboardId) return;
+ const artboard = project.artboards.find((a) => a.id === selectedArtboardId);
+ if (!artboard) return;
+ const index = artboard.layerIds.indexOf(layerId);
+ if (index <= 0) return;
+ const newIds = [...artboard.layerIds];
+ [newIds[index - 1], newIds[index]] = [newIds[index], newIds[index - 1]];
+ const cmd = new ReorderLayerCommand(selectedArtboardId, newIds, artboard.layerIds, 'Move layer up');
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, isDirty: true });
},
moveLayerDown: (layerId) => {
- set((state) => {
- if (state.project && state.selectedArtboardId) {
- const artboard = state.project.artboards.find((a) => a.id === state.selectedArtboardId);
- if (artboard) {
- const index = artboard.layerIds.indexOf(layerId);
- if (index < artboard.layerIds.length - 1) {
- const layerIds = [...artboard.layerIds];
- [layerIds[index], layerIds[index + 1]] = [layerIds[index + 1], layerIds[index]];
- state.project = reorderArtboardLayers(state.project, state.selectedArtboardId, layerIds);
- state.isDirty = true;
- }
- }
- }
- });
+ const { project, selectedArtboardId } = get();
+ if (!project || !selectedArtboardId) return;
+ const artboard = project.artboards.find((a) => a.id === selectedArtboardId);
+ if (!artboard) return;
+ const index = artboard.layerIds.indexOf(layerId);
+ if (index >= artboard.layerIds.length - 1) return;
+ const newIds = [...artboard.layerIds];
+ [newIds[index], newIds[index + 1]] = [newIds[index + 1], newIds[index]];
+ const cmd = new ReorderLayerCommand(selectedArtboardId, newIds, artboard.layerIds, 'Move layer down');
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, isDirty: true });
},
moveLayerToTop: (layerId) => {
- set((state) => {
- if (state.project && state.selectedArtboardId) {
- const artboard = state.project.artboards.find((a) => a.id === state.selectedArtboardId);
- if (artboard) {
- const layerIds = artboard.layerIds.filter((id) => id !== layerId);
- layerIds.unshift(layerId);
- state.project = reorderArtboardLayers(state.project, state.selectedArtboardId, layerIds);
- state.isDirty = true;
- }
- }
- });
+ const { project, selectedArtboardId } = get();
+ if (!project || !selectedArtboardId) return;
+ const artboard = project.artboards.find((a) => a.id === selectedArtboardId);
+ if (!artboard) return;
+ const newIds = [layerId, ...artboard.layerIds.filter((id) => id !== layerId)];
+ const cmd = new ReorderLayerCommand(selectedArtboardId, newIds, artboard.layerIds, 'Move layer to top');
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, isDirty: true });
},
moveLayerToBottom: (layerId) => {
- set((state) => {
- if (state.project && state.selectedArtboardId) {
- const artboard = state.project.artboards.find((a) => a.id === state.selectedArtboardId);
- if (artboard) {
- const layerIds = artboard.layerIds.filter((id) => id !== layerId);
- layerIds.push(layerId);
- state.project = reorderArtboardLayers(state.project, state.selectedArtboardId, layerIds);
- state.isDirty = true;
- }
- }
- });
+ const { project, selectedArtboardId } = get();
+ if (!project || !selectedArtboardId) return;
+ const artboard = project.artboards.find((a) => a.id === selectedArtboardId);
+ if (!artboard) return;
+ const newIds = [...artboard.layerIds.filter((id) => id !== layerId), layerId];
+ const cmd = new ReorderLayerCommand(selectedArtboardId, newIds, artboard.layerIds, 'Move layer to bottom');
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, isDirty: true });
},
reorderLayers: (layerIds) => {
- set((state) => {
- if (state.project && state.selectedArtboardId) {
- state.project = reorderArtboardLayers(state.project, state.selectedArtboardId, layerIds);
- state.isDirty = true;
- }
- });
+ const { project, selectedArtboardId } = get();
+ if (!project || !selectedArtboardId) return;
+ const artboard = project.artboards.find((a) => a.id === selectedArtboardId);
+ if (!artboard) return;
+ const cmd = new ReorderLayerCommand(selectedArtboardId, layerIds, artboard.layerIds);
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, isDirty: true });
},
+ // ── Copy / paste ─────────────────────────────────────────────────────
+
copyLayers: () => {
const { project, selectedLayerIds } = get();
if (project && selectedLayerIds.length > 0) {
@@ -718,65 +785,109 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
pasteLayers: () => {
const { copiedLayers, selectedArtboardId, project } = get();
- if (copiedLayers.length > 0 && selectedArtboardId && project) {
- const newIds: string[] = [];
- set((state) => {
- if (state.project) {
- const artboard = state.project.artboards.find((a) => a.id === selectedArtboardId);
- if (artboard) {
- copiedLayers.forEach((layer) => {
- const newId = generateId();
- const newLayer = JSON.parse(JSON.stringify(layer));
- newLayer.id = newId;
- newLayer.name = `${layer.name} copy`;
- newLayer.transform.x += 20;
- newLayer.transform.y += 20;
- state.project!.layers[newId] = newLayer;
- artboard.layerIds.unshift(newId);
- newIds.push(newId);
- });
- state.selectedLayerIds = newIds;
- state.project.updatedAt = Date.now();
- state.isDirty = true;
- }
- }
- });
+ if (!copiedLayers.length || !selectedArtboardId || !project) return;
+ const artboard = project.artboards.find((a) => a.id === selectedArtboardId);
+ if (!artboard) return;
+ const pastedLayers: Layer[] = copiedLayers.map((layer) => ({
+ ...JSON.parse(JSON.stringify(layer)),
+ id: generateId(),
+ name: `${layer.name} copy`,
+ transform: { ...layer.transform, x: layer.transform.x + 20, y: layer.transform.y + 20 },
+ }));
+ const cmd = new PasteLayersCommand(selectedArtboardId, pastedLayers, artboard.layerIds);
+ const newProject = execCmd(project, cmd);
+ set({
+ project: newProject,
+ selectedLayerIds: pastedLayers.map((l) => l.id),
+ isDirty: true,
+ });
+ },
+
+ // ── Style copy/paste (pure UI state + one UpdateLayerStyleCommand) ──
+
+ copyLayerStyle: () => {
+ const { project, selectedLayerIds } = get();
+ if (project && selectedLayerIds.length === 1) {
+ const layer = project.layers[selectedLayerIds[0]];
+ if (layer) {
+ set({
+ copiedStyle: {
+ blendMode: layer.blendMode ? JSON.parse(JSON.stringify(layer.blendMode)) : DEFAULT_BLEND_MODE,
+ shadow: layer.shadow ? JSON.parse(JSON.stringify(layer.shadow)) : DEFAULT_SHADOW,
+ innerShadow: layer.innerShadow ? JSON.parse(JSON.stringify(layer.innerShadow)) : DEFAULT_INNER_SHADOW,
+ stroke: layer.stroke ? JSON.parse(JSON.stringify(layer.stroke)) : DEFAULT_STROKE,
+ glow: layer.glow ? JSON.parse(JSON.stringify(layer.glow)) : DEFAULT_GLOW,
+ filters: layer.filters ? JSON.parse(JSON.stringify(layer.filters)) : DEFAULT_FILTER,
+ },
+ });
+ }
}
},
+ pasteLayerStyle: () => {
+ const { copiedStyle, selectedLayerIds, project } = get();
+ if (!copiedStyle || !selectedLayerIds.length || !project) return;
+ selectedLayerIds.forEach((layerId) => {
+ const layer = project?.layers[layerId];
+ if (!layer) return;
+ const styleUpdates: Partial<Layer> = {
+ blendMode: copiedStyle.blendMode ? JSON.parse(JSON.stringify(copiedStyle.blendMode)) : DEFAULT_BLEND_MODE,
+ shadow: copiedStyle.shadow ? JSON.parse(JSON.stringify(copiedStyle.shadow)) : DEFAULT_SHADOW,
+ innerShadow: copiedStyle.innerShadow ? JSON.parse(JSON.stringify(copiedStyle.innerShadow)) : DEFAULT_INNER_SHADOW,
+ stroke: copiedStyle.stroke ? JSON.parse(JSON.stringify(copiedStyle.stroke)) : DEFAULT_STROKE,
+ glow: copiedStyle.glow ? JSON.parse(JSON.stringify(copiedStyle.glow)) : DEFAULT_GLOW,
+ filters: copiedStyle.filters ? JSON.parse(JSON.stringify(copiedStyle.filters)) : DEFAULT_FILTER,
+ };
+ const prevValues: Partial<Layer> = {
+ blendMode: layer.blendMode,
+ shadow: layer.shadow,
+ innerShadow: layer.innerShadow,
+ stroke: layer.stroke,
+ glow: layer.glow,
+ filters: layer.filters,
+ };
+ const latestProject = useProjectStore.getState().project;
+ if (!latestProject) return;
+ const cmd = new UpdateLayerStyleCommand(layerId, styleUpdates, prevValues, 'Paste layer style');
+ const newProject = execCmd(latestProject, cmd);
+ useProjectStore.setState({ project: newProject, isDirty: true });
+ });
+ },
+
+ // ── Group / ungroup ──────────────────────────────────────────────────
+
groupLayers: (layerIds) => {
if (layerIds.length < 2) return null;
return get().addGroupLayer(layerIds);
},
ungroupLayers: (groupId) => {
- set((state) => {
- if (state.project && state.selectedArtboardId) {
- const group = state.project.layers[groupId] as GroupLayer;
- if (group && group.type === 'group') {
- const artboard = state.project.artboards.find((a) => a.id === state.selectedArtboardId);
- if (artboard) {
- const groupIndex = artboard.layerIds.indexOf(groupId);
- const { x: groupX, y: groupY } = group.transform;
- group.childIds.forEach((childId) => {
- const child = state.project!.layers[childId];
- if (child) {
- child.transform.x += groupX;
- child.transform.y += groupY;
- child.parentId = null;
- }
- });
- artboard.layerIds.splice(groupIndex, 1, ...group.childIds);
- delete state.project.layers[groupId];
- state.selectedLayerIds = group.childIds;
- state.project.updatedAt = Date.now();
- state.isDirty = true;
- }
- }
+ const { project, selectedArtboardId } = get();
+ if (!project || !selectedArtboardId) return;
+ const group = project.layers[groupId] as GroupLayer;
+ if (!group || group.type !== 'group') return;
+ const artboard = project.artboards.find((a) => a.id === selectedArtboardId);
+ if (!artboard) return;
+ const prevArtboardLayerIds = [...artboard.layerIds];
+ const childLayersBefore: Record<string, Layer> = {};
+ group.childIds.forEach((childId) => {
+ if (project.layers[childId]) {
+ childLayersBefore[childId] = JSON.parse(JSON.stringify(project.layers[childId]));
}
});
+ const cmd = new UngroupLayersCommand(
+ selectedArtboardId,
+ groupId,
+ JSON.parse(JSON.stringify(group)),
+ prevArtboardLayerIds,
+ childLayersBefore,
+ );
+ const newProject = execCmd(project, cmd);
+ set({ project: newProject, selectedLayerIds: group.childIds, isDirty: true });
},
+ // ── Assets (no undo needed for asset registration) ───────────────────
+
addAsset: (asset) => {
set((state) => {
if (state.project) {
@@ -797,48 +908,6 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
});
},
- copyLayerStyle: () => {
- const { project, selectedLayerIds } = get();
- if (project && selectedLayerIds.length === 1) {
- const layer = project.layers[selectedLayerIds[0]];
- if (layer) {
- set({
- copiedStyle: {
- blendMode: layer.blendMode ? JSON.parse(JSON.stringify(layer.blendMode)) : DEFAULT_BLEND_MODE,
- shadow: layer.shadow ? JSON.parse(JSON.stringify(layer.shadow)) : DEFAULT_SHADOW,
- innerShadow: layer.innerShadow ? JSON.parse(JSON.stringify(layer.innerShadow)) : DEFAULT_INNER_SHADOW,
- stroke: layer.stroke ? JSON.parse(JSON.stringify(layer.stroke)) : DEFAULT_STROKE,
- glow: layer.glow ? JSON.parse(JSON.stringify(layer.glow)) : DEFAULT_GLOW,
- filters: layer.filters ? JSON.parse(JSON.stringify(layer.filters)) : DEFAULT_FILTER,
- },
- });
- }
- }
- },
-
- pasteLayerStyle: () => {
- const { copiedStyle, selectedLayerIds } = get();
- if (copiedStyle && selectedLayerIds.length > 0) {
- set((state) => {
- if (state.project) {
- selectedLayerIds.forEach((layerId) => {
- const layer = state.project!.layers[layerId];
- if (layer) {
- layer.blendMode = copiedStyle.blendMode ? JSON.parse(JSON.stringify(copiedStyle.blendMode)) : DEFAULT_BLEND_MODE;
- layer.shadow = copiedStyle.shadow ? JSON.parse(JSON.stringify(copiedStyle.shadow)) : DEFAULT_SHADOW;
- layer.innerShadow = copiedStyle.innerShadow ? JSON.parse(JSON.stringify(copiedStyle.innerShadow)) : DEFAULT_INNER_SHADOW;
- layer.stroke = copiedStyle.stroke ? JSON.parse(JSON.stringify(copiedStyle.stroke)) : DEFAULT_STROKE;
- layer.glow = copiedStyle.glow ? JSON.parse(JSON.stringify(copiedStyle.glow)) : DEFAULT_GLOW;
- layer.filters = copiedStyle.filters ? JSON.parse(JSON.stringify(copiedStyle.filters)) : DEFAULT_FILTER;
- }
- });
- state.project.updatedAt = Date.now();
- state.isDirty = true;
- }
- });
- }
- },
-
markDirty: () => set({ isDirty: true }),
markClean: () => set({ isDirty: false }),
}))
diff --git a/packages/image-core/src/commands.test.ts b/packages/image-core/src/commands.test.ts
new file mode 100644
index 00000000..9d85f6c1
--- /dev/null
+++ b/packages/image-core/src/commands.test.ts
@@ -0,0 +1,723 @@
+import { describe, expect, it } from 'vitest';
+import {
+ DEFAULT_BLEND_MODE,
+ DEFAULT_CURVES,
+ DEFAULT_FILTER,
+ DEFAULT_GLOW,
+ DEFAULT_INNER_SHADOW,
+ DEFAULT_LEVELS,
+ DEFAULT_SHAPE_STYLE,
+ DEFAULT_SHADOW,
+ DEFAULT_STROKE,
+ DEFAULT_TEXT_STYLE,
+ DEFAULT_TRANSFORM,
+ DEFAULT_COLOR_BALANCE,
+ DEFAULT_SELECTIVE_COLOR,
+ DEFAULT_BLACK_WHITE,
+ DEFAULT_PHOTO_FILTER,
+ DEFAULT_CHANNEL_MIXER,
+ DEFAULT_GRADIENT_MAP,
+ DEFAULT_POSTERIZE,
+ DEFAULT_THRESHOLD,
+ type GroupLayer,
+ type ShapeLayer,
+ type TextLayer,
+} from './project';
+import { DEFAULT_LAYER_MASK } from './mask';
+import { createProjectDocument } from './operations';
+import {
+ AddArtboardCommand,
+ AddLayerCommand,
+ ApplyAdjustmentCommand,
+ ApplyMaskCommand,
+ DuplicateLayerCommand,
+ GroupLayersCommand,
+ PasteLayersCommand,
+ RasterEditCommand,
+ RemoveArtboardCommand,
+ RemoveLayerCommand,
+ ReorderLayerCommand,
+ SetProjectNameCommand,
+ UngroupLayersCommand,
+ UpdateArtboardCommand,
+ UpdateLayerStyleCommand,
+ UpdateLayerTransformCommand,
+ UpdateTextCommand,
+} from './commands';
+
+// ── Fixtures ──────────────────────────────────────────────────────────────────
+
+const SIZE = { width: 1080, height: 1080 };
+const AB_ID = 'ab-1';
+
+function makeProject() {
+ return createProjectDocument({
+ id: 'proj-1',
+ artboardId: AB_ID,
+ name: 'Test',
+ size: SIZE,
+ });
+}
+
+function makeTextLayer(id: string, name = 'Text'): TextLayer {
+ return {
+ id,
+ name,
+ type: 'text',
+ visible: true,
+ locked: false,
+ transform: { ...DEFAULT_TRANSFORM, width: 200, height: 50 },
+ blendMode: { ...DEFAULT_BLEND_MODE },
+ shadow: { ...DEFAULT_SHADOW },
+ innerShadow: { ...DEFAULT_INNER_SHADOW },
+ stroke: { ...DEFAULT_STROKE },
+ glow: { ...DEFAULT_GLOW },
+ filters: { ...DEFAULT_FILTER },
+ parentId: null,
+ flipHorizontal: false,
+ flipVertical: false,
+ mask: null,
+ clippingMask: false,
+ levels: { ...DEFAULT_LEVELS },
+ curves: { ...DEFAULT_CURVES },
+ colorBalance: { ...DEFAULT_COLOR_BALANCE },
+ selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },
+ blackWhite: { ...DEFAULT_BLACK_WHITE },
+ photoFilter: { ...DEFAULT_PHOTO_FILTER },
+ channelMixer: { ...DEFAULT_CHANNEL_MIXER },
+ gradientMap: { ...DEFAULT_GRADIENT_MAP },
+ posterize: { ...DEFAULT_POSTERIZE },
+ threshold: { ...DEFAULT_THRESHOLD },
+ content: name,
+ style: { ...DEFAULT_TEXT_STYLE },
+ autoSize: true,
+ };
+}
+
+function makeShapeLayer(id: string): ShapeLayer {
+ return {
+ id,
+ name: 'Shape',
+ type: 'shape',
+ visible: true,
+ locked: false,
+ transform: { ...DEFAULT_TRANSFORM, x: 10, y: 20, width: 100, height: 100 },
+ blendMode: { ...DEFAULT_BLEND_MODE },
+ shadow: { ...DEFAULT_SHADOW },
+ innerShadow: { ...DEFAULT_INNER_SHADOW },
+ stroke: { ...DEFAULT_STROKE },
+ glow: { ...DEFAULT_GLOW },
+ filters: { ...DEFAULT_FILTER },
+ parentId: null,
+ flipHorizontal: false,
+ flipVertical: false,
+ mask: null,
+ clippingMask: false,
+ levels: { ...DEFAULT_LEVELS },
+ curves: { ...DEFAULT_CURVES },
+ colorBalance: { ...DEFAULT_COLOR_BALANCE },
+ selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },
+ blackWhite: { ...DEFAULT_BLACK_WHITE },
+ photoFilter: { ...DEFAULT_PHOTO_FILTER },
+ channelMixer: { ...DEFAULT_CHANNEL_MIXER },
+ gradientMap: { ...DEFAULT_GRADIENT_MAP },
+ posterize: { ...DEFAULT_POSTERIZE },
+ threshold: { ...DEFAULT_THRESHOLD },
+ shapeType: 'rectangle',
+ shapeStyle: { ...DEFAULT_SHAPE_STYLE },
+ };
+}
+
+// ── Helper: apply then invert ─────────────────────────────────────────────────
+
+/**
+ * Applies cmd to project, then applies the inverse to the result.
+ * The final project should equal the original (deep-equal data).
+ */
+function roundTrip<T>(project: T, cmd: { apply: (p: T) => T; invert: () => { apply: (p: T) => T } }): T {
+ const after = cmd.apply(project);
+ const inverse = cmd.invert();
+ return inverse.apply(after);
+}
+
+// ── SetProjectNameCommand ─────────────────────────────────────────────────────
+
+describe('SetProjectNameCommand', () => {
+ it('renames the project', () => {
+ const project = makeProject();
+ const cmd = new SetProjectNameCommand('New Name', 'Test');
+ const next = cmd.apply(project);
+ expect(next.name).toBe('New Name');
+ });
+
+ it('inverse restores the original name', () => {
+ const project = makeProject();
+ const cmd = new SetProjectNameCommand('New Name', 'Test');
+ const restored = roundTrip(project, cmd);
+ expect(restored.name).toBe('Test');
+ });
+
+ it('has a descriptive description', () => {
+ const cmd = new SetProjectNameCommand('Foo', 'Bar');
+ expect(cmd.description).toMatch(/Foo/);
+ });
+});
+
+// ── AddArtboardCommand ────────────────────────────────────────────────────────
+
+describe('AddArtboardCommand', () => {
+ it('adds an artboard to the project', () => {
+ const project = makeProject();
+ const artboard = { id: 'ab-2', name: 'Page 2', size: SIZE, background: { type: 'color' as const, color: '#fff' }, layerIds: [], position: { x: 0, y: 0 } };
+ const cmd = new AddArtboardCommand(artboard);
+ const next = cmd.apply(project);
+ expect(next.artboards).toHaveLength(2);
+ expect(next.artboards.find((a) => a.id === 'ab-2')).toBeDefined();
+ });
+
+ it('inverse removes the artboard', () => {
+ const project = makeProject();
+ const artboard = { id: 'ab-2', name: 'Page 2', size: SIZE, background: { type: 'color' as const, color: '#fff' }, layerIds: [], position: { x: 0, y: 0 } };
+ const cmd = new AddArtboardCommand(artboard);
+ const restored = roundTrip(project, cmd);
+ expect(restored.artboards).toHaveLength(1);
+ expect(restored.artboards.find((a) => a.id === 'ab-2')).toBeUndefined();
+ });
+});
+
+// ── RemoveArtboardCommand ─────────────────────────────────────────────────────
+
+describe('RemoveArtboardCommand', () => {
+ it('removes the artboard from the project', () => {
+ const base = makeProject();
+ const artboard = base.artboards[0];
+ const cmd = new RemoveArtboardCommand(AB_ID, artboard, {}, 0);
+ const next = cmd.apply(base);
+ expect(next.artboards.find((a) => a.id === AB_ID)).toBeUndefined();
+ });
+
+ it('inverse restores the artboard', () => {
+ const project = makeProject();
+ const artboard = project.artboards[0];
+ const cmd = new RemoveArtboardCommand(AB_ID, artboard, {}, 0);
+ const restored = roundTrip(project, cmd);
+ expect(restored.artboards.find((a) => a.id === AB_ID)).toBeDefined();
+ });
+
+ it('inverse restores removed layers', () => {
+ let project = makeProject();
+ const layer = makeTextLayer('l-1');
+ const addCmd = new AddLayerCommand(AB_ID, layer, 0);
+ project = addCmd.apply(project);
+
+ const artboard = project.artboards[0];
+ const removedLayers = { 'l-1': project.layers['l-1'] };
+ const cmd = new RemoveArtboardCommand(AB_ID, artboard, removedLayers, 0);
+ const after = cmd.apply(project);
+ expect(after.layers['l-1']).toBeUndefined();
+
+ const restored = cmd.invert().apply(after);
+ expect(restored.layers['l-1']).toBeDefined();
+ });
+});
+
+// ── UpdateArtboardCommand ─────────────────────────────────────────────────────
+
+describe('UpdateArtboardCommand', () => {
+ it('updates artboard fields', () => {
+ const project = makeProject();
+ const cmd = new UpdateArtboardCommand(AB_ID, { name: 'Renamed' }, { name: 'Artboard 1' });
+ const next = cmd.apply(project);
+ expect(next.artboards[0].name).toBe('Renamed');
+ });
+
+ it('inverse restores original fields', () => {
+ const project = makeProject();
+ const cmd = new UpdateArtboardCommand(AB_ID, { name: 'Renamed' }, { name: project.artboards[0].name });
+ const restored = roundTrip(project, cmd);
+ expect(restored.artboards[0].name).toBe('Artboard 1');
+ });
+});
+
+// ── AddLayerCommand ───────────────────────────────────────────────────────────
+
+describe('AddLayerCommand', () => {
+ it('adds a layer to the artboard', () => {
+ const project = makeProject();
+ const layer = makeTextLayer('l-1');
+ const cmd = new AddLayerCommand(AB_ID, layer, 0);
+ const next = cmd.apply(project);
+ expect(next.layers['l-1']).toBeDefined();
+ expect(next.artboards[0].layerIds).toContain('l-1');
+ });
+
+ it('inverse removes the layer', () => {
+ const project = makeProject();
+ const layer = makeTextLayer('l-1');
+ const cmd = new AddLayerCommand(AB_ID, layer, 0);
+ const restored = roundTrip(project, cmd);
+ expect(restored.layers['l-1']).toBeUndefined();
+ expect(restored.artboards[0].layerIds).not.toContain('l-1');
+ });
+
+ it('has a descriptive description', () => {
+ const layer = makeTextLayer('l-1', 'My Text');
+ const cmd = new AddLayerCommand(AB_ID, layer, 0);
+ expect(cmd.description).toMatch(/text/i);
+ expect(cmd.description).toMatch(/My Text/);
+ });
+});
+
+// ── RemoveLayerCommand ────────────────────────────────────────────────────────
+
+describe('RemoveLayerCommand', () => {
+ it('removes a layer from the project', () => {
+ let project = makeProject();
+ const layer = makeTextLayer('l-1');
+ project = new AddLayerCommand(AB_ID, layer, 0).apply(project);
+
+ const cmd = new RemoveLayerCommand('l-1', AB_ID, layer, 0);
+ const next = cmd.apply(project);
+ expect(next.layers['l-1']).toBeUndefined();
+ });
+
+ it('inverse restores the layer at the correct index', () => {
+ let project = makeProject();
+ const layer = makeTextLayer('l-1');
+ project = new AddLayerCommand(AB_ID, layer, 0).apply(project);
+
+ const cmd = new RemoveLayerCommand('l-1', AB_ID, layer, 0);
+ const after = cmd.apply(project);
+ const restored = cmd.invert().apply(after);
+ expect(restored.layers['l-1']).toBeDefined();
+ expect(restored.artboards[0].layerIds).toContain('l-1');
+ });
+});
+
+// ── DuplicateLayerCommand ─────────────────────────────────────────────────────
+
+describe('DuplicateLayerCommand', () => {
+ it('adds the duplicated layer to the artboard', () => {
+ const project = makeProject();
+ const dup = makeTextLayer('dup-1', 'Original copy');
+ const cmd = new DuplicateLayerCommand(AB_ID, dup, 0);
+ const next = cmd.apply(project);
+ expect(next.layers['dup-1']).toBeDefined();
+ });
+
+ it('inverse removes the duplicate', () => {
+ const project = makeProject();
+ const dup = makeTextLayer('dup-1', 'Original copy');
+ const cmd = new DuplicateLayerCommand(AB_ID, dup, 0);
+ const restored = roundTrip(project, cmd);
+ expect(restored.layers['dup-1']).toBeUndefined();
+ });
+});
+
+// ── ReorderLayerCommand ───────────────────────────────────────────────────────
+
+describe('ReorderLayerCommand', () => {
+ it('reorders artboard layer IDs', () => {
+ let project = makeProject();
+ project = new AddLayerCommand(AB_ID, makeTextLayer('l-1'), 0).apply(project);
+ project = new AddLayerCommand(AB_ID, makeTextLayer('l-2'), 0).apply(project);
+ // current: ['l-2', 'l-1']
+
+ const cmd = new ReorderLayerCommand(AB_ID, ['l-1', 'l-2'], ['l-2', 'l-1']);
+ const next = cmd.apply(project);
+ expect(next.artboards[0].layerIds).toEqual(['l-1', 'l-2']);
+ });
+
+ it('inverse restores the original order', () => {
+ let project = makeProject();
+ project = new AddLayerCommand(AB_ID, makeTextLayer('l-1'), 0).apply(project);
+ project = new AddLayerCommand(AB_ID, makeTextLayer('l-2'), 0).apply(project);
+ const prev = project.artboards[0].layerIds;
+
+ const cmd = new ReorderLayerCommand(AB_ID, ['l-1', 'l-2'], [...prev]);
+ const after = cmd.apply(project);
+ const restored = cmd.invert().apply(after);
+ expect(restored.artboards[0].layerIds).toEqual(prev);
+ });
+});
+
+// ── UpdateLayerTransformCommand ───────────────────────────────────────────────
+
+describe('UpdateLayerTransformCommand', () => {
+ it('applies the new transform', () => {
+ let project = makeProject();
+ project = new AddLayerCommand(AB_ID, makeTextLayer('l-1'), 0).apply(project);
+
+ const cmd = new UpdateLayerTransformCommand('l-1', { x: 100, y: 200 }, { x: 0, y: 0 });
+ const next = cmd.apply(project);
+ expect(next.layers['l-1'].transform.x).toBe(100);
+ expect(next.layers['l-1'].transform.y).toBe(200);
+ });
+
+ it('inverse restores the old transform', () => {
+ let project = makeProject();
+ project = new AddLayerCommand(AB_ID, makeTextLayer('l-1'), 0).apply(project);
+
+ const cmd = new UpdateLayerTransformCommand('l-1', { x: 100, y: 200 }, { x: 0, y: 0 });
+ const restored = roundTrip(project, cmd);
+ expect(restored.layers['l-1'].transform.x).toBe(0);
+ expect(restored.layers['l-1'].transform.y).toBe(0);
+ });
+
+ it('merges consecutive transform commands on the same layer', () => {
+ let project = makeProject();
+ project = new AddLayerCommand(AB_ID, makeTextLayer('l-1'), 0).apply(project);
+
+ const cmd1 = new UpdateLayerTransformCommand('l-1', { x: 50 }, { x: 0 });
+ const cmd2 = new UpdateLayerTransformCommand('l-1', { x: 100 }, { x: 50 });
+ const merged = cmd1.merge!(cmd2);
+
+ expect(merged).not.toBeNull();
+ const next = merged!.apply(project);
+ expect(next.layers['l-1'].transform.x).toBe(100);
+
+ // Undoing the merged command returns to original x=0
+ const restored = merged!.invert().apply(next);
+ expect(restored.layers['l-1'].transform.x).toBe(0);
+ });
+
+ it('does not merge transform commands on different layers', () => {
+ const cmd1 = new UpdateLayerTransformCommand('l-1', { x: 50 }, { x: 0 });
+ const cmd2 = new UpdateLayerTransformCommand('l-2', { x: 50 }, { x: 0 });
+ expect(cmd1.merge!(cmd2)).toBeNull();
+ });
+});
+
+// ── UpdateLayerStyleCommand ───────────────────────────────────────────────────
+
+describe('UpdateLayerStyleCommand', () => {
+ it('applies style updates', () => {
+ let project = makeProject();
+ project = new AddLayerCommand(AB_ID, makeTextLayer('l-1'), 0).apply(project);
+
+ const cmd = new UpdateLayerStyleCommand(
+ 'l-1',
+ { visible: false },
+ { visible: true },
+ );
+ const next = cmd.apply(project);
+ expect(next.layers['l-1'].visible).toBe(false);
+ });
+
+ it('inverse restores original style', () => {
+ let project = makeProject();
+ project = new AddLayerCommand(AB_ID, makeTextLayer('l-1'), 0).apply(project);
+
+ const cmd = new UpdateLayerStyleCommand('l-1', { visible: false }, { visible: true });
+ const restored = roundTrip(project, cmd);
+ expect(restored.layers['l-1'].visible).toBe(true);
+ });
+
+ it('merges style updates on the same layer', () => {
+ let project = makeProject();
+ project = new AddLayerCommand(AB_ID, makeTextLayer('l-1'), 0).apply(project);
+
+ const cmd1 = new UpdateLayerStyleCommand('l-1', { visible: false }, { visible: true });
+ const cmd2 = new UpdateLayerStyleCommand('l-1', { locked: true }, { locked: false });
+ const merged = cmd1.merge!(cmd2);
+ expect(merged).not.toBeNull();
+
+ const next = merged!.apply(project);
+ expect(next.layers['l-1'].visible).toBe(false);
+ expect(next.layers['l-1'].locked).toBe(true);
+
+ const restored = merged!.invert().apply(next);
+ expect(restored.layers['l-1'].visible).toBe(true);
+ expect(restored.layers['l-1'].locked).toBe(false);
+ });
+});
+
+// ── UpdateTextCommand ─────────────────────────────────────────────────────────
+
+describe('UpdateTextCommand', () => {
+ it('updates text content', () => {
+ let project = makeProject();
+ project = new AddLayerCommand(AB_ID, makeTextLayer('l-1', 'Hello'), 0).apply(project);
+
+ const cmd = new UpdateTextCommand('l-1', 'World', 'Hello', null, null);
+ const next = cmd.apply(project);
+ expect((next.layers['l-1'] as TextLayer).content).toBe('World');
+ });
+
+ it('inverse restores the previous content', () => {
+ let project = makeProject();
+ project = new AddLayerCommand(AB_ID, makeTextLayer('l-1', 'Hello'), 0).apply(project);
+
+ const cmd = new UpdateTextCommand('l-1', 'World', 'Hello', null, null);
+ const restored = roundTrip(project, cmd);
+ expect((restored.layers['l-1'] as TextLayer).content).toBe('Hello');
+ });
+
+ it('merges consecutive text edits on the same layer', () => {
+ let project = makeProject();
+ project = new AddLayerCommand(AB_ID, makeTextLayer('l-1', 'A'), 0).apply(project);
+
+ const cmd1 = new UpdateTextCommand('l-1', 'AB', 'A', null, null);
+ const cmd2 = new UpdateTextCommand('l-1', 'ABC', 'AB', null, null);
+ const merged = cmd1.merge!(cmd2)!;
+ expect(merged).not.toBeNull();
+
+ const next = merged.apply(project);
+ expect((next.layers['l-1'] as TextLayer).content).toBe('ABC');
+
+ const restored = merged.invert().apply(next);
+ expect((restored.layers['l-1'] as TextLayer).content).toBe('A');
+ });
+});
+
+// ── ApplyAdjustmentCommand ────────────────────────────────────────────────────
+
+describe('ApplyAdjustmentCommand', () => {
+ it('applies an adjustment value', () => {
+ let project = makeProject();
+ const layer = makeShapeLayer('l-1');
+ project = new AddLayerCommand(AB_ID, layer, 0).apply(project);
+
+ const cmd = new ApplyAdjustmentCommand('l-1', 'visible', false, true);
+ const next = cmd.apply(project);
+ expect(next.layers['l-1'].visible).toBe(false);
+ });
+
+ it('inverse restores the original adjustment value', () => {
+ let project = makeProject();
+ const layer = makeShapeLayer('l-1');
+ project = new AddLayerCommand(AB_ID, layer, 0).apply(project);
+
+ const cmd = new ApplyAdjustmentCommand('l-1', 'visible', false, true);
+ const restored = roundTrip(project, cmd);
+ expect(restored.layers['l-1'].visible).toBe(true);
+ });
+
+ it('merges same adjustment on same layer', () => {
+ let project = makeProject();
+ project = new AddLayerCommand(AB_ID, makeShapeLayer('l-1'), 0).apply(project);
+
+ const cmd1 = new ApplyAdjustmentCommand('l-1', 'visible', false, true);
+ const cmd2 = new ApplyAdjustmentCommand('l-1', 'visible', true, false);
+ const merged = cmd1.merge!(cmd2)!;
+ expect(merged).not.toBeNull();
+
+ const next = merged.apply(project);
+ expect(next.layers['l-1'].visible).toBe(true);
+
+ const restored = merged.invert().apply(next);
+ expect(restored.layers['l-1'].visible).toBe(true); // original was true
+ });
+
+ it('does not merge different adjustments', () => {
+ const cmd1 = new ApplyAdjustmentCommand('l-1', 'visible', false, true);
+ const cmd2 = new ApplyAdjustmentCommand('l-1', 'locked', true, false);
+ expect(cmd1.merge!(cmd2)).toBeNull();
+ });
+});
+
+// ── ApplyMaskCommand ──────────────────────────────────────────────────────────
+
+describe('ApplyMaskCommand', () => {
+ it('applies a mask to the layer', () => {
+ let project = makeProject();
+ project = new AddLayerCommand(AB_ID, makeTextLayer('l-1'), 0).apply(project);
+
+ const mask = { ...DEFAULT_LAYER_MASK, id: 'mask-1', type: 'vector' as const };
+ const cmd = new ApplyMaskCommand('l-1', mask, null);
+ const next = cmd.apply(project);
+ expect(next.layers['l-1'].mask).toEqual(mask);
+ });
+
+ it('inverse removes the mask', () => {
+ let project = makeProject();
+ project = new AddLayerCommand(AB_ID, makeTextLayer('l-1'), 0).apply(project);
+
+ const mask = { ...DEFAULT_LAYER_MASK, id: 'mask-1', type: 'vector' as const };
+ const cmd = new ApplyMaskCommand('l-1', mask, null);
+ const restored = roundTrip(project, cmd);
+ expect(restored.layers['l-1'].mask).toBeNull();
+ });
+
+ it('description mentions "Apply mask" when setting a mask', () => {
+ const mask = { ...DEFAULT_LAYER_MASK, id: 'mask-1' };
+ const cmd = new ApplyMaskCommand('l-1', mask, null);
+ expect(cmd.description).toMatch(/apply mask/i);
+ });
+
+ it('description mentions "Remove mask" when clearing a mask', () => {
+ const mask = { ...DEFAULT_LAYER_MASK, id: 'mask-1' };
+ const cmd = new ApplyMaskCommand('l-1', null, mask);
+ expect(cmd.description).toMatch(/remove mask/i);
+ });
+});
+
+// ── RasterEditCommand ─────────────────────────────────────────────────────────
+
+describe('RasterEditCommand', () => {
+ it('replaces layer data with after-state', () => {
+ let project = makeProject();
+ const before = makeShapeLayer('l-1');
+ project = new AddLayerCommand(AB_ID, before, 0).apply(project);
+ const after = { ...before, name: 'After raster' };
+
+ const cmd = new RasterEditCommand(
+ 'l-1',
+ AB_ID,
+ JSON.stringify(after),
+ JSON.stringify(before),
+ );
+ const next = cmd.apply(project);
+ expect(next.layers['l-1'].name).toBe('After raster');
+ });
+
+ it('inverse restores the before-state', () => {
+ let project = makeProject();
+ const before = makeShapeLayer('l-1');
+ project = new AddLayerCommand(AB_ID, before, 0).apply(project);
+ const after = { ...before, name: 'After raster' };
+
+ const cmd = new RasterEditCommand(
+ 'l-1',
+ AB_ID,
+ JSON.stringify(after),
+ JSON.stringify(before),
+ );
+ const restored = roundTrip(project, cmd);
+ expect(restored.layers['l-1'].name).toBe('Shape');
+ });
+});
+
+// ── GroupLayersCommand / UngroupLayersCommand ─────────────────────────────────
+
+describe('GroupLayersCommand / UngroupLayersCommand', () => {
+ function makeGroupSetup() {
+ let project = makeProject();
+ const shape1 = makeShapeLayer('s-1');
+ const shape2 = makeShapeLayer('s-2');
+ project = new AddLayerCommand(AB_ID, shape1, 0).apply(project);
+ project = new AddLayerCommand(AB_ID, shape2, 0).apply(project);
+ return project;
+ }
+
+ it('group adds a group layer containing the children', () => {
+ let project = makeGroupSetup();
+ const artboard = project.artboards[0];
+ const adjustedChildren: Record<string, import('./project').Layer> = {};
+ ['s-1', 's-2'].forEach((id) => {
+ adjustedChildren[id] = { ...project.layers[id], parentId: 'g-1' };
+ });
+ const groupLayer: GroupLayer = {
+ id: 'g-1',
+ name: 'Group',
+ type: 'group',
+ visible: true,
+ locked: false,
+ transform: { ...DEFAULT_TRANSFORM, x: 10, y: 20, width: 100, height: 100 },
+ blendMode: { ...DEFAULT_BLEND_MODE },
+ shadow: { ...DEFAULT_SHADOW },
+ innerShadow: { ...DEFAULT_INNER_SHADOW },
+ stroke: { ...DEFAULT_STROKE },
+ glow: { ...DEFAULT_GLOW },
+ filters: { ...DEFAULT_FILTER },
+ parentId: null,
+ flipHorizontal: false,
+ flipVertical: false,
+ mask: null,
+ clippingMask: false,
+ levels: { ...DEFAULT_LEVELS },
+ curves: { ...DEFAULT_CURVES },
+ colorBalance: { ...DEFAULT_COLOR_BALANCE },
+ selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },
+ blackWhite: { ...DEFAULT_BLACK_WHITE },
+ photoFilter: { ...DEFAULT_PHOTO_FILTER },
+ channelMixer: { ...DEFAULT_CHANNEL_MIXER },
+ gradientMap: { ...DEFAULT_GRADIENT_MAP },
+ posterize: { ...DEFAULT_POSTERIZE },
+ threshold: { ...DEFAULT_THRESHOLD },
+ childIds: ['s-1', 's-2'],
+ expanded: true,
+ };
+ const cmd = new GroupLayersCommand(AB_ID, groupLayer, 0, [...artboard.layerIds], adjustedChildren);
+ const next = cmd.apply(project);
+ expect(next.layers['g-1']).toBeDefined();
+ expect(next.artboards[0].layerIds).toContain('g-1');
+ });
+
+ it('ungroup restores children to artboard', () => {
+ let project = makeGroupSetup();
+ const artboard = project.artboards[0];
+ const adjustedChildren: Record<string, import('./project').Layer> = {};
+ ['s-1', 's-2'].forEach((id) => {
+ adjustedChildren[id] = { ...project.layers[id], parentId: 'g-1' };
+ });
+ const groupLayer: GroupLayer = {
+ id: 'g-1',
+ name: 'Group',
+ type: 'group',
+ visible: true,
+ locked: false,
+ transform: { ...DEFAULT_TRANSFORM, x: 10, y: 20, width: 100, height: 100 },
+ blendMode: { ...DEFAULT_BLEND_MODE },
+ shadow: { ...DEFAULT_SHADOW },
+ innerShadow: { ...DEFAULT_INNER_SHADOW },
+ stroke: { ...DEFAULT_STROKE },
+ glow: { ...DEFAULT_GLOW },
+ filters: { ...DEFAULT_FILTER },
+ parentId: null,
+ flipHorizontal: false,
+ flipVertical: false,
+ mask: null,
+ clippingMask: false,
+ levels: { ...DEFAULT_LEVELS },
+ curves: { ...DEFAULT_CURVES },
+ colorBalance: { ...DEFAULT_COLOR_BALANCE },
+ selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },
+ blackWhite: { ...DEFAULT_BLACK_WHITE },
+ photoFilter: { ...DEFAULT_PHOTO_FILTER },
+ channelMixer: { ...DEFAULT_CHANNEL_MIXER },
+ gradientMap: { ...DEFAULT_GRADIENT_MAP },
+ posterize: { ...DEFAULT_POSTERIZE },
+ threshold: { ...DEFAULT_THRESHOLD },
+ childIds: ['s-1', 's-2'],
+ expanded: true,
+ };
+ const prevIds = [...artboard.layerIds];
+ const groupCmd = new GroupLayersCommand(AB_ID, groupLayer, 0, prevIds, adjustedChildren);
+ const grouped = groupCmd.apply(project);
+
+ const ungroupCmd = new UngroupLayersCommand(
+ AB_ID,
+ 'g-1',
+ groupLayer,
+ prevIds,
+ { 's-1': project.layers['s-1'], 's-2': project.layers['s-2'] },
+ );
+ const ungrouped = ungroupCmd.apply(grouped);
+ expect(ungrouped.layers['g-1']).toBeUndefined();
+ expect(ungrouped.artboards[0].layerIds).toContain('s-1');
+ expect(ungrouped.artboards[0].layerIds).toContain('s-2');
+ });
+});
+
+// ── PasteLayersCommand ────────────────────────────────────────────────────────
+
+describe('PasteLayersCommand', () => {
+ it('pastes layers into the artboard', () => {
+ const project = makeProject();
+ const pasted = [makeTextLayer('p-1', 'Pasted')];
+ const cmd = new PasteLayersCommand(AB_ID, pasted, []);
+ const next = cmd.apply(project);
+ expect(next.layers['p-1']).toBeDefined();
+ expect(next.artboards[0].layerIds).toContain('p-1');
+ });
+
+ it('inverse removes the pasted layers', () => {
+ const project = makeProject();
+ const pasted = [makeTextLayer('p-1', 'Pasted')];
+ const cmd = new PasteLayersCommand(AB_ID, pasted, []);
+ const restored = roundTrip(project, cmd);
+ expect(restored.layers['p-1']).toBeUndefined();
+ expect(restored.artboards[0].layerIds).not.toContain('p-1');
+ });
+});
diff --git a/packages/image-core/src/commands.ts b/packages/image-core/src/commands.ts
new file mode 100644
index 00000000..98b9caf6
--- /dev/null
+++ b/packages/image-core/src/commands.ts
@@ -0,0 +1,751 @@
+import type { Artboard, Layer, Project, TextStyle, Transform } from './project';
+import type { LayerMask } from './mask';
+import {
+ addLayerToProject,
+ removeLayerFromProject,
+ reorderArtboardLayers,
+ updateLayerInProject,
+ updateLayerTransformInProject,
+} from './operations';
+
+// ---------------------------------------------------------------------------
+// Command interface
+// ---------------------------------------------------------------------------
+
+/**
+ * A reversible editing operation. Each command captures enough data to both
+ * apply itself and to construct an exact inverse command so that undo/redo is
+ * always correct. The optional `merge` method allows consecutive commands of
+ * the same type on the same target (e.g. dragging) to be coalesced into a
+ * single undo step.
+ */
+export interface Command {
+ readonly type: string;
+ readonly description: string;
+ apply(project: Project): Project;
+ invert(): Command;
+ merge?(next: Command): Command | null;
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function cloneProject(project: Project): Project {
+ return JSON.parse(JSON.stringify(project)) as Project;
+}
+
+function findArtboardIndex(project: Project, artboardId: string): number {
+ return project.artboards.findIndex((a) => a.id === artboardId);
+}
+
+function findLayerIndexInArtboard(project: Project, artboardId: string, layerId: string): number {
+ const artboard = project.artboards.find((a) => a.id === artboardId);
+ return artboard ? artboard.layerIds.indexOf(layerId) : -1;
+}
+
+// ---------------------------------------------------------------------------
+// Project-level commands
+// ---------------------------------------------------------------------------
+
+export class SetProjectNameCommand implements Command {
+ readonly type = 'SetProjectName';
+
+ constructor(
+ private readonly newName: string,
+ private readonly prevName: string,
+ ) {}
+
+ get description(): string {
+ return `Rename project to "${this.newName}"`;
+ }
+
+ apply(project: Project): Project {
+ const next = cloneProject(project);
+ next.name = this.newName;
+ next.updatedAt = Date.now();
+ return next;
+ }
+
+ invert(): Command {
+ return new SetProjectNameCommand(this.prevName, this.newName);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Artboard commands
+// ---------------------------------------------------------------------------
+
+export class AddArtboardCommand implements Command {
+ readonly type = 'AddArtboard';
+
+ constructor(
+ private readonly artboard: Artboard,
+ private readonly insertIndex?: number,
+ ) {}
+
+ get description(): string {
+ return `Add artboard "${this.artboard.name}"`;
+ }
+
+ apply(project: Project): Project {
+ const next = cloneProject(project);
+ const idx = this.insertIndex ?? next.artboards.length;
+ next.artboards.splice(idx, 0, structuredClone(this.artboard));
+ next.updatedAt = Date.now();
+ return next;
+ }
+
+ invert(): Command {
+ return new RemoveArtboardCommand(
+ this.artboard.id,
+ this.artboard,
+ {},
+ this.insertIndex ?? -1,
+ );
+ }
+}
+
+export class RemoveArtboardCommand implements Command {
+ readonly type = 'RemoveArtboard';
+
+ constructor(
+ private readonly artboardId: string,
+ private readonly artboard: Artboard,
+ private readonly removedLayers: Record<string, Layer>,
+ private readonly originalIndex: number,
+ ) {}
+
+ get description(): string {
+ return `Remove artboard "${this.artboard.name}"`;
+ }
+
+ apply(project: Project): Project {
+ const next = cloneProject(project);
+ const artboard = next.artboards.find((a) => a.id === this.artboardId);
+ if (artboard) {
+ artboard.layerIds.forEach((id) => {
+ delete next.layers[id];
+ });
+ next.artboards = next.artboards.filter((a) => a.id !== this.artboardId);
+ if (next.activeArtboardId === this.artboardId) {
+ next.activeArtboardId = next.artboards[0]?.id ?? null;
+ }
+ next.updatedAt = Date.now();
+ }
+ return next;
+ }
+
+ invert(): Command {
+ const restoredArtboard = structuredClone(this.artboard);
+ const restoredLayers = structuredClone(this.removedLayers);
+ return new RestoreArtboardCommand(restoredArtboard, restoredLayers, this.originalIndex);
+ }
+}
+
+/** Internal command used only as the inverse of RemoveArtboardCommand. */
+class RestoreArtboardCommand implements Command {
+ readonly type = 'RestoreArtboard';
+
+ constructor(
+ private readonly artboard: Artboard,
+ private readonly layers: Record<string, Layer>,
+ private readonly insertIndex: number,
+ ) {}
+
+ get description(): string {
+ return `Restore artboard "${this.artboard.name}"`;
+ }
+
+ apply(project: Project): Project {
+ const next = cloneProject(project);
+ const idx = this.insertIndex >= 0 ? this.insertIndex : next.artboards.length;
+ next.artboards.splice(idx, 0, structuredClone(this.artboard));
+ Object.entries(this.layers).forEach(([id, layer]) => {
+ next.layers[id] = structuredClone(layer);
+ });
+ next.updatedAt = Date.now();
+ return next;
+ }
+
+ invert(): Command {
+ return new RemoveArtboardCommand(
+ this.artboard.id,
+ this.artboard,
+ this.layers,
+ this.insertIndex,
+ );
+ }
+}
+
+export class UpdateArtboardCommand implements Command {
+ readonly type = 'UpdateArtboard';
+
+ constructor(
+ private readonly artboardId: string,
+ private readonly updates: Partial<Artboard>,
+ private readonly prevValues: Partial<Artboard>,
+ private readonly descriptionText?: string,
+ ) {}
+
+ get description(): string {
+ return this.descriptionText ?? 'Update artboard';
+ }
+
+ apply(project: Project): Project {
+ const next = cloneProject(project);
+ const artboard = next.artboards.find((a) => a.id === this.artboardId);
+ if (artboard) {
+ Object.assign(artboard, this.updates);
+ next.updatedAt = Date.now();
+ }
+ return next;
+ }
+
+ invert(): Command {
+ return new UpdateArtboardCommand(
+ this.artboardId,
+ this.prevValues,
+ this.updates,
+ `Undo ${this.description.toLowerCase()}`,
+ );
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Layer commands
+// ---------------------------------------------------------------------------
+
+export class AddLayerCommand implements Command {
+ readonly type = 'AddLayer';
+
+ constructor(
+ private readonly artboardId: string,
+ private readonly layer: Layer,
+ private readonly index: number,
+ private readonly descriptionText?: string,
+ ) {}
+
+ get description(): string {
+ return this.descriptionText ?? `Add ${this.layer.type} layer "${this.layer.name}"`;
+ }
+
+ apply(project: Project): Project {
+ return addLayerToProject(project, this.artboardId, structuredClone(this.layer), this.index);
+ }
+
+ invert(): Command {
+ return new RemoveLayerCommand(
+ this.layer.id,
+ this.artboardId,
+ structuredClone(this.layer),
+ this.index,
+ `Remove ${this.layer.type} layer "${this.layer.name}"`,
+ );
+ }
+}
+
+export class RemoveLayerCommand implements Command {
+ readonly type = 'RemoveLayer';
+
+ constructor(
+ private readonly layerId: string,
+ private readonly artboardId: string,
+ private readonly layer: Layer,
+ private readonly originalIndex: number,
+ private readonly descriptionText?: string,
+ ) {}
+
+ get description(): string {
+ return this.descriptionText ?? `Remove layer "${this.layer.name}"`;
+ }
+
+ apply(project: Project): Project {
+ return removeLayerFromProject(project, this.layerId);
+ }
+
+ invert(): Command {
+ return new AddLayerCommand(
+ this.artboardId,
+ structuredClone(this.layer),
+ this.originalIndex,
+ `Restore layer "${this.layer.name}"`,
+ );
+ }
+}
+
+export class DuplicateLayerCommand implements Command {
+ readonly type = 'DuplicateLayer';
+
+ constructor(
+ private readonly artboardId: string,
+ private readonly duplicatedLayer: Layer,
+ private readonly insertIndex: number,
+ ) {}
+
+ get description(): string {
+ return `Duplicate layer "${this.duplicatedLayer.name}"`;
+ }
+
+ apply(project: Project): Project {
+ return addLayerToProject(
+ project,
+ this.artboardId,
+ structuredClone(this.duplicatedLayer),
+ this.insertIndex,
+ );
+ }
+
+ invert(): Command {
+ return new RemoveLayerCommand(
+ this.duplicatedLayer.id,
+ this.artboardId,
+ structuredClone(this.duplicatedLayer),
+ this.insertIndex,
+ `Remove duplicate "${this.duplicatedLayer.name}"`,
+ );
+ }
+}
+
+export class ReorderLayerCommand implements Command {
+ readonly type = 'ReorderLayer';
+
+ constructor(
+ private readonly artboardId: string,
+ private readonly newLayerIds: string[],
+ private readonly prevLayerIds: string[],
+ private readonly descriptionText?: string,
+ ) {}
+
+ get description(): string {
+ return this.descriptionText ?? 'Reorder layers';
+ }
+
+ apply(project: Project): Project {
+ return reorderArtboardLayers(project, this.artboardId, this.newLayerIds);
+ }
+
+ invert(): Command {
+ return new ReorderLayerCommand(this.artboardId, this.prevLayerIds, this.newLayerIds, 'Undo reorder');
+ }
+}
+
+export class UpdateLayerTransformCommand implements Command {
+ readonly type = 'UpdateLayerTransform';
+
+ constructor(
+ private readonly layerId: string,
+ private readonly newTransform: Partial<Transform>,
+ private readonly prevTransform: Partial<Transform>,
+ private readonly descriptionText?: string,
+ ) {}
+
+ get description(): string {
+ return this.descriptionText ?? 'Move/resize layer';
+ }
+
+ apply(project: Project): Project {
+ return updateLayerTransformInProject(project, this.layerId, this.newTransform);
+ }
+
+ invert(): Command {
+ return new UpdateLayerTransformCommand(
+ this.layerId,
+ this.prevTransform,
+ this.newTransform,
+ `Undo ${this.description.toLowerCase()}`,
+ );
+ }
+
+ merge(next: Command): Command | null {
+ if (!(next instanceof UpdateLayerTransformCommand)) return null;
+ if (next.layerId !== this.layerId) return null;
+ return new UpdateLayerTransformCommand(
+ this.layerId,
+ next.newTransform,
+ this.prevTransform,
+ next.descriptionText ?? this.descriptionText,
+ );
+ }
+}
+
+export class UpdateLayerStyleCommand implements Command {
+ readonly type = 'UpdateLayerStyle';
+
+ constructor(
+ private readonly layerId: string,
+ private readonly updates: Partial<Layer>,
+ private readonly prevValues: Partial<Layer>,
+ private readonly descriptionText?: string,
+ ) {}
+
+ get description(): string {
+ return this.descriptionText ?? 'Update layer style';
+ }
+
+ apply(project: Project): Project {
+ return updateLayerInProject(project, this.layerId, this.updates);
+ }
+
+ invert(): Command {
+ return new UpdateLayerStyleCommand(
+ this.layerId,
+ this.prevValues,
+ this.updates,
+ `Undo ${this.description.toLowerCase()}`,
+ );
+ }
+
+ merge(next: Command): Command | null {
+ if (!(next instanceof UpdateLayerStyleCommand)) return null;
+ if (next.layerId !== this.layerId) return null;
+ const mergedUpdates = { ...this.updates, ...next.updates };
+ const mergedPrev = { ...next.prevValues, ...this.prevValues };
+ return new UpdateLayerStyleCommand(
+ this.layerId,
+ mergedUpdates,
+ mergedPrev,
+ next.descriptionText ?? this.descriptionText,
+ );
+ }
+}
+
+export class UpdateTextCommand implements Command {
+ readonly type = 'UpdateText';
+
+ constructor(
+ private readonly layerId: string,
+ private readonly newContent: string,
+ private readonly prevContent: string,
+ private readonly newStyle: TextStyle | null,
+ private readonly prevStyle: TextStyle | null,
+ ) {}
+
+ get description(): string {
+ return 'Edit text';
+ }
+
+ apply(project: Project): Project {
+ const updates: Record<string, unknown> = { content: this.newContent };
+ if (this.newStyle !== null) updates.style = this.newStyle;
+ return updateLayerInProject(project, this.layerId, updates as Partial<Layer>);
+ }
+
+ invert(): Command {
+ return new UpdateTextCommand(
+ this.layerId,
+ this.prevContent,
+ this.newContent,
+ this.prevStyle,
+ this.newStyle,
+ );
+ }
+
+ merge(next: Command): Command | null {
+ if (!(next instanceof UpdateTextCommand)) return null;
+ if (next.layerId !== this.layerId) return null;
+ return new UpdateTextCommand(
+ this.layerId,
+ next.newContent,
+ this.prevContent,
+ next.newStyle,
+ this.prevStyle,
+ );
+ }
+}
+
+export class ApplyAdjustmentCommand implements Command {
+ readonly type = 'ApplyAdjustment';
+
+ constructor(
+ private readonly layerId: string,
+ private readonly adjustmentKey: string,
+ private readonly newValue: unknown,
+ private readonly prevValue: unknown,
+ ) {}
+
+ get description(): string {
+ return `Adjust ${this.adjustmentKey}`;
+ }
+
+ apply(project: Project): Project {
+ return updateLayerInProject(project, this.layerId, {
+ [this.adjustmentKey]: this.newValue,
+ } as Partial<Layer>);
+ }
+
+ invert(): Command {
+ return new ApplyAdjustmentCommand(
+ this.layerId,
+ this.adjustmentKey,
+ this.prevValue,
+ this.newValue,
+ );
+ }
+
+ merge(next: Command): Command | null {
+ if (!(next instanceof ApplyAdjustmentCommand)) return null;
+ if (next.layerId !== this.layerId) return null;
+ if (next.adjustmentKey !== this.adjustmentKey) return null;
+ return new ApplyAdjustmentCommand(
+ this.layerId,
+ this.adjustmentKey,
+ next.newValue,
+ this.prevValue,
+ );
+ }
+}
+
+export class ApplyMaskCommand implements Command {
+ readonly type = 'ApplyMask';
+
+ constructor(
+ private readonly layerId: string,
+ private readonly newMask: LayerMask | null,
+ private readonly prevMask: LayerMask | null,
+ ) {}
+
+ get description(): string {
+ return this.newMask ? 'Apply mask' : 'Remove mask';
+ }
+
+ apply(project: Project): Project {
+ return updateLayerInProject(project, this.layerId, { mask: this.newMask } as Partial<Layer>);
+ }
+
+ invert(): Command {
+ return new ApplyMaskCommand(this.layerId, this.prevMask, this.newMask);
+ }
+}
+
+/**
+ * RasterEdit captures a full serialized snapshot of the affected layer for
+ * large pixel-level edits where computing an inverse analytically is not
+ * practical. The inverse simply restores the layer to its pre-edit state.
+ */
+export class RasterEditCommand implements Command {
+ readonly type = 'RasterEdit';
+
+ constructor(
+ private readonly layerId: string,
+ private readonly artboardId: string,
+ private readonly afterLayerJson: string,
+ private readonly beforeLayerJson: string,
+ private readonly descriptionText = 'Raster edit',
+ ) {}
+
+ get description(): string {
+ return this.descriptionText;
+ }
+
+ apply(project: Project): Project {
+ const next = cloneProject(project);
+ next.layers[this.layerId] = JSON.parse(this.afterLayerJson) as Layer;
+ next.updatedAt = Date.now();
+ return next;
+ }
+
+ invert(): Command {
+ return new RasterEditCommand(
+ this.layerId,
+ this.artboardId,
+ this.beforeLayerJson,
+ this.afterLayerJson,
+ `Undo ${this.descriptionText.toLowerCase()}`,
+ );
+ }
+}
+
+/**
+ * GroupLayersCommand groups several layers under a new group layer.
+ * It stores enough state to restore the original flat arrangement on undo.
+ */
+export class GroupLayersCommand implements Command {
+ readonly type = 'GroupLayers';
+
+ constructor(
+ private readonly artboardId: string,
+ private readonly groupLayer: Layer,
+ private readonly groupInsertIndex: number,
+ private readonly prevArtboardLayerIds: string[],
+ private readonly childLayersBefore: Record<string, Layer>,
+ ) {}
+
+ get description(): string {
+ return `Group ${Object.keys(this.childLayersBefore).length} layers`;
+ }
+
+ apply(project: Project): Project {
+ const next = cloneProject(project);
+ const artboard = next.artboards.find((a) => a.id === this.artboardId);
+ if (!artboard) return next;
+ const childIds = (this.groupLayer as import('./project').GroupLayer).childIds;
+ childIds.forEach((childId) => {
+ if (next.layers[childId]) {
+ next.layers[childId] = {
+ ...next.layers[childId],
+ ...structuredClone(this.childLayersBefore[childId]) ?? {},
+ parentId: this.groupLayer.id,
+ };
+ }
+ });
+ artboard.layerIds = artboard.layerIds.filter((id) => !childIds.includes(id));
+ next.layers[this.groupLayer.id] = structuredClone(this.groupLayer);
+ artboard.layerIds.splice(this.groupInsertIndex, 0, this.groupLayer.id);
+ next.updatedAt = Date.now();
+ return next;
+ }
+
+ invert(): Command {
+ return new UngroupLayersCommand(
+ this.artboardId,
+ this.groupLayer.id,
+ this.groupLayer,
+ this.prevArtboardLayerIds,
+ this.childLayersBefore,
+ );
+ }
+}
+
+export class UngroupLayersCommand implements Command {
+ readonly type = 'UngroupLayers';
+
+ constructor(
+ private readonly artboardId: string,
+ private readonly groupId: string,
+ private readonly groupLayer: Layer,
+ private readonly prevArtboardLayerIds: string[],
+ private readonly childLayersBefore: Record<string, Layer>,
+ ) {}
+
+ get description(): string {
+ return 'Ungroup layers';
+ }
+
+ apply(project: Project): Project {
+ const next = cloneProject(project);
+ const artboard = next.artboards.find((a) => a.id === this.artboardId);
+ if (!artboard) return next;
+ const group = next.layers[this.groupId] as import('./project').GroupLayer;
+ if (!group || group.type !== 'group') return next;
+ const groupIndex = artboard.layerIds.indexOf(this.groupId);
+ const { x: groupX, y: groupY } = group.transform;
+ group.childIds.forEach((childId) => {
+ const child = next.layers[childId];
+ if (child) {
+ child.transform.x += groupX;
+ child.transform.y += groupY;
+ child.parentId = null;
+ }
+ });
+ artboard.layerIds.splice(groupIndex, 1, ...group.childIds);
+ delete next.layers[this.groupId];
+ next.updatedAt = Date.now();
+ return next;
+ }
+
+ invert(): Command {
+ const childIds = (this.groupLayer as import('./project').GroupLayer).childIds;
+ return new GroupLayersCommand(
+ this.artboardId,
+ structuredClone(this.groupLayer),
+ this.prevArtboardLayerIds.indexOf(this.groupId),
+ this.prevArtboardLayerIds,
+ Object.fromEntries(
+ childIds.map((id) => [id, structuredClone(this.childLayersBefore[id])]),
+ ),
+ );
+ }
+}
+
+export class PasteLayersCommand implements Command {
+ readonly type = 'PasteLayers';
+
+ constructor(
+ private readonly artboardId: string,
+ private readonly pastedLayers: Layer[],
+ private readonly prevArtboardLayerIds: string[],
+ ) {}
+
+ get description(): string {
+ return `Paste ${this.pastedLayers.length} layer${this.pastedLayers.length !== 1 ? 's' : ''}`;
+ }
+
+ apply(project: Project): Project {
+ let next = cloneProject(project);
+ const artboard = next.artboards.find((a) => a.id === this.artboardId);
+ if (!artboard) return next;
+ this.pastedLayers.forEach((layer) => {
+ next.layers[layer.id] = structuredClone(layer);
+ artboard.layerIds.unshift(layer.id);
+ });
+ next.updatedAt = Date.now();
+ return next;
+ }
+
+ invert(): Command {
+ const layerIds = this.pastedLayers.map((l) => l.id);
+ return new RemovePastedLayersCommand(
+ this.artboardId,
+ layerIds,
+ this.pastedLayers,
+ this.prevArtboardLayerIds,
+ );
+ }
+}
+
+class RemovePastedLayersCommand implements Command {
+ readonly type = 'RemovePastedLayers';
+
+ constructor(
+ private readonly artboardId: string,
+ private readonly layerIds: string[],
+ private readonly layers: Layer[],
+ private readonly prevArtboardLayerIds: string[],
+ ) {}
+
+ get description(): string {
+ return `Undo paste ${this.layers.length} layer${this.layers.length !== 1 ? 's' : ''}`;
+ }
+
+ apply(project: Project): Project {
+ let next = cloneProject(project);
+ this.layerIds.forEach((id) => {
+ next = removeLayerFromProject(next, id);
+ });
+ return next;
+ }
+
+ invert(): Command {
+ return new PasteLayersCommand(this.artboardId, this.layers, this.prevArtboardLayerIds);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Lookup table for history panel icons / display grouping
+// ---------------------------------------------------------------------------
+
+export const COMMAND_DISPLAY_INFO: Record<string, { icon: string; category: string }> = {
+ SetProjectName: { icon: 'pencil', category: 'Project' },
+ AddArtboard: { icon: 'layout', category: 'Artboard' },
+ RemoveArtboard: { icon: 'layout', category: 'Artboard' },
+ RestoreArtboard: { icon: 'layout', category: 'Artboard' },
+ UpdateArtboard: { icon: 'layout', category: 'Artboard' },
+ AddLayer: { icon: 'plus', category: 'Layer' },
+ RemoveLayer: { icon: 'trash', category: 'Layer' },
+ DuplicateLayer: { icon: 'copy', category: 'Layer' },
+ ReorderLayer: { icon: 'move', category: 'Layer' },
+ UpdateLayerTransform: { icon: 'move', category: 'Transform' },
+ UpdateLayerStyle: { icon: 'sliders', category: 'Style' },
+ UpdateText: { icon: 'type', category: 'Text' },
+ ApplyAdjustment: { icon: 'sliders', category: 'Adjustment' },
+ ApplyMask: { icon: 'scissors', category: 'Mask' },
+ RasterEdit: { icon: 'image', category: 'Paint' },
+ GroupLayers: { icon: 'folder', category: 'Layer' },
+ UngroupLayers: { icon: 'folder-open', category: 'Layer' },
+ PasteLayers: { icon: 'clipboard', category: 'Layer' },
+ RemovePastedLayers: { icon: 'clipboard', category: 'Layer' },
+};
+
+// Re-export helpers used by callers that capture "before" data
+export { findArtboardIndex, findLayerIndexInArtboard };
diff --git a/packages/image-core/src/index.ts b/packages/image-core/src/index.ts
index 00fb180c..449b97b6 100644
--- a/packages/image-core/src/index.ts
+++ b/packages/image-core/src/index.ts
@@ -1,4 +1,5 @@
export * from './adjustments';
+export * from './commands';
export * from './mask';
export * from './migration';
export * from './operations';