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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): real unsaved-changes model + save prompts (dirty-state)
esengineadc80640e2f2
diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex aee904d7a..eb8a226a2 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -152,8 +152,35 @@ function createWindow() {// a real origin. handleApp serves dist/.win.loadURL(`${APP_ORIGIN}/index.html`);}++ // Unsaved-changes quit guard: prompt before closing a window with a dirty scene.+ // `sceneDirty` is pushed from the renderer (app:dirty); `quitting` lets the chosen+ // action close past this handler.+ win.on('close', (e) => {+ if (quitting || !sceneDirty || !win) return;+ e.preventDefault();+ const choice = dialog.showMessageBoxSync(win, {+ type: 'warning',+ buttons: ['Save', "Don't Save", 'Cancel'],+ defaultId: 0,+ cancelId: 2,+ message: 'Save changes before closing?',+ detail: 'Your scene has unsaved changes that will be lost otherwise.',+ });+ if (choice === 2) return; // Cancel → keep the window open+ if (choice === 1) { quitting = true; win.destroy(); return; } // Don't Save+ // Save → ask the renderer to write the scene, then close when it confirms.+ ipcMain.once('app:quitConfirmed', () => { quitting = true; win?.destroy(); });+ win.webContents.send('app:saveBeforeQuit');+ });}+// The renderer's current unsaved-changes state, mirrored for the close guard above.+let sceneDirty = false;+// Set once the user has chosen to close (Save/Don't Save), so win.destroy() is allowed through.+let quitting = false;+ipcMain.on('app:dirty', (_e, dirty: boolean) => { sceneDirty = !!dirty; });+// — Minimal IPC surface (expanded as the editor grows) —ipcMain.handle('app:version', () => app.getVersion());ipcMain.handle('app:platform', () => process.platform);diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex d567acc3e..9004d85f1 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -18,6 +18,20 @@ const api = {// Surfaces engine lifecycle in the main-process log (useful for headless checks).reportEngineStatus: (status: string): void => ipcRenderer.send('engine:status', status),+ // — App lifecycle: the unsaved-changes quit guard. The renderer pushes its dirty+ // state so main can prompt (Save / Don't Save / Cancel) on window close; on Save+ // main asks the renderer to save, which confirms back when done. —+ app: {+ setDirty: (dirty: boolean): void => ipcRenderer.send('app:dirty', dirty),+ /** Run `cb` (save the scene) when main requests a save-before-quit, then signal done. */+ onSaveBeforeQuit: (cb: () => Promise<void> | void): void => {+ ipcRenderer.removeAllListeners('app:saveBeforeQuit');+ ipcRenderer.on('app:saveBeforeQuit', () => {+ void Promise.resolve(cb()).finally(() => ipcRenderer.send('app:quitConfirmed'));+ });+ },+ },+// — Project / workspace (RC12 §E7) —project: {/** Show a directory picker and open the chosen Estella project (null if cancelled). */diff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex 2d5261e9b..418fe9d90 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -19,6 +19,7 @@ import { PlayInspect } from '@/engine/PlayInspect';import { TimelinePreview } from '@/engine/TimelinePreview';import { TimelineRecorder } from '@/timeline/TimelineRecorder';import { ProjectStore } from '@/project/ProjectStore';+import { EditorHistory } from '@/engine/EditorHistory';import { dockApi } from '@/layout/dockApi';import { Toasts } from '@/store/Toasts';@@ -57,6 +58,24 @@ export function App() {TimelineRecorder.attach();}, []);+ // Mirror unsaved-changes state to main for the window-close quit guard, and run+ // the save when main requests a save-before-quit.+ useEffect(() => {+ const bridge = window.estella?.app;+ if (!bridge) return;+ const push = () => bridge.setDirty(EditorHistory.isDirty());+ push();+ const unsub = EditorHistory.subscribe(push);+ bridge.onSaveBeforeQuit(async () => {+ try {+ await ProjectStore.save();+ } catch {+ await ProjectStore.saveAsViaDialog();+ }+ });+ return unsub;+ }, []);+// Play runs in an ISOLATED realm (the Game panel's iframe = the shipping// runtime), NOT by flipping the main edit World — so gameplay can never dirty// the scene and the Viewport stays a live Scene view.diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsindex 8f7a8c480..6f5c4082d 100644--- a/desktop/src/commands/editorCommands.ts+++ b/desktop/src/commands/editorCommands.ts@@ -10,6 +10,7 @@*/import { commands } from './registry';import { ProjectStore } from '@/project/ProjectStore';+import { confirmDiscard } from '@/project/discardGuard';import { EditorHistory } from '@/engine/EditorHistory';import { SceneCommands } from '@/engine/SceneCommands';import { SceneModel } from '@/engine/SceneModel';@@ -31,8 +32,7 @@ commands.register({keybinding: 'mod+n',isEnabled: () => !!ProjectStore.getSnapshot(),run: () => {- // Discard guard: history is the editor's unsaved-changes proxy (no dirty flag).- if (EditorHistory.canUndo() && !window.confirm('New scene? Unsaved changes will be lost.')) return;+ if (!confirmDiscard('Creating a new scene will discard them')) return;void ProjectStore.newScene().then(() => sel().select(null));},});@@ -48,7 +48,12 @@ commands.register({label: 'Save Scene',category: 'File',keybinding: 'mod+s',- isEnabled: () => !!ProjectStore.getSnapshot(),+ // Enabled while there are unsaved edits, or the scene is untitled (Save → Save As+ // to give it a path on disk for the first time).+ isEnabled: () => {+ const p = ProjectStore.getSnapshot();+ return !!p && (EditorHistory.isDirty() || !p.currentScene);+ },run: () => void ProjectStore.save().catch(() => ProjectStore.saveAsViaDialog()),});commands.register({@@ -71,7 +76,10 @@ commands.register({label: 'Close Project',category: 'File',isEnabled: () => !!ProjectStore.getSnapshot(),- run: () => editor().openLauncher(),+ run: () => {+ if (!confirmDiscard('Closing the project will discard them')) return;+ editor().openLauncher();+ },});// — Edit / history —diff --git a/desktop/src/engine/EditorHistory.ts b/desktop/src/engine/EditorHistory.tsindex 24b288860..f017a7270 100644--- a/desktop/src/engine/EditorHistory.ts+++ b/desktop/src/engine/EditorHistory.ts@@ -11,15 +11,39 @@ import { TransactionManager } from 'esengine';* before/after and calls {@link record} so the pair becomes undoable without* re-running the forward closure. Panels subscribe for undo/redo availability.*/+const HISTORY_LIMIT = 200;+export class EditorHistoryImpl {- private readonly tm = new TransactionManager({ historyLimit: 200 });+ private readonly tm = new TransactionManager({ historyLimit: HISTORY_LIMIT });private readonly store = createStore<{ version: number }>(() => ({ version: 0 }));+ // Dirty tracking. `version` bumps on every op (drives subscriptions) but is+ // monotonic, so it can't tell "back at the saved state". Instead each committed+ // edit gets a unique id pushed onto a mirror of the undo stack; `savedHead` is the+ // head id at the last save. dirty ⇔ head id ≠ savedHead — so undoing back to the+ // saved point clears the star (UE semantics), and a fresh edit at the same depth+ // does NOT (its id is new). Capped to the TM history limit so it can't grow+ // unbounded; an evicted saved point just stays dirty (you can't reach it anyway).+ private undoIds: number[] = [];+ private redoIds: number[] = [];+ private seq = 0;+ private savedHead: number | null = null;++ private head(): number | null {+ return this.undoIds.length ? this.undoIds[this.undoIds.length - 1] : null;+ }+ private pushEdit() {+ this.undoIds.push(++this.seq);+ if (this.undoIds.length > HISTORY_LIMIT) this.undoIds.shift();+ this.redoIds.length = 0;+ }+/** Register an already-applied mutation as one undo step (forward NOT run). */record(label: string, forward: () => void, reverse: () => void) {const tx = this.tm.begin(label);tx.addDeferred({ forward, reverse });this.tm.commit(tx);+ this.pushEdit();this.bump();}@@ -28,6 +52,7 @@ export class EditorHistoryImpl {const tx = this.tm.begin(label);tx.add({ forward, reverse });this.tm.commit(tx);+ this.pushEdit();this.bump();}@@ -38,14 +63,23 @@ export class EditorHistoryImpl {const tx = this.tm.begin(label);for (const op of ops) tx.addDeferred(op);this.tm.commit(tx);+ this.pushEdit();this.bump();}undo() {- if (this.tm.undo()) this.bump();+ if (this.tm.undo()) {+ const id = this.undoIds.pop();+ if (id !== undefined) this.redoIds.push(id);+ this.bump();+ }}redo() {- if (this.tm.redo()) this.bump();+ if (this.tm.redo()) {+ const id = this.redoIds.pop();+ if (id !== undefined) this.undoIds.push(id);+ this.bump();+ }}canUndo() {return this.tm.canUndo();@@ -61,8 +95,20 @@ export class EditorHistoryImpl {}clear() {this.tm.clear();+ // A cleared history is the new clean baseline (scene load / new scene).+ this.undoIds.length = 0;+ this.redoIds.length = 0;+ this.savedHead = null;+ this.bump();+ }++ /** Mark the current state as saved — the dirty star clears until the next edit. */+ markSaved() {+ this.savedHead = this.head();this.bump();}+ /** True when the document has unsaved edits relative to the last save / load. */+ isDirty = (): boolean => this.head() !== this.savedHead;private bump() {this.store.setState((s) => ({ version: s.version + 1 }));diff --git a/desktop/src/layout/MenuBar.tsx b/desktop/src/layout/MenuBar.tsxindex 87f4883ca..929dac98d 100644--- a/desktop/src/layout/MenuBar.tsx+++ b/desktop/src/layout/MenuBar.tsx@@ -7,6 +7,7 @@import { useEffect, useRef, useState, useSyncExternalStore } from 'react';import { useEditorStore } from '@/store/editorStore';import { ProjectStore } from '@/project/ProjectStore';+import { EditorHistory } from '@/engine/EditorHistory';import { Toasts } from '@/store/Toasts';import { MenuItems, type MenuItem } from '@/components/Menu';import { commands, formatKeybinding } from '@/commands';@@ -39,6 +40,8 @@ export function MenuBar() {// are rebuilt from the command registry each time a menu opens (a re-render),// so their enabled / checked state reads fresh from the domain stores then.const project = useSyncExternalStore(ProjectStore.subscribe, ProjectStore.getSnapshot);+ // Unsaved-changes star next to the scene name (UE's modified-document indicator).+ const dirty = useSyncExternalStore(EditorHistory.subscribe, EditorHistory.isDirty);// Build a menu item from a registered command — one source for label, shortcut// hint, action, enablement, and checked state.@@ -182,7 +185,13 @@ export function MenuBar() {<span className="sep">/</span><span className="mono">{project.currentScene.split('/').pop()}</span></>- ) : null}+ ) : (+ <>+ <span className="sep">/</span>+ <span className="mono">untitled</span>+ </>+ )}+ {dirty && <span className="dirty" title="Unsaved changes">●</span>}</div>) : null}</div>diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex 4ae0535ad..fc93060cd 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -42,6 +42,7 @@ import { PlayInspect } from '@/engine/PlayInspect';import type { SceneData } from 'esengine';import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel, hexToRgba } from '@/engine/schema';import { ProjectStore } from '@/project/ProjectStore';+import { confirmDiscard } from '@/project/discardGuard';import { MaterialDocument } from '@/material/MaterialDocument';import {isMaterialAsset,@@ -1509,7 +1510,13 @@ function AssetInspector({ path }: { path: string }) {</div><div className="cb-act">{type === 'scene' && (- <button type="button" className="primary" onClick={() => void ProjectStore.openScene(path)}>+ <button+ type="button"+ className="primary"+ onClick={() => {+ if (confirmDiscard(`Opening ${baseName(path)} will discard them`)) void ProjectStore.openScene(path);+ }}+ ><FolderOpen size={13} strokeWidth={1.85} /> Open Scene</button>)}diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex ab121c23e..75935bd88 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -777,6 +777,7 @@ class ProjectStoreImpl {if (!st || !st.currentScene) throw new Error('no scene to save');await this.writeScene(st.currentScene, await this.serializeCurrent());await this.persistLastScene(st.currentScene);+ EditorHistory.markSaved();Toasts.push(`Saved ${st.currentScene.split('/').pop()}`, 'success');}@@ -785,6 +786,7 @@ class ProjectStoreImpl {if (!this.state) throw new Error('no project open');await this.writeScene(relPath, await this.serializeCurrent());await this.persistLastScene(relPath);+ EditorHistory.markSaved();Toasts.push(`Saved ${relPath.split('/').pop()}`, 'success');}diff --git a/desktop/src/project/assetOpen.ts b/desktop/src/project/assetOpen.tsindex 0403ba800..76d993b61 100644--- a/desktop/src/project/assetOpen.ts+++ b/desktop/src/project/assetOpen.ts@@ -9,7 +9,7 @@*/import type { AssetType } from '@/types';import { ProjectStore } from './ProjectStore';-import { EditorHistory } from '@/engine/EditorHistory';+import { confirmDiscard } from './discardGuard';import { openAnimationClip } from '@/timeline/openClip';import { openTileset } from '@/tileset/openTileset';import { openMaterial } from '@/material/openMaterial';@@ -18,8 +18,7 @@ import { openMaterialGraph } from '@/material/openMaterialGraph';/** Open action per asset type; types absent here aren't double-click-openable. */export const ASSET_OPEN: Partial<Record<AssetType, (path: string, name: string) => void>> = {scene: (path, name) => {- // History is cleared on open, so canUndo ≈ "edited this session" — warn first.- if (EditorHistory.canUndo() && !window.confirm(`Open ${name}? Unsaved changes will be lost.`)) return;+ if (!confirmDiscard(`Opening ${name} will discard them`)) return;void ProjectStore.openScene(path);},animation: (path) => void openAnimationClip(path),diff --git a/desktop/src/project/discardGuard.ts b/desktop/src/project/discardGuard.tsnew file mode 100644index 000000000..6158bd382--- /dev/null+++ b/desktop/src/project/discardGuard.ts@@ -0,0 +1,21 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file discardGuard.ts+ * @brief The single unsaved-changes gate. Any action that would discard the+ * current scene (new / open / close / switch) calls this first, so the+ * prompt logic lives in one place and reflects the REAL dirty state+ * (EditorHistory.isDirty), not the old `canUndo` proxy that stayed true+ * after a save and false-warned.+ */+import { EditorHistory } from '@/engine/EditorHistory';++/**+ * Returns true if it's safe to proceed with a destructive document action: when+ * there are no unsaved changes, or the user confirms discarding them. `what`+ * names the consequence, e.g. "Creating a new scene will discard them".+ */+export function confirmDiscard(what = 'They will be lost'): boolean {+ if (!EditorHistory.isDirty()) return true;+ return window.confirm(`You have unsaved changes. ${what}. Continue?`);+}diff --git a/desktop/src/theme/chrome.css b/desktop/src/theme/chrome.cssindex 80657fda4..399a27ea1 100644--- a/desktop/src/theme/chrome.css+++ b/desktop/src/theme/chrome.css@@ -41,6 +41,7 @@.menubar-title { font-size: var(--fs-xs); color: var(--text-mute); display: flex; align-items: center; gap: 6px; padding-right: 12px; }.menubar-title strong { color: var(--text-dim); font-weight: 600; }.menubar-title .sep { opacity: 0.5; }+.menubar-title .dirty { color: var(--sel); font-size: 0.7em; line-height: 1; margin-left: -2px; }/* ── Toolbar (modes left · play center · actions right) ── */.toolbar {diff --git a/desktop/tests/editor-history-dirty.test.ts b/desktop/tests/editor-history-dirty.test.tsnew file mode 100644index 000000000..beaaf7e9c--- /dev/null+++ b/desktop/tests/editor-history-dirty.test.ts@@ -0,0 +1,70 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file EditorHistory dirty tracking — unsaved-changes state via the edit-id+ * mirror of the undo stack. Undoing back to the saved point clears dirty+ * (UE semantics); a fresh edit at the same depth does NOT (new id). Pure TS.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { EditorHistoryImpl } from '@/engine/EditorHistory';++const noop = () => {};+const edit = (h: EditorHistoryImpl, label = 'Edit') => h.record(label, noop, noop);++describe('EditorHistory dirty', () => {+ let h: EditorHistoryImpl;+ beforeEach(() => {+ h = new EditorHistoryImpl();+ });++ it('starts clean', () => {+ expect(h.isDirty()).toBe(false);+ });++ it('an edit makes it dirty; markSaved clears it', () => {+ edit(h);+ expect(h.isDirty()).toBe(true);+ h.markSaved();+ expect(h.isDirty()).toBe(false);+ });++ it('undoing back to the saved point clears dirty; redo re-dirties', () => {+ edit(h);+ h.markSaved(); // saved at depth 1+ edit(h); // depth 2 → dirty+ expect(h.isDirty()).toBe(true);+ h.undo(); // back to depth 1 = saved+ expect(h.isDirty()).toBe(false);+ h.redo(); // forward again → dirty+ expect(h.isDirty()).toBe(true);+ });++ it('an edit after undo is dirty even at the saved DEPTH (id differs, not depth)', () => {+ edit(h); // id 1+ edit(h); // id 2+ h.markSaved(); // saved head = id 2 (depth 2)+ h.undo(); // depth 1, head = id 1 → dirty+ expect(h.isDirty()).toBe(true);+ edit(h); // depth 2 again, but head = id 3 ≠ saved id 2+ expect(h.isDirty()).toBe(true); // a naive depth check would wrongly say clean+ });++ it('clear() resets the clean baseline (scene load / new scene)', () => {+ edit(h);+ expect(h.isDirty()).toBe(true);+ h.clear();+ expect(h.isDirty()).toBe(false);+ });++ it('saving, editing, then undoing to the save is clean again', () => {+ edit(h);+ edit(h);+ h.markSaved();+ edit(h);+ edit(h);+ expect(h.isDirty()).toBe(true);+ h.undo();+ h.undo();+ expect(h.isDirty()).toBe(false); // back at the saved head+ });+});