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
refactor: decompose Editor god object into service-oriented architecture
esengine19e79a58694a
diff --git a/editor/src/DockLayoutManager.ts b/editor/src/DockLayoutManager.tsindex 77ac7b7db..af3c6562e 100644--- a/editor/src/DockLayoutManager.ts+++ b/editor/src/DockLayoutManager.ts@@ -31,16 +31,14 @@ class EditorPanelRenderer implements IContentRenderer {private readonly element_: HTMLElement;private panelId_: string;private panelManager_: PanelManager;- private store_: EditorStore;get element(): HTMLElement {return this.element_;}- constructor(panelId: string, panelManager: PanelManager, store: EditorStore) {+ constructor(panelId: string, panelManager: PanelManager) {this.panelId_ = panelId;this.panelManager_ = panelManager;- this.store_ = store;this.element_ = document.createElement('div');this.element_.className = 'es-panel-container';this.element_.dataset.panelId = panelId;@@ -50,7 +48,7 @@ class EditorPanelRenderer implements IContentRenderer {}init(_params: GroupPanelPartInitParameters): void {- this.panelManager_.createPanelInContainer(this.panelId_, this.element_, this.store_);+ this.panelManager_.createPanelInContainer(this.panelId_, this.element_);}dispose(): void {@@ -92,7 +90,6 @@ export class DockLayoutManager {return new EditorPanelRenderer(options.id,this.panelManager_,- this.store_,);},disableFloatingGroups: true,diff --git a/editor/src/Editor.ts b/editor/src/Editor.tsindex f0db87df0..8d0d7b864 100644--- a/editor/src/Editor.ts+++ b/editor/src/Editor.ts@@ -1,60 +1,52 @@-import type { App, Entity } from 'esengine';-import type { EntityData } from './types/SceneTypes';-import * as esengine from 'esengine';-import {- Draw, Geometry, Material, BlendMode, DataType, ShaderSources,- PostProcess, Renderer, RenderStage,- registerDrawCallback, unregisterDrawCallback, clearDrawCallbacks,-} from 'esengine';+import type { App } from 'esengine';import { EditorStore } from './store/EditorStore';-import { EditorBridge } from './bridge/EditorBridge';import { PanelManager } from './PanelManager';import { MenuManager } from './MenuManager';-import { PreviewManager } from './PreviewManager';-import { getAllPanels } from './panels/PanelRegistry';import { exposeRegistrationAPI } from './schemas/ComponentSchemas';-import {- EditorContainer, setEditorContainer, getEditorContainer,- PANEL,-} from './container';-import * as containerTokens from './container/tokens';-import { saveSceneToFile, saveSceneToPath, loadSceneFromFile, loadSceneFromPath, hasFileHandle, clearFileHandle } from './io/SceneSerializer';-import { isAbsolutePath, joinPath, getProjectDir } from './utils/path';+import { EditorContainer, setEditorContainer, getEditorContainer } from './container';import { icons } from './utils/icons';-import { ScriptLoader } from './scripting';-import { showBuildSettingsDialog, BuildService } from './builder';-import { AddressablePanel } from './panels/AddressablePanel';-import { getGlobalPathResolver } from './asset';-import { getSharedRenderContext } from './renderer/SharedRenderContext';import type { EditorAssetServer } from './asset/EditorAssetServer';-import { getAssetLibrary } from './asset/AssetLibrary';-import { setEditorInstance, getEditorContext, getEditorInstance } from './context/EditorContext';-import { ExtensionLoader } from './extension';-import { setEditorAPI, clearEditorAPI } from './extension/editorAPI';-import { showToast, showSuccessToast, showErrorToast } from './ui/Toast';-import { showContextMenu } from './ui/ContextMenu';+import { setEditorInstance } from './context/EditorContext';+import { showToast, showErrorToast } from './ui/Toast';import { installGlobalErrorHandler } from './error/GlobalErrorHandler';import { EditorLogger, createConsoleHandler, createToastHandler } from './logging';-import type { EditorPlugin, EditorPluginContext } from './plugins/EditorPlugin';import { builtinPlugins, coreStatusbarPlugin } from './plugins';--import { showConfirmDialog, showInputDialog, showDialog } from './ui/dialog';+import { PluginManager as PluginManagerService } from './services/PluginManager';import { getEditorStore } from './store';-import { generateUniqueName } from './utils/naming';-import {- showSettingsDialog,- getSettingsValue,- setSettingsValue,- onSettingsChange,- ProjectSettingsSync,-} from './settings';-import { loadEditorLocalSettings, saveEditorLocalSetting } from './launcher/ProjectService';import { DockLayoutManager } from './DockLayoutManager';import { ContentDrawer } from './ui/ContentDrawer';-import { MainWindowBridge } from './multiwindow/MainWindowBridge';-import { WindowManager } from './multiwindow/WindowManager';-import { emit } from '@tauri-apps/api/event';-import { CHANNEL_PROFILER_STATS } from './multiwindow/protocol';+import { closeAddressableWindow, hasAddressableWindow } from './dialogs/AddressableWindow';++import { OutputService } from './services/OutputService';+import { ClipboardService } from './services/ClipboardService';+import { ShellService } from './services/ShellService';+import { ProfilerService } from './services/ProfilerService';+import { NavigationService } from './services/NavigationService';+import { SpineService } from './services/SpineService';+import { RuntimeService } from './services/RuntimeService';+import { ScriptService } from './services/ScriptService';+import { ExtensionService } from './services/ExtensionService';+import { PreviewService } from './services/PreviewService';+import { SceneService } from './services/SceneService';+import { ProjectService } from './services/ProjectService';+import { MultiWindowService } from './services/MultiWindowService';+import {+ OUTPUT_SERVICE,+ CLIPBOARD_SERVICE,+ SHELL_SERVICE,+ PROFILER_SERVICE,+ NAVIGATION_SERVICE,+ SPINE_SERVICE,+ RUNTIME_SERVICE,+ SCRIPT_SERVICE,+ EXTENSION_SERVICE,+ PREVIEW_SERVICE,+ SCENE_SERVICE,+ PROJECT_SERVICE,+ MULTI_WINDOW_SERVICE,+ LAYOUT_SERVICE,+ PLUGIN_MANAGER,+} from './container/tokens';export interface EditorOptions {projectPath?: string;@@ -62,38 +54,31 @@ export interface EditorOptions {export class Editor {private container_: HTMLElement;- private app_: App | null = null;- private spineModule_: unknown = null;- private spineVersion_: string = 'none';- private spineVersionChangeHandler_: ((version: string) => void) | null = null;private store_: EditorStore;- private bridge_: EditorBridge | null = null;private projectPath_: string | null = null;private panelManager_: PanelManager;private menuManager_: MenuManager;- private previewManager_: PreviewManager;- private baseAPI_: Record<string, unknown> | null = null;- private scriptLoader_: ScriptLoader | null = null;- private extensionLoader_: ExtensionLoader | null = null;private dockLayout_: DockLayoutManager | null = null;private contentDrawer_: ContentDrawer | null = null;- private assetLibraryReady_: Promise<void> = Promise.resolve();- private scriptsReady_: Promise<void> = Promise.resolve();- private clipboard_: EntityData[] | null = null;- private addressableWindow_: { element: HTMLElement; panel: AddressablePanel; keyHandler: (e: KeyboardEvent) => void } | null = null;- private profilerActive_ = false;- private previewUrl_: string | null = null;private escapeHandler_: ((e: KeyboardEvent) => void) | null = null;- private closeUnlisten_: (() => void) | null = null;private contextMenuHandler_: ((e: Event) => void) | null = null;- private settingsSync_: ProjectSettingsSync | null = null;- private mainWindowBridge_: MainWindowBridge | null = null;- private windowManager_: WindowManager | null = null;- private plugins_: EditorPlugin[] = [];- private pluginNames_ = new Set<string>();- private pluginContext_!: EditorPluginContext;+ private pluginManager_!: PluginManagerService;++ private outputService_!: OutputService;+ private clipboardService_!: ClipboardService;+ private shellService_!: ShellService;+ private profilerService_!: ProfilerService;+ private navigationService_!: NavigationService;+ private spineService_!: SpineService;+ private runtimeService_!: RuntimeService;+ private scriptService_!: ScriptService;+ private extensionService_!: ExtensionService;+ private previewService_!: PreviewService;+ private sceneService_!: SceneService;+ private projectService_!: ProjectService;+ private multiWindowService_!: MultiWindowService;constructor(container: HTMLElement, options?: EditorOptions) {this.container_ = container;@@ -102,12 +87,10 @@ export class Editor {const iocContainer = new EditorContainer();setEditorContainer(iocContainer);- this.pluginContext_ = {+ this.pluginManager_ = new PluginManagerService({registrar: iocContainer,- editor: this,projectPath: this.projectPath_,- onOpenScene: (path: string) => this.openSceneFromPath(path),- };+ });installGlobalErrorHandler();@@ -119,866 +102,151 @@ export class Editor {EditorLogger.setMinLevel('info');for (const plugin of builtinPlugins) {- this.addPlugin(plugin);+ this.pluginManager_.addPlugin(plugin);}this.store_ = getEditorStore();this.panelManager_ = new PanelManager();this.menuManager_ = new MenuManager();this.menuManager_.setStore(this.store_);- this.previewManager_ = new PreviewManager(this.projectPath_);++ this.createServices_(iocContainer);+exposeRegistrationAPI();iocContainer.lockBuiltins();- this.setupLayout();+ this.setupLayout_();- this.addPlugin(coreStatusbarPlugin);+ this.pluginManager_.addPlugin(coreStatusbarPlugin);this.menuManager_.instantiateStatusbar(this.container_);this.menuManager_.setupMenuShortcuts();this.menuManager_.attach();- this.initMultiWindow();+ this.initMultiWindow_();if (this.projectPath_) {- this.setupEditorGlobals();- this.assetLibraryReady_ = this.initializeAssetLibrary();- this.scriptsReady_ = this.initializeAllScripts();- this.initProjectSettingsSync();- this.restoreLastScene();+ this.extensionService_.setupEditorGlobals();+ const assetReady = this.projectService_.initializeAssetLibrary();+ this.sceneService_.setAssetLibraryReady(assetReady);+ const scriptsReady = this.initializeAllScripts_();+ this.sceneService_.setScriptsReady(scriptsReady);+ this.projectService_.initProjectSettingsSync();+ this.sceneService_.restoreLastScene();}}- addPlugin(plugin: EditorPlugin): this {- if (this.pluginNames_.has(plugin.name)) return this;- if (plugin.dependencies) {- for (const dep of plugin.dependencies) {- if (!this.pluginNames_.has(dep)) {- throw new Error(`Plugin "${plugin.name}" requires "${dep}"`);- }- }- }- plugin.register(this.pluginContext_);- this.plugins_.push(plugin);- this.pluginNames_.add(plugin.name);- return this;- }+ // =========================================================================+ // Public API (used by desktop/main.ts)+ // =========================================================================get projectPath(): string | null {return this.projectPath_;}- get currentScenePath(): string | null {- return this.store_.filePath;- }-- setApp(app: App): void {- this.app_ = app;- this.bridge_ = new EditorBridge(app, this.store_);- this.panelManager_.setApp(app, this.bridge_);- }-- setPhysicsFactory(factory: unknown): void {- getSharedRenderContext().setPhysicsFactory(factory);- }-- setSpineModule(module: unknown, version: string): void {- this.spineModule_ = module;- this.spineVersion_ = version;- this.panelManager_.setSpineModule(module);- this.store_.notifyChange();- }-- onSpineVersionChange(handler: (version: string) => void): void {- this.spineVersionChangeHandler_ = handler;- }-- get spineModule(): unknown {- return this.spineModule_;- }-- get spineVersion(): string {- return this.spineVersion_;- }-get store(): EditorStore {return this.store_;}get assetServer(): EditorAssetServer | null {- return this.panelManager_.assetServer;- }-- getSpineSkeletonInfo(entityId: number): { animations: string[]; skins: string[] } | null {- return this.panelManager_.getSpineSkeletonInfo(entityId);- }-- onSpineInstanceReady(listener: (entityId: number) => void): () => void {- return this.panelManager_.onSpineInstanceReady(listener);- }-- // =========================================================================- // Panel Operations- // =========================================================================-- showPanel(id: string): void {- if (id === 'content-browser') {- this.contentDrawer_?.toggle();- return;- }- this.dockLayout_?.showPanel(id);- this.panelManager_.showPanel(id);- }-- hidePanel(id: string): void {- this.panelManager_.hidePanel(id);- }-- togglePanel(id: string): void {- if (id === 'content-browser') {- this.contentDrawer_?.toggle();- return;- }- const panel = this.dockLayout_?.api?.getPanel(id);- if (panel) {- this.dockLayout_!.removePanel(id);- this.panelManager_.removePanelInstance(id);- } else {- this.showPanel(id);- }- }-- resetLayout(): void {- this.contentDrawer_?.onResetLayout();- this.dockLayout_?.resetLayout();- }-- // =========================================================================- // Scene Operations- // =========================================================================-- async newScene(): Promise<void> {- if (this.store_.isDirty) {- const result = await this.showUnsavedChangesPrompt();- if (result === 'cancel') return;- if (result === 'save') await this.saveScene();- }- const w = getSettingsValue<number>('project.designWidth');- const h = getSettingsValue<number>('project.designHeight');- this.store_.newScene('Untitled', { width: w, height: h });- clearFileHandle();- }-- async saveScene(): Promise<void> {- if (this.store_.isEditingPrefab) {- await this.store_.savePrefabEditing();- return;- }-- await this.saveDirtyPanels();-- const filePath = this.store_.filePath;-- if (filePath && hasFileHandle()) {- const success = await saveSceneToPath(this.store_.scene, filePath);- if (success) {- this.store_.markSaved();- this.previewManager_.refreshFiles(this.store_.scene, this.scriptLoader_, this.spineVersion_);- return;- }- }-- const savedPath = await saveSceneToFile(this.store_.scene);- if (savedPath) {- this.store_.markSaved(savedPath);- this.previewManager_.refreshFiles(this.store_.scene, this.scriptLoader_, this.spineVersion_);- }- }-- private async saveDirtyPanels(): Promise<void> {- await this.panelManager_.saveDirtyPanels();- }-- async saveSceneAs(): Promise<void> {- clearFileHandle();- const savedPath = await saveSceneToFile(this.store_.scene);- if (savedPath) {- this.store_.markSaved(savedPath);- }- }-- async loadScene(): Promise<void> {- if (this.store_.isDirty) {- const result = await this.showUnsavedChangesPrompt();- if (result === 'cancel') return;- if (result === 'save') await this.saveScene();- }- await this.assetLibraryReady_;- const scene = await loadSceneFromFile();- if (scene) {- await getAssetLibrary().migrateScene(scene);- this.store_.loadScene(scene);- }- }-- async openSceneFromPath(scenePath: string): Promise<void> {- if (this.store_.isEditingPrefab) {- await this.store_.exitPrefabEditMode();- }-- let resolvedPath = scenePath;- if (!isAbsolutePath(scenePath) && this.projectPath_) {- const projectDir = getProjectDir(this.projectPath_);- resolvedPath = joinPath(projectDir, scenePath);- }-- await this.assetLibraryReady_;- const scene = await loadSceneFromPath(resolvedPath);- if (scene) {- const migrated = await getAssetLibrary().migrateScene(scene);- if (migrated) {- await saveSceneToPath(scene, resolvedPath);- }- this.store_.loadScene(scene, resolvedPath);- this.saveLastOpenedScene(scenePath);- console.log('Scene loaded:', resolvedPath);- }- }-- duplicateSelected(): void {- const selected = Array.from(this.store_.selectedEntities);- if (selected.length === 0) return;-- for (const id of selected) {- const entityData = this.store_.getEntityData(id);- if (!entityData) continue;-- const scene = this.store_.scene;- const siblings = scene.entities- .filter(e => e.parent === entityData.parent)- .map(e => e.name);- const siblingNames = new Set(siblings);- const newName = generateUniqueName(entityData.name, siblingNames);-- const newEntity = this.store_.createEntity(- newName,- entityData.parent as Entity | null- );-- for (const comp of entityData.components) {- this.store_.addComponent(newEntity, comp.type, JSON.parse(JSON.stringify(comp.data)));- }- }- }-- copySelected(): void {- const selected = Array.from(this.store_.selectedEntities);- if (selected.length === 0) return;-- const allTrees: EntityData[] = [];- for (const id of selected) {- const tree = this.collectEntityTree_(id);- allTrees.push(...tree);- }- if (allTrees.length === 0) return;-- this.clipboard_ = JSON.parse(JSON.stringify(allTrees));- for (const e of this.clipboard_!) {- delete e.prefab;- }- }-- pasteEntity(): void {- if (!this.clipboard_ || this.clipboard_.length === 0) return;-- const cloned: EntityData[] = JSON.parse(JSON.stringify(this.clipboard_));- const parent = this.store_.selectedEntity;- const clipboardIds = new Set(cloned.map(e => e.id));- const oldIdToNewId = new Map<number, Entity>();-- const scene = this.store_.scene;- const siblings = scene.entities- .filter(e => e.parent === (parent as number | null))- .map(e => e.name);- const siblingNames = new Set(siblings);-- let lastRoot: Entity | null = null;-- for (const entityData of cloned) {- const isRoot = entityData.parent === null || !clipboardIds.has(entityData.parent);- const newParent = isRoot ? parent : (oldIdToNewId.get(entityData.parent!) ?? null);- if (!isRoot && newParent === null) continue;-- const name = isRoot- ? generateUniqueName(entityData.name, siblingNames)- : entityData.name;-- const newEntity = this.store_.createEntity(name, newParent);- oldIdToNewId.set(entityData.id, newEntity);-- if (isRoot) {- siblingNames.add(name);- lastRoot = newEntity;- }-- for (const comp of entityData.components) {- this.store_.addComponent(newEntity, comp.type, { ...comp.data });- }- }-- if (lastRoot !== null) {- this.store_.selectEntity(lastRoot);- }- }-- hasClipboard(): boolean {- return this.clipboard_ !== null && this.clipboard_.length > 0;- }-- private collectEntityTree_(entityId: number): EntityData[] {- const entity = this.store_.getEntityData(entityId);- if (!entity) return [];- const result: EntityData[] = [entity];- for (const childId of entity.children) {- result.push(...this.collectEntityTree_(childId));- }- return result;- }-- showBuildSettings(): void {- if (!this.projectPath_) {- alert('请先打开一个项目');- return;- }-- const buildService = new BuildService(this.projectPath_);- showBuildSettingsDialog({- projectPath: this.projectPath_,- onBuild: async (config) => {- return await buildService.build(config);- },- onClose: () => {},- });- }-- showAboutDialog(): void {- const hasUpdater = !!getEditorContext().onCheckUpdate;- const overlay = document.createElement('div');- overlay.className = 'es-dialog-overlay';- overlay.innerHTML = `- <div class="es-dialog" style="max-width: 360px;">- <div class="es-dialog-header">- <span class="es-dialog-title">About ESEngine</span>- <button class="es-dialog-close">×</button>- </div>- <div class="es-dialog-body" style="text-align: center; padding: 24px;">- <div style="margin-bottom: 16px;">${icons.logo(64)}</div>- <h3 style="margin: 0 0 8px; color: var(--es-text-primary);">ESEngine Editor</h3>- <p style="margin: 0 0 16px; color: var(--es-text-secondary);">Version ${getEditorContext().version ?? '0.0.0'}</p>- <p style="margin: 0; font-size: 12px; color: var(--es-text-secondary);">- A lightweight 2D game engine<br>for web and mini-programs.- </p>- </div>- <div class="es-dialog-footer" style="justify-content: center; gap: 8px;">- ${hasUpdater ? '<button class="es-dialog-btn" id="about-check-update">Check for Updates</button>' : ''}- <button class="es-dialog-btn es-dialog-btn-primary">OK</button>- </div>- </div>- `;-- const close = () => overlay.remove();- overlay.querySelector('.es-dialog-close')?.addEventListener('click', close);- overlay.querySelector('.es-dialog-btn-primary')?.addEventListener('click', close);- overlay.querySelector('#about-check-update')?.addEventListener('click', () => {- close();- getEditorContext().onCheckUpdate?.();- });- overlay.addEventListener('click', (e) => {- if (e.target === overlay) close();- });-- document.body.appendChild(overlay);- }-- showAddressableWindow(): void {- if (this.addressableWindow_) {- this.addressableWindow_.element.style.zIndex = '1001';- return;- }-- const win = document.createElement('div');- win.className = 'es-floating-window es-addressable-window';- win.innerHTML = `- <div class="es-floating-header">- <span class="es-floating-title">Addressable Groups</span>- <button class="es-dialog-close">×</button>- </div>- <div class="es-floating-body"></div>- `;-- const body = win.querySelector('.es-floating-body') as HTMLElement;- const panel = new AddressablePanel(body, this.store_);-- const close = () => {- panel.dispose();- win.remove();- document.removeEventListener('keydown', keyHandler);- this.addressableWindow_ = null;- };-- win.querySelector('.es-dialog-close')!.addEventListener('click', close);-- const header = win.querySelector('.es-floating-header') as HTMLElement;- header.addEventListener('mousedown', (e) => {- if ((e.target as HTMLElement).closest('.es-dialog-close')) return;- const rect = win.getBoundingClientRect();- win.style.left = `${rect.left}px`;- win.style.top = `${rect.top}px`;- win.style.transform = 'none';- const offsetX = e.clientX - rect.left;- const offsetY = e.clientY - rect.top;- const onMove = (e: MouseEvent) => {- const w = win.offsetWidth;- const h = win.offsetHeight;- const x = Math.max(0, Math.min(e.clientX - offsetX, window.innerWidth - w));- const y = Math.max(0, Math.min(e.clientY - offsetY, window.innerHeight - h));- win.style.left = `${x}px`;- win.style.top = `${y}px`;- };- const onUp = () => {- document.removeEventListener('mousemove', onMove);- document.removeEventListener('mouseup', onUp);- };- document.addEventListener('mousemove', onMove);- document.addEventListener('mouseup', onUp);- });-- const keyHandler = (e: KeyboardEvent) => {- if (e.key === 'Escape') close();- };- document.addEventListener('keydown', keyHandler);-- document.body.appendChild(win);- this.addressableWindow_ = { element: win, panel, keyHandler };- }-- async showProfilerWindow(): Promise<void> {- if (!this.windowManager_) return;-- await this.windowManager_.detachPanel('profiler', 'Profiler');- this.startProfilerStats();- }-- startProfilerStats(): void {- if (this.profilerActive_) return;- this.profilerActive_ = true;-- const ctx = getSharedRenderContext();- ctx.setPostTickCallback(() => this.emitProfilerStats());- }-- stopProfilerStats(): void {- if (!this.profilerActive_) return;- this.profilerActive_ = false;-- const ctx = getSharedRenderContext();- ctx.setPostTickCallback(null);+ return this.navigationService_.getAssetServer();}- private emitProfilerStats(): void {- const ctx = getSharedRenderContext();- const app = ctx.app_;-- const frameTimeMs = app?.getPhaseTimings()- ? [...(app.getPhaseTimings() as Map<string, number>).values()].reduce((a: number, b: number) => a + b, 0)- : 0;-- const phaseTimings: [string, number][] = app?.getPhaseTimings()- ? [...(app.getPhaseTimings() as Map<string, number>).entries()]- : [];-- const systemTimings: [string, number][] = app?.getSystemTimings()- ? [...(app.getSystemTimings() as ReadonlyMap<string, number>).entries()]- : [];-- const msg = { frameTimeMs, phaseTimings, systemTimings };- emit(CHANNEL_PROFILER_STATS, msg);- }-- private async initProjectSettingsSync(): Promise<void> {- if (!this.projectPath_) return;- this.settingsSync_ = new ProjectSettingsSync(- this.projectPath_,- (version) => this.spineVersionChangeHandler_?.(version),- );- await this.settingsSync_.loadFromProject();- this.settingsSync_.startAutoSync();+ setApp(app: App): void {+ this.runtimeService_.setApp(app);}- private async restoreLastScene(): Promise<void> {- if (!this.projectPath_) return;- await this.scriptsReady_;- const settings = await loadEditorLocalSettings(this.projectPath_);- const lastScene = settings?.lastOpenedScene as string | undefined;- if (lastScene) {- await this.openSceneFromPath(lastScene);- }+ setPhysicsFactory(factory: unknown): void {+ this.runtimeService_.setPhysicsFactory(factory);}- private saveLastOpenedScene(scenePath: string): void {- if (!this.projectPath_) return;- saveEditorLocalSetting(this.projectPath_, 'lastOpenedScene', scenePath);+ setSpineModule(module: unknown, version: string): void {+ this.spineService_.setSpineModule(module, version);}- showSettings(): void {- showSettingsDialog();+ onSpineVersionChange(handler: (version: string) => void): void {+ this.spineService_.onSpineVersionChange(handler);}// =========================================================================- // Script Operations+ // Plugin system// =========================================================================- private async initializeAssetLibrary(): Promise<void> {- console.log(`[Editor] initializeAssetLibrary: projectPath=${this.projectPath_}`);- if (!this.projectPath_) {- console.warn('[Editor] initializeAssetLibrary: no projectPath');- return;- }-- const fs = getEditorContext().fs;- if (!fs) {- console.warn('[Editor] initializeAssetLibrary: no fs in context');- return;- }-- const projectDir = this.projectPath_.replace(/[/\\][^/\\]+$/, '');- try {- await getAssetLibrary().initialize(projectDir, fs);- } catch (err) {- console.error('Failed to initialize AssetLibrary:', err);- }- }-- private async initializeAllScripts(): Promise<void> {- await this.initializeExtensions();- await this.initializeScripts();- }-- private async initializeScripts(): Promise<void> {- if (!this.projectPath_) return;-- this.scriptLoader_ = new ScriptLoader({- projectPath: this.projectPath_,- onCompileError: (errors) => {- console.error('Script compilation errors:', errors);- const msg = errors.map(e => `${e.file}:${e.line} - ${e.message}`).join('\n');- showErrorToast('Script compile failed', msg);- for (const e of errors) {- this.appendOutput(`${e.file}:${e.line}:${e.column} - ${e.message}`, 'error');- }- },- onCompileSuccess: () => {- this.store_.notifyChange();- },- });-- try {- await this.scriptLoader_.initialize();- await this.scriptLoader_.compile();- await this.scriptLoader_.watch();- } catch (err) {- console.error('Failed to initialize scripts:', err);- }- }-- getCompiledScripts(): string | null {- return this.scriptLoader_?.getCompiledCode() ?? null;- }-- async reloadScripts(): Promise<boolean> {- if (!this.scriptLoader_) {- if (this.projectPath_) {- await this.initializeScripts();- return true;- }- return false;- }- return this.scriptLoader_.reload();+ get pluginManager(): PluginManagerService {+ return this.pluginManager_;}// =========================================================================- // Extension Operations+ // Lifecycle// =========================================================================- private setupEditorGlobals(): void {- const container = getEditorContainer();- const registrar = container as import('./container').PluginRegistrar;-- this.baseAPI_ = {- ...esengine,- registrar,- tokens: containerTokens,- icons,- showToast,- showSuccessToast,- showErrorToast,- showContextMenu,- showConfirmDialog,- showInputDialog,- getEditorInstance,- getEditorStore,- getSettingsValue,- setSettingsValue,- Draw,- Geometry,- Material,- BlendMode,- DataType,- ShaderSources,- PostProcess,- Renderer,- RenderStage,- registerDrawCallback,- unregisterDrawCallback,- clearDrawCallbacks,- };- setEditorAPI(this.baseAPI_);- }-- private async initializeExtensions(): Promise<void> {- if (!this.projectPath_ || !this.baseAPI_) return;-- this.extensionLoader_ = new ExtensionLoader({- projectPath: this.projectPath_,- baseAPI: this.baseAPI_,- onCompileError: (errors) => {- console.error('Extension compilation errors:', errors);- const msg = errors.map(e => `${e.file}:${e.line} - ${e.message}`).join('\n');- showErrorToast(`Extension compile failed:\n${msg}`);- },- onCompileSuccess: () => {},- onCleanup: () => this.cleanupExtensionUI(),- onAfterReload: () => this.applyExtensionUI(),- });-- try {- await this.extensionLoader_.initialize();- await this.extensionLoader_.reload();- await this.extensionLoader_.watch();- } catch (err) {- console.error('Failed to initialize extensions:', err);- }- }-- private cleanupExtensionUI(): void {- const c = getEditorContainer();- if (this.dockLayout_) {- for (const [id] of this.panelManager_.panelInstances) {- if (!c.isBuiltin(PANEL, id)) {- this.dockLayout_.removePanel(id);- }- }- }- this.panelManager_.cleanupExtensionPanels();-- this.container_.querySelectorAll('[data-statusbar-id^="toggle-"]').forEach(el => {- const panelId = el.getAttribute('data-statusbar-id')?.replace('toggle-', '');- if (panelId && !c.isBuiltin(PANEL, panelId)) el.remove();- });-- c.clearExtensions();- }-- private applyExtensionUI(): void {- const c = getEditorContainer();- if (this.dockLayout_) {- for (const desc of getAllPanels()) {- if (c.isBuiltin(PANEL, desc.id)) continue;- this.dockLayout_.addPanel(desc);- }+ dispose(): void {+ if (this.contextMenuHandler_) {+ this.container_.removeEventListener('contextmenu', this.contextMenuHandler_);+ this.contextMenuHandler_ = null;}- this.menuManager_.rebuildMenuBar(this.container_);- }-- async reloadExtensions(): Promise<boolean> {- if (!this.extensionLoader_) {- if (this.projectPath_) {- await this.initializeExtensions();- return true;- }- return false;+ closeAddressableWindow();+ this.profilerService_.stopProfilerStats();+ if (this.escapeHandler_) {+ document.removeEventListener('keydown', this.escapeHandler_);+ this.escapeHandler_ = null;}-- return this.extensionLoader_.reload();+ this.multiWindowService_.dispose();+ this.contentDrawer_?.dispose();+ this.menuManager_.dispose();+ this.scriptService_.dispose();+ this.extensionService_.dispose();+ this.dockLayout_?.dispose();+ this.panelManager_.dispose();+ this.previewService_.dispose();}// =========================================================================- // Preview Operations+ // Private// =========================================================================- async startPreview(): Promise<void> {- if (this.store_.isDirty && this.store_.filePath && hasFileHandle()) {- await this.saveScene();- showToast({ type: 'info', title: 'Scene saved before preview' });- }- const port = await this.previewManager_.startPreview(- this.store_.scene, this.scriptLoader_, this.spineVersion_,+ private createServices_(iocContainer: EditorContainer): void {+ this.outputService_ = new OutputService();+ this.clipboardService_ = new ClipboardService(this.store_);+ this.navigationService_ = new NavigationService(this.panelManager_);+ this.profilerService_ = new ProfilerService();+ this.spineService_ = new SpineService(this.store_);+ this.runtimeService_ = new RuntimeService(this.store_);+ this.scriptService_ = new ScriptService(this.projectPath_, this.outputService_, this.store_);+ this.extensionService_ = new ExtensionService(+ this.projectPath_, this.panelManager_, this.menuManager_, this.container_,);- if (port !== null) {- this.previewUrl_ = `http://localhost:${port}`;- this.updatePreviewUrl();- }- }+ this.sceneService_ = new SceneService(this.store_, this.projectPath_);+ this.projectService_ = new ProjectService(this.projectPath_, this.spineService_);+ this.multiWindowService_ = new MultiWindowService(this.store_, this.projectPath_);- async startPreviewServer(): Promise<string | null> {- if (this.store_.isDirty && this.store_.filePath && hasFileHandle()) {- await this.saveScene();- }- const port = await this.previewManager_.startServer(- this.store_.scene, this.scriptLoader_, this.spineVersion_,+ this.shellService_ = new ShellService(+ this.projectPath_, this.outputService_,+ (id) => this.navigationService_.showPanel(id),);- if (port === null) return null;- this.previewUrl_ = `http://localhost:${port}`;- this.updatePreviewUrl();- return this.previewUrl_;- }-- async stopPreviewServer(): Promise<void> {- await this.previewManager_.stopPreview();- this.previewUrl_ = null;- this.updatePreviewUrl();- }- togglePreviewStats(enabled: boolean): void {- this.previewManager_.setShowStats(enabled);- if (this.previewUrl_) {- this.previewManager_.refreshFiles(- this.store_.scene, this.scriptLoader_, this.spineVersion_,- );- }- }-- get previewStatsEnabled(): boolean {- return this.previewManager_.showStats;- }-- private updatePreviewUrl(): void {- const urlEl = this.container_.querySelector('.es-preview-url') as HTMLElement;- if (!urlEl) return;- if (this.previewUrl_) {- urlEl.textContent = this.previewUrl_;- urlEl.dataset.url = this.previewUrl_;- urlEl.style.display = '';- } else {- urlEl.style.display = 'none';- }- }-- async navigateToAsset(assetPath: string): Promise<void> {- await this.panelManager_.navigateToAsset(assetPath);- }-- // =========================================================================- // Shell Commands- // =========================================================================-- executeCommand(fullCommand: string): void {- this.executeShellCommand(fullCommand);- }-- private async executeShellCommand(fullCommand: string): Promise<void> {- if (!this.projectPath_) {- this.appendOutput('Error: No project loaded\n', 'error');- return;- }-- const shell = getEditorContext().shell;- if (!shell) {- this.appendOutput('Error: Shell not available\n', 'error');- return;- }-- const projectDir = this.projectPath_.replace(/[/\\][^/\\]+$/, '');-- this.showPanel('output');-- const parts = fullCommand.split(/\s+/);- const cmd = parts[0];- const args = parts.slice(1);-- this.appendOutput(`> ${fullCommand}\n`, 'command');-- try {- const result = await shell.execute(cmd, args, projectDir, (stream: string, data: string) => {- this.appendOutput(data + '\n', stream === 'stderr' ? 'stderr' : 'stdout');- });-- if (result.code !== 0) {- this.appendOutput(`Process exited with code ${result.code}\n`, 'error');- } else {- this.appendOutput(`Done.\n`, 'success');- }- } catch (err) {- this.appendOutput(`Error: ${err}\n`, 'error');- }- }-- private installConsoleCapture(): void {- const original = {- log: console.log.bind(console),- info: console.info.bind(console),- warn: console.warn.bind(console),- error: console.error.bind(console),- };-- const formatArg = (a: unknown): string => {- if (typeof a === 'string') return a;- if (a instanceof Error) return `${a.name}: ${a.message}`;- return JSON.stringify(a, null, 2) ?? String(a);- };- const formatArgs = (args: unknown[]) => args.map(formatArg).join(' ');-- const cleanStack = (raw: string | undefined): string => {- if (!raw) return '';- return raw.split('\n')- .filter(line => {- const t = line.trim();- if (!t || t === 'Error') return false;- if (t.includes('/editor/dist/')) return false;- return true;- })- .map(line => line- .replace(/https?:\/\/[^/]+\/@fs/g, '')- .replace(/blob:https?:\/\/[^/]+\/[a-f0-9-]+/g, '<extension>')- )- .join('\n');- };-- const INTERNAL_PREFIXES = [- '[TAURI]', '[INFO]', 'File change:',- ];-- const forward = (type: 'stdout' | 'stderr' | 'error', args: unknown[], stack?: string) => {- const first = typeof args[0] === 'string' ? args[0] : '';- if (INTERNAL_PREFIXES.some(p => first.startsWith(p))) return;-- let text = formatArgs(args);- if (stack) {- text += '\n' + stack;- }- this.appendOutput(text + '\n', type);- };-- console.log = (...args) => { original.log(...args); forward('stdout', args); };- console.info = (...args) => { original.info(...args); forward('stdout', args); };- console.warn = (...args) => { original.warn(...args); forward('stderr', args, cleanStack(new Error().stack)); };- console.error = (...args) => { original.error(...args); forward('error', args, cleanStack(new Error().stack)); };- }-- // =========================================================================- // Layout- // =========================================================================-- private setupLayout(): void {+ const sk = 'default';+ iocContainer.provide(OUTPUT_SERVICE, sk, this.outputService_);+ iocContainer.provide(CLIPBOARD_SERVICE, sk, this.clipboardService_);+ iocContainer.provide(NAVIGATION_SERVICE, sk, this.navigationService_);+ iocContainer.provide(PROFILER_SERVICE, sk, this.profilerService_);+ iocContainer.provide(SHELL_SERVICE, sk, this.shellService_);+ iocContainer.provide(SPINE_SERVICE, sk, this.spineService_);+ iocContainer.provide(RUNTIME_SERVICE, sk, this.runtimeService_);+ iocContainer.provide(SCRIPT_SERVICE, sk, this.scriptService_);+ iocContainer.provide(EXTENSION_SERVICE, sk, this.extensionService_);+ iocContainer.provide(SCENE_SERVICE, sk, this.sceneService_);+ iocContainer.provide(PROJECT_SERVICE, sk, this.projectService_);+ iocContainer.provide(MULTI_WINDOW_SERVICE, sk, this.multiWindowService_);+ iocContainer.provide(LAYOUT_SERVICE, sk, this.navigationService_);+ iocContainer.provide(PLUGIN_MANAGER, sk, this.pluginManager_);+ }++ private async initializeAllScripts_(): Promise<void> {+ await this.extensionService_.initialize();+ await this.scriptService_.initialize();+ }++ private setupLayout_(): void {this.container_.className = 'es-editor';this.container_.innerHTML = `<div class="es-editor-menubar">@@ -1006,16 +274,24 @@ export class Editor {this.container_, this.dockLayout_, this.store_,{projectPath: this.projectPath_ ?? undefined,- onOpenScene: (scenePath) => this.openSceneFromPath(scenePath),+ onOpenScene: (scenePath) => this.sceneService_.openSceneFromPath(scenePath),},);- setEditorInstance(this);+ this.navigationService_.setDockLayout(this.dockLayout_);+ this.navigationService_.setContentDrawer(this.contentDrawer_);+ this.extensionService_.setDockLayout(this.dockLayout_);- if (this.projectPath_) {- const projectDir = this.projectPath_.replace(/[/\\][^/\\]+$/, '');- getGlobalPathResolver().setProjectDir(projectDir);- }+ this.previewService_ = new PreviewService(+ this.projectPath_, this.store_, this.scriptService_, this.spineService_,+ this.container_, () => this.sceneService_.saveScene(),+ );+ this.sceneService_.setPreviewService(this.previewService_);+ getEditorContainer().provide(PREVIEW_SERVICE, 'default', this.previewService_);++ this.projectService_.initializeProjectDir();++ setEditorInstance(this);this.contextMenuHandler_ = (e) => { e.preventDefault(); };this.container_.addEventListener('contextmenu', this.contextMenuHandler_);@@ -1033,20 +309,20 @@ export class Editor {const statsCb = this.container_.querySelector('.es-preview-stats-cb') as HTMLInputElement;statsCb?.addEventListener('change', () => {- this.togglePreviewStats(statsCb.checked);+ this.previewService_.togglePreviewStats(statsCb.checked);});- this.menuManager_.setupToolbarEvents(this.container_, () => this.startPreview());- this.setupEscapeHandler();+ this.menuManager_.setupToolbarEvents(this.container_, () => this.previewService_.startPreview());+ this.setupEscapeHandler_();this.store_.subscribe(() => this.menuManager_.updateToolbarState(this.container_));this.store_.subscribe(() => {this.menuManager_.updateStatusbar();- this.updateSceneNameDisplay();+ this.updateSceneNameDisplay_();});- this.installConsoleCapture();+ this.outputService_.installConsoleCapture();}- private updateSceneNameDisplay(): void {+ private updateSceneNameDisplay_(): void {const el = this.container_.querySelector('.es-menubar-scene-name');if (!el) return;const filePath = this.store_.filePath;@@ -1059,33 +335,7 @@ export class Editor {}}- private async showUnsavedChangesPrompt(): Promise<'save' | 'discard' | 'cancel'> {- return new Promise((resolve) => {- let resolved = false;- showDialog({- title: 'Unsaved Changes',- content: 'You have unsaved changes. Save before continuing?',- buttons: [- { label: 'Cancel', role: 'cancel' },- {- label: "Don't Save", role: 'custom',- onClick: () => { resolved = true; resolve('discard'); },- },- {- label: 'Save', role: 'confirm', primary: true,- onClick: () => { resolved = true; resolve('save'); },- },- ],- closeOnEscape: true,- }).then((result) => {- if (!resolved) {- resolve(result.action === 'confirm' ? 'save' : 'cancel');- }- });- });- }-- private setupEscapeHandler(): void {+ private setupEscapeHandler_(): void {this.escapeHandler_ = (e: KeyboardEvent) => {if (e.key !== 'Escape') return;if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) return;@@ -1104,11 +354,8 @@ export class Editor {return;}- if (this.addressableWindow_) {- this.addressableWindow_.panel.dispose();- this.addressableWindow_.element.remove();- document.removeEventListener('keydown', this.addressableWindow_.keyHandler);- this.addressableWindow_ = null;+ if (hasAddressableWindow()) {+ closeAddressableWindow();return;}@@ -1119,81 +366,18 @@ export class Editor {document.addEventListener('keydown', this.escapeHandler_);}- get windowManager(): WindowManager | null {- return this.windowManager_;- }-- appendOutput(text: string, type: 'command' | 'stdout' | 'stderr' | 'error' | 'success'): void {- this.panelManager_.appendOutput(text, type);- this.mainWindowBridge_?.broadcastOutput(text, type);- }-- private initMultiWindow(): void {- if (typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window) {- this.mainWindowBridge_ = new MainWindowBridge(this.store_);- this.mainWindowBridge_.start();- this.windowManager_ = new WindowManager();- this.windowManager_.setProjectPath(this.projectPath_);-- if (this.dockLayout_) {- const bridge = this.mainWindowBridge_;- this.dockLayout_.setDetachContext({- handler: this.windowManager_,- getPreviewUrl: () => this.startPreviewServer(),- onPanelClosed: (cb) => bridge.onPanelClosed(cb),- });- }-- this.setupCloseHandler();- }- }-- private setupCloseHandler(): void {- import('@tauri-apps/api/window').then(async ({ getCurrentWindow }) => {- const mainWindow = getCurrentWindow();- this.closeUnlisten_ = await mainWindow.onCloseRequested(async (event) => {- if (!this.store_.isDirty) return;- event.preventDefault();- try {- const result = await this.showUnsavedChangesPrompt();- if (result === 'cancel') return;- if (result === 'save') await this.saveScene();- } catch (e) {- console.error('Close handler error:', e);- }- mainWindow.destroy();- });- });- }-- dispose(): void {- this.closeUnlisten_?.();- this.closeUnlisten_ = null;- if (this.contextMenuHandler_) {- this.container_.removeEventListener('contextmenu', this.contextMenuHandler_);- this.contextMenuHandler_ = null;- }- if (this.addressableWindow_) {- this.addressableWindow_.panel.dispose();- this.addressableWindow_.element.remove();- document.removeEventListener('keydown', this.addressableWindow_.keyHandler);- this.addressableWindow_ = null;- }- this.stopProfilerStats();- if (this.escapeHandler_) {- document.removeEventListener('keydown', this.escapeHandler_);- this.escapeHandler_ = null;- }- this.windowManager_?.closeAll();- this.mainWindowBridge_?.dispose();- this.contentDrawer_?.dispose();- this.menuManager_.dispose();- this.scriptLoader_?.dispose();- this.extensionLoader_?.dispose();- this.dockLayout_?.dispose();- this.panelManager_.dispose();- this.previewManager_.dispose();- clearEditorAPI();+ private initMultiWindow_(): void {+ this.multiWindowService_.initialize(+ this.dockLayout_,+ this.outputService_,+ this.profilerService_,+ () => this.previewService_.startPreviewServer(),+ async () => {+ const result = await this.sceneService_.showUnsavedChangesPrompt_();+ if (result === 'cancel') return;+ if (result === 'save') await this.sceneService_.saveScene();+ },+ );}}diff --git a/editor/src/PanelManager.ts b/editor/src/PanelManager.tsindex 87445e135..982e71eda 100644--- a/editor/src/PanelManager.ts+++ b/editor/src/PanelManager.ts@@ -1,11 +1,5 @@-import type { App } from 'esengine';-import type { SpineWasmModule } from 'esengine/spine';-import { SpineModuleController as SpineModuleControllerClass, wrapSpineModule } from 'esengine/spine';-import type { EditorStore } from './store/EditorStore';-import type { EditorBridge } from './bridge/EditorBridge';-import type { PanelInstance, PanelDescriptor, PanelHooks } from './panels/PanelRegistry';+import type { PanelInstance, PanelDescriptor } from './panels/PanelRegistry';import { getPanel } from './panels/PanelRegistry';-import type { EditorAssetServer } from './asset/EditorAssetServer';import { getEditorContainer } from './container';import { PANEL } from './container/tokens';import { icons } from './utils/icons';@@ -13,54 +7,34 @@ import { escapeHtml } from './utils/html';export class PanelManager {private panelInstances_ = new Map<string, PanelInstance>();- private panelHooks_ = new Map<string, PanelHooks>();- private bridge_: EditorBridge | null = null;- private app_: App | null = null;get panelInstances(): Map<string, PanelInstance> {return this.panelInstances_;}- get assetServer(): EditorAssetServer | null {- for (const hooks of this.panelHooks_.values()) {- if (hooks.getAssetServer) return hooks.getAssetServer();- }- return null;- }-- createPanelInContainer(panelId: string, container: HTMLElement, store: EditorStore): void {+ createPanelInContainer(panelId: string, container: HTMLElement): void {if (this.panelInstances_.has(panelId)) return;const desc = getPanel(panelId);if (!desc) return;- this.createPanelWithErrorBoundary(desc, container, store, this.bridge_, this.app_);+ this.createPanelWithErrorBoundary(desc, container);}private createPanelWithErrorBoundary(desc: PanelDescriptor,container: HTMLElement,- store: EditorStore,- bridge?: EditorBridge | null,- app?: App | null,): void {try {- const result = desc.factory(container, store);- const { instance, hooks } = result;- if (hooks) {- this.panelHooks_.set(desc.id, hooks);- if (bridge) hooks.setBridge?.(bridge);- if (app) hooks.setApp?.(app);- }- this.panelInstances_.set(desc.id, instance);+ const result = desc.factory(container);+ this.panelInstances_.set(desc.id, result.instance);} catch (err) {console.error(`Panel "${desc.id}" failed to initialize:`, err);- this.showPanelError(desc, container, store, err as Error);+ this.showPanelError(desc, container, err as Error);}}private showPanelError(desc: PanelDescriptor,container: HTMLElement,- store: EditorStore,error: Error,): void {container.innerHTML = '';@@ -84,7 +58,7 @@ export class PanelManager {overlay.querySelector('[data-action="retry"]')?.addEventListener('click', () => {overlay.remove();- this.createPanelWithErrorBoundary(desc, container, store, this.bridge_, this.app_);+ this.createPanelWithErrorBoundary(desc, container);});overlay.querySelector('[data-action="close"]')?.addEventListener('click', () => {@@ -94,50 +68,6 @@ export class PanelManager {container.appendChild(overlay);}- setApp(app: App, bridge: EditorBridge): void {- this.app_ = app;- this.bridge_ = bridge;- for (const hooks of this.panelHooks_.values()) {- hooks.setBridge?.(bridge);- hooks.setApp?.(app);- }- }-- setSpineModule(module: unknown): void {- const raw = module as SpineWasmModule;- const controller = module ? new SpineModuleControllerClass(raw, wrapSpineModule(raw)) : null;- for (const hooks of this.panelHooks_.values()) {- hooks.setSpineController?.(controller);- }- }-- getSpineSkeletonInfo(entityId: number): { animations: string[]; skins: string[] } | null {- for (const hooks of this.panelHooks_.values()) {- if (hooks.getSpineSkeletonInfo) {- return hooks.getSpineSkeletonInfo(entityId);- }- }- return null;- }-- onSpineInstanceReady(listener: (entityId: number) => void): () => void {- for (const hooks of this.panelHooks_.values()) {- if (hooks.onSpineInstanceReady) {- return hooks.onSpineInstanceReady(listener);- }- }- return () => {};- }-- async navigateToAsset(assetPath: string): Promise<void> {- for (const hooks of this.panelHooks_.values()) {- if (hooks.navigateToAsset) {- await hooks.navigateToAsset(assetPath);- return;- }- }- }-showPanel(id: string): void {try {this.panelInstances_.get(id)?.onShow?.();@@ -154,29 +84,11 @@ export class PanelManager {}}- appendOutput(text: string, type: 'command' | 'stdout' | 'stderr' | 'error' | 'success'): void {- const hooks = this.panelHooks_.get('output');- if (hooks?.appendOutput) {- hooks.appendOutput(text, type);- }- }-- saveDirtyPanels(): Promise<void> {- const promises: Promise<boolean>[] = [];- for (const hooks of this.panelHooks_.values()) {- if (hooks.isDirty?.() && hooks.saveAsset) {- promises.push(hooks.saveAsset());- }- }- return Promise.all(promises).then(() => {});- }-removePanelInstance(panelId: string): void {const instance = this.panelInstances_.get(panelId);if (instance) {instance.dispose();this.panelInstances_.delete(panelId);- this.panelHooks_.delete(panelId);}}@@ -186,7 +98,6 @@ export class PanelManager {if (c.isBuiltin(PANEL, id)) continue;instance.dispose();this.panelInstances_.delete(id);- this.panelHooks_.delete(id);}}@@ -195,6 +106,5 @@ export class PanelManager {panel.dispose();}this.panelInstances_.clear();- this.panelHooks_.clear();}}diff --git a/editor/src/builder/BuildSettingsDialog.ts b/editor/src/builder/BuildSettingsDialog.tsindex 91ac58cae..876bafef8 100644--- a/editor/src/builder/BuildSettingsDialog.ts+++ b/editor/src/builder/BuildSettingsDialog.ts@@ -12,7 +12,8 @@ import {createDefaultBuildConfig,createDefaultBuildSettings,} from '../types/BuildTypes';-import { getEditorContext, getEditorInstance } from '../context/EditorContext';+import { getEditorContext } from '../context/EditorContext';+import { getEditorStore } from '../store';import { type BuildResult } from './BuildService';import { showProgressToast, dismissToast, showToast } from '../ui/Toast';import { BuildHistory, formatBuildTime, formatBuildDuration, getBuildStatusIcon, type BuildHistoryEntry } from './BuildHistory';@@ -725,8 +726,7 @@ export class BuildSettingsDialog {case 'add-current-scene':if (config) {- const editor = getEditorInstance();- const scenePath = editor?.currentScenePath;+ const scenePath = getEditorStore().filePath;if (scenePath) {const relativePath = this.toRelativePath(scenePath);if (!config.scenes.includes(relativePath)) {diff --git a/editor/src/container/tokens.ts b/editor/src/container/tokens.tsindex ffbb98639..6e7fa58c4 100644--- a/editor/src/container/tokens.ts+++ b/editor/src/container/tokens.ts@@ -47,3 +47,19 @@ export interface ComponentLifecycle {remove(world: any, entity: any, entityId: number): void;}export const COMPONENT_LIFECYCLE = new ServiceToken<ComponentLifecycle>('COMPONENT_LIFECYCLE');++export const SCENE_SERVICE = new ServiceToken<any>('SCENE_SERVICE');+export const CLIPBOARD_SERVICE = new ServiceToken<any>('CLIPBOARD_SERVICE');+export const PREVIEW_SERVICE = new ServiceToken<any>('PREVIEW_SERVICE');+export const SCRIPT_SERVICE = new ServiceToken<any>('SCRIPT_SERVICE');+export const EXTENSION_SERVICE = new ServiceToken<any>('EXTENSION_SERVICE');+export const SHELL_SERVICE = new ServiceToken<any>('SHELL_SERVICE');+export const PROFILER_SERVICE = new ServiceToken<any>('PROFILER_SERVICE');+export const LAYOUT_SERVICE = new ServiceToken<any>('LAYOUT_SERVICE');+export const NAVIGATION_SERVICE = new ServiceToken<any>('NAVIGATION_SERVICE');+export const OUTPUT_SERVICE = new ServiceToken<any>('OUTPUT_SERVICE');+export const SPINE_SERVICE = new ServiceToken<any>('SPINE_SERVICE');+export const RUNTIME_SERVICE = new ServiceToken<any>('RUNTIME_SERVICE');+export const MULTI_WINDOW_SERVICE = new ServiceToken<any>('MULTI_WINDOW_SERVICE');+export const PROJECT_SERVICE = new ServiceToken<any>('PROJECT_SERVICE');+export const PLUGIN_MANAGER = new ServiceToken<any>('PLUGIN_MANAGER');diff --git a/editor/src/dialogs/AboutDialog.ts b/editor/src/dialogs/AboutDialog.tsnew file mode 100644index 000000000..86003d206--- /dev/null+++ b/editor/src/dialogs/AboutDialog.ts@@ -0,0 +1,41 @@+import { getEditorContext } from '../context/EditorContext';+import { icons } from '../utils/icons';++export function showAboutDialog(): void {+ const hasUpdater = !!getEditorContext().onCheckUpdate;+ const overlay = document.createElement('div');+ overlay.className = 'es-dialog-overlay';+ overlay.innerHTML = `+ <div class="es-dialog" style="max-width: 360px;">+ <div class="es-dialog-header">+ <span class="es-dialog-title">About ESEngine</span>+ <button class="es-dialog-close">×</button>+ </div>+ <div class="es-dialog-body" style="text-align: center; padding: 24px;">+ <div style="margin-bottom: 16px;">${icons.logo(64)}</div>+ <h3 style="margin: 0 0 8px; color: var(--es-text-primary);">ESEngine Editor</h3>+ <p style="margin: 0 0 16px; color: var(--es-text-secondary);">Version ${getEditorContext().version ?? '0.0.0'}</p>+ <p style="margin: 0; font-size: 12px; color: var(--es-text-secondary);">+ A lightweight 2D game engine<br>for web and mini-programs.+ </p>+ </div>+ <div class="es-dialog-footer" style="justify-content: center; gap: 8px;">+ ${hasUpdater ? '<button class="es-dialog-btn" id="about-check-update">Check for Updates</button>' : ''}+ <button class="es-dialog-btn es-dialog-btn-primary">OK</button>+ </div>+ </div>+ `;++ const close = () => overlay.remove();+ overlay.querySelector('.es-dialog-close')?.addEventListener('click', close);+ overlay.querySelector('.es-dialog-btn-primary')?.addEventListener('click', close);+ overlay.querySelector('#about-check-update')?.addEventListener('click', () => {+ close();+ getEditorContext().onCheckUpdate?.();+ });+ overlay.addEventListener('click', (e) => {+ if (e.target === overlay) close();+ });++ document.body.appendChild(overlay);+}diff --git a/editor/src/dialogs/AddressableWindow.ts b/editor/src/dialogs/AddressableWindow.tsnew file mode 100644index 000000000..dc85b75e6--- /dev/null+++ b/editor/src/dialogs/AddressableWindow.ts@@ -0,0 +1,79 @@+import { AddressablePanel } from '../panels/AddressablePanel';+import { getEditorStore } from '../store';++let activeWindow: { element: HTMLElement; panel: AddressablePanel; keyHandler: (e: KeyboardEvent) => void } | null = null;++export function showAddressableWindow(): void {+ if (activeWindow) {+ activeWindow.element.style.zIndex = '1001';+ return;+ }++ const store = getEditorStore();+ const win = document.createElement('div');+ win.className = 'es-floating-window es-addressable-window';+ win.innerHTML = `+ <div class="es-floating-header">+ <span class="es-floating-title">Addressable Groups</span>+ <button class="es-dialog-close">×</button>+ </div>+ <div class="es-floating-body"></div>+ `;++ const body = win.querySelector('.es-floating-body') as HTMLElement;+ const panel = new AddressablePanel(body, store);++ const close = () => {+ panel.dispose();+ win.remove();+ document.removeEventListener('keydown', keyHandler);+ activeWindow = null;+ };++ win.querySelector('.es-dialog-close')!.addEventListener('click', close);++ const header = win.querySelector('.es-floating-header') as HTMLElement;+ header.addEventListener('mousedown', (e) => {+ if ((e.target as HTMLElement).closest('.es-dialog-close')) return;+ const rect = win.getBoundingClientRect();+ win.style.left = `${rect.left}px`;+ win.style.top = `${rect.top}px`;+ win.style.transform = 'none';+ const offsetX = e.clientX - rect.left;+ const offsetY = e.clientY - rect.top;+ const onMove = (ev: MouseEvent) => {+ const w = win.offsetWidth;+ const h = win.offsetHeight;+ const x = Math.max(0, Math.min(ev.clientX - offsetX, window.innerWidth - w));+ const y = Math.max(0, Math.min(ev.clientY - offsetY, window.innerHeight - h));+ win.style.left = `${x}px`;+ win.style.top = `${y}px`;+ };+ const onUp = () => {+ document.removeEventListener('mousemove', onMove);+ document.removeEventListener('mouseup', onUp);+ };+ document.addEventListener('mousemove', onMove);+ document.addEventListener('mouseup', onUp);+ });++ const keyHandler = (e: KeyboardEvent) => {+ if (e.key === 'Escape') close();+ };+ document.addEventListener('keydown', keyHandler);++ document.body.appendChild(win);+ activeWindow = { element: win, panel, keyHandler };+}++export function closeAddressableWindow(): void {+ if (!activeWindow) return;+ activeWindow.panel.dispose();+ activeWindow.element.remove();+ document.removeEventListener('keydown', activeWindow.keyHandler);+ activeWindow = null;+}++export function hasAddressableWindow(): boolean {+ return activeWindow !== null;+}diff --git a/editor/src/index.ts b/editor/src/index.tsindex 6268f59a6..f1470b1de 100644--- a/editor/src/index.ts+++ b/editor/src/index.ts@@ -87,7 +87,6 @@ export {type PanelDescriptor,type PanelFactory,type PanelInstance,- type PanelHooks,type PanelFactoryResult,registerPanel,getPanel,diff --git a/editor/src/menus/builtinMenus.ts b/editor/src/menus/builtinMenus.tsindex 7dab06492..b6b006eb5 100644--- a/editor/src/menus/builtinMenus.ts+++ b/editor/src/menus/builtinMenus.ts@@ -1,13 +1,24 @@import type { MenuDescriptor, MenuItemDescriptor } from './MenuRegistry';-import type { Editor } from '../Editor';import type { PluginRegistrar } from '../container';import { MENU, MENU_ITEM } from '../container/tokens';import { getEditorContext } from '../context/EditorContext';+import { showAboutDialog } from '../dialogs/AboutDialog';+import { showAddressableWindow } from '../dialogs/AddressableWindow';import { showStatusBarMessage } from './builtinStatusbar';import { showConfirmDialog } from '../ui/dialog';+import { getEditorStore } from '../store';+import {+ getSceneService,+ getClipboardService,+ getPreviewService,+ getNavigationService,+ getProfilerService,+ getProjectService,+ getExtensionService,+} from '../services';import type { Entity } from 'esengine';-export function registerBuiltinMenus(registrar: PluginRegistrar, editor: Editor): void {+export function registerBuiltinMenus(registrar: PluginRegistrar): void {const registerMenu = (d: MenuDescriptor) => registrar.provide(MENU, d.id, d);const registerMenuItem = (d: MenuItemDescriptor) => registrar.provide(MENU_ITEM, d.id, d);registerMenu({ id: 'file', label: 'File', order: 0 });@@ -18,61 +29,64 @@ export function registerBuiltinMenus(registrar: PluginRegistrar, editor: Editor)registerMenuItem({id: 'file.new', menu: 'file', label: 'New Scene',shortcut: 'Ctrl+N', order: 0,- action: () => editor.newScene(),+ action: () => getSceneService().newScene(),});registerMenuItem({id: 'file.open', menu: 'file', label: 'Open...',shortcut: 'Ctrl+O', order: 1,- action: () => editor.loadScene(),+ action: () => getSceneService().loadScene(),});registerMenuItem({id: 'file.save', menu: 'file', label: 'Save',shortcut: 'Ctrl+S', order: 2, separator: true,- action: () => editor.saveScene(),+ action: () => getSceneService().saveScene(),});registerMenuItem({id: 'file.save-as', menu: 'file', label: 'Save As...',shortcut: 'Ctrl+Shift+S', order: 3,- action: () => editor.saveSceneAs(),+ action: () => getSceneService().saveSceneAs(),});registerMenuItem({id: 'file.preview', menu: 'file', label: 'Preview',shortcut: 'F5', order: 4, separator: true,- action: () => editor.startPreview(),+ action: () => getPreviewService().startPreview(),});registerMenuItem({id: 'file.build-settings', menu: 'file', label: 'Build Settings...',shortcut: 'Ctrl+Shift+B', order: 6, separator: true,- action: () => editor.showBuildSettings(),+ action: () => getProjectService().showBuildSettings(),});registerMenuItem({id: 'edit.undo', menu: 'edit', label: 'Undo',shortcut: 'Ctrl+Z', order: 0,- enabled: () => editor.store.canUndo,+ enabled: () => getEditorStore().canUndo,action: () => {- const desc = editor.store.undoDescription;- editor.store.undo();+ const store = getEditorStore();+ const desc = store.undoDescription;+ store.undo();if (desc) showStatusBarMessage(`Undo: ${desc}`);},});registerMenuItem({id: 'edit.redo', menu: 'edit', label: 'Redo',shortcut: 'Ctrl+Y', order: 1,- enabled: () => editor.store.canRedo,+ enabled: () => getEditorStore().canRedo,action: () => {- const desc = editor.store.redoDescription;- editor.store.redo();+ const store = getEditorStore();+ const desc = store.redoDescription;+ store.redo();if (desc) showStatusBarMessage(`Redo: ${desc}`);},});registerMenuItem({id: 'edit.redo-alt', menu: 'edit', label: 'Redo (Alt)',shortcut: 'Ctrl+Shift+Z', order: 1,- enabled: () => editor.store.canRedo,+ enabled: () => getEditorStore().canRedo,action: () => {- const desc = editor.store.redoDescription;- editor.store.redo();+ const store = getEditorStore();+ const desc = store.redoDescription;+ store.redo();if (desc) showStatusBarMessage(`Redo: ${desc}`);},hidden: true,@@ -80,95 +94,100 @@ export function registerBuiltinMenus(registrar: PluginRegistrar, editor: Editor)registerMenuItem({id: 'edit.delete', menu: 'edit', label: 'Delete',shortcut: 'Delete', order: 2, separator: true,- enabled: () => editor.store.selectedEntities.size > 0,+ enabled: () => getEditorStore().selectedEntities.size > 0,action: () => {- if (editor.store.selectedEntities.size === 1) {- const id = Array.from(editor.store.selectedEntities)[0];- editor.store.deleteEntity(id as Entity);- } else if (editor.store.selectedEntities.size > 1) {- editor.store.deleteSelectedEntities();+ const store = getEditorStore();+ if (store.selectedEntities.size === 1) {+ const id = Array.from(store.selectedEntities)[0];+ store.deleteEntity(id as Entity);+ } else if (store.selectedEntities.size > 1) {+ store.deleteSelectedEntities();}},});registerMenuItem({id: 'edit.duplicate', menu: 'edit', label: 'Duplicate',shortcut: 'Ctrl+D', order: 3,- enabled: () => editor.store.selectedEntities.size > 0,- action: () => editor.duplicateSelected(),+ enabled: () => getEditorStore().selectedEntities.size > 0,+ action: () => getClipboardService().duplicateSelected(),});registerMenuItem({id: 'edit.copy', menu: 'edit', label: 'Copy',shortcut: 'Ctrl+C', order: 4,- enabled: () => editor.store.selectedEntities.size > 0,- action: () => editor.copySelected(),+ enabled: () => getEditorStore().selectedEntities.size > 0,+ action: () => getClipboardService().copySelected(),});registerMenuItem({id: 'edit.cut', menu: 'edit', label: 'Cut',shortcut: 'Ctrl+X', order: 4.5,- enabled: () => editor.store.selectedEntities.size > 0,+ enabled: () => getEditorStore().selectedEntities.size > 0,action: () => {- editor.copySelected();- if (editor.store.selectedEntities.size === 1) {- const id = Array.from(editor.store.selectedEntities)[0];- editor.store.deleteEntity(id as Entity);- } else if (editor.store.selectedEntities.size > 1) {- editor.store.deleteSelectedEntities();+ const store = getEditorStore();+ getClipboardService().copySelected();+ if (store.selectedEntities.size === 1) {+ const id = Array.from(store.selectedEntities)[0];+ store.deleteEntity(id as Entity);+ } else if (store.selectedEntities.size > 1) {+ store.deleteSelectedEntities();}},});registerMenuItem({id: 'edit.paste', menu: 'edit', label: 'Paste',shortcut: 'Ctrl+V', order: 5,- enabled: () => editor.hasClipboard(),- action: () => editor.pasteEntity(),+ enabled: () => getClipboardService().hasClipboard(),+ action: () => getClipboardService().pasteEntity(),});registerMenuItem({id: 'edit.create-entity', menu: 'edit', label: 'Create Entity',shortcut: 'Ctrl+Shift+N', order: 6,- action: () => editor.store.createEntity('New Entity', editor.store.selectedEntity),+ action: () => {+ const store = getEditorStore();+ store.createEntity('New Entity', store.selectedEntity);+ },hidden: true,});registerMenuItem({id: 'edit.preferences', menu: 'edit', label: 'Settings...',shortcut: 'Ctrl+,', order: 10, separator: true,- action: () => editor.showSettings(),+ action: () => getProjectService().showSettings(),});registerMenuItem({id: 'view.hierarchy', menu: 'view', label: 'Hierarchy', order: 0,- action: () => editor.showPanel('hierarchy'),+ action: () => getNavigationService().showPanel('hierarchy'),});registerMenuItem({id: 'view.inspector', menu: 'view', label: 'Inspector', order: 1,- action: () => editor.showPanel('inspector'),+ action: () => getNavigationService().showPanel('inspector'),});registerMenuItem({id: 'view.content-browser', menu: 'view', label: 'Content Browser',shortcut: 'Ctrl+Space', order: 2,- action: () => editor.showPanel('content-browser'),+ action: () => getNavigationService().showPanel('content-browser'),});registerMenuItem({id: 'view.output', menu: 'view', label: 'Output', order: 3,- action: () => editor.showPanel('output'),+ action: () => getNavigationService().showPanel('output'),});registerMenuItem({id: 'view.game', menu: 'view', label: 'Game', order: 4,- action: () => editor.showPanel('game'),+ action: () => getNavigationService().showPanel('game'),});registerMenuItem({id: 'view.profiler', menu: 'view', label: 'Profiler',order: 5, separator: true,- action: () => editor.showProfilerWindow(),+ action: () => getProfilerService().showProfilerWindow(),});registerMenuItem({id: 'view.addressable', menu: 'view', label: 'Addressable Groups',order: 6,- action: () => editor.showAddressableWindow(),+ action: () => showAddressableWindow(),});registerMenuItem({id: 'view.reset-layout', menu: 'view', label: 'Reset Layout',order: 6, separator: true,- action: () => editor.resetLayout(),+ action: () => getNavigationService().resetLayout(),});registerMenuItem({id: 'view.reload-extensions', menu: 'view', label: 'Reload Extensions',@@ -179,7 +198,7 @@ export function registerBuiltinMenus(registrar: PluginRegistrar, editor: Editor)message: 'Reload all extensions? This will reset any extension state.',confirmText: 'Reload',});- if (confirmed) editor.reloadExtensions();+ if (confirmed) getExtensionService().reload();},});registerMenuItem({@@ -199,19 +218,19 @@ export function registerBuiltinMenus(registrar: PluginRegistrar, editor: Editor)registerMenuItem({id: 'view.focus-hierarchy', menu: 'view', label: 'Focus Hierarchy',shortcut: 'Ctrl+1', order: 30,- action: () => editor.showPanel('hierarchy'),+ action: () => getNavigationService().showPanel('hierarchy'),hidden: true,});registerMenuItem({id: 'view.focus-scene', menu: 'view', label: 'Focus Scene',shortcut: 'Ctrl+2', order: 31,- action: () => editor.showPanel('scene'),+ action: () => getNavigationService().showPanel('scene'),hidden: true,});registerMenuItem({id: 'view.focus-inspector', menu: 'view', label: 'Focus Inspector',shortcut: 'Ctrl+3', order: 32,- action: () => editor.showPanel('inspector'),+ action: () => getNavigationService().showPanel('inspector'),hidden: true,});@@ -228,6 +247,6 @@ export function registerBuiltinMenus(registrar: PluginRegistrar, editor: Editor)});registerMenuItem({id: 'help.about', menu: 'help', label: 'About ESEngine', order: 1, separator: true,- action: () => editor.showAboutDialog(),+ action: () => showAboutDialog(),});}diff --git a/editor/src/menus/builtinStatusbar.ts b/editor/src/menus/builtinStatusbar.tsindex 674c86edd..dd80ef374 100644--- a/editor/src/menus/builtinStatusbar.ts+++ b/editor/src/menus/builtinStatusbar.ts@@ -1,9 +1,10 @@import type { StatusbarItemDescriptor } from './MenuRegistry';import { getPanelsByPosition } from '../panels/PanelRegistry';import { icons } from '../utils/icons';-import type { Editor } from '../Editor';import type { PluginRegistrar } from '../container';import { STATUSBAR_ITEM } from '../container/tokens';+import { getEditorStore } from '../store';+import { getNavigationService, getShellService, getProjectService } from '../services';let statusMessageTimer_: ReturnType<typeof setTimeout> | null = null;let statusMessageEl_: HTMLElement | null = null;@@ -18,7 +19,7 @@ export function showStatusBarMessage(text: string, durationMs = 2000): void {}, durationMs);}-export function registerBuiltinStatusbarItems(registrar: PluginRegistrar, editor: Editor): void {+export function registerBuiltinStatusbarItems(registrar: PluginRegistrar): void {const registerStatusbarItem = (d: StatusbarItemDescriptor) => registrar.provide(STATUSBAR_ITEM, d.id, d);const bottomPanels = getPanelsByPosition('bottom');@@ -38,7 +39,7 @@ export function registerBuiltinStatusbarItems(registrar: PluginRegistrar, editorbtn.innerHTML += icons.chevronDown(10);}- btn.addEventListener('click', () => editor.showPanel(panel.id));+ btn.addEventListener('click', () => getNavigationService().showPanel(panel.id));container.appendChild(btn);return {@@ -67,7 +68,7 @@ export function registerBuiltinStatusbarItems(registrar: PluginRegistrar, editorif (e.key === 'Enter') {const command = input.value.trim();if (command) {- editor.executeCommand(command);+ getShellService().executeCommand(command);input.value = '';}}@@ -103,8 +104,9 @@ export function registerBuiltinStatusbarItems(registrar: PluginRegistrar, editorundoBtn.title = 'Undo';undoBtn.innerHTML = '<span>Undo</span>';undoBtn.addEventListener('click', () => {- const desc = editor.store.undoDescription;- editor.store.undo();+ const store = getEditorStore();+ const desc = store.undoDescription;+ store.undo();if (desc) showStatusBarMessage(`Undo: ${desc}`);});@@ -112,8 +114,9 @@ export function registerBuiltinStatusbarItems(registrar: PluginRegistrar, editorredoBtn.title = 'Redo';redoBtn.innerHTML = '<span>Redo</span>';redoBtn.addEventListener('click', () => {- const desc = editor.store.redoDescription;- editor.store.redo();+ const store = getEditorStore();+ const desc = store.redoDescription;+ store.redo();if (desc) showStatusBarMessage(`Redo: ${desc}`);});@@ -124,12 +127,13 @@ export function registerBuiltinStatusbarItems(registrar: PluginRegistrar, editorreturn {dispose() { wrapper.remove(); },update() {- const undoDesc = editor.store.undoDescription;- const redoDesc = editor.store.redoDescription;+ const store = getEditorStore();+ const undoDesc = store.undoDescription;+ const redoDesc = store.redoDescription;undoBtn.title = undoDesc ? `Undo: ${undoDesc}` : 'Undo';redoBtn.title = redoDesc ? `Redo: ${redoDesc}` : 'Redo';- undoBtn.disabled = !editor.store.canUndo;- redoBtn.disabled = !editor.store.canRedo;+ undoBtn.disabled = !store.canUndo;+ redoBtn.disabled = !store.canRedo;},};},@@ -146,12 +150,12 @@ export function registerBuiltinStatusbarItems(registrar: PluginRegistrar, editorconst notifBtn = document.createElement('button');notifBtn.title = 'Notifications';notifBtn.innerHTML = icons.list(12);- notifBtn.addEventListener('click', () => editor.showPanel('output'));+ notifBtn.addEventListener('click', () => getNavigationService().showPanel('output'));const settingsBtn = document.createElement('button');settingsBtn.title = 'Settings';settingsBtn.innerHTML = icons.settings(12);- settingsBtn.addEventListener('click', () => editor.showSettings());+ settingsBtn.addEventListener('click', () => getProjectService().showSettings());wrapper.appendChild(notifBtn);wrapper.appendChild(settingsBtn);@@ -180,9 +184,10 @@ export function registerBuiltinStatusbarItems(registrar: PluginRegistrar, editorreturn {dispose() { container.innerHTML = ''; },update() {+ const store = getEditorStore();const saved = container.querySelector('.es-status-saved') as HTMLElement;const unsaved = container.querySelector('.es-status-unsaved') as HTMLElement;- if (editor.store.isDirty) {+ if (store.isDirty) {if (saved) saved.style.display = 'none';if (unsaved) unsaved.style.display = '';} else {diff --git a/editor/src/panels/AddressablePanel.ts b/editor/src/panels/AddressablePanel.tsindex 7b646b3d4..384dbaf41 100644--- a/editor/src/panels/AddressablePanel.ts+++ b/editor/src/panels/AddressablePanel.ts@@ -9,7 +9,8 @@ import { icons } from '../utils/icons';import { getAssetDatabase, type AssetEntry } from '../asset/AssetDatabase';import type { AssetGroupService, AssetGroupDef, BundleMode } from '../asset/AssetGroup';import { AssetDependencyAnalyzer } from '../asset/AssetDependencyAnalyzer';-import { getEditorInstance, getEditorContext } from '../context/EditorContext';+import { getEditorContext } from '../context/EditorContext';+import { getNavigationService, getProjectService } from '../services';import { showInputDialog, showConfirmDialog } from '../ui/dialog';import { showContextMenu, type ContextMenuItem } from '../ui/ContextMenu';import { getContextMenuItems, type ContextMenuContext } from '../ui/ContextMenuRegistry';@@ -565,7 +566,7 @@ export class AddressablePanel implements PanelInstance {if (!uuid) return;const entry = db.getEntry(uuid);if (entry) {- getEditorInstance()?.navigateToAsset(entry.path);+ getNavigationService().navigateToAsset(entry.path);}});});@@ -618,7 +619,7 @@ export class AddressablePanel implements PanelInstance {if (this.analyzing_) return;const db = getAssetDatabase();const fs = getEditorContext().fs;- const projectFilePath = getEditorInstance()?.projectPath;+ const projectFilePath = getProjectService().projectPath;if (!fs || !projectFilePath) {showErrorToast('No project loaded');return;@@ -828,7 +829,7 @@ export class AddressablePanel implements PanelInstance {{label: 'Reveal in Content Browser',onClick: () => {- getEditorInstance()?.navigateToAsset(entry.path);+ getNavigationService().navigateToAsset(entry.path);},},],@@ -879,7 +880,7 @@ export class AddressablePanel implements PanelInstance {}private getProjectDir(): string | null {- const projectPath = getEditorInstance()?.projectPath;+ const projectPath = getProjectService().projectPath;if (!projectPath) return null;return projectPath.replace(/[/\\][^/\\]+$/, '');}diff --git a/editor/src/panels/OutputPanel.ts b/editor/src/panels/OutputPanel.tsindex 3d405028e..8e11a8f77 100644--- a/editor/src/panels/OutputPanel.ts+++ b/editor/src/panels/OutputPanel.ts@@ -1,6 +1,7 @@import type { PanelInstance } from './PanelRegistry';import { icons } from '../utils/icons';import { DisposableStore } from '../utils/Disposable';+import { getOutputService } from '../services';type OutputType = 'command' | 'stdout' | 'stderr' | 'error' | 'success';@@ -47,10 +48,12 @@ export class OutputPanel implements PanelInstance {private filterBtns_ = new Map<OutputType, HTMLElement>();private scrollBtn_: HTMLElement | null = null;private searchInput_: HTMLElement | null = null;+ private disposeOutputReg_: (() => void) | null = null;constructor(container: HTMLElement) {this.container_ = container;this.render();+ this.disposeOutputReg_ = getOutputService().registerOutputHandler((text, type) => this.appendOutput(text, type));}appendOutput(text: string, type: OutputType): void {@@ -155,6 +158,7 @@ export class OutputPanel implements PanelInstance {}dispose(): void {+ this.disposeOutputReg_?.();this.disposables_.dispose();this.container_.innerHTML = '';}diff --git a/editor/src/panels/PanelRegistry.ts b/editor/src/panels/PanelRegistry.tsindex 49bdc8a76..75cac626a 100644--- a/editor/src/panels/PanelRegistry.ts+++ b/editor/src/panels/PanelRegistry.ts@@ -1,8 +1,3 @@-import type { App } from 'esengine';-import type { SpineModuleController } from 'esengine/spine';-import type { EditorStore } from '../store/EditorStore';-import type { EditorBridge } from '../bridge/EditorBridge';-import type { EditorAssetServer } from '../asset/EditorAssetServer';import { getEditorContainer } from '../container';import { PANEL } from '../container/tokens';@@ -19,26 +14,11 @@ export interface PanelDescriptor {factory: PanelFactory;}-export interface PanelHooks {- setBridge?: (bridge: EditorBridge) => void;- setApp?: (app: App | null) => void;- resize?: () => void;- getAssetServer?: () => EditorAssetServer | null;- navigateToAsset?: (path: string) => Promise<void>;- appendOutput?: (text: string, type: string) => void;- setSpineController?: (ctrl: SpineModuleController | null) => void;- getSpineSkeletonInfo?: (entityId: number) => { animations: string[]; skins: string[] } | null;- onSpineInstanceReady?: (listener: (entityId: number) => void) => () => void;- saveAsset?: () => Promise<boolean>;- isDirty?: () => boolean;-}-export interface PanelFactoryResult {instance: PanelInstance;- hooks?: PanelHooks;}-export type PanelFactory = (container: HTMLElement, store: EditorStore) => PanelFactoryResult;+export type PanelFactory = (container: HTMLElement) => PanelFactoryResult;export interface PanelInstance {dispose(): void;diff --git a/editor/src/panels/builtinPanels.ts b/editor/src/panels/builtinPanels.tsindex 0799a190b..763a9f27f 100644--- a/editor/src/panels/builtinPanels.ts+++ b/editor/src/panels/builtinPanels.ts@@ -1,4 +1,4 @@-import type { PanelHooks, PanelDescriptor } from './PanelRegistry';+import type { PanelDescriptor } from './PanelRegistry';import type { PluginRegistrar } from '../container';import { PANEL } from '../container/tokens';import { HierarchyPanel } from './hierarchy/HierarchyPanel';@@ -10,12 +10,12 @@ import { OutputPanel } from './OutputPanel';import { ProfilerPanel } from './profiler/ProfilerPanel';import { TimelinePanel } from './timeline/TimelinePanel';import { icons } from '../utils/icons';+import { getEditorStore } from '../store';const PANEL_ICON_SIZE = 14;export interface BuiltinPanelOptions {projectPath?: string;- onOpenScene?: (path: string) => void;}export function registerBuiltinPanels(registrar: PluginRegistrar, options: BuiltinPanelOptions): void {@@ -27,7 +27,7 @@ export function registerBuiltinPanels(registrar: PluginRegistrar, options: Builtposition: 'left',order: 0,defaultVisible: true,- factory: (c, s) => ({ instance: new HierarchyPanel(c, s) }),+ factory: (c) => ({ instance: new HierarchyPanel(c, getEditorStore()) }),});registerPanel({@@ -36,19 +36,7 @@ export function registerBuiltinPanels(registrar: PluginRegistrar, options: Builtposition: 'center',order: 0,defaultVisible: true,- factory: (c, s) => {- const panel = new SceneViewPanel(c, s, { projectPath: options.projectPath });- const hooks: PanelHooks = {- setBridge: (b) => panel.setBridge(b),- setApp: (a) => panel.setApp(a!),- resize: () => panel.resize(),- getAssetServer: () => panel.assetServer,- setSpineController: (ctrl) => panel.setSpineController(ctrl),- getSpineSkeletonInfo: (id) => panel.getSpineSkeletonInfo(id),- onSpineInstanceReady: (listener) => panel.onSpineInstanceReady(listener),- };- return { instance: panel, hooks };- },+ factory: (c) => ({ instance: new SceneViewPanel(c, getEditorStore(), { projectPath: options.projectPath }) }),});registerPanel({@@ -58,13 +46,7 @@ export function registerBuiltinPanels(registrar: PluginRegistrar, options: Builtposition: 'center',order: 2,defaultVisible: true,- factory: (c, s) => {- const panel = new GameViewPanel(c, s, { projectPath: options.projectPath });- const hooks: PanelHooks = {- resize: () => panel.resize(),- };- return { instance: panel, hooks };- },+ factory: (c) => ({ instance: new GameViewPanel(c, getEditorStore(), { projectPath: options.projectPath }) }),});registerPanel({@@ -74,7 +56,7 @@ export function registerBuiltinPanels(registrar: PluginRegistrar, options: Builtposition: 'right',order: 0,defaultVisible: true,- factory: (c, s) => ({ instance: new InspectorPanel(c, s) }),+ factory: (c) => ({ instance: new InspectorPanel(c, getEditorStore()) }),});registerPanel({@@ -84,15 +66,14 @@ export function registerBuiltinPanels(registrar: PluginRegistrar, options: Builtposition: 'bottom',order: 0,defaultVisible: true,- factory: (c, s) => {- const panel = new ContentBrowserPanel(c, s, {- projectPath: options.projectPath,- onOpenScene: options.onOpenScene,- });- const hooks: PanelHooks = {- navigateToAsset: (path) => panel.navigateToAsset(path),+ factory: (c) => {+ const { getSceneService } = require('../services');+ return {+ instance: new ContentBrowserPanel(c, getEditorStore(), {+ projectPath: options.projectPath,+ onOpenScene: (path: string) => getSceneService().openSceneFromPath(path),+ }),};- return { instance: panel, hooks };},});@@ -103,13 +84,7 @@ export function registerBuiltinPanels(registrar: PluginRegistrar, options: Builtposition: 'bottom',order: 1,defaultVisible: false,- factory: (c) => {- const panel = new OutputPanel(c);- const hooks: PanelHooks = {- appendOutput: (text, type) => panel.appendOutput(text, type as any),- };- return { instance: panel, hooks };- },+ factory: (c) => ({ instance: new OutputPanel(c) }),});registerPanel({@@ -119,15 +94,7 @@ export function registerBuiltinPanels(registrar: PluginRegistrar, options: Builtposition: 'bottom',order: 2,defaultVisible: false,- factory: (c, s) => {- const panel = new TimelinePanel(c, s);- const hooks: PanelHooks = {- resize: () => panel.resize(),- saveAsset: () => panel.saveAsset(),- isDirty: () => panel.isDirty,- };- return { instance: panel, hooks };- },+ factory: (c) => ({ instance: new TimelinePanel(c, getEditorStore()) }),});registerPanel({diff --git a/editor/src/panels/content-browser/ContentBrowserPanel.ts b/editor/src/panels/content-browser/ContentBrowserPanel.tsindex cf4b7598a..a8440b0b9 100644--- a/editor/src/panels/content-browser/ContentBrowserPanel.ts+++ b/editor/src/panels/content-browser/ContentBrowserPanel.ts@@ -13,6 +13,7 @@ import {importDroppedFiles, saveDroppedEntityAsPrefab,} from './AssetContextMenu';import { DisposableStore } from '../../utils/Disposable';+import { getNavigationService } from '../../services';export class ContentBrowserPanel implements ContentBrowserState {container: HTMLElement;@@ -39,6 +40,7 @@ export class ContentBrowserPanel implements ContentBrowserState {private refreshing_ = false;private refreshPending_ = false;private thumbnailCache_ = new ThumbnailCache();+ private disposeNavReg_: (() => void) | null = null;constructor(container: HTMLElement, store: EditorStore, options?: ContentBrowserOptions) {this.container = container;@@ -83,9 +85,11 @@ export class ContentBrowserPanel implements ContentBrowserState {this.updateViewToggleButton();this.setupEvents();this.initialize();+ this.disposeNavReg_ = getNavigationService().registerNavigateToAsset(async (path) => { this.navigateToAsset(path); });}dispose(): void {+ this.disposeNavReg_?.();this.disposables_.dispose();}diff --git a/editor/src/panels/hierarchy/HierarchyContextMenu.ts b/editor/src/panels/hierarchy/HierarchyContextMenu.tsindex d976b5205..dd578dcc4 100644--- a/editor/src/panels/hierarchy/HierarchyContextMenu.ts+++ b/editor/src/panels/hierarchy/HierarchyContextMenu.ts@@ -4,7 +4,7 @@ import { icons } from '../../utils/icons';import { getInitialComponentData } from '../../schemas/ComponentSchemas';import { showContextMenu, type ContextMenuItem } from '../../ui/ContextMenu';import { getContextMenuItems, type ContextMenuContext } from '../../ui/ContextMenuRegistry';-import { getEditorInstance } from '../../context/EditorContext';+import { getClipboardService, getProjectService } from '../../services';import { generateUniqueName } from '../../utils/naming';import { showInputDialog } from '../../ui/dialog';import { joinPath, getParentDir } from '../../utils/path';@@ -15,7 +15,7 @@ import type { HierarchyState } from './HierarchyTypes';export function showEntityContextMenu(state: HierarchyState, x: number, y: number, entity: Entity | null): void {const entityData = entity !== null ? state.store.getEntityData(entity as number) : null;const has = (type: string) => entityData?.components.some(c => c.type === type) ?? false;- const editor = getEditorInstance();+ const clipboard = getClipboardService();const multiSelected = state.store.selectedEntities.size > 1;const createChildren: ContextMenuItem[] = [@@ -80,17 +80,17 @@ export function showEntityContextMenu(state: HierarchyState, x: number, y: numbeduplicateEntity(state, entity);}} },- { label: 'Copy', icon: icons.copy(14), onClick: () => { state.store.selectEntity(entity); editor?.copySelected(); } },+ { label: 'Copy', icon: icons.copy(14), onClick: () => { state.store.selectEntity(entity); clipboard.copySelected(); } },{ label: 'Cut', icon: icons.copy(14), onClick: () => {state.store.selectEntity(entity);- editor?.copySelected();+ clipboard.copySelected();if (multiSelected) {state.store.deleteSelectedEntities();} else {state.store.deleteEntity(entity);}} },- { label: 'Paste', icon: icons.template(14), disabled: !editor?.hasClipboard(), onClick: () => { state.store.selectEntity(entity); editor?.pasteEntity(); } },+ { label: 'Paste', icon: icons.template(14), disabled: !clipboard.hasClipboard(), onClick: () => { state.store.selectEntity(entity); clipboard.pasteEntity(); } },{ label: 'Delete', icon: icons.trash(14), onClick: () => {if (multiSelected) {state.store.deleteSelectedEntities();@@ -105,7 +105,7 @@ export function showEntityContextMenu(state: HierarchyState, x: number, y: numbeitems.push({ label: 'Create', icon: icons.plus(14), children: createChildren });if (entity === null) {- items.push({ label: 'Paste', icon: icons.template(14), disabled: !editor?.hasClipboard(), onClick: () => { editor?.pasteEntity(); } });+ items.push({ label: 'Paste', icon: icons.template(14), disabled: !clipboard.hasClipboard(), onClick: () => { clipboard.pasteEntity(); } });}if (entity !== null) {@@ -520,7 +520,7 @@ async function saveEntityAsPrefab(state: HierarchyState, entity: Entity): Promisconst entityData = state.store.getEntityData(entity as number);if (!entityData) return;- const projectPath = getEditorInstance()?.projectPath;+ const projectPath = getProjectService().projectPath;if (!projectPath) return;const projectDir = getParentDir(projectPath);diff --git a/editor/src/panels/index.ts b/editor/src/panels/index.tsindex 967023413..558b8f2fb 100644--- a/editor/src/panels/index.ts+++ b/editor/src/panels/index.ts@@ -14,7 +14,6 @@ export {type PanelDescriptor,type PanelFactory,type PanelInstance,- type PanelHooks,type PanelFactoryResult,registerPanel,getPanel,diff --git a/editor/src/panels/inspector/EntityInspector.ts b/editor/src/panels/inspector/EntityInspector.tsindex 38fd4c414..a2f003df8 100644--- a/editor/src/panels/inspector/EntityInspector.ts+++ b/editor/src/panels/inspector/EntityInspector.ts@@ -16,7 +16,8 @@ import {} from '../../schemas/ComponentSchemas';import { icons } from '../../utils/icons';import { showAddComponentPopup } from '../AddComponentPopup';-import { getEditorContext, getEditorInstance } from '../../context/EditorContext';+import { getEditorContext } from '../../context/EditorContext';+import { getNavigationService } from '../../services';import { getPlatformAdapter } from '../../platform/PlatformAdapter';import { getAssetLibrary, isUUID } from '../../asset/AssetLibrary';import {@@ -119,7 +120,7 @@ function renderPrefabInfoBar(const pathEl = bar.querySelector('.es-prefab-info-link');pathEl?.addEventListener('click', () => {- getEditorInstance()?.navigateToAsset(resolvedPath);+ getNavigationService().navigateToAsset(resolvedPath);});if (prefab.isRoot) {diff --git a/editor/src/panels/inspector/FileInspector.ts b/editor/src/panels/inspector/FileInspector.tsindex 387454903..0cffb641b 100644--- a/editor/src/panels/inspector/FileInspector.ts+++ b/editor/src/panels/inspector/FileInspector.ts@@ -4,7 +4,7 @@*/import { icons } from '../../utils/icons';-import { getEditorInstance } from '../../context/EditorContext';+import { getSceneService } from '../../services';import { getNativeFS, getFileExtension, formatFileSize, formatDate, escapeHtml, renderError } from './InspectorHelpers';export async function renderScriptInspector(container: HTMLElement, path: string): Promise<void> {@@ -137,10 +137,7 @@ export async function renderSceneInspector(container: HTMLElement, path: string)const openBtn = actionsWrapper.querySelector('.es-btn-open-scene');openBtn?.addEventListener('click', () => {- const editor = getEditorInstance();- if (editor && typeof editor.openSceneFromPath === 'function') {- editor.openSceneFromPath(path);- }+ getSceneService().openSceneFromPath(path);});container.appendChild(actionsWrapper);diff --git a/editor/src/panels/inspector/InspectorHelpers.ts b/editor/src/panels/inspector/InspectorHelpers.tsindex 00a58972f..ea27caf31 100644--- a/editor/src/panels/inspector/InspectorHelpers.ts+++ b/editor/src/panels/inspector/InspectorHelpers.ts@@ -8,7 +8,8 @@ import type { PropertyEditorInstance } from '../../property/PropertyEditor';import type { EditorAssetServer } from '../../asset/EditorAssetServer';import type { NativeFS } from '../../types/NativeFS';import { getAssetMimeType } from 'esengine';-import { getEditorContext, getEditorInstance } from '../../context/EditorContext';+import { getEditorContext } from '../../context/EditorContext';+import { getProjectService, getNavigationService } from '../../services';import { icons } from '../../utils/icons';// =============================================================================@@ -74,22 +75,17 @@ export function escapeHtml(text: string): string {}export function getProjectDir(): string | null {- const editor = getEditorInstance();- const projectPath = editor?.projectPath;+ const projectPath = getProjectService().projectPath;if (!projectPath) return null;return projectPath.replace(/\\/g, '/').replace(/\/[^/]+$/, '');}export function openAssetInBrowser(assetPath: string): void {- const editor = getEditorInstance();- if (editor && typeof editor.navigateToAsset === 'function') {- editor.navigateToAsset(assetPath);- }+ getNavigationService().navigateToAsset(assetPath);}export function getAssetServer(): EditorAssetServer | null {- const editor = getEditorInstance();- return editor?.assetServer ?? null;+ return getNavigationService().getAssetServer();}const COMPONENT_ICON_MAP = new Map<string, (size: number) => string>([diff --git a/editor/src/panels/profiler/ProfilerPanel.ts b/editor/src/panels/profiler/ProfilerPanel.tsindex adbef1b15..48eab679e 100644--- a/editor/src/panels/profiler/ProfilerPanel.ts+++ b/editor/src/panels/profiler/ProfilerPanel.ts@@ -1,7 +1,7 @@import { FrameHistory, type FrameSnapshot } from 'esengine';import { listen, type UnlistenFn } from '@tauri-apps/api/event';import { CHANNEL_PROFILER_STATS, type ProfilerStatsMessage } from '../../multiwindow/protocol';-import { getEditorInstance } from '../../context/EditorContext';+import { getProfilerService } from '../../services';import type { PanelInstance } from '../PanelRegistry';import { FrameTimeline } from './FrameTimeline';import { PhaseWaterfall } from './PhaseWaterfall';@@ -38,7 +38,7 @@ export class ProfilerPanel implements PanelInstance {this.container_ = container;this.buildUI();this.startListening();- getEditorInstance()?.startProfilerStats();+ getProfilerService().startProfilerStats();}dispose(): void {@@ -50,7 +50,7 @@ export class ProfilerPanel implements PanelInstance {this.waterfall_?.dispose();this.systemTable_?.dispose();this.container_.innerHTML = '';- getEditorInstance()?.stopProfilerStats();+ getProfilerService().stopProfilerStats();}private buildUI(): void {diff --git a/editor/src/panels/scene-view/SceneViewInput.ts b/editor/src/panels/scene-view/SceneViewInput.tsindex 6bdf7fff3..ed82eab1d 100644--- a/editor/src/panels/scene-view/SceneViewInput.ts+++ b/editor/src/panels/scene-view/SceneViewInput.ts@@ -4,7 +4,7 @@ import type { GizmoContext } from '../../gizmos';import { GizmoManager } from '../../gizmos';import { ColliderOverlay } from '../../gizmos/ColliderOverlay';import { getSettingsValue } from '../../settings/SettingsRegistry';-import { getEditorInstance } from '../../context/EditorContext';+import { getClipboardService } from '../../services';import type { CameraController } from './CameraController';import type { GizmoToolbar } from './GizmoToolbar';import type { MarqueeSelection, BoundsProvider } from './MarqueeSelection';@@ -93,7 +93,7 @@ export class SceneViewInput {if ((e.key === 'd' || e.key === 'D') && (e.ctrlKey || e.metaKey)) {e.preventDefault();- getEditorInstance()?.duplicateSelected();+ getClipboardService().duplicateSelected();return;}diff --git a/editor/src/panels/scene-view/SceneViewPanel.ts b/editor/src/panels/scene-view/SceneViewPanel.tsindex 70f19c564..85ddb6123 100644--- a/editor/src/panels/scene-view/SceneViewPanel.ts+++ b/editor/src/panels/scene-view/SceneViewPanel.ts@@ -23,6 +23,7 @@ import { EntityDropHandler } from './EntityDropHandler';import { SceneViewInput } from './SceneViewInput';import { TilemapOverlay } from '../../gizmos/TilemapOverlay';import { DisposableStore } from '../../utils/Disposable';+import { getRuntimeService, getSpineService, getNavigationService } from '../../services';const CAMERA_COLORS = ['#ffaa00',@@ -73,6 +74,10 @@ export class SceneViewPanel {private fpsCollector_ = new StatsCollector();private lastFrameTime_ = 0;+ private disposeRuntimeReg_: (() => void) | null = null;+ private disposeSpineReg_: (() => void) | null = null;+ private disposeAssetServerReg_: (() => void) | null = null;+private static readonly MAX_CACHE_SIZE = 100;private textureCache_: Map<string, HTMLImageElement | null> = new Map();private loadingTextures_: Set<string> = new Set();@@ -176,6 +181,21 @@ export class SceneViewPanel {} else {this.startContinuousRender();}++ this.disposeRuntimeReg_ = getRuntimeService().registerAppListener((app, bridge) => {+ this.setBridge(bridge);+ this.setApp(app);+ });++ this.disposeSpineReg_ = getSpineService().registerSpinePanel({+ setSpineController: (ctrl) => this.setSpineController(ctrl),+ getSpineSkeletonInfo: (id) => this.getSpineSkeletonInfo(id),+ onSpineInstanceReady: (listener) => this.onSpineInstanceReady(listener),+ });++ this.disposeAssetServerReg_ = getNavigationService().registerAssetServerProvider(+ () => this.assetServer+ );}private getEntityBoundsWithSpine(entityData: EntityData): { width: number; height: number; offsetX?: number; offsetY?: number } {@@ -267,6 +287,9 @@ export class SceneViewPanel {dispose(): void {this.continuousRender_ = false;+ this.disposeRuntimeReg_?.();+ this.disposeSpineReg_?.();+ this.disposeAssetServerReg_?.();this.disposables_.dispose();getSharedRenderContext().setSceneViewportSize(0, 0);}diff --git a/editor/src/panels/timeline/TimelinePanel.ts b/editor/src/panels/timeline/TimelinePanel.tsindex 1d03c4cee..7d0e23f72 100644--- a/editor/src/panels/timeline/TimelinePanel.ts+++ b/editor/src/panels/timeline/TimelinePanel.ts@@ -8,7 +8,8 @@ import { TimelineTrackList } from './TimelineTrackList';import { TimelineKeyframeArea, type TimelineAssetData, type TimelineTrackData } from './TimelineKeyframeArea';import { TimelineCurveEditor } from './TimelineCurveEditor';import { AddKeyframeCommand } from './TimelineCommands';-import { getEditorContext, getEditorInstance } from '../../context/EditorContext';+import { getEditorContext } from '../../context/EditorContext';+import { getProjectService, getSceneService } from '../../services';import { getAssetDatabase as getAssetLibrary, isUUID } from '../../asset';import { DisposableStore } from '../../utils/Disposable';@@ -34,6 +35,7 @@ export class TimelinePanel implements PanelInstance {private assetPath_: string | null = null;private dirty_ = false;private boundEntityId_: number | null = null;+ private disposeDirtyReg_: (() => void) | null = null;constructor(container: HTMLElement, store: EditorStore) {this.container_ = container;@@ -61,9 +63,14 @@ export class TimelinePanel implements PanelInstance {}));this.updateEmptyState();+ this.disposeDirtyReg_ = getSceneService().registerDirtyChecker(() => ({+ isDirty: this.isDirty,+ save: () => this.saveAsset(),+ }));}dispose(): void {+ this.disposeDirtyReg_?.();this.stopPlayback();this.toolbar_?.dispose();this.trackList_?.dispose();@@ -411,7 +418,7 @@ export class TimelinePanel implements PanelInstance {if (!resolved) return null;relativePath = resolved;}- const projectPath = getEditorInstance()?.projectPath;+ const projectPath = getProjectService().projectPath;if (!projectPath) return null;const projectDir = projectPath.replace(/\\/g, '/').replace(/\/[^/]+$/, '');return `${projectDir}/${relativePath}`;diff --git a/editor/src/plugins/EditorPlugin.ts b/editor/src/plugins/EditorPlugin.tsindex 79e449051..88291729e 100644--- a/editor/src/plugins/EditorPlugin.ts+++ b/editor/src/plugins/EditorPlugin.ts@@ -1,11 +1,8 @@-import type { Editor } from '../Editor';import type { PluginRegistrar } from '../container';export interface EditorPluginContext {registrar: PluginRegistrar;- editor: Editor;projectPath: string | null;- onOpenScene: (path: string) => void;}export interface EditorPlugin {diff --git a/editor/src/plugins/coreMenus.ts b/editor/src/plugins/coreMenus.tsindex e8f542682..55de65203 100644--- a/editor/src/plugins/coreMenus.ts+++ b/editor/src/plugins/coreMenus.ts@@ -5,7 +5,7 @@ import { registerBuiltinStatusbarItems } from '../menus/builtinStatusbar';export const coreMenusPlugin: EditorPlugin = {name: 'core-menus',register(ctx: EditorPluginContext) {- registerBuiltinMenus(ctx.registrar, ctx.editor);+ registerBuiltinMenus(ctx.registrar);},};@@ -13,6 +13,6 @@ export const coreStatusbarPlugin: EditorPlugin = {name: 'core-statusbar',dependencies: ['core-menus', 'core-panels'],register(ctx: EditorPluginContext) {- registerBuiltinStatusbarItems(ctx.registrar, ctx.editor);+ registerBuiltinStatusbarItems(ctx.registrar);},};diff --git a/editor/src/plugins/corePanels.ts b/editor/src/plugins/corePanels.tsindex c5b0c7d64..a9a98e3a9 100644--- a/editor/src/plugins/corePanels.ts+++ b/editor/src/plugins/corePanels.ts@@ -6,7 +6,6 @@ export const corePanelsPlugin: EditorPlugin = {register(ctx: EditorPluginContext) {registerBuiltinPanels(ctx.registrar, {projectPath: ctx.projectPath ?? undefined,- onOpenScene: ctx.onOpenScene,});},};diff --git a/editor/src/property/EntityPicker.ts b/editor/src/property/EntityPicker.tsindex c0e1c411e..3ebc14d3b 100644--- a/editor/src/property/EntityPicker.ts+++ b/editor/src/property/EntityPicker.ts@@ -1,5 +1,5 @@-import { getEditorInstance } from '../context/EditorContext';import type { EntityData } from '../types/SceneTypes';+import { getEditorStore } from '../store';export interface EntityPickerOptions {anchorEl: HTMLElement;@@ -36,8 +36,7 @@ export function openEntityPicker(options: EntityPickerOptions): () => void {let filter = '';function buildFlatList(): FlatEntry[] {- const editor = getEditorInstance();- const entities = editor?.store.scene.entities;+ const entities = getEditorStore().scene.entities;if (!entities) return [];const childMap = new Map<number | null, EntityData[]>();diff --git a/editor/src/property/editors.ts b/editor/src/property/editors.tsindex 8835602de..33db3406d 100644--- a/editor/src/property/editors.ts+++ b/editor/src/property/editors.ts@@ -1,1932 +1,3 @@-/**- * @file editors.ts- * @brief Built-in property editors- */--import {- type PropertyEditorContext,- type PropertyEditorInstance,- type PropertyEditorFactory,-} from './PropertyEditor';-import type { PluginRegistrar } from '../container';-import { PROPERTY_EDITOR } from '../container/tokens';-import { getEditorContext, getEditorInstance } from '../context/EditorContext';-import { getPlatformAdapter } from '../platform/PlatformAdapter';-import { getAssetLibrary, isUUID } from '../asset/AssetLibrary';-import type { NativeFS } from '../types/NativeFS';-import { INVALID_TEXTURE, getAssetMimeType, getAssetTypeEntry } from 'esengine';-import { createUIRectEditor } from './uiRectEditor';-import { createButtonTransitionEditor } from './buttonTransitionEditor';-import { openEntityPicker } from './EntityPicker';-import { setupDragLabel, colorToHex, hexToColor } from './editorUtils';-import { validateNumber, validateVec2, validateVec3, validateColor, showValidationError } from './validation';-import { getNamedLayers, layerIndexFromBits, bitsFromLayerIndex } from '../settings/collisionLayers';-import { onSettingsChange } from '../settings/SettingsRegistry';-import { AssetType } from '../constants/AssetTypes';-export { setupDragLabel, colorToHex, hexToColor };--// =============================================================================-// Number Editor-// =============================================================================--function createNumberEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, meta, onChange } = ctx;-- const wrapper = document.createElement('div');- wrapper.className = 'es-number-editor';-- const label = document.createElement('span');- label.className = 'es-number-drag-label';- label.innerHTML = '⋮⋮';- label.title = 'Drag to adjust value';-- const input = document.createElement('input');- input.type = 'number';- input.className = 'es-input es-input-number';- input.value = String(value ?? 0);-- if (meta.min !== undefined) input.min = String(meta.min);- if (meta.max !== undefined) input.max = String(meta.max);- if (meta.step !== undefined) input.step = String(meta.step);-- const step = meta.step ?? 1;-- const handleChange = () => {- const result = validateNumber(input.value, meta);- if (!result.valid) {- showValidationError(input, result.error!);- input.value = String(result.value);- }- onChange(result.value);- };-- input.addEventListener('change', handleChange);-- input.addEventListener('keydown', (e) => {- if (e.key === 'Enter') {- input.blur();- handleChange();- }- });-- setupDragLabel(label, input, (newValue) => {- onChange(newValue);- }, step);-- wrapper.appendChild(label);- wrapper.appendChild(input);- container.appendChild(wrapper);-- return {- update(v: unknown) {- input.value = String(v ?? 0);- },- dispose() {- wrapper.remove();- },- };-}--// =============================================================================-// String Editor-// =============================================================================--function createStringEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, onChange } = ctx;- const input = document.createElement('input');- input.type = 'text';- input.className = 'es-input es-input-string';- input.value = String(value ?? '');-- input.addEventListener('change', () => {- onChange(input.value);- });-- container.appendChild(input);-- return {- update(v: unknown) {- input.value = String(v ?? '');- },- dispose() {- input.remove();- },- };-}--// =============================================================================-// Boolean Editor-// =============================================================================--function createBooleanEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, onChange } = ctx;- const input = document.createElement('input');- input.type = 'checkbox';- input.className = 'es-input es-input-checkbox';- input.checked = Boolean(value);-- input.addEventListener('change', () => {- onChange(input.checked);- });-- container.appendChild(input);-- return {- update(v: unknown) {- input.checked = Boolean(v);- },- dispose() {- input.remove();- },- };-}--// =============================================================================-// Vec2 Editor-// =============================================================================--interface Vec2 {- x: number;- y: number;-}--function createVec2Editor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, onChange } = ctx;- let currentVec = (value as Vec2) ?? { x: 0, y: 0 };-- const wrapper = document.createElement('div');- wrapper.className = 'es-vec-editor es-vec2-editor';-- const inputs: HTMLInputElement[] = [];- const labelTexts = ['X', 'Y'];- const colorClasses = ['es-vec-x', 'es-vec-y'];- const keys: (keyof Vec2)[] = ['x', 'y'];-- labelTexts.forEach((labelText, i) => {- const group = document.createElement('div');- group.className = `es-vec-field ${colorClasses[i]}`;-- const label = document.createElement('span');- label.className = 'es-vec-label';- label.textContent = labelText;-- const input = document.createElement('input');- input.type = 'number';- input.className = 'es-input es-input-number';- input.step = '0.01';- input.value = String(currentVec[keys[i]]);-- const handleChange = () => {- const updatedVec = { ...currentVec, [keys[i]]: parseFloat(input.value) || 0 };- const result = validateVec2(updatedVec, ctx.meta);- if (!result.valid) {- showValidationError(input, result.error!);- currentVec = result.value as Vec2;- input.value = String(currentVec[keys[i]]);- } else {- currentVec = updatedVec;- }- onChange(currentVec);- };-- input.addEventListener('change', handleChange);-- input.addEventListener('keydown', (e) => {- if (e.key === 'Enter') {- input.blur();- handleChange();- }- });-- setupDragLabel(label, input, (newValue) => {- currentVec = { ...currentVec, [keys[i]]: newValue };- onChange(currentVec);- });-- group.appendChild(label);- group.appendChild(input);- wrapper.appendChild(group);- inputs.push(input);- });-- container.appendChild(wrapper);-- return {- update(v: unknown) {- currentVec = (v as Vec2) ?? { x: 0, y: 0 };- inputs[0].value = String(currentVec.x);- inputs[1].value = String(currentVec.y);- },- dispose() {- wrapper.remove();- },- };-}--// =============================================================================-// Vec3 Editor-// =============================================================================--interface Vec3 {- x: number;- y: number;- z: number;-}--function createVec3Editor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, onChange } = ctx;- let currentVec = (value as Vec3) ?? { x: 0, y: 0, z: 0 };-- const wrapper = document.createElement('div');- wrapper.className = 'es-vec-editor es-vec3-editor';-- const inputs: HTMLInputElement[] = [];- const labelTexts = ['X', 'Y', 'Z'];- const keys: (keyof Vec3)[] = ['x', 'y', 'z'];- const colorClasses = ['es-vec-x', 'es-vec-y', 'es-vec-z'];-- labelTexts.forEach((labelText, i) => {- const group = document.createElement('div');- group.className = `es-vec-field ${colorClasses[i]}`;-- const label = document.createElement('span');- label.className = 'es-vec-label';- label.textContent = labelText;-- const input = document.createElement('input');- input.type = 'number';- input.className = 'es-input es-input-number';- input.step = '0.01';- input.value = String(currentVec[keys[i]]);-- const handleChange = () => {- const updatedVec = { ...currentVec, [keys[i]]: parseFloat(input.value) || 0 };- const result = validateVec3(updatedVec, ctx.meta);- if (!result.valid) {- showValidationError(input, result.error!);- currentVec = result.value as Vec3;- input.value = String(currentVec[keys[i]]);- } else {- currentVec = updatedVec;- }- onChange(currentVec);- };-- input.addEventListener('change', handleChange);-- input.addEventListener('keydown', (e) => {- if (e.key === 'Enter') {- input.blur();- handleChange();- }- });-- setupDragLabel(label, input, (newValue) => {- currentVec = { ...currentVec, [keys[i]]: newValue };- onChange(currentVec);- });-- group.appendChild(label);- group.appendChild(input);- wrapper.appendChild(group);- inputs.push(input);- });-- container.appendChild(wrapper);-- return {- update(v: unknown) {- currentVec = (v as Vec3) ?? { x: 0, y: 0, z: 0 };- inputs[0].value = String(currentVec.x);- inputs[1].value = String(currentVec.y);- inputs[2].value = String(currentVec.z);- },- dispose() {- wrapper.remove();- },- };-}--// =============================================================================-// Vec4 Editor-// =============================================================================--interface Vec4 {- x: number;- y: number;- z: number;- w: number;-}--function createVec4Editor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, onChange } = ctx;- let currentVec = (value as Vec4) ?? { x: 0, y: 0, z: 0, w: 1 };-- const wrapper = document.createElement('div');- wrapper.className = 'es-vec-editor es-vec4-editor';-- const inputs: HTMLInputElement[] = [];- const labelTexts = ['X', 'Y', 'Z', 'W'];- const keys: (keyof Vec4)[] = ['x', 'y', 'z', 'w'];- const colorClasses = ['es-vec-x', 'es-vec-y', 'es-vec-z', 'es-vec-w'];-- labelTexts.forEach((labelText, i) => {- const group = document.createElement('div');- group.className = `es-vec-field ${colorClasses[i]}`;-- const label = document.createElement('span');- label.className = 'es-vec-label';- label.textContent = labelText;-- const input = document.createElement('input');- input.type = 'number';- input.className = 'es-input es-input-number';- input.step = '0.01';- input.value = String(currentVec[keys[i]]);-- input.addEventListener('change', () => {- currentVec = { ...currentVec, [keys[i]]: parseFloat(input.value) || 0 };- onChange(currentVec);- });-- input.addEventListener('keydown', (e) => {- if (e.key === 'Enter') {- input.blur();- currentVec = { ...currentVec, [keys[i]]: parseFloat(input.value) || 0 };- onChange(currentVec);- }- });-- setupDragLabel(label, input, (newValue) => {- currentVec = { ...currentVec, [keys[i]]: newValue };- onChange(currentVec);- });-- group.appendChild(label);- group.appendChild(input);- wrapper.appendChild(group);- inputs.push(input);- });-- container.appendChild(wrapper);-- return {- update(v: unknown) {- currentVec = (v as Vec4) ?? { x: 0, y: 0, z: 0, w: 1 };- inputs[0].value = String(currentVec.x);- inputs[1].value = String(currentVec.y);- inputs[2].value = String(currentVec.z);- inputs[3].value = String(currentVec.w);- },- dispose() {- wrapper.remove();- },- };-}--// =============================================================================-// Padding Editor-// =============================================================================--interface PaddingValue { left: number; top: number; right: number; bottom: number }--function createPaddingEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const wrapper = document.createElement('div');- wrapper.className = 'vec-editor';-- const keys: (keyof PaddingValue)[] = ['left', 'top', 'right', 'bottom'];- const labels = ['L', 'T', 'R', 'B'];- let currentPad: PaddingValue = { left: 0, top: 0, right: 0, bottom: 0 };- const inputs: HTMLInputElement[] = [];-- const onChange = (value: PaddingValue) => {- ctx.onChange(value);- };-- keys.forEach((key, i) => {- const group = document.createElement('div');- group.className = 'vec-component';- const label = document.createElement('span');- label.className = 'vec-label';- label.textContent = labels[i];- const input = document.createElement('input');- input.type = 'number';- input.className = 'property-input vec-input';- input.value = String(currentPad[key]);-- input.addEventListener('change', () => {- currentPad = { ...currentPad, [key]: parseFloat(input.value) || 0 };- onChange(currentPad);- });-- input.addEventListener('keydown', (e) => {- if (e.key === 'Enter') {- input.blur();- currentPad = { ...currentPad, [key]: parseFloat(input.value) || 0 };- onChange(currentPad);- }- });-- setupDragLabel(label, input, (newValue) => {- currentPad = { ...currentPad, [key]: newValue };- onChange(currentPad);- });-- group.appendChild(label);- group.appendChild(input);- wrapper.appendChild(group);- inputs.push(input);- });-- container.appendChild(wrapper);-- return {- update(v: unknown) {- currentPad = (v as PaddingValue) ?? { left: 0, top: 0, right: 0, bottom: 0 };- inputs[0].value = String(currentPad.left);- inputs[1].value = String(currentPad.top);- inputs[2].value = String(currentPad.right);- inputs[3].value = String(currentPad.bottom);- },- dispose() {- wrapper.remove();- },- };-}--// =============================================================================-// Color Editor-// =============================================================================--type RGBA = { r: number; g: number; b: number; a: number };--function sanitizeColor(color: RGBA | null | undefined): RGBA {- if (!color || typeof color !== 'object') return { r: 1, g: 1, b: 1, a: 1 };- const s = (v: unknown) => (typeof v === 'number' && Number.isFinite(v)) ? v : 0;- return { r: s(color.r), g: s(color.g), b: s(color.b), a: s(color.a) || 1 };-}--function createColorEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, onChange } = ctx;- const raw = value as { r: number; g: number; b: number; a: number } | null | undefined;- const color = sanitizeColor(raw);-- const wrapper = document.createElement('div');- wrapper.className = 'es-color-editor';-- const colorInput = document.createElement('input');- colorInput.type = 'color';- colorInput.className = 'es-input es-input-color';- colorInput.value = colorToHex(color);-- const hexInput = document.createElement('input');- hexInput.type = 'text';- hexInput.className = 'es-input es-input-hex';- hexInput.value = colorToHex(color).toUpperCase();-- const alphaInput = document.createElement('input');- alphaInput.type = 'number';- alphaInput.className = 'es-input es-input-number es-input-alpha';- alphaInput.min = '0';- alphaInput.max = '1';- alphaInput.step = '0.01';- alphaInput.value = String(color.a);-- const applyColor = (hex: string, alpha: number) => {- const newColor = hexToColor(hex);- newColor.a = alpha;- onChange(newColor);- };-- colorInput.addEventListener('change', () => {- hexInput.value = colorInput.value.toUpperCase();- applyColor(colorInput.value, parseFloat(alphaInput.value) || 1);- });-- alphaInput.addEventListener('change', () => {- applyColor(colorInput.value, parseFloat(alphaInput.value) || 1);- });-- hexInput.addEventListener('keydown', (e) => {- if (e.key !== 'Enter') return;- let hex = hexInput.value.trim();- if (!hex.startsWith('#')) hex = '#' + hex;- if (/^#[0-9a-fA-F]{6}$/.test(hex)) {- colorInput.value = hex;- hexInput.value = hex.toUpperCase();- applyColor(hex, parseFloat(alphaInput.value) || 1);- } else {- hexInput.value = colorInput.value.toUpperCase();- }- });-- wrapper.appendChild(colorInput);- wrapper.appendChild(hexInput);- wrapper.appendChild(alphaInput);- container.appendChild(wrapper);-- return {- update(v: unknown) {- const newColor = sanitizeColor(v as { r: number; g: number; b: number; a: number } | null | undefined);- colorInput.value = colorToHex(newColor);- hexInput.value = colorToHex(newColor).toUpperCase();- alphaInput.value = String(newColor.a);- },- dispose() {- wrapper.remove();- },- };-}---// =============================================================================-// Euler Angle Editor (displays degrees, stores as quaternion)-// =============================================================================--interface Quat {- x: number;- y: number;- z: number;- w: number;-}--interface EulerAngles {- x: number;- y: number;- z: number;-}--function quatToEuler(q: Quat): EulerAngles {- const { x, y, z, w } = q;-- const sinrCosp = 2 * (w * x + y * z);- const cosrCosp = 1 - 2 * (x * x + y * y);- const roll = Math.atan2(sinrCosp, cosrCosp);-- const sinp = 2 * (w * y - z * x);- let pitch: number;- if (Math.abs(sinp) >= 1) {- pitch = Math.sign(sinp) * Math.PI / 2;- } else {- pitch = Math.asin(sinp);- }-- const sinyCosp = 2 * (w * z + x * y);- const cosyCosp = 1 - 2 * (y * y + z * z);- const yaw = Math.atan2(sinyCosp, cosyCosp);-- const toDeg = 180 / Math.PI;- return {- x: roll * toDeg,- y: pitch * toDeg,- z: yaw * toDeg,- };-}--function eulerToQuat(euler: EulerAngles): Quat {- const toRad = Math.PI / 180;- const roll = euler.x * toRad;- const pitch = euler.y * toRad;- const yaw = euler.z * toRad;-- const cr = Math.cos(roll * 0.5);- const sr = Math.sin(roll * 0.5);- const cp = Math.cos(pitch * 0.5);- const sp = Math.sin(pitch * 0.5);- const cy = Math.cos(yaw * 0.5);- const sy = Math.sin(yaw * 0.5);-- return {- w: cr * cp * cy + sr * sp * sy,- x: sr * cp * cy - cr * sp * sy,- y: cr * sp * cy + sr * cp * sy,- z: cr * cp * sy - sr * sp * cy,- };-}--function createEulerEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, onChange } = ctx;- const quat = (value as Quat) ?? { x: 0, y: 0, z: 0, w: 1 };- let currentEuler = quatToEuler(quat);-- const wrapper = document.createElement('div');- wrapper.className = 'es-vec-editor es-vec3-editor';-- const inputs: HTMLInputElement[] = [];- const labelTexts = ['X', 'Y', 'Z'];- const keys: (keyof EulerAngles)[] = ['x', 'y', 'z'];- const colorClasses = ['es-vec-x', 'es-vec-y', 'es-vec-z'];-- labelTexts.forEach((labelText, i) => {- const group = document.createElement('div');- group.className = `es-vec-field ${colorClasses[i]}`;-- const label = document.createElement('span');- label.className = 'es-vec-label';- label.textContent = labelText;-- const input = document.createElement('input');- input.type = 'number';- input.className = 'es-input es-input-number';- input.step = '0.1';- input.value = currentEuler[keys[i]].toFixed(1);-- input.addEventListener('change', () => {- currentEuler = { ...currentEuler, [keys[i]]: parseFloat(input.value) || 0 };- onChange(eulerToQuat(currentEuler));- });-- input.addEventListener('keydown', (e) => {- if (e.key === 'Enter') {- input.blur();- currentEuler = { ...currentEuler, [keys[i]]: parseFloat(input.value) || 0 };- onChange(eulerToQuat(currentEuler));- }- });-- setupDragLabel(label, input, (newValue) => {- currentEuler = { ...currentEuler, [keys[i]]: newValue };- onChange(eulerToQuat(currentEuler));- }, 1);-- group.appendChild(label);- group.appendChild(input);- wrapper.appendChild(group);- inputs.push(input);- });-- container.appendChild(wrapper);-- return {- update(v: unknown) {- const q = (v as Quat) ?? { x: 0, y: 0, z: 0, w: 1 };- currentEuler = quatToEuler(q);- inputs[0].value = currentEuler.x.toFixed(1);- inputs[1].value = currentEuler.y.toFixed(1);- inputs[2].value = currentEuler.z.toFixed(1);- },- dispose() {- wrapper.remove();- },- };-}--// =============================================================================-// Enum Editor-// =============================================================================--function createEnumEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, meta, onChange } = ctx;- const options = meta.options ?? [];-- const select = document.createElement('select');- select.className = 'es-input es-input-select';-- options.forEach(opt => {- const option = document.createElement('option');- option.value = String(opt.value);- option.textContent = opt.label;- if (opt.value === value) {- option.selected = true;- }- select.appendChild(option);- });-- select.addEventListener('change', () => {- const selected = options.find(o => String(o.value) === select.value);- if (selected) {- onChange(selected.value);- }- });-- container.appendChild(select);-- return {- update(v: unknown) {- select.value = String(v);- },- dispose() {- select.remove();- },- };-}--// =============================================================================-// Texture Editor-// =============================================================================--export function getNativeFS(): NativeFS | null {- return getEditorContext().fs ?? null;-}--export function getProjectDir(): string | null {- const editor = getEditorInstance();- const projectPath = editor?.projectPath;- if (!projectPath) return null;- return projectPath.replace(/\\/g, '/').replace(/\/[^/]+$/, '');-}--export function getMimeType(path: string): string {- const ext = path.split('.').pop()?.toLowerCase() ?? '';- return getAssetMimeType(ext) ?? 'image/png';-}--function resolveDisplayName(ref: string): string {- if (!ref) return '';- if (isUUID(ref)) {- const path = getAssetLibrary().getPath(ref);- return path ?? ref;- }- return ref;-}--async function checkAssetMissing(ref: string, input: HTMLInputElement): Promise<void> {- if (!ref) {- input.classList.remove('es-missing-asset');- return;- }- const path = resolveToPath(ref);- const projectDir = getProjectDir();- const fs = getNativeFS();- if (!path || !projectDir || !fs) return;- const exists = await fs.exists(`${projectDir}/${path}`);- input.classList.toggle('es-missing-asset', !exists);-}--function resolveToPath(ref: string): string {- if (!ref) return '';- if (isUUID(ref)) {- return getAssetLibrary().getPath(ref) ?? ref;- }- return ref;-}--function createTextureEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, onChange } = ctx;- let currentBlobUrl: string | null = null;- let currentRef = '';- let previewGeneration = 0;-- const wrapper = document.createElement('div');- wrapper.className = 'es-texture-editor';-- const preview = document.createElement('div');- preview.className = 'es-texture-preview';- preview.title = 'Click to locate in Content Browser';-- const previewImg = document.createElement('img');- previewImg.className = 'es-texture-preview-img';- preview.appendChild(previewImg);-- const inputRow = document.createElement('div');- inputRow.className = 'es-texture-input-row';-- const input = document.createElement('input');- input.type = 'text';- input.className = 'es-input es-input-texture es-asset-link';- input.value = (value && typeof value === 'string' && value !== String(INVALID_TEXTURE)) ? resolveDisplayName(value) : '';- input.placeholder = 'None';- input.readOnly = true;-- const browseBtn = document.createElement('button');- browseBtn.className = 'es-btn es-btn-icon es-btn-browse';- browseBtn.title = 'Browse';- browseBtn.innerHTML = BROWSE_ICON;-- const clearBtn = document.createElement('button');- clearBtn.className = 'es-btn es-btn-icon es-btn-clear';- clearBtn.title = 'Clear';- clearBtn.innerHTML = CLEAR_ICON;-- const updatePreview = async (textureRef: string) => {- const gen = ++previewGeneration;-- if (currentBlobUrl) {- URL.revokeObjectURL(currentBlobUrl);- currentBlobUrl = null;- }-- const projectDir = getProjectDir();- const fs = getNativeFS();- const texturePath = resolveToPath(textureRef);-- if (texturePath && projectDir && fs) {- const fullPath = `${projectDir}/${texturePath}`;- try {- const data = await fs.readBinaryFile(fullPath);- if (gen !== previewGeneration) return;- if (data) {- const blob = new Blob([data.buffer as ArrayBuffer], { type: getMimeType(texturePath) });- currentBlobUrl = URL.createObjectURL(blob);- previewImg.src = currentBlobUrl;- previewImg.style.display = 'block';- preview.classList.add('es-has-preview');- return;- }- } catch (err) {- if (gen !== previewGeneration) return;- console.warn('Failed to load texture preview:', err);- }- }-- previewImg.src = '';- previewImg.style.display = 'none';- preview.classList.remove('es-has-preview');- };-- const navigateToAssetPath = async (e: Event) => {- e.stopPropagation();- const displayPath = input.value;- if (!displayPath) return;-- const editor = getEditorInstance();- if (editor?.navigateToAsset) {- await editor.navigateToAsset(displayPath);- }- };-- currentRef = (value && typeof value === 'string' && value !== String(INVALID_TEXTURE)) ? value : '';- updatePreview(currentRef);- checkAssetMissing(currentRef, input);-- input.addEventListener('click', navigateToAssetPath);- preview.addEventListener('click', navigateToAssetPath);-- handleAssetDrop(wrapper, [AssetType.IMAGE], (relativePath, ref) => {- input.value = relativePath;- currentRef = ref;- onChange(ref);- updatePreview(ref);- });-- browseBtn.addEventListener('click', async () => {- const result = await browseForAsset('Select Texture', 'Images', ['png', 'jpg', 'jpeg', 'webp']);- if (result) {- input.value = result.relativePath;- currentRef = result.ref;- onChange(result.ref);- updatePreview(result.ref);- }- });-- clearBtn.addEventListener('click', () => {- input.value = '';- currentRef = '';- onChange('');- updatePreview('');- });-- inputRow.appendChild(input);- inputRow.appendChild(browseBtn);- inputRow.appendChild(clearBtn);- wrapper.appendChild(preview);- wrapper.appendChild(inputRow);- container.appendChild(wrapper);-- return {- update(v: unknown) {- const raw = (typeof v === 'string') ? v : '';- const newValue = (!raw || raw === String(INVALID_TEXTURE)) ? '' : raw;- input.value = newValue ? resolveDisplayName(newValue) : '';- if (newValue !== currentRef) {- currentRef = newValue;- updatePreview(newValue);- checkAssetMissing(newValue, input);- }- },- dispose() {- if (currentBlobUrl) {- URL.revokeObjectURL(currentBlobUrl);- }- wrapper.remove();- },- };-}--// =============================================================================-// Font Editor-// =============================================================================--const AVAILABLE_FONTS = [- 'Arial',- 'Helvetica',- 'Times New Roman',- 'Georgia',- 'Verdana',- 'Tahoma',- 'Trebuchet MS',- 'Courier New',- 'Lucida Console',- 'Impact',- 'Comic Sans MS',- 'Microsoft YaHei',- 'SimHei',- 'SimSun',- 'KaiTi',- 'FangSong',-];--function getAvailableFonts(): string[] {- const testString = 'mmmmmmmmmmlli';- const testSize = '72px';- const baseline = 'monospace';-- const canvas = document.createElement('canvas');- const ctx = canvas.getContext('2d')!;- ctx.font = `${testSize} ${baseline}`;- const baselineWidth = ctx.measureText(testString).width;-- const available: string[] = [];- for (const font of AVAILABLE_FONTS) {- ctx.font = `${testSize} "${font}", ${baseline}`;- const width = ctx.measureText(testString).width;- if (width !== baselineWidth) {- available.push(font);- }- }-- return available.length > 0 ? available : ['Arial', 'sans-serif'];-}--function createFontEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, onChange } = ctx;-- const wrapper = document.createElement('div');- wrapper.className = 'es-font-editor';-- const select = document.createElement('select');- select.className = 'es-input es-input-select';-- const fonts = getAvailableFonts();- const currentFont = String(value ?? 'Arial');-- if (!fonts.includes(currentFont)) {- fonts.unshift(currentFont);- }-- for (const font of fonts) {- const option = document.createElement('option');- option.value = font;- option.textContent = font;- option.style.fontFamily = font;- if (font === currentFont) {- option.selected = true;- }- select.appendChild(option);- }-- select.addEventListener('change', () => {- onChange(select.value);- });-- wrapper.appendChild(select);- container.appendChild(wrapper);-- return {- update(v: unknown) {- select.value = String(v ?? 'Arial');- },- dispose() {- wrapper.remove();- },- };-}--// =============================================================================-// Spine File Editor-// =============================================================================--function createSpineFileEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, meta, onChange } = ctx;- const fileFilter = meta.fileFilter ?? ['.json', '.skel'];-- const wrapper = document.createElement('div');- wrapper.className = 'es-file-editor';-- const input = document.createElement('input');- input.type = 'text';- input.className = 'es-input es-input-file';- input.value = resolveDisplayName(String(value ?? ''));- input.placeholder = 'None';- checkAssetMissing(String(value ?? ''), input);-- const browseBtn = document.createElement('button');- browseBtn.className = 'es-btn es-btn-icon es-btn-browse';- browseBtn.title = 'Browse';- browseBtn.innerHTML = BROWSE_ICON;-- const clearBtn = document.createElement('button');- clearBtn.className = 'es-btn es-btn-icon es-btn-clear';- clearBtn.title = 'Clear';- clearBtn.innerHTML = CLEAR_ICON;-- input.addEventListener('change', () => {- onChange(input.value || '');- });-- browseBtn.addEventListener('click', async () => {- const extensions = fileFilter.map((f: string) => f.replace('.', ''));- const result = await browseForAsset('Select File', 'Spine Files', extensions);- if (result) {- input.value = result.relativePath;- onChange(result.ref);- }- });-- clearBtn.addEventListener('click', () => {- input.value = '';- onChange('');- });-- wrapper.appendChild(input);- wrapper.appendChild(browseBtn);- wrapper.appendChild(clearBtn);- container.appendChild(wrapper);-- return {- update(v: unknown) {- const ref = String(v ?? '');- input.value = resolveDisplayName(ref);- checkAssetMissing(ref, input);- },- dispose() {- wrapper.remove();- },- };-}--// =============================================================================-// Spine Animation Editor (dynamic dropdown from skeleton file)-// =============================================================================--interface SpineSkeletonData {- animations?: Record<string, unknown>;- skins?: Array<{ name: string }> | Record<string, unknown>;-}--async function loadSpineSkeletonData(skeletonPath: string, atlasPath?: string): Promise<SpineSkeletonData | null> {- if (!skeletonPath) return null;-- const editor = getEditorInstance();- if (editor) {- const entityId = editor.store.selectedEntity as number | null;- if (entityId !== null) {- const info = editor.getSpineSkeletonInfo(entityId);- if (info) {- const animRecord: Record<string, unknown> = {};- for (const name of info.animations) {- animRecord[name] = {};- }- return {- animations: animRecord,- skins: info.skins.map(name => ({ name })),- };- }- }- }-- if (getAssetTypeEntry(skeletonPath)?.contentType === 'binary') {- return null;- }-- const projectDir = getProjectDir();- const fs = getNativeFS();- if (!projectDir || !fs) return null;-- const jsonPath = `${projectDir}/${skeletonPath}`;- try {- const content = await fs.readFile(jsonPath);- if (!content) return null;- return JSON.parse(content) as SpineSkeletonData;- } catch {- return null;- }-}--function getAnimationNames(data: SpineSkeletonData): string[] {- if (!data.animations) return [];- return Object.keys(data.animations);-}--function getSkinNames(data: SpineSkeletonData): string[] {- if (!data.skins) return [];- if (Array.isArray(data.skins)) {- return data.skins.map(s => s.name);- }- return Object.keys(data.skins);-}--function createSpineAnimationEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, onChange, getComponentValue } = ctx;-- const wrapper = document.createElement('div');- wrapper.className = 'es-spine-animation-editor';-- const select = document.createElement('select');- select.className = 'es-input es-input-select';-- const refreshBtn = document.createElement('button');- refreshBtn.className = 'es-btn es-btn-icon es-btn-refresh';- refreshBtn.title = 'Refresh animations';- refreshBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 2v6h-6M3 12a9 9 0 0 1 15-6.7L21 8M3 22v-6h6M21 12a9 9 0 0 1-15 6.7L3 16"></path></svg>`;-- let currentAnimations: string[] = [];-- const updateOptions = (animations: string[], currentValue: string) => {- select.innerHTML = '';-- const emptyOption = document.createElement('option');- emptyOption.value = '';- emptyOption.textContent = '(None)';- select.appendChild(emptyOption);-- for (const anim of animations) {- const option = document.createElement('option');- option.value = anim;- option.textContent = anim;- if (anim === currentValue) {- option.selected = true;- }- select.appendChild(option);- }-- currentAnimations = animations;- };-- const loadAnimations = async () => {- const skeletonRef = getComponentValue?.('skeletonPath') as string;- const skeletonPath = skeletonRef ? resolveToPath(skeletonRef) : '';- if (!skeletonPath) {- updateOptions([], String(value ?? ''));- return;- }-- const atlasRef = getComponentValue?.('atlasPath') as string;- const atlasPath = atlasRef ? resolveToPath(atlasRef) : undefined;- const data = await loadSpineSkeletonData(skeletonPath, atlasPath);- if (data) {- const animations = getAnimationNames(data);- updateOptions(animations, String(value ?? ''));- } else {- updateOptions([], String(value ?? ''));- }- };-- const editor = getEditorInstance();- const unsubSpineReady = editor?.onSpineInstanceReady((entityId) => {- const selected = editor.store.selectedEntity as number | null;- if (selected === entityId) {- loadAnimations();- }- }) ?? null;-- select.addEventListener('change', () => {- onChange(select.value);- });-- refreshBtn.addEventListener('click', () => {- loadAnimations();- });-- wrapper.appendChild(select);- wrapper.appendChild(refreshBtn);- container.appendChild(wrapper);-- loadAnimations();-- return {- update(v: unknown) {- const newValue = String(v ?? '');- if (currentAnimations.includes(newValue) || newValue === '') {- select.value = newValue;- } else {- loadAnimations();- }- },- dispose() {- unsubSpineReady?.();- wrapper.remove();- },- };-}--// =============================================================================-// Spine Skin Editor (dynamic dropdown from skeleton file)-// =============================================================================--function createSpineSkinEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, onChange, getComponentValue } = ctx;-- const wrapper = document.createElement('div');- wrapper.className = 'es-spine-skin-editor';-- const select = document.createElement('select');- select.className = 'es-input es-input-select';-- const refreshBtn = document.createElement('button');- refreshBtn.className = 'es-btn es-btn-icon es-btn-refresh';- refreshBtn.title = 'Refresh skins';- refreshBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 2v6h-6M3 12a9 9 0 0 1 15-6.7L21 8M3 22v-6h6M21 12a9 9 0 0 1-15 6.7L3 16"></path></svg>`;-- let currentSkins: string[] = [];-- const updateOptions = (skins: string[], currentValue: string) => {- select.innerHTML = '';-- for (const skin of skins) {- const option = document.createElement('option');- option.value = skin;- option.textContent = skin;- if (skin === currentValue) {- option.selected = true;- }- select.appendChild(option);- }-- if (skins.length === 0) {- const defaultOption = document.createElement('option');- defaultOption.value = 'default';- defaultOption.textContent = 'default';- select.appendChild(defaultOption);- }-- currentSkins = skins;- };-- const loadSkins = async () => {- const skeletonRef = getComponentValue?.('skeletonPath') as string;- const skeletonPath = skeletonRef ? resolveToPath(skeletonRef) : '';- if (!skeletonPath) {- updateOptions(['default'], String(value ?? 'default'));- return;- }-- const atlasRef = getComponentValue?.('atlasPath') as string;- const atlasPath = atlasRef ? resolveToPath(atlasRef) : undefined;- const data = await loadSpineSkeletonData(skeletonPath, atlasPath);- if (data) {- const skins = getSkinNames(data);- updateOptions(skins.length > 0 ? skins : ['default'], String(value ?? 'default'));- } else {- updateOptions(['default'], String(value ?? 'default'));- }- };-- const editor = getEditorInstance();- const unsubSpineReady = editor?.onSpineInstanceReady((entityId) => {- const selected = editor.store.selectedEntity as number | null;- if (selected === entityId) {- loadSkins();- }- }) ?? null;-- select.addEventListener('change', () => {- onChange(select.value);- });-- refreshBtn.addEventListener('click', () => {- loadSkins();- });-- wrapper.appendChild(select);- wrapper.appendChild(refreshBtn);- container.appendChild(wrapper);-- loadSkins();-- return {- update(v: unknown) {- const newValue = String(v ?? 'default');- if (currentSkins.includes(newValue)) {- select.value = newValue;- } else {- loadSkins();- }- },- dispose() {- unsubSpineReady?.();- wrapper.remove();- },- };-}--// =============================================================================-// Generic Asset File Editor Factory-// =============================================================================--interface AssetFileEditorConfig {- acceptTypes: string[];- dialogTitle: string;- filterName: string;- extensions: string[];-}--export function navigateToAsset(assetPath: string): void {- const editor = getEditorInstance();- if (editor && typeof editor.navigateToAsset === 'function') {- editor.navigateToAsset(assetPath);- }-}--export const BROWSE_ICON = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-6l-2-2H5a2 2 0 0 0-2 2z"></path></svg>`;-export const CLEAR_ICON = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`;-const ASSET_DRAG_MIME = 'application/esengine-asset';-const ASSETS_DIR_NAME = 'assets';--export function handleAssetDrop(- wrapper: HTMLElement,- acceptTypes: string[],- onAccept: (relativePath: string, ref: string) => void-): void {- wrapper.addEventListener('dragover', (e) => {- e.preventDefault();- if (e.dataTransfer?.types.includes(ASSET_DRAG_MIME)) {- wrapper.classList.add('es-drag-over');- e.dataTransfer!.dropEffect = 'copy';- } else {- e.dataTransfer!.dropEffect = 'none';- }- });-- wrapper.addEventListener('dragleave', () => {- wrapper.classList.remove('es-drag-over');- });-- wrapper.addEventListener('drop', (e) => {- e.preventDefault();- wrapper.classList.remove('es-drag-over');- const jsonData = e.dataTransfer?.getData(ASSET_DRAG_MIME);- if (!jsonData) return;- try {- const assetData = JSON.parse(jsonData);- if (acceptTypes.includes(assetData.type)) {- const projectDir = getProjectDir();- if (projectDir && assetData.path.startsWith(projectDir)) {- const relativePath = assetData.path.substring(projectDir.length + 1);- const uuid = getAssetLibrary().getUuid(relativePath);- onAccept(relativePath, uuid ?? relativePath);- }- }- } catch (err) {- console.error('Failed to parse drop data:', err);- }- });-}--export async function browseForAsset(- dialogTitle: string,- filterName: string,- extensions: string[]-): Promise<{ relativePath: string; ref: string } | null> {- const projectDir = getProjectDir();- if (!projectDir) return null;-- const assetsDir = `${projectDir}/${ASSETS_DIR_NAME}`;- try {- const platform = getPlatformAdapter();- const result = await platform.openFileDialog({- title: dialogTitle,- defaultPath: assetsDir,- filters: [{ name: filterName, extensions }],- });- if (result) {- const normalizedPath = result.replace(/\\/g, '/');- const assetsIndex = normalizedPath.indexOf(`/${ASSETS_DIR_NAME}/`);- if (assetsIndex !== -1) {- const relativePath = normalizedPath.substring(assetsIndex + 1);- const uuid = getAssetLibrary().getUuid(relativePath);- return { relativePath, ref: uuid ?? relativePath };- }- }- } catch (err) {- console.error('Failed to open file dialog:', err);- }- return null;-}--function createAssetFileEditor(- container: HTMLElement,- ctx: PropertyEditorContext,- config: AssetFileEditorConfig-): PropertyEditorInstance {- const { value, onChange } = ctx;-- const wrapper = document.createElement('div');- wrapper.className = 'es-file-editor';-- const input = document.createElement('input');- input.type = 'text';- input.className = 'es-input es-input-file es-asset-link';- input.value = resolveDisplayName(String(value ?? ''));- input.placeholder = 'None';- input.readOnly = true;- checkAssetMissing(String(value ?? ''), input);-- const browseBtn = document.createElement('button');- browseBtn.className = 'es-btn es-btn-icon es-btn-browse';- browseBtn.title = 'Browse';- browseBtn.innerHTML = BROWSE_ICON;-- const clearBtn = document.createElement('button');- clearBtn.className = 'es-btn es-btn-icon es-btn-clear';- clearBtn.title = 'Clear';- clearBtn.innerHTML = CLEAR_ICON;-- input.addEventListener('click', () => {- if (input.value) navigateToAsset(input.value);- });-- handleAssetDrop(wrapper, config.acceptTypes, (relativePath, ref) => {- input.value = relativePath;- onChange(ref);- });-- browseBtn.addEventListener('click', async () => {- const result = await browseForAsset(config.dialogTitle, config.filterName, config.extensions);- if (result) {- input.value = result.relativePath;- onChange(result.ref);- }- });-- clearBtn.addEventListener('click', () => {- input.value = '';- onChange('');- });-- wrapper.appendChild(input);- wrapper.appendChild(browseBtn);- wrapper.appendChild(clearBtn);- container.appendChild(wrapper);-- return {- update(v: unknown) {- const ref = String(v ?? '');- input.value = resolveDisplayName(ref);- checkAssetMissing(ref, input);- },- dispose() {- wrapper.remove();- },- };-}--// =============================================================================-// Entity Editor-// =============================================================================--function createEntityEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, onChange } = ctx;- let currentValue = Number(value) || 0;- let closePicker: (() => void) | null = null;-- const wrapper = document.createElement('div');- wrapper.className = 'es-entity-field';-- const label = document.createElement('span');- label.className = 'es-entity-field-label';- updateLabel(currentValue);-- label.addEventListener('click', () => {- if (currentValue === 0) return;- const editor = getEditorInstance();- if (editor) {- editor.store.selectEntity(currentValue);- }- });-- const pickerBtn = document.createElement('button');- pickerBtn.className = 'es-entity-field-btn';- pickerBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 12 12" fill="none"><circle cx="6" cy="6" r="4.5" stroke="currentColor" stroke-width="1.2"/><circle cx="6" cy="6" r="1.5" fill="currentColor"/></svg>';- pickerBtn.title = 'Pick entity';-- pickerBtn.addEventListener('click', () => {- if (closePicker) return;- closePicker = openEntityPicker({- anchorEl: wrapper,- currentValue,- onSelect: (id: number) => {- currentValue = id;- updateLabel(id);- onChange(id);- },- onClose: () => { closePicker = null; },- });- });-- const ENTITY_MIME = 'application/esengine-entity';-- wrapper.addEventListener('dragover', (e) => {- if (e.dataTransfer?.types.includes(ENTITY_MIME)) {- e.preventDefault();- e.dataTransfer.dropEffect = 'link';- wrapper.classList.add('es-drag-over');- }- });-- wrapper.addEventListener('dragleave', () => {- wrapper.classList.remove('es-drag-over');- });-- wrapper.addEventListener('drop', (e) => {- wrapper.classList.remove('es-drag-over');- const raw = e.dataTransfer?.getData(ENTITY_MIME);- if (!raw) return;- e.preventDefault();- const entityId = parseInt(raw, 10);- if (!isNaN(entityId) && entityId > 0) {- currentValue = entityId;- updateLabel(entityId);- onChange(entityId);- }- });-- wrapper.appendChild(label);- wrapper.appendChild(pickerBtn);- container.appendChild(wrapper);-- function updateLabel(entityId: number) {- if (entityId === 0) {- label.textContent = '(None)';- label.classList.add('es-none');- } else {- label.classList.remove('es-none');- const editor = getEditorInstance();- const entity = editor?.store.scene.entities.find(e => e.id === entityId);- label.textContent = entity ? entity.name : `Entity ${entityId}`;- }- }-- return {- update(v: unknown) {- currentValue = Number(v) || 0;- updateLabel(currentValue);- },- dispose() {- if (closePicker) closePicker();- wrapper.remove();- },- };-}--// =============================================================================-// Vec2 Array Editor-// =============================================================================--type Vec2Item = { x: number; y: number };--function createVec2ArrayEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, meta, onChange } = ctx;- let items: Vec2Item[] = Array.isArray(value)- ? (value as Vec2Item[]).map(v => ({ x: v.x, y: v.y }))- : [];-- const wrapper = document.createElement('div');- wrapper.className = 'es-vec2-array-editor';-- const listEl = document.createElement('div');- listEl.className = 'es-vec2-array-list';-- const addBtn = document.createElement('button');- addBtn.className = 'es-btn es-btn-sm es-btn-add-item';- addBtn.textContent = '+';- addBtn.title = 'Add vertex';-- function emitChange() {- onChange(items.map(v => ({ x: v.x, y: v.y })));- }-- function updateAddButton() {- if (meta.max !== undefined && items.length >= meta.max) {- addBtn.style.display = 'none';- } else {- addBtn.style.display = '';- }- }-- function renderItems() {- listEl.innerHTML = '';- items.forEach((item, index) => {- const row = document.createElement('div');- row.className = 'es-vec2-array-row';-- const indexLabel = document.createElement('span');- indexLabel.className = 'es-vec2-array-index';- indexLabel.textContent = String(index);-- const xGroup = document.createElement('div');- xGroup.className = 'es-vec-field es-vec-x';- const xLabel = document.createElement('span');- xLabel.className = 'es-vec-label';- xLabel.textContent = 'X';- const xInput = document.createElement('input');- xInput.type = 'number';- xInput.className = 'es-input es-input-number';- xInput.step = '0.01';- xInput.value = String(item.x);- xInput.addEventListener('change', () => {- items[index] = { ...items[index], x: parseFloat(xInput.value) || 0 };- emitChange();- });- setupDragLabel(xLabel, xInput, (newValue) => {- items[index] = { ...items[index], x: newValue };- emitChange();- });- xGroup.appendChild(xLabel);- xGroup.appendChild(xInput);-- const yGroup = document.createElement('div');- yGroup.className = 'es-vec-field es-vec-y';- const yLabel = document.createElement('span');- yLabel.className = 'es-vec-label';- yLabel.textContent = 'Y';- const yInput = document.createElement('input');- yInput.type = 'number';- yInput.className = 'es-input es-input-number';- yInput.step = '0.01';- yInput.value = String(item.y);- yInput.addEventListener('change', () => {- items[index] = { ...items[index], y: parseFloat(yInput.value) || 0 };- emitChange();- });- setupDragLabel(yLabel, yInput, (newValue) => {- items[index] = { ...items[index], y: newValue };- emitChange();- });- yGroup.appendChild(yLabel);- yGroup.appendChild(yInput);-- const removeBtn = document.createElement('button');- removeBtn.className = 'es-btn es-btn-icon es-btn-clear';- removeBtn.title = 'Remove';- removeBtn.innerHTML = `<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`;- removeBtn.addEventListener('click', () => {- items.splice(index, 1);- emitChange();- renderItems();- });-- row.appendChild(indexLabel);- row.appendChild(xGroup);- row.appendChild(yGroup);- row.appendChild(removeBtn);- listEl.appendChild(row);- });- updateAddButton();- }-- addBtn.addEventListener('click', () => {- items.push({ x: 0, y: 0 });- emitChange();- renderItems();- });-- renderItems();- wrapper.appendChild(listEl);- wrapper.appendChild(addBtn);- container.appendChild(wrapper);-- return {- update(v: unknown) {- items = Array.isArray(v)- ? (v as Vec2Item[]).map(vi => ({ x: vi.x, y: vi.y }))- : [];- renderItems();- },- dispose() {- wrapper.remove();- },- };-}--// =============================================================================-// String Array Editor-// =============================================================================--function createStringArrayEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, onChange } = ctx;- let items = Array.isArray(value) ? [...value as string[]] : [];-- const wrapper = document.createElement('div');- wrapper.className = 'es-string-array-editor';-- const listEl = document.createElement('div');- listEl.className = 'es-string-array-list';-- const addBtn = document.createElement('button');- addBtn.className = 'es-btn es-btn-sm es-btn-add-item';- addBtn.textContent = '+';- addBtn.title = 'Add item';-- function renderItems() {- listEl.innerHTML = '';- items.forEach((item, index) => {- const row = document.createElement('div');- row.className = 'es-string-array-row';-- const input = document.createElement('input');- input.type = 'text';- input.className = 'es-input es-input-string';- input.value = item;-- input.addEventListener('change', () => {- items[index] = input.value;- onChange([...items]);- });-- const removeBtn = document.createElement('button');- removeBtn.className = 'es-btn es-btn-icon es-btn-clear';- removeBtn.title = 'Remove';- removeBtn.innerHTML = `<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`;-- removeBtn.addEventListener('click', () => {- items.splice(index, 1);- onChange([...items]);- renderItems();- });-- row.appendChild(input);- row.appendChild(removeBtn);- listEl.appendChild(row);- });- }-- addBtn.addEventListener('click', () => {- items.push('');- onChange([...items]);- renderItems();- const lastInput = listEl.querySelector('.es-string-array-row:last-child input') as HTMLInputElement;- lastInput?.focus();- });-- renderItems();- wrapper.appendChild(listEl);- wrapper.appendChild(addBtn);- container.appendChild(wrapper);-- return {- update(v: unknown) {- items = Array.isArray(v) ? [...v as string[]] : [];- renderItems();- },- dispose() {- wrapper.remove();- },- };-}--// =============================================================================-// Asset File Editor Configs (data-driven via createAssetFileEditor)-// =============================================================================--const ASSET_FILE_EDITORS: Record<string, AssetFileEditorConfig> = {- 'material-file': { acceptTypes: [AssetType.MATERIAL], dialogTitle: 'Select Material', filterName: 'Material Files', extensions: ['esmaterial'] },- 'bitmap-font-file': { acceptTypes: [AssetType.FONT], dialogTitle: 'Select BitmapFont', filterName: 'BitmapFont Files', extensions: ['bmfont'] },- 'anim-file': { acceptTypes: [AssetType.ANIMCLIP], dialogTitle: 'Select Animation Clip', filterName: 'Animation Clip', extensions: ['esanim'] },- 'timeline-file': { acceptTypes: [AssetType.TIMELINE], dialogTitle: 'Select Timeline', filterName: 'Timeline', extensions: ['estimeline'] },- 'audio-file': { acceptTypes: [AssetType.AUDIO], dialogTitle: 'Select Audio File', filterName: 'Audio', extensions: ['mp3', 'wav', 'ogg'] },- 'tilemap-file': { acceptTypes: [AssetType.TILEMAP], dialogTitle: 'Select Tilemap', filterName: 'Tiled Map', extensions: ['tmj'] },-};--// =============================================================================-// Collision Layer Editor-// =============================================================================--function createCollisionLayerEditor(- container: HTMLElement,- ctx: PropertyEditorContext-): PropertyEditorInstance {- const { value, onChange } = ctx;-- const select = document.createElement('select');- select.className = 'es-input es-input-select';-- function populateOptions(): void {- select.innerHTML = '';- const layers = getNamedLayers();- for (const layer of layers) {- const option = document.createElement('option');- option.value = String(layer.index);- option.textContent = `${layer.index}: ${layer.name}`;- select.appendChild(option);- }- }-- populateOptions();- const currentIndex = layerIndexFromBits(value as number);- select.value = String(currentIndex);-- select.addEventListener('change', () => {- const idx = parseInt(select.value, 10);- onChange(bitsFromLayerIndex(idx));- });-- const unsubscribe = onSettingsChange((id) => {- if (id.startsWith('physics.layerName')) {- const prev = select.value;- populateOptions();- select.value = prev;- }- });-- container.appendChild(select);-- return {- update(newValue: unknown) {- populateOptions();- const idx = layerIndexFromBits(newValue as number);- select.value = String(idx);- },- dispose() {- unsubscribe();- select.remove();- },- };-}--// =============================================================================-// Register All Editors-// =============================================================================--export function registerBuiltinEditors(registrar: PluginRegistrar): void {- const registerPropertyEditor = (type: string, factory: PropertyEditorFactory) => registrar.provide(PROPERTY_EDITOR, type, factory);- console.log('[PropertyEditor] registerBuiltinEditors called');- registerPropertyEditor('number', createNumberEditor);- registerPropertyEditor('string', createStringEditor);- registerPropertyEditor('boolean', createBooleanEditor);- registerPropertyEditor('vec2', createVec2Editor);- registerPropertyEditor('vec3', createVec3Editor);- registerPropertyEditor('vec4', createVec4Editor);- registerPropertyEditor('padding', createPaddingEditor);- registerPropertyEditor('color', createColorEditor);- registerPropertyEditor('enum', createEnumEditor);- registerPropertyEditor('euler', createEulerEditor);- registerPropertyEditor('texture', createTextureEditor);- registerPropertyEditor('font', createFontEditor);- registerPropertyEditor('spine-file', createSpineFileEditor);- registerPropertyEditor('spine-animation', createSpineAnimationEditor);- registerPropertyEditor('spine-skin', createSpineSkinEditor);- for (const [editorType, config] of Object.entries(ASSET_FILE_EDITORS)) {- registerPropertyEditor(editorType, (container, ctx) => createAssetFileEditor(container, ctx, config));- }- registerPropertyEditor('uirect', createUIRectEditor);- registerPropertyEditor('button-transition', createButtonTransitionEditor);- registerPropertyEditor('entity', createEntityEditor);- registerPropertyEditor('string-array', createStringArrayEditor);- registerPropertyEditor('vec2-array', createVec2ArrayEditor);- registerPropertyEditor('collision-layer', createCollisionLayerEditor);-}+export { registerBuiltinEditors } from './editors/index';+export { setupDragLabel, colorToHex, hexToColor } from './editorUtils';+export { getNativeFS, getProjectDir, getMimeType, navigateToAsset, handleAssetDrop, browseForAsset, BROWSE_ICON, CLEAR_ICON } from './editors/assetEditors';diff --git a/editor/src/property/editors/arrayEditors.ts b/editor/src/property/editors/arrayEditors.tsnew file mode 100644index 000000000..63039bafc--- /dev/null+++ b/editor/src/property/editors/arrayEditors.ts@@ -0,0 +1,209 @@+import {+ type PropertyEditorContext,+ type PropertyEditorInstance,+} from '../PropertyEditor';+import { setupDragLabel } from '../editorUtils';++type Vec2Item = { x: number; y: number };++export function createVec2ArrayEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, meta, onChange } = ctx;+ let items: Vec2Item[] = Array.isArray(value)+ ? (value as Vec2Item[]).map(v => ({ x: v.x, y: v.y }))+ : [];++ const wrapper = document.createElement('div');+ wrapper.className = 'es-vec2-array-editor';++ const listEl = document.createElement('div');+ listEl.className = 'es-vec2-array-list';++ const addBtn = document.createElement('button');+ addBtn.className = 'es-btn es-btn-sm es-btn-add-item';+ addBtn.textContent = '+';+ addBtn.title = 'Add vertex';++ function emitChange() {+ onChange(items.map(v => ({ x: v.x, y: v.y })));+ }++ function updateAddButton() {+ if (meta.max !== undefined && items.length >= meta.max) {+ addBtn.style.display = 'none';+ } else {+ addBtn.style.display = '';+ }+ }++ function renderItems() {+ listEl.innerHTML = '';+ items.forEach((item, index) => {+ const row = document.createElement('div');+ row.className = 'es-vec2-array-row';++ const indexLabel = document.createElement('span');+ indexLabel.className = 'es-vec2-array-index';+ indexLabel.textContent = String(index);++ const xGroup = document.createElement('div');+ xGroup.className = 'es-vec-field es-vec-x';+ const xLabel = document.createElement('span');+ xLabel.className = 'es-vec-label';+ xLabel.textContent = 'X';+ const xInput = document.createElement('input');+ xInput.type = 'number';+ xInput.className = 'es-input es-input-number';+ xInput.step = '0.01';+ xInput.value = String(item.x);+ xInput.addEventListener('change', () => {+ items[index] = { ...items[index], x: parseFloat(xInput.value) || 0 };+ emitChange();+ });+ setupDragLabel(xLabel, xInput, (newValue) => {+ items[index] = { ...items[index], x: newValue };+ emitChange();+ });+ xGroup.appendChild(xLabel);+ xGroup.appendChild(xInput);++ const yGroup = document.createElement('div');+ yGroup.className = 'es-vec-field es-vec-y';+ const yLabel = document.createElement('span');+ yLabel.className = 'es-vec-label';+ yLabel.textContent = 'Y';+ const yInput = document.createElement('input');+ yInput.type = 'number';+ yInput.className = 'es-input es-input-number';+ yInput.step = '0.01';+ yInput.value = String(item.y);+ yInput.addEventListener('change', () => {+ items[index] = { ...items[index], y: parseFloat(yInput.value) || 0 };+ emitChange();+ });+ setupDragLabel(yLabel, yInput, (newValue) => {+ items[index] = { ...items[index], y: newValue };+ emitChange();+ });+ yGroup.appendChild(yLabel);+ yGroup.appendChild(yInput);++ const removeBtn = document.createElement('button');+ removeBtn.className = 'es-btn es-btn-icon es-btn-clear';+ removeBtn.title = 'Remove';+ removeBtn.innerHTML = `<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`;+ removeBtn.addEventListener('click', () => {+ items.splice(index, 1);+ emitChange();+ renderItems();+ });++ row.appendChild(indexLabel);+ row.appendChild(xGroup);+ row.appendChild(yGroup);+ row.appendChild(removeBtn);+ listEl.appendChild(row);+ });+ updateAddButton();+ }++ addBtn.addEventListener('click', () => {+ items.push({ x: 0, y: 0 });+ emitChange();+ renderItems();+ });++ renderItems();+ wrapper.appendChild(listEl);+ wrapper.appendChild(addBtn);+ container.appendChild(wrapper);++ return {+ update(v: unknown) {+ items = Array.isArray(v)+ ? (v as Vec2Item[]).map(vi => ({ x: vi.x, y: vi.y }))+ : [];+ renderItems();+ },+ dispose() {+ wrapper.remove();+ },+ };+}++export function createStringArrayEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, onChange } = ctx;+ let items = Array.isArray(value) ? [...value as string[]] : [];++ const wrapper = document.createElement('div');+ wrapper.className = 'es-string-array-editor';++ const listEl = document.createElement('div');+ listEl.className = 'es-string-array-list';++ const addBtn = document.createElement('button');+ addBtn.className = 'es-btn es-btn-sm es-btn-add-item';+ addBtn.textContent = '+';+ addBtn.title = 'Add item';++ function renderItems() {+ listEl.innerHTML = '';+ items.forEach((item, index) => {+ const row = document.createElement('div');+ row.className = 'es-string-array-row';++ const input = document.createElement('input');+ input.type = 'text';+ input.className = 'es-input es-input-string';+ input.value = item;++ input.addEventListener('change', () => {+ items[index] = input.value;+ onChange([...items]);+ });++ const removeBtn = document.createElement('button');+ removeBtn.className = 'es-btn es-btn-icon es-btn-clear';+ removeBtn.title = 'Remove';+ removeBtn.innerHTML = `<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`;++ removeBtn.addEventListener('click', () => {+ items.splice(index, 1);+ onChange([...items]);+ renderItems();+ });++ row.appendChild(input);+ row.appendChild(removeBtn);+ listEl.appendChild(row);+ });+ }++ addBtn.addEventListener('click', () => {+ items.push('');+ onChange([...items]);+ renderItems();+ const lastInput = listEl.querySelector('.es-string-array-row:last-child input') as HTMLInputElement;+ lastInput?.focus();+ });++ renderItems();+ wrapper.appendChild(listEl);+ wrapper.appendChild(addBtn);+ container.appendChild(wrapper);++ return {+ update(v: unknown) {+ items = Array.isArray(v) ? [...v as string[]] : [];+ renderItems();+ },+ dispose() {+ wrapper.remove();+ },+ };+}diff --git a/editor/src/property/editors/assetEditors.ts b/editor/src/property/editors/assetEditors.tsnew file mode 100644index 000000000..fdc409d63--- /dev/null+++ b/editor/src/property/editors/assetEditors.ts@@ -0,0 +1,219 @@+import {+ type PropertyEditorContext,+ type PropertyEditorInstance,+} from '../PropertyEditor';+import { getEditorContext } from '../../context/EditorContext';+import { getNavigationService, getProjectService } from '../../services';+import { getPlatformAdapter } from '../../platform/PlatformAdapter';+import { getAssetLibrary, isUUID } from '../../asset/AssetLibrary';+import type { NativeFS } from '../../types/NativeFS';+import { getAssetMimeType } from 'esengine';+import { AssetType } from '../../constants/AssetTypes';++export function getNativeFS(): NativeFS | null {+ return getEditorContext().fs ?? null;+}++export function getProjectDir(): string | null {+ const projectPath = getProjectService().projectPath;+ if (!projectPath) return null;+ return projectPath.replace(/\\/g, '/').replace(/\/[^/]+$/, '');+}++export function getMimeType(path: string): string {+ const ext = path.split('.').pop()?.toLowerCase() ?? '';+ return getAssetMimeType(ext) ?? 'image/png';+}++export function resolveDisplayName(ref: string): string {+ if (!ref) return '';+ if (isUUID(ref)) {+ const path = getAssetLibrary().getPath(ref);+ return path ?? ref;+ }+ return ref;+}++export async function checkAssetMissing(ref: string, input: HTMLInputElement): Promise<void> {+ if (!ref) {+ input.classList.remove('es-missing-asset');+ return;+ }+ const path = resolveToPath(ref);+ const projectDir = getProjectDir();+ const fs = getNativeFS();+ if (!path || !projectDir || !fs) return;+ const exists = await fs.exists(`${projectDir}/${path}`);+ input.classList.toggle('es-missing-asset', !exists);+}++export function resolveToPath(ref: string): string {+ if (!ref) return '';+ if (isUUID(ref)) {+ return getAssetLibrary().getPath(ref) ?? ref;+ }+ return ref;+}++export function navigateToAsset(assetPath: string): void {+ getNavigationService().navigateToAsset(assetPath);+}++export const BROWSE_ICON = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-6l-2-2H5a2 2 0 0 0-2 2z"></path></svg>`;+export const CLEAR_ICON = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`;+const ASSET_DRAG_MIME = 'application/esengine-asset';+const ASSETS_DIR_NAME = 'assets';++export function handleAssetDrop(+ wrapper: HTMLElement,+ acceptTypes: string[],+ onAccept: (relativePath: string, ref: string) => void+): void {+ wrapper.addEventListener('dragover', (e) => {+ e.preventDefault();+ if (e.dataTransfer?.types.includes(ASSET_DRAG_MIME)) {+ wrapper.classList.add('es-drag-over');+ e.dataTransfer!.dropEffect = 'copy';+ } else {+ e.dataTransfer!.dropEffect = 'none';+ }+ });++ wrapper.addEventListener('dragleave', () => {+ wrapper.classList.remove('es-drag-over');+ });++ wrapper.addEventListener('drop', (e) => {+ e.preventDefault();+ wrapper.classList.remove('es-drag-over');+ const jsonData = e.dataTransfer?.getData(ASSET_DRAG_MIME);+ if (!jsonData) return;+ try {+ const assetData = JSON.parse(jsonData);+ if (acceptTypes.includes(assetData.type)) {+ const projectDir = getProjectDir();+ if (projectDir && assetData.path.startsWith(projectDir)) {+ const relativePath = assetData.path.substring(projectDir.length + 1);+ const uuid = getAssetLibrary().getUuid(relativePath);+ onAccept(relativePath, uuid ?? relativePath);+ }+ }+ } catch (err) {+ console.error('Failed to parse drop data:', err);+ }+ });+}++export async function browseForAsset(+ dialogTitle: string,+ filterName: string,+ extensions: string[]+): Promise<{ relativePath: string; ref: string } | null> {+ const projectDir = getProjectDir();+ if (!projectDir) return null;++ const assetsDir = `${projectDir}/${ASSETS_DIR_NAME}`;+ try {+ const platform = getPlatformAdapter();+ const result = await platform.openFileDialog({+ title: dialogTitle,+ defaultPath: assetsDir,+ filters: [{ name: filterName, extensions }],+ });+ if (result) {+ const normalizedPath = result.replace(/\\/g, '/');+ const assetsIndex = normalizedPath.indexOf(`/${ASSETS_DIR_NAME}/`);+ if (assetsIndex !== -1) {+ const relativePath = normalizedPath.substring(assetsIndex + 1);+ const uuid = getAssetLibrary().getUuid(relativePath);+ return { relativePath, ref: uuid ?? relativePath };+ }+ }+ } catch (err) {+ console.error('Failed to open file dialog:', err);+ }+ return null;+}++interface AssetFileEditorConfig {+ acceptTypes: string[];+ dialogTitle: string;+ filterName: string;+ extensions: string[];+}++export function createAssetFileEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext,+ config: AssetFileEditorConfig+): PropertyEditorInstance {+ const { value, onChange } = ctx;++ const wrapper = document.createElement('div');+ wrapper.className = 'es-file-editor';++ const input = document.createElement('input');+ input.type = 'text';+ input.className = 'es-input es-input-file es-asset-link';+ input.value = resolveDisplayName(String(value ?? ''));+ input.placeholder = 'None';+ input.readOnly = true;+ checkAssetMissing(String(value ?? ''), input);++ const browseBtn = document.createElement('button');+ browseBtn.className = 'es-btn es-btn-icon es-btn-browse';+ browseBtn.title = 'Browse';+ browseBtn.innerHTML = BROWSE_ICON;++ const clearBtn = document.createElement('button');+ clearBtn.className = 'es-btn es-btn-icon es-btn-clear';+ clearBtn.title = 'Clear';+ clearBtn.innerHTML = CLEAR_ICON;++ input.addEventListener('click', () => {+ if (input.value) navigateToAsset(input.value);+ });++ handleAssetDrop(wrapper, config.acceptTypes, (relativePath, ref) => {+ input.value = relativePath;+ onChange(ref);+ });++ browseBtn.addEventListener('click', async () => {+ const result = await browseForAsset(config.dialogTitle, config.filterName, config.extensions);+ if (result) {+ input.value = result.relativePath;+ onChange(result.ref);+ }+ });++ clearBtn.addEventListener('click', () => {+ input.value = '';+ onChange('');+ });++ wrapper.appendChild(input);+ wrapper.appendChild(browseBtn);+ wrapper.appendChild(clearBtn);+ container.appendChild(wrapper);++ return {+ update(v: unknown) {+ const ref = String(v ?? '');+ input.value = resolveDisplayName(ref);+ checkAssetMissing(ref, input);+ },+ dispose() {+ wrapper.remove();+ },+ };+}++export const ASSET_FILE_EDITORS: Record<string, AssetFileEditorConfig> = {+ 'material-file': { acceptTypes: [AssetType.MATERIAL], dialogTitle: 'Select Material', filterName: 'Material Files', extensions: ['esmaterial'] },+ 'bitmap-font-file': { acceptTypes: [AssetType.FONT], dialogTitle: 'Select BitmapFont', filterName: 'BitmapFont Files', extensions: ['bmfont'] },+ 'anim-file': { acceptTypes: [AssetType.ANIMCLIP], dialogTitle: 'Select Animation Clip', filterName: 'Animation Clip', extensions: ['esanim'] },+ 'timeline-file': { acceptTypes: [AssetType.TIMELINE], dialogTitle: 'Select Timeline', filterName: 'Timeline', extensions: ['estimeline'] },+ 'audio-file': { acceptTypes: [AssetType.AUDIO], dialogTitle: 'Select Audio File', filterName: 'Audio', extensions: ['mp3', 'wav', 'ogg'] },+ 'tilemap-file': { acceptTypes: [AssetType.TILEMAP], dialogTitle: 'Select Tilemap', filterName: 'Tiled Map', extensions: ['tmj'] },+};diff --git a/editor/src/property/editors/booleanEditor.ts b/editor/src/property/editors/booleanEditor.tsnew file mode 100644index 000000000..94f4c0ded--- /dev/null+++ b/editor/src/property/editors/booleanEditor.ts@@ -0,0 +1,30 @@+import {+ type PropertyEditorContext,+ type PropertyEditorInstance,+} from '../PropertyEditor';++export function createBooleanEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, onChange } = ctx;+ const input = document.createElement('input');+ input.type = 'checkbox';+ input.className = 'es-input es-input-checkbox';+ input.checked = Boolean(value);++ input.addEventListener('change', () => {+ onChange(input.checked);+ });++ container.appendChild(input);++ return {+ update(v: unknown) {+ input.checked = Boolean(v);+ },+ dispose() {+ input.remove();+ },+ };+}diff --git a/editor/src/property/editors/collisionLayerEditor.ts b/editor/src/property/editors/collisionLayerEditor.tsnew file mode 100644index 000000000..a86b9a0ac--- /dev/null+++ b/editor/src/property/editors/collisionLayerEditor.ts@@ -0,0 +1,58 @@+import {+ type PropertyEditorContext,+ type PropertyEditorInstance,+} from '../PropertyEditor';+import { getNamedLayers, layerIndexFromBits, bitsFromLayerIndex } from '../../settings/collisionLayers';+import { onSettingsChange } from '../../settings/SettingsRegistry';++export function createCollisionLayerEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, onChange } = ctx;++ const select = document.createElement('select');+ select.className = 'es-input es-input-select';++ function populateOptions(): void {+ select.innerHTML = '';+ const layers = getNamedLayers();+ for (const layer of layers) {+ const option = document.createElement('option');+ option.value = String(layer.index);+ option.textContent = `${layer.index}: ${layer.name}`;+ select.appendChild(option);+ }+ }++ populateOptions();+ const currentIndex = layerIndexFromBits(value as number);+ select.value = String(currentIndex);++ select.addEventListener('change', () => {+ const idx = parseInt(select.value, 10);+ onChange(bitsFromLayerIndex(idx));+ });++ const unsubscribe = onSettingsChange((id) => {+ if (id.startsWith('physics.layerName')) {+ const prev = select.value;+ populateOptions();+ select.value = prev;+ }+ });++ container.appendChild(select);++ return {+ update(newValue: unknown) {+ populateOptions();+ const idx = layerIndexFromBits(newValue as number);+ select.value = String(idx);+ },+ dispose() {+ unsubscribe();+ select.remove();+ },+ };+}diff --git a/editor/src/property/editors/colorEditor.ts b/editor/src/property/editors/colorEditor.tsnew file mode 100644index 000000000..c680689dc--- /dev/null+++ b/editor/src/property/editors/colorEditor.ts@@ -0,0 +1,88 @@+import {+ type PropertyEditorContext,+ type PropertyEditorInstance,+} from '../PropertyEditor';+import { colorToHex, hexToColor } from '../editorUtils';++type RGBA = { r: number; g: number; b: number; a: number };++function sanitizeColor(color: RGBA | null | undefined): RGBA {+ if (!color || typeof color !== 'object') return { r: 1, g: 1, b: 1, a: 1 };+ const s = (v: unknown) => (typeof v === 'number' && Number.isFinite(v)) ? v : 0;+ return { r: s(color.r), g: s(color.g), b: s(color.b), a: s(color.a) || 1 };+}++export function createColorEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, onChange } = ctx;+ const raw = value as { r: number; g: number; b: number; a: number } | null | undefined;+ const color = sanitizeColor(raw);++ const wrapper = document.createElement('div');+ wrapper.className = 'es-color-editor';++ const colorInput = document.createElement('input');+ colorInput.type = 'color';+ colorInput.className = 'es-input es-input-color';+ colorInput.value = colorToHex(color);++ const hexInput = document.createElement('input');+ hexInput.type = 'text';+ hexInput.className = 'es-input es-input-hex';+ hexInput.value = colorToHex(color).toUpperCase();++ const alphaInput = document.createElement('input');+ alphaInput.type = 'number';+ alphaInput.className = 'es-input es-input-number es-input-alpha';+ alphaInput.min = '0';+ alphaInput.max = '1';+ alphaInput.step = '0.01';+ alphaInput.value = String(color.a);++ const applyColor = (hex: string, alpha: number) => {+ const newColor = hexToColor(hex);+ newColor.a = alpha;+ onChange(newColor);+ };++ colorInput.addEventListener('change', () => {+ hexInput.value = colorInput.value.toUpperCase();+ applyColor(colorInput.value, parseFloat(alphaInput.value) || 1);+ });++ alphaInput.addEventListener('change', () => {+ applyColor(colorInput.value, parseFloat(alphaInput.value) || 1);+ });++ hexInput.addEventListener('keydown', (e) => {+ if (e.key !== 'Enter') return;+ let hex = hexInput.value.trim();+ if (!hex.startsWith('#')) hex = '#' + hex;+ if (/^#[0-9a-fA-F]{6}$/.test(hex)) {+ colorInput.value = hex;+ hexInput.value = hex.toUpperCase();+ applyColor(hex, parseFloat(alphaInput.value) || 1);+ } else {+ hexInput.value = colorInput.value.toUpperCase();+ }+ });++ wrapper.appendChild(colorInput);+ wrapper.appendChild(hexInput);+ wrapper.appendChild(alphaInput);+ container.appendChild(wrapper);++ return {+ update(v: unknown) {+ const newColor = sanitizeColor(v as { r: number; g: number; b: number; a: number } | null | undefined);+ colorInput.value = colorToHex(newColor);+ hexInput.value = colorToHex(newColor).toUpperCase();+ alphaInput.value = String(newColor.a);+ },+ dispose() {+ wrapper.remove();+ },+ };+}diff --git a/editor/src/property/editors/entityEditor.ts b/editor/src/property/editors/entityEditor.tsnew file mode 100644index 000000000..65242a0ec--- /dev/null+++ b/editor/src/property/editors/entityEditor.ts@@ -0,0 +1,99 @@+import {+ type PropertyEditorContext,+ type PropertyEditorInstance,+} from '../PropertyEditor';+import { getEditorStore } from '../../store/EditorStore';+import { openEntityPicker } from '../EntityPicker';++export function createEntityEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, onChange } = ctx;+ let currentValue = Number(value) || 0;+ let closePicker: (() => void) | null = null;++ const wrapper = document.createElement('div');+ wrapper.className = 'es-entity-field';++ const label = document.createElement('span');+ label.className = 'es-entity-field-label';+ updateLabel(currentValue);++ label.addEventListener('click', () => {+ if (currentValue === 0) return;+ getEditorStore().selectEntity(currentValue);+ });++ const pickerBtn = document.createElement('button');+ pickerBtn.className = 'es-entity-field-btn';+ pickerBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 12 12" fill="none"><circle cx="6" cy="6" r="4.5" stroke="currentColor" stroke-width="1.2"/><circle cx="6" cy="6" r="1.5" fill="currentColor"/></svg>';+ pickerBtn.title = 'Pick entity';++ pickerBtn.addEventListener('click', () => {+ if (closePicker) return;+ closePicker = openEntityPicker({+ anchorEl: wrapper,+ currentValue,+ onSelect: (id: number) => {+ currentValue = id;+ updateLabel(id);+ onChange(id);+ },+ onClose: () => { closePicker = null; },+ });+ });++ const ENTITY_MIME = 'application/esengine-entity';++ wrapper.addEventListener('dragover', (e) => {+ if (e.dataTransfer?.types.includes(ENTITY_MIME)) {+ e.preventDefault();+ e.dataTransfer.dropEffect = 'link';+ wrapper.classList.add('es-drag-over');+ }+ });++ wrapper.addEventListener('dragleave', () => {+ wrapper.classList.remove('es-drag-over');+ });++ wrapper.addEventListener('drop', (e) => {+ wrapper.classList.remove('es-drag-over');+ const raw = e.dataTransfer?.getData(ENTITY_MIME);+ if (!raw) return;+ e.preventDefault();+ const entityId = parseInt(raw, 10);+ if (!isNaN(entityId) && entityId > 0) {+ currentValue = entityId;+ updateLabel(entityId);+ onChange(entityId);+ }+ });++ wrapper.appendChild(label);+ wrapper.appendChild(pickerBtn);+ container.appendChild(wrapper);++ function updateLabel(entityId: number) {+ if (entityId === 0) {+ label.textContent = '(None)';+ label.classList.add('es-none');+ } else {+ label.classList.remove('es-none');+ const entity = getEditorStore().scene.entities.find((e: { id: number }) => e.id === entityId);+ label.textContent = entity ? entity.name : `Entity ${entityId}`;+ }+ }++ return {+ update(v: unknown) {+ currentValue = Number(v) || 0;+ updateLabel(currentValue);+ },+ dispose() {+ if (closePicker) closePicker();+ wrapper.remove();+ },+ };+}diff --git a/editor/src/property/editors/enumEditor.ts b/editor/src/property/editors/enumEditor.tsnew file mode 100644index 000000000..d1833ac92--- /dev/null+++ b/editor/src/property/editors/enumEditor.ts@@ -0,0 +1,43 @@+import {+ type PropertyEditorContext,+ type PropertyEditorInstance,+} from '../PropertyEditor';++export function createEnumEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, meta, onChange } = ctx;+ const options = meta.options ?? [];++ const select = document.createElement('select');+ select.className = 'es-input es-input-select';++ options.forEach(opt => {+ const option = document.createElement('option');+ option.value = String(opt.value);+ option.textContent = opt.label;+ if (opt.value === value) {+ option.selected = true;+ }+ select.appendChild(option);+ });++ select.addEventListener('change', () => {+ const selected = options.find(o => String(o.value) === select.value);+ if (selected) {+ onChange(selected.value);+ }+ });++ container.appendChild(select);++ return {+ update(v: unknown) {+ select.value = String(v);+ },+ dispose() {+ select.remove();+ },+ };+}diff --git a/editor/src/property/editors/eulerEditor.ts b/editor/src/property/editors/eulerEditor.tsnew file mode 100644index 000000000..1b0d02183--- /dev/null+++ b/editor/src/property/editors/eulerEditor.ts@@ -0,0 +1,136 @@+import {+ type PropertyEditorContext,+ type PropertyEditorInstance,+} from '../PropertyEditor';+import { setupDragLabel } from '../editorUtils';++interface Quat {+ x: number;+ y: number;+ z: number;+ w: number;+}++interface EulerAngles {+ x: number;+ y: number;+ z: number;+}++function quatToEuler(q: Quat): EulerAngles {+ const { x, y, z, w } = q;++ const sinrCosp = 2 * (w * x + y * z);+ const cosrCosp = 1 - 2 * (x * x + y * y);+ const roll = Math.atan2(sinrCosp, cosrCosp);++ const sinp = 2 * (w * y - z * x);+ let pitch: number;+ if (Math.abs(sinp) >= 1) {+ pitch = Math.sign(sinp) * Math.PI / 2;+ } else {+ pitch = Math.asin(sinp);+ }++ const sinyCosp = 2 * (w * z + x * y);+ const cosyCosp = 1 - 2 * (y * y + z * z);+ const yaw = Math.atan2(sinyCosp, cosyCosp);++ const toDeg = 180 / Math.PI;+ return {+ x: roll * toDeg,+ y: pitch * toDeg,+ z: yaw * toDeg,+ };+}++function eulerToQuat(euler: EulerAngles): Quat {+ const toRad = Math.PI / 180;+ const roll = euler.x * toRad;+ const pitch = euler.y * toRad;+ const yaw = euler.z * toRad;++ const cr = Math.cos(roll * 0.5);+ const sr = Math.sin(roll * 0.5);+ const cp = Math.cos(pitch * 0.5);+ const sp = Math.sin(pitch * 0.5);+ const cy = Math.cos(yaw * 0.5);+ const sy = Math.sin(yaw * 0.5);++ return {+ w: cr * cp * cy + sr * sp * sy,+ x: sr * cp * cy - cr * sp * sy,+ y: cr * sp * cy + sr * cp * sy,+ z: cr * cp * sy - sr * sp * cy,+ };+}++export function createEulerEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, onChange } = ctx;+ const quat = (value as Quat) ?? { x: 0, y: 0, z: 0, w: 1 };+ let currentEuler = quatToEuler(quat);++ const wrapper = document.createElement('div');+ wrapper.className = 'es-vec-editor es-vec3-editor';++ const inputs: HTMLInputElement[] = [];+ const labelTexts = ['X', 'Y', 'Z'];+ const keys: (keyof EulerAngles)[] = ['x', 'y', 'z'];+ const colorClasses = ['es-vec-x', 'es-vec-y', 'es-vec-z'];++ labelTexts.forEach((labelText, i) => {+ const group = document.createElement('div');+ group.className = `es-vec-field ${colorClasses[i]}`;++ const label = document.createElement('span');+ label.className = 'es-vec-label';+ label.textContent = labelText;++ const input = document.createElement('input');+ input.type = 'number';+ input.className = 'es-input es-input-number';+ input.step = '0.1';+ input.value = currentEuler[keys[i]].toFixed(1);++ input.addEventListener('change', () => {+ currentEuler = { ...currentEuler, [keys[i]]: parseFloat(input.value) || 0 };+ onChange(eulerToQuat(currentEuler));+ });++ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ input.blur();+ currentEuler = { ...currentEuler, [keys[i]]: parseFloat(input.value) || 0 };+ onChange(eulerToQuat(currentEuler));+ }+ });++ setupDragLabel(label, input, (newValue) => {+ currentEuler = { ...currentEuler, [keys[i]]: newValue };+ onChange(eulerToQuat(currentEuler));+ }, 1);++ group.appendChild(label);+ group.appendChild(input);+ wrapper.appendChild(group);+ inputs.push(input);+ });++ container.appendChild(wrapper);++ return {+ update(v: unknown) {+ const q = (v as Quat) ?? { x: 0, y: 0, z: 0, w: 1 };+ currentEuler = quatToEuler(q);+ inputs[0].value = currentEuler.x.toFixed(1);+ inputs[1].value = currentEuler.y.toFixed(1);+ inputs[2].value = currentEuler.z.toFixed(1);+ },+ dispose() {+ wrapper.remove();+ },+ };+}diff --git a/editor/src/property/editors/fontEditor.ts b/editor/src/property/editors/fontEditor.tsnew file mode 100644index 000000000..3d8f48fcb--- /dev/null+++ b/editor/src/property/editors/fontEditor.ts@@ -0,0 +1,92 @@+import {+ type PropertyEditorContext,+ type PropertyEditorInstance,+} from '../PropertyEditor';++const AVAILABLE_FONTS = [+ 'Arial',+ 'Helvetica',+ 'Times New Roman',+ 'Georgia',+ 'Verdana',+ 'Tahoma',+ 'Trebuchet MS',+ 'Courier New',+ 'Lucida Console',+ 'Impact',+ 'Comic Sans MS',+ 'Microsoft YaHei',+ 'SimHei',+ 'SimSun',+ 'KaiTi',+ 'FangSong',+];++function getAvailableFonts(): string[] {+ const testString = 'mmmmmmmmmmlli';+ const testSize = '72px';+ const baseline = 'monospace';++ const canvas = document.createElement('canvas');+ const ctx = canvas.getContext('2d')!;+ ctx.font = `${testSize} ${baseline}`;+ const baselineWidth = ctx.measureText(testString).width;++ const available: string[] = [];+ for (const font of AVAILABLE_FONTS) {+ ctx.font = `${testSize} "${font}", ${baseline}`;+ const width = ctx.measureText(testString).width;+ if (width !== baselineWidth) {+ available.push(font);+ }+ }++ return available.length > 0 ? available : ['Arial', 'sans-serif'];+}++export function createFontEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, onChange } = ctx;++ const wrapper = document.createElement('div');+ wrapper.className = 'es-font-editor';++ const select = document.createElement('select');+ select.className = 'es-input es-input-select';++ const fonts = getAvailableFonts();+ const currentFont = String(value ?? 'Arial');++ if (!fonts.includes(currentFont)) {+ fonts.unshift(currentFont);+ }++ for (const font of fonts) {+ const option = document.createElement('option');+ option.value = font;+ option.textContent = font;+ option.style.fontFamily = font;+ if (font === currentFont) {+ option.selected = true;+ }+ select.appendChild(option);+ }++ select.addEventListener('change', () => {+ onChange(select.value);+ });++ wrapper.appendChild(select);+ container.appendChild(wrapper);++ return {+ update(v: unknown) {+ select.value = String(v ?? 'Arial');+ },+ dispose() {+ wrapper.remove();+ },+ };+}diff --git a/editor/src/property/editors/index.ts b/editor/src/property/editors/index.tsnew file mode 100644index 000000000..b179766d3--- /dev/null+++ b/editor/src/property/editors/index.ts@@ -0,0 +1,51 @@+import type { PropertyEditorFactory } from '../PropertyEditor';+import type { PluginRegistrar } from '../../container';+import { PROPERTY_EDITOR } from '../../container/tokens';+import { createUIRectEditor } from '../uiRectEditor';+import { createButtonTransitionEditor } from '../buttonTransitionEditor';++import { createNumberEditor } from './numberEditor';+import { createStringEditor } from './stringEditor';+import { createBooleanEditor } from './booleanEditor';+import { createVec2Editor, createVec3Editor, createVec4Editor, createPaddingEditor } from './vectorEditors';+import { createColorEditor } from './colorEditor';+import { createEulerEditor } from './eulerEditor';+import { createEnumEditor } from './enumEditor';+import { createTextureEditor } from './textureEditor';+import { createFontEditor } from './fontEditor';+import { createSpineFileEditor, createSpineAnimationEditor, createSpineSkinEditor } from './spineEditors';+import { createAssetFileEditor, ASSET_FILE_EDITORS } from './assetEditors';+import { createEntityEditor } from './entityEditor';+import { createVec2ArrayEditor, createStringArrayEditor } from './arrayEditors';+import { createCollisionLayerEditor } from './collisionLayerEditor';++export { getNativeFS, getProjectDir, getMimeType, navigateToAsset, handleAssetDrop, browseForAsset, BROWSE_ICON, CLEAR_ICON } from './assetEditors';++export function registerBuiltinEditors(registrar: PluginRegistrar): void {+ const registerPropertyEditor = (type: string, factory: PropertyEditorFactory) => registrar.provide(PROPERTY_EDITOR, type, factory);+ console.log('[PropertyEditor] registerBuiltinEditors called');+ registerPropertyEditor('number', createNumberEditor);+ registerPropertyEditor('string', createStringEditor);+ registerPropertyEditor('boolean', createBooleanEditor);+ registerPropertyEditor('vec2', createVec2Editor);+ registerPropertyEditor('vec3', createVec3Editor);+ registerPropertyEditor('vec4', createVec4Editor);+ registerPropertyEditor('padding', createPaddingEditor);+ registerPropertyEditor('color', createColorEditor);+ registerPropertyEditor('enum', createEnumEditor);+ registerPropertyEditor('euler', createEulerEditor);+ registerPropertyEditor('texture', createTextureEditor);+ registerPropertyEditor('font', createFontEditor);+ registerPropertyEditor('spine-file', createSpineFileEditor);+ registerPropertyEditor('spine-animation', createSpineAnimationEditor);+ registerPropertyEditor('spine-skin', createSpineSkinEditor);+ for (const [editorType, config] of Object.entries(ASSET_FILE_EDITORS)) {+ registerPropertyEditor(editorType, (container, ctx) => createAssetFileEditor(container, ctx, config));+ }+ registerPropertyEditor('uirect', createUIRectEditor);+ registerPropertyEditor('button-transition', createButtonTransitionEditor);+ registerPropertyEditor('entity', createEntityEditor);+ registerPropertyEditor('string-array', createStringArrayEditor);+ registerPropertyEditor('vec2-array', createVec2ArrayEditor);+ registerPropertyEditor('collision-layer', createCollisionLayerEditor);+}diff --git a/editor/src/property/editors/numberEditor.ts b/editor/src/property/editors/numberEditor.tsnew file mode 100644index 000000000..2b9d02855--- /dev/null+++ b/editor/src/property/editors/numberEditor.ts@@ -0,0 +1,67 @@+import {+ type PropertyEditorContext,+ type PropertyEditorInstance,+} from '../PropertyEditor';+import { setupDragLabel } from '../editorUtils';+import { validateNumber, showValidationError } from '../validation';++export function createNumberEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, meta, onChange } = ctx;++ const wrapper = document.createElement('div');+ wrapper.className = 'es-number-editor';++ const label = document.createElement('span');+ label.className = 'es-number-drag-label';+ label.innerHTML = '⋮⋮';+ label.title = 'Drag to adjust value';++ const input = document.createElement('input');+ input.type = 'number';+ input.className = 'es-input es-input-number';+ input.value = String(value ?? 0);++ if (meta.min !== undefined) input.min = String(meta.min);+ if (meta.max !== undefined) input.max = String(meta.max);+ if (meta.step !== undefined) input.step = String(meta.step);++ const step = meta.step ?? 1;++ const handleChange = () => {+ const result = validateNumber(input.value, meta);+ if (!result.valid) {+ showValidationError(input, result.error!);+ input.value = String(result.value);+ }+ onChange(result.value);+ };++ input.addEventListener('change', handleChange);++ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ input.blur();+ handleChange();+ }+ });++ setupDragLabel(label, input, (newValue) => {+ onChange(newValue);+ }, step);++ wrapper.appendChild(label);+ wrapper.appendChild(input);+ container.appendChild(wrapper);++ return {+ update(v: unknown) {+ input.value = String(v ?? 0);+ },+ dispose() {+ wrapper.remove();+ },+ };+}diff --git a/editor/src/property/editors/spineEditors.ts b/editor/src/property/editors/spineEditors.tsnew file mode 100644index 000000000..0c9836265--- /dev/null+++ b/editor/src/property/editors/spineEditors.ts@@ -0,0 +1,331 @@+import {+ type PropertyEditorContext,+ type PropertyEditorInstance,+} from '../PropertyEditor';+import { getEditorStore } from '../../store/EditorStore';+import { getSpineService } from '../../services';+import { getAssetTypeEntry } from 'esengine';+import {+ getNativeFS,+ getProjectDir,+ resolveDisplayName,+ resolveToPath,+ checkAssetMissing,+ browseForAsset,+ BROWSE_ICON,+ CLEAR_ICON,+} from './assetEditors';++interface SpineSkeletonData {+ animations?: Record<string, unknown>;+ skins?: Array<{ name: string }> | Record<string, unknown>;+}++async function loadSpineSkeletonData(skeletonPath: string, atlasPath?: string): Promise<SpineSkeletonData | null> {+ if (!skeletonPath) return null;++ const spineService = getSpineService();+ const store = getEditorStore();+ {+ const entityId = store.selectedEntity as number | null;+ if (entityId !== null) {+ const info = spineService.getSpineSkeletonInfo(entityId);+ if (info) {+ const animRecord: Record<string, unknown> = {};+ for (const name of info.animations) {+ animRecord[name] = {};+ }+ return {+ animations: animRecord,+ skins: info.skins.map(name => ({ name })),+ };+ }+ }+ }++ if (getAssetTypeEntry(skeletonPath)?.contentType === 'binary') {+ return null;+ }++ const projectDir = getProjectDir();+ const fs = getNativeFS();+ if (!projectDir || !fs) return null;++ const jsonPath = `${projectDir}/${skeletonPath}`;+ try {+ const content = await fs.readFile(jsonPath);+ if (!content) return null;+ return JSON.parse(content) as SpineSkeletonData;+ } catch {+ return null;+ }+}++function getAnimationNames(data: SpineSkeletonData): string[] {+ if (!data.animations) return [];+ return Object.keys(data.animations);+}++function getSkinNames(data: SpineSkeletonData): string[] {+ if (!data.skins) return [];+ if (Array.isArray(data.skins)) {+ return data.skins.map(s => s.name);+ }+ return Object.keys(data.skins);+}++export function createSpineFileEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, meta, onChange } = ctx;+ const fileFilter = meta.fileFilter ?? ['.json', '.skel'];++ const wrapper = document.createElement('div');+ wrapper.className = 'es-file-editor';++ const input = document.createElement('input');+ input.type = 'text';+ input.className = 'es-input es-input-file';+ input.value = resolveDisplayName(String(value ?? ''));+ input.placeholder = 'None';+ checkAssetMissing(String(value ?? ''), input);++ const browseBtn = document.createElement('button');+ browseBtn.className = 'es-btn es-btn-icon es-btn-browse';+ browseBtn.title = 'Browse';+ browseBtn.innerHTML = BROWSE_ICON;++ const clearBtn = document.createElement('button');+ clearBtn.className = 'es-btn es-btn-icon es-btn-clear';+ clearBtn.title = 'Clear';+ clearBtn.innerHTML = CLEAR_ICON;++ input.addEventListener('change', () => {+ onChange(input.value || '');+ });++ browseBtn.addEventListener('click', async () => {+ const extensions = fileFilter.map((f: string) => f.replace('.', ''));+ const result = await browseForAsset('Select File', 'Spine Files', extensions);+ if (result) {+ input.value = result.relativePath;+ onChange(result.ref);+ }+ });++ clearBtn.addEventListener('click', () => {+ input.value = '';+ onChange('');+ });++ wrapper.appendChild(input);+ wrapper.appendChild(browseBtn);+ wrapper.appendChild(clearBtn);+ container.appendChild(wrapper);++ return {+ update(v: unknown) {+ const ref = String(v ?? '');+ input.value = resolveDisplayName(ref);+ checkAssetMissing(ref, input);+ },+ dispose() {+ wrapper.remove();+ },+ };+}++export function createSpineAnimationEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, onChange, getComponentValue } = ctx;++ const wrapper = document.createElement('div');+ wrapper.className = 'es-spine-animation-editor';++ const select = document.createElement('select');+ select.className = 'es-input es-input-select';++ const refreshBtn = document.createElement('button');+ refreshBtn.className = 'es-btn es-btn-icon es-btn-refresh';+ refreshBtn.title = 'Refresh animations';+ refreshBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 2v6h-6M3 12a9 9 0 0 1 15-6.7L21 8M3 22v-6h6M21 12a9 9 0 0 1-15 6.7L3 16"></path></svg>`;++ let currentAnimations: string[] = [];++ const updateOptions = (animations: string[], currentValue: string) => {+ select.innerHTML = '';++ const emptyOption = document.createElement('option');+ emptyOption.value = '';+ emptyOption.textContent = '(None)';+ select.appendChild(emptyOption);++ for (const anim of animations) {+ const option = document.createElement('option');+ option.value = anim;+ option.textContent = anim;+ if (anim === currentValue) {+ option.selected = true;+ }+ select.appendChild(option);+ }++ currentAnimations = animations;+ };++ const loadAnimations = async () => {+ const skeletonRef = getComponentValue?.('skeletonPath') as string;+ const skeletonPath = skeletonRef ? resolveToPath(skeletonRef) : '';+ if (!skeletonPath) {+ updateOptions([], String(value ?? ''));+ return;+ }++ const atlasRef = getComponentValue?.('atlasPath') as string;+ const atlasPath = atlasRef ? resolveToPath(atlasRef) : undefined;+ const data = await loadSpineSkeletonData(skeletonPath, atlasPath);+ if (data) {+ const animations = getAnimationNames(data);+ updateOptions(animations, String(value ?? ''));+ } else {+ updateOptions([], String(value ?? ''));+ }+ };++ const unsubSpineReady = getSpineService().onSpineInstanceReady((entityId: number) => {+ const selected = getEditorStore().selectedEntity as number | null;+ if (selected === entityId) {+ loadAnimations();+ }+ });++ select.addEventListener('change', () => {+ onChange(select.value);+ });++ refreshBtn.addEventListener('click', () => {+ loadAnimations();+ });++ wrapper.appendChild(select);+ wrapper.appendChild(refreshBtn);+ container.appendChild(wrapper);++ loadAnimations();++ return {+ update(v: unknown) {+ const newValue = String(v ?? '');+ if (currentAnimations.includes(newValue) || newValue === '') {+ select.value = newValue;+ } else {+ loadAnimations();+ }+ },+ dispose() {+ unsubSpineReady?.();+ wrapper.remove();+ },+ };+}++export function createSpineSkinEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, onChange, getComponentValue } = ctx;++ const wrapper = document.createElement('div');+ wrapper.className = 'es-spine-skin-editor';++ const select = document.createElement('select');+ select.className = 'es-input es-input-select';++ const refreshBtn = document.createElement('button');+ refreshBtn.className = 'es-btn es-btn-icon es-btn-refresh';+ refreshBtn.title = 'Refresh skins';+ refreshBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 2v6h-6M3 12a9 9 0 0 1 15-6.7L21 8M3 22v-6h6M21 12a9 9 0 0 1-15 6.7L3 16"></path></svg>`;++ let currentSkins: string[] = [];++ const updateOptions = (skins: string[], currentValue: string) => {+ select.innerHTML = '';++ for (const skin of skins) {+ const option = document.createElement('option');+ option.value = skin;+ option.textContent = skin;+ if (skin === currentValue) {+ option.selected = true;+ }+ select.appendChild(option);+ }++ if (skins.length === 0) {+ const defaultOption = document.createElement('option');+ defaultOption.value = 'default';+ defaultOption.textContent = 'default';+ select.appendChild(defaultOption);+ }++ currentSkins = skins;+ };++ const loadSkins = async () => {+ const skeletonRef = getComponentValue?.('skeletonPath') as string;+ const skeletonPath = skeletonRef ? resolveToPath(skeletonRef) : '';+ if (!skeletonPath) {+ updateOptions(['default'], String(value ?? 'default'));+ return;+ }++ const atlasRef = getComponentValue?.('atlasPath') as string;+ const atlasPath = atlasRef ? resolveToPath(atlasRef) : undefined;+ const data = await loadSpineSkeletonData(skeletonPath, atlasPath);+ if (data) {+ const skins = getSkinNames(data);+ updateOptions(skins.length > 0 ? skins : ['default'], String(value ?? 'default'));+ } else {+ updateOptions(['default'], String(value ?? 'default'));+ }+ };++ const unsubSpineReady = getSpineService().onSpineInstanceReady((entityId: number) => {+ const selected = getEditorStore().selectedEntity as number | null;+ if (selected === entityId) {+ loadSkins();+ }+ });++ select.addEventListener('change', () => {+ onChange(select.value);+ });++ refreshBtn.addEventListener('click', () => {+ loadSkins();+ });++ wrapper.appendChild(select);+ wrapper.appendChild(refreshBtn);+ container.appendChild(wrapper);++ loadSkins();++ return {+ update(v: unknown) {+ const newValue = String(v ?? 'default');+ if (currentSkins.includes(newValue)) {+ select.value = newValue;+ } else {+ loadSkins();+ }+ },+ dispose() {+ unsubSpineReady?.();+ wrapper.remove();+ },+ };+}diff --git a/editor/src/property/editors/stringEditor.ts b/editor/src/property/editors/stringEditor.tsnew file mode 100644index 000000000..89bad1441--- /dev/null+++ b/editor/src/property/editors/stringEditor.ts@@ -0,0 +1,30 @@+import {+ type PropertyEditorContext,+ type PropertyEditorInstance,+} from '../PropertyEditor';++export function createStringEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, onChange } = ctx;+ const input = document.createElement('input');+ input.type = 'text';+ input.className = 'es-input es-input-string';+ input.value = String(value ?? '');++ input.addEventListener('change', () => {+ onChange(input.value);+ });++ container.appendChild(input);++ return {+ update(v: unknown) {+ input.value = String(v ?? '');+ },+ dispose() {+ input.remove();+ },+ };+}diff --git a/editor/src/property/editors/textureEditor.ts b/editor/src/property/editors/textureEditor.tsnew file mode 100644index 000000000..bd51e15d1--- /dev/null+++ b/editor/src/property/editors/textureEditor.ts@@ -0,0 +1,161 @@+import {+ type PropertyEditorContext,+ type PropertyEditorInstance,+} from '../PropertyEditor';+import { getNavigationService } from '../../services';+import { INVALID_TEXTURE } from 'esengine';+import { AssetType } from '../../constants/AssetTypes';+import {+ getNativeFS,+ getProjectDir,+ getMimeType,+ resolveDisplayName,+ resolveToPath,+ checkAssetMissing,+ handleAssetDrop,+ browseForAsset,+ BROWSE_ICON,+ CLEAR_ICON,+} from './assetEditors';++export function createTextureEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, onChange } = ctx;+ let currentBlobUrl: string | null = null;+ let currentRef = '';+ let previewGeneration = 0;++ const wrapper = document.createElement('div');+ wrapper.className = 'es-texture-editor';++ const preview = document.createElement('div');+ preview.className = 'es-texture-preview';+ preview.title = 'Click to locate in Content Browser';++ const previewImg = document.createElement('img');+ previewImg.className = 'es-texture-preview-img';+ preview.appendChild(previewImg);++ const inputRow = document.createElement('div');+ inputRow.className = 'es-texture-input-row';++ const input = document.createElement('input');+ input.type = 'text';+ input.className = 'es-input es-input-texture es-asset-link';+ input.value = (value && typeof value === 'string' && value !== String(INVALID_TEXTURE)) ? resolveDisplayName(value) : '';+ input.placeholder = 'None';+ input.readOnly = true;++ const browseBtn = document.createElement('button');+ browseBtn.className = 'es-btn es-btn-icon es-btn-browse';+ browseBtn.title = 'Browse';+ browseBtn.innerHTML = BROWSE_ICON;++ const clearBtn = document.createElement('button');+ clearBtn.className = 'es-btn es-btn-icon es-btn-clear';+ clearBtn.title = 'Clear';+ clearBtn.innerHTML = CLEAR_ICON;++ const updatePreview = async (textureRef: string) => {+ const gen = ++previewGeneration;++ if (currentBlobUrl) {+ URL.revokeObjectURL(currentBlobUrl);+ currentBlobUrl = null;+ }++ const projectDir = getProjectDir();+ const fs = getNativeFS();+ const texturePath = resolveToPath(textureRef);++ if (texturePath && projectDir && fs) {+ const fullPath = `${projectDir}/${texturePath}`;+ try {+ const data = await fs.readBinaryFile(fullPath);+ if (gen !== previewGeneration) return;+ if (data) {+ const blob = new Blob([data.buffer as ArrayBuffer], { type: getMimeType(texturePath) });+ currentBlobUrl = URL.createObjectURL(blob);+ previewImg.src = currentBlobUrl;+ previewImg.style.display = 'block';+ preview.classList.add('es-has-preview');+ return;+ }+ } catch (err) {+ if (gen !== previewGeneration) return;+ console.warn('Failed to load texture preview:', err);+ }+ }++ previewImg.src = '';+ previewImg.style.display = 'none';+ preview.classList.remove('es-has-preview');+ };++ const navigateToAssetPath = async (e: Event) => {+ e.stopPropagation();+ const displayPath = input.value;+ if (!displayPath) return;++ await getNavigationService().navigateToAsset(displayPath);+ };++ currentRef = (value && typeof value === 'string' && value !== String(INVALID_TEXTURE)) ? value : '';+ updatePreview(currentRef);+ checkAssetMissing(currentRef, input);++ input.addEventListener('click', navigateToAssetPath);+ preview.addEventListener('click', navigateToAssetPath);++ handleAssetDrop(wrapper, [AssetType.IMAGE], (relativePath, ref) => {+ input.value = relativePath;+ currentRef = ref;+ onChange(ref);+ updatePreview(ref);+ });++ browseBtn.addEventListener('click', async () => {+ const result = await browseForAsset('Select Texture', 'Images', ['png', 'jpg', 'jpeg', 'webp']);+ if (result) {+ input.value = result.relativePath;+ currentRef = result.ref;+ onChange(result.ref);+ updatePreview(result.ref);+ }+ });++ clearBtn.addEventListener('click', () => {+ input.value = '';+ currentRef = '';+ onChange('');+ updatePreview('');+ });++ inputRow.appendChild(input);+ inputRow.appendChild(browseBtn);+ inputRow.appendChild(clearBtn);+ wrapper.appendChild(preview);+ wrapper.appendChild(inputRow);+ container.appendChild(wrapper);++ return {+ update(v: unknown) {+ const raw = (typeof v === 'string') ? v : '';+ const newValue = (!raw || raw === String(INVALID_TEXTURE)) ? '' : raw;+ input.value = newValue ? resolveDisplayName(newValue) : '';+ if (newValue !== currentRef) {+ currentRef = newValue;+ updatePreview(newValue);+ checkAssetMissing(newValue, input);+ }+ },+ dispose() {+ if (currentBlobUrl) {+ URL.revokeObjectURL(currentBlobUrl);+ }+ wrapper.remove();+ },+ };+}diff --git a/editor/src/property/editors/vectorEditors.ts b/editor/src/property/editors/vectorEditors.tsnew file mode 100644index 000000000..a791c4281--- /dev/null+++ b/editor/src/property/editors/vectorEditors.ts@@ -0,0 +1,315 @@+import {+ type PropertyEditorContext,+ type PropertyEditorInstance,+} from '../PropertyEditor';+import { setupDragLabel } from '../editorUtils';+import { validateVec2, validateVec3, showValidationError } from '../validation';++interface Vec2 {+ x: number;+ y: number;+}++export function createVec2Editor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, onChange } = ctx;+ let currentVec = (value as Vec2) ?? { x: 0, y: 0 };++ const wrapper = document.createElement('div');+ wrapper.className = 'es-vec-editor es-vec2-editor';++ const inputs: HTMLInputElement[] = [];+ const labelTexts = ['X', 'Y'];+ const colorClasses = ['es-vec-x', 'es-vec-y'];+ const keys: (keyof Vec2)[] = ['x', 'y'];++ labelTexts.forEach((labelText, i) => {+ const group = document.createElement('div');+ group.className = `es-vec-field ${colorClasses[i]}`;++ const label = document.createElement('span');+ label.className = 'es-vec-label';+ label.textContent = labelText;++ const input = document.createElement('input');+ input.type = 'number';+ input.className = 'es-input es-input-number';+ input.step = '0.01';+ input.value = String(currentVec[keys[i]]);++ const handleChange = () => {+ const updatedVec = { ...currentVec, [keys[i]]: parseFloat(input.value) || 0 };+ const result = validateVec2(updatedVec, ctx.meta);+ if (!result.valid) {+ showValidationError(input, result.error!);+ currentVec = result.value as Vec2;+ input.value = String(currentVec[keys[i]]);+ } else {+ currentVec = updatedVec;+ }+ onChange(currentVec);+ };++ input.addEventListener('change', handleChange);++ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ input.blur();+ handleChange();+ }+ });++ setupDragLabel(label, input, (newValue) => {+ currentVec = { ...currentVec, [keys[i]]: newValue };+ onChange(currentVec);+ });++ group.appendChild(label);+ group.appendChild(input);+ wrapper.appendChild(group);+ inputs.push(input);+ });++ container.appendChild(wrapper);++ return {+ update(v: unknown) {+ currentVec = (v as Vec2) ?? { x: 0, y: 0 };+ inputs[0].value = String(currentVec.x);+ inputs[1].value = String(currentVec.y);+ },+ dispose() {+ wrapper.remove();+ },+ };+}++interface Vec3 {+ x: number;+ y: number;+ z: number;+}++export function createVec3Editor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, onChange } = ctx;+ let currentVec = (value as Vec3) ?? { x: 0, y: 0, z: 0 };++ const wrapper = document.createElement('div');+ wrapper.className = 'es-vec-editor es-vec3-editor';++ const inputs: HTMLInputElement[] = [];+ const labelTexts = ['X', 'Y', 'Z'];+ const keys: (keyof Vec3)[] = ['x', 'y', 'z'];+ const colorClasses = ['es-vec-x', 'es-vec-y', 'es-vec-z'];++ labelTexts.forEach((labelText, i) => {+ const group = document.createElement('div');+ group.className = `es-vec-field ${colorClasses[i]}`;++ const label = document.createElement('span');+ label.className = 'es-vec-label';+ label.textContent = labelText;++ const input = document.createElement('input');+ input.type = 'number';+ input.className = 'es-input es-input-number';+ input.step = '0.01';+ input.value = String(currentVec[keys[i]]);++ const handleChange = () => {+ const updatedVec = { ...currentVec, [keys[i]]: parseFloat(input.value) || 0 };+ const result = validateVec3(updatedVec, ctx.meta);+ if (!result.valid) {+ showValidationError(input, result.error!);+ currentVec = result.value as Vec3;+ input.value = String(currentVec[keys[i]]);+ } else {+ currentVec = updatedVec;+ }+ onChange(currentVec);+ };++ input.addEventListener('change', handleChange);++ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ input.blur();+ handleChange();+ }+ });++ setupDragLabel(label, input, (newValue) => {+ currentVec = { ...currentVec, [keys[i]]: newValue };+ onChange(currentVec);+ });++ group.appendChild(label);+ group.appendChild(input);+ wrapper.appendChild(group);+ inputs.push(input);+ });++ container.appendChild(wrapper);++ return {+ update(v: unknown) {+ currentVec = (v as Vec3) ?? { x: 0, y: 0, z: 0 };+ inputs[0].value = String(currentVec.x);+ inputs[1].value = String(currentVec.y);+ inputs[2].value = String(currentVec.z);+ },+ dispose() {+ wrapper.remove();+ },+ };+}++interface Vec4 {+ x: number;+ y: number;+ z: number;+ w: number;+}++export function createVec4Editor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const { value, onChange } = ctx;+ let currentVec = (value as Vec4) ?? { x: 0, y: 0, z: 0, w: 1 };++ const wrapper = document.createElement('div');+ wrapper.className = 'es-vec-editor es-vec4-editor';++ const inputs: HTMLInputElement[] = [];+ const labelTexts = ['X', 'Y', 'Z', 'W'];+ const keys: (keyof Vec4)[] = ['x', 'y', 'z', 'w'];+ const colorClasses = ['es-vec-x', 'es-vec-y', 'es-vec-z', 'es-vec-w'];++ labelTexts.forEach((labelText, i) => {+ const group = document.createElement('div');+ group.className = `es-vec-field ${colorClasses[i]}`;++ const label = document.createElement('span');+ label.className = 'es-vec-label';+ label.textContent = labelText;++ const input = document.createElement('input');+ input.type = 'number';+ input.className = 'es-input es-input-number';+ input.step = '0.01';+ input.value = String(currentVec[keys[i]]);++ input.addEventListener('change', () => {+ currentVec = { ...currentVec, [keys[i]]: parseFloat(input.value) || 0 };+ onChange(currentVec);+ });++ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ input.blur();+ currentVec = { ...currentVec, [keys[i]]: parseFloat(input.value) || 0 };+ onChange(currentVec);+ }+ });++ setupDragLabel(label, input, (newValue) => {+ currentVec = { ...currentVec, [keys[i]]: newValue };+ onChange(currentVec);+ });++ group.appendChild(label);+ group.appendChild(input);+ wrapper.appendChild(group);+ inputs.push(input);+ });++ container.appendChild(wrapper);++ return {+ update(v: unknown) {+ currentVec = (v as Vec4) ?? { x: 0, y: 0, z: 0, w: 1 };+ inputs[0].value = String(currentVec.x);+ inputs[1].value = String(currentVec.y);+ inputs[2].value = String(currentVec.z);+ inputs[3].value = String(currentVec.w);+ },+ dispose() {+ wrapper.remove();+ },+ };+}++interface PaddingValue { left: number; top: number; right: number; bottom: number }++export function createPaddingEditor(+ container: HTMLElement,+ ctx: PropertyEditorContext+): PropertyEditorInstance {+ const wrapper = document.createElement('div');+ wrapper.className = 'vec-editor';++ const keys: (keyof PaddingValue)[] = ['left', 'top', 'right', 'bottom'];+ const labels = ['L', 'T', 'R', 'B'];+ let currentPad: PaddingValue = { left: 0, top: 0, right: 0, bottom: 0 };+ const inputs: HTMLInputElement[] = [];++ const onChange = (value: PaddingValue) => {+ ctx.onChange(value);+ };++ keys.forEach((key, i) => {+ const group = document.createElement('div');+ group.className = 'vec-component';+ const label = document.createElement('span');+ label.className = 'vec-label';+ label.textContent = labels[i];+ const input = document.createElement('input');+ input.type = 'number';+ input.className = 'property-input vec-input';+ input.value = String(currentPad[key]);++ input.addEventListener('change', () => {+ currentPad = { ...currentPad, [key]: parseFloat(input.value) || 0 };+ onChange(currentPad);+ });++ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ input.blur();+ currentPad = { ...currentPad, [key]: parseFloat(input.value) || 0 };+ onChange(currentPad);+ }+ });++ setupDragLabel(label, input, (newValue) => {+ currentPad = { ...currentPad, [key]: newValue };+ onChange(currentPad);+ });++ group.appendChild(label);+ group.appendChild(input);+ wrapper.appendChild(group);+ inputs.push(input);+ });++ container.appendChild(wrapper);++ return {+ update(v: unknown) {+ currentPad = (v as PaddingValue) ?? { left: 0, top: 0, right: 0, bottom: 0 };+ inputs[0].value = String(currentPad.left);+ inputs[1].value = String(currentPad.top);+ inputs[2].value = String(currentPad.right);+ inputs[3].value = String(currentPad.bottom);+ },+ dispose() {+ wrapper.remove();+ },+ };+}diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.tsindex 1e621757d..085cc2479 100644--- a/editor/src/schemas/ComponentSchemas.ts+++ b/editor/src/schemas/ComponentSchemas.ts@@ -33,6 +33,7 @@ export function inferPropertyType(value: unknown): string {'x' in value && 'y' in value && 'z' in value && !('w' in value)) return 'vec3';if (typeof value === 'object' && value !== null) {if ('r' in value && 'g' in value && 'b' in value && 'a' in value) return 'color';+ if ('left' in value && 'top' in value && 'right' in value && 'bottom' in value) return 'padding';if ('x' in value && 'y' in value && 'z' in value && 'w' in value) return 'vec4';}return 'string';diff --git a/editor/src/services/ClipboardService.ts b/editor/src/services/ClipboardService.tsnew file mode 100644index 000000000..7caa0ff5e--- /dev/null+++ b/editor/src/services/ClipboardService.ts@@ -0,0 +1,113 @@+import type { Entity } from 'esengine';+import type { EntityData } from '../types/SceneTypes';+import type { EditorStore } from '../store/EditorStore';+import { generateUniqueName } from '../utils/naming';++export class ClipboardService {+ private clipboard_: EntityData[] | null = null;+ private store_: EditorStore;++ constructor(store: EditorStore) {+ this.store_ = store;+ }++ duplicateSelected(): void {+ const selected = Array.from(this.store_.selectedEntities);+ if (selected.length === 0) return;++ for (const id of selected) {+ const entityData = this.store_.getEntityData(id);+ if (!entityData) continue;++ const scene = this.store_.scene;+ const siblings = scene.entities+ .filter(e => e.parent === entityData.parent)+ .map(e => e.name);+ const siblingNames = new Set(siblings);+ const newName = generateUniqueName(entityData.name, siblingNames);++ const newEntity = this.store_.createEntity(+ newName,+ entityData.parent as Entity | null+ );++ for (const comp of entityData.components) {+ this.store_.addComponent(newEntity, comp.type, JSON.parse(JSON.stringify(comp.data)));+ }+ }+ }++ copySelected(): void {+ const selected = Array.from(this.store_.selectedEntities);+ if (selected.length === 0) return;++ const allTrees: EntityData[] = [];+ for (const id of selected) {+ const tree = this.collectEntityTree_(id);+ allTrees.push(...tree);+ }+ if (allTrees.length === 0) return;++ this.clipboard_ = JSON.parse(JSON.stringify(allTrees));+ for (const e of this.clipboard_!) {+ delete e.prefab;+ }+ }++ pasteEntity(): void {+ if (!this.clipboard_ || this.clipboard_.length === 0) return;++ const cloned: EntityData[] = JSON.parse(JSON.stringify(this.clipboard_));+ const parent = this.store_.selectedEntity;+ const clipboardIds = new Set(cloned.map(e => e.id));+ const oldIdToNewId = new Map<number, Entity>();++ const scene = this.store_.scene;+ const siblings = scene.entities+ .filter(e => e.parent === (parent as number | null))+ .map(e => e.name);+ const siblingNames = new Set(siblings);++ let lastRoot: Entity | null = null;++ for (const entityData of cloned) {+ const isRoot = entityData.parent === null || !clipboardIds.has(entityData.parent);+ const newParent = isRoot ? parent : (oldIdToNewId.get(entityData.parent!) ?? null);+ if (!isRoot && newParent === null) continue;++ const name = isRoot+ ? generateUniqueName(entityData.name, siblingNames)+ : entityData.name;++ const newEntity = this.store_.createEntity(name, newParent);+ oldIdToNewId.set(entityData.id, newEntity);++ if (isRoot) {+ siblingNames.add(name);+ lastRoot = newEntity;+ }++ for (const comp of entityData.components) {+ this.store_.addComponent(newEntity, comp.type, { ...comp.data });+ }+ }++ if (lastRoot !== null) {+ this.store_.selectEntity(lastRoot);+ }+ }++ hasClipboard(): boolean {+ return this.clipboard_ !== null && this.clipboard_.length > 0;+ }++ private collectEntityTree_(entityId: number): EntityData[] {+ const entity = this.store_.getEntityData(entityId);+ if (!entity) return [];+ const result: EntityData[] = [entity];+ for (const childId of entity.children) {+ result.push(...this.collectEntityTree_(childId));+ }+ return result;+ }+}diff --git a/editor/src/services/ExtensionService.ts b/editor/src/services/ExtensionService.tsnew file mode 100644index 000000000..a0ff9fab2--- /dev/null+++ b/editor/src/services/ExtensionService.ts@@ -0,0 +1,161 @@+import * as esengine from 'esengine';+import {+ Draw, Geometry, Material, BlendMode, DataType, ShaderSources,+ PostProcess, Renderer, RenderStage,+ registerDrawCallback, unregisterDrawCallback, clearDrawCallbacks,+} from 'esengine';+import { ExtensionLoader } from '../extension';+import { setEditorAPI, clearEditorAPI } from '../extension/editorAPI';+import { showToast, showSuccessToast, showErrorToast } from '../ui/Toast';+import { showContextMenu } from '../ui/ContextMenu';+import { showConfirmDialog, showInputDialog } from '../ui/dialog';+import { getEditorInstance } from '../context/EditorContext';+import { getEditorStore } from '../store';+import { getSettingsValue, setSettingsValue } from '../settings';+import { icons } from '../utils/icons';+import {+ getEditorContainer,+ PANEL,+} from '../container';+import * as containerTokens from '../container/tokens';+import { getAllPanels } from '../panels/PanelRegistry';+import type { PanelManager } from '../PanelManager';+import type { MenuManager } from '../MenuManager';+import type { DockLayoutManager } from '../DockLayoutManager';++export class ExtensionService {+ private baseAPI_: Record<string, unknown> | null = null;+ private extensionLoader_: ExtensionLoader | null = null;+ private projectPath_: string | null;+ private panelManager_: PanelManager;+ private menuManager_: MenuManager;+ private container_: HTMLElement;+ private dockLayout_: DockLayoutManager | null = null;++ constructor(+ projectPath: string | null,+ panelManager: PanelManager,+ menuManager: MenuManager,+ container: HTMLElement,+ ) {+ this.projectPath_ = projectPath;+ this.panelManager_ = panelManager;+ this.menuManager_ = menuManager;+ this.container_ = container;+ }++ setDockLayout(dockLayout: DockLayoutManager | null): void {+ this.dockLayout_ = dockLayout;+ }++ setupEditorGlobals(): void {+ const container = getEditorContainer();+ const registrar = container as import('../container').PluginRegistrar;++ this.baseAPI_ = {+ ...esengine,+ registrar,+ tokens: containerTokens,+ icons,+ showToast,+ showSuccessToast,+ showErrorToast,+ showContextMenu,+ showConfirmDialog,+ showInputDialog,+ getEditorInstance,+ getEditorStore,+ getSettingsValue,+ setSettingsValue,+ Draw,+ Geometry,+ Material,+ BlendMode,+ DataType,+ ShaderSources,+ PostProcess,+ Renderer,+ RenderStage,+ registerDrawCallback,+ unregisterDrawCallback,+ clearDrawCallbacks,+ };+ setEditorAPI(this.baseAPI_);+ }++ async initialize(): Promise<void> {+ if (!this.projectPath_ || !this.baseAPI_) return;++ this.extensionLoader_ = new ExtensionLoader({+ projectPath: this.projectPath_,+ baseAPI: this.baseAPI_,+ onCompileError: (errors) => {+ console.error('Extension compilation errors:', errors);+ const msg = errors.map(e => `${e.file}:${e.line} - ${e.message}`).join('\n');+ showErrorToast(`Extension compile failed:\n${msg}`);+ },+ onCompileSuccess: () => {},+ onCleanup: () => this.cleanupExtensionUI_(),+ onAfterReload: () => this.applyExtensionUI_(),+ });++ try {+ await this.extensionLoader_.initialize();+ await this.extensionLoader_.reload();+ await this.extensionLoader_.watch();+ } catch (err) {+ console.error('Failed to initialize extensions:', err);+ }+ }++ private cleanupExtensionUI_(): void {+ const c = getEditorContainer();+ if (this.dockLayout_) {+ for (const [id] of this.panelManager_.panelInstances) {+ if (!c.isBuiltin(PANEL, id)) {+ this.dockLayout_.removePanel(id);+ }+ }+ }+ this.panelManager_.cleanupExtensionPanels();++ this.container_.querySelectorAll('[data-statusbar-id^="toggle-"]').forEach(el => {+ const panelId = el.getAttribute('data-statusbar-id')?.replace('toggle-', '');+ if (panelId && !c.isBuiltin(PANEL, panelId)) el.remove();+ });++ c.clearExtensions();+ }++ private applyExtensionUI_(): void {+ const c = getEditorContainer();+ if (this.dockLayout_) {+ for (const desc of getAllPanels()) {+ if (c.isBuiltin(PANEL, desc.id)) continue;+ this.dockLayout_.addPanel(desc);+ }+ }+ this.menuManager_.rebuildMenuBar(this.container_);+ }++ async reload(): Promise<boolean> {+ if (!this.extensionLoader_) {+ if (this.projectPath_) {+ await this.initialize();+ return true;+ }+ return false;+ }++ return this.extensionLoader_.reload();+ }++ clearAPI(): void {+ clearEditorAPI();+ }++ dispose(): void {+ this.extensionLoader_?.dispose();+ clearEditorAPI();+ }+}diff --git a/editor/src/services/MultiWindowService.ts b/editor/src/services/MultiWindowService.tsnew file mode 100644index 000000000..7514d4148--- /dev/null+++ b/editor/src/services/MultiWindowService.ts@@ -0,0 +1,79 @@+import { MainWindowBridge } from '../multiwindow/MainWindowBridge';+import { WindowManager } from '../multiwindow/WindowManager';+import type { EditorStore } from '../store/EditorStore';+import type { DockLayoutManager } from '../DockLayoutManager';+import type { OutputService } from './OutputService';+import type { ProfilerService } from './ProfilerService';++export class MultiWindowService {+ private mainWindowBridge_: MainWindowBridge | null = null;+ private windowManager_: WindowManager | null = null;+ private store_: EditorStore;+ private projectPath_: string | null;+ private closeUnlisten_: (() => void) | null = null;++ constructor(store: EditorStore, projectPath: string | null) {+ this.store_ = store;+ this.projectPath_ = projectPath;+ }++ get windowManager(): WindowManager | null {+ return this.windowManager_;+ }++ get mainWindowBridge(): MainWindowBridge | null {+ return this.mainWindowBridge_;+ }++ initialize(+ dockLayout: DockLayoutManager | null,+ outputService: OutputService,+ profilerService: ProfilerService,+ getPreviewUrl: () => Promise<string | null>,+ onUnsavedClose: () => Promise<void>,+ ): void {+ if (typeof window === 'undefined' || !('__TAURI_INTERNALS__' in window)) return;++ this.mainWindowBridge_ = new MainWindowBridge(this.store_);+ this.mainWindowBridge_.start();+ this.windowManager_ = new WindowManager();+ this.windowManager_.setProjectPath(this.projectPath_);++ outputService.setMainWindowBridge(this.mainWindowBridge_);+ profilerService.setWindowManager(this.windowManager_);++ if (dockLayout) {+ const bridge = this.mainWindowBridge_;+ dockLayout.setDetachContext({+ handler: this.windowManager_,+ getPreviewUrl,+ onPanelClosed: (cb) => bridge.onPanelClosed(cb),+ });+ }++ this.setupCloseHandler_(onUnsavedClose);+ }++ private setupCloseHandler_(onUnsavedClose: () => Promise<void>): void {+ import('@tauri-apps/api/window').then(async ({ getCurrentWindow }) => {+ const mainWindow = getCurrentWindow();+ this.closeUnlisten_ = await mainWindow.onCloseRequested(async (event) => {+ if (!this.store_.isDirty) return;+ event.preventDefault();+ try {+ await onUnsavedClose();+ } catch (e) {+ console.error('Close handler error:', e);+ }+ mainWindow.destroy();+ });+ });+ }++ dispose(): void {+ this.closeUnlisten_?.();+ this.closeUnlisten_ = null;+ this.windowManager_?.closeAll();+ this.mainWindowBridge_?.dispose();+ }+}diff --git a/editor/src/services/NavigationService.ts b/editor/src/services/NavigationService.tsnew file mode 100644index 000000000..d6ddbf638--- /dev/null+++ b/editor/src/services/NavigationService.ts@@ -0,0 +1,77 @@+import type { PanelManager } from '../PanelManager';+import type { DockLayoutManager } from '../DockLayoutManager';+import type { ContentDrawer } from '../ui/ContentDrawer';+import type { EditorAssetServer } from '../asset/EditorAssetServer';++export type NavigateToAssetHandler = (path: string) => Promise<void>;+export type AssetServerProvider = () => EditorAssetServer | null;++export class NavigationService {+ private panelManager_: PanelManager;+ private dockLayout_: DockLayoutManager | null = null;+ private contentDrawer_: ContentDrawer | null = null;+ private navigateHandler_: NavigateToAssetHandler | null = null;+ private assetServerProvider_: AssetServerProvider | null = null;++ constructor(panelManager: PanelManager) {+ this.panelManager_ = panelManager;+ }++ setDockLayout(dockLayout: DockLayoutManager | null): void {+ this.dockLayout_ = dockLayout;+ }++ setContentDrawer(contentDrawer: ContentDrawer | null): void {+ this.contentDrawer_ = contentDrawer;+ }++ registerNavigateToAsset(handler: NavigateToAssetHandler): () => void {+ this.navigateHandler_ = handler;+ return () => { this.navigateHandler_ = null; };+ }++ registerAssetServerProvider(provider: AssetServerProvider): () => void {+ this.assetServerProvider_ = provider;+ return () => { this.assetServerProvider_ = null; };+ }++ showPanel(id: string): void {+ if (id === 'content-browser') {+ this.contentDrawer_?.toggle();+ return;+ }+ this.dockLayout_?.showPanel(id);+ this.panelManager_.showPanel(id);+ }++ hidePanel(id: string): void {+ this.panelManager_.hidePanel(id);+ }++ togglePanel(id: string): void {+ if (id === 'content-browser') {+ this.contentDrawer_?.toggle();+ return;+ }+ const panel = this.dockLayout_?.api?.getPanel(id);+ if (panel) {+ this.dockLayout_!.removePanel(id);+ this.panelManager_.removePanelInstance(id);+ } else {+ this.showPanel(id);+ }+ }++ resetLayout(): void {+ this.contentDrawer_?.onResetLayout();+ this.dockLayout_?.resetLayout();+ }++ async navigateToAsset(assetPath: string): Promise<void> {+ await this.navigateHandler_?.(assetPath);+ }++ getAssetServer(): EditorAssetServer | null {+ return this.assetServerProvider_?.() ?? null;+ }+}diff --git a/editor/src/services/OutputService.ts b/editor/src/services/OutputService.tsnew file mode 100644index 000000000..372f789f2--- /dev/null+++ b/editor/src/services/OutputService.ts@@ -0,0 +1,75 @@+import type { MainWindowBridge } from '../multiwindow/MainWindowBridge';++export type OutputType = 'command' | 'stdout' | 'stderr' | 'error' | 'success';+export type OutputHandler = (text: string, type: OutputType) => void;++export class OutputService {+ private mainWindowBridge_: MainWindowBridge | null = null;+ private outputHandler_: OutputHandler | null = null;++ setMainWindowBridge(bridge: MainWindowBridge | null): void {+ this.mainWindowBridge_ = bridge;+ }++ registerOutputHandler(handler: OutputHandler): () => void {+ this.outputHandler_ = handler;+ return () => { this.outputHandler_ = null; };+ }++ appendOutput(text: string, type: OutputType): void {+ this.outputHandler_?.(text, type);+ this.mainWindowBridge_?.broadcastOutput(text, type);+ }++ installConsoleCapture(): void {+ const original = {+ log: console.log.bind(console),+ info: console.info.bind(console),+ warn: console.warn.bind(console),+ error: console.error.bind(console),+ };++ const formatArg = (a: unknown): string => {+ if (typeof a === 'string') return a;+ if (a instanceof Error) return `${a.name}: ${a.message}`;+ return JSON.stringify(a, null, 2) ?? String(a);+ };+ const formatArgs = (args: unknown[]) => args.map(formatArg).join(' ');++ const cleanStack = (raw: string | undefined): string => {+ if (!raw) return '';+ return raw.split('\n')+ .filter(line => {+ const t = line.trim();+ if (!t || t === 'Error') return false;+ if (t.includes('/editor/dist/')) return false;+ return true;+ })+ .map(line => line+ .replace(/https?:\/\/[^/]+\/@fs/g, '')+ .replace(/blob:https?:\/\/[^/]+\/[a-f0-9-]+/g, '<extension>')+ )+ .join('\n');+ };++ const INTERNAL_PREFIXES = [+ '[TAURI]', '[INFO]', 'File change:',+ ];++ const forward = (type: 'stdout' | 'stderr' | 'error', args: unknown[], stack?: string) => {+ const first = typeof args[0] === 'string' ? args[0] : '';+ if (INTERNAL_PREFIXES.some(p => first.startsWith(p))) return;++ let text = formatArgs(args);+ if (stack) {+ text += '\n' + stack;+ }+ this.appendOutput(text + '\n', type);+ };++ console.log = (...args) => { original.log(...args); forward('stdout', args); };+ console.info = (...args) => { original.info(...args); forward('stdout', args); };+ console.warn = (...args) => { original.warn(...args); forward('stderr', args, cleanStack(new Error().stack)); };+ console.error = (...args) => { original.error(...args); forward('error', args, cleanStack(new Error().stack)); };+ }+}diff --git a/editor/src/services/PlayModeService.ts b/editor/src/services/PlayModeService.tsindex 435ac3887..61f78b0b8 100644--- a/editor/src/services/PlayModeService.ts+++ b/editor/src/services/PlayModeService.ts@@ -5,7 +5,8 @@ import type { Entity, World } from 'esengine';import { getEditorStore, type SceneSnapshot } from '../store/EditorStore';import { getSharedRenderContext } from '../renderer/SharedRenderContext';import { ScriptInjector } from './ScriptInjector';-import { getEditorInstance, getEditorContext } from '../context/EditorContext';+import { getEditorContext } from '../context/EditorContext';+import { getScriptService } from './index';import { getAssetDatabase, isUUID } from '../asset';export interface EntityComponentData {@@ -270,10 +271,7 @@ export class PlayModeService {const app = ctx.app_;if (!app) return;- const editor = getEditorInstance();- if (!editor) return;-- const compiledCode = editor.getCompiledScripts();+ const compiledCode = getScriptService().getCompiledScripts();if (!compiledCode) return;this.scriptInjector_ = new ScriptInjector();diff --git a/editor/src/services/PluginManager.ts b/editor/src/services/PluginManager.tsnew file mode 100644index 000000000..01905785f--- /dev/null+++ b/editor/src/services/PluginManager.ts@@ -0,0 +1,33 @@+import type { EditorPlugin, EditorPluginContext } from '../plugins/EditorPlugin';++export class PluginManager {+ private plugins_: EditorPlugin[] = [];+ private pluginNames_ = new Set<string>();+ private context_: EditorPluginContext;++ constructor(context: EditorPluginContext) {+ this.context_ = context;+ }++ addPlugin(plugin: EditorPlugin): void {+ if (this.pluginNames_.has(plugin.name)) return;+ if (plugin.dependencies) {+ for (const dep of plugin.dependencies) {+ if (!this.pluginNames_.has(dep)) {+ throw new Error(`Plugin "${plugin.name}" requires "${dep}"`);+ }+ }+ }+ plugin.register(this.context_);+ this.plugins_.push(plugin);+ this.pluginNames_.add(plugin.name);+ }++ hasPlugin(name: string): boolean {+ return this.pluginNames_.has(name);+ }++ get plugins(): readonly EditorPlugin[] {+ return this.plugins_;+ }+}diff --git a/editor/src/services/PreviewService.ts b/editor/src/services/PreviewService.tsnew file mode 100644index 000000000..d837398b3--- /dev/null+++ b/editor/src/services/PreviewService.ts@@ -0,0 +1,104 @@+import { PreviewManager } from '../PreviewManager';+import { showToast } from '../ui/Toast';+import { hasFileHandle } from '../io/SceneSerializer';+import type { EditorStore } from '../store/EditorStore';+import type { ScriptService } from './ScriptService';+import type { SpineService } from './SpineService';++export class PreviewService {+ private previewManager_: PreviewManager;+ private previewUrl_: string | null = null;+ private store_: EditorStore;+ private scriptService_: ScriptService;+ private spineService_: SpineService;+ private container_: HTMLElement;+ private saveScene_: () => Promise<void>;++ constructor(+ projectPath: string | null,+ store: EditorStore,+ scriptService: ScriptService,+ spineService: SpineService,+ container: HTMLElement,+ saveScene: () => Promise<void>,+ ) {+ this.previewManager_ = new PreviewManager(projectPath);+ this.store_ = store;+ this.scriptService_ = scriptService;+ this.spineService_ = spineService;+ this.container_ = container;+ this.saveScene_ = saveScene;+ }++ get previewManager(): PreviewManager {+ return this.previewManager_;+ }++ async startPreview(): Promise<void> {+ if (this.store_.isDirty && this.store_.filePath && hasFileHandle()) {+ await this.saveScene_();+ showToast({ type: 'info', title: 'Scene saved before preview' });+ }+ const port = await this.previewManager_.startPreview(+ this.store_.scene, this.scriptService_.scriptLoader, this.spineService_.spineVersion,+ );+ if (port !== null) {+ this.previewUrl_ = `http://localhost:${port}`;+ this.updatePreviewUrl_();+ }+ }++ async startPreviewServer(): Promise<string | null> {+ if (this.store_.isDirty && this.store_.filePath && hasFileHandle()) {+ await this.saveScene_();+ }+ const port = await this.previewManager_.startServer(+ this.store_.scene, this.scriptService_.scriptLoader, this.spineService_.spineVersion,+ );+ if (port === null) return null;+ this.previewUrl_ = `http://localhost:${port}`;+ this.updatePreviewUrl_();+ return this.previewUrl_;+ }++ async stopPreviewServer(): Promise<void> {+ await this.previewManager_.stopPreview();+ this.previewUrl_ = null;+ this.updatePreviewUrl_();+ }++ togglePreviewStats(enabled: boolean): void {+ this.previewManager_.setShowStats(enabled);+ if (this.previewUrl_) {+ this.previewManager_.refreshFiles(+ this.store_.scene, this.scriptService_.scriptLoader, this.spineService_.spineVersion,+ );+ }+ }++ get previewStatsEnabled(): boolean {+ return this.previewManager_.showStats;+ }++ refreshFiles(): void {+ this.previewManager_.refreshFiles(+ this.store_.scene, this.scriptService_.scriptLoader, this.spineService_.spineVersion,+ );+ }++ private updatePreviewUrl_(): void {+ const urlEl = this.container_.querySelector('.es-preview-url') as HTMLElement;+ if (!urlEl) return;+ if (this.previewUrl_) {+ urlEl.textContent = this.previewUrl_;+ urlEl.dataset.url = this.previewUrl_;+ urlEl.style.display = '';+ } else {+ urlEl.style.display = 'none';+ }+ }++ dispose(): void {+ this.previewManager_.dispose();+ }+}diff --git a/editor/src/services/ProfilerService.ts b/editor/src/services/ProfilerService.tsnew file mode 100644index 000000000..965c33286--- /dev/null+++ b/editor/src/services/ProfilerService.ts@@ -0,0 +1,56 @@+import { getSharedRenderContext } from '../renderer/SharedRenderContext';+import { emit } from '@tauri-apps/api/event';+import { CHANNEL_PROFILER_STATS } from '../multiwindow/protocol';+import type { WindowManager } from '../multiwindow/WindowManager';++export class ProfilerService {+ private profilerActive_ = false;+ private windowManager_: WindowManager | null = null;++ setWindowManager(windowManager: WindowManager | null): void {+ this.windowManager_ = windowManager;+ }++ async showProfilerWindow(): Promise<void> {+ if (!this.windowManager_) return;++ await this.windowManager_.detachPanel('profiler', 'Profiler');+ this.startProfilerStats();+ }++ startProfilerStats(): void {+ if (this.profilerActive_) return;+ this.profilerActive_ = true;++ const ctx = getSharedRenderContext();+ ctx.setPostTickCallback(() => this.emitProfilerStats_());+ }++ stopProfilerStats(): void {+ if (!this.profilerActive_) return;+ this.profilerActive_ = false;++ const ctx = getSharedRenderContext();+ ctx.setPostTickCallback(null);+ }++ private emitProfilerStats_(): void {+ const ctx = getSharedRenderContext();+ const app = ctx.app_;++ const frameTimeMs = app?.getPhaseTimings()+ ? [...(app.getPhaseTimings() as Map<string, number>).values()].reduce((a: number, b: number) => a + b, 0)+ : 0;++ const phaseTimings: [string, number][] = app?.getPhaseTimings()+ ? [...(app.getPhaseTimings() as Map<string, number>).entries()]+ : [];++ const systemTimings: [string, number][] = app?.getSystemTimings()+ ? [...(app.getSystemTimings() as ReadonlyMap<string, number>).entries()]+ : [];++ const msg = { frameTimeMs, phaseTimings, systemTimings };+ emit(CHANNEL_PROFILER_STATS, msg);+ }+}diff --git a/editor/src/services/ProjectService.ts b/editor/src/services/ProjectService.tsnew file mode 100644index 000000000..ade99a4f6--- /dev/null+++ b/editor/src/services/ProjectService.ts@@ -0,0 +1,79 @@+import { showBuildSettingsDialog, BuildService } from '../builder';+import { showSettingsDialog, ProjectSettingsSync } from '../settings';+import { getEditorContext } from '../context/EditorContext';+import { getAssetLibrary } from '../asset/AssetLibrary';+import { getGlobalPathResolver } from '../asset';+import type { SpineService } from './SpineService';++export class ProjectService {+ private projectPath_: string | null;+ private settingsSync_: ProjectSettingsSync | null = null;+ private spineService_: SpineService;++ constructor(projectPath: string | null, spineService: SpineService) {+ this.projectPath_ = projectPath;+ this.spineService_ = spineService;+ }++ get projectPath(): string | null {+ return this.projectPath_;+ }++ async initializeAssetLibrary(): Promise<void> {+ console.log(`[Editor] initializeAssetLibrary: projectPath=${this.projectPath_}`);+ if (!this.projectPath_) {+ console.warn('[Editor] initializeAssetLibrary: no projectPath');+ return;+ }++ const fs = getEditorContext().fs;+ if (!fs) {+ console.warn('[Editor] initializeAssetLibrary: no fs in context');+ return;+ }++ const projectDir = this.projectPath_.replace(/[/\\][^/\\]+$/, '');+ try {+ await getAssetLibrary().initialize(projectDir, fs);+ } catch (err) {+ console.error('Failed to initialize AssetLibrary:', err);+ }+ }++ async initProjectSettingsSync(): Promise<void> {+ if (!this.projectPath_) return;+ this.settingsSync_ = new ProjectSettingsSync(+ this.projectPath_,+ (version) => this.spineService_.notifyVersionChange(version),+ );+ await this.settingsSync_.loadFromProject();+ this.settingsSync_.startAutoSync();+ }++ initializeProjectDir(): void {+ if (this.projectPath_) {+ const projectDir = this.projectPath_.replace(/[/\\][^/\\]+$/, '');+ getGlobalPathResolver().setProjectDir(projectDir);+ }+ }++ showBuildSettings(): void {+ if (!this.projectPath_) {+ alert('请先打开一个项目');+ return;+ }++ const buildService = new BuildService(this.projectPath_);+ showBuildSettingsDialog({+ projectPath: this.projectPath_,+ onBuild: async (config) => {+ return await buildService.build(config);+ },+ onClose: () => {},+ });+ }++ showSettings(): void {+ showSettingsDialog();+ }+}diff --git a/editor/src/services/RuntimeService.ts b/editor/src/services/RuntimeService.tsnew file mode 100644index 000000000..29bbd02c3--- /dev/null+++ b/editor/src/services/RuntimeService.ts@@ -0,0 +1,48 @@+import type { App } from 'esengine';+import { EditorBridge } from '../bridge/EditorBridge';+import type { EditorStore } from '../store/EditorStore';+import { getSharedRenderContext } from '../renderer/SharedRenderContext';++export type AppListener = (app: App, bridge: EditorBridge) => void;++export class RuntimeService {+ private app_: App | null = null;+ private bridge_: EditorBridge | null = null;+ private store_: EditorStore;+ private appListeners_: AppListener[] = [];++ constructor(store: EditorStore) {+ this.store_ = store;+ }++ get app(): App | null {+ return this.app_;+ }++ get bridge(): EditorBridge | null {+ return this.bridge_;+ }++ registerAppListener(listener: AppListener): () => void {+ this.appListeners_.push(listener);+ if (this.app_ && this.bridge_) {+ listener(this.app_, this.bridge_);+ }+ return () => {+ const idx = this.appListeners_.indexOf(listener);+ if (idx >= 0) this.appListeners_.splice(idx, 1);+ };+ }++ setApp(app: App): void {+ this.app_ = app;+ this.bridge_ = new EditorBridge(app, this.store_);+ for (const listener of this.appListeners_) {+ listener(app, this.bridge_!);+ }+ }++ setPhysicsFactory(factory: unknown): void {+ getSharedRenderContext().setPhysicsFactory(factory);+ }+}diff --git a/editor/src/services/SceneService.ts b/editor/src/services/SceneService.tsnew file mode 100644index 000000000..51ceadf7a--- /dev/null+++ b/editor/src/services/SceneService.ts@@ -0,0 +1,178 @@+import { saveSceneToFile, saveSceneToPath, loadSceneFromFile, loadSceneFromPath, hasFileHandle, clearFileHandle } from '../io/SceneSerializer';+import { isAbsolutePath, joinPath, getProjectDir } from '../utils/path';+import { getAssetLibrary } from '../asset/AssetLibrary';+import { getSettingsValue } from '../settings';+import { showDialog } from '../ui/dialog';+import { loadEditorLocalSettings, saveEditorLocalSetting } from '../launcher/ProjectService';+import type { EditorStore } from '../store/EditorStore';+import type { PreviewService } from './PreviewService';++export type DirtyPanelChecker = () => { isDirty: boolean; save: () => Promise<boolean> };++export class SceneService {+ private store_: EditorStore;+ private projectPath_: string | null;+ private previewService_!: PreviewService;+ private assetLibraryReady_: Promise<void> = Promise.resolve();+ private scriptsReady_: Promise<void> = Promise.resolve();+ private dirtyCheckers_: DirtyPanelChecker[] = [];++ constructor(store: EditorStore, projectPath: string | null) {+ this.store_ = store;+ this.projectPath_ = projectPath;+ }++ registerDirtyChecker(checker: DirtyPanelChecker): () => void {+ this.dirtyCheckers_.push(checker);+ return () => {+ const idx = this.dirtyCheckers_.indexOf(checker);+ if (idx >= 0) this.dirtyCheckers_.splice(idx, 1);+ };+ }++ private async saveDirtyPanels_(): Promise<void> {+ const promises: Promise<boolean>[] = [];+ for (const checker of this.dirtyCheckers_) {+ const { isDirty, save } = checker();+ if (isDirty) promises.push(save());+ }+ await Promise.all(promises);+ }++ setPreviewService(previewService: PreviewService): void {+ this.previewService_ = previewService;+ }++ setAssetLibraryReady(promise: Promise<void>): void {+ this.assetLibraryReady_ = promise;+ }++ setScriptsReady(promise: Promise<void>): void {+ this.scriptsReady_ = promise;+ }++ async newScene(): Promise<void> {+ if (this.store_.isDirty) {+ const result = await this.showUnsavedChangesPrompt_();+ if (result === 'cancel') return;+ if (result === 'save') await this.saveScene();+ }+ const w = getSettingsValue<number>('project.designWidth');+ const h = getSettingsValue<number>('project.designHeight');+ this.store_.newScene('Untitled', { width: w, height: h });+ clearFileHandle();+ }++ async saveScene(): Promise<void> {+ if (this.store_.isEditingPrefab) {+ await this.store_.savePrefabEditing();+ return;+ }++ await this.saveDirtyPanels_();++ const filePath = this.store_.filePath;++ if (filePath && hasFileHandle()) {+ const success = await saveSceneToPath(this.store_.scene, filePath);+ if (success) {+ this.store_.markSaved();+ this.previewService_.refreshFiles();+ return;+ }+ }++ const savedPath = await saveSceneToFile(this.store_.scene);+ if (savedPath) {+ this.store_.markSaved(savedPath);+ this.previewService_.refreshFiles();+ }+ }++ async saveSceneAs(): Promise<void> {+ clearFileHandle();+ const savedPath = await saveSceneToFile(this.store_.scene);+ if (savedPath) {+ this.store_.markSaved(savedPath);+ }+ }++ async loadScene(): Promise<void> {+ if (this.store_.isDirty) {+ const result = await this.showUnsavedChangesPrompt_();+ if (result === 'cancel') return;+ if (result === 'save') await this.saveScene();+ }+ await this.assetLibraryReady_;+ const scene = await loadSceneFromFile();+ if (scene) {+ await getAssetLibrary().migrateScene(scene);+ this.store_.loadScene(scene);+ }+ }++ async openSceneFromPath(scenePath: string): Promise<void> {+ if (this.store_.isEditingPrefab) {+ await this.store_.exitPrefabEditMode();+ }++ let resolvedPath = scenePath;+ if (!isAbsolutePath(scenePath) && this.projectPath_) {+ const projectDir = getProjectDir(this.projectPath_);+ resolvedPath = joinPath(projectDir, scenePath);+ }++ await this.assetLibraryReady_;+ const scene = await loadSceneFromPath(resolvedPath);+ if (scene) {+ const migrated = await getAssetLibrary().migrateScene(scene);+ if (migrated) {+ await saveSceneToPath(scene, resolvedPath);+ }+ this.store_.loadScene(scene, resolvedPath);+ this.saveLastOpenedScene_(scenePath);+ console.log('Scene loaded:', resolvedPath);+ }+ }++ async restoreLastScene(): Promise<void> {+ if (!this.projectPath_) return;+ await this.scriptsReady_;+ const settings = await loadEditorLocalSettings(this.projectPath_);+ const lastScene = settings?.lastOpenedScene as string | undefined;+ if (lastScene) {+ await this.openSceneFromPath(lastScene);+ }+ }++ async showUnsavedChangesPrompt_(): Promise<'save' | 'discard' | 'cancel'> {+ return new Promise((resolve) => {+ let resolved = false;+ showDialog({+ title: 'Unsaved Changes',+ content: 'You have unsaved changes. Save before continuing?',+ buttons: [+ { label: 'Cancel', role: 'cancel' },+ {+ label: "Don't Save", role: 'custom',+ onClick: () => { resolved = true; resolve('discard'); },+ },+ {+ label: 'Save', role: 'confirm', primary: true,+ onClick: () => { resolved = true; resolve('save'); },+ },+ ],+ closeOnEscape: true,+ }).then((result) => {+ if (!resolved) {+ resolve(result.action === 'confirm' ? 'save' : 'cancel');+ }+ });+ });+ }++ private saveLastOpenedScene_(scenePath: string): void {+ if (!this.projectPath_) return;+ saveEditorLocalSetting(this.projectPath_, 'lastOpenedScene', scenePath);+ }+}diff --git a/editor/src/services/ScriptService.ts b/editor/src/services/ScriptService.tsnew file mode 100644index 000000000..2fe121355--- /dev/null+++ b/editor/src/services/ScriptService.ts@@ -0,0 +1,67 @@+import { ScriptLoader } from '../scripting';+import { showErrorToast } from '../ui/Toast';+import type { OutputService } from './OutputService';+import type { EditorStore } from '../store/EditorStore';++export class ScriptService {+ private scriptLoader_: ScriptLoader | null = null;+ private projectPath_: string | null;+ private outputService_: OutputService;+ private store_: EditorStore;++ constructor(projectPath: string | null, outputService: OutputService, store: EditorStore) {+ this.projectPath_ = projectPath;+ this.outputService_ = outputService;+ this.store_ = store;+ }++ get scriptLoader(): ScriptLoader | null {+ return this.scriptLoader_;+ }++ async initialize(): Promise<void> {+ if (!this.projectPath_) return;++ this.scriptLoader_ = new ScriptLoader({+ projectPath: this.projectPath_,+ onCompileError: (errors) => {+ console.error('Script compilation errors:', errors);+ const msg = errors.map(e => `${e.file}:${e.line} - ${e.message}`).join('\n');+ showErrorToast('Script compile failed', msg);+ for (const e of errors) {+ this.outputService_.appendOutput(`${e.file}:${e.line}:${e.column} - ${e.message}`, 'error');+ }+ },+ onCompileSuccess: () => {+ this.store_.notifyChange();+ },+ });++ try {+ await this.scriptLoader_.initialize();+ await this.scriptLoader_.compile();+ await this.scriptLoader_.watch();+ } catch (err) {+ console.error('Failed to initialize scripts:', err);+ }+ }++ getCompiledScripts(): string | null {+ return this.scriptLoader_?.getCompiledCode() ?? null;+ }++ async reload(): Promise<boolean> {+ if (!this.scriptLoader_) {+ if (this.projectPath_) {+ await this.initialize();+ return true;+ }+ return false;+ }+ return this.scriptLoader_.reload();+ }++ dispose(): void {+ this.scriptLoader_?.dispose();+ }+}diff --git a/editor/src/services/ShellService.ts b/editor/src/services/ShellService.tsnew file mode 100644index 000000000..ae8ca314d--- /dev/null+++ b/editor/src/services/ShellService.ts@@ -0,0 +1,59 @@+import { getEditorContext } from '../context/EditorContext';+import type { OutputService } from './OutputService';++export class ShellService {+ private projectPath_: string | null;+ private outputService_: OutputService;+ private showPanel_: (id: string) => void;++ constructor(+ projectPath: string | null,+ outputService: OutputService,+ showPanel: (id: string) => void,+ ) {+ this.projectPath_ = projectPath;+ this.outputService_ = outputService;+ this.showPanel_ = showPanel;+ }++ executeCommand(fullCommand: string): void {+ this.executeShellCommand_(fullCommand);+ }++ private async executeShellCommand_(fullCommand: string): Promise<void> {+ if (!this.projectPath_) {+ this.outputService_.appendOutput('Error: No project loaded\n', 'error');+ return;+ }++ const shell = getEditorContext().shell;+ if (!shell) {+ this.outputService_.appendOutput('Error: Shell not available\n', 'error');+ return;+ }++ const projectDir = this.projectPath_.replace(/[/\\][^/\\]+$/, '');++ this.showPanel_('output');++ const parts = fullCommand.split(/\s+/);+ const cmd = parts[0];+ const args = parts.slice(1);++ this.outputService_.appendOutput(`> ${fullCommand}\n`, 'command');++ try {+ const result = await shell.execute(cmd, args, projectDir, (stream: string, data: string) => {+ this.outputService_.appendOutput(data + '\n', stream === 'stderr' ? 'stderr' : 'stdout');+ });++ if (result.code !== 0) {+ this.outputService_.appendOutput(`Process exited with code ${result.code}\n`, 'error');+ } else {+ this.outputService_.appendOutput(`Done.\n`, 'success');+ }+ } catch (err) {+ this.outputService_.appendOutput(`Error: ${err}\n`, 'error');+ }+ }+}diff --git a/editor/src/services/SpineService.ts b/editor/src/services/SpineService.tsnew file mode 100644index 000000000..3a4e0ba02--- /dev/null+++ b/editor/src/services/SpineService.ts@@ -0,0 +1,66 @@+import type { SpineWasmModule } from 'esengine/spine';+import { SpineModuleController, wrapSpineModule } from 'esengine/spine';+import type { EditorStore } from '../store/EditorStore';++export interface SpinePanelDelegate {+ setSpineController(ctrl: SpineModuleController | null): void;+ getSpineSkeletonInfo(entityId: number): { animations: string[]; skins: string[] } | null;+ onSpineInstanceReady(listener: (entityId: number) => void): () => void;+}++export class SpineService {+ private spineModule_: unknown = null;+ private spineVersion_: string = 'none';+ private spineVersionChangeHandler_: ((version: string) => void) | null = null;+ private store_: EditorStore;+ private delegate_: SpinePanelDelegate | null = null;++ constructor(store: EditorStore) {+ this.store_ = store;+ }++ registerSpinePanel(delegate: SpinePanelDelegate): () => void {+ this.delegate_ = delegate;+ if (this.spineModule_) {+ const raw = this.spineModule_ as SpineWasmModule;+ const controller = new SpineModuleController(raw, wrapSpineModule(raw));+ delegate.setSpineController(controller);+ }+ return () => { this.delegate_ = null; };+ }++ setSpineModule(module: unknown, version: string): void {+ this.spineModule_ = module;+ this.spineVersion_ = version;+ if (this.delegate_ && module) {+ const raw = module as SpineWasmModule;+ const controller = new SpineModuleController(raw, wrapSpineModule(raw));+ this.delegate_.setSpineController(controller);+ }+ this.store_.notifyChange();+ }++ onSpineVersionChange(handler: (version: string) => void): void {+ this.spineVersionChangeHandler_ = handler;+ }++ notifyVersionChange(version: string): void {+ this.spineVersionChangeHandler_?.(version);+ }++ get spineModule(): unknown {+ return this.spineModule_;+ }++ get spineVersion(): string {+ return this.spineVersion_;+ }++ getSpineSkeletonInfo(entityId: number): { animations: string[]; skins: string[] } | null {+ return this.delegate_?.getSpineSkeletonInfo(entityId) ?? null;+ }++ onSpineInstanceReady(listener: (entityId: number) => void): () => void {+ return this.delegate_?.onSpineInstanceReady(listener) ?? (() => {});+ }+}diff --git a/editor/src/services/index.ts b/editor/src/services/index.tsnew file mode 100644index 000000000..b986c9504--- /dev/null+++ b/editor/src/services/index.ts@@ -0,0 +1,111 @@+export { PlayModeService, getPlayModeService } from './PlayModeService';+export { RuntimeStoreProxy } from './RuntimeStoreProxy';+export { ScriptInjector } from './ScriptInjector';+export { OutputService } from './OutputService';+export { ClipboardService } from './ClipboardService';+export { ShellService } from './ShellService';+export { ProfilerService } from './ProfilerService';+export { NavigationService } from './NavigationService';+export { SpineService } from './SpineService';+export { RuntimeService } from './RuntimeService';+export { ScriptService } from './ScriptService';+export { ExtensionService } from './ExtensionService';+export { PreviewService } from './PreviewService';+export { SceneService } from './SceneService';+export { ProjectService } from './ProjectService';+export { MultiWindowService } from './MultiWindowService';+export { PluginManager } from './PluginManager';++import type { OutputService } from './OutputService';+import type { ClipboardService } from './ClipboardService';+import type { ShellService } from './ShellService';+import type { ProfilerService } from './ProfilerService';+import type { NavigationService } from './NavigationService';+import type { SpineService } from './SpineService';+import type { RuntimeService } from './RuntimeService';+import type { ScriptService } from './ScriptService';+import type { ExtensionService } from './ExtensionService';+import type { PreviewService } from './PreviewService';+import type { SceneService } from './SceneService';+import type { ProjectService } from './ProjectService';+import type { MultiWindowService } from './MultiWindowService';+import { getEditorContainer } from '../container/EditorContainer';+import {+ SCENE_SERVICE,+ CLIPBOARD_SERVICE,+ PREVIEW_SERVICE,+ SCRIPT_SERVICE,+ EXTENSION_SERVICE,+ SHELL_SERVICE,+ PROFILER_SERVICE,+ LAYOUT_SERVICE,+ NAVIGATION_SERVICE,+ OUTPUT_SERVICE,+ SPINE_SERVICE,+ RUNTIME_SERVICE,+ MULTI_WINDOW_SERVICE,+ PROJECT_SERVICE,+ PLUGIN_MANAGER,+} from '../container/tokens';++const SERVICE_KEY = 'default';++export function getSceneService(): SceneService {+ return getEditorContainer().get(SCENE_SERVICE, SERVICE_KEY)!;+}++export function getClipboardService(): ClipboardService {+ return getEditorContainer().get(CLIPBOARD_SERVICE, SERVICE_KEY)!;+}++export function getPreviewService(): PreviewService {+ return getEditorContainer().get(PREVIEW_SERVICE, SERVICE_KEY)!;+}++export function getScriptService(): ScriptService {+ return getEditorContainer().get(SCRIPT_SERVICE, SERVICE_KEY)!;+}++export function getExtensionService(): ExtensionService {+ return getEditorContainer().get(EXTENSION_SERVICE, SERVICE_KEY)!;+}++export function getShellService(): ShellService {+ return getEditorContainer().get(SHELL_SERVICE, SERVICE_KEY)!;+}++export function getProfilerService(): ProfilerService {+ return getEditorContainer().get(PROFILER_SERVICE, SERVICE_KEY)!;+}++export function getLayoutService() {+ return getEditorContainer().get(LAYOUT_SERVICE, SERVICE_KEY)!;+}++export function getNavigationService(): NavigationService {+ return getEditorContainer().get(NAVIGATION_SERVICE, SERVICE_KEY)!;+}++export function getOutputService(): OutputService {+ return getEditorContainer().get(OUTPUT_SERVICE, SERVICE_KEY)!;+}++export function getSpineService(): SpineService {+ return getEditorContainer().get(SPINE_SERVICE, SERVICE_KEY)!;+}++export function getRuntimeService(): RuntimeService {+ return getEditorContainer().get(RUNTIME_SERVICE, SERVICE_KEY)!;+}++export function getMultiWindowService(): MultiWindowService {+ return getEditorContainer().get(MULTI_WINDOW_SERVICE, SERVICE_KEY)!;+}++export function getProjectService(): ProjectService {+ return getEditorContainer().get(PROJECT_SERVICE, SERVICE_KEY)!;+}++export function getPluginManager() {+ return getEditorContainer().get(PLUGIN_MANAGER, SERVICE_KEY)!;+}