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): asset deletes tell you what breaks, renames follow open docs, plus Find Usages and a command palette
esengined51345420617
diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex cbbb47d7a..944d357d1 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -16,6 +16,8 @@ import {mkdirInRoot,duplicateInRoot,statInRoot,+ snapshotForTrash,+ restoreTrashed,saveWorkspace,resolveInRoot,META_EXT,@@ -590,13 +592,20 @@ ipcMain.handle('fs:mkdir', (_e, relPath: string) => mkdirInRoot(requireRoot(), ripcMain.handle('fs:duplicate', (_e, relPath: string) => duplicateInRoot(requireRoot(), relPath));ipcMain.handle('fs:stat', (_e, relPath: string) => statInRoot(requireRoot(), relPath));// Delete to the OS trash (recoverable, not an unrecoverable rm) — the asset's-// `.meta` sidecar goes with it so no orphan stays in the registry.+// `.meta` sidecar goes with it so no orphan stays in the registry. A pre-trash+// snapshot backs the renderer's Undo toast; the returned token restores it.ipcMain.handle('fs:trash', async (_e, relPath: string) => {- const abs = resolveInRoot(requireRoot(), relPath);+ const root = requireRoot();+ const token = await snapshotForTrash(root, relPath);+ const abs = resolveInRoot(root, relPath);await shell.trashItem(abs);const meta = abs + META_EXT;if (existsSync(meta)) await shell.trashItem(meta);+ return token;});+ipcMain.handle('fs:restoreTrashed', (_e, relPath: string, token: string) =>+ restoreTrashed(requireRoot(), relPath, token),+);// Reveal a file/folder in the OS file manager (Finder / Explorer).ipcMain.handle('shell:showItem', (_e, relPath: string) => {shell.showItemInFolder(resolveInRoot(requireRoot(), relPath));diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex a3e15e8cc..6d40d799e 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -135,8 +135,13 @@ const api = {mkdir: (relPath: string): Promise<void> => ipcRenderer.invoke('fs:mkdir', relPath),/** Duplicate a file/folder next to itself (new uuid); returns the new path. */duplicate: (relPath: string): Promise<string> => ipcRenderer.invoke('fs:duplicate', relPath),- /** Delete to the OS trash (recoverable), sidecar included. */- trash: (relPath: string): Promise<void> => ipcRenderer.invoke('fs:trash', relPath),+ /** Delete to the OS trash (recoverable), sidecar included. Returns a token+ * that `restoreTrashed` accepts to undo the delete. */+ trash: (relPath: string): Promise<string> => ipcRenderer.invoke('fs:trash', relPath),+ /** Undo a trash: rewrite the file/folder (+ `.meta`, uuid intact) from the+ * pre-trash snapshot named by `token`. */+ restoreTrashed: (relPath: string, token: string): Promise<void> =>+ ipcRenderer.invoke('fs:restoreTrashed', relPath, token),/** Size + modified time (for the asset tooltip / inspector metadata). */stat: (relPath: string): Promise<{ size: number; mtimeMs: number; isDir: boolean }> =>ipcRenderer.invoke('fs:stat', relPath),diff --git a/desktop/electron/projectFs.ts b/desktop/electron/projectFs.tsindex 660448455..b27145262 100644--- a/desktop/electron/projectFs.ts+++ b/desktop/electron/projectFs.ts@@ -8,9 +8,10 @@* refused, so a compromised/buggy renderer can't read or write arbitrary files.* See RC12 §E7.*/-import { readFile, writeFile, readdir, mkdir, rename, cp, stat } from 'node:fs/promises';+import { readFile, writeFile, readdir, mkdir, rename, cp, stat, rm } from 'node:fs/promises';import { existsSync } from 'node:fs';import { randomUUID } from 'node:crypto';+import { tmpdir } from 'node:os';import path from 'node:path';import {PROJECT_MANIFEST_FILE,@@ -182,6 +183,42 @@ export async function duplicateInRoot(root: string, relPath: string): Promise<streturn toRel(root, to);}+// Pre-trash snapshots for the delete-undo toast. shell.trashItem has no restore+// API, so undo rewrites the file from a copy taken just before the trash — the+// `.meta` travels along, so the uuid (and every `@uuid:` ref to it) survives.+const TRASH_HOLDING_DIR = path.join(tmpdir(), 'estella-trash-undo');+const TOKEN_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;++/** Copy a file/folder (+ sidecar) into the holding dir; returns a restore token. */+export async function snapshotForTrash(root: string, relPath: string): Promise<string> {+ const abs = resolveInRoot(root, relPath);+ if (!existsSync(abs)) throw new Error(`"${relPath}" does not exist`);+ const token = randomUUID();+ const dir = path.join(TRASH_HOLDING_DIR, token);+ await mkdir(dir, { recursive: true });+ await cp(abs, path.join(dir, 'item'), { recursive: true });+ const meta = abs + META_EXT;+ if (existsSync(meta)) await cp(meta, path.join(dir, 'item' + META_EXT));+ return token;+}++/** Undo a trash: rewrite `relPath` (+ `.meta`) from its pre-trash snapshot.+ * Refuses if the path has been re-taken in the meantime. */+export async function restoreTrashed(root: string, relPath: string, token: string): Promise<void> {+ // The token names a directory — reject anything that isn't a plain uuid.+ if (!TOKEN_SHAPE.test(token)) throw new Error('invalid restore token');+ const dir = path.join(TRASH_HOLDING_DIR, token);+ const item = path.join(dir, 'item');+ if (!existsSync(item)) throw new Error('nothing to restore (snapshot expired)');+ const abs = resolveInRoot(root, relPath);+ if (existsSync(abs)) throw new Error(`"${relPath}" already exists`);+ await mkdir(path.dirname(abs), { recursive: true });+ await cp(item, abs, { recursive: true });+ const meta = item + META_EXT;+ if (existsSync(meta)) await cp(meta, abs + META_EXT);+ await rm(dir, { recursive: true, force: true });+}+/** Size + modified time for the asset tooltip / inspector metadata. */export async function statInRoot(root: string,diff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex 470e998b1..ea4cd944e 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -19,6 +19,7 @@ import { PerfRealmBridge } from '@/components/PerfRealmBridge';import { BuildDialog } from '@/components/BuildDialog';import { SettingsDialog } from '@/components/SettingsDialog';import { TilemapPickerDialog } from '@/components/TilemapPickerDialog';+import { CommandPalette } from '@/components/CommandPalette';import { useEditorStore } from '@/store/editorStore';import { commands } from '@/commands';import { handleTilePaintKey } from '@/tools/tileMode';@@ -228,6 +229,7 @@ export function App() {const buildOpen = useEditorStore((s) => s.buildOpen);const settingsOpen = useEditorStore((s) => s.settingsOpen);const tilemapPickerOpen = useEditorStore((s) => s.tilemapPickerOpen);+ const paletteOpen = useEditorStore((s) => s.paletteOpen);if (showLauncher) return <Launcher />;return (@@ -244,6 +246,7 @@ export function App() {{buildOpen && <BuildDialog />}{settingsOpen && <SettingsDialog />}{tilemapPickerOpen && <TilemapPickerDialog />}+ {paletteOpen && <CommandPalette onClose={() => useEditorStore.getState().setPaletteOpen(false)} />}<Toaster /><ConfirmHost /><LoadingScreen />diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsindex d273e57fd..67f037b0b 100644--- a/desktop/src/commands/editorCommands.ts+++ b/desktop/src/commands/editorCommands.ts@@ -357,6 +357,13 @@ commands.register({keybinding: 'mod+,',run: () => editor().setSettingsOpen(true),});+commands.register({+ id: 'palette.open',+ label: t('cmd.palette.open'),+ category: t('cat.editor'),+ keybinding: 'mod+shift+p',+ run: () => editor().setPaletteOpen(true),+});// — Play —commands.register({diff --git a/desktop/src/commands/palette.ts b/desktop/src/commands/palette.tsnew file mode 100644index 000000000..76a2bb4ae--- /dev/null+++ b/desktop/src/commands/palette.ts@@ -0,0 +1,88 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file palette.ts+ * @brief Pure command-palette logic: the registry → display-item projection and+ * the fuzzy filter/rank. Kept out of the React component so ranking and+ * enablement rules are unit-testable.+ */+import type { Command } from './types';++/** A palette row: what the list renders and what Enter executes. */+export interface PaletteItem {+ id: string;+ label: string;+ category?: string;+ /** Effective keybinding chord (overrides resolved), for the hint column. */+ keybinding?: string;+ /** Disabled commands stay listed but grey and inert (VS Code convention). */+ enabled: boolean;+}++/** The searchable text of an item — category-qualified, like VS Code. */+export function paletteText(item: { label: string; category?: string }): string {+ return item.category ? `${item.category}: ${item.label}` : item.label;+}++/**+ * Fuzzy subsequence score of `query` against `text`; null = no match. Bonuses+ * favor consecutive runs and word starts, so 'sq' ranks 'Scene Quality' over+ * 'settings…quit'. Case-insensitive; an empty query matches everything at 0.+ */+export function fuzzyScore(query: string, text: string): number | null {+ const q = query.toLowerCase();+ const t = text.toLowerCase();+ if (!q) return 0;+ let score = 0;+ let searchFrom = 0;+ let prevHit = -2;+ for (const ch of q) {+ if (ch === ' ') continue; // spaces separate terms, they don't need matching+ const hit = t.indexOf(ch, searchFrom);+ if (hit === -1) return null;+ score += 1;+ if (hit === prevHit + 1) score += 3;+ if (hit === 0 || /[\s./:+-]/.test(t[hit - 1])) score += 2;+ prevHit = hit;+ searchFrom = hit + 1;+ }+ return score;+}++/**+ * Filter + rank items for a query. Empty query preserves registration order+ * (commands group naturally by category); otherwise best score first, ties+ * broken by label so the order is stable.+ */+export function filterPalette<T extends { label: string; category?: string }>(+ items: readonly T[],+ query: string,+): T[] {+ const q = query.trim();+ if (!q) return [...items];+ const scored: { item: T; score: number }[] = [];+ for (const item of items) {+ const score = fuzzyScore(q, paletteText(item));+ if (score != null) scored.push({ item, score });+ }+ scored.sort((a, b) => b.score - a.score || a.item.label.localeCompare(b.item.label));+ return scored.map((s) => s.item);+}++/** Project registry commands into palette items (enablement resolved NOW —+ * the palette is a snapshot of what is runnable at open time). */+export function paletteItems(+ all: readonly Command[],+ keybindingFor: (id: string) => string | string[] | undefined,+): PaletteItem[] {+ return all.map((c) => {+ const kb = keybindingFor(c.id);+ return {+ id: c.id,+ label: c.label,+ category: c.category,+ keybinding: Array.isArray(kb) ? kb[0] : kb,+ enabled: c.isEnabled?.() ?? true,+ };+ });+}diff --git a/desktop/src/components/CommandPalette.tsx b/desktop/src/components/CommandPalette.tsxnew file mode 100644index 000000000..6f5c2a50d--- /dev/null+++ b/desktop/src/components/CommandPalette.tsx@@ -0,0 +1,139 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file CommandPalette.tsx+ * @brief The Ctrl/Cmd+Shift+P command palette: every registry command, fuzzy-+ * filtered, keyboard-first (↑/↓ + Enter), keybinding hints, disabled+ * commands greyed but listed (VS Code convention). Reuses the .ac+ * picker chrome so it reads like the Add-Component palette.+ */+import { useEffect, useMemo, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { SearchField } from '@/components/SearchField';+import { useDialogFocus } from '@/components/dialogFocus';+import { usePanelWindow } from '@/components/PanelWindow';+import { commands, formatKeybinding } from '@/commands';+import { filterPalette, paletteItems, type PaletteItem } from '@/commands/palette';+import { t } from '@/i18n';++export function CommandPalette({ onClose }: { onClose: () => void }) {+ const win = usePanelWindow();+ const [query, setQuery] = useState('');+ const [active, setActive] = useState(0);+ const inputRef = useRef<HTMLInputElement>(null);+ const activeRef = useRef<HTMLButtonElement>(null);+ const shellRef = useRef<HTMLDivElement>(null);+ useDialogFocus(shellRef);++ // Enablement is resolved once at open — the palette is a snapshot of what is+ // runnable now, and predicates read live store state (cheap but not reactive).+ const [items] = useState<PaletteItem[]>(() =>+ paletteItems(commands.all(), (id) => commands.keybindingFor(id)),+ );++ useEffect(() => {+ inputRef.current?.focus();+ }, []);++ useEffect(() => {+ const close = () => onClose();+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') onClose();+ };+ win.addEventListener('mousedown', close);+ win.addEventListener('keydown', onKey);+ return () => {+ win.removeEventListener('mousedown', close);+ win.removeEventListener('keydown', onKey);+ };+ }, [onClose, win]);++ const filtered = useMemo(() => filterPalette(items, query), [items, query]);++ useEffect(() => {+ setActive(0);+ }, [query]);+ useEffect(() => {+ activeRef.current?.scrollIntoView({ block: 'nearest' });+ }, [active]);++ const run = (item: PaletteItem) => {+ if (!item.enabled) return;+ onClose();+ commands.run(item.id);+ };++ const onKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.preventDefault();+ onClose();+ } else if (e.key === 'ArrowDown') {+ e.preventDefault();+ setActive((a) => Math.min(filtered.length - 1, a + 1));+ } else if (e.key === 'ArrowUp') {+ e.preventDefault();+ setActive((a) => Math.max(0, a - 1));+ } else if (e.key === 'Enter') {+ e.preventDefault();+ const item = filtered[active];+ if (item) run(item);+ }+ };++ return createPortal(+ <div className="ac-scrim open" onMouseDown={onClose}>+ <div+ ref={shellRef}+ className="ac cp"+ role="dialog"+ aria-modal="true"+ aria-label={t('cmd.palette.open')}+ tabIndex={-1}+ onMouseDown={(e) => e.stopPropagation()}+ >+ <SearchField+ flush+ className="ac-search"+ iconSize={15}+ inputRef={inputRef}+ placeholder={t('palette.placeholder')}+ value={query}+ onChange={setQuery}+ onKeyDown={onKeyDown}+ >+ <kbd className="esc">Esc</kbd>+ </SearchField>++ <div className="ac-body">+ {filtered.length === 0 ? (+ <div className="empty-line">{t('palette.noMatch')}</div>+ ) : (+ filtered.map((item, idx) => {+ const isActive = idx === active;+ return (+ <button+ key={item.id}+ ref={isActive ? activeRef : undefined}+ type="button"+ className={`ac-item cp-item${isActive ? ' sel' : ''}${item.enabled ? '' : ' is-disabled'}`}+ aria-disabled={!item.enabled}+ onMouseEnter={() => setActive(idx)}+ onClick={() => run(item)}+ >+ <span className="at">+ <div className="an">+ {item.category && <span className="cp-cat">{item.category}: </span>}+ {item.label}+ </div>+ </span>+ {item.keybinding && <span className="cp-kb">{formatKeybinding(item.keybinding)}</span>}+ </button>+ );+ })+ )}+ </div>+ </div>+ </div>,+ win.document.body,+ );+}diff --git a/desktop/src/components/FindUsagesDialog.tsx b/desktop/src/components/FindUsagesDialog.tsxnew file mode 100644index 000000000..aeb75caa7Binary files /dev/null and b/desktop/src/components/FindUsagesDialog.tsx differdiff --git a/desktop/src/i18n/messages/commands.ts b/desktop/src/i18n/messages/commands.tsindex bab486e14..81de73d3f 100644--- a/desktop/src/i18n/messages/commands.ts+++ b/desktop/src/i18n/messages/commands.ts@@ -56,6 +56,9 @@ export const commandMessages = defineMessages({// — Editor / play / build —'cmd.settings.open': { en: 'Settings…', zh: '设置…' },+ 'cmd.palette.open': { en: 'Command Palette…', zh: '命令面板…' },+ 'palette.placeholder': { en: 'Run a command…', zh: '运行命令…' },+ 'palette.noMatch': { en: 'No matching commands', zh: '没有匹配的命令' },'cmd.play.toggle': { en: 'Play', zh: '运行' },'cmd.play.stop': { en: 'Stop', zh: '停止' },'cmd.build.scripts': { en: 'Build Project Scripts', zh: '构建项目脚本' },diff --git a/desktop/src/i18n/messages/content.ts b/desktop/src/i18n/messages/content.tsindex 039c2c038..77bd6a35a 100644--- a/desktop/src/i18n/messages/content.ts+++ b/desktop/src/i18n/messages/content.ts@@ -95,14 +95,22 @@ export const contentMessages = defineMessages({en: 'Delete “{name}”? It will be moved to the trash.',zh: '确定删除“{name}”?它将被移入回收站。',},- 'cb.deleteRefWarnOne': {- en: 'It is referenced by {count} asset ({names}); those references will break.',- zh: '它被 {count} 个资产引用({names});这些引用将会失效。',+ 'cb.deleteRefListOne': {+ en: 'It is referenced by {count} document; that reference will break:',+ zh: '它被 {count} 个文档引用;该引用将会失效:',},- 'cb.deleteRefWarnMany': {- en: 'It is referenced by {count} assets ({names}); those references will break.',- zh: '它被 {count} 个资产引用({names});这些引用将会失效。',+ 'cb.deleteRefListMany': {+ en: 'It is referenced by {count} documents; those references will break:',+ zh: '它被 {count} 个文档引用;这些引用将会失效:',},+ 'cb.usagesMore': { en: '…and {count} more', zh: '……以及另外 {count} 个' },+ 'cb.deletedName': { en: 'Deleted “{name}”', zh: '已删除“{name}”' },+ 'cb.menuFindUsages': { en: 'Find Usages', zh: '查找引用' },+ 'cb.findUsagesTitle': { en: 'Usages of “{name}”', zh: '“{name}”的引用' },+ 'cb.findUsagesScanning': { en: 'Scanning…', zh: '正在扫描……' },+ 'cb.noUsages': { en: 'Nothing references this asset.', zh: '没有内容引用此资产。' },+ 'cb.unsavedScene': { en: 'Untitled scene', zh: '未命名场景' },+ 'cb.unsavedMark': { en: 'unsaved', zh: '未保存' },'cb.movedTo': { en: 'Moved “{name}” to {dest}', zh: '已将“{name}”移动到 {dest}' },'cb.projectRoot': { en: 'the project root', zh: '项目根目录' },'cb.moveFailed': { en: 'Move failed: {error}', zh: '移动失败:{error}' },diff --git a/desktop/src/i18n/messages/details.ts b/desktop/src/i18n/messages/details.tsindex ed8966a7f..ac282a4dc 100644--- a/desktop/src/i18n/messages/details.ts+++ b/desktop/src/i18n/messages/details.ts@@ -174,6 +174,7 @@ export const detailsMessages = defineMessages({'det.metaModified': { en: 'Modified', zh: '修改时间' },'det.metaUuid': { en: 'UUID', zh: 'UUID' },'det.metaReferences': { en: 'References', zh: '引用' },+ 'det.findUsagesTip': { en: 'Show what references this asset', zh: '查看哪些内容引用了此资产' },'det.openScene': { en: 'Open Scene', zh: '打开场景' },'det.copyPath': { en: 'Copy Path', zh: '复制路径' },'det.copiedPath': { en: 'Copied path', zh: '已复制路径' },diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsxindex 499e65786..52b05318e 100644--- a/desktop/src/panels/ContentBrowser.tsx+++ b/desktop/src/panels/ContentBrowser.tsx@@ -12,9 +12,11 @@ import { Segmented } from '@/components/Segmented';import { ProjectStore } from '@/project/ProjectStore';import { Toasts } from '@/store/Toasts';import { useSelection } from '@/store/selectionStore';-import { IMAGE_RE, assetTypeOf as assetType, TYPE_CODE } from '@/project/assetMeta';+import { IMAGE_RE, assetTypeOf as assetType, baseName, TYPE_CODE } from '@/project/assetMeta';import { ASSET_OPEN } from '@/project/assetOpen';-import { referencingPaths } from '@/project/assetRefs';+import { syncAssetPaths } from '@/project/assetPathSync';+import { findAssetUsages, type AssetUsage } from '@/project/assetUsages';+import { FindUsagesDialog } from '@/components/FindUsagesDialog';import { parseAssetQuery, filterAndSortAssets, type AssetSort } from '@/project/assetFilter';import { createTilesetFromTexture } from '@/tileset/openTileset';import { createFlipbookFromTexture } from '@/flipbook/openFlipbook';@@ -433,6 +435,7 @@ export function ContentBrowser() {const undoMove = async (from: string, to: string) => {try {await window.estella.fs.rename(from, to);+ syncAssetPaths(from, to);refreshFs();selectAsset(to);} catch (e) {@@ -452,6 +455,7 @@ export function ContentBrowser() {const dest = join(parentOf(path), name);try {await window.estella.fs.rename(path, dest);+ syncAssetPaths(path, dest);refreshFs();selectAsset(dest);Toasts.push(t('cb.renamedTo', { name }), 'info', 6000, { label: t('cb.undo'), run: () => void undoMove(dest, path) });@@ -483,33 +487,39 @@ export function ContentBrowser() {};// Delete = themed confirm (Enter confirms, Esc cancels) → trash. The dialog- // body warns when scenes/prefabs reference the asset (those refs would break).- const [confirmDel, setConfirmDel] = useState<{ path: string; name: string; warn: string } | null>(null);+ // body lists WHICH scenes/prefabs reference the asset (disk dep graph + the+ // unsaved in-memory scene — a ref added since the last save would break too).+ const [confirmDel, setConfirmDel] = useState<{ path: string; name: string; usages: AssetUsage[] } | null>(null);+ const [usagesPath, setUsagesPath] = useState<string | null>(null);const remove = async (path: string, name: string) => {- let warn = '';+ let usages: AssetUsage[] = [];try {- const scan = await window.estella.project.scanAssets();- const refs = referencingPaths(scan.index, path);- if (refs.length) {- const names = refs.slice(0, 3).map((p) => p.split('/').pop()).join(', ');- warn = `\n\n${t(refs.length > 1 ? 'cb.deleteRefWarnMany' : 'cb.deleteRefWarnOne', {- count: refs.length,- names: names + (refs.length > 3 ? ', …' : ''),- })}`;- }+ usages = await findAssetUsages(path);} catch {// Best-effort: if the scan fails, confirm without the reference warning.}- setConfirmDel({ path, name, warn });+ setConfirmDel({ path, name, usages });};const doRemove = async () => {const target = confirmDel;setConfirmDel(null);if (!target) return;try {- await window.estella.fs.trash(target.path);+ const token = await window.estella.fs.trash(target.path);refreshFs();if (selected === target.path) selectAsset(null);+ Toasts.push(t('cb.deletedName', { name: target.name }), 'info', 6000, {+ label: t('cb.undo'),+ run: async () => {+ try {+ await window.estella.fs.restoreTrashed(target.path, token);+ refreshFs();+ selectAsset(target.path);+ } catch (e) {+ Toasts.push(t('cb.undoFailed', { error: errMsg(e) }), 'error');+ }+ },+ });} catch (e) {Toasts.push(t('cb.deleteFailed', { error: errMsg(e) }), 'error');}@@ -754,6 +764,7 @@ export function ContentBrowser() {if (dest === srcPath || srcPath === folderPath || folderPath.startsWith(`${srcPath}/`)) return;try {await window.estella.fs.rename(srcPath, dest);+ syncAssetPaths(srcPath, dest);refreshFs();if (selected === srcPath) selectAsset(dest);Toasts.push(t('cb.movedTo', { name, dest: folderPath || t('cb.projectRoot') }), 'info', 6000, {@@ -908,6 +919,7 @@ export function ContentBrowser() {{ sep: true },{ label: t('cb.menuCopyPath'), onClick: () => copy(path, t('cb.copiedPath')) },...(ref ? [{ label: t('cb.menuCopyReference'), onClick: () => copy(ref, t('cb.copiedReference')) }] : []),+ ...(entry.isDir ? [] : [{ label: t('cb.menuFindUsages'), onClick: () => setUsagesPath(path) }]),{ label: t('cb.menuShowInExplorer'), onClick: () => void showInExplorer(path) },{ sep: true },{ label: t('ui.delete'), danger: true, onClick: () => void remove(path, entry.name) },@@ -1191,12 +1203,36 @@ export function ContentBrowser() {{!ctx && tip.card}{ctx && <ContextMenu x={ctx.x} y={ctx.y} items={ctxItems} onClose={() => setCtx(null)} />}+ {usagesPath && <FindUsagesDialog path={usagesPath} onClose={() => setUsagesPath(null)} />}{confirmDel && (<ConfirmDialogtitle={t('cb.deleteTitle')}dangerconfirmLabel={t('ui.delete')}- body={t('cb.deleteBody', { name: confirmDel.name }) + confirmDel.warn}+ body={+ <>+ {t('cb.deleteBody', { name: confirmDel.name })}+ {confirmDel.usages.length > 0 && (+ <>+ {'\n\n' ++ t(confirmDel.usages.length > 1 ? 'cb.deleteRefListMany' : 'cb.deleteRefListOne', {+ count: confirmDel.usages.length,+ })}+ <ul className="cb-usages">+ {confirmDel.usages.slice(0, 8).map((u) => (+ <li key={u.path ?? ' unsaved'}>+ <span className="n">{u.path ? baseName(u.path) : t('cb.unsavedScene')}</span>+ {u.path && <span className="p">{u.path}</span>}+ {u.unsaved && <span className="u">{t('cb.unsavedMark')}</span>}+ </li>+ ))}+ </ul>+ {confirmDel.usages.length > 8 &&+ t('cb.usagesMore', { count: confirmDel.usages.length - 8 })}+ </>+ )}+ </>+ }onConfirm={() => void doRemove()}onCancel={() => setConfirmDel(null)}/>diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex 14d1abad8..348692cbb 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -58,9 +58,10 @@ import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, pretimport * as imap from '@/project/inputMapDoc';import * as ldoc from '@/project/localeTableDoc';import { buildImporterComponent, applyImporterEdit } from '@/project/assetImporter';-import { referencingPaths } from '@/project/assetRefs';+import { findAssetUsages } from '@/project/assetUsages';+import { FindUsagesDialog } from '@/components/FindUsagesDialog';import { ProjectStore } from '@/project/ProjectStore';-import { confirmDiscard } from '@/project/discardGuard';+import { confirmDiscard, confirmDiscardDoc } from '@/project/discardGuard';import { t } from '@/i18n';import { MaterialDocument } from '@/material/MaterialDocument';import { DirtyRegistry } from '@/document/DirtyRegistry';@@ -1834,17 +1835,24 @@ function MaterialAssetInspector({ path }: { path: string }) {// the running handle the scene's sprites use (0 when it's not in the current scene).useEffect(() => {let alive = true;- void window.estella.fs- .read(path)- .then((text) => {- if (!alive) return;- MaterialDocument.openJson(JSON.parse(text), path);+ void (async () => {+ // Selection round-trip back to the file already open (possibly dirty —+ // the cleanup below kept it): rebind the handle, never reload from disk.+ if (MaterialDocument.isOpen && MaterialDocument.filePath === path) {MaterialDocument.setLiveHandle(ProjectStore.materialHandle(path));- })- .catch(() => {});+ return;+ }+ if (!(await confirmDiscardDoc(MaterialDocument.dirty, t('discard.openAsset', { name: baseName(path) }))) || !alive) return;+ const text = await window.estella.fs.read(path);+ if (!alive) return;+ MaterialDocument.openJson(JSON.parse(text), path);+ MaterialDocument.setLiveHandle(ProjectStore.materialHandle(path));+ })().catch(() => {});return () => {alive = false;- MaterialDocument.close();+ // A dirty document stays open on select-away so the DirtyRegistry guards+ // still see the unsaved edits (closing here would discard them silently).+ if (!MaterialDocument.dirty) MaterialDocument.close();};}, [path]);@@ -2424,6 +2432,7 @@ function GenericAssetInspector({ path }: { path: string }) {const [dims, setDims] = useState<string | null>(null);const [refCount, setRefCount] = useState<number | null>(null);const [collapsed, setCollapsed] = useState(false);+ const [usagesOpen, setUsagesOpen] = useState(false);// Load the `.meta` importer block on (re)selection.useEffect(() => {@@ -2451,9 +2460,10 @@ function GenericAssetInspector({ path }: { path: string }) {img.onload = () => alive && setDims(`${img.naturalWidth} × ${img.naturalHeight}`);img.src = `estella://project/${path}`;}- void window.estella.project- .scanAssets()- .then((r) => alive && setRefCount(referencingPaths(r.index, path).length))+ // Same collector as Find Usages (disk graph + unsaved scene), so the count+ // always matches what the dialog lists.+ void findAssetUsages(path)+ .then((u) => alive && setRefCount(u.length)).catch(() => {});return () => {alive = false;@@ -2580,9 +2590,21 @@ function GenericAssetInspector({ path }: { path: string }) {{stat && <MetaRow k={t('det.metaSize')} v={formatBytes(stat.size)} />}{stat && <MetaRow k={t('det.metaModified')} v={new Date(stat.mtimeMs).toLocaleString()} />}{assetRef && <MetaRow k={t('det.metaUuid')} v={assetRef} mono />}- {refCount != null && <MetaRow k={t('det.metaReferences')} v={String(refCount)} />}+ {refCount != null && (+ // The count opens Find Usages — the number alone answers nothing.+ <button+ type="button"+ className="cb-mr cb-mr-link"+ title={t('det.findUsagesTip')}+ onClick={() => setUsagesOpen(true)}+ >+ <span className="k">{t('det.metaReferences')}</span>+ <span className="v" style={{ fontFamily: 'inherit' }}>{refCount}</span>+ </button>+ )}</div></div>+ {usagesOpen && <FindUsagesDialog path={path} onClose={() => setUsagesOpen(false)} />}<div className="cb-act">{type === 'scene' && (diff --git a/desktop/src/project/assetPathSync.ts b/desktop/src/project/assetPathSync.tsnew file mode 100644index 000000000..4327da97e--- /dev/null+++ b/desktop/src/project/assetPathSync.ts@@ -0,0 +1,32 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file assetPathSync.ts+ * @brief Propagate an asset rename/move to in-memory holders of the OLD path:+ * every open AssetDocument (tileset/flipbook/timeline/fsm/bt/material/+ * materialgraph) and the tilemap painter's palette. `@uuid:` refs in the+ * scene model survive a rename by design; these path-valued bindings are+ * the ones that would silently go stale.+ */+import { AssetDocument } from '@/document/AssetDocument';+import { useTilemapPaint } from '@/store/tilemapPaintStore';+import { remapAssetPath } from './pathRemap';++/** Call after a successful fs.rename of `from` → `to` (file or folder). */+export function syncAssetPaths(from: string, to: string): void {+ for (const doc of AssetDocument.openDocuments()) doc.rebindPath(from, to);++ const s = useTilemapPaint.getState();+ const tilesets = s.tilesets.map((ts) => {+ const next = remapAssetPath(ts.path, from, to);+ return next ? { ...ts, path: next } : ts;+ });+ const changed = tilesets.some((ts, i) => ts !== s.tilesets[i]);+ const nextPath = s.tilesetPath ? remapAssetPath(s.tilesetPath, from, to) : null;+ if (changed || nextPath) {+ useTilemapPaint.setState({+ ...(changed ? { tilesets } : null),+ ...(nextPath ? { tilesetPath: nextPath } : null),+ });+ }+}diff --git a/desktop/src/project/assetRefs.ts b/desktop/src/project/assetRefs.tsindex ad5d642ce..5a9fa915d 100644--- a/desktop/src/project/assetRefs.ts+++ b/desktop/src/project/assetRefs.ts@@ -30,3 +30,56 @@ export function referencingPaths(index: AssetIndexLike, path: string): string[]}return out;}++/** One asset/scene that references the asset being inspected or deleted. */+export interface AssetUsage {+ /** Project-relative path of the referencing document; null = the unsaved,+ * still-untitled scene (it exists only in memory). */+ path: string | null;+ /** The reference lives in the unsaved in-memory scene, not (yet) on disk. */+ unsaved: boolean;+}++/**+ * Whether a JSON tree (a scene/asset document) references the asset identified+ * by `uuid` (as `@uuid:` or a bare uuid string) or by its exact project path+ * (path-valued slots, e.g. spine skeleton/atlas).+ */+export function valueReferencesAsset(+ value: unknown,+ target: { uuid: string | null; path: string },+): boolean {+ const uuid = target.uuid?.toLowerCase() ?? null;+ const walk = (v: unknown): boolean => {+ if (typeof v === 'string') {+ if (v === target.path) return true;+ if (!uuid) return false;+ const body = v.startsWith('@uuid:') ? v.slice('@uuid:'.length) : v;+ return body.toLowerCase() === uuid;+ }+ if (Array.isArray(v)) return v.some(walk);+ if (v && typeof v === 'object') return Object.values(v as Record<string, unknown>).some(walk);+ return false;+ };+ return walk(value);+}++/**+ * The full usage list for the asset at `path`: the on-disk dependency graph+ * (saved scenes/prefabs/materials/…) plus the UNSAVED in-memory scene — the+ * dep graph is built from files, so a reference added since the last save is+ * invisible to it and deleting would still break the open scene.+ */+export function collectAssetUsages(+ index: AssetIndexLike,+ path: string,+ liveScene?: { path: string | null; data: unknown } | null,+): AssetUsage[] {+ const disk: AssetUsage[] = referencingPaths(index, path).map((p) => ({ path: p, unsaved: false }));+ if (!liveScene?.data) return disk;+ const uuid = index.entries.find((e) => e.path === path)?.uuid ?? null;+ if (!valueReferencesAsset(liveScene.data, { uuid, path })) return disk;+ // A saved copy of the same scene already reports it — one row per document.+ if (liveScene.path && disk.some((d) => d.path === liveScene.path)) return disk;+ return [...disk, { path: liveScene.path, unsaved: true }];+}diff --git a/desktop/src/project/assetUsages.ts b/desktop/src/project/assetUsages.tsnew file mode 100644index 000000000..9ed2c6741--- /dev/null+++ b/desktop/src/project/assetUsages.ts@@ -0,0 +1,24 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file assetUsages.ts+ * @brief The impure glue over {@link collectAssetUsages}: scan the on-disk dep+ * graph AND the live in-memory scene model, so both the delete confirm+ * and Find Usages see references the last save doesn't know about yet.+ */+import { SceneModel } from '@/engine/SceneModel';+import { ProjectStore } from './ProjectStore';+import { collectAssetUsages, type AssetUsage } from './assetRefs';++export type { AssetUsage };++/** Everything referencing the asset at `path` (disk graph + unsaved scene). */+export async function findAssetUsages(path: string): Promise<AssetUsage[]> {+ const scan = await window.estella.project.scanAssets();+ const data = SceneModel.current;+ return collectAssetUsages(+ scan.index,+ path,+ data ? { path: ProjectStore.getSnapshot()?.currentScene ?? null, data } : null,+ );+}diff --git a/desktop/src/project/pathRemap.ts b/desktop/src/project/pathRemap.tsnew file mode 100644index 000000000..4c96c587b--- /dev/null+++ b/desktop/src/project/pathRemap.ts@@ -0,0 +1,19 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file pathRemap.ts+ * @brief Pure path arithmetic for asset rename/move: what a dependent path+ * becomes after `from` → `to`. Kept dependency-free so both the document+ * layer and project stores can share it without cycles.+ */++/**+ * The new project-relative path for `path` after the asset at `from` moved to+ * `to` — an exact match (file rename) or a prefix match (a containing folder+ * moved). Null when `path` is unaffected.+ */+export function remapAssetPath(path: string, from: string, to: string): string | null {+ if (path === from) return to;+ if (path.startsWith(from + '/')) return to + path.slice(from.length);+ return null;+}diff --git a/desktop/src/store/editorStore.ts b/desktop/src/store/editorStore.tsindex 9ff5e24c6..a570d1924 100644--- a/desktop/src/store/editorStore.ts+++ b/desktop/src/store/editorStore.ts@@ -91,6 +91,10 @@ interface EditorState {settingsOpen: boolean;setSettingsOpen: (open: boolean) => void;+ // Command palette (Ctrl/Cmd+Shift+P) — run any registry command by name.+ paletteOpen: boolean;+ setPaletteOpen: (open: boolean) => void;+// "New Tilemap" tileset chooser (Entity → New Tilemap): picks the .estileset// palette for a fresh map, then createTilemapFromTileset does the rest.tilemapPickerOpen: boolean;@@ -164,6 +168,9 @@ export const useEditorStore = create<EditorState>((set) => ({settingsOpen: false,setSettingsOpen: (settingsOpen) => set({ settingsOpen }),+ paletteOpen: false,+ setPaletteOpen: (paletteOpen) => set({ paletteOpen }),+tilemapPickerOpen: false,setTilemapPickerOpen: (tilemapPickerOpen) => set({ tilemapPickerOpen }),}));diff --git a/desktop/src/theme/content.css b/desktop/src/theme/content.cssindex 707e2f754..8a9caf51f 100644--- a/desktop/src/theme/content.css+++ b/desktop/src/theme/content.css@@ -136,6 +136,25 @@.cb-mr { display: flex; align-items: center; height: 26px; font-size: var(--fs-sm); }.cb-mr .k { width: 76px; color: var(--text-mute); flex-shrink: 0; }.cb-mr .v { color: var(--text-dim); font-family: var(--mono); font-size: var(--fs-xs); }+/* Clickable meta row (the References count → Find Usages). */+.cb-mr-link { width: 100%; padding: 0; background: none; border: none; text-align: left; cursor: pointer; border-radius: var(--r-xs); }+.cb-mr-link:hover .v { color: var(--acc-hi); text-decoration: underline; }++/* Referencing-document list in the delete confirm. */+.cb-usages { list-style: none; margin: 8px 0 0; padding: 6px 8px; display: flex; flex-direction: column; gap: 3px; max-height: 168px; overflow-y: auto; background: var(--srf-3); border: 1px solid var(--border-line); border-radius: var(--r-sm); }+.cb-usages li { display: flex; align-items: baseline; gap: 8px; min-width: 0; }+.cb-usages .n { color: var(--text); font-size: var(--fs-sm); flex-shrink: 0; }+.cb-usages .p { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-mute); font-family: var(--mono); font-size: var(--fs-2xs); }+.cb-usages .u { flex-shrink: 0; color: var(--warn); font-size: var(--fs-2xs); }++/* Find Usages dialog rows. */+.fu-list { display: flex; flex-direction: column; gap: 3px; }+.fu-row { display: flex; align-items: center; gap: 9px; padding: 7px 10px; background: var(--srf-3); border: 1px solid transparent; border-radius: var(--r-md); color: var(--text-dim); cursor: pointer; text-align: left; font: inherit; min-width: 0; }+.fu-row:hover { color: var(--text); border-color: var(--acc); background: var(--srf-2); }+.fu-row svg { flex-shrink: 0; color: var(--text-mute); }+.fu-name { flex-shrink: 0; font-weight: 600; font-size: var(--fs-sm); }+.fu-path { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--fs-2xs); color: var(--text-mute); font-family: var(--mono); text-align: right; }+.fu-unsaved { flex-shrink: 0; color: var(--warn); font-size: var(--fs-2xs); }.cb-act { padding: 11px 13px; border-top: 1px solid var(--border); display: flex; flex-direction: column; gap: 7px; }.cb-act button { height: 30px; display: inline-flex; align-items: center; justify-content: center; gap: 6px; font-size: var(--fs-sm); border-radius: var(--r-sm); transition: background var(--t-fast); }/* Outlined like .cb-add — the accent fill stays reserved for Play. */diff --git a/desktop/src/theme/menus.css b/desktop/src/theme/menus.cssindex 3ddde15b5..d5e52931f 100644--- a/desktop/src/theme/menus.css+++ b/desktop/src/theme/menus.css@@ -105,6 +105,15 @@.ac-item .ak { font-size: var(--fs-2xs); color: var(--text-mute); opacity: 0; }.ac-item.sel .ak { opacity: 1; }+/* ── Command palette (rides the .ac picker chrome) ── */+.ac.cp { width: 520px; }+.cp-item { padding: 5px 10px; }+.cp-item .an { font-size: var(--fs-sm); }+.cp-cat { color: var(--text-mute); font-weight: 400; }+.cp-kb { margin-left: auto; flex-shrink: 0; font-size: var(--fs-2xs); color: var(--text-mute); font-family: var(--mono); }+.cp-item.is-disabled { opacity: 0.45; cursor: default; }+.cp-item.is-disabled:hover { background: none; }+/* ════════════════════════ Modal dialog ════════════════════════ */.modal-backdrop {position: fixed;diff --git a/desktop/tests/asset-path-sync.test.ts b/desktop/tests/asset-path-sync.test.tsnew file mode 100644index 000000000..1fec2848f--- /dev/null+++ b/desktop/tests/asset-path-sync.test.ts@@ -0,0 +1,95 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Rename/move propagation to in-memory path holders: open AssetDocuments+ * rebind their filePath (a later save must NOT resurrect the old file)+ * and the tilemap painter's palette follows a renamed .estileset.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { createTileset } from 'esengine';+import { remapAssetPath } from '@/project/pathRemap';+import { syncAssetPaths } from '@/project/assetPathSync';+import { AssetDocument } from '@/document/AssetDocument';+import { useTilemapPaint } from '@/store/tilemapPaintStore';+import { EditorHistory } from '@/engine/EditorHistory';++class TestDoc extends AssetDocument<{ n: number }> {+ open(filePath: string | null) {+ this.openAsset({ n: 1 }, filePath);+ }+ close() {+ this.closeAsset();+ }+}++describe('remapAssetPath', () => {+ it('remaps an exact file rename', () => {+ expect(remapAssetPath('a/b.estileset', 'a/b.estileset', 'a/c.estileset')).toBe('a/c.estileset');+ });+ it('remaps paths under a moved folder', () => {+ expect(remapAssetPath('art/tiles/t.estileset', 'art', 'assets/art')).toBe('assets/art/tiles/t.estileset');+ });+ it('leaves unrelated and prefix-similar paths alone', () => {+ expect(remapAssetPath('other/t.estileset', 'art', 'assets/art')).toBeNull();+ expect(remapAssetPath('artwork/t.png', 'art', 'assets/art')).toBeNull();+ });+});++describe('AssetDocument.rebindPath / syncAssetPaths', () => {+ beforeEach(() => EditorHistory.clear());++ it('an open document follows a rename; dirty state and content survive', () => {+ const doc = new TestDoc('t1');+ doc.open('assets/a.estileset');+ doc.edit('touch', (d) => {+ d.n = 2;+ });+ syncAssetPaths('assets/a.estileset', 'assets/b.estileset');+ expect(doc.filePath).toBe('assets/b.estileset');+ expect(doc.dirty).toBe(true);+ expect(doc.asset).toEqual({ n: 2 });+ expect(EditorHistory.canUndo()).toBe(true); // history untouched by the rebind+ });++ it('a folder move rebinds documents under it', () => {+ const doc = new TestDoc('t2');+ doc.open('art/deep/a.esanim');+ syncAssetPaths('art', 'assets/art');+ expect(doc.filePath).toBe('assets/art/deep/a.esanim');+ });++ it('unaffected and closed documents are left alone', () => {+ const open = new TestDoc('t3');+ open.open('other/x.esfsm');+ const closed = new TestDoc('t4');+ closed.open('assets/a.esfsm');+ closed.close();+ syncAssetPaths('assets/a.esfsm', 'assets/b.esfsm');+ expect(open.filePath).toBe('other/x.esfsm');+ expect(closed.filePath).toBeNull();+ });++ it('bumps the revision so subscribed panels re-read the new path', () => {+ const doc = new TestDoc('t5');+ doc.open('assets/a.estileset');+ const r0 = doc.getRevision();+ syncAssetPaths('assets/a.estileset', 'assets/b.estileset');+ expect(doc.getRevision()).toBeGreaterThan(r0);+ });++ it('remaps the tilemap palette (tilesets list + active path)', () => {+ const asset = createTileset('@uuid:x', 8, 8, 2);+ useTilemapPaint.setState({+ tilesets: [+ { path: 'tiles/ground.estileset', asset, firstId: 1 },+ { path: 'tiles/props.estileset', asset, firstId: 65 },+ ],+ tilesetPath: 'tiles/ground.estileset',+ });+ syncAssetPaths('tiles/ground.estileset', 'tiles/terrain.estileset');+ const s = useTilemapPaint.getState();+ expect(s.tilesets.map((t) => t.path)).toEqual(['tiles/terrain.estileset', 'tiles/props.estileset']);+ expect(s.tilesetPath).toBe('tiles/terrain.estileset');+ expect(s.tilesets[0].firstId).toBe(1); // gid mapping untouched+ });+});diff --git a/desktop/tests/asset-usages.test.ts b/desktop/tests/asset-usages.test.tsnew file mode 100644index 000000000..82b07856e--- /dev/null+++ b/desktop/tests/asset-usages.test.ts@@ -0,0 +1,92 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Usage collection for delete-confirm / Find Usages: the on-disk dep+ * graph merged with the UNSAVED in-memory scene — the graph is built from+ * files, so a reference added since the last save is invisible to it.+ */+import { describe, it, expect } from 'vitest';+import {+ collectAssetUsages,+ valueReferencesAsset,+ type AssetIndexLike,+} from '@/project/assetRefs';++const HERO = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';+const SCENE = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';++const index: AssetIndexLike = {+ entries: [+ { uuid: HERO, path: 'assets/hero.png' },+ { uuid: SCENE, path: 'scenes/main.esscene' },+ ],+ deps: { [SCENE]: [HERO] },+};++describe('valueReferencesAsset', () => {+ const target = { uuid: HERO, path: 'assets/hero.png' };++ it('finds @uuid: refs nested anywhere in the tree (case-insensitive)', () => {+ const data = { entities: [{ components: [{ type: 'Sprite', data: { texture: `@uuid:${HERO.toUpperCase()}` } }] }] };+ expect(valueReferencesAsset(data, target)).toBe(true);+ });++ it('finds bare-uuid and exact-path refs', () => {+ expect(valueReferencesAsset({ frames: [HERO] }, target)).toBe(true);+ expect(valueReferencesAsset({ skeletonPath: 'assets/hero.png' }, target)).toBe(true);+ });++ it('rejects other uuids, other paths, and partial path matches', () => {+ expect(valueReferencesAsset({ texture: `@uuid:${SCENE}` }, target)).toBe(false);+ expect(valueReferencesAsset({ p: 'assets/hero.png.meta' }, target)).toBe(false);+ expect(valueReferencesAsset(null, target)).toBe(false);+ });++ it('matches by path even when the asset is untracked (uuid null)', () => {+ expect(valueReferencesAsset({ p: 'assets/loose.png' }, { uuid: null, path: 'assets/loose.png' })).toBe(true);+ expect(valueReferencesAsset({ p: HERO }, { uuid: null, path: 'assets/loose.png' })).toBe(false);+ });+});++describe('collectAssetUsages', () => {+ const refScene = (uuid: string) => ({+ entities: [{ components: [{ type: 'Sprite', data: { texture: `@uuid:${uuid}` } }] }],+ });++ it('reports disk-graph references without a live scene', () => {+ expect(collectAssetUsages(index, 'assets/hero.png')).toEqual([+ { path: 'scenes/main.esscene', unsaved: false },+ ]);+ });++ it('adds the unsaved in-memory scene when only IT references the asset', () => {+ const noDeps: AssetIndexLike = { ...index, deps: {} };+ const usages = collectAssetUsages(noDeps, 'assets/hero.png', {+ path: 'scenes/other.esscene',+ data: refScene(HERO),+ });+ expect(usages).toEqual([{ path: 'scenes/other.esscene', unsaved: true }]);+ });++ it('reports the untitled unsaved scene as path null', () => {+ const noDeps: AssetIndexLike = { ...index, deps: {} };+ const usages = collectAssetUsages(noDeps, 'assets/hero.png', { path: null, data: refScene(HERO) });+ expect(usages).toEqual([{ path: null, unsaved: true }]);+ });++ it('does not duplicate a scene already reported from disk', () => {+ const usages = collectAssetUsages(index, 'assets/hero.png', {+ path: 'scenes/main.esscene',+ data: refScene(HERO),+ });+ expect(usages).toEqual([{ path: 'scenes/main.esscene', unsaved: false }]);+ });++ it('keeps the disk entry when the live model no longer references (file still does)', () => {+ const usages = collectAssetUsages(index, 'assets/hero.png', {+ path: 'scenes/main.esscene',+ data: refScene(SCENE),+ });+ expect(usages).toEqual([{ path: 'scenes/main.esscene', unsaved: false }]);+ });+});diff --git a/desktop/tests/command-palette.test.ts b/desktop/tests/command-palette.test.tsnew file mode 100644index 000000000..0206cf028--- /dev/null+++ b/desktop/tests/command-palette.test.ts@@ -0,0 +1,92 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Command-palette logic: fuzzy filter/rank and the registry → item+ * projection (keybinding + enablement snapshot). The React shell only+ * renders these results, so the contract lives here.+ */+import { describe, it, expect } from 'vitest';+import { fuzzyScore, filterPalette, paletteItems, paletteText } from '@/commands/palette';+import type { Command } from '@/commands/types';++describe('fuzzyScore', () => {+ it('matches subsequences, rejects non-subsequences', () => {+ expect(fuzzyScore('sv', 'Save Scene')).not.toBeNull();+ expect(fuzzyScore('xyz', 'Save Scene')).toBeNull();+ });++ it('is case-insensitive and matches everything on an empty query', () => {+ expect(fuzzyScore('SAVE', 'save scene')).not.toBeNull();+ expect(fuzzyScore('', 'anything')).toBe(0);+ });++ it('ranks consecutive and word-start matches above scattered ones', () => {+ const consecutive = fuzzyScore('save', 'Save Scene')!;+ const scattered = fuzzyScore('save', 'Set Anchor & Viewport Edge')!;+ expect(consecutive).toBeGreaterThan(scattered);+ });++ it('ignores spaces in the query (VS Code style multi-term typing)', () => {+ expect(fuzzyScore('open proj', 'File: Open Project…')).not.toBeNull();+ });+});++describe('filterPalette', () => {+ const items = [+ { label: 'Undo', category: 'Edit' },+ { label: 'Open Project…', category: 'File' },+ { label: 'Redo', category: 'Edit' },+ { label: 'Play', category: 'Play' },+ ];++ it('empty query keeps registration order', () => {+ expect(filterPalette(items, ' ').map((i) => i.label)).toEqual(['Undo', 'Open Project…', 'Redo', 'Play']);+ });++ it('filters by fuzzy match over "category: label"', () => {+ expect(filterPalette(items, 'file open').map((i) => i.label)).toEqual(['Open Project…']);+ // Both Edit commands tie on the category match → alphabetical by label.+ expect(filterPalette(items, 'edit').map((i) => i.label)).toEqual(['Redo', 'Undo']);+ });++ it('ties broken by label, so the order is deterministic', () => {+ // 'do' scores 'Edit: Undo' and 'Edit: Redo' identically → alphabetical.+ expect(filterPalette(items, 'do').map((i) => i.label)).toEqual(['Redo', 'Undo']);+ });+});++describe('paletteItems', () => {+ const cmds: Command[] = [+ { id: 'a.on', label: 'Enabled', category: 'Test', keybinding: 'mod+k', run: () => {} },+ { id: 'a.off', label: 'Disabled', category: 'Test', run: () => {}, isEnabled: () => false },+ { id: 'a.multi', label: 'Multi', keybinding: ['mod+shift+z', 'mod+y'], run: () => {} },+ ];++ it('snapshots enablement — disabled commands stay listed but flagged', () => {+ const items = paletteItems(cmds, (id) => cmds.find((c) => c.id === id)?.keybinding);+ expect(items.map((i) => [i.id, i.enabled])).toEqual([+ ['a.on', true],+ ['a.off', false],+ ['a.multi', true],+ ]);+ });++ it('resolves the effective keybinding (first chord of a multi-binding)', () => {+ const items = paletteItems(cmds, (id) => cmds.find((c) => c.id === id)?.keybinding);+ expect(items.find((i) => i.id === 'a.on')?.keybinding).toBe('mod+k');+ expect(items.find((i) => i.id === 'a.multi')?.keybinding).toBe('mod+shift+z');+ expect(items.find((i) => i.id === 'a.off')?.keybinding).toBeUndefined();+ });++ it('honors a user override passed through keybindingFor', () => {+ const items = paletteItems(cmds, (id) => (id === 'a.on' ? 'mod+alt+k' : undefined));+ expect(items.find((i) => i.id === 'a.on')?.keybinding).toBe('mod+alt+k');+ });+});++describe('paletteText', () => {+ it('is category-qualified like VS Code', () => {+ expect(paletteText({ label: 'Undo', category: 'Edit' })).toBe('Edit: Undo');+ expect(paletteText({ label: 'Undo' })).toBe('Undo');+ });+});diff --git a/desktop/tests/project-fs.test.ts b/desktop/tests/project-fs.test.tsindex 4ac915ac0..3eacdd082 100644--- a/desktop/tests/project-fs.test.ts+++ b/desktop/tests/project-fs.test.ts@@ -18,6 +18,8 @@ import {mkdirInRoot,duplicateInRoot,statInRoot,+ snapshotForTrash,+ restoreTrashed,} from '../electron/projectFs';import { isIgnoredPath } from '../electron/projectWatcher';import { importAssets, createAsset } from '../electron/importAssets';@@ -170,6 +172,51 @@ describe('duplicateInRoot', () => {});});+describe('trash undo (snapshotForTrash / restoreTrashed)', () => {+ const rmAt = (rel: string) => rmSync(path.join(root, rel), { force: true, recursive: true });++ it('restores a deleted file + .meta with the SAME uuid (refs stay valid)', async () => {+ const token = await snapshotForTrash(root, 'assets/hero.png');+ rmAt('assets/hero.png'); // stands in for shell.trashItem+ rmAt('assets/hero.png.meta');+ await restoreTrashed(root, 'assets/hero.png', token);+ expect(read('assets/hero.png')).toBe('PNG');+ expect(JSON.parse(read('assets/hero.png.meta')).uuid).toBe('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa');+ });++ it('restores a folder recursively, sidecars included', async () => {+ mkdirSync(path.join(root, 'assets', 'pack'));+ writeFileSync(path.join(root, 'assets', 'pack', 'a.png'), 'A');+ writeFileSync(path.join(root, 'assets', 'pack', 'a.png.meta'), meta('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'));+ const token = await snapshotForTrash(root, 'assets/pack');+ rmAt('assets/pack');+ await restoreTrashed(root, 'assets/pack', token);+ expect(read('assets/pack/a.png')).toBe('A');+ expect(JSON.parse(read('assets/pack/a.png.meta')).uuid).toBe('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb');+ });++ it('refuses to clobber a path re-taken since the delete', async () => {+ const token = await snapshotForTrash(root, 'assets/hero.png');+ // The path was re-taken (e.g. a new import with the same name).+ await expect(restoreTrashed(root, 'assets/hero.png', token)).rejects.toThrow(/already exists/);+ expect(read('assets/hero.png')).toBe('PNG'); // untouched+ });++ it('a snapshot restores only once; malformed tokens are rejected', async () => {+ const token = await snapshotForTrash(root, 'assets/hero.png');+ rmAt('assets/hero.png');+ rmAt('assets/hero.png.meta');+ await restoreTrashed(root, 'assets/hero.png', token);+ rmAt('assets/hero.png');+ await expect(restoreTrashed(root, 'assets/hero.png', token)).rejects.toThrow(/nothing to restore/);+ await expect(restoreTrashed(root, 'assets/hero.png', '../../etc')).rejects.toThrow(/invalid restore token/);+ });++ it('snapshotting a missing path fails up front (no empty undo)', async () => {+ await expect(snapshotForTrash(root, 'assets/ghost.png')).rejects.toThrow(/does not exist/);+ });+});+describe('createAsset', () => {it('writes the file + a .meta (fresh uuid + type) and dedups the name', async () => {const p1 = await createAsset(root, 'assets', 'scene.esscene', '{"v":"1.0"}', 'scene');