feat: add project management features including open/save functionality and recovery support
This commit is contained in:
58
operations/project/format.test.ts
Normal file
58
operations/project/format.test.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { ImageDocument } from "@core/document";
|
||||
import { CURRENT_PROJECT_VERSION, parseProject, projectFileName, serializeProject } from "./format";
|
||||
|
||||
describe("project format", () => {
|
||||
test("round-trips a versioned project with embedded assets", () => {
|
||||
const document = projectDocument();
|
||||
const result = parseProject(serializeProject(document, "2026-07-10T12:00:00.000Z"));
|
||||
|
||||
expect(result.version).toBe(CURRENT_PROJECT_VERSION);
|
||||
expect(result.savedAt).toBe("2026-07-10T12:00:00.000Z");
|
||||
expect(result.document).toEqual(document);
|
||||
});
|
||||
|
||||
test("migrates a legacy bare document", () => {
|
||||
const result = parseProject(JSON.stringify(projectDocument()));
|
||||
expect(result.version).toBe(1);
|
||||
expect(result.savedAt).toBe("1970-01-01T00:00:00.000Z");
|
||||
});
|
||||
|
||||
test("rejects unknown versions and invalid JSON", () => {
|
||||
expect(() => parseProject("not json")).toThrow("not valid JSON");
|
||||
expect(() => parseProject(JSON.stringify({ format: "image-studio-project", version: 99, savedAt: "now", document: projectDocument() }))).toThrow("Unsupported project version");
|
||||
});
|
||||
|
||||
test("enforces project-owned embedded assets and valid references", () => {
|
||||
const externalAsset = projectDocument();
|
||||
externalAsset.assets[0]!.source = "blob:https://example.test/asset";
|
||||
expect(() => serializeProject(externalAsset)).toThrow("not embedded");
|
||||
|
||||
const missingAsset = projectDocument();
|
||||
missingAsset.assets = [];
|
||||
expect(() => serializeProject(missingAsset)).toThrow("references missing asset");
|
||||
});
|
||||
|
||||
test("creates safe project file names", () => {
|
||||
expect(projectFileName(" Summer / Study ")).toBe("Summer-Study.image-studio.json");
|
||||
expect(projectFileName("***")).toBe("untitled.image-studio.json");
|
||||
});
|
||||
});
|
||||
|
||||
function projectDocument(): ImageDocument {
|
||||
return {
|
||||
id: "document-1",
|
||||
name: "Test Project",
|
||||
version: 1,
|
||||
assets: [{ id: "asset-1", name: "pixels.png", mimeType: "image/png", source: "data:image/png;base64,AA==", intrinsicSize: { w: 10, h: 20 } }],
|
||||
artboards: [{
|
||||
id: "artboard-1",
|
||||
name: "Board",
|
||||
bounds: { x: 0, y: 0, w: 100, h: 100 },
|
||||
backgroundColor: "transparent",
|
||||
visible: true,
|
||||
locked: false,
|
||||
layers: [{ id: "layer-1", type: "image", name: "Pixels", visible: true, locked: false, opacity: 1, assetId: "asset-1", transform: { position: { x: 0, y: 0 }, scale: { x: 1, y: 1 }, rotation: 0 } }],
|
||||
}],
|
||||
};
|
||||
}
|
||||
150
operations/project/format.ts
Normal file
150
operations/project/format.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
import type { ImageDocument } from "@core/document";
|
||||
import type { Layer } from "@core/layer";
|
||||
|
||||
export const PROJECT_FORMAT = "image-studio-project";
|
||||
export const CURRENT_PROJECT_VERSION = 1;
|
||||
|
||||
export type ProjectFile = {
|
||||
format: typeof PROJECT_FORMAT;
|
||||
version: typeof CURRENT_PROJECT_VERSION;
|
||||
savedAt: string;
|
||||
document: ImageDocument;
|
||||
};
|
||||
|
||||
export function serializeProject(document: ImageDocument, savedAt = new Date().toISOString()): string {
|
||||
assertDocumentAssetOwnership(document);
|
||||
return JSON.stringify({ format: PROJECT_FORMAT, version: CURRENT_PROJECT_VERSION, savedAt, document } satisfies ProjectFile);
|
||||
}
|
||||
|
||||
export function parseProject(source: string): ProjectFile {
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(source);
|
||||
} catch {
|
||||
throw new Error("The selected file is not valid JSON.");
|
||||
}
|
||||
|
||||
const migrated = migrateProject(value);
|
||||
assertImageDocument(migrated.document);
|
||||
assertDocumentAssetOwnership(migrated.document);
|
||||
return migrated;
|
||||
}
|
||||
|
||||
export function projectFileName(documentName: string): string {
|
||||
const base = documentName.trim().replace(/[^a-z0-9._-]+/gi, "-").replace(/^-+|-+$/g, "") || "untitled";
|
||||
return `${base}.image-studio.json`;
|
||||
}
|
||||
|
||||
function migrateProject(value: unknown): ProjectFile {
|
||||
if (!isRecord(value)) throw new Error("The project file must contain an object.");
|
||||
|
||||
if (value.format === PROJECT_FORMAT) {
|
||||
if (value.version !== CURRENT_PROJECT_VERSION) {
|
||||
throw new Error(`Unsupported project version: ${String(value.version)}.`);
|
||||
}
|
||||
if (typeof value.savedAt !== "string") throw new Error("The project is missing its save timestamp.");
|
||||
return value as ProjectFile;
|
||||
}
|
||||
|
||||
// Legacy exports stored ImageDocument directly. Loading upgrades them to v1.
|
||||
if (looksLikeDocument(value)) {
|
||||
return {
|
||||
format: PROJECT_FORMAT,
|
||||
version: CURRENT_PROJECT_VERSION,
|
||||
savedAt: new Date(0).toISOString(),
|
||||
document: value as ImageDocument,
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error("This is not an Image Studio project file.");
|
||||
}
|
||||
|
||||
function assertImageDocument(value: unknown): asserts value is ImageDocument {
|
||||
if (!isRecord(value) || typeof value.id !== "string" || typeof value.name !== "string" || typeof value.version !== "number") {
|
||||
throw new Error("The project contains an invalid document.");
|
||||
}
|
||||
if (!Array.isArray(value.artboards) || !Array.isArray(value.assets)) throw new Error("The project document is incomplete.");
|
||||
|
||||
for (const asset of value.assets) {
|
||||
if (!isRecord(asset) || typeof asset.id !== "string" || typeof asset.name !== "string" || typeof asset.mimeType !== "string" || typeof asset.source !== "string" || !isSize(asset.intrinsicSize)) {
|
||||
throw new Error("The project contains an invalid asset.");
|
||||
}
|
||||
}
|
||||
for (const artboard of value.artboards) {
|
||||
if (!isRecord(artboard) || typeof artboard.id !== "string" || typeof artboard.name !== "string" || !isRect(artboard.bounds) || !Array.isArray(artboard.layers)) {
|
||||
throw new Error("The project contains an invalid artboard.");
|
||||
}
|
||||
assertLayers(artboard.layers);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertDocumentAssetOwnership(document: ImageDocument): void {
|
||||
const assetIds = new Set<string>();
|
||||
for (const asset of document.assets) {
|
||||
if (assetIds.has(asset.id)) throw new Error(`Duplicate asset id: ${asset.id}.`);
|
||||
assetIds.add(asset.id);
|
||||
if (!isOwnedAssetSource(asset.source)) throw new Error(`Asset ${asset.name} is not embedded in the project.`);
|
||||
}
|
||||
|
||||
const layerIds = new Set<string>();
|
||||
for (const artboard of document.artboards) {
|
||||
walkLayers(artboard.layers, (layer) => {
|
||||
if (layerIds.has(layer.id)) throw new Error(`Duplicate layer id: ${layer.id}.`);
|
||||
layerIds.add(layer.id);
|
||||
if ((layer.type === "image" || layer.type === "raster") && !assetIds.has(layer.assetId)) {
|
||||
throw new Error(`Layer ${layer.name} references missing asset ${layer.assetId}.`);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function isOwnedAssetSource(source: string): boolean {
|
||||
return source.startsWith("data:");
|
||||
}
|
||||
|
||||
function assertLayers(value: unknown[]): asserts value is Layer[] {
|
||||
for (const layer of value) {
|
||||
if (!isRecord(layer) || typeof layer.id !== "string" || typeof layer.name !== "string" || typeof layer.type !== "string" || typeof layer.visible !== "boolean" || typeof layer.locked !== "boolean" || typeof layer.opacity !== "number" || !isTransform(layer.transform)) {
|
||||
throw new Error("The project contains an invalid layer.");
|
||||
}
|
||||
if (layer.type === "group") {
|
||||
if (!Array.isArray(layer.children)) throw new Error("A project group is missing its children.");
|
||||
assertLayers(layer.children);
|
||||
} else if ((layer.type === "image" || layer.type === "raster") && typeof layer.assetId !== "string") {
|
||||
throw new Error("A project layer is missing its asset reference.");
|
||||
} else if (layer.type !== "image" && layer.type !== "raster") {
|
||||
throw new Error(`Unsupported layer type: ${layer.type}.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function walkLayers(layers: Layer[], visit: (layer: Layer) => void): void {
|
||||
for (const layer of layers) {
|
||||
visit(layer);
|
||||
if (layer.type === "group") walkLayers(layer.children, visit);
|
||||
}
|
||||
}
|
||||
|
||||
function looksLikeDocument(value: Record<string, unknown>): boolean {
|
||||
return typeof value.id === "string" && Array.isArray(value.artboards) && Array.isArray(value.assets);
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isSize(value: unknown): boolean {
|
||||
return isRecord(value) && isFiniteNumber(value.w) && isFiniteNumber(value.h) && value.w >= 0 && value.h >= 0;
|
||||
}
|
||||
|
||||
function isRect(value: unknown): boolean {
|
||||
return isRecord(value) && isFiniteNumber(value.x) && isFiniteNumber(value.y) && isFiniteNumber(value.w) && isFiniteNumber(value.h);
|
||||
}
|
||||
|
||||
function isTransform(value: unknown): boolean {
|
||||
return isRecord(value) && isRecord(value.position) && isFiniteNumber(value.position.x) && isFiniteNumber(value.position.y) && isRecord(value.scale) && isFiniteNumber(value.scale.x) && isFiniteNumber(value.scale.y) && isFiniteNumber(value.rotation);
|
||||
}
|
||||
|
||||
function isFiniteNumber(value: unknown): value is number {
|
||||
return typeof value === "number" && Number.isFinite(value);
|
||||
}
|
||||
99
operations/project/lifecycle.test.ts
Normal file
99
operations/project/lifecycle.test.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { commandIds } from "@commands/ids";
|
||||
import { documentAddArtboardCommand, documentRenameArtboardCommand } from "@commands/document";
|
||||
import { projectOpenCommand } from "@commands/project";
|
||||
import { createCommandRegistry } from "@commands/registry";
|
||||
import { createInitialAppState } from "@editor/initial-state";
|
||||
import { createAppStore } from "@editor/store";
|
||||
import type { RecoveryStorage } from "@platform/projectStorage";
|
||||
import { createProjectLifecycle, RECOVERY_STORAGE_KEY } from "./lifecycle";
|
||||
import { parseProject, serializeProject } from "./format";
|
||||
|
||||
describe("project lifecycle", () => {
|
||||
test("autosaves document changes after the debounce", async () => {
|
||||
const app = createTestApp();
|
||||
const storage = memoryStorage();
|
||||
let scheduled: (() => void) | undefined;
|
||||
const lifecycle = createProjectLifecycle({
|
||||
store: app.store,
|
||||
storage,
|
||||
schedule(callback) {
|
||||
scheduled = callback;
|
||||
return 1 as unknown as ReturnType<typeof setTimeout>;
|
||||
},
|
||||
cancel() {},
|
||||
});
|
||||
|
||||
const artboardId = app.store.getState().document.artboards[0]!.id;
|
||||
app.store.dispatch(commandIds.documentRenameArtboard, { id: artboardId, name: "Recovered board" });
|
||||
expect(await storage.read(RECOVERY_STORAGE_KEY)).toBeNull();
|
||||
scheduled?.();
|
||||
await Promise.resolve();
|
||||
expect(parseProject((await storage.read(RECOVERY_STORAGE_KEY))!).document.artboards[0]!.name).toBe("Recovered board");
|
||||
lifecycle.dispose();
|
||||
});
|
||||
|
||||
test("recovers a document through the project command and clears history", async () => {
|
||||
const app = createTestApp();
|
||||
const recovered = createTestApp("Recovered").store.getState().document;
|
||||
const storage = memoryStorage([[RECOVERY_STORAGE_KEY, serializeProject(recovered)]]);
|
||||
const lifecycle = createProjectLifecycle({ store: app.store, storage });
|
||||
|
||||
expect((await lifecycle.recover())?.document.name).toBe("Recovered");
|
||||
expect(app.store.getState().document.name).toBe("Recovered");
|
||||
expect(app.store.getState().history).toEqual({ past: [], future: [] });
|
||||
lifecycle.dispose();
|
||||
});
|
||||
|
||||
test("discards corrupted recovery and clears recovery after explicit save", async () => {
|
||||
const app = createTestApp();
|
||||
const storage = memoryStorage([[RECOVERY_STORAGE_KEY, "broken"]]);
|
||||
const lifecycle = createProjectLifecycle({ store: app.store, storage });
|
||||
|
||||
expect(await lifecycle.recover()).toBeUndefined();
|
||||
expect(await storage.read(RECOVERY_STORAGE_KEY)).toBeNull();
|
||||
await storage.write(RECOVERY_STORAGE_KEY, lifecycle.snapshot());
|
||||
await lifecycle.markSaved();
|
||||
expect(await storage.read(RECOVERY_STORAGE_KEY)).toBeNull();
|
||||
lifecycle.dispose();
|
||||
});
|
||||
|
||||
test("explicit save cancels a pending recovery write", async () => {
|
||||
const app = createTestApp();
|
||||
const storage = memoryStorage();
|
||||
let scheduled: (() => void) | undefined;
|
||||
let cancelled = false;
|
||||
const lifecycle = createProjectLifecycle({
|
||||
store: app.store,
|
||||
storage,
|
||||
schedule(callback) {
|
||||
scheduled = callback;
|
||||
return 1;
|
||||
},
|
||||
cancel() { cancelled = true; },
|
||||
});
|
||||
|
||||
const artboardId = app.store.getState().document.artboards[0]!.id;
|
||||
app.store.dispatch(commandIds.documentRenameArtboard, { id: artboardId, name: "Saved" });
|
||||
await lifecycle.markSaved();
|
||||
expect(cancelled).toBe(true);
|
||||
expect(await storage.read(RECOVERY_STORAGE_KEY)).toBeNull();
|
||||
expect(scheduled).toBeDefined();
|
||||
lifecycle.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
function memoryStorage(entries: [string, string][] = []): RecoveryStorage {
|
||||
const values = new Map(entries);
|
||||
return {
|
||||
read: async (key) => values.get(key) ?? null,
|
||||
write: async (key, value) => { values.set(key, value); },
|
||||
remove: async (key) => { values.delete(key); },
|
||||
};
|
||||
}
|
||||
|
||||
function createTestApp(name = "Test") {
|
||||
const store = createAppStore(createInitialAppState(name), createCommandRegistry([projectOpenCommand, documentAddArtboardCommand, documentRenameArtboardCommand]));
|
||||
store.dispatch(commandIds.documentAddArtboard, { id: `${name}-artboard`, name: "Board", bounds: { x: 0, y: 0, w: 100, h: 100 } });
|
||||
return { store };
|
||||
}
|
||||
86
operations/project/lifecycle.ts
Normal file
86
operations/project/lifecycle.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { commandIds } from "@commands/ids";
|
||||
import type { AppStore } from "@editor/store";
|
||||
import type { ProjectFile } from "./format";
|
||||
import { parseProject, serializeProject } from "./format";
|
||||
import type { RecoveryStorage } from "@platform/projectStorage";
|
||||
|
||||
export const RECOVERY_STORAGE_KEY = "image-studio.recovery.v1";
|
||||
|
||||
type TimerHandle = number | ReturnType<typeof setTimeout>;
|
||||
|
||||
export type ProjectLifecycle = {
|
||||
recover(): Promise<ProjectFile | undefined>;
|
||||
open(source: string): Promise<ProjectFile>;
|
||||
snapshot(): string;
|
||||
markSaved(): Promise<void>;
|
||||
dispose(): void;
|
||||
};
|
||||
|
||||
export function createProjectLifecycle(options: {
|
||||
store: AppStore;
|
||||
storage: RecoveryStorage;
|
||||
debounceMs?: number;
|
||||
schedule?: (callback: () => void, delay: number) => TimerHandle;
|
||||
cancel?: (handle: TimerHandle) => void;
|
||||
}): ProjectLifecycle {
|
||||
const debounceMs = options.debounceMs ?? 750;
|
||||
const schedule = options.schedule ?? setTimeout;
|
||||
const cancel = options.cancel ?? ((handle: TimerHandle) => clearTimeout(handle));
|
||||
let observedDocument = options.store.getState().document;
|
||||
let pending: TimerHandle | undefined;
|
||||
let disposed = false;
|
||||
|
||||
const cancelPending = () => {
|
||||
if (pending === undefined) return;
|
||||
cancel(pending);
|
||||
pending = undefined;
|
||||
};
|
||||
|
||||
const unsubscribe = options.store.subscribe((state) => {
|
||||
if (state.document === observedDocument) return;
|
||||
observedDocument = state.document;
|
||||
cancelPending();
|
||||
pending = schedule(() => {
|
||||
pending = undefined;
|
||||
void options.storage.write(RECOVERY_STORAGE_KEY, serializeProject(options.store.getState().document)).catch(() => undefined);
|
||||
}, debounceMs);
|
||||
});
|
||||
|
||||
const replace = (project: ProjectFile) => {
|
||||
options.store.dispatch(commandIds.projectOpen, { document: project.document });
|
||||
cancelPending();
|
||||
observedDocument = options.store.getState().document;
|
||||
return project;
|
||||
};
|
||||
|
||||
return {
|
||||
async recover() {
|
||||
const source = await options.storage.read(RECOVERY_STORAGE_KEY);
|
||||
if (!source || disposed) return undefined;
|
||||
try {
|
||||
return replace(parseProject(source));
|
||||
} catch {
|
||||
await options.storage.remove(RECOVERY_STORAGE_KEY);
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
async open(source) {
|
||||
const project = replace(parseProject(source));
|
||||
await options.storage.remove(RECOVERY_STORAGE_KEY);
|
||||
return project;
|
||||
},
|
||||
snapshot() {
|
||||
return serializeProject(options.store.getState().document);
|
||||
},
|
||||
async markSaved() {
|
||||
cancelPending();
|
||||
observedDocument = options.store.getState().document;
|
||||
await options.storage.remove(RECOVERY_STORAGE_KEY);
|
||||
},
|
||||
dispose() {
|
||||
disposed = true;
|
||||
unsubscribe();
|
||||
cancelPending();
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user