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

fix: address code review issues - merge direction, goToEntry order, pasteLayerStyle loop, isDirty after undo

copilot-swe-agent[bot]8c2af6ed1693
diff --git a/apps/image/src/stores/history-store.test.ts b/apps/image/src/stores/history-store.test.ts
index 19dc2cdb..7bf4f68f 100644
--- a/apps/image/src/stores/history-store.test.ts
+++ b/apps/image/src/stores/history-store.test.ts
@@ -1,10 +1,6 @@
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 };
@@ -34,64 +30,21 @@ 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', () => {
+ it('executes a command and records it in the undo stack', () => {
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);
-
+ useProjectStore.getState().addTextLayer('Hello');
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');
@@ -350,8 +303,8 @@ describe('history-store (command-based)', () => {
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');
+ useProjectStore.getState().addTextLayer('First');
+ useProjectStore.getState().addTextLayer('Second');
// Undo twice
useProjectStore.getState().undo();
diff --git a/apps/image/src/stores/history-store.ts b/apps/image/src/stores/history-store.ts
index b6aef5d8..8d60db45 100644
--- a/apps/image/src/stores/history-store.ts
+++ b/apps/image/src/stores/history-store.ts
@@ -121,10 +121,11 @@ export const useHistoryStore = create<HistoryState & HistoryActions>()(
const base = baseProject ?? JSON.stringify(currentProject);
// Attempt to coalesce with the most recent command via Command.merge.
- if (undoStack.length > 0 && typeof cmd.merge === 'function') {
+ // Merge is called on the LAST (older) command with the NEW command as argument.
+ if (undoStack.length > 0) {
const last = undoStack[undoStack.length - 1];
- const merged = cmd.merge.call(last.command, cmd);
- if (merged !== null && merged !== undefined) {
+ const merged = last.command.merge?.(cmd) ?? null;
+ if (merged !== null) {
const newProject = cmd.apply(currentProject);
const updatedStack = [
...undoStack.slice(0, -1),
@@ -230,7 +231,10 @@ export const useHistoryStore = create<HistoryState & HistoryActions>()(
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) });
+ // Commands past the target index become the redo stack, with the
+ // next-to-apply command at the end (to be popped first on redo).
+ const futureCommands = undoStack.slice(index + 1).reverse();
+ set({ undoStack: undoStack.slice(0, index + 1), redoStack: futureCommands });
return project;
} catch {
return null;
diff --git a/apps/image/src/stores/project-store.ts b/apps/image/src/stores/project-store.ts
index 49a6eb8b..9efd9079 100644
--- a/apps/image/src/stores/project-store.ts
+++ b/apps/image/src/stores/project-store.ts
@@ -200,36 +200,28 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
undo: () => {
const { project } = get();
if (!project) return;
- const histStore = useHistoryStore.getState();
- const newProject = histStore.undo(project);
+ const newProject = useHistoryStore.getState().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,
- });
- }
+ set({
+ project: newProject,
+ selectedLayerIds: [],
+ selectedArtboardId: newProject.activeArtboardId,
+ isDirty: true,
+ });
}
},
redo: () => {
const { project } = get();
if (!project) return;
- const histStore = useHistoryStore.getState();
- const newProject = histStore.redo(project);
+ const newProject = useHistoryStore.getState().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,
- });
- }
+ set({
+ project: newProject,
+ selectedLayerIds: [],
+ selectedArtboardId: newProject.activeArtboardId,
+ isDirty: true,
+ });
}
},
@@ -825,18 +817,20 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
},
pasteLayerStyle: () => {
- const { copiedStyle, selectedLayerIds, project } = get();
- if (!copiedStyle || !selectedLayerIds.length || !project) return;
- selectedLayerIds.forEach((layerId) => {
- const layer = project?.layers[layerId];
- if (!layer) return;
+ const { copiedStyle, selectedLayerIds } = get();
+ let currentProject = get().project;
+ if (!copiedStyle || !selectedLayerIds.length || !currentProject) return;
+
+ for (const layerId of selectedLayerIds) {
+ const layer = currentProject.layers[layerId];
+ if (!layer) continue;
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,
+ blendMode: structuredClone(copiedStyle.blendMode ?? DEFAULT_BLEND_MODE),
+ shadow: structuredClone(copiedStyle.shadow ?? DEFAULT_SHADOW),
+ innerShadow: structuredClone(copiedStyle.innerShadow ?? DEFAULT_INNER_SHADOW),
+ stroke: structuredClone(copiedStyle.stroke ?? DEFAULT_STROKE),
+ glow: structuredClone(copiedStyle.glow ?? DEFAULT_GLOW),
+ filters: structuredClone(copiedStyle.filters ?? DEFAULT_FILTER),
};
const prevValues: Partial<Layer> = {
blendMode: layer.blendMode,
@@ -846,12 +840,10 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(
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 });
- });
+ currentProject = execCmd(currentProject, cmd);
+ }
+ set({ project: currentProject, isDirty: true });
},
// ── Group / ungroup ──────────────────────────────────────────────────
diff --git a/packages/image-core/src/commands.ts b/packages/image-core/src/commands.ts
index 98b9caf6..8770f84e 100644
--- a/packages/image-core/src/commands.ts
+++ b/packages/image-core/src/commands.ts
@@ -1,4 +1,4 @@
-import type { Artboard, Layer, Project, TextStyle, Transform } from './project';
+import type { Artboard, GroupLayer, Layer, Project, TextStyle, Transform } from './project';
import type { LayerMask } from './mask';
import {
addLayerToProject,
@@ -565,7 +565,7 @@ export class GroupLayersCommand implements Command {
constructor(
private readonly artboardId: string,
- private readonly groupLayer: Layer,
+ private readonly groupLayer: GroupLayer,
private readonly groupInsertIndex: number,
private readonly prevArtboardLayerIds: string[],
private readonly childLayersBefore: Record<string, Layer>,
@@ -579,12 +579,12 @@ export class GroupLayersCommand implements Command {
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;
+ const { childIds } = this.groupLayer;
childIds.forEach((childId) => {
if (next.layers[childId]) {
next.layers[childId] = {
...next.layers[childId],
- ...structuredClone(this.childLayersBefore[childId]) ?? {},
+ ...(structuredClone(this.childLayersBefore[childId]) ?? {}),
parentId: this.groupLayer.id,
};
}
@@ -613,7 +613,7 @@ export class UngroupLayersCommand implements Command {
constructor(
private readonly artboardId: string,
private readonly groupId: string,
- private readonly groupLayer: Layer,
+ private readonly groupLayer: GroupLayer,
private readonly prevArtboardLayerIds: string[],
private readonly childLayersBefore: Record<string, Layer>,
) {}
@@ -626,7 +626,7 @@ export class UngroupLayersCommand implements Command {
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;
+ const group = next.layers[this.groupId] as GroupLayer;
if (!group || group.type !== 'group') return next;
const groupIndex = artboard.layerIds.indexOf(this.groupId);
const { x: groupX, y: groupY } = group.transform;
@@ -645,7 +645,7 @@ export class UngroupLayersCommand implements Command {
}
invert(): Command {
- const childIds = (this.groupLayer as import('./project').GroupLayer).childIds;
+ const { childIds } = this.groupLayer;
return new GroupLayersCommand(
this.artboardId,
structuredClone(this.groupLayer),