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): UE5 alignment, command registry, engine-anchored selection, editor camera
esengine786331b091e0
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex e98a5c3fd..6f408dec4 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -3,61 +3,29 @@ import { MenuBar } from '@/layout/MenuBar';import { Toolbar } from '@/layout/Toolbar';import { StatusBar } from '@/layout/StatusBar';import { DockLayout } from '@/layout/DockLayout';-import { EditorHistory } from '@/engine/EditorHistory';-import { SceneCommands } from '@/engine/SceneCommands';import { EngineHost } from '@/engine/EngineHost';-import { ProjectStore } from '@/project/ProjectStore';import { Launcher } from '@/launcher/Launcher';import { Toaster } from '@/components/Toaster';import { useEditorStore } from '@/store/editorStore';+import { useSelection } from '@/store/selectionStore';+import { commands } from '@/commands';// The editor shell: fixed menu + toolbar on top, dockable workspace in the// middle, status strip at the bottom.export function App() {- // Global editor shortcuts — skipped while a text field is focused so typing,- // native text undo, and backspace-to-delete-text aren't hijacked.+ // Global keymap: every shortcut is declared on its Command (single source).+ // Skipped while a text field is focused so typing, native text undo, and+ // backspace-to-delete-text aren't hijacked.useEffect(() => {const onKey = (e: KeyboardEvent) => {const el = document.activeElement as HTMLElement | null;if (el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable)) {return;}- const store = useEditorStore.getState();- const sel = store.selectedId;- const mod = e.metaKey || e.ctrlKey;- const key = e.key.toLowerCase();-- if (mod && key === 'o') {- // Open a project folder; loads its scene into the live world (E7-3).- e.preventDefault();- void ProjectStore.openViaDialog().then((ok) => {- if (ok) store.select(null); // entity ids change on load — drop stale selection- });- } else if (mod && key === 's') {- // Save (E7-4): ⌘S overwrites the current scene (lossless, JSON-first);- // ⇧⌘S is Save-As. ⌘S falls back to Save-As when there's no current scene.- e.preventDefault();- if (e.shiftKey) void ProjectStore.saveAsViaDialog();- else void ProjectStore.save().catch(() => ProjectStore.saveAsViaDialog());- } else if (mod && key === 'z' && !e.shiftKey) {- e.preventDefault();- EditorHistory.undo();- } else if (mod && ((key === 'z' && e.shiftKey) || key === 'y')) {- e.preventDefault();- EditorHistory.redo();- } else if (mod && key === 'd') {- e.preventDefault();- if (sel != null) {- const dup = SceneCommands.duplicateEntity(sel);- if (dup != null) store.select(dup);- }- } else if (e.key === 'Delete' || e.key === 'Backspace') {+ const cmd = commands.forEvent(e);+ if (cmd) {e.preventDefault();- const ids = [...store.selectedIds];- if (ids.length) {- ids.forEach((id) => SceneCommands.deleteEntity(id));- store.select(null);- }+ cmd.run();}};window.addEventListener('keydown', onKey);@@ -72,7 +40,7 @@ export function App() {const isPaused = useEditorStore((s) => s.isPaused);useEffect(() => {const restored = EngineHost.setRunMode(isPlaying, isPaused);- if (restored) useEditorStore.getState().select(null);+ if (restored) useSelection.getState().select(null);}, [isPlaying, isPaused]);// The editor opens on the launcher (project browser); the shell + engine mountdiff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsnew file mode 100644index 000000000..26cab3426--- /dev/null+++ b/desktop/src/commands/editorCommands.ts@@ -0,0 +1,181 @@+/**+ * @file editorCommands.ts+ * @brief Registers every editor command. This is the ONE place each action,+ * its enablement, and its keybinding are wired — App's keymap, the menu+ * bar, the toolbar, and the viewport toolbar all dispatch through these+ * ids rather than re-implementing the action + disabled logic per site.+ * Importing this module performs the registration (side effect).+ */+import { commands } from './registry';+import { ProjectStore } from '@/project/ProjectStore';+import { EditorHistory } from '@/engine/EditorHistory';+import { SceneCommands } from '@/engine/SceneCommands';+import { ViewportController } from '@/engine/ViewportController';+import { useEditorStore } from '@/store/editorStore';+import { useSelection } from '@/store/selectionStore';+import { Toasts } from '@/store/Toasts';+import type { ToolMode } from '@/types';++const editor = () => useEditorStore.getState();+const sel = () => useSelection.getState();+const tool = (mode: ToolMode) => () => editor().setTool(mode);++// — File / project —+commands.register({+ id: 'project.open',+ label: 'Open Project…',+ category: 'File',+ keybinding: 'mod+o',+ run: () => void ProjectStore.openViaDialog().then((ok) => ok && sel().select(null)),+});+commands.register({+ id: 'project.save',+ label: 'Save Scene',+ category: 'File',+ keybinding: 'mod+s',+ isEnabled: () => !!ProjectStore.getSnapshot(),+ run: () => void ProjectStore.save().catch(() => ProjectStore.saveAsViaDialog()),+});+commands.register({+ id: 'project.saveAs',+ label: 'Save Scene As…',+ category: 'File',+ keybinding: 'mod+shift+s',+ isEnabled: () => !!ProjectStore.getSnapshot(),+ run: () => void ProjectStore.saveAsViaDialog(),+});+commands.register({+ id: 'project.close',+ label: 'Close Project',+ category: 'File',+ isEnabled: () => !!ProjectStore.getSnapshot(),+ run: () => editor().openLauncher(),+});++// — Edit / history —+commands.register({+ id: 'edit.undo',+ label: 'Undo',+ category: 'Edit',+ keybinding: 'mod+z',+ isEnabled: () => EditorHistory.canUndo(),+ run: () => EditorHistory.undo(),+});+commands.register({+ id: 'edit.redo',+ label: 'Redo',+ category: 'Edit',+ keybinding: ['mod+shift+z', 'mod+y'],+ isEnabled: () => EditorHistory.canRedo(),+ run: () => EditorHistory.redo(),+});++// — Entity —+commands.register({+ id: 'entity.add',+ label: 'Add Entity',+ category: 'Entity',+ run: () => {+ const e = SceneCommands.addEntity();+ if (e != null) sel().select(e);+ },+});+commands.register({+ id: 'entity.duplicate',+ label: 'Duplicate',+ category: 'Entity',+ keybinding: 'mod+d',+ isEnabled: () => sel().selectedId != null,+ run: () => {+ const id = sel().selectedId;+ if (id == null) return;+ const dup = SceneCommands.duplicateEntity(id);+ if (dup != null) sel().select(dup);+ },+});+commands.register({+ id: 'entity.delete',+ label: 'Delete',+ category: 'Entity',+ keybinding: ['delete', 'backspace'],+ isEnabled: () => sel().selectedIds.size > 0,+ // Despawn self-heals the selection (SelectionStore) — no manual deselect.+ run: () => [...sel().selectedIds].forEach((id) => SceneCommands.deleteEntity(id)),+});+commands.register({+ id: 'entity.deselect',+ label: 'Deselect',+ category: 'Entity',+ isEnabled: () => sel().selectedId != null,+ run: () => sel().select(null),+});++// — Transform tools —+commands.register({ id: 'tool.select', label: 'Select Tool', category: 'Tools', keybinding: 'q', run: tool('select') });+commands.register({ id: 'tool.move', label: 'Move Tool', category: 'Tools', keybinding: 'w', run: tool('move') });+commands.register({ id: 'tool.rotate', label: 'Rotate Tool', category: 'Tools', keybinding: 'e', run: tool('rotate') });+commands.register({ id: 'tool.scale', label: 'Scale Tool', category: 'Tools', keybinding: 'r', run: tool('scale') });++// — Viewport / view —+commands.register({+ id: 'view.frameSelected',+ label: 'Frame Selected',+ category: 'View',+ keybinding: 'f',+ isEnabled: () => sel().selectedId != null,+ run: () => {+ const id = sel().selectedId;+ if (id != null) ViewportController.frameEntity(id);+ },+});+commands.register({+ id: 'view.toggleGrid',+ label: 'Show Grid',+ category: 'View',+ isChecked: () => editor().showGrid,+ run: () => editor().toggleGrid(),+});+commands.register({+ id: 'view.toggleGizmos',+ label: 'Show Gizmos',+ category: 'View',+ isChecked: () => editor().showGizmos,+ run: () => editor().toggleGizmos(),+});+commands.register({+ id: 'view.toggleSnapping',+ label: 'Snapping',+ category: 'View',+ isChecked: () => editor().snapping,+ run: () => editor().toggleSnapping(),+});++// — Play —+commands.register({+ id: 'play.toggle',+ label: 'Play',+ category: 'Play',+ keybinding: 'f5',+ run: () => editor().togglePlay(),+});+commands.register({+ id: 'play.stop',+ label: 'Stop',+ category: 'Play',+ keybinding: 'escape',+ isEnabled: () => editor().isPlaying,+ run: () => editor().stop(),+});++// — Build —+commands.register({+ id: 'build.scripts',+ label: 'Build Project Scripts',+ category: 'Build',+ isEnabled: () => !!ProjectStore.getSnapshot(),+ run: () =>+ void window.estella?.project+ ?.buildScripts?.()+ .then(() => Toasts.push('Built project scripts', 'success'))+ .catch(() => Toasts.push('Build failed', 'error')),+});diff --git a/desktop/src/commands/index.ts b/desktop/src/commands/index.tsnew file mode 100644index 000000000..0e61a5655--- /dev/null+++ b/desktop/src/commands/index.ts@@ -0,0 +1,11 @@+/**+ * @file index.ts+ * @brief Public entry for the editor command system. Importing it registers+ * every command (via ./editorCommands side effect) and re-exports the+ * registry + helpers consumers need.+ */+import './editorCommands';++export { commands } from './registry';+export { formatKeybinding } from './keybinding';+export type { Command, Keybinding } from './types';diff --git a/desktop/src/commands/keybinding.ts b/desktop/src/commands/keybinding.tsnew file mode 100644index 000000000..5d1f656ca--- /dev/null+++ b/desktop/src/commands/keybinding.ts@@ -0,0 +1,101 @@+/**+ * @file keybinding.ts+ * @brief Keybinding chord parsing, normalization, event-matching, and display+ * formatting — so a command's `keybinding` string is the single source+ * for both global key dispatch and the shortcut hint shown in menus.+ *+ * Chord grammar: '+'-joined, case-insensitive tokens — modifiers `mod`/`alt`/+ * `shift` plus one key (`s`, `z`, `f5`, `delete`, `escape`, …). `mod` is the+ * platform command key: ⌘ on macOS, Ctrl elsewhere.+ */+import type { Keybinding } from './types';++const IS_MAC =+ typeof navigator !== 'undefined' && /mac/i.test(navigator.platform || navigator.userAgent || '');++const SPECIAL_KEYS: Record<string, string> = {+ ' ': 'space',+ spacebar: 'space',+ esc: 'escape',+ del: 'delete',+ arrowup: 'up',+ arrowdown: 'down',+ arrowleft: 'left',+ arrowright: 'right',+};++function normalizeKey(key: string): string {+ const k = key.toLowerCase();+ return SPECIAL_KEYS[k] ?? k;+}++/** Canonical chord for a key event: e.g. ⇧⌘S → 'mod+shift+s'. */+export function eventToChord(e: KeyboardEvent): string {+ const parts: string[] = [];+ if (e.metaKey || e.ctrlKey) parts.push('mod');+ if (e.altKey) parts.push('alt');+ if (e.shiftKey) parts.push('shift');+ parts.push(normalizeKey(e.key));+ return parts.join('+');+}++/** Canonical chord for a binding string: tokens reordered to mod+alt+shift+key. */+export function normalizeChord(kb: string): string {+ let mod = false;+ let alt = false;+ let shift = false;+ let key = '';+ for (const raw of kb.toLowerCase().split('+')) {+ const t = raw.trim();+ if (t === 'mod' || t === 'cmd' || t === 'command' || t === 'ctrl' || t === 'control' || t === 'meta')+ mod = true;+ else if (t === 'alt' || t === 'option') alt = true;+ else if (t === 'shift') shift = true;+ else if (t) key = normalizeKey(t);+ }+ const parts: string[] = [];+ if (mod) parts.push('mod');+ if (alt) parts.push('alt');+ if (shift) parts.push('shift');+ parts.push(key);+ return parts.join('+');+}++/** Does a key event match any chord of a binding? */+export function chordMatches(e: KeyboardEvent, kb: Keybinding): boolean {+ const chord = eventToChord(e);+ const list = Array.isArray(kb) ? kb : [kb];+ return list.some((k) => normalizeChord(k) === chord);+}++function displayKey(key: string): string {+ const map: Record<string, string> = {+ delete: IS_MAC ? '⌫' : 'Del',+ backspace: IS_MAC ? '⌫' : 'Backspace',+ escape: 'Esc',+ space: 'Space',+ up: '↑',+ down: '↓',+ left: '←',+ right: '→',+ };+ return map[key] ?? key.toUpperCase();+}++/** Human-readable hint for a binding (first chord), e.g. 'mod+shift+s' → '⇧⌘S'. */+export function formatKeybinding(kb: Keybinding): string {+ const first = Array.isArray(kb) ? kb[0] : kb;+ const tokens = normalizeChord(first).split('+');+ const key = tokens.pop() ?? '';+ const mod = tokens.includes('mod');+ const alt = tokens.includes('alt');+ const shift = tokens.includes('shift');+ const k = displayKey(key);+ if (IS_MAC) return `${alt ? '⌥' : ''}${shift ? '⇧' : ''}${mod ? '⌘' : ''}${k}`;+ const parts: string[] = [];+ if (mod) parts.push('Ctrl');+ if (alt) parts.push('Alt');+ if (shift) parts.push('Shift');+ parts.push(k);+ return parts.join('+');+}diff --git a/desktop/src/commands/registry.ts b/desktop/src/commands/registry.tsnew file mode 100644index 000000000..8ffefaaa0--- /dev/null+++ b/desktop/src/commands/registry.ts@@ -0,0 +1,51 @@+/**+ * @file registry.ts+ * @brief The editor command registry — one map of id → Command, plus the+ * dispatch helpers every consumer shares: run by id, query enablement /+ * checked state, resolve the command bound to a key event. Holds no+ * reactive state of its own; enablement is derived on demand from the+ * domain stores the UI already subscribes to.+ */+import type { Command } from './types';+import { chordMatches } from './keybinding';++class CommandRegistry {+ private readonly map = new Map<string, Command>();++ register(cmd: Command): void {+ this.map.set(cmd.id, cmd);+ }++ get(id: string): Command | undefined {+ return this.map.get(id);+ }++ all(): Command[] {+ return [...this.map.values()];+ }++ isEnabled(id: string): boolean {+ const c = this.map.get(id);+ return c ? c.isEnabled?.() ?? true : false;+ }++ isChecked(id: string): boolean | undefined {+ return this.map.get(id)?.isChecked?.();+ }++ /** Run a command by id (no-op if missing or currently disabled). */+ run(id: string): void {+ const c = this.map.get(id);+ if (c && (c.isEnabled?.() ?? true)) c.run();+ }++ /** The enabled command bound to a key event, if any. */+ forEvent(e: KeyboardEvent): Command | undefined {+ for (const c of this.map.values()) {+ if (c.keybinding && chordMatches(e, c.keybinding) && (c.isEnabled?.() ?? true)) return c;+ }+ return undefined;+ }+}++export const commands = new CommandRegistry();diff --git a/desktop/src/commands/types.ts b/desktop/src/commands/types.tsnew file mode 100644index 000000000..2c2c0ae88--- /dev/null+++ b/desktop/src/commands/types.ts@@ -0,0 +1,29 @@+/**+ * @file types.ts+ * @brief The Command descriptor — the single declarative unit behind every+ * editor action. Menus, the toolbar, keyboard shortcuts, and (later) a+ * command palette all render/run from these, so an action is defined+ * and gated in exactly one place.+ */++/** A keybinding chord (e.g. 'mod+s', 'mod+shift+z', 'delete', 'q'). `mod` = ⌘ on+ * macOS, Ctrl elsewhere. A command may bind several chords (e.g. redo). */+export type Keybinding = string | string[];++export interface Command {+ /** Stable dotted id, e.g. 'edit.undo', 'entity.delete'. */+ id: string;+ /** Human label, shown in menus / palette. */+ label: string;+ /** Grouping for the (future) command palette + menu sections. */+ category?: string;+ /** Chord(s) that trigger this command globally. */+ keybinding?: Keybinding;+ /** Perform the action. */+ run: () => void;+ /** Enablement predicate (default: always enabled). Gates menus, the toolbar,+ * and keyboard dispatch alike — one source of truth. */+ isEnabled?: () => boolean;+ /** For toggle commands: current on/off state (drives the menu checkmark). */+ isChecked?: () => boolean;+}diff --git a/desktop/src/components/AddComponentMenu.tsx b/desktop/src/components/AddComponentMenu.tsxnew file mode 100644index 000000000..6e72cf031--- /dev/null+++ b/desktop/src/components/AddComponentMenu.tsx@@ -0,0 +1,185 @@+/**+ * @file AddComponentMenu.tsx+ * @brief UE5-style "Add Component" picker — a portaled popover with a search+ * box, category-grouped entries, per-component icons, and full keyboard+ * navigation (type to filter, ↑/↓ to move, Enter to add, Esc to close).+ * Replaces the flat ContextMenu list the inspector used before.+ */+import { useEffect, useMemo, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { Search } from 'lucide-react';+import { ComponentIcon } from '@/components/icons';+import { CATEGORY_ORDER } from '@/engine/schema';++export interface AddComponentEntry {+ name: string;+ label: string;+ category: string;+}++const WIDTH = 248;+const MAX_H = 380;++function groupByCategory(entries: AddComponentEntry[]) {+ const byCat = new Map<string, AddComponentEntry[]>();+ for (const e of entries) {+ const list = byCat.get(e.category) ?? [];+ list.push(e);+ byCat.set(e.category, list);+ }+ const groups: { category: string; items: AddComponentEntry[] }[] = [];+ for (const cat of CATEGORY_ORDER) {+ const items = byCat.get(cat);+ if (items?.length) groups.push({ category: cat, items });+ }+ // Any category not in the canonical order (defensive) trails at the end.+ for (const [cat, items] of byCat) {+ if (!CATEGORY_ORDER.includes(cat as (typeof CATEGORY_ORDER)[number])) {+ groups.push({ category: cat, items });+ }+ }+ return groups;+}++export function AddComponentMenu({+ x,+ y,+ entries,+ onAdd,+ onClose,+}: {+ x: number;+ y: number;+ entries: AddComponentEntry[];+ onAdd: (name: string) => void;+ onClose: () => void;+}) {+ const [query, setQuery] = useState('');+ const [active, setActive] = useState(0);+ const inputRef = useRef<HTMLInputElement>(null);+ const activeRef = useRef<HTMLButtonElement>(null);++ // Focus the search on open (type-to-filter immediately, like UE5).+ useEffect(() => {+ inputRef.current?.focus();+ }, []);++ // Dismiss on an outside press (clicks inside stopPropagation below) or Esc.+ // Deliberately NOT on scroll: the picker owns a scrollable list (the wheel+ // scrolls it), and the popover is position:fixed so it stays put even if the+ // inspector behind scrolls — UE5 keeps the dropdown open while you scroll it.+ useEffect(() => {+ const close = () => onClose();+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') onClose();+ };+ window.addEventListener('mousedown', close);+ window.addEventListener('keydown', onKey);+ return () => {+ window.removeEventListener('mousedown', close);+ window.removeEventListener('keydown', onKey);+ };+ }, [onClose]);++ const filtered = useMemo(() => {+ const q = query.trim().toLowerCase();+ if (!q) return entries;+ return entries.filter(+ (e) => e.label.toLowerCase().includes(q) || e.name.toLowerCase().includes(q),+ );+ }, [entries, query]);++ const groups = useMemo(() => groupByCategory(filtered), [filtered]);+ const flat = useMemo(() => groups.flatMap((g) => g.items), [groups]);++ // Reset the highlight whenever the result set changes.+ useEffect(() => {+ setActive(0);+ }, [query]);+ useEffect(() => {+ activeRef.current?.scrollIntoView({ block: 'nearest' });+ }, [active]);++ const commit = (name: string) => {+ onAdd(name);+ onClose();+ };++ const onKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.preventDefault();+ onClose();+ } else if (e.key === 'ArrowDown') {+ e.preventDefault();+ setActive((a) => Math.min(flat.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 = flat[active];+ if (item) commit(item.name);+ }+ };++ // Keep the popover on-screen near the trigger.+ const left = Math.max(8, Math.min(x, window.innerWidth - WIDTH - 8));+ const top = Math.max(8, Math.min(y, window.innerHeight - MAX_H - 8));++ return createPortal(+ <div+ className="addcomp"+ role="menu"+ style={{ left, top, width: WIDTH, maxHeight: MAX_H }}+ onMouseDown={(e) => e.stopPropagation()}+ >+ <div className="addcomp__search">+ <Search size={13} strokeWidth={1.9} />+ <input+ ref={inputRef}+ className="addcomp__input"+ placeholder="Search Components"+ value={query}+ spellCheck={false}+ onChange={(e) => setQuery(e.target.value)}+ onKeyDown={onKeyDown}+ />+ </div>++ <div className="addcomp__list">+ {flat.length === 0 ? (+ <p className="addcomp__empty">+ {entries.length === 0 ? 'All components added' : 'No matching components'}+ </p>+ ) : (+ groups.map((g) => (+ <div key={g.category} className="addcomp__group">+ <div className="addcomp__cat">{g.category}</div>+ {g.items.map((it) => {+ const idx = flat.indexOf(it);+ const isActive = idx === active;+ return (+ <button+ key={it.name}+ ref={isActive ? activeRef : undefined}+ type="button"+ role="menuitem"+ className={`addcomp__item${isActive ? ' is-active' : ''}`}+ onMouseEnter={() => setActive(idx)}+ onClick={() => commit(it.name)}+ >+ <span className="addcomp__icon">+ <ComponentIcon name={it.name} />+ </span>+ <span className="addcomp__label">{it.label}</span>+ </button>+ );+ })}+ </div>+ ))+ )}+ </div>+ </div>,+ document.body,+ );+}diff --git a/desktop/src/components/icons.tsx b/desktop/src/components/icons.tsxindex 89eb631e2..d00f42d93 100644--- a/desktop/src/components/icons.tsx+++ b/desktop/src/components/icons.tsx@@ -16,6 +16,12 @@ import {Blend,FileCode2,File,+ Type,+ Grid3x3,+ Sparkles,+ Box,+ Hexagon,+ Link2,type LucideIcon,} from 'lucide-react';import type { NodeKind, AssetType } from '@/types';@@ -38,17 +44,18 @@ export function NodeIcon({ kind, size = 14 }: { kind: NodeKind; size?: number })return <Glyph size={size} strokeWidth={1.75} />;}-// Asset type → glyph + accent tint, so the content browser is scannable by color.+// Asset type → glyph + muted type tint. Desaturated (vs candy colors) so the+// content browser stays scannable by type but reads as a professional tool.const ASSET_ICON: Record<AssetType, { icon: LucideIcon; tint: string }> = {folder: { icon: Folder, tint: 'var(--star)' },- scene: { icon: Film, tint: '#ff8fa3' },- sprite: { icon: Image, tint: '#6fd3ff' },- texture: { icon: FileImage, tint: '#6fd3ff' },- spine: { icon: PersonStanding, tint: '#b69bff' },- audio: { icon: Music, tint: '#43d39e' },- prefab: { icon: Component, tint: '#ffb454' },- material: { icon: Blend, tint: '#ff9d6f' },- script: { icon: FileCode2, tint: '#9fb2d6' },+ scene: { icon: Film, tint: '#c98a93' },+ sprite: { icon: Image, tint: '#7fa6c4' },+ texture: { icon: FileImage, tint: '#7fa6c4' },+ spine: { icon: PersonStanding, tint: '#9b8fc0' },+ audio: { icon: Music, tint: '#7faf9c' },+ prefab: { icon: Component, tint: '#c2a274' },+ material: { icon: Blend, tint: '#c0917a' },+ script: { icon: FileCode2, tint: '#93a3bf' },file: { icon: File, tint: 'var(--text-dim)' },};@@ -60,3 +67,35 @@ export function AssetIcon({ type, size = 22 }: { type: AssetType; size?: numberexport function assetTint(type: AssetType): string {return ASSET_ICON[type].tint;}++// Component (by registry name) → glyph, for the Add-Component picker. Known+// builtins are mapped; the rest fall back by name heuristic, then a generic+// component glyph. Inherits currentColor so callers control the tint.+const COMPONENT_ICON: Record<string, LucideIcon> = {+ Camera,+ Sprite: Image,+ ShapeRenderer: Square,+ BitmapText: Type,+ TilemapLayer: Grid3x3,+ ParticleEmitter: Sparkles,+ Canvas: LayoutPanelTop,+ SpineAnimation: PersonStanding,+ RigidBody: Box,+};++function componentGlyph(name: string): LucideIcon {+ const hit = COMPONENT_ICON[name];+ if (hit) return hit;+ if (/Collider$/.test(name)) return Hexagon;+ if (/Joint$/.test(name)) return Link2;+ if (/Audio|Sound/.test(name)) return Volume2;+ if (/Light/.test(name)) return Lightbulb;+ if (/Particle|Emitter|Trail/.test(name)) return Sparkles;+ if (/Text|Font|Label/.test(name)) return Type;+ return Component;+}++export function ComponentIcon({ name, size = 14 }: { name: string; size?: number }) {+ const Glyph = componentGlyph(name);+ return <Glyph size={size} strokeWidth={1.75} />;+}diff --git a/desktop/src/engine/EditorHistory.ts b/desktop/src/engine/EditorHistory.tsindex 74cfaafb8..c27b3d598 100644--- a/desktop/src/engine/EditorHistory.ts+++ b/desktop/src/engine/EditorHistory.ts@@ -1,3 +1,4 @@+import { createStore } from 'zustand/vanilla';import { TransactionManager } from 'esengine';/**@@ -10,8 +11,7 @@ import { TransactionManager } from 'esengine';*/class EditorHistoryImpl {private readonly tm = new TransactionManager({ historyLimit: 200 });- private version = 0;- private readonly listeners = new Set<() => void>();+ private readonly store = createStore<{ version: number }>(() => ({ version: 0 }));/** Register an already-applied mutation as one undo step (forward NOT run). */record(label: string, forward: () => void, reverse: () => void) {@@ -53,14 +53,10 @@ class EditorHistoryImpl {}private bump() {- this.version += 1;- for (const l of this.listeners) l();+ this.store.setState((s) => ({ version: s.version + 1 }));}- subscribe = (fn: () => void): (() => void) => {- this.listeners.add(fn);- return () => this.listeners.delete(fn);- };- getVersion = (): number => this.version;+ subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);+ getVersion = (): number => this.store.getState().version;}export const EditorHistory = new EditorHistoryImpl();diff --git a/desktop/src/engine/EngineHost.ts b/desktop/src/engine/EngineHost.tsindex f497831be..b16480d8e 100644--- a/desktop/src/engine/EngineHost.ts+++ b/desktop/src/engine/EngineHost.ts@@ -1,3 +1,4 @@+import { createStore } from 'zustand/vanilla';import {createWebApp,defineSystem,@@ -6,6 +7,7 @@ import {Transform,Sprite,Camera,+ EditorView,setEditorMode,setPlayMode,serializeScene,@@ -45,8 +47,7 @@ class EngineHostImpl {private booted = false;private resizeObserver: ResizeObserver | null = null;- private snapshot: EngineSnapshot = { status: 'idle', error: null };- private readonly listeners = new Set<() => void>();+ private readonly statusStore = createStore<EngineSnapshot>(() => ({ status: 'idle', error: null }));// Play-state isolation: the scene captured when entering play, restored on stop.private playing_ = false;@@ -88,16 +89,12 @@ class EngineHostImpl {}// — Status as an external store (for useSyncExternalStore) —- subscribe = (fn: () => void): (() => void) => {- this.listeners.add(fn);- return () => this.listeners.delete(fn);- };- getSnapshot = (): EngineSnapshot => this.snapshot;+ subscribe = (fn: () => void): (() => void) => this.statusStore.subscribe(fn);+ getSnapshot = (): EngineSnapshot => this.statusStore.getState();private setStatus(status: EngineStatus, error: string | null = null) {- this.snapshot = { status, error };+ this.statusStore.setState({ status, error });window.estella?.reportEngineStatus?.(error ? `${status}: ${error}` : status);- this.listeners.forEach((l) => l());}private ensureCanvas(): HTMLCanvasElement {@@ -157,11 +154,54 @@ class EngineHostImpl {}this.playing_ = isPlaying;+ // The editor camera shows in edit mode; entering play switches the viewport+ // to the scene's game camera (the real "Game" view). Toggling `active` keeps+ // the editor view's pan/zoom intact across play→stop.+ const view = this.getResource(EditorView);+ if (view) view.active = !isPlaying;+setPlayMode(isPlaying);app.setPaused(isPlaying && isPaused);return restored;}+ /**+ * Seed the editor camera from the scene's active camera and activate it for+ * edit mode. Called after a scene loads; navigation thereafter is independent+ * of the scene — the editor view never writes back to a scene Camera entity,+ * so panning/zooming the viewport never dirties or moves the game camera.+ */+ syncEditorViewToScene(): void {+ const view = this.getResource(EditorView);+ if (!view) return;+ const cam = this.readSceneCamera();+ if (cam) {+ view.x = cam.x;+ view.y = cam.y;+ view.orthoSize = cam.orthoSize;+ }+ view.active = !this.playing_;+ }++ /** The active (or first) scene camera's center + ortho half-height, for seeding. */+ private readSceneCamera(): { x: number; y: number; orthoSize: number } | null {+ const world = this.world;+ if (!world) return null;+ let chosen: number | null = null;+ for (const e of world.getAllEntities()) {+ if (!world.has(e, Camera) || !world.has(e, Transform)) continue;+ if (chosen == null) chosen = e;+ if ((world.get(e, Camera) as { isActive?: boolean }).isActive) {+ chosen = e;+ break;+ }+ }+ if (chosen == null) return null;+ const t = world.get(chosen, Transform);+ const c = world.get(chosen, Camera) as { orthoSize?: number };+ return { x: t.position.x, y: t.position.y, orthoSize: c.orthoSize ?? 360 };+ }+// — Headless / automation drive (see docs/REARCH_EDITOR_AUTOMATION.md) —// The live editor lets the engine drive its own rAF loop (app.run()); a// headless render host or a verification/automation driver instead advances@@ -318,6 +358,7 @@ class EngineHostImpl {console.warn('[engine] scene load failed; using placeholder', err);this.setupScene(app);}+ this.syncEditorViewToScene();}// Report ready before run() (the DOM path) in case the loop never resolves.@@ -331,7 +372,7 @@ class EngineHostImpl {private swallowUnwind(err: unknown) {const msg = err instanceof Error ? err.message : String(err);if (err === 'unwind' || msg.includes('unwind')) {- if (this.snapshot.status !== 'ready') this.setStatus('ready');+ if (this.statusStore.getState().status !== 'ready') this.setStatus('ready');return;}console.error('[engine] boot failed', err);diff --git a/desktop/src/engine/SceneStore.ts b/desktop/src/engine/SceneStore.tsindex ac8949318..73c1e6e48 100644--- a/desktop/src/engine/SceneStore.ts+++ b/desktop/src/engine/SceneStore.ts@@ -1,3 +1,4 @@+import { createStore } from 'zustand/vanilla';import { getDefaultContext } from 'esengine';import type { EditorBridge } from 'esengine';@@ -14,10 +15,12 @@ import type { EditorBridge } from 'esengine';* - `revision` bumps on any change, incl. component-data edits (inspector values)*/class SceneStoreImpl {- private revision = 1;- private structureRevision = 1;private installed = false;- private readonly listeners = new Set<() => void>();+ private readonly store = createStore<{ revision: number; structureRevision: number }>(() => ({+ revision: 1,+ structureRevision: 1,+ }));+ private readonly despawnListeners = new Set<(id: number) => void>();/** Register the bridge on the engine's default context. Idempotent. */install() {@@ -26,7 +29,13 @@ class SceneStoreImpl {const bridge: EditorBridge = {registerComponent: () => {},onEntitySpawned: () => this.bump(true),- onEntityDespawned: () => this.bump(true),+ onEntityDespawned: (e) => {+ // Carry the dead id so consumers (SelectionStore) can drop references+ // precisely. Fires BEFORE the entity is fully removed, so re-validating+ // by world.valid() here would race — dropping by id is exact.+ this.despawnListeners.forEach((l) => l(e as unknown as number));+ this.bump(true);+ },onComponentAdded: () => this.bump(true),onComponentRemoved: () => this.bump(true),onParentChanged: () => this.bump(true),@@ -35,18 +44,22 @@ class SceneStoreImpl {getDefaultContext().editorBridge = bridge;}+ /** Subscribe to entity despawns by id (the self-healing hook for selection). */+ onEntityDespawn(fn: (id: number) => void): () => void {+ this.despawnListeners.add(fn);+ return () => this.despawnListeners.delete(fn);+ }+private bump(structural: boolean) {- this.revision += 1;- if (structural) this.structureRevision += 1;- for (const l of this.listeners) l();+ this.store.setState((s) => ({+ revision: s.revision + 1,+ structureRevision: structural ? s.structureRevision + 1 : s.structureRevision,+ }));}- subscribe = (fn: () => void): (() => void) => {- this.listeners.add(fn);- return () => this.listeners.delete(fn);- };- getRevision = (): number => this.revision;- getStructureRevision = (): number => this.structureRevision;+ subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);+ getRevision = (): number => this.store.getState().revision;+ getStructureRevision = (): number => this.store.getState().structureRevision;}export const SceneStore = new SceneStoreImpl();diff --git a/desktop/src/engine/StatsStore.ts b/desktop/src/engine/StatsStore.tsindex 7217714bc..db292feeb 100644--- a/desktop/src/engine/StatsStore.ts+++ b/desktop/src/engine/StatsStore.ts@@ -1,3 +1,4 @@+import { createStore } from 'zustand/vanilla';import { EngineHost } from './EngineHost';export interface StatsSnapshot {@@ -10,8 +11,7 @@ export interface StatsSnapshot {// entity count, and the viewport cursor's world position. Updated a few times// a second (not per frame) to avoid churning the status bar.class StatsStoreImpl {- private snapshot: StatsSnapshot = { fps: 0, entities: 0, cursor: null };- private readonly listeners = new Set<() => void>();+ private readonly store = createStore<StatsSnapshot>(() => ({ fps: 0, entities: 0, cursor: null }));private running = false;private frames = 0;@@ -32,8 +32,9 @@ class StatsStoreImpl {const entities = EngineHost.world?.getAllEntities().length ?? 0;this.frames = 0;this.windowStart = t;- if (fps !== this.snapshot.fps || entities !== this.snapshot.entities) {- this.emit({ ...this.snapshot, fps, entities });+ const cur = this.store.getState();+ if (fps !== cur.fps || entities !== cur.entities) {+ this.store.setState({ fps, entities });}}};@@ -44,25 +45,17 @@ class StatsStoreImpl {setCursor(x: number, y: number) {const cx = Math.round(x);const cy = Math.round(y);- const cur = this.snapshot.cursor;+ const cur = this.store.getState().cursor;if (cur && cur.x === cx && cur.y === cy) return;- this.emit({ ...this.snapshot, cursor: { x: cx, y: cy } });+ this.store.setState({ cursor: { x: cx, y: cy } });}clearCursor() {- if (this.snapshot.cursor) this.emit({ ...this.snapshot, cursor: null });+ if (this.store.getState().cursor) this.store.setState({ cursor: null });}- private emit(next: StatsSnapshot) {- this.snapshot = next;- for (const l of this.listeners) l();- }-- subscribe = (fn: () => void): (() => void) => {- this.listeners.add(fn);- return () => this.listeners.delete(fn);- };- getSnapshot = (): StatsSnapshot => this.snapshot;+ subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);+ getSnapshot = (): StatsSnapshot => this.store.getState();}export const StatsStore = new StatsStoreImpl();diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.tsindex 31d1f72ea..f6f239d84 100644--- a/desktop/src/engine/ViewportController.ts+++ b/desktop/src/engine/ViewportController.ts@@ -1,4 +1,4 @@-import { Camera, CameraView, Sprite, Transform } from 'esengine';+import { CameraView, EditorView, Sprite, Transform } from 'esengine';import type { EntityId } from '@/types';import { EngineHost } from './EngineHost';@@ -13,20 +13,12 @@ function cameraView(): CameraViewLike | null {return cv ?? null;}-// The active scene camera entity (or the first camera). Editor navigation writes-// it directly on the live World — NOT through SceneCommands/SceneModel — so it-// moves the rendered view without going on the undo stack or dirtying the saved-// scene (an editor camera, reset to the scene's camera on reload).-function activeCameraId(): EntityId | null {- const world = EngineHost.world;- if (!world) return null;- let first: EntityId | null = null;- for (const e of world.getAllEntities()) {- if (!world.has(e, Camera) || !world.has(e, Transform)) continue;- if (first == null) first = e;- if ((world.get(e, Camera) as { isActive?: boolean }).isActive) return e;- }- return first;+// The dedicated editor viewport camera — an engine resource, NOT a scene entity.+// Navigation mutates this in place; the camera system renders + resolves+// screen<->world through it in edit mode (see sdk EditorView / CameraPlugin), so+// panning/zooming/framing never touches — or dirties — the scene's game Camera.+function editorView(): { active: boolean; x: number; y: number; orthoSize: number } | null {+ return EngineHost.getResource(EditorView) ?? null;}/** DOM pointer position → engine screen space (buffer px, y-up). */@@ -138,36 +130,30 @@ export const ViewportController = {return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };},- /** Pan the editor view by a CSS-pixel drag (prev→cur); moves the live camera. */+ /** Pan the editor view by a CSS-pixel drag (prev→cur). Moves only the editor camera. */panByClient(prevX: number, prevY: number, curX: number, curY: number): void {- const world = EngineHost.mutableWorld();- const cam = activeCameraId();- if (!world || cam == null) return;+ const view = editorView();+ if (!view) return;const a = this.canvasToWorld(prevX, prevY);const b = this.canvasToWorld(curX, curY);if (!a || !b) return;- const t = world.get(cam, Transform) as unknown as { position: { x: number; y: number; z: number } };- const next = { ...t, position: { ...t.position, x: t.position.x + (a.x - b.x), y: t.position.y + (a.y - b.y) } };- world.set(cam, Transform, next as never);+ view.x += a.x - b.x;+ view.y += a.y - b.y;},- /** Zoom the editor view: factor > 1 zooms out, < 1 zooms in (camera orthoSize). */+ /** Zoom the editor view: factor > 1 zooms out, < 1 zooms in (editor orthoSize). */zoomBy(factor: number): void {- const world = EngineHost.mutableWorld();- const cam = activeCameraId();- if (!world || cam == null) return;- const c = world.get(cam, Camera) as unknown as { orthoSize: number };- const next = { ...c, orthoSize: Math.max(8, Math.min(40000, c.orthoSize * factor)) };- world.set(cam, Camera, next as never);+ const view = editorView();+ if (!view) return;+ view.orthoSize = Math.max(8, Math.min(40000, view.orthoSize * factor));},/** Center the editor view on an entity (frame-selected). */frameEntity(id: EntityId): void {- const world = EngineHost.mutableWorld();- const cam = activeCameraId();+ const view = editorView();const pos = this.getEntityXY(id);- if (!world || cam == null || !pos) return;- const t = world.get(cam, Transform) as unknown as { position: { x: number; y: number; z: number } };- world.set(cam, Transform, { ...t, position: { ...t.position, x: pos.x, y: pos.y } } as never);+ if (!view || !pos) return;+ view.x = pos.x;+ view.y = pos.y;},};diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.tsindex f5a3bb4f6..2a52ebc35 100644--- a/desktop/src/engine/schema.ts+++ b/desktop/src/engine/schema.ts@@ -1,5 +1,6 @@import {getAllRegisteredComponents,+ getUserComponents,getComponent,Sprite,Camera,@@ -75,6 +76,70 @@ export function inspectableComponents(return out;}+// Add-Component picker categories, in display order (UE5 groups the picker by+// category). Editor-side presentation policy — the engine has no category metadata+// today, so builtins are mapped/heuristic'd here; user/script components are+// authoritatively bucketed under "Scripts" via the engine's getUserComponents().+export const CATEGORY_ORDER = [+ 'Common',+ 'Rendering',+ 'Physics',+ 'Animation',+ 'UI',+ 'Audio',+ 'Effects',+ 'Scripts',+ 'Other',+] as const;++const COMPONENT_CATEGORY: Record<string, string> = {+ Camera: 'Common',+ Sprite: 'Rendering',+ ShapeRenderer: 'Rendering',+ BitmapText: 'Rendering',+ TilemapLayer: 'Rendering',+ Canvas: 'UI',+ SpineAnimation: 'Animation',+ ParticleEmitter: 'Effects',+ RigidBody: 'Physics',+};++/**+ * Classify a component into an Add-Component picker category. `isUser` (an+ * engine-authoritative flag from getUserComponents) wins first — project/script+ * components always land under "Scripts", never a name-heuristic bucket. Builtins+ * use the explicit map, then name heuristics, then "Other".+ */+export function componentCategory(name: string, isUser = false): string {+ if (isUser) return 'Scripts';+ const hit = COMPONENT_CATEGORY[name];+ if (hit) return hit;+ if (/Collider$|Joint$|^RigidBody/.test(name)) return 'Physics';+ if (/Audio|Sound/.test(name)) return 'Audio';+ if (/Particle|Emitter|Trail|PostProcess/.test(name)) return 'Effects';+ if (/Canvas|Widget|Layout|Button|Label/.test(name)) return 'UI';+ if (/Sprite|Render|Mesh|Tilemap|Light|Font|Text(?!ure)/.test(name)) return 'Rendering';+ if (/Anim|Tween|Spine/.test(name)) return 'Animation';+ return 'Other';+}++/**+ * The Add-Component candidates as picker entries (name + label + category),+ * resolving user-vs-builtin once via the engine registry. One place owns the+ * category assignment so the panel stays presentation-only.+ */+export function addableComponentEntries(+ world: ReadonlyWorldT,+ entity: EntityId,+): Array<{ name: string; label: string; category: string }> {+ const userNames = new Set(getUserComponents().keys());+ return addableComponents(world, entity).map((c) => ({+ name: c.name,+ label: c.label,+ category: componentCategory(c.name, userNames.has(c.name)),+ }));+}+/** Registered components NOT yet on an entity — the "Add Component" candidates. */export function addableComponents(world: ReadonlyWorldT,diff --git a/desktop/src/layout/MenuBar.tsx b/desktop/src/layout/MenuBar.tsxindex 63a88e7a8..1097fd78f 100644--- a/desktop/src/layout/MenuBar.tsx+++ b/desktop/src/layout/MenuBar.tsx@@ -4,11 +4,10 @@// the drag region; the menus + dropdowns opt out of dragging.import { useEffect, useRef, useState, useSyncExternalStore } from 'react';import { useEditorStore } from '@/store/editorStore';-import { EditorHistory } from '@/engine/EditorHistory';-import { SceneCommands } from '@/engine/SceneCommands';import { ProjectStore } from '@/project/ProjectStore';import { Toasts } from '@/store/Toasts';import { MenuItems, type MenuItem } from '@/components/Menu';+import { commands, formatKeybinding } from '@/commands';const LAYOUT_KEY = 'estella.editor.layout.v1';@@ -34,14 +33,24 @@ export function MenuBar() {const [open, setOpen] = useState<string | null>(null);const barRef = useRef<HTMLDivElement>(null);- // Re-render on history changes so undo/redo enabled state stays live.- useSyncExternalStore(EditorHistory.subscribe, EditorHistory.getVersion);+ // Only the always-visible project label needs a live subscription. Menu items+ // 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);- const {- selectedId, select,- showGrid, showGizmos, snapping, toggleGrid, toggleGizmos, toggleSnapping,- openLauncher,- } = useEditorStore();++ // Build a menu item from a registered command — one source for label, shortcut+ // hint, action, enablement, and checked state.+ const cmdItem = (id: string): MenuItem => {+ const c = commands.get(id)!;+ return {+ label: c.label,+ shortcut: c.keybinding ? formatKeybinding(c.keybinding) : undefined,+ onClick: () => commands.run(id),+ disabled: !commands.isEnabled(id),+ checked: commands.isChecked(id),+ };+ };+ const openLauncher = () => useEditorStore.getState().openLauncher();// Close the open menu on an outside click or Escape.useEffect(() => {@@ -60,71 +69,45 @@ export function MenuBar() {};}, [open]);- const save = () => void ProjectStore.save().catch(() => ProjectStore.saveAsViaDialog());- const duplicate = () => {- if (selectedId == null) return;- const dup = SceneCommands.duplicateEntity(selectedId);- if (dup != null) select(dup);- };- const remove = () => {- const ids = [...useEditorStore.getState().selectedIds];- if (!ids.length) return;- ids.forEach((i) => SceneCommands.deleteEntity(i));- select(null);- };- const addEntity = () => {- const e = SceneCommands.addEntity();- if (e != null) select(e);- };-const menus: MenuDef[] = [{title: 'File',items: [- { label: 'Open Project…', shortcut: '⌘O', onClick: () => void ProjectStore.openViaDialog().then((ok) => ok && select(null)) },+ cmdItem('project.open'),{ sep: true },- { label: 'Save Scene', shortcut: '⌘S', onClick: save, disabled: !project?.currentScene },- { label: 'Save Scene As…', shortcut: '⇧⌘S', onClick: () => void ProjectStore.saveAsViaDialog(), disabled: !project },+ cmdItem('project.save'),+ cmdItem('project.saveAs'),{ sep: true },- { label: 'Close Project', onClick: openLauncher, disabled: !project },+ cmdItem('project.close'),],},{title: 'Edit',- items: [- { label: 'Undo', shortcut: '⌘Z', onClick: () => EditorHistory.undo(), disabled: !EditorHistory.canUndo() },- { label: 'Redo', shortcut: '⇧⌘Z', onClick: () => EditorHistory.redo(), disabled: !EditorHistory.canRedo() },- ],+ items: [cmdItem('edit.undo'), cmdItem('edit.redo')],},{title: 'Entity',items: [- { label: 'Add Entity', onClick: addEntity },+ cmdItem('entity.add'),{ sep: true },- { label: 'Duplicate', shortcut: '⌘D', onClick: duplicate, disabled: selectedId == null },- { label: 'Delete', shortcut: '⌫', onClick: remove, disabled: selectedId == null },+ cmdItem('entity.duplicate'),+ cmdItem('entity.delete'),{ sep: true },- { label: 'Deselect', onClick: () => select(null), disabled: selectedId == null },+ cmdItem('entity.deselect'),],},{title: 'View',items: [- { label: 'Show Grid', onClick: toggleGrid, checked: showGrid },- { label: 'Show Gizmos', onClick: toggleGizmos, checked: showGizmos },- { label: 'Snapping', onClick: toggleSnapping, checked: snapping },+ cmdItem('view.toggleGrid'),+ cmdItem('view.toggleGizmos'),+ cmdItem('view.toggleSnapping'),],},{title: 'Build',items: [- {- label: 'Build Project Scripts',- onClick: () => void window.estella?.project?.buildScripts?.()- .then(() => Toasts.push('Built project scripts', 'success'))- .catch(() => Toasts.push('Build failed', 'error')),- disabled: !project,- },+ cmdItem('build.scripts'),{label: 'Extract Component Schemas',onClick: () => void window.estella?.project?.extractSchemas?.()diff --git a/desktop/src/layout/StatusBar.tsx b/desktop/src/layout/StatusBar.tsxindex 529126660..2e41687cd 100644--- a/desktop/src/layout/StatusBar.tsx+++ b/desktop/src/layout/StatusBar.tsx@@ -1,13 +1,14 @@import { useSyncExternalStore } from 'react';import { Circle, Gauge, MousePointer2, Boxes } from 'lucide-react';import { useEditorStore } from '@/store/editorStore';+import { useSelection } from '@/store/selectionStore';import { StatsStore } from '@/engine/StatsStore';// Bottom status strip — live engine telemetry (real FPS / entity count / cursor// world position) reads in the mono face.export function StatusBar() {const isPlaying = useEditorStore((s) => s.isPlaying);- const selectedId = useEditorStore((s) => s.selectedId);+ const selectedIds = useSelection((s) => s.selectedIds);const stats = useSyncExternalStore(StatsStore.subscribe, StatsStore.getSnapshot);return (@@ -18,7 +19,7 @@ export function StatusBar() {{isPlaying ? 'Running' : 'Edit Mode'}</span><span className="statusbar__item">- {selectedId != null ? '1 selected' : 'No selection'}+ {selectedIds.size ? `${selectedIds.size} selected` : 'No selection'}</span></div>diff --git a/desktop/src/layout/Toolbar.tsx b/desktop/src/layout/Toolbar.tsxindex dc3affd2a..9eb0926dd 100644--- a/desktop/src/layout/Toolbar.tsx+++ b/desktop/src/layout/Toolbar.tsx@@ -19,24 +19,22 @@ import {} from 'lucide-react';import { useEditorStore } from '@/store/editorStore';import { EditorHistory } from '@/engine/EditorHistory';-import { ProjectStore } from '@/project/ProjectStore';-import { Toasts } from '@/store/Toasts';+import { commands, formatKeybinding } from '@/commands';import type { ToolMode } from '@/types';-interface ToolDef {- mode: ToolMode;- icon: LucideIcon;- label: string;- key: string;-}--const TOOLS: ToolDef[] = [- { mode: 'select', icon: MousePointer2, label: 'Select', key: 'Q' },- { mode: 'move', icon: Move, label: 'Move', key: 'W' },- { mode: 'rotate', icon: RotateCw, label: 'Rotate', key: 'E' },- { mode: 'scale', icon: Scale3d, label: 'Scale', key: 'R' },+const TOOLS: { mode: ToolMode; icon: LucideIcon; label: string }[] = [+ { mode: 'select', icon: MousePointer2, label: 'Select' },+ { mode: 'move', icon: Move, label: 'Move' },+ { mode: 'rotate', icon: RotateCw, label: 'Rotate' },+ { mode: 'scale', icon: Scale3d, label: 'Scale' },];+/** Shortcut-hint suffix for a command's tooltip, derived from its keybinding. */+function hint(id: string): string {+ const kb = commands.get(id)?.keybinding;+ return kb ? ` ${formatKeybinding(kb)}` : '';+}+function TBtn({icon: Icon,label,@@ -68,21 +66,10 @@ function TBtn({}export function Toolbar() {- const {- tool,- setTool,- snapping,- toggleSnapping,- showGrid,- toggleGrid,- showGizmos,- toggleGizmos,- isPlaying,- isPaused,- togglePlay,- togglePause,- stop,- } = useEditorStore();+ // Reactive display state (tool / toggles / play); actions dispatch through the+ // command registry so menu, toolbar, and keyboard share one implementation.+ const { tool, snapping, showGrid, showGizmos, isPlaying, isPaused, togglePause, stop } =+ useEditorStore();// Re-render on history changes to refresh undo/redo enabled state + labels.useSyncExternalStore(EditorHistory.subscribe, EditorHistory.getVersion);@@ -94,8 +81,8 @@ export function Toolbar() {<div className="toolbar__group"><TBtnicon={Save}- label="Save Scene ⌘S"- onClick={() => void ProjectStore.save().catch(() => ProjectStore.saveAsViaDialog())}+ label={`Save Scene${hint('project.save')}`}+ onClick={() => commands.run('project.save')}/></div>@@ -104,15 +91,15 @@ export function Toolbar() {<div className="toolbar__group"><TBtnicon={Undo2}- label={undoLabel ? `Undo ${undoLabel} ⌘Z` : 'Undo ⌘Z'}- disabled={!EditorHistory.canUndo()}- onClick={() => EditorHistory.undo()}+ label={`${undoLabel ? `Undo ${undoLabel}` : 'Undo'}${hint('edit.undo')}`}+ disabled={!commands.isEnabled('edit.undo')}+ onClick={() => commands.run('edit.undo')}/><TBtnicon={Redo2}- label={redoLabel ? `Redo ${redoLabel} ⇧⌘Z` : 'Redo ⇧⌘Z'}- disabled={!EditorHistory.canRedo()}- onClick={() => EditorHistory.redo()}+ label={`${redoLabel ? `Redo ${redoLabel}` : 'Redo'}${hint('edit.redo')}`}+ disabled={!commands.isEnabled('edit.redo')}+ onClick={() => commands.run('edit.redo')}/></div>@@ -123,9 +110,9 @@ export function Toolbar() {<TBtnkey={t.mode}icon={t.icon}- label={`${t.label} (${t.key})`}+ label={`${t.label}${hint(`tool.${t.mode}`)}`}active={tool === t.mode}- onClick={() => setTool(t.mode)}+ onClick={() => commands.run(`tool.${t.mode}`)}/>))}</div>@@ -133,8 +120,8 @@ export function Toolbar() {<span className="toolbar__div" /><div className="toolbar__group">- <TBtn icon={Magnet} label="Snapping" active={snapping} onClick={toggleSnapping} />- <TBtn icon={Grid3x3} label="Show Grid" active={showGrid} onClick={toggleGrid} />+ <TBtn icon={Magnet} label="Snapping" active={snapping} onClick={() => commands.run('view.toggleSnapping')} />+ <TBtn icon={Grid3x3} label="Show Grid" active={showGrid} onClick={() => commands.run('view.toggleGrid')} /></div>{/* Play controls sit dead-center — the focal action, like UE5. */}@@ -142,10 +129,10 @@ export function Toolbar() {<div className="playbar"><TBtnicon={Play}- label={isPlaying ? 'Restart' : 'Play (F5)'}+ label={isPlaying ? 'Restart' : `Play${hint('play.toggle')}`}tone="run"active={isPlaying}- onClick={togglePlay}+ onClick={() => commands.run('play.toggle')}/><TBtn icon={Pause} label="Pause" active={isPaused} onClick={togglePause} /><TBtn icon={Stop} label="Stop" onClick={stop} />@@ -153,7 +140,7 @@ export function Toolbar() {</div><div className="toolbar__group toolbar__right">- <TBtn icon={Eye} label="Show Gizmos" active={showGizmos} onClick={toggleGizmos} />+ <TBtn icon={Eye} label="Show Gizmos" active={showGizmos} onClick={() => commands.run('view.toggleGizmos')} /><button type="button" className="chip" title="Build target"><Smartphone size={13} strokeWidth={1.85} /><span>Web</span>@@ -162,11 +149,7 @@ export function Toolbar() {type="button"className="chip chip--accent"title="Build project scripts"- onClick={() =>- void window.estella?.project?.buildScripts?.()- .then(() => Toasts.push('Built project scripts', 'success'))- .catch(() => Toasts.push('Build failed', 'error'))- }+ onClick={() => commands.run('build.scripts')}><Hammer size={13} strokeWidth={1.85} /><span>Build</span>diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex 063c56b51..3ea32c78b 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -1,12 +1,13 @@import { useMemo, useRef, useState, useSyncExternalStore } from 'react';import { Box, ChevronDown, MoreHorizontal, Plus, Search } from 'lucide-react';-import { useEditorStore } from '@/store/editorStore';+import { useSelection } from '@/store/selectionStore';import { EngineHost } from '@/engine/EngineHost';import { SceneStore } from '@/engine/SceneStore';import { SceneQuery } from '@/engine/SceneQuery';import { SceneCommands } from '@/engine/SceneCommands';-import { addableComponents } from '@/engine/schema';-import { ContextMenu, type MenuItem } from '@/components/Menu';+import { addableComponentEntries } from '@/engine/schema';+import { ContextMenu } from '@/components/Menu';+import { AddComponentMenu } from '@/components/AddComponentMenu';import type { InspectorComponent, InspectorField, EntityId } from '@/types';const AXES = ['x', 'y', 'z'];@@ -293,7 +294,7 @@ function ComponentSection({export function Details() {const engine = useSyncExternalStore(EngineHost.subscribe, EngineHost.getSnapshot);const revision = useSyncExternalStore(SceneStore.subscribe, SceneStore.getRevision);- const selectedId = useEditorStore((s) => s.selectedId);+ const selectedId = useSelection((s) => s.selectedId);const ready = engine.status === 'ready' && selectedId != null;const [query, setQuery] = useState('');@@ -345,15 +346,6 @@ export function Details() {}const world = EngineHost.world;- const addItems: MenuItem[] =- addMenu && world- ? (() => {- const list = addableComponents(world, selectedId);- return list.length- ? list.map((c) => ({ label: c.label, onClick: () => SceneCommands.addComponent(selectedId, c.name) }))- : [{ label: 'All components added', onClick: () => {}, disabled: true }];- })()- : [];return (<div className="panel">@@ -368,15 +360,30 @@ export function Details() {<span className="inspector-head__id mono">#{selectedId}</span></div>- <div className="inspector-search">- <Search size={13} strokeWidth={1.9} />- <input- className="inspector-search__input"- placeholder="Search components"- value={query}- spellCheck={false}- onChange={(e) => setQuery(e.target.value)}- />+ <div className="inspector-bar">+ <button+ type="button"+ className="add-component"+ title="Add Component"+ onClick={(e) => {+ const r = e.currentTarget.getBoundingClientRect();+ setAddMenu({ x: r.left, y: r.bottom + 4 });+ }}+ >+ <Plus size={14} strokeWidth={2.4} />+ Add+ <ChevronDown size={12} strokeWidth={2.4} className="add-component__caret" />+ </button>+ <div className="inspector-search">+ <Search size={13} strokeWidth={1.9} />+ <input+ className="inspector-search__input"+ placeholder="Search"+ value={query}+ spellCheck={false}+ onChange={(e) => setQuery(e.target.value)}+ />+ </div></div><div className="panel__body">@@ -393,17 +400,6 @@ export function Details() {{query && visible.length === 0 && (<p className="inspector-note">No components match “{query}”.</p>)}-- <button- type="button"- className="add-component"- onClick={(e) => {- const r = e.currentTarget.getBoundingClientRect();- setAddMenu({ x: r.left, y: r.bottom + 2 });- }}- >- <Plus size={15} strokeWidth={2} /> Add Component- </button></div>{compMenu && (@@ -416,7 +412,15 @@ export function Details() {onClose={() => setCompMenu(null)}/>)}- {addMenu && <ContextMenu x={addMenu.x} y={addMenu.y} items={addItems} onClose={() => setAddMenu(null)} />}+ {addMenu && world && (+ <AddComponentMenu+ x={addMenu.x}+ y={addMenu.y}+ entries={addableComponentEntries(world, selectedId)}+ onAdd={(name) => SceneCommands.addComponent(selectedId, name)}+ onClose={() => setAddMenu(null)}+ />+ )}</div>);}diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsxindex 834312df9..0777ba7b5 100644--- a/desktop/src/panels/Outliner.tsx+++ b/desktop/src/panels/Outliner.tsx@@ -1,6 +1,7 @@import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';import { ChevronRight, Eye, EyeOff, Lock, Search, Plus } from 'lucide-react';import { useEditorStore } from '@/store/editorStore';+import { useSelection } from '@/store/selectionStore';import { EngineHost } from '@/engine/EngineHost';import { SceneStore } from '@/engine/SceneStore';import { SceneQuery } from '@/engine/SceneQuery';@@ -26,8 +27,8 @@ interface RowProps {function Row(props: RowProps) {const { node, depth, forceExpand, renaming, dropId } = props;- const selectedIds = useEditorStore((s) => s.selectedIds);- const selectedId = useEditorStore((s) => s.selectedId);+ const selectedIds = useSelection((s) => s.selectedIds);+ const selectedId = useSelection((s) => s.selectedId);const expanded = useEditorStore((s) => s.expanded);const toggleExpanded = useEditorStore((s) => s.toggleExpanded);@@ -177,15 +178,15 @@ export function Outliner() {});walk(tree);useEditorStore.getState().setExpanded(parents);- if (useEditorStore.getState().selectedId == null) {- useEditorStore.getState().select(tree[0].id);+ if (useSelection.getState().selectedId == null) {+ useSelection.getState().select(tree[0].id);}}, [tree]);- const select = (id: EntityId | null) => useEditorStore.getState().select(id);+ const select = (id: EntityId | null) => useSelection.getState().select(id);const onRowClick = (id: EntityId, e: React.MouseEvent) => {- const store = useEditorStore.getState();+ const store = useSelection.getState();if (e.metaKey || e.ctrlKey) {store.toggleSelect(id);} else if (e.shiftKey && store.selectedId != null) {@@ -204,7 +205,7 @@ export function Outliner() {e.preventDefault();// Right-clicking outside the current selection selects just that entity;// right-clicking within it keeps the multi-selection (UE5 behaviour).- if (!useEditorStore.getState().selectedIds.has(id)) select(id);+ if (!useSelection.getState().selectedIds.has(id)) select(id);setCtx({ x: e.clientX, y: e.clientY, id });};const commitRename = (id: EntityId, name: string) => {@@ -217,7 +218,7 @@ export function Outliner() {if (id != null) select(id);};const selectionOrTarget = (id: EntityId): EntityId[] => {- const ids = useEditorStore.getState().selectedIds;+ const ids = useSelection.getState().selectedIds;return ids.has(id) ? [...ids] : [id];};diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex 4c35ae0fd..3e607af47 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -5,6 +5,8 @@ import {Loader2, TriangleAlert, type LucideIcon,} from 'lucide-react';import { useEditorStore } from '@/store/editorStore';+import { useSelection } from '@/store/selectionStore';+import { commands } from '@/commands';import { EngineHost } from '@/engine/EngineHost';import { ViewportController } from '@/engine/ViewportController';import { SceneCommands } from '@/engine/SceneCommands';@@ -68,6 +70,13 @@ const TOOLS: { mode: ToolMode; icon: LucideIcon; label: string; key: string }[]{ mode: 'scale', icon: Scale3d, label: 'Scale', key: 'R' },];+// Grid/angle/scale increments applied while the Snapping toggle is on. Fixed for+// now — a future Preferences panel will make these user-configurable.+const SNAP_MOVE = 10; // world units per grid step+const SNAP_ROTATE = 15; // degrees+const SNAP_SCALE = 0.1; // uniform scale step+const snap = (v: number, step: number) => Math.round(v / step) * step;+// Entity's screen-center in viewport (client) coordinates.function entityClientCenter(id: number): { cx: number; cy: number } | null {const pos = ViewportController.getEntityXY(id);@@ -90,13 +99,9 @@ function VBtn({ icon: Icon, label, active, onClick }: { icon: LucideIcon; label:export function Viewport() {const isPlaying = useEditorStore((s) => s.isPlaying);const tool = useEditorStore((s) => s.tool);- const setTool = useEditorStore((s) => s.setTool);const showGrid = useEditorStore((s) => s.showGrid);const showGizmos = useEditorStore((s) => s.showGizmos);const snapping = useEditorStore((s) => s.snapping);- const toggleGrid = useEditorStore((s) => s.toggleGrid);- const toggleGizmos = useEditorStore((s) => s.toggleGizmos);- const toggleSnapping = useEditorStore((s) => s.toggleSnapping);const stageRef = useRef<HTMLDivElement>(null);const gizmoRef = useRef<HTMLDivElement>(null);@@ -128,20 +133,6 @@ export function Viewport() {return () => stage.removeEventListener('wheel', onWheel);}, []);- // F = frame the selected entity (skip while typing).- useEffect(() => {- const onKey = (e: KeyboardEvent) => {- const el = document.activeElement as HTMLElement | null;- if (el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable)) return;- if (e.key === 'f' || e.key === 'F') {- const id = useEditorStore.getState().selectedId;- if (id != null) ViewportController.frameEntity(id);- }- };- window.addEventListener('keydown', onKey);- return () => window.removeEventListener('keydown', onKey);- }, []);-// Glue the gizmo + selection outline to the selected entity, every frame.useEffect(() => {let raf = 0;@@ -150,7 +141,7 @@ export function Viewport() {const g = gizmoRef.current;const sel = selectionRef.current;if (!g || !sel) return;- const id = useEditorStore.getState().selectedId;+ const id = useSelection.getState().selectedId;const ready = EngineHost.getSnapshot().status === 'ready';const showG = useEditorStore.getState().showGizmos;@@ -190,7 +181,7 @@ export function Viewport() {if (e.button !== 0) return;const id = ViewportController.pickEntity(e.clientX, e.clientY);- useEditorStore.getState().select(id);+ useSelection.getState().select(id);if (id == null) return;if (tool === 'rotate') {@@ -230,22 +221,33 @@ export function Viewport() {if (wp) StatsStore.setCursor(wp.x, wp.y);const drag = dragRef.current;if (!drag) return;+ const snapOn = useEditorStore.getState().snapping;if (drag.kind === 'pan') {ViewportController.panByClient(drag.px, drag.py, e.clientX, e.clientY);drag.px = e.clientX;drag.py = e.clientY;} else if (drag.kind === 'move') {- if (wp) SceneCommands.setEntityXY(drag.id, wp.x + drag.dx, wp.y + drag.dy);+ if (wp) {+ let x = wp.x + drag.dx;+ let y = wp.y + drag.dy;+ if (snapOn) { x = snap(x, SNAP_MOVE); y = snap(y, SNAP_MOVE); }+ SceneCommands.setEntityXY(drag.id, x, y);+ }} else if (drag.kind === 'rotate') {const angle = Math.atan2(e.clientY - drag.cy, e.clientX - drag.cx);const deltaDeg = ((angle - drag.startAngle) * 180) / Math.PI;// Screen y is down, so a clockwise screen drag is a negative world rotation.- SceneCommands.setField(drag.id, 'Transform', 'rotation', 'angle', drag.startRot - deltaDeg);+ let rot = drag.startRot - deltaDeg;+ if (snapOn) rot = snap(rot, SNAP_ROTATE);+ SceneCommands.setField(drag.id, 'Transform', 'rotation', 'angle', rot);} else if (drag.kind === 'scale') {const dist = Math.hypot(e.clientX - drag.cx, e.clientY - drag.cy);const f = dist / drag.startDist;- SceneCommands.setField(drag.id, 'Transform', 'scale', 'vec3', [drag.sx * f, drag.sy * f, drag.sz]);+ let sx = drag.sx * f;+ let sy = drag.sy * f;+ if (snapOn) { sx = snap(sx, SNAP_SCALE); sy = snap(sy, SNAP_SCALE); }+ SceneCommands.setField(drag.id, 'Transform', 'scale', 'vec3', [sx, sy, drag.sz]);}};@@ -262,21 +264,14 @@ export function Viewport() {<div className="viewport"><div className="viewport__toolbar">{TOOLS.map((t) => (- <VBtn key={t.mode} icon={t.icon} label={`${t.label} (${t.key})`} active={tool === t.mode} onClick={() => setTool(t.mode)} />+ <VBtn key={t.mode} icon={t.icon} label={`${t.label} (${t.key})`} active={tool === t.mode} onClick={() => commands.run(`tool.${t.mode}`)} />))}<span className="viewport__toolbar-div" />- <VBtn icon={Grid3x3} label="Show Grid" active={showGrid} onClick={toggleGrid} />- <VBtn icon={Eye} label="Show Gizmos" active={showGizmos} onClick={toggleGizmos} />- <VBtn icon={Magnet} label="Snapping" active={snapping} onClick={toggleSnapping} />+ <VBtn icon={Grid3x3} label="Show Grid" active={showGrid} onClick={() => commands.run('view.toggleGrid')} />+ <VBtn icon={Eye} label="Show Gizmos" active={showGizmos} onClick={() => commands.run('view.toggleGizmos')} />+ <VBtn icon={Magnet} label="Snapping" active={snapping} onClick={() => commands.run('view.toggleSnapping')} /><span className="viewport__toolbar-div" />- <VBtn- icon={Frame}- label="Frame Selected (F)"- onClick={() => {- const id = useEditorStore.getState().selectedId;- if (id != null) ViewportController.frameEntity(id);- }}- />+ <VBtn icon={Frame} label="Frame Selected (F)" onClick={() => commands.run('view.frameSelected')} /></div>{/* The engine canvas mounts here; pointer events drive pick + transform + pan. */}diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex f029fbda6..81ecf6291 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -1,3 +1,4 @@+import { createStore } from 'zustand/vanilla';import { resetWorldTo, getComponent, Assets } from 'esengine';import type { SceneData } from 'esengine';import { EngineHost } from '@/engine/EngineHost';@@ -76,19 +77,15 @@ function mapAssetRefs(value: unknown, resolve: (uuid: string) => number): unknow}class ProjectStoreImpl {- private state: ProjectState | null = null;- private readonly listeners = new Set<() => void>();-- subscribe = (fn: () => void): (() => void) => {- this.listeners.add(fn);- return () => this.listeners.delete(fn);- };- getSnapshot = (): ProjectState | null => this.state;-- private emit() {- for (const l of this.listeners) l();+ private readonly store = createStore<{ project: ProjectState | null }>(() => ({ project: null }));+ /** Read accessor so existing `this.state` reads stay unchanged after the move. */+ private get state(): ProjectState | null {+ return this.store.getState().project;}+ subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);+ getSnapshot = (): ProjectState | null => this.store.getState().project;+/** Show the OS folder picker and open the chosen project. */async openViaDialog(): Promise<boolean> {const bridge = window.estella;@@ -132,15 +129,16 @@ class ProjectStoreImpl {}private adopt(opened: OpenedProject) {- this.state = {- root: opened.root,- name: opened.manifest.name,- layout: resolveLayout(opened.manifest),- workspace: opened.workspace,- defaultScene: opened.manifest.defaultScene,- currentScene: null,- };- this.emit();+ this.store.setState({+ project: {+ root: opened.root,+ name: opened.manifest.name,+ layout: resolveLayout(opened.manifest),+ workspace: opened.workspace,+ defaultScene: opened.manifest.defaultScene,+ currentScene: null,+ },+ });}/** Read + parse a project-relative `.esscene` (raw — refs unresolved). */@@ -173,8 +171,8 @@ class ProjectStoreImpl {const entityMap = resetWorldTo(world, data);SceneModel.adopt(raw, entityMap);}- this.state = { ...st, currentScene: rel };- this.emit();+ EngineHost.syncEditorViewToScene();+ this.store.setState({ project: { ...st, currentScene: rel } });}/**@@ -247,8 +245,7 @@ class ProjectStoreImpl {const st = this.state;if (!st) return;const workspace: WorkspaceState = { ...st.workspace, lastOpenedScene: relPath };- this.state = { ...st, workspace, currentScene: relPath };- this.emit();+ this.store.setState({ project: { ...st, workspace, currentScene: relPath } });await window.estella.workspace.save(workspace);}diff --git a/desktop/src/store/Toasts.ts b/desktop/src/store/Toasts.tsindex 116f0b2a7..3a58f8fc6 100644--- a/desktop/src/store/Toasts.ts+++ b/desktop/src/store/Toasts.ts@@ -4,6 +4,8 @@* store (same subscribe/getSnapshot shape as EngineHost / ProjectStore)* so any module — React component or plain class — can post a toast.*/+import { createStore } from 'zustand/vanilla';+export type ToastKind = 'info' | 'success' | 'warn' | 'error';export interface Toast {@@ -13,34 +15,23 @@ export interface Toast {}class ToastsImpl {- private list: Toast[] = [];- private readonly listeners = new Set<() => void>();+ private readonly store = createStore<{ list: Toast[] }>(() => ({ list: [] }));private seq = 0;- subscribe = (fn: () => void): (() => void) => {- this.listeners.add(fn);- return () => this.listeners.delete(fn);- };- getSnapshot = (): Toast[] => this.list;+ subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);+ getSnapshot = (): Toast[] => this.store.getState().list;/** Post a toast; it auto-dismisses after `ttl` ms (0 = sticky until clicked). */push(message: string, kind: ToastKind = 'info', ttl = 3200): number {const id = ++this.seq;- this.list = [...this.list, { id, kind, message }];- this.emit();+ this.store.setState((s) => ({ list: [...s.list, { id, kind, message }] }));if (ttl > 0) setTimeout(() => this.dismiss(id), ttl);return id;}dismiss(id: number): void {- const next = this.list.filter((t) => t.id !== id);- if (next.length !== this.list.length) {- this.list = next;- this.emit();- }- }-- private emit() {- for (const l of this.listeners) l();+ const cur = this.store.getState().list;+ const next = cur.filter((t) => t.id !== id);+ if (next.length !== cur.length) this.store.setState({ list: next });}}diff --git a/desktop/src/store/editorStore.ts b/desktop/src/store/editorStore.tsindex 8da14e446..f0e14f1ef 100644--- a/desktop/src/store/editorStore.ts+++ b/desktop/src/store/editorStore.ts@@ -1,23 +1,13 @@import { create } from 'zustand';import type { EntityId, ToolMode } from '@/types';-// Global editor state. Intentionally small for the static shell — it grows as-// real selection/scene/asset operations are wired to the engine bridge.+// Global editor UI state (tools, viewport toggles, play state, launcher gate).+// Entity selection lives in its own engine-anchored store — see selectionStore.ts.interface EditorState {// Active manipulation tool (select / move / rotate / scale).tool: ToolMode;setTool: (tool: ToolMode) => void;- // Selection. `selectedId` is the PRIMARY/active entity (drives the Details- // panel + viewport gizmo); `selectedIds` is the full multi-selection set.- selectedId: EntityId | null;- selectedIds: Set<EntityId>;- select: (id: EntityId | null) => void;- /** Ctrl/Cmd-click: add/remove one entity from the selection. */- toggleSelect: (id: EntityId) => void;- /** Shift-click / box: replace the selection with a set, with a primary. */- selectMany: (ids: EntityId[], primary: EntityId) => void;-// Expanded nodes in the outliner tree.expanded: Set<EntityId>;toggleExpanded: (id: EntityId) => void;@@ -49,23 +39,6 @@ export const useEditorStore = create<EditorState>((set) => ({tool: 'move',setTool: (tool) => set({ tool }),- selectedId: null,- selectedIds: new Set<EntityId>(),- select: (selectedId) =>- set({ selectedId, selectedIds: selectedId != null ? new Set([selectedId]) : new Set() }),- toggleSelect: (id) =>- set((s) => {- const next = new Set(s.selectedIds);- if (next.has(id)) {- next.delete(id);- const primary = s.selectedId === id ? (next.size ? [...next][next.size - 1] : null) : s.selectedId;- return { selectedIds: next, selectedId: primary };- }- next.add(id);- return { selectedIds: next, selectedId: id };- }),- selectMany: (ids, primary) => set({ selectedIds: new Set(ids), selectedId: primary }),-expanded: new Set<EntityId>(),toggleExpanded: (id) =>set((s) => {diff --git a/desktop/src/store/selectionStore.ts b/desktop/src/store/selectionStore.tsnew file mode 100644index 000000000..bddc47124--- /dev/null+++ b/desktop/src/store/selectionStore.ts@@ -0,0 +1,67 @@+import { create } from 'zustand';+import { SceneStore } from '@/engine/SceneStore';+import type { EntityId } from '@/types';++/**+ * Entity selection — engine-anchored.+ *+ * Selection holds ids, but the entities live in the engine World, so a selected+ * id can be destroyed out from under us (delete, undo-of-create, scene teardown).+ * Instead of scattering defensive `select(null)` after every such op, this store+ * listens for entity despawns and drops the dead id by hand — selection+ * self-heals, and stale-selection bugs become structurally impossible.+ *+ * `selectedId` is the primary/active entity (drives the Details panel + viewport+ * gizmo); `selectedIds` is the full multi-selection set.+ */+interface SelectionState {+ selectedId: EntityId | null;+ selectedIds: Set<EntityId>;+ /** Replace the selection with a single entity (or clear it with null). */+ select: (id: EntityId | null) => void;+ /** Ctrl/Cmd-click: add/remove one entity from the selection. */+ toggleSelect: (id: EntityId) => void;+ /** Shift-click / box: replace the selection with a set, with a primary. */+ selectMany: (ids: EntityId[], primary: EntityId) => void;+ /** Remove one id from the selection (despawn self-healing). */+ dropId: (id: EntityId) => void;+}++export const useSelection = create<SelectionState>((set) => ({+ selectedId: null,+ selectedIds: new Set<EntityId>(),++ select: (selectedId) =>+ set({ selectedId, selectedIds: selectedId != null ? new Set([selectedId]) : new Set() }),++ toggleSelect: (id) =>+ set((s) => {+ const next = new Set(s.selectedIds);+ if (next.has(id)) {+ next.delete(id);+ const primary =+ s.selectedId === id ? (next.size ? [...next][next.size - 1] : null) : s.selectedId;+ return { selectedIds: next, selectedId: primary };+ }+ next.add(id);+ return { selectedIds: next, selectedId: id };+ }),++ selectMany: (ids, primary) => set({ selectedIds: new Set(ids), selectedId: primary }),++ dropId: (id) =>+ set((s) => {+ if (s.selectedId !== id && !s.selectedIds.has(id)) return s;+ const next = new Set(s.selectedIds);+ next.delete(id);+ const primary =+ s.selectedId === id ? (next.size ? [...next][next.size - 1] : null) : s.selectedId;+ return { selectedIds: next, selectedId: primary };+ }),+}));++// Engine-anchored self-healing: when an entity is despawned (delete, undo-of-create,+// scene teardown), drop it from the selection by id — no manual deselect, no+// validity race. Wholesale scene swaps (open project, play-stop) still call+// select(null) explicitly, since ids can be reused by the incoming scene.+SceneStore.onEntityDespawn((id) => useSelection.getState().dropId(id));diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.cssindex d82a9a625..ec142037a 100644--- a/desktop/src/theme/app.css+++ b/desktop/src/theme/app.css@@ -92,7 +92,7 @@align-items: center;gap: 8px;width: 100%;- height: 26px;+ height: 24px;padding: 0 8px 0 4px;border-radius: var(--r-xs);font-size: var(--fs-sm);@@ -180,8 +180,8 @@.tbtn {display: grid;place-items: center;- width: 30px;- height: 30px;+ width: 28px;+ height: 28px;border-radius: var(--r-sm);color: var(--text-dim);transition: background 0.12s, color 0.12s;@@ -395,7 +395,7 @@display: flex;align-items: center;gap: 5px;- height: 24px;+ height: 22px;padding-right: 6px;border-radius: var(--r-sm);color: var(--text);@@ -569,7 +569,7 @@white-space: nowrap;font-size: var(--fs-2xs);color: var(--star-hi);- background: rgba(8, 11, 18, 0.7);+ background: rgba(var(--glass-rgb), 0.7);padding: 2px 6px;border-radius: var(--r-xs);border: 1px solid var(--star-line);@@ -598,7 +598,7 @@left: 12px;font-size: var(--fs-xs);color: var(--text-dim);- background: rgba(14, 15, 18, 0.62);+ background: rgba(var(--glass-rgb), 0.62);padding: 3px 8px;border-radius: var(--r-sm);border: 1px solid var(--line);@@ -614,7 +614,7 @@align-items: center;gap: 2px;padding: 3px;- background: rgba(14, 15, 18, 0.72);+ background: rgba(var(--glass-rgb), 0.72);border: 1px solid var(--line);border-radius: var(--r-sm);backdrop-filter: blur(6px);@@ -651,7 +651,7 @@padding: 0 10px;font-size: var(--fs-xs);color: var(--text);- background: rgba(19, 24, 38, 0.72);+ background: rgba(var(--glass-rgb), 0.72);backdrop-filter: blur(8px);border: 1px solid var(--line);border-radius: var(--r-sm);@@ -675,7 +675,7 @@font-weight: 600;letter-spacing: 0.1em;color: var(--run);- background: rgba(8, 11, 18, 0.8);+ background: rgba(var(--glass-rgb), 0.8);border: 1px solid rgba(76, 174, 135, 0.5);padding: 4px 12px;border-radius: 999px;@@ -698,7 +698,7 @@padding: 14px 18px;font-size: var(--fs-sm);color: var(--text);- background: rgba(13, 17, 27, 0.82);+ background: rgba(var(--glass-rgb), 0.82);backdrop-filter: blur(10px);border: 1px solid var(--line);border-radius: var(--r-md);@@ -761,16 +761,31 @@color: var(--text-faint);}+/* Top inspector toolbar: UE5-style compact "+ Add" button + inline search field. */+.inspector-bar {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 6px 10px;+ border-bottom: 1px solid var(--line-soft);+ flex-shrink: 0;+}/* Inspector field/component search (UE5 Details filter). */.inspector-search {display: flex;align-items: center;gap: 6px;- height: 30px;- padding: 0 10px;- border-bottom: 1px solid var(--line-soft);+ flex: 1;+ min-width: 0;+ height: 26px;+ padding: 0 8px;+ background: var(--input);+ border: 1px solid var(--line);+ border-radius: var(--r-sm);color: var(--text-faint);- flex-shrink: 0;+}+.inspector-search:focus-within {+ border-color: var(--star-line);}.inspector-search__input {flex: 1;@@ -792,7 +807,7 @@display: flex;align-items: center;gap: 7px;- height: 32px;+ height: 28px;padding: 0 10px;background: var(--elevated);cursor: pointer;@@ -1112,21 +1127,109 @@}.add-component {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ flex-shrink: 0;+ height: 26px;+ padding: 0 9px 0 8px;+ font-size: var(--fs-sm);+ font-weight: 600;+ white-space: nowrap;+ color: #f3f6f4;+ background: var(--create);+ border: 1px solid var(--create);+ border-radius: var(--r-sm);+}+.add-component:hover {+ background: var(--create-hi);+ border-color: var(--create-hi);+ color: #fff;+}+.add-component__caret {+ opacity: 0.75;+}++/* UE5-style Add Component picker: search + category groups + icons, keyboard-nav. */+.addcomp {+ position: fixed;+ z-index: 200;+ display: flex;+ flex-direction: column;+ background: var(--raised);+ border: 1px solid var(--line-strong);+ border-radius: var(--r-md);+ box-shadow: var(--shadow-pop);+ overflow: hidden;+}+.addcomp__search {display: flex;align-items: center;- justify-content: center;gap: 6px;- margin: 12px 10px;- height: 30px;+ padding: 7px 9px;+ border-bottom: 1px solid var(--line);+ color: var(--text-dim);+ flex-shrink: 0;+}+.addcomp__input {+ flex: 1;+ min-width: 0;+ background: transparent;+ border: none;+ outline: none;+ color: var(--text-hi);font-size: var(--fs-sm);- font-weight: 500;- color: var(--star-hi);+}+.addcomp__input::placeholder {+ color: var(--text-faint);+}+.addcomp__list {+ overflow-y: auto;+ padding: 4px;+}+.addcomp__cat {+ padding: 7px 8px 3px;+ font-size: var(--fs-2xs);+ font-weight: 600;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--text-faint);+}+.addcomp__item {+ display: flex;+ align-items: center;+ gap: 8px;+ width: 100%;+ height: 26px;+ padding: 0 8px;+ border-radius: var(--r-xs);+ color: var(--text);+ text-align: left;+}+.addcomp__item.is-active {background: var(--star-dim);- border: 1px solid var(--star-line);- border-radius: var(--r-sm);+ color: var(--text-hi);}-.add-component:hover {- background: rgba(76, 143, 214, 0.22);+.addcomp__icon {+ display: flex;+ flex-shrink: 0;+ color: var(--text-dim);+}+.addcomp__item.is-active .addcomp__icon {+ color: var(--star-hi);+}+.addcomp__label {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: var(--fs-sm);+}+.addcomp__empty {+ padding: 18px 12px;+ text-align: center;+ font-size: var(--fs-xs);+ color: var(--text-faint);}.inspector-note {diff --git a/desktop/src/theme/dockview-theme.css b/desktop/src/theme/dockview-theme.cssindex 0ecb8bac1..ae6e70425 100644--- a/desktop/src/theme/dockview-theme.css+++ b/desktop/src/theme/dockview-theme.css@@ -16,7 +16,7 @@/* Tab strip */--dv-tabs-and-actions-container-background-color: var(--elevated);- --dv-tabs-and-actions-container-height: 34px;+ --dv-tabs-and-actions-container-height: 28px;--dv-tabs-and-actions-container-font-size: var(--fs-sm);--dv-tab-divider-color: transparent;@@ -48,9 +48,10 @@--dv-tabs-container-scrollbar-color: var(--line-strong);}-/* The focused group gets a thin starlight top-edge — the one "glow" accent. */+/* The focused group gets a subtle neutral top-edge; the active TAB carries the+ one starlight accent (its underline), so blue stays reserved for selection. */.dockview-theme-estella .dv-groupview.dv-active-group > .dv-tabs-and-actions-container {- box-shadow: inset 0 2px 0 -1px var(--star);+ box-shadow: inset 0 1px 0 0 var(--line-strong);}/* Tabs: hairline-separated, instrument-like, with a starlight underline when active. */diff --git a/desktop/src/theme/launcher.css b/desktop/src/theme/launcher.cssindex 8cebddf1e..4ecab0480 100644--- a/desktop/src/theme/launcher.css+++ b/desktop/src/theme/launcher.css@@ -326,7 +326,7 @@right: 8px;padding: 2px 6px;border-radius: var(--r-xs);- background: rgba(8, 11, 18, 0.66);+ background: rgba(var(--glass-rgb), 0.66);border: 1px solid var(--line);font-size: var(--fs-2xs);color: var(--text-dim);diff --git a/desktop/src/theme/tokens.css b/desktop/src/theme/tokens.cssindex 3a51840e9..257e32df8 100644--- a/desktop/src/theme/tokens.css+++ b/desktop/src/theme/tokens.css@@ -18,6 +18,7 @@--input: #15161a; /* fields, wells (darker than panel) */--hover: rgba(255, 255, 255, 0.05);--pressed: rgba(255, 255, 255, 0.08);+ --glass-rgb: 14, 15, 18; /* neutral base for floating overlays (was navy-tinted) *//* — Structure: neutral hairlines do the visual work, not boxes — */--line: #2b2e34;@@ -41,6 +42,8 @@/* — Semantic (muted, flat) — */--run: #4cae87; /* play / running */--run-glow: 0 0 0 1px rgba(76, 174, 135, 0.45);+ --create: #2c9a55; /* additive/create actions (UE5 "+Add" green), distinct from play */+ --create-hi: #34b163;--warn: #e0a049; /* amber / warnings */--error: #e06464;@@ -64,7 +67,7 @@/* — Chrome heights (tightened a notch for density) — */--h-titlebar: 28px;- --h-toolbar: 40px;+ --h-toolbar: 36px;--h-statusbar: 22px;/* — Elevation — */diff --git a/desktop/tests/commands.test.ts b/desktop/tests/commands.test.tsnew file mode 100644index 000000000..39896a71a--- /dev/null+++ b/desktop/tests/commands.test.ts@@ -0,0 +1,71 @@+/**+ * @file Editor command system — keybinding parsing/matching/formatting and the+ * registry's event resolution + enablement gating. Pure logic (no WASM):+ * importing '@/commands' registers every editor command as a side effect.+ */+import { describe, it, expect } from 'vitest';+import { eventToChord, normalizeChord, chordMatches, formatKeybinding } from '@/commands/keybinding';+import { commands } from '@/commands';++const ev = (+ key: string,+ mods: { mod?: boolean; shift?: boolean; alt?: boolean } = {},+): KeyboardEvent =>+ ({+ key,+ metaKey: !!mods.mod,+ ctrlKey: false,+ shiftKey: !!mods.shift,+ altKey: !!mods.alt,+ }) as KeyboardEvent;++describe('keybinding', () => {+ it('eventToChord canonicalizes modifiers + key', () => {+ expect(eventToChord(ev('s', { mod: true }))).toBe('mod+s');+ expect(eventToChord(ev('S', { mod: true, shift: true }))).toBe('mod+shift+s');+ expect(eventToChord(ev('Delete'))).toBe('delete');+ expect(eventToChord(ev('Escape'))).toBe('escape');+ expect(eventToChord(ev('F5'))).toBe('f5');+ });++ it('normalizeChord reorders + aliases modifiers', () => {+ expect(normalizeChord('shift+mod+s')).toBe('mod+shift+s');+ expect(normalizeChord('cmd+z')).toBe('mod+z');+ expect(normalizeChord('ctrl+y')).toBe('mod+y');+ expect(normalizeChord('Delete')).toBe('delete');+ });++ it('chordMatches handles single + multi bindings', () => {+ expect(chordMatches(ev('z', { mod: true, shift: true }), ['mod+shift+z', 'mod+y'])).toBe(true);+ expect(chordMatches(ev('y', { mod: true }), ['mod+shift+z', 'mod+y'])).toBe(true);+ expect(chordMatches(ev('z', { mod: true }), 'mod+z')).toBe(true);+ expect(chordMatches(ev('z', { mod: true, shift: true }), 'mod+z')).toBe(false); // shift differs+ });++ it('formatKeybinding renders a hint from the first chord', () => {+ expect(formatKeybinding('mod+s')).toMatch(/S$/);+ expect(formatKeybinding(['mod+shift+z', 'mod+y'])).toMatch(/Z$/);+ });+});++describe('command registry', () => {+ it('forEvent resolves an enabled command by chord', () => {+ // tool.move ('w') has no isEnabled → always enabled.+ expect(commands.forEvent(ev('w'))?.id).toBe('tool.move');+ expect(commands.forEvent(ev('q'))?.id).toBe('tool.select');+ });++ it('forEvent skips a disabled command', () => {+ // edit.undo ('mod+z') is disabled with an empty history → no match.+ expect(commands.forEvent(ev('z', { mod: true }))).toBeUndefined();+ });++ it('registers the editor commands with ids + labels', () => {+ const ids = commands.all().map((c) => c.id);+ expect(ids).toContain('entity.delete');+ expect(ids).toContain('play.toggle');+ expect(ids).toContain('view.toggleGrid');+ expect(commands.get('entity.delete')?.label).toBe('Delete');+ expect(commands.get('entity.delete')?.keybinding).toEqual(['delete', 'backspace']);+ });+});diff --git a/desktop/tests/selection-store.test.ts b/desktop/tests/selection-store.test.tsnew file mode 100644index 000000000..37061eeb4--- /dev/null+++ b/desktop/tests/selection-store.test.ts@@ -0,0 +1,116 @@+/**+ * @file SelectionStore — engine-anchored entity selection.+ *+ * Covers the pure selection ops and, crucially, the SELF-HEALING property that+ * lets every call site stop hand-clearing selection: when an entity is despawned+ * the scene bridge carries its id to the store, which drops it — no manual+ * deselect, no world.valid() race (the despawn notify fires before removal).+ *+ * EngineHost is mocked to a headless World built from the WASM SDK (same harness+ * as engine-commands.test.ts); SceneStore + SceneCommands run for real.+ */+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';+import { App } from 'esengine';+import type { ESEngineModule } from 'esengine';+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';++const host = vi.hoisted(() => ({ world: null as unknown as App['world'] }));+vi.mock('@/engine/EngineHost', () => ({+ EngineHost: {+ mutableWorld: () => host.world,+ get world() {+ return host.world;+ },+ getResource: () => undefined,+ },+}));++import { useSelection } from '@/store/selectionStore';+import { SceneStore } from '@/engine/SceneStore';+import { SceneCommands } from '@/engine/SceneCommands';++const sel = () => useSelection.getState();++describe('SelectionStore — pure selection ops', () => {+ beforeEach(() => sel().select(null));++ it('select / toggleSelect / selectMany maintain the set + primary', () => {+ sel().select(5);+ expect(sel().selectedId).toBe(5);+ expect([...sel().selectedIds]).toEqual([5]);++ sel().toggleSelect(6);+ expect(sel().selectedId).toBe(6);+ expect(sel().selectedIds.has(5)).toBe(true);+ expect(sel().selectedIds.has(6)).toBe(true);++ sel().toggleSelect(6); // removing the primary falls back to a remaining id+ expect(sel().selectedIds.has(6)).toBe(false);+ expect(sel().selectedId).toBe(5);++ sel().selectMany([1, 2, 3], 2);+ expect([...sel().selectedIds].sort()).toEqual([1, 2, 3]);+ expect(sel().selectedId).toBe(2);++ sel().select(null);+ expect(sel().selectedId).toBeNull();+ expect(sel().selectedIds.size).toBe(0);+ });++ it('dropId removes one id and re-picks the primary', () => {+ sel().selectMany([1, 2, 3], 2);+ sel().dropId(2); // drop the primary+ expect(sel().selectedIds.has(2)).toBe(false);+ expect(sel().selectedIds.size).toBe(2);+ expect(sel().selectedId).toBe(3); // last of the remaining++ sel().dropId(1); // drop a non-primary+ expect(sel().selectedId).toBe(3);+ expect(sel().selectedIds.size).toBe(1);++ sel().dropId(3);+ expect(sel().selectedId).toBeNull();+ expect(sel().selectedIds.size).toBe(0);++ sel().dropId(99); // no-op on an unselected id+ expect(sel().selectedId).toBeNull();+ });+});++describe.skipIf(!HAS_WASM)('SelectionStore — engine-anchored self-healing', () => {+ // One World + one bridge install for the whole block, so the default context+ // (which notifyBridge reads) stays consistent across tests.+ beforeAll(async () => {+ const module: ESEngineModule = await loadWasmModule();+ const app = App.new();+ const registry = new module.Registry();+ app.connectCpp(registry as never, module);+ host.world = app.world;+ SceneStore.install();+ });+ beforeEach(() => sel().select(null));++ it('a deleted entity auto-drops from the selection via the scene bridge', () => {+ const id = SceneCommands.addEntity()!;+ sel().select(id);+ expect(sel().selectedId).toBe(id);++ // Delete via the command path → world.despawn → onEntityDespawned bridge →+ // SelectionStore.dropId. The selection clears itself, no manual deselect.+ SceneCommands.deleteEntity(id);+ expect(sel().selectedId).toBeNull();+ expect(sel().selectedIds.size).toBe(0);+ });++ it('deleting one of a multi-selection keeps the survivors selected', () => {+ const a = SceneCommands.addEntity()!;+ const b = SceneCommands.addEntity()!;+ sel().selectMany([a, b], b);+ expect(sel().selectedIds.size).toBe(2);++ SceneCommands.deleteEntity(b); // bridge drops b; a survives and becomes primary+ expect(sel().selectedIds.has(b)).toBe(false);+ expect(sel().selectedIds.has(a)).toBe(true);+ expect(sel().selectedId).toBe(a);+ });+});