Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

refactor(editor): extract AssetDocument<T> base from TimelineDocument — REARCH_ANIMATION P5

esengine84ce839a8506
diff --git a/desktop/src/document/AssetDocument.ts b/desktop/src/document/AssetDocument.ts
new file mode 100644
index 000000000..6214f1e62
--- /dev/null
+++ b/desktop/src/document/AssetDocument.ts
@@ -0,0 +1,94 @@
+/**
+ * @file AssetDocument.ts
+ * @brief Reactive, undoable in-memory asset document — the shared base for
+ * single-file asset editors (docs/REARCH_ANIMATION.md L4 / P5).
+ *
+ * Mirrors the scene's model-authoritative reactivity for ONE asset file: the
+ * typed in-memory asset is the source of truth, panels subscribe via
+ * `useSyncExternalStore(subscribe, getRevision)` and re-read on each bump, and
+ * {@link edit} records one undo step per mutation on the shared EditorHistory.
+ *
+ * Extracted from the Sequencer's TimelineDocument once it was proven; it carries
+ * ONLY the genuinely-generic, in-use core (asset + file binding + dirty + revision
+ * + snapshot-undo). Asset-specific state (a timeline's fps/preview-root, a
+ * tileset's source image, …) lives in the subclass — the second real consumer
+ * (the tileset editor) will reveal any further shared shape, so nothing is
+ * speculated here.
+ */
+
+import { createStore } from 'zustand/vanilla';
+import { EditorHistory } from '@/engine/EditorHistory';
+
+const clone = <T>(v: T): T =>
+ typeof structuredClone === 'function' ? structuredClone(v) : (JSON.parse(JSON.stringify(v)) as T);
+
+export class AssetDocument<T> {
+ protected _asset: T | null = null;
+ protected _filePath: string | null = null;
+ protected _dirty = false;
+ private readonly store = createStore<{ revision: number }>(() => ({ revision: 0 }));
+
+ subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);
+ getRevision = (): number => this.store.getState().revision;
+ protected bump(): void {
+ this.store.setState((s) => ({ revision: s.revision + 1 }));
+ }
+
+ get asset(): T | null {
+ return this._asset;
+ }
+ get filePath(): string | null {
+ return this._filePath;
+ }
+ get dirty(): boolean {
+ return this._dirty;
+ }
+ get isOpen(): boolean {
+ return this._asset !== null;
+ }
+
+ /** @internal Subclasses call this from their typed `open()`. */
+ protected openAsset(asset: T, filePath: string | null): void {
+ this._asset = asset;
+ this._filePath = filePath;
+ this._dirty = false;
+ this.bump();
+ }
+
+ /** Replace the asset (after a command mutation); marks dirty by default. */
+ replaceAsset(next: T, opts: { dirty?: boolean } = {}): void {
+ this._asset = next;
+ this._dirty = opts.dirty ?? true;
+ this.bump();
+ }
+
+ /** Clear the dirty flag after a successful save. */
+ markSaved(): void {
+ if (this._dirty) {
+ this._dirty = false;
+ this.bump();
+ }
+ }
+
+ /** @internal Subclasses call this from their typed `close()`. */
+ protected closeAsset(): void {
+ this._asset = null;
+ this._filePath = null;
+ this._dirty = false;
+ this.bump();
+ }
+
+ /** Apply an undoable mutation as ONE EditorHistory step (whole-asset snapshot). */
+ edit(label: string, mutate: (draft: T) => void): void {
+ const before = this._asset;
+ if (before == null) return;
+ const after = clone(before);
+ mutate(after);
+ this.replaceAsset(after);
+ EditorHistory.record(
+ label,
+ () => this.replaceAsset(after),
+ () => this.replaceAsset(before),
+ );
+ }
+}
diff --git a/desktop/src/timeline/TimelineCommands.ts b/desktop/src/timeline/TimelineCommands.ts
index a2e5ea917..bc53b5055 100644
--- a/desktop/src/timeline/TimelineCommands.ts
+++ b/desktop/src/timeline/TimelineCommands.ts
@@ -12,8 +12,8 @@
*/
import {
- serializeTimelineToJson,
TrackType,
+ serializeTimelineToJson,
type TimelineAsset,
type InterpType,
type WrapMode,
@@ -22,14 +22,10 @@ import {
} from 'esengine';
import { TimelineDocument } from './TimelineDocument';
import { findChannel, upsertKeyframe, type ChannelRef } from './timelineView';
-import { EditorHistory } from '@/engine/EditorHistory';
import { Toasts } from '@/store/Toasts';
export type { ChannelRef };
-const clone = <T>(v: T): T =>
- typeof structuredClone === 'function' ? structuredClone(v) : (JSON.parse(JSON.stringify(v)) as T);
-
// Keyframes equal within this many seconds are treated as the same key.
const EPS = 1e-4;
@@ -37,23 +33,11 @@ function sortKeys(ch: PropertyChannel): void {
ch.keyframes.sort((a, b) => a.time - b.time);
}
+// Commands mutate the open document via `TimelineDocument.edit` — the shared
+// AssetDocument snapshot-undo helper (one EditorHistory step per command).
class TimelineCommandsImpl {
- /** Apply an already-decided mutation as one undo step (whole-asset snapshot). */
- private apply(label: string, mutate: (draft: TimelineAsset) => void): void {
- const before = TimelineDocument.asset;
- if (!before) return;
- const after = clone(before);
- mutate(after);
- TimelineDocument.replaceAsset(after);
- EditorHistory.record(
- label,
- () => TimelineDocument.replaceAsset(after),
- () => TimelineDocument.replaceAsset(before),
- );
- }
-
addKey(ref: ChannelRef, time: number, value: number, interp?: InterpType): void {
- this.apply('Add Keyframe', (a) => {
+ TimelineDocument.edit('Add Keyframe', (a) => {
const ch = findChannel(a, ref);
if (ch) upsertKeyframe(ch, time, value, interp);
});
@@ -66,7 +50,7 @@ class TimelineCommandsImpl {
*/
addTrack(ref: ChannelRef, valueAtTime: number, time: number): void {
if (findChannel(TimelineDocument.asset ?? ({} as TimelineAsset), ref)) return;
- this.apply('Add Track', (a) => {
+ TimelineDocument.edit('Add Track', (a) => {
let track = a.tracks.find(
(t): t is PropertyTrack =>
t.type === TrackType.Property && t.childPath === ref.childPath && t.component === ref.component,
@@ -86,7 +70,7 @@ class TimelineCommandsImpl {
/** Remove an animatable channel; drop its property track when it goes empty. */
removeChannel(ref: ChannelRef): void {
- this.apply('Remove Track', (a) => {
+ TimelineDocument.edit('Remove Track', (a) => {
for (let ti = a.tracks.length - 1; ti >= 0; ti--) {
const t = a.tracks[ti];
if (t.type !== TrackType.Property || t.childPath !== ref.childPath || t.component !== ref.component) continue;
@@ -97,7 +81,7 @@ class TimelineCommandsImpl {
}
deleteKey(ref: ChannelRef, time: number): void {
- this.apply('Delete Keyframe', (a) => {
+ TimelineDocument.edit('Delete Keyframe', (a) => {
const ch = findChannel(a, ref);
if (!ch) return;
const i = ch.keyframes.findIndex((k) => Math.abs(k.time - time) < EPS);
@@ -106,14 +90,14 @@ class TimelineCommandsImpl {
}
setKeyValue(ref: ChannelRef, time: number, value: number): void {
- this.apply('Edit Keyframe', (a) => {
+ TimelineDocument.edit('Edit Keyframe', (a) => {
const k = findChannel(a, ref)?.keyframes.find((x) => Math.abs(x.time - time) < EPS);
if (k) k.value = value;
});
}
setKeyInterp(ref: ChannelRef, time: number, interp: InterpType): void {
- this.apply('Set Interpolation', (a) => {
+ TimelineDocument.edit('Set Interpolation', (a) => {
const k = findChannel(a, ref)?.keyframes.find((x) => Math.abs(x.time - time) < EPS);
if (k) k.interpolation = interp;
});
@@ -121,7 +105,7 @@ class TimelineCommandsImpl {
/** Move a key in time AND set its value in one step (curve-view 2D drag). */
editKey(ref: ChannelRef, fromTime: number, toTime: number, value: number): void {
- this.apply('Edit Keyframe', (a) => {
+ TimelineDocument.edit('Edit Keyframe', (a) => {
const ch = findChannel(a, ref);
const k = ch?.keyframes.find((x) => Math.abs(x.time - fromTime) < EPS);
if (!ch || !k) return;
@@ -137,7 +121,7 @@ class TimelineCommandsImpl {
/** Set a key's in/out tangents (and switch it to Hermite) — curve handle drag. */
setKeyTangents(ref: ChannelRef, time: number, inTangent: number, outTangent: number): void {
- this.apply('Edit Tangents', (a) => {
+ TimelineDocument.edit('Edit Tangents', (a) => {
const k = findChannel(a, ref)?.keyframes.find((x) => Math.abs(x.time - time) < EPS);
if (!k) return;
k.inTangent = inTangent;
@@ -149,7 +133,7 @@ class TimelineCommandsImpl {
/** Move a keyframe in time (drag). A key already at `toTime` is overwritten. */
moveKey(ref: ChannelRef, fromTime: number, toTime: number): void {
if (Math.abs(fromTime - toTime) < EPS) return;
- this.apply('Move Keyframe', (a) => {
+ TimelineDocument.edit('Move Keyframe', (a) => {
const ch = findChannel(a, ref);
if (!ch) return;
const k = ch.keyframes.find((x) => Math.abs(x.time - fromTime) < EPS);
@@ -162,13 +146,13 @@ class TimelineCommandsImpl {
}
setDuration(seconds: number): void {
- this.apply('Set Duration', (a) => {
+ TimelineDocument.edit('Set Duration', (a) => {
a.duration = Math.max(0, seconds);
});
}
setWrapMode(mode: WrapMode): void {
- this.apply('Set Wrap Mode', (a) => {
+ TimelineDocument.edit('Set Wrap Mode', (a) => {
a.wrapMode = mode;
});
}
diff --git a/desktop/src/timeline/TimelineDocument.ts b/desktop/src/timeline/TimelineDocument.ts
index 1b4556492..b414329d6 100644
--- a/desktop/src/timeline/TimelineDocument.ts
+++ b/desktop/src/timeline/TimelineDocument.ts
@@ -1,19 +1,16 @@
/**
* @file TimelineDocument.ts
- * @brief The open .estimeline as a reactive editor document — the first asset
- * document session (docs/REARCH_ANIMATION.md L4).
+ * @brief The open .estimeline as a reactive editor document — the first
+ * {@link AssetDocument} (docs/REARCH_ANIMATION.md L4 / P5).
*
- * Mirrors the scene's model-authoritative reactivity (SceneStore): the in-memory
- * TimelineAsset is the source of truth, panels subscribe via useSyncExternalStore
- * and re-read on each revision bump. Editing commands (P2) mutate the asset and
- * bump; for P1 the document just holds an opened clip + its preview binding.
- *
- * `fps` is editor display metadata (the asset stores time in seconds); the design
- * shows a frame ruler, so the panel converts seconds ↔ frames via this fps.
+ * The generic reactive + snapshot-undo core lives in AssetDocument; this adds the
+ * timeline-specific state: `fps` (editor display metadata — the asset stores time
+ * in seconds, the panel renders a frame ruler) and `rootEntity` (which scene
+ * entity the timeline previews against).
*/
-import { createStore } from 'zustand/vanilla';
import { parseTimelineAsset, type TimelineAsset } from 'esengine';
+import { AssetDocument } from '@/document/AssetDocument';
import type { EntityId } from '@/types';
export interface TimelineDocMeta {
@@ -26,10 +23,6 @@ export interface TimelineDocMeta {
// in the asset, which is frame-rate-independent (keyframe times are seconds).
const DEFAULT_FPS = 12;
-function emptyMeta(): TimelineDocMeta {
- return { filePath: null, fps: DEFAULT_FPS, dirty: false };
-}
-
export interface OpenParams {
asset: TimelineAsset;
filePath?: string | null;
@@ -37,41 +30,22 @@ export interface OpenParams {
rootEntity?: EntityId | null;
}
-export class TimelineDocumentImpl {
- private _asset: TimelineAsset | null = null;
- private _meta: TimelineDocMeta = emptyMeta();
+export class TimelineDocumentImpl extends AssetDocument<TimelineAsset> {
+ private _fps = DEFAULT_FPS;
private _root: EntityId | null = null;
- private readonly store = createStore<{ revision: number }>(() => ({ revision: 0 }));
-
- subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);
- getRevision = (): number => this.store.getState().revision;
- private bump() {
- this.store.setState((s) => ({ revision: s.revision + 1 }));
- }
- get asset(): TimelineAsset | null {
- return this._asset;
- }
get meta(): TimelineDocMeta {
- return this._meta;
+ return { filePath: this.filePath, fps: this._fps, dirty: this.dirty };
}
get rootEntity(): EntityId | null {
return this._root;
}
- get isOpen(): boolean {
- return this._asset !== null;
- }
/** Open an already-parsed timeline asset, optionally bound to a preview entity. */
open(params: OpenParams): void {
- this._asset = params.asset;
- this._meta = {
- filePath: params.filePath ?? null,
- fps: params.fps ?? DEFAULT_FPS,
- dirty: false,
- };
+ this._fps = params.fps ?? DEFAULT_FPS;
this._root = params.rootEntity ?? null;
- this.bump();
+ this.openAsset(params.asset, params.filePath ?? null);
}
/** Open from raw .estimeline JSON (parsed + migrated by the SDK loader). */
@@ -88,33 +62,15 @@ export class TimelineDocumentImpl {
/** Set the editor display frame rate (view metadata; not persisted in the asset). */
setFps(fps: number): void {
const next = Math.max(1, Math.round(fps));
- if (next === this._meta.fps) return;
- this._meta = { ...this._meta, fps: next };
- this.bump();
- }
-
- /** Clear the dirty flag after a successful save. */
- markSaved(): void {
- if (!this._meta.dirty) return;
- this._meta = { ...this._meta, dirty: false };
- this.bump();
- }
-
- /**
- * Replace the asset after a command mutation (P2). Kept distinct from open() so
- * the file binding / fps survive an edit; marks the document dirty by default.
- */
- replaceAsset(next: TimelineAsset, opts: { dirty?: boolean } = {}): void {
- this._asset = next;
- this._meta = { ...this._meta, dirty: opts.dirty ?? true };
+ if (next === this._fps) return;
+ this._fps = next;
this.bump();
}
close(): void {
- this._asset = null;
- this._meta = emptyMeta();
+ this._fps = DEFAULT_FPS;
this._root = null;
- this.bump();
+ this.closeAsset();
}
}
diff --git a/desktop/tests/asset-document.test.ts b/desktop/tests/asset-document.test.ts
new file mode 100644
index 000000000..026f389f4
--- /dev/null
+++ b/desktop/tests/asset-document.test.ts
@@ -0,0 +1,64 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { AssetDocument } from '@/document/AssetDocument';
+import { EditorHistory } from '@/engine/EditorHistory';
+
+interface Doc { n: number }
+
+class TestDoc extends AssetDocument<Doc> {
+ open(asset: Doc, filePath: string | null = 'a.json') {
+ this.openAsset(asset, filePath);
+ }
+}
+
+describe('AssetDocument (generic reactive + undoable base)', () => {
+ let doc: TestDoc;
+ beforeEach(() => {
+ EditorHistory.clear();
+ doc = new TestDoc();
+ });
+
+ it('opens clean and tracks dirty on edit', () => {
+ doc.open({ n: 1 });
+ expect(doc.isOpen).toBe(true);
+ expect(doc.asset).toEqual({ n: 1 });
+ expect(doc.dirty).toBe(false);
+
+ doc.edit('inc', (d) => { d.n += 1; });
+ expect(doc.asset).toEqual({ n: 2 });
+ expect(doc.dirty).toBe(true);
+ });
+
+ it('edit is one undoable step (snapshot)', () => {
+ doc.open({ n: 1 });
+ doc.edit('inc', (d) => { d.n = 10; });
+ expect(doc.asset).toEqual({ n: 10 });
+ EditorHistory.undo();
+ expect(doc.asset).toEqual({ n: 1 });
+ EditorHistory.redo();
+ expect(doc.asset).toEqual({ n: 10 });
+ });
+
+ it('bumps the revision so subscribers re-read', () => {
+ let bumps = 0;
+ doc.subscribe(() => { bumps += 1; });
+ const r0 = doc.getRevision();
+ doc.open({ n: 1 });
+ doc.edit('inc', (d) => { d.n += 1; });
+ expect(doc.getRevision()).toBeGreaterThan(r0);
+ expect(bumps).toBeGreaterThanOrEqual(2); // open + edit
+ });
+
+ it('markSaved clears dirty', () => {
+ doc.open({ n: 1 });
+ doc.edit('inc', (d) => { d.n += 1; });
+ expect(doc.dirty).toBe(true);
+ doc.markSaved();
+ expect(doc.dirty).toBe(false);
+ });
+
+ it('edit is a no-op when nothing is open', () => {
+ doc.edit('inc', (d) => { d.n += 1; }); // no asset → ignored
+ expect(doc.isOpen).toBe(false);
+ expect(EditorHistory.canUndo()).toBe(false);
+ });
+});