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
fix(editor): save/create UX — data-loss guard, context Ctrl+S, discoverable create
esenginef8d08806e811
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsindex 7b4d75ed2..12e79427f 100644--- a/desktop/src/commands/editorCommands.ts+++ b/desktop/src/commands/editorCommands.ts@@ -18,6 +18,8 @@ import { hasEntityClipboard } from '@/engine/entityClipboard';import { ViewportController } from '@/engine/ViewportController';import { applyFxPreview } from '@/engine/fxPreview';import { dockApi } from '@/layout/dockApi';+import { panelDirtySource } from '@/layout/panelDirty';+import { DirtyRegistry } from '@/document/DirtyRegistry';import { EDITOR_MODES } from '@/mode/editorModes';import { activeMode } from '@/mode/activeMode';import { useEditorMode } from '@/store/editorModeStore';@@ -58,13 +60,25 @@ commands.register({label: t('cmd.project.save'),category: t('cat.file'),keybinding: 'mod+s',- // 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).+ // Context-aware "save what you're looking at": if an asset editor panel is active,+ // Ctrl+S targets THAT document (else it was a scene-only no-op or, worse, it saved+ // the scene instead). Otherwise save the scene — enabled while it has unsaved edits+ // or is untitled (Save → Save As to give it a path the first time).isEnabled: () => {const p = ProjectStore.getSnapshot();- return !!p && (EditorHistory.isDirty() || !p.currentScene);+ if (!p) return false;+ const active = panelDirtySource(dockApi.activePanelId() ?? '');+ if (active.docId) return active.isDirty();+ return EditorHistory.isDirty() || !p.currentScene;+ },+ run: () => {+ const active = panelDirtySource(dockApi.activePanelId() ?? '');+ if (active.docId) {+ void DirtyRegistry.saveDoc(active.docId);+ return;+ }+ void ProjectStore.save().catch(() => ProjectStore.saveAsViaDialog());},- run: () => void ProjectStore.save().catch(() => ProjectStore.saveAsViaDialog()),});commands.register({id: 'project.saveAs',diff --git a/desktop/src/document/DirtyRegistry.ts b/desktop/src/document/DirtyRegistry.tsindex 9e4b681b6..cf83f09af 100644--- a/desktop/src/document/DirtyRegistry.ts+++ b/desktop/src/document/DirtyRegistry.ts@@ -62,6 +62,15 @@ class DirtyRegistryImpl {return false;}+ /** Save ONE registered document by id if it's dirty; returns whether it saved.+ * Powers context-aware Save (the active asset editor), vs saveAll (quit). */+ async saveDoc(id: string): Promise<boolean> {+ const entry = this.docs.get(id);+ if (!entry || !entry.doc.isDirty()) return false;+ await entry.doc.save();+ return true;+ }+/** Save every dirty document (sequentially; a failure aborts and rethrows so* the caller never reports a clean quit over lost edits). */async saveAll(): Promise<void> {diff --git a/desktop/src/document/dirtyDocs.ts b/desktop/src/document/dirtyDocs.tsindex 15a77b7aa..837b401fa 100644--- a/desktop/src/document/dirtyDocs.ts+++ b/desktop/src/document/dirtyDocs.ts@@ -17,6 +17,7 @@ import { AnimClipCommands } from '@/flipbook/AnimClipCommands';import { TimelineDocument } from '@/timeline/TimelineDocument';import { TimelineCommands } from '@/timeline/TimelineCommands';import { FsmGraphDocument } from '@/fsm/FsmGraphDocument';+import { AnimatorGraphDocument } from '@/animator/AnimatorGraphDocument';import { BtDocument } from '@/bt/BtDocument';import { MaterialDocument } from '@/material/MaterialDocument';import { MaterialGraphDocument } from '@/material/MaterialGraphDocument';@@ -64,6 +65,7 @@ function jsonDoc<T>(id: string, doc: AssetDocument<T>): void {jsonDoc('bt', BtDocument);jsonDoc('fsm', FsmGraphDocument);+jsonDoc('animator', AnimatorGraphDocument);jsonDoc('material', MaterialDocument);// Documents with a richer save (custom serializer / compiled sibling output)diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex aa414711a..6ab944e46 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -209,6 +209,15 @@ export class SceneCommandsImpl {return c ? (c.data as Record<string, unknown>)[key] : undefined;}+ /** Whether re-parenting every id in `ids` under `target` is valid — false when+ * `target` is one of them or a descendant of one (which {@link reparentEntities}+ * silently drops). The Outliner drag-over calls this to REJECT an invalid drop+ * (no move cursor, no drop indicator) instead of signalling a phantom success. */+ canReparent(ids: readonly EntityId[], target: EntityId | null): boolean {+ if (target == null) return true;+ return !ids.some((id) => id === target || this.isModelAncestor(target, id));+ }+// True if walking up from `nodeSrc` reaches `ancestorSrc` — rejects re-parenting// an entity under its own descendant (a cycle). Reads the model hierarchy.private isModelAncestor(nodeSrc: number, ancestorSrc: number): boolean {@@ -599,11 +608,11 @@ export class SceneCommandsImpl {// — Undoable entity lifecycle (model ops; the Reconciler re-spawns/-despawns) —/** Spawn a new empty entity (with a Transform). Returns its source id. */- addEntity(): EntityId | null {+ addEntity(parent: EntityId | null = null): EntityId | null {if (!this.model.current) return null;const sourceId = this.model.addEntity('Entity', [{ type: 'Transform', data: structuredClone(DEFAULT_TRANSFORM) } as SceneComponent,- ]);+ ], parent);let record: SceneEntity | undefined;this.history.record('Add Entity',diff --git a/desktop/src/i18n/messages/content.ts b/desktop/src/i18n/messages/content.tsindex a3c8bdb88..831efa7d5 100644--- a/desktop/src/i18n/messages/content.ts+++ b/desktop/src/i18n/messages/content.ts@@ -22,6 +22,8 @@ export const contentMessages = defineMessages({'cb.listView': { en: 'List view', zh: '列表视图' },'cb.importAssets': { en: 'Import assets', zh: '导入资产' },'cb.import': { en: 'Import', zh: '导入' },+ 'cb.newAsset': { en: 'New', zh: '新建' },+ 'cb.newAssetTip': { en: 'Create a new asset in this folder', zh: '在当前文件夹新建资产' },'cb.thumbSize': { en: 'Thumbnail size', zh: '缩略图大小' },// — Type filter chips —diff --git a/desktop/src/i18n/messages/outliner.ts b/desktop/src/i18n/messages/outliner.tsindex 4a3110c1c..e4d4d940e 100644--- a/desktop/src/i18n/messages/outliner.ts+++ b/desktop/src/i18n/messages/outliner.ts@@ -20,7 +20,7 @@ export const outlinerMessages = defineMessages({'out.sortName': { en: 'Name', zh: '名称' },'out.sortType': { en: 'Type', zh: '类型' },'out.newFolderTip': { en: 'New folder', zh: '新建文件夹' },- 'out.addEntityTip': { en: 'Add entity', zh: '添加实体' },+ 'out.addEntityTip': { en: 'Create entity…', zh: '创建实体…' },// — Column header strip + show/hide-columns menu —'out.columnsTip': { en: 'Right-click to show/hide columns', zh: '右键点击以显示/隐藏列' },@@ -39,6 +39,8 @@ export const outlinerMessages = defineMessages({// — Context menus (empty space / folder / entity) —'out.addEntity': { en: 'Add Entity', zh: '添加实体' },'out.createTemplate': { en: 'Create…', zh: '创建…' },+ 'out.addChild': { en: 'Add Child', zh: '添加子实体' },+ 'out.createChild': { en: 'Create Child…', zh: '创建子实体…' },'out.newFolder': { en: 'New Folder', zh: '新建文件夹' },'out.expandAll': { en: 'Expand All', zh: '全部展开' },'out.collapseAll': { en: 'Collapse All', zh: '全部折叠' },diff --git a/desktop/src/layout/dockApi.ts b/desktop/src/layout/dockApi.tsindex 4b7113e81..61e189c13 100644--- a/desktop/src/layout/dockApi.ts+++ b/desktop/src/layout/dockApi.ts@@ -62,6 +62,11 @@ export const dockApi = {set(next: DockviewApi | null) {api = next;},+ /** The id of the active (focused) dock panel, or null. Drives context-aware+ * Save: Ctrl+S targets the asset editor you're looking at, else the scene. */+ activePanelId(): string | null {+ return api?.activePanel?.id ?? null;+ },/** Bring a docked panel to the front of its group (no-op if absent). */reveal(id: string) {api?.getPanel(id)?.api.setActive();diff --git a/desktop/src/layout/panelDirty.ts b/desktop/src/layout/panelDirty.tsindex 7555e1ab8..8a84b1a02 100644--- a/desktop/src/layout/panelDirty.ts+++ b/desktop/src/layout/panelDirty.ts@@ -17,6 +17,9 @@ import { TimelineDocument } from '@/timeline/TimelineDocument';export interface DirtySource {subscribe(cb: () => void): () => void;isDirty(): boolean;+ /** The panel's DirtyRegistry document id — lets context-aware Save (Ctrl+S) route+ * to this editor's document instead of the scene. Absent for panels with no doc. */+ docId?: string;/** Close the underlying document, dropping its unsaved edits — the dock tab X* calls this after the user confirms the discard, so the dirty state (and the* document's undo steps) don't linger invisibly behind a closed tab. */@@ -24,13 +27,13 @@ export interface DirtySource {}const SOURCES: Record<string, DirtySource> = {- statemachine: { subscribe: FsmGraphDocument.subscribe, isDirty: () => FsmGraphDocument.dirty, discard: () => FsmGraphDocument.close() },- animatorcontroller: { subscribe: AnimatorGraphDocument.subscribe, isDirty: () => AnimatorGraphDocument.dirty, discard: () => AnimatorGraphDocument.close() },- behaviortree: { subscribe: BtDocument.subscribe, isDirty: () => BtDocument.dirty, discard: () => BtDocument.close() },- materialgraph: { subscribe: MaterialGraphDocument.subscribe, isDirty: () => MaterialGraphDocument.dirty, discard: () => MaterialGraphDocument.close() },- tileset: { subscribe: TilesetDocument.subscribe, isDirty: () => TilesetDocument.dirty, discard: () => TilesetDocument.close() },- flipbook: { subscribe: AnimClipDocument.subscribe, isDirty: () => AnimClipDocument.dirty, discard: () => AnimClipDocument.close() },- sequencer: { subscribe: TimelineDocument.subscribe, isDirty: () => TimelineDocument.dirty, discard: () => TimelineDocument.close() },+ statemachine: { docId: 'fsm', subscribe: FsmGraphDocument.subscribe, isDirty: () => FsmGraphDocument.dirty, discard: () => FsmGraphDocument.close() },+ animatorcontroller: { docId: 'animator', subscribe: AnimatorGraphDocument.subscribe, isDirty: () => AnimatorGraphDocument.dirty, discard: () => AnimatorGraphDocument.close() },+ behaviortree: { docId: 'bt', subscribe: BtDocument.subscribe, isDirty: () => BtDocument.dirty, discard: () => BtDocument.close() },+ materialgraph: { docId: 'materialgraph', subscribe: MaterialGraphDocument.subscribe, isDirty: () => MaterialGraphDocument.dirty, discard: () => MaterialGraphDocument.close() },+ tileset: { docId: 'tileset', subscribe: TilesetDocument.subscribe, isDirty: () => TilesetDocument.dirty, discard: () => TilesetDocument.close() },+ flipbook: { docId: 'flipbook', subscribe: AnimClipDocument.subscribe, isDirty: () => AnimClipDocument.dirty, discard: () => AnimClipDocument.close() },+ sequencer: { docId: 'timeline', subscribe: TimelineDocument.subscribe, isDirty: () => TimelineDocument.dirty, discard: () => TimelineDocument.close() },};const NONE: DirtySource = { subscribe: () => () => {}, isDirty: () => false };diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsxindex 55eb00ca7..5bceb1c96 100644--- a/desktop/src/panels/ContentBrowser.tsx+++ b/desktop/src/panels/ContentBrowser.tsx@@ -1,7 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { Fragment, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';-import { ChevronRight, LayoutGrid, List, Import, FolderOpen, FolderPlus, ArrowLeft, ArrowRight, ArrowUp, ArrowDownUp, Play, EyeOff } from 'lucide-react';+import { ChevronRight, LayoutGrid, List, Import, FolderOpen, FolderPlus, ArrowLeft, ArrowRight, ArrowUp, ArrowDownUp, Play, EyeOff, Plus } from 'lucide-react';import { AssetIcon, assetTint } from '@/components/icons';import { IconButton } from '@/components/IconButton';import { ConfirmDialog } from '@/components/ConfirmDialog';@@ -449,13 +449,21 @@ export function ContentBrowser() {const commitRename = async (path: string, raw: string) => {setRenaming(null);- const name = raw.trim();+ let name = raw.trim();const cur = path.slice(path.lastIndexOf('/') + 1);if (!name || name === cur) return;if (/[\\/]/.test(name)) {Toasts.push(t('cb.nameNoSlashes'), 'error');return;}+ // Preserve a FILE's extension if the user dropped it (e.g. Ctrl+A + retype):+ // assetType() drives the icon AND double-click open and is extension-based, so+ // an extensionless file would go inert. Folders have no extension to keep.+ const isDir = entries.find((e) => e.name === cur)?.isDir ?? false;+ const dot = cur.lastIndexOf('.');+ const ext = !isDir && dot > 0 ? cur.slice(dot) : '';+ if (ext && !name.toLowerCase().endsWith(ext.toLowerCase())) name += ext;+ if (name === cur) return;const dest = join(parentOf(path), name);try {await window.estella.fs.rename(path, dest);@@ -1008,6 +1016,20 @@ export function ContentBrowser() {<IconButton size="lg" variant="outline" title={t('cb.menuNewFolder')} onClick={() => void newFolder()}><FolderPlus size={13} strokeWidth={1.9} /></IconButton>+ {/* Discoverable create entry point — opens the same menu as right-click+ empty space, so making an asset isn't a hidden right-click-only action. */}+ <button+ type="button"+ className="cb-add"+ title={t('cb.newAssetTip')}+ onClick={(e) => {+ const r = e.currentTarget.getBoundingClientRect();+ tip.close();+ setCtx({ x: r.left, y: r.bottom + 4, target: null });+ }}+ >+ <Plus size={13} strokeWidth={1.9} /> {t('cb.newAsset')}+ </button><button type="button" className="cb-add" title={t('cb.importAssets')} onClick={() => void importAssets()}><Import size={13} strokeWidth={1.9} /> {t('cb.import')}</button>diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex d357b1a16..c9b49349f 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -2999,6 +2999,15 @@ function EditorDetails() {className="ent-name"defaultValue={entity.name}spellCheck={false}+ onKeyDown={(e) => {+ // Match the Outliner rename: Enter commits (blur → onBlur writes),+ // Escape reverts to the current name and blurs without committing.+ if (e.key === 'Enter') e.currentTarget.blur();+ else if (e.key === 'Escape') {+ e.currentTarget.value = entity.name;+ e.currentTarget.blur();+ }+ }}onBlur={(e) => SceneCommands.renameEntity(selectedId, e.target.value)}/>)}diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsxindex aa67f10ba..c3cb7b1e7 100644--- a/desktop/src/panels/Outliner.tsx+++ b/desktop/src/panels/Outliner.tsx@@ -374,8 +374,8 @@ export function Outliner() {}};- const addEntity = () => {- const id = SceneCommands.addEntity();+ const addEntity = (parent: EntityId | null = null) => {+ const id = SceneCommands.addEntity(parent);if (id != null) select(id);};// Create a ready-made entity from a source (no add-component dance). Where it@@ -450,6 +450,15 @@ export function Outliner() {const rel = (e.clientY - rect.top) / rect.height;pos = item.kind === 'folder' ? (rel < 0.33 ? 'before' : rel > 0.66 ? 'after' : 'on') : rel < 0.5 ? 'before' : 'after';}+ // Reject an entity reparent onto itself or a descendant — reparentEntities would+ // silently no-op, so don't flash a positive drop cue. (before/after reorders,+ // which don't reparent, stay valid.)+ if (dragIds.current && item.kind === 'entity' && pos === 'on'+ && !SceneCommands.canReparent(dragIds.current, item.id)) {+ e.dataTransfer.dropEffect = 'none';+ if (drop) setDrop(null);+ return;+ }if (drop?.key !== item.key || drop?.pos !== pos) setDrop({ key: item.key, pos });};/** Nest folder `src` under `destParent` (or root). Rejects self/descendant/no-op. */@@ -535,7 +544,7 @@ export function Outliner() {if (!ctx.item) {// Empty-space (scene) menu.return [- { label: t('out.addEntity'), onClick: addEntity },+ { label: t('out.addEntity'), onClick: () => addEntity(null) },{ label: t('out.createTemplate'), onClick: () => setCreateFor({ parent: null }) },{ label: t('out.newFolder'), onClick: () => newFolder('', null) },{ sep: true },@@ -590,8 +599,10 @@ export function Outliner() {{ label: t('out.moveToRoot'), onClick: () => SceneCommands.moveToFolder(selectionOrTarget(id), null) },{ label: t('out.unparent'), onClick: () => SceneCommands.reparentEntities(selectionOrTarget(id), null) },{ sep: true },- { label: t('out.addEntity'), onClick: addEntity },- { label: t('out.createTemplate'), onClick: () => setCreateFor({ parent: id }) },+ // On an entity, both "add" actions parent to it (predictable), unlike the+ // old "Add Entity" which jumped to root.+ { label: t('out.addChild'), onClick: () => addEntity(id) },+ { label: t('out.createChild'), onClick: () => setCreateFor({ parent: id }) },];// eslint-disable-next-line react-hooks/exhaustive-deps}, [ctx]);@@ -689,7 +700,7 @@ export function Outliner() {<button type="button" className="pbtn" title={t('out.newFolderTip')} onClick={() => newFolder('', null)}><FolderPlus size={15} strokeWidth={2} /></button>- <button type="button" className="pbtn" title={t('out.addEntityTip')} onClick={addEntity}>+ <button type="button" className="pbtn" title={t('out.addEntityTip')} onClick={() => setCreateFor({ parent: null })}><Plus size={15} strokeWidth={2} /></button></div>diff --git a/desktop/tests/dirty-docs.test.ts b/desktop/tests/dirty-docs.test.tsindex 9e0568665..a053cb644 100644--- a/desktop/tests/dirty-docs.test.ts+++ b/desktop/tests/dirty-docs.test.ts@@ -10,7 +10,8 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { DirtyRegistry } from '@/document/DirtyRegistry';import { BtDocument } from '@/bt/BtDocument';import { FsmGraphDocument } from '@/fsm/FsmGraphDocument';-import type { BtDefinition } from 'esengine';+import { AnimatorGraphDocument } from '@/animator/AnimatorGraphDocument';+import type { BtDefinition, AnimatorControllerDef } from 'esengine';import '@/document/dirtyDocs';const write = vi.fn(async (_path: string, _text: string) => {});@@ -23,9 +24,13 @@ beforeEach(() => {afterEach(() => {BtDocument.close();FsmGraphDocument.close();+ AnimatorGraphDocument.close();delete (globalThis as { window?: unknown }).window;});+const animDef = (): AnimatorControllerDef =>+ ({ parameters: [], initialState: 'a', states: [{ name: 'a', transitions: [] }] }) as AnimatorControllerDef;+const btDef = (): BtDefinition =>({ root: { id: 'root', type: 'selector', children: [] } }) as unknown as BtDefinition;@@ -63,6 +68,40 @@ describe('built-in dirty documents', () => {});});+ it('an edited .esanimator makes the aggregate dirty and saveAll writes it (no silent loss)', async () => {+ AnimatorGraphDocument.open(animDef(), 'assets/anim/player.esanimator');+ expect(DirtyRegistry.isDirty()).toBe(false);+ AnimatorGraphDocument.edit('Rename state', (d) => {+ (d as AnimatorControllerDef).initialState = 'b';+ });+ // The whole point of the fix: the aggregate guard (discard/quit/autosave) sees it.+ expect(DirtyRegistry.isDirty()).toBe(true);+ await DirtyRegistry.saveAll();+ expect(write.mock.calls.map((c) => c[0])).toContain('assets/anim/player.esanimator');+ expect(AnimatorGraphDocument.dirty).toBe(false);+ });++ it('saveDoc saves ONLY the named document (context-aware Ctrl+S)', async () => {+ BtDocument.open(btDef(), 'assets/ai/x.esbt');+ BtDocument.edit('Add node', (d) => {+ (d as { root: { children: unknown[] } }).root.children.push({ id: 'n1', type: 'action' });+ });+ AnimatorGraphDocument.open(animDef(), 'assets/anim/player.esanimator');+ AnimatorGraphDocument.edit('Rename', (d) => {+ (d as AnimatorControllerDef).initialState = 'b';+ });++ const saved = await DirtyRegistry.saveDoc('animator');+ expect(saved).toBe(true);+ const paths = write.mock.calls.map((c) => c[0]);+ expect(paths).toContain('assets/anim/player.esanimator');+ expect(paths).not.toContain('assets/ai/x.esbt'); // the BT was NOT touched+ expect(AnimatorGraphDocument.dirty).toBe(false);+ expect(BtDocument.dirty).toBe(true); // still dirty — only the active doc saved+ // A clean doc is a no-op.+ expect(await DirtyRegistry.saveDoc('animator')).toBe(false);+ });+it('a clean (or closed) document is not written', async () => {await DirtyRegistry.saveAll();expect(write).not.toHaveBeenCalled();