Skip to content

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.

feat: add editor extension loading system

esengine79008c48bfb2
diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs
index c04488164..de3e6f64c 100644
--- a/desktop/src-tauri/src/lib.rs
+++ b/desktop/src-tauri/src/lib.rs
@@ -20,6 +20,7 @@ const SDK_ESM_JS: &[u8] = include_bytes!("../../public/sdk/esm/esengine.js");
const SDK_ESM_DTS: &[u8] = include_bytes!("../../public/sdk/esm/esengine.d.ts");
const SDK_WASM_JS: &[u8] = include_bytes!("../../public/sdk/esm/wasm.js");
const SDK_WASM_DTS: &[u8] = include_bytes!("../../public/sdk/esm/wasm.d.ts");
+const EDITOR_DTS: &[u8] = include_bytes!("../../../editor/dist/index.d.ts");
// =============================================================================
// State
@@ -123,6 +124,11 @@ fn get_sdk_wasm_dts() -> Vec<u8> {
SDK_WASM_DTS.to_vec()
}
+#[tauri::command]
+fn get_editor_dts() -> Vec<u8> {
+ EDITOR_DTS.to_vec()
+}
+
#[derive(Clone, serde::Serialize)]
struct CommandOutput {
stream: String,
@@ -214,6 +220,7 @@ pub fn run() {
get_sdk_esm_dts,
get_sdk_wasm_js,
get_sdk_wasm_dts,
+ get_editor_dts,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
diff --git a/desktop/src/native-fs.ts b/desktop/src/native-fs.ts
index ba435049b..4bd8bce29 100644
--- a/desktop/src/native-fs.ts
+++ b/desktop/src/native-fs.ts
@@ -18,6 +18,7 @@ import {
import { invoke } from '@tauri-apps/api/core';
import { listen, type UnlistenFn } from '@tauri-apps/api/event';
import { resourceDir } from '@tauri-apps/api/path';
+import type { NativeShell } from '@esengine/editor';
export interface DirectoryEntry {
name: string;
@@ -70,301 +71,300 @@ export interface NativeFS {
getSdkEsmDts(): Promise<string>;
getSdkWasmJs(): Promise<string>;
getSdkWasmDts(): Promise<string>;
+ getEditorDts(): Promise<string>;
}
-export function injectNativeFS(): void {
- const nativeFS: NativeFS = {
- async saveFile(content: string, defaultPath?: string) {
- try {
- const path = await save({
- defaultPath,
- filters: [{ name: 'ESEngine Scene', extensions: ['esscene'] }],
- });
-
- if (path) {
- await writeTextFile(path, content);
- return path;
- }
- return null;
- } catch (err) {
- console.error('Failed to save file:', err);
- return null;
- }
- },
-
- async loadFile() {
- try {
- const path = await open({
- multiple: false,
- filters: [{ name: 'ESEngine Scene', extensions: ['esscene'] }],
- });
-
- if (path && typeof path === 'string') {
- const content = await readTextFile(path);
- return { path, content };
- }
- return null;
- } catch (err) {
- console.error('Failed to load file:', err);
- return null;
- }
- },
-
- async selectDirectory() {
- try {
- const path = await open({
- directory: true,
- multiple: false,
- });
- return typeof path === 'string' ? path : null;
- } catch (err) {
- console.error('Failed to select directory:', err);
- return null;
- }
- },
-
- async createDirectory(path: string) {
- try {
- await mkdir(path, { recursive: true });
- return true;
- } catch (err) {
- console.error('Failed to create directory:', err);
- return false;
- }
- },
-
- async exists(path: string) {
- try {
- return await exists(path);
- } catch {
- return false;
- }
- },
+export const nativeFS: NativeFS = {
+ async saveFile(content: string, defaultPath?: string) {
+ try {
+ const path = await save({
+ defaultPath,
+ filters: [{ name: 'ESEngine Scene', extensions: ['esscene'] }],
+ });
- async writeFile(path: string, content: string) {
- try {
+ if (path) {
await writeTextFile(path, content);
- return true;
- } catch (err) {
- console.error('Failed to write file:', err);
- return false;
- }
- },
-
- async writeBinaryFile(path: string, data: Uint8Array) {
- try {
- await writeFile(path, data);
- return true;
- } catch (err) {
- console.error('Failed to write binary file:', err);
- return false;
- }
- },
-
- async readFile(path: string) {
- try {
- return await readTextFile(path);
- } catch (err) {
- console.error('Failed to read file:', err);
- return null;
- }
- },
-
- async readBinaryFile(path: string) {
- try {
- return await readFile(path);
- } catch (err) {
- console.error('Failed to read binary file:', err);
- return null;
+ return path;
}
- },
-
- async copyFile(src: string, dest: string) {
- try {
- await copyFile(src, dest);
- return true;
- } catch (err) {
- console.error('Failed to copy file:', err);
- return false;
- }
- },
-
- async getFileStats(path: string) {
- try {
- const stats = await stat(path);
- return {
- size: stats.size,
- modified: stats.mtime,
- created: stats.birthtime,
- };
- } catch (err) {
- console.error('Failed to get file stats:', err);
- return null;
- }
- },
-
- async openProject() {
- try {
- const path = await open({
- multiple: false,
- filters: [{ name: 'ESEngine Project', extensions: ['esproject'] }],
- });
- return typeof path === 'string' ? path : null;
- } catch (err) {
- console.error('Failed to open project:', err);
- return null;
- }
- },
-
- async listDirectory(path: string) {
- try {
- const entries = await readDir(path);
- return entries.map(e => e.name);
- } catch {
- return [];
- }
- },
-
- async listDirectoryDetailed(path: string) {
- try {
- const entries = await readDir(path);
- return entries.map(e => ({
- name: e.name,
- isDirectory: e.isDirectory,
- isFile: e.isFile,
- }));
- } catch (err) {
- console.error('Failed to list directory:', err);
- return [];
- }
- },
-
- async watchDirectory(
- _path: string,
- _callback: (event: FileChangeEvent) => void,
- _options?: { recursive?: boolean }
- ) {
- // File watching not yet supported - use manual refresh
- return () => {};
- },
-
- async openFolder(path: string) {
- try {
- await invoke('open_folder', { path });
- return true;
- } catch (err) {
- console.error('Failed to open folder:', err);
- return false;
- }
- },
+ return null;
+ } catch (err) {
+ console.error('Failed to save file:', err);
+ return null;
+ }
+ },
+
+ async loadFile() {
+ try {
+ const path = await open({
+ multiple: false,
+ filters: [{ name: 'ESEngine Scene', extensions: ['esscene'] }],
+ });
- async getResourcePath() {
- try {
- return await resourceDir();
- } catch {
- return '';
+ if (path && typeof path === 'string') {
+ const content = await readTextFile(path);
+ return { path, content };
}
- },
-
- async getEngineJs() {
- const data = await invoke<number[]>('get_engine_js');
- return new TextDecoder().decode(new Uint8Array(data));
- },
-
- async getEngineWasm() {
- const data = await invoke<number[]>('get_engine_wasm');
- return new Uint8Array(data);
- },
-
- async getEngineSingleJs() {
- const data = await invoke<number[]>('get_engine_single_js');
- return new TextDecoder().decode(new Uint8Array(data));
- },
-
- async getEngineWxgameJs() {
- const data = await invoke<number[]>('get_engine_wxgame_js');
- return new TextDecoder().decode(new Uint8Array(data));
- },
-
- async getEngineWxgameWasm() {
- const data = await invoke<number[]>('get_engine_wxgame_wasm');
- return new Uint8Array(data);
- },
-
- async getSdkWechatJs() {
- const data = await invoke<number[]>('get_sdk_wechat_js');
- return new TextDecoder().decode(new Uint8Array(data));
- },
-
- async getSdkEsmJs() {
- const data = await invoke<number[]>('get_sdk_esm_js');
- return new TextDecoder().decode(new Uint8Array(data));
- },
-
- async getSdkEsmDts() {
- const data = await invoke<number[]>('get_sdk_esm_dts');
- return new TextDecoder().decode(new Uint8Array(data));
- },
-
- async getSdkWasmJs() {
- const data = await invoke<number[]>('get_sdk_wasm_js');
- return new TextDecoder().decode(new Uint8Array(data));
- },
-
- async getSdkWasmDts() {
- const data = await invoke<number[]>('get_sdk_wasm_dts');
- return new TextDecoder().decode(new Uint8Array(data));
- },
- };
-
- (window as any).__esengine_fs = nativeFS;
-
- const nativeShell = {
- async openFile(path: string): Promise<void> {
- await invoke('execute_command', {
- cmd: 'open',
- args: [path],
- cwd: '/',
+ return null;
+ } catch (err) {
+ console.error('Failed to load file:', err);
+ return null;
+ }
+ },
+
+ async selectDirectory() {
+ try {
+ const path = await open({
+ directory: true,
+ multiple: false,
});
- },
-
- async openInEditor(projectPath: string, filePath: string): Promise<void> {
- await invoke('execute_command', {
- cmd: 'open',
- args: ['-a', 'Visual Studio Code', projectPath, filePath],
- cwd: projectPath,
+ return typeof path === 'string' ? path : null;
+ } catch (err) {
+ console.error('Failed to select directory:', err);
+ return null;
+ }
+ },
+
+ async createDirectory(path: string) {
+ try {
+ await mkdir(path, { recursive: true });
+ return true;
+ } catch (err) {
+ console.error('Failed to create directory:', err);
+ return false;
+ }
+ },
+
+ async exists(path: string) {
+ try {
+ return await exists(path);
+ } catch {
+ return false;
+ }
+ },
+
+ async writeFile(path: string, content: string) {
+ try {
+ await writeTextFile(path, content);
+ return true;
+ } catch (err) {
+ console.error('Failed to write file:', err);
+ return false;
+ }
+ },
+
+ async writeBinaryFile(path: string, data: Uint8Array) {
+ try {
+ await writeFile(path, data);
+ return true;
+ } catch (err) {
+ console.error('Failed to write binary file:', err);
+ return false;
+ }
+ },
+
+ async readFile(path: string) {
+ try {
+ return await readTextFile(path);
+ } catch (err) {
+ console.error('Failed to read file:', err);
+ return null;
+ }
+ },
+
+ async readBinaryFile(path: string) {
+ try {
+ return await readFile(path);
+ } catch (err) {
+ console.error('Failed to read binary file:', err);
+ return null;
+ }
+ },
+
+ async copyFile(src: string, dest: string) {
+ try {
+ await copyFile(src, dest);
+ return true;
+ } catch (err) {
+ console.error('Failed to copy file:', err);
+ return false;
+ }
+ },
+
+ async getFileStats(path: string) {
+ try {
+ const stats = await stat(path);
+ return {
+ size: stats.size,
+ modified: stats.mtime,
+ created: stats.birthtime,
+ };
+ } catch (err) {
+ console.error('Failed to get file stats:', err);
+ return null;
+ }
+ },
+
+ async openProject() {
+ try {
+ const path = await open({
+ multiple: false,
+ filters: [{ name: 'ESEngine Project', extensions: ['esproject'] }],
});
- },
-
- async execute(
- cmd: string,
- args: string[],
- cwd: string,
- onOutput?: (stream: 'stdout' | 'stderr', data: string) => void
- ): Promise<{ code: number }> {
- let unlisten: UnlistenFn | null = null;
-
- try {
- if (onOutput) {
- unlisten = await listen<{ stream: string; data: string }>(
- 'command-output',
- (event) => {
- onOutput(event.payload.stream as 'stdout' | 'stderr', event.payload.data);
- }
- );
- }
-
- const result = await invoke<{ code: number }>('execute_command', { cmd, args, cwd });
- return result;
- } catch (err) {
- return { code: 1 };
- } finally {
- if (unlisten) {
- unlisten();
- }
+ return typeof path === 'string' ? path : null;
+ } catch (err) {
+ console.error('Failed to open project:', err);
+ return null;
+ }
+ },
+
+ async listDirectory(path: string) {
+ try {
+ const entries = await readDir(path);
+ return entries.map(e => e.name);
+ } catch {
+ return [];
+ }
+ },
+
+ async listDirectoryDetailed(path: string) {
+ try {
+ const entries = await readDir(path);
+ return entries.map(e => ({
+ name: e.name,
+ isDirectory: e.isDirectory,
+ isFile: e.isFile,
+ }));
+ } catch (err) {
+ console.error('Failed to list directory:', err);
+ return [];
+ }
+ },
+
+ async watchDirectory(
+ _path: string,
+ _callback: (event: FileChangeEvent) => void,
+ _options?: { recursive?: boolean }
+ ) {
+ return () => {};
+ },
+
+ async openFolder(path: string) {
+ try {
+ await invoke('open_folder', { path });
+ return true;
+ } catch (err) {
+ console.error('Failed to open folder:', err);
+ return false;
+ }
+ },
+
+ async getResourcePath() {
+ try {
+ return await resourceDir();
+ } catch {
+ return '';
+ }
+ },
+
+ async getEngineJs() {
+ const data = await invoke<number[]>('get_engine_js');
+ return new TextDecoder().decode(new Uint8Array(data));
+ },
+
+ async getEngineWasm() {
+ const data = await invoke<number[]>('get_engine_wasm');
+ return new Uint8Array(data);
+ },
+
+ async getEngineSingleJs() {
+ const data = await invoke<number[]>('get_engine_single_js');
+ return new TextDecoder().decode(new Uint8Array(data));
+ },
+
+ async getEngineWxgameJs() {
+ const data = await invoke<number[]>('get_engine_wxgame_js');
+ return new TextDecoder().decode(new Uint8Array(data));
+ },
+
+ async getEngineWxgameWasm() {
+ const data = await invoke<number[]>('get_engine_wxgame_wasm');
+ return new Uint8Array(data);
+ },
+
+ async getSdkWechatJs() {
+ const data = await invoke<number[]>('get_sdk_wechat_js');
+ return new TextDecoder().decode(new Uint8Array(data));
+ },
+
+ async getSdkEsmJs() {
+ const data = await invoke<number[]>('get_sdk_esm_js');
+ return new TextDecoder().decode(new Uint8Array(data));
+ },
+
+ async getSdkEsmDts() {
+ const data = await invoke<number[]>('get_sdk_esm_dts');
+ return new TextDecoder().decode(new Uint8Array(data));
+ },
+
+ async getSdkWasmJs() {
+ const data = await invoke<number[]>('get_sdk_wasm_js');
+ return new TextDecoder().decode(new Uint8Array(data));
+ },
+
+ async getSdkWasmDts() {
+ const data = await invoke<number[]>('get_sdk_wasm_dts');
+ return new TextDecoder().decode(new Uint8Array(data));
+ },
+
+ async getEditorDts() {
+ const data = await invoke<number[]>('get_editor_dts');
+ return new TextDecoder().decode(new Uint8Array(data));
+ },
+};
+
+export const nativeShell: NativeShell = {
+ async openFile(path: string): Promise<void> {
+ await invoke('execute_command', {
+ cmd: 'open',
+ args: [path],
+ cwd: '/',
+ });
+ },
+
+ async openInEditor(projectPath: string, filePath: string): Promise<void> {
+ await invoke('execute_command', {
+ cmd: 'open',
+ args: ['-a', 'Visual Studio Code', projectPath, filePath],
+ cwd: projectPath,
+ });
+ },
+
+ async execute(
+ cmd: string,
+ args: string[],
+ cwd: string,
+ onOutput?: (stream: 'stdout' | 'stderr', data: string) => void
+ ): Promise<{ code: number }> {
+ let unlisten: UnlistenFn | null = null;
+
+ try {
+ if (onOutput) {
+ unlisten = await listen<{ stream: string; data: string }>(
+ 'command-output',
+ (event) => {
+ onOutput(event.payload.stream as 'stdout' | 'stderr', event.payload.data);
+ }
+ );
}
- },
- };
- (window as any).__esengine_shell = nativeShell;
-}
+ const result = await invoke<{ code: number }>('execute_command', { cmd, args, cwd });
+ return result;
+ } catch (err) {
+ return { code: 1 };
+ } finally {
+ if (unlisten) {
+ unlisten();
+ }
+ }
+ },
+};
diff --git a/editor/src/Editor.ts b/editor/src/Editor.ts
index 16bffabd9..ff5899c36 100644
--- a/editor/src/Editor.ts
+++ b/editor/src/Editor.ts
@@ -6,20 +6,43 @@
import type { App, Entity } from 'esengine';
import { EditorStore } from './store/EditorStore';
import { EditorBridge } from './bridge/EditorBridge';
-import { HierarchyPanel } from './panels/HierarchyPanel';
-import { InspectorPanel } from './panels/InspectorPanel';
-import { SceneViewPanel } from './panels/SceneViewPanel';
-import { ContentBrowserPanel, type ContentBrowserOptions } from './panels/ContentBrowserPanel';
+import type { PanelInstance, PanelPosition } from './panels/PanelRegistry';
+import {
+ registerPanel,
+ getAllPanels,
+ getPanelsByPosition,
+ isResizable,
+ isBridgeAware,
+ isAppAware,
+ isAssetServerProvider,
+ isAssetNavigable,
+ isOutputAppendable,
+} from './panels/PanelRegistry';
+import { registerBuiltinPanels } from './panels/builtinPanels';
import { registerBuiltinEditors } from './property/editors';
import { registerMaterialEditors } from './property/materialEditors';
import { registerBuiltinSchemas } from './schemas/ComponentSchemas';
-import { initBoundsProviders } from './bounds';
+import { initBoundsProviders, registerBoundsProvider } from './bounds';
import { saveSceneToFile, saveSceneToPath, loadSceneFromFile, loadSceneFromPath, hasFileHandle, clearFileHandle } from './io/SceneSerializer';
import { icons } from './utils/icons';
import { ScriptLoader } from './scripting';
import { PreviewService } from './preview';
import { showBuildSettingsDialog, BuildService } from './builder';
import { getGlobalPathResolver } from './asset';
+import type { EditorAssetServer } from './asset/EditorAssetServer';
+import { setEditorInstance, getEditorContext, getEditorInstance } from './context/EditorContext';
+import { getAllMenus, getMenuItems, getAllStatusbarItems, registerBuiltinMenus } from './menus';
+import { ShortcutManager } from './menus/ShortcutManager';
+import { registerBuiltinGizmos, registerGizmo } from './gizmos';
+import { registerBuiltinStatusbarItems } from './menus/builtinStatusbar';
+import { ExtensionLoader } from './extension';
+import { registerMenu, registerMenuItem, registerStatusbarItem } from './menus/MenuRegistry';
+import { registerPropertyEditor } from './property';
+import { registerComponentSchema } from './schemas';
+import { showToast, showSuccessToast, showErrorToast } from './ui/Toast';
+import { showContextMenu } from './ui/ContextMenu';
+import { showConfirmDialog, showInputDialog } from './ui/dialog';
+import { getEditorStore } from './store';
// =============================================================================
// Types
@@ -40,29 +63,42 @@ export class Editor {
private bridge_: EditorBridge | null = null;
private projectPath_: string | null = null;
- private hierarchyPanel_: HierarchyPanel | null = null;
- private inspectorPanel_: InspectorPanel | null = null;
- private sceneViewPanel_: SceneViewPanel | null = null;
- private contentBrowserPanel_: ContentBrowserPanel | null = null;
+ private panelInstances_ = new Map<string, PanelInstance>();
+ private statusbarInstances_: Array<{ dispose(): void; update?(): void }> = [];
private scriptLoader_: ScriptLoader | null = null;
+ private extensionLoader_: ExtensionLoader | null = null;
private previewService_: PreviewService | null = null;
- private assetsPanelVisible_: boolean = true;
- private outputPanelVisible_: boolean = false;
+ private shortcutManager_: ShortcutManager;
+ private activeBottomPanelId_: string | null = 'content-browser';
constructor(container: HTMLElement, options?: EditorOptions) {
this.container_ = container;
this.store_ = new EditorStore();
this.projectPath_ = options?.projectPath ?? null;
+ this.shortcutManager_ = new ShortcutManager();
registerBuiltinEditors();
registerMaterialEditors();
registerBuiltinSchemas();
initBoundsProviders();
+ registerBuiltinGizmos();
+
+ registerBuiltinPanels({
+ projectPath: this.projectPath_ ?? undefined,
+ onOpenScene: (scenePath) => this.openSceneFromPath(scenePath),
+ });
this.setupLayout();
- this.setupKeyboardShortcuts();
+
+ registerBuiltinMenus(this);
+ registerBuiltinStatusbarItems(this);
+ this.instantiateStatusbar();
+ this.setupMenuShortcuts();
+ this.shortcutManager_.attach();
if (this.projectPath_) {
+ this.setupEditorGlobals();
+ this.initializeExtensions();
this.initializeScripts();
this.previewService_ = new PreviewService({ projectPath: this.projectPath_ });
}
@@ -76,13 +112,17 @@ export class Editor {
return this.store_.filePath;
}
+ get activeBottomPanelId(): string | null {
+ return this.activeBottomPanelId_;
+ }
+
setApp(app: App): void {
this.app_ = app;
this.bridge_ = new EditorBridge(app, this.store_);
- if (this.sceneViewPanel_) {
- this.sceneViewPanel_.setBridge(this.bridge_);
- this.sceneViewPanel_.setApp(app);
+ for (const panel of this.panelInstances_.values()) {
+ if (isBridgeAware(panel)) panel.setBridge(this.bridge_);
+ if (isAppAware(panel)) panel.setApp(app);
}
}
@@ -90,8 +130,38 @@ export class Editor {
return this.store_;
}
- get assetServer() {
- return this.sceneViewPanel_?.assetServer ?? null;
+ get assetServer(): EditorAssetServer | null {
+ for (const panel of this.panelInstances_.values()) {
+ if (isAssetServerProvider(panel)) return panel.assetServer as EditorAssetServer;
+ }
+ return null;
+ }
+
+ // =========================================================================
+ // Panel Operations
+ // =========================================================================
+
+ showPanel(id: string): void {
+ this.panelInstances_.get(id)?.onShow?.();
+ }
+
+ hidePanel(id: string): void {
+ this.panelInstances_.get(id)?.onHide?.();
+ }
+
+ togglePanel(id: string): void {
+ const panel = this.panelInstances_.get(id);
+ if (!panel) return;
+ panel.onShow?.();
+ }
+
+ toggleBottomPanel(id: string): void {
+ if (this.activeBottomPanelId_ === id) {
+ this.activeBottomPanelId_ = null;
+ } else {
+ this.activeBottomPanelId_ = id;
+ }
+ this.updateBottomPanelVisibility();
}
// =========================================================================
@@ -120,6 +190,14 @@ export class Editor {
}
}
+ async saveSceneAs(): Promise<void> {
+ clearFileHandle();
+ const savedPath = await saveSceneToFile(this.store_.scene);
+ if (savedPath) {
+ this.store_.markSaved(savedPath);
+ }
+ }
+
async loadScene(): Promise<void> {
const scene = await loadSceneFromFile();
if (scene) {
@@ -135,6 +213,72 @@ export class Editor {
}
}
+ duplicateSelected(): void {
+ const entity = this.store_.selectedEntity;
+ if (entity === null) return;
+
+ const entityData = this.store_.getEntityData(entity as number);
+ if (!entityData) return;
+
+ const newEntity = this.store_.createEntity(
+ `${entityData.name}_copy`,
+ entityData.parent as Entity | null
+ );
+
+ for (const comp of entityData.components) {
+ this.store_.addComponent(newEntity, comp.type, { ...comp.data });
+ }
+ }
+
+ 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 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">&times;</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 0.1.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;">
+ <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')?.addEventListener('click', close);
+ overlay.addEventListener('click', (e) => {
+ if (e.target === overlay) close();
+ });
+
+ document.body.appendChild(overlay);
+ }
+
// =========================================================================
// Script Operations
// =========================================================================
@@ -171,6 +315,143 @@ export class Editor {
return this.scriptLoader_.reload();
}
+ // =========================================================================
+ // Extension Operations
+ // =========================================================================
+
+ private setupEditorGlobals(): void {
+ (window as any).__ESENGINE_EDITOR__ = {
+ registerPanel,
+ registerMenuItem,
+ registerMenu,
+ registerGizmo,
+ registerStatusbarItem,
+ registerPropertyEditor,
+ registerComponentSchema,
+ registerBoundsProvider,
+ icons,
+ showToast,
+ showSuccessToast,
+ showErrorToast,
+ showContextMenu,
+ showConfirmDialog,
+ showInputDialog,
+ getEditorInstance,
+ getEditorStore,
+ };
+ }
+
+ private async initializeExtensions(): Promise<void> {
+ if (!this.projectPath_) return;
+
+ this.extensionLoader_ = new ExtensionLoader({
+ projectPath: this.projectPath_,
+ onCompileError: (errors) => {
+ console.error('Extension compilation errors:', errors);
+ },
+ onCompileSuccess: () => {
+ console.log('Extensions compiled successfully');
+ },
+ });
+
+ try {
+ await this.extensionLoader_.initialize();
+ const compiled = await this.extensionLoader_.compile();
+ if (compiled) {
+ await this.extensionLoader_.execute();
+ this.instantiateExtensionPanels();
+ }
+ } catch (err) {
+ console.error('Failed to initialize extensions:', err);
+ }
+ }
+
+ private instantiateExtensionPanels(): void {
+ for (const desc of getAllPanels()) {
+ if (this.panelInstances_.has(desc.id)) continue;
+
+ const position = desc.position ?? 'bottom';
+ let parentEl: HTMLElement | null = null;
+
+ if (position === 'bottom') {
+ parentEl = this.container_.querySelector('.es-editor-bottom');
+ } else {
+ parentEl = this.container_.querySelector(`.es-editor-${position}`);
+ }
+ if (!parentEl) continue;
+
+ const container = document.createElement('div');
+ container.className = 'es-panel-container';
+ container.dataset.panelId = desc.id;
+
+ if (position === 'bottom') {
+ container.style.display = 'none';
+ }
+
+ parentEl.appendChild(container);
+ const instance = desc.factory(container, this.store_);
+ this.panelInstances_.set(desc.id, instance);
+
+ if (this.bridge_ && isBridgeAware(instance)) instance.setBridge(this.bridge_);
+ if (this.app_ && isAppAware(instance)) instance.setApp(this.app_);
+ }
+
+ this.refreshBottomPanelStatusbar();
+ }
+
+ private refreshBottomPanelStatusbar(): void {
+ const leftContainer = this.container_.querySelector('.es-statusbar-left');
+ if (!leftContainer) return;
+
+ const bottomPanels = getPanelsByPosition('bottom');
+ for (const panel of bottomPanels) {
+ const existing = leftContainer.querySelector(`[data-statusbar-id="toggle-${panel.id}"]`);
+ if (existing) continue;
+
+ const cmdWrapper = leftContainer.querySelector('.es-statusbar-cmd-wrapper');
+
+ const span = document.createElement('span');
+ span.dataset.statusbarId = `toggle-${panel.id}`;
+
+ const btn = document.createElement('button');
+ btn.className = 'es-statusbar-btn';
+ btn.dataset.bottomPanel = panel.id;
+ btn.innerHTML = `${panel.icon ?? ''}<span>${panel.title}</span>`;
+ btn.addEventListener('click', () => this.toggleBottomPanel(panel.id));
+ span.appendChild(btn);
+
+ if (cmdWrapper) {
+ leftContainer.insertBefore(span, cmdWrapper);
+ } else {
+ leftContainer.appendChild(span);
+ }
+
+ this.statusbarInstances_.push({
+ dispose() { span.remove(); },
+ update: () => {
+ const isActive = this.activeBottomPanelId_ === panel.id;
+ btn.classList.toggle('es-active', isActive);
+ },
+ });
+ }
+ }
+
+ async reloadExtensions(): Promise<boolean> {
+ if (!this.extensionLoader_) {
+ if (this.projectPath_) {
+ await this.initializeExtensions();
+ return true;
+ }
+ return false;
+ }
+
+ const success = await this.extensionLoader_.reload();
+ if (success) {
+ this.instantiateExtensionPanels();
+ }
+ return success;
+ }
+
// =========================================================================
// Preview Operations
// =========================================================================
@@ -194,13 +475,69 @@ export class Editor {
}
async navigateToAsset(assetPath: string): Promise<void> {
- if (this.contentBrowserPanel_) {
- await this.contentBrowserPanel_.navigateToAsset(assetPath);
+ for (const panel of this.panelInstances_.values()) {
+ if (isAssetNavigable(panel)) {
+ await panel.navigateToAsset(assetPath);
+ return;
+ }
}
}
// =========================================================================
- // Private Methods
+ // 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.activeBottomPanelId_ = 'output';
+ this.updateBottomPanelVisibility();
+
+ 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 appendOutput(text: string, type: 'command' | 'stdout' | 'stderr' | 'error' | 'success'): void {
+ const outputPanel = this.panelInstances_.get('output');
+ if (outputPanel && isOutputAppendable(outputPanel)) {
+ outputPanel.appendOutput(text, type);
+ }
+ }
+
+ // =========================================================================
+ // Layout
// =========================================================================
private setupLayout(): void {
@@ -208,183 +545,25 @@ export class Editor {
this.container_.innerHTML = `
<div class="es-editor-menubar">
<div class="es-menubar-logo">${icons.logo(24)}</div>
- <div class="es-menu" data-menu="file">
- <div class="es-menu-trigger">File</div>
- <div class="es-menu-dropdown">
- <div class="es-menu-item" data-action="new">
- <span class="es-menu-item-text">New Scene</span>
- <span class="es-menu-item-shortcut">Ctrl+N</span>
- </div>
- <div class="es-menu-item" data-action="open">
- <span class="es-menu-item-text">Open...</span>
- <span class="es-menu-item-shortcut">Ctrl+O</span>
- </div>
- <div class="es-menu-divider"></div>
- <div class="es-menu-item" data-action="save">
- <span class="es-menu-item-text">Save</span>
- <span class="es-menu-item-shortcut">Ctrl+S</span>
- </div>
- <div class="es-menu-item" data-action="save-as">
- <span class="es-menu-item-text">Save As...</span>
- <span class="es-menu-item-shortcut">Ctrl+Shift+S</span>
- </div>
- <div class="es-menu-divider"></div>
- <div class="es-menu-item" data-action="build-settings">
- <span class="es-menu-item-text">Build Settings...</span>
- <span class="es-menu-item-shortcut">Ctrl+Shift+B</span>
- </div>
- </div>
- </div>
- <div class="es-menu" data-menu="edit">
- <div class="es-menu-trigger">Edit</div>
- <div class="es-menu-dropdown">
- <div class="es-menu-item" data-action="undo">
- <span class="es-menu-item-text">Undo</span>
- <span class="es-menu-item-shortcut">Ctrl+Z</span>
- </div>
- <div class="es-menu-item" data-action="redo">
- <span class="es-menu-item-text">Redo</span>
- <span class="es-menu-item-shortcut">Ctrl+Y</span>
- </div>
- <div class="es-menu-divider"></div>
- <div class="es-menu-item" data-action="delete">
- <span class="es-menu-item-text">Delete</span>
- <span class="es-menu-item-shortcut">Delete</span>
- </div>
- <div class="es-menu-item" data-action="duplicate">
- <span class="es-menu-item-text">Duplicate</span>
- <span class="es-menu-item-shortcut">Ctrl+D</span>
- </div>
- </div>
- </div>
- <div class="es-menu" data-menu="view">
- <div class="es-menu-trigger">View</div>
- <div class="es-menu-dropdown">
- <div class="es-menu-item" data-action="toggle-hierarchy">
- <span class="es-menu-item-text">Hierarchy</span>
- </div>
- <div class="es-menu-item" data-action="toggle-inspector">
- <span class="es-menu-item-text">Inspector</span>
- </div>
- <div class="es-menu-item" data-action="toggle-assets">
- <span class="es-menu-item-text">Content Browser</span>
- </div>
- <div class="es-menu-item" data-action="toggle-output">
- <span class="es-menu-item-text">Output</span>
- </div>
- </div>
- </div>
- <div class="es-menu" data-menu="help">
- <div class="es-menu-trigger">Help</div>
- <div class="es-menu-dropdown">
- <div class="es-menu-item" data-action="docs">
- <span class="es-menu-item-text">Documentation</span>
- </div>
- <div class="es-menu-divider"></div>
- <div class="es-menu-item" data-action="about">
- <span class="es-menu-item-text">About ESEngine</span>
- </div>
- </div>
- </div>
+ ${this.buildMenuBarHTML()}
<div class="es-menubar-spacer"></div>
<button class="es-btn es-btn-preview" data-action="preview">${icons.play(14)} Preview</button>
</div>
<div class="es-editor-tabs">
- <div class="es-tab es-tab-active" data-panel="hierarchy">
- <span class="es-tab-label">Hierarchy</span>
- <button class="es-tab-close">${icons.x(10)}</button>
- </div>
- <div class="es-tab es-tab-active" data-panel="scene">
- <span class="es-tab-label">Scene</span>
- <button class="es-tab-close">${icons.x(10)}</button>
- </div>
- <div class="es-tab es-tab-active" data-panel="inspector">
- <span class="es-tab-label">Inspector</span>
- <button class="es-tab-close">${icons.x(10)}</button>
- </div>
+ ${this.buildTabBarHTML()}
</div>
<div class="es-editor-body">
- <div class="es-editor-main">
- <div class="es-editor-left">
- <div class="es-hierarchy-container"></div>
- </div>
- <div class="es-editor-center">
- <div class="es-sceneview-container"></div>
- </div>
- <div class="es-editor-right">
- <div class="es-inspector-container"></div>
- </div>
- </div>
+ ${this.buildMainPanelsHTML()}
<div class="es-editor-bottom">
- <div class="es-content-browser-container"></div>
- <div class="es-output-container" style="display: none;">
- <div class="es-output-panel">
- <div class="es-output-header">
- <span class="es-output-title">${icons.list(14)} Output</span>
- <div class="es-output-actions">
- <button class="es-btn es-btn-icon" title="Clear">${icons.trash(12)}</button>
- </div>
- </div>
- <div class="es-output-content">
- <div class="es-output-empty">No output messages</div>
- </div>
- </div>
- </div>
- </div>
- </div>
- <div class="es-editor-statusbar">
- <div class="es-statusbar-left">
- <button class="es-statusbar-btn es-statusbar-btn-primary es-active" data-action="toggle-assets">
- ${icons.folder(12)}
- <span>Content Browser</span>
- ${icons.chevronDown(10)}
- </button>
- <button class="es-statusbar-btn" data-action="toggle-output">
- ${icons.list(12)}
- <span>Output</span>
- </button>
- <div class="es-statusbar-divider"></div>
- <span class="es-cmd-prompt">&gt;</span>
- <input type="text" class="es-cmd-input" placeholder="pnpm install, npm run build..." />
- </div>
- <div class="es-statusbar-right">
- <button class="es-statusbar-btn" data-action="undo" title="Undo">
- <span>Undo</span>
- </button>
- <div class="es-statusbar-icons">
- <button title="Notifications">${icons.list(12)}</button>
- <button title="Extensions">${icons.grid(12)}</button>
- <button title="Settings">${icons.settings(12)}</button>
- </div>
- <span class="es-status-indicator es-status-saved">
- ${icons.check(12)}
- <span>All Saved</span>
- </span>
- <div class="es-statusbar-divider"></div>
- <span class="es-status-indicator">
- <span>Version Control</span>
- </span>
+ ${this.buildBottomPanelsHTML()}
</div>
</div>
+ ${this.buildStatusBarHTML()}
`;
- const hierarchyContainer = this.container_.querySelector('.es-hierarchy-container') as HTMLElement;
- const inspectorContainer = this.container_.querySelector('.es-inspector-container') as HTMLElement;
- const sceneViewContainer = this.container_.querySelector('.es-sceneview-container') as HTMLElement;
- const contentBrowserContainer = this.container_.querySelector('.es-content-browser-container') as HTMLElement;
+ this.instantiatePanels();
- this.hierarchyPanel_ = new HierarchyPanel(hierarchyContainer, this.store_);
- this.inspectorPanel_ = new InspectorPanel(inspectorContainer, this.store_);
- this.sceneViewPanel_ = new SceneViewPanel(sceneViewContainer, this.store_, {
- projectPath: this.projectPath_ ?? undefined,
- });
- this.contentBrowserPanel_ = new ContentBrowserPanel(contentBrowserContainer, this.store_, {
- projectPath: this.projectPath_ ?? undefined,
- onOpenScene: (scenePath) => this.openSceneFromPath(scenePath),
- });
-
- (window as any).__esengine_editor = this;
- (window as any).__esengine_projectPath = this.projectPath_;
+ setEditorInstance(this);
if (this.projectPath_) {
const projectDir = this.projectPath_.replace(/[/\\][^/\\]+$/, '');
@@ -392,11 +571,115 @@ export class Editor {
}
this.setupToolbarEvents();
- this.setupStatusbarEvents();
this.store_.subscribe(() => this.updateToolbarState());
this.store_.subscribe(() => this.updateStatusbar());
}
+ private buildTabBarHTML(): string {
+ const positions: PanelPosition[] = ['left', 'center', 'right'];
+ return positions.flatMap(pos => getPanelsByPosition(pos))
+ .filter(p => p.defaultVisible)
+ .map(p => `
+ <div class="es-tab es-tab-active" data-panel="${p.id}">
+ <span class="es-tab-label">${p.title}</span>
+ <button class="es-tab-close">${icons.x(10)}</button>
+ </div>
+ `).join('');
+ }
+
+ private buildMainPanelsHTML(): string {
+ const sections = (['left', 'center', 'right'] as const).map(pos => {
+ const panels = getPanelsByPosition(pos).filter(p => p.defaultVisible);
+ const containers = panels.map(p =>
+ `<div class="es-panel-container" data-panel-id="${p.id}"></div>`
+ ).join('');
+ return `<div class="es-editor-${pos}">${containers}</div>`;
+ }).join('');
+ return `<div class="es-editor-main">${sections}</div>`;
+ }
+
+ private buildBottomPanelsHTML(): string {
+ const panels = getPanelsByPosition('bottom');
+ return panels.map(p => {
+ const display = p.id === this.activeBottomPanelId_ ? '' : 'display: none;';
+ return `<div class="es-panel-container" data-panel-id="${p.id}" style="${display}"></div>`;
+ }).join('');
+ }
+
+ private buildStatusBarHTML(): string {
+ return `
+ <div class="es-editor-statusbar">
+ <div class="es-statusbar-left"></div>
+ <div class="es-statusbar-right"></div>
+ </div>
+ `;
+ }
+
+ private buildMenuBarHTML(): string {
+ const menus = getAllMenus();
+ return menus.map(menu => {
+ const items = getMenuItems(menu.id);
+ const itemsHTML = items.map(item => {
+ const parts: string[] = [];
+ if (item.separator) {
+ parts.push('<div class="es-menu-divider"></div>');
+ }
+ parts.push(`<div class="es-menu-item" data-action="${item.id}">`);
+ parts.push(`<span class="es-menu-item-text">${item.label}</span>`);
+ if (item.shortcut) {
+ parts.push(`<span class="es-menu-item-shortcut">${item.shortcut}</span>`);
+ }
+ parts.push('</div>');
+ return parts.join('');
+ }).join('');
+
+ return `
+ <div class="es-menu" data-menu="${menu.id}">
+ <div class="es-menu-trigger">${menu.label}</div>
+ <div class="es-menu-dropdown">${itemsHTML}</div>
+ </div>
+ `;
+ }).join('');
+ }
+
+ private instantiatePanels(): void {
+ for (const desc of getAllPanels()) {
+ if (!desc.defaultVisible && desc.position !== 'bottom') continue;
+ const el = this.container_.querySelector(`[data-panel-id="${desc.id}"]`) as HTMLElement;
+ if (!el) continue;
+ const instance = desc.factory(el, this.store_);
+ this.panelInstances_.set(desc.id, instance);
+ }
+ }
+
+ private instantiateStatusbar(): void {
+ const items = getAllStatusbarItems();
+ const leftContainer = this.container_.querySelector('.es-statusbar-left');
+ const rightContainer = this.container_.querySelector('.es-statusbar-right');
+
+ for (const item of items) {
+ const container = item.position === 'left' ? leftContainer : rightContainer;
+ if (!container) continue;
+ const span = document.createElement('span');
+ span.dataset.statusbarId = item.id;
+ container.appendChild(span);
+ const instance = item.render(span);
+ this.statusbarInstances_.push(instance);
+ }
+ }
+
+ private setupMenuShortcuts(): void {
+ const menus = getAllMenus();
+ for (const menu of menus) {
+ const items = getMenuItems(menu.id);
+ for (const item of items) {
+ if (item.shortcut) {
+ this.shortcutManager_.register(item.shortcut, item.action);
+ }
+ }
+ }
+ }
+
private setupToolbarEvents(): void {
const menubar = this.container_.querySelector('.es-editor-menubar');
if (!menubar) return;
@@ -435,11 +718,22 @@ export class Editor {
const menuItem = target.closest('.es-menu-item') as HTMLElement;
if (!menuItem) return;
- const action = menuItem.dataset.action;
if (menuItem.classList.contains('es-disabled')) return;
+ const actionId = menuItem.dataset.action;
+ if (!actionId) return;
+
closeAllMenus();
- this.handleMenuAction(action);
+
+ const allMenus = getAllMenus();
+ for (const menu of allMenus) {
+ const items = getMenuItems(menu.id);
+ const found = items.find(i => i.id === actionId);
+ if (found) {
+ found.action();
+ return;
+ }
+ }
});
const previewBtn = menubar.querySelector('[data-action="preview"]');
@@ -452,368 +746,64 @@ export class Editor {
});
}
- private handleMenuAction(action: string | undefined): void {
- switch (action) {
- case 'new':
- this.newScene();
- break;
- case 'open':
- this.loadScene();
- break;
- case 'save':
- this.saveScene();
- break;
- case 'save-as':
- this.saveSceneAs();
- break;
- case 'undo':
- this.store_.undo();
- break;
- case 'redo':
- this.store_.redo();
- break;
- case 'delete':
- if (this.store_.selectedEntity !== null) {
- this.store_.deleteEntity(this.store_.selectedEntity);
- }
- break;
- case 'duplicate':
- this.duplicateSelected();
- break;
- case 'toggle-hierarchy':
- case 'toggle-inspector':
- case 'toggle-assets':
- this.toggleAssetsPanel();
- break;
- case 'toggle-output':
- this.toggleOutputPanel();
- break;
- case 'docs':
- window.open('https://github.com/nicholaswan/ESEngine', '_blank');
- break;
- case 'about':
- this.showAboutDialog();
- break;
- case 'build-settings':
- this.showBuildSettings();
- break;
- }
- }
-
- private 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: () => {},
- });
- }
-
- private async saveSceneAs(): Promise<void> {
- clearFileHandle();
- const savedPath = await saveSceneToFile(this.store_.scene);
- if (savedPath) {
- this.store_.markSaved(savedPath);
- }
- }
-
- private duplicateSelected(): void {
- const entity = this.store_.selectedEntity;
- if (entity === null) return;
-
- const entityData = this.store_.getEntityData(entity as number);
- if (!entityData) return;
-
- const newEntity = this.store_.createEntity(
- `${entityData.name}_copy`,
- entityData.parent as Entity | null
- );
-
- for (const comp of entityData.components) {
- this.store_.addComponent(newEntity, comp.type, { ...comp.data });
- }
- }
-
- private showAboutDialog(): void {
- 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">&times;</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 0.1.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;">
- <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')?.addEventListener('click', close);
- overlay.addEventListener('click', (e) => {
- if (e.target === overlay) close();
- });
-
- document.body.appendChild(overlay);
- }
-
private updateToolbarState(): void {
- const undoItem = this.container_.querySelector('[data-action="undo"]');
- const redoItem = this.container_.querySelector('[data-action="redo"]');
- const deleteItem = this.container_.querySelector('[data-action="delete"]');
- const duplicateItem = this.container_.querySelector('[data-action="duplicate"]');
-
- undoItem?.classList.toggle('es-disabled', !this.store_.canUndo);
- redoItem?.classList.toggle('es-disabled', !this.store_.canRedo);
-
- const hasSelection = this.store_.selectedEntity !== null;
- deleteItem?.classList.toggle('es-disabled', !hasSelection);
- duplicateItem?.classList.toggle('es-disabled', !hasSelection);
- }
-
- private setupKeyboardShortcuts(): void {
- document.addEventListener('keydown', (e) => {
- if (e.ctrlKey || e.metaKey) {
- switch (e.key.toLowerCase()) {
- case 'z':
- e.preventDefault();
- if (e.shiftKey) {
- this.store_.redo();
- } else {
- this.store_.undo();
- }
- break;
- case 'y':
- e.preventDefault();
- this.store_.redo();
- break;
- case 's':
- e.preventDefault();
- if (e.shiftKey) {
- this.saveSceneAs();
- } else {
- this.saveScene();
- }
- break;
- case 'o':
- e.preventDefault();
- this.loadScene();
- break;
- case 'n':
- e.preventDefault();
- this.newScene();
- break;
- case 'd':
- e.preventDefault();
- this.duplicateSelected();
- break;
- case 'b':
- if (e.shiftKey) {
- e.preventDefault();
- this.showBuildSettings();
- }
- break;
- }
- } else if (e.key === 'Delete') {
- const selected = this.store_.selectedEntity;
- if (selected !== null) {
- this.store_.deleteEntity(selected);
+ const allMenus = getAllMenus();
+ for (const menu of allMenus) {
+ const items = getMenuItems(menu.id);
+ for (const item of items) {
+ if (item.enabled) {
+ const el = this.container_.querySelector(`[data-action="${item.id}"]`);
+ el?.classList.toggle('es-disabled', !item.enabled());
}
}
- });
+ }
}
- private setupStatusbarEvents(): void {
- const statusbar = this.container_.querySelector('.es-editor-statusbar');
- if (!statusbar) return;
-
- statusbar.addEventListener('click', (e) => {
- const target = e.target as HTMLElement;
- const btn = target.closest('[data-action]') as HTMLElement;
- if (!btn) return;
-
- const action = btn.dataset.action;
- if (action === 'toggle-assets') {
- this.toggleAssetsPanel();
- } else if (action === 'toggle-output') {
- this.toggleOutputPanel();
- } else if (action === 'undo') {
- this.store_.undo();
- }
- });
-
- const cmdInput = statusbar.querySelector('.es-cmd-input') as HTMLInputElement;
+ private updateBottomPanelVisibility(): void {
+ const bottomSection = this.container_.querySelector('.es-editor-bottom') as HTMLElement;
+ const bottomPanels = getPanelsByPosition('bottom');
- cmdInput?.addEventListener('keydown', (e) => {
- if (e.key === 'Enter') {
- const command = cmdInput.value.trim();
- if (command) {
- this.executeShellCommand(command);
- cmdInput.value = '';
- }
+ for (const desc of bottomPanels) {
+ const el = this.container_.querySelector(`[data-panel-id="${desc.id}"]`) as HTMLElement;
+ if (el) {
+ el.style.display = desc.id === this.activeBottomPanelId_ ? '' : 'none';
}
- });
- }
-
- private async executeShellCommand(fullCommand: string): Promise<void> {
- if (!this.projectPath_) {
- this.appendOutput('Error: No project loaded\n', 'error');
- return;
}
- const shell = (window as any).__esengine_shell;
- if (!shell) {
- this.appendOutput('Error: Shell not available\n', 'error');
- return;
+ if (bottomSection) {
+ bottomSection.style.display = this.activeBottomPanelId_ ? '' : 'none';
}
- const projectDir = this.projectPath_.replace(/[/\\][^/\\]+$/, '');
-
- this.outputPanelVisible_ = true;
- this.assetsPanelVisible_ = false;
- this.updateBottomPanelVisibility();
-
- 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');
+ for (const instance of this.statusbarInstances_) {
+ instance.update?.();
}
- }
-
- private appendOutput(text: string, type: 'command' | 'stdout' | 'stderr' | 'error' | 'success'): void {
- const outputContent = this.container_.querySelector('.es-output-content');
- if (!outputContent) return;
-
- const empty = outputContent.querySelector('.es-output-empty');
- if (empty) empty.remove();
-
- const line = document.createElement('div');
- line.className = `es-output-line es-output-${type}`;
- line.textContent = text;
- outputContent.appendChild(line);
- outputContent.scrollTop = outputContent.scrollHeight;
- }
- private updateBottomPanelVisibility(): void {
- const assetsBtn = this.container_.querySelector('[data-action="toggle-assets"]');
- const outputBtn = this.container_.querySelector('[data-action="toggle-output"]');
- const contentBrowser = this.container_.querySelector('.es-content-browser-container') as HTMLElement;
- const outputPanel = this.container_.querySelector('.es-output-container') as HTMLElement;
- const bottomPanel = this.container_.querySelector('.es-editor-bottom') as HTMLElement;
-
- assetsBtn?.classList.toggle('es-active', this.assetsPanelVisible_);
- outputBtn?.classList.toggle('es-active', this.outputPanelVisible_);
-
- if (contentBrowser) contentBrowser.style.display = this.assetsPanelVisible_ ? '' : 'none';
- if (outputPanel) outputPanel.style.display = this.outputPanelVisible_ ? '' : 'none';
- if (bottomPanel) bottomPanel.style.display = (this.assetsPanelVisible_ || this.outputPanelVisible_) ? '' : 'none';
-
- requestAnimationFrame(() => this.sceneViewPanel_?.resize());
- }
-
- private toggleAssetsPanel(): void {
- const assetsBtn = this.container_.querySelector('[data-action="toggle-assets"]');
- const outputBtn = this.container_.querySelector('[data-action="toggle-output"]');
- const contentBrowser = this.container_.querySelector('.es-content-browser-container') as HTMLElement;
- const outputPanel = this.container_.querySelector('.es-output-container') as HTMLElement;
- const bottomPanel = this.container_.querySelector('.es-editor-bottom') as HTMLElement;
-
- if (this.assetsPanelVisible_) {
- this.assetsPanelVisible_ = false;
- assetsBtn?.classList.remove('es-active');
- if (contentBrowser) contentBrowser.style.display = 'none';
- if (bottomPanel) bottomPanel.style.display = this.outputPanelVisible_ ? '' : 'none';
- } else {
- this.assetsPanelVisible_ = true;
- this.outputPanelVisible_ = false;
- assetsBtn?.classList.add('es-active');
- outputBtn?.classList.remove('es-active');
- if (contentBrowser) contentBrowser.style.display = '';
- if (outputPanel) outputPanel.style.display = 'none';
- if (bottomPanel) bottomPanel.style.display = '';
- }
-
- requestAnimationFrame(() => this.sceneViewPanel_?.resize());
- }
-
- private toggleOutputPanel(): void {
- const assetsBtn = this.container_.querySelector('[data-action="toggle-assets"]');
- const outputBtn = this.container_.querySelector('[data-action="toggle-output"]');
- const contentBrowser = this.container_.querySelector('.es-content-browser-container') as HTMLElement;
- const outputPanel = this.container_.querySelector('.es-output-container') as HTMLElement;
- const bottomPanel = this.container_.querySelector('.es-editor-bottom') as HTMLElement;
-
- if (this.outputPanelVisible_) {
- this.outputPanelVisible_ = false;
- outputBtn?.classList.remove('es-active');
- if (outputPanel) outputPanel.style.display = 'none';
- if (bottomPanel) bottomPanel.style.display = this.assetsPanelVisible_ ? '' : 'none';
- } else {
- this.outputPanelVisible_ = true;
- this.assetsPanelVisible_ = false;
- outputBtn?.classList.add('es-active');
- assetsBtn?.classList.remove('es-active');
- if (outputPanel) outputPanel.style.display = '';
- if (contentBrowser) contentBrowser.style.display = 'none';
- if (bottomPanel) bottomPanel.style.display = '';
+ for (const panel of this.panelInstances_.values()) {
+ if (isResizable(panel)) {
+ requestAnimationFrame(() => panel.resize());
+ break;
+ }
}
-
- requestAnimationFrame(() => this.sceneViewPanel_?.resize());
}
private updateStatusbar(): void {
- const savedIndicator = this.container_.querySelector('.es-status-saved');
- const unsavedIndicator = this.container_.querySelector('.es-status-unsaved');
-
- if (this.store_.isDirty) {
- savedIndicator?.classList.add('es-hidden');
- if (unsavedIndicator) {
- unsavedIndicator.classList.remove('es-hidden');
- }
- } else {
- savedIndicator?.classList.remove('es-hidden');
- if (unsavedIndicator) {
- unsavedIndicator.classList.add('es-hidden');
- }
+ for (const instance of this.statusbarInstances_) {
+ instance.update?.();
}
}
dispose(): void {
- this.hierarchyPanel_?.dispose();
- this.inspectorPanel_?.dispose();
- this.sceneViewPanel_?.dispose();
- this.contentBrowserPanel_?.dispose();
+ this.shortcutManager_.detach();
+ this.extensionLoader_?.dispose();
+ for (const instance of this.statusbarInstances_) {
+ instance.dispose();
+ }
+ this.statusbarInstances_ = [];
+ for (const panel of this.panelInstances_.values()) {
+ panel.dispose();
+ }
+ this.panelInstances_.clear();
+ delete (window as any).__ESENGINE_EDITOR__;
}
}
diff --git a/editor/src/extension/EditorExportService.ts b/editor/src/extension/EditorExportService.ts
new file mode 100644
index 000000000..ab9062e81
--- /dev/null
+++ b/editor/src/extension/EditorExportService.ts
@@ -0,0 +1,60 @@
+/**
+ * @file EditorExportService.ts
+ * @brief Export editor type definitions to user projects
+ */
+
+import { SDK_VERSION } from '../types/ProjectTypes';
+import { getEditorContext } from '../context/EditorContext';
+
+// =============================================================================
+// Native FS Interface
+// =============================================================================
+
+interface NativeFS {
+ createDirectory(path: string): Promise<boolean>;
+ writeFile(path: string, content: string): Promise<boolean>;
+ readFile(path: string): Promise<string | null>;
+ getEditorDts(): Promise<string>;
+}
+
+function getNativeFS(): NativeFS | null {
+ return getEditorContext().fs ?? null;
+}
+
+// =============================================================================
+// Editor Export Service
+// =============================================================================
+
+export class EditorExportService {
+ private fs_: NativeFS | null;
+
+ constructor() {
+ this.fs_ = getNativeFS();
+ }
+
+ async exportToProject(projectDir: string): Promise<boolean> {
+ if (!this.fs_) return false;
+
+ const editorDir = `${projectDir}/.esengine/editor`;
+
+ await this.fs_.createDirectory(`${projectDir}/.esengine`);
+ await this.fs_.createDirectory(editorDir);
+
+ const results = await Promise.all([
+ this.fs_.writeFile(`${editorDir}/version.txt`, SDK_VERSION),
+ this.fs_.writeFile(`${editorDir}/index.d.ts`, await this.fs_.getEditorDts()),
+ ]);
+
+ return results.every(r => r);
+ }
+
+ async needsUpdate(projectDir: string): Promise<boolean> {
+ if (!this.fs_) return true;
+
+ const versionPath = `${projectDir}/.esengine/editor/version.txt`;
+ const content = await this.fs_.readFile(versionPath);
+ if (!content) return true;
+
+ return content.trim() !== SDK_VERSION;
+ }
+}
diff --git a/editor/src/extension/ExtensionLoader.ts b/editor/src/extension/ExtensionLoader.ts
new file mode 100644
index 000000000..2a7c01bff
--- /dev/null
+++ b/editor/src/extension/ExtensionLoader.ts
@@ -0,0 +1,208 @@
+/**
+ * @file ExtensionLoader.ts
+ * @brief Load and compile user editor extensions from project editor/ directory
+ */
+
+import * as esbuild from 'esbuild-wasm/esm/browser';
+import { editorShimPlugin, virtualFsPlugin } from '../scripting/esbuildPlugins';
+import type { NativeFS, CompileError } from '../scripting/types';
+import { getEditorContext } from '../context/EditorContext';
+
+// =============================================================================
+// Path Utilities
+// =============================================================================
+
+function normalizePath(path: string): string {
+ return path.replace(/\\/g, '/');
+}
+
+function joinPath(...parts: string[]): string {
+ return normalizePath(parts.join('/').replace(/\/+/g, '/'));
+}
+
+function getProjectDir(projectPath: string): string {
+ const normalized = normalizePath(projectPath);
+ const lastSlash = normalized.lastIndexOf('/');
+ return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
+}
+
+// =============================================================================
+// Native FS Access
+// =============================================================================
+
+function getNativeFS(): NativeFS | null {
+ return getEditorContext().fs ?? null;
+}
+
+// =============================================================================
+// Extension Loader
+// =============================================================================
+
+export interface ExtensionLoaderOptions {
+ projectPath: string;
+ onCompileError?: (errors: CompileError[]) => void;
+ onCompileSuccess?: () => void;
+}
+
+export class ExtensionLoader {
+ constructor(options: ExtensionLoaderOptions) {
+ this.projectPath_ = normalizePath(options.projectPath);
+ this.projectDir_ = getProjectDir(this.projectPath_);
+ this.onCompileError_ = options.onCompileError;
+ this.onCompileSuccess_ = options.onCompileSuccess;
+ }
+
+ // =========================================================================
+ // Public Methods
+ // =========================================================================
+
+ async initialize(): Promise<void> {
+ if (this.initialized_) return;
+
+ try {
+ await esbuild.initialize({
+ wasmURL: 'https://cdn.jsdelivr.net/npm/[email protected]/esbuild.wasm',
+ });
+ this.initialized_ = true;
+ } catch (err) {
+ if (String(err).includes('Cannot call "initialize" more than once')) {
+ this.initialized_ = true;
+ } else {
+ throw err;
+ }
+ }
+ }
+
+ async discover(): Promise<string[]> {
+ const fs = getNativeFS();
+ if (!fs) return [];
+
+ const editorDir = joinPath(this.projectDir_, 'editor');
+
+ try {
+ if (!(await fs.exists(editorDir))) return [];
+
+ const entries = await fs.listDirectoryDetailed(editorDir);
+ return entries
+ .filter(e => !e.isDirectory && e.name.endsWith('.ts'))
+ .map(e => joinPath(editorDir, e.name));
+ } catch (err) {
+ console.error('ExtensionLoader: Failed to discover extensions:', err);
+ return [];
+ }
+ }
+
+ async compile(): Promise<boolean> {
+ const fs = getNativeFS();
+ if (!fs) return false;
+
+ const scripts = await this.discover();
+ if (scripts.length === 0) {
+ this.lastCompiled_ = null;
+ return true;
+ }
+
+ console.log('ExtensionLoader: Compiling extensions:', scripts);
+
+ try {
+ const entryContent = scripts
+ .map(p => `import "${p}";`)
+ .join('\n');
+
+ const result = await esbuild.build({
+ stdin: {
+ contents: entryContent,
+ loader: 'ts',
+ resolveDir: joinPath(this.projectDir_, 'editor'),
+ },
+ bundle: true,
+ format: 'esm',
+ write: false,
+ platform: 'browser',
+ target: 'es2020',
+ external: ['esengine'],
+ plugins: [
+ editorShimPlugin(),
+ virtualFsPlugin({ fs, projectDir: this.projectDir_ }),
+ ],
+ });
+
+ if (result.errors.length > 0) {
+ const errors: CompileError[] = result.errors.map(e => ({
+ file: e.location?.file || 'unknown',
+ line: e.location?.line || 0,
+ column: e.location?.column || 0,
+ message: e.text,
+ }));
+ console.error('ExtensionLoader: Compilation errors:', errors);
+ this.onCompileError_?.(errors);
+ return false;
+ }
+
+ this.lastCompiled_ = result.outputFiles?.[0]?.text ?? null;
+ console.log('ExtensionLoader: Extensions compiled successfully');
+ this.onCompileSuccess_?.();
+ return true;
+ } catch (err) {
+ console.error('ExtensionLoader: Compilation failed:', err);
+ const errors: CompileError[] = [{
+ file: 'unknown',
+ line: 0,
+ column: 0,
+ message: String(err),
+ }];
+ this.onCompileError_?.(errors);
+ return false;
+ }
+ }
+
+ async execute(): Promise<boolean> {
+ if (!this.lastCompiled_) return false;
+
+ this.disposeCurrentUrl();
+
+ try {
+ const blob = new Blob([this.lastCompiled_], { type: 'application/javascript' });
+ this.currentBlobUrl_ = URL.createObjectURL(blob);
+ await import(/* @vite-ignore */ this.currentBlobUrl_);
+ console.log('ExtensionLoader: Extensions executed successfully');
+ return true;
+ } catch (err) {
+ console.error('ExtensionLoader: Extension execution failed:', err);
+ return false;
+ }
+ }
+
+ async reload(): Promise<boolean> {
+ const compiled = await this.compile();
+ if (!compiled) return false;
+ return this.execute();
+ }
+
+ dispose(): void {
+ this.disposeCurrentUrl();
+ }
+
+ // =========================================================================
+ // Private Methods
+ // =========================================================================
+
+ private disposeCurrentUrl(): void {
+ if (this.currentBlobUrl_) {
+ URL.revokeObjectURL(this.currentBlobUrl_);
+ this.currentBlobUrl_ = null;
+ }
+ }
+
+ // =========================================================================
+ // Member Variables
+ // =========================================================================
+
+ private projectPath_: string;
+ private projectDir_: string;
+ private initialized_ = false;
+ private lastCompiled_: string | null = null;
+ private currentBlobUrl_: string | null = null;
+ private onCompileError_?: (errors: CompileError[]) => void;
+ private onCompileSuccess_?: () => void;
+}
diff --git a/editor/src/extension/index.ts b/editor/src/extension/index.ts
new file mode 100644
index 000000000..e8e8bb639
--- /dev/null
+++ b/editor/src/extension/index.ts
@@ -0,0 +1,2 @@
+export { ExtensionLoader, type ExtensionLoaderOptions } from './ExtensionLoader';
+export { EditorExportService } from './EditorExportService';
diff --git a/editor/src/index.ts b/editor/src/index.ts
index 66b206e01..23b7f92cc 100644
--- a/editor/src/index.ts
+++ b/editor/src/index.ts
@@ -59,8 +59,65 @@ export {
HierarchyPanel,
InspectorPanel,
SceneViewPanel,
+ OutputPanel,
} from './panels';
+// =============================================================================
+// Panel Registry
+// =============================================================================
+
+export {
+ type PanelPosition,
+ type PanelDescriptor,
+ type PanelFactory,
+ type PanelInstance,
+ type Resizable,
+ type BridgeAware,
+ type AppAware,
+ type AssetServerProvider,
+ type AssetNavigable,
+ type OutputAppendable,
+ registerPanel,
+ getPanel,
+ getAllPanels,
+ isResizable,
+ isBridgeAware,
+ isAppAware,
+ isAssetServerProvider,
+ isAssetNavigable,
+ isOutputAppendable,
+} from './panels/PanelRegistry';
+
+// =============================================================================
+// Gizmo Registry
+// =============================================================================
+
+export {
+ type GizmoContext,
+ type GizmoDescriptor,
+ GizmoManager,
+ registerGizmo,
+ getGizmo,
+ getAllGizmos,
+} from './gizmos';
+
+// =============================================================================
+// Menu Registry
+// =============================================================================
+
+export {
+ type MenuDescriptor,
+ type MenuItemDescriptor,
+ type StatusbarItemDescriptor,
+ registerMenu,
+ registerMenuItem,
+ registerStatusbarItem,
+ getAllMenus,
+ getMenuItems,
+} from './menus/MenuRegistry';
+
+export { ShortcutManager } from './menus/ShortcutManager';
+
// =============================================================================
// Property Editors
// =============================================================================
@@ -92,6 +149,76 @@ export {
registerBuiltinSchemas,
} from './schemas';
+// =============================================================================
+// Bounds
+// =============================================================================
+
+export {
+ type Bounds,
+ type BoundsProvider,
+ registerBoundsProvider,
+ getEntityBounds,
+} from './bounds';
+
+// =============================================================================
+// Events
+// =============================================================================
+
+export {
+ type AssetEvent,
+ type AssetCategory,
+ type AssetEventType,
+ type AssetEventListener,
+ AssetEventBus,
+ getAssetEventBus,
+} from './events/AssetEventBus';
+
+// =============================================================================
+// UI
+// =============================================================================
+
+export {
+ showContextMenu,
+ hideContextMenu,
+ type ContextMenuItem,
+ type ContextMenuOptions,
+} from './ui/ContextMenu';
+
+export {
+ showToast,
+ showSuccessToast,
+ showErrorToast,
+ showProgressToast,
+ updateToast,
+ dismissToast,
+ type ToastOptions,
+ type ToastAction,
+} from './ui/Toast';
+
+// =============================================================================
+// Utils
+// =============================================================================
+
+export { icons } from './utils/icons';
+
+// =============================================================================
+// Asset
+// =============================================================================
+
+export { AssetPathResolver, getGlobalPathResolver } from './asset';
+
+// =============================================================================
+// Math
+// =============================================================================
+
+export { quatToEuler, eulerToQuat, type Transform } from './math/Transform';
+
+// =============================================================================
+// Content Browser
+// =============================================================================
+
+export { ContentBrowserPanel } from './panels/ContentBrowserPanel';
+
// =============================================================================
// Bridge
// =============================================================================
@@ -178,3 +305,28 @@ export {
type ConfirmDialogOptions,
type AlertDialogOptions,
} from './ui/dialog';
+
+// =============================================================================
+// Context
+// =============================================================================
+
+export {
+ setEditorContext,
+ getEditorContext,
+ setEditorInstance,
+ getEditorInstance,
+ type EditorContextConfig,
+ type NativeShell,
+} from './context/EditorContext';
+
+export type { NativeFS, DirectoryEntry } from './scripting/types';
+
+// =============================================================================
+// Extension
+// =============================================================================
+
+export {
+ ExtensionLoader,
+ EditorExportService,
+ type ExtensionLoaderOptions,
+} from './extension';
diff --git a/editor/src/launcher/ProjectService.ts b/editor/src/launcher/ProjectService.ts
index d97495351..d7934bf0c 100644
--- a/editor/src/launcher/ProjectService.ts
+++ b/editor/src/launcher/ProjectService.ts
@@ -10,6 +10,8 @@ import type {
} from '../types/ProjectTypes';
import { ENGINE_VERSION } from '../types/ProjectTypes';
import { SdkExportService } from '../sdk';
+import { EditorExportService } from '../extension';
+import { getEditorContext } from '../context/EditorContext';
// =============================================================================
// Native FS Interface
@@ -25,7 +27,7 @@ interface NativeFS {
}
function getNativeFS(): NativeFS | null {
- return (window as any).__esengine_fs ?? null;
+ return getEditorContext().fs ?? null;
}
// =============================================================================
@@ -116,6 +118,7 @@ export async function createProject(
const directories = [
projectDir,
joinPath(projectDir, 'src'),
+ joinPath(projectDir, 'editor'),
joinPath(projectDir, 'assets'),
joinPath(projectDir, 'assets/scenes'),
joinPath(projectDir, 'assets/textures'),
@@ -174,6 +177,10 @@ export async function createProject(
const sdkService = new SdkExportService();
await sdkService.exportToProject(projectDir);
+ // Export editor types to project
+ const editorExportService = new EditorExportService();
+ await editorExportService.exportToProject(projectDir);
+
// Add to recent projects
addRecentProject({
name,
@@ -231,6 +238,12 @@ export async function openProject(
await sdkService.exportToProject(projectDir);
}
+ // Update editor types if needed
+ const editorExportService = new EditorExportService();
+ if (await editorExportService.needsUpdate(projectDir)) {
+ await editorExportService.exportToProject(projectDir);
+ }
+
// Update recent projects
addRecentProject({
name: config.name,
@@ -393,14 +406,15 @@ const TSCONFIG_TEMPLATE = JSON.stringify({
forceConsistentCasingInFileNames: true,
declaration: false,
outDir: './dist',
- rootDir: './src',
+ rootDir: '.',
baseUrl: '.',
paths: {
'esengine': ['./.esengine/sdk/index.d.ts'],
'esengine/wasm': ['./.esengine/sdk/wasm.d.ts'],
+ '@esengine/editor': ['./.esengine/editor/index.d.ts'],
},
},
- include: ['src/**/*'],
+ include: ['src/**/*', 'editor/**/*'],
exclude: ['node_modules'],
}, null, 2);
diff --git a/editor/src/menus/builtinMenus.ts b/editor/src/menus/builtinMenus.ts
new file mode 100644
index 000000000..f5fe8309b
--- /dev/null
+++ b/editor/src/menus/builtinMenus.ts
@@ -0,0 +1,94 @@
+import { registerMenu, registerMenuItem } from './MenuRegistry';
+import type { Editor } from '../Editor';
+
+export function registerBuiltinMenus(editor: Editor): void {
+ registerMenu({ id: 'file', label: 'File', order: 0 });
+ registerMenu({ id: 'edit', label: 'Edit', order: 1 });
+ registerMenu({ id: 'view', label: 'View', order: 2 });
+ registerMenu({ id: 'help', label: 'Help', order: 3 });
+
+ registerMenuItem({
+ id: 'file.new', menu: 'file', label: 'New Scene',
+ shortcut: 'Ctrl+N', order: 0,
+ action: () => editor.newScene(),
+ });
+ registerMenuItem({
+ id: 'file.open', menu: 'file', label: 'Open...',
+ shortcut: 'Ctrl+O', order: 1,
+ action: () => editor.loadScene(),
+ });
+ registerMenuItem({
+ id: 'file.save', menu: 'file', label: 'Save',
+ shortcut: 'Ctrl+S', order: 2, separator: true,
+ action: () => editor.saveScene(),
+ });
+ registerMenuItem({
+ id: 'file.save-as', menu: 'file', label: 'Save As...',
+ shortcut: 'Ctrl+Shift+S', order: 3,
+ action: () => editor.saveSceneAs(),
+ });
+ registerMenuItem({
+ id: 'file.build-settings', menu: 'file', label: 'Build Settings...',
+ shortcut: 'Ctrl+Shift+B', order: 4, separator: true,
+ action: () => editor.showBuildSettings(),
+ });
+
+ registerMenuItem({
+ id: 'edit.undo', menu: 'edit', label: 'Undo',
+ shortcut: 'Ctrl+Z', order: 0,
+ enabled: () => editor.store.canUndo,
+ action: () => editor.store.undo(),
+ });
+ registerMenuItem({
+ id: 'edit.redo', menu: 'edit', label: 'Redo',
+ shortcut: 'Ctrl+Y', order: 1,
+ enabled: () => editor.store.canRedo,
+ action: () => editor.store.redo(),
+ });
+ registerMenuItem({
+ id: 'edit.delete', menu: 'edit', label: 'Delete',
+ shortcut: 'Delete', order: 2, separator: true,
+ enabled: () => editor.store.selectedEntity !== null,
+ action: () => {
+ const selected = editor.store.selectedEntity;
+ if (selected !== null) editor.store.deleteEntity(selected);
+ },
+ });
+ registerMenuItem({
+ id: 'edit.duplicate', menu: 'edit', label: 'Duplicate',
+ shortcut: 'Ctrl+D', order: 3,
+ enabled: () => editor.store.selectedEntity !== null,
+ action: () => editor.duplicateSelected(),
+ });
+
+ registerMenuItem({
+ id: 'view.hierarchy', menu: 'view', label: 'Hierarchy', order: 0,
+ action: () => editor.togglePanel('hierarchy'),
+ });
+ registerMenuItem({
+ id: 'view.inspector', menu: 'view', label: 'Inspector', order: 1,
+ action: () => editor.togglePanel('inspector'),
+ });
+ registerMenuItem({
+ id: 'view.content-browser', menu: 'view', label: 'Content Browser', order: 2,
+ action: () => editor.toggleBottomPanel('content-browser'),
+ });
+ registerMenuItem({
+ id: 'view.output', menu: 'view', label: 'Output', order: 3,
+ action: () => editor.toggleBottomPanel('output'),
+ });
+ registerMenuItem({
+ id: 'view.reload-extensions', menu: 'view', label: 'Reload Extensions',
+ order: 10, separator: true,
+ action: () => editor.reloadExtensions(),
+ });
+
+ registerMenuItem({
+ id: 'help.docs', menu: 'help', label: 'Documentation', order: 0,
+ action: () => window.open('https://github.com/nicholaswan/ESEngine', '_blank'),
+ });
+ registerMenuItem({
+ id: 'help.about', menu: 'help', label: 'About ESEngine', order: 1, separator: true,
+ action: () => editor.showAboutDialog(),
+ });
+}
diff --git a/editor/src/scripting/esbuildPlugins.ts b/editor/src/scripting/esbuildPlugins.ts
index 2596b8c6c..e78530ae6 100644
--- a/editor/src/scripting/esbuildPlugins.ts
+++ b/editor/src/scripting/esbuildPlugins.ts
@@ -44,6 +44,37 @@ function resolvePath(from: string, to: string): string {
return parts.join('/');
}
+// =============================================================================
+// Editor Shim Plugin
+// =============================================================================
+
+const EDITOR_SHIM_EXPORTS = [
+ 'registerPanel', 'registerMenuItem', 'registerMenu',
+ 'registerGizmo', 'registerStatusbarItem', 'registerPropertyEditor',
+ 'registerComponentSchema', 'registerBoundsProvider',
+ 'icons', 'showToast', 'showSuccessToast', 'showErrorToast',
+ 'showContextMenu', 'showConfirmDialog', 'showInputDialog',
+ 'getEditorInstance', 'getEditorStore',
+] as const;
+
+const EDITOR_SHIM_CODE = EDITOR_SHIM_EXPORTS.map(
+ name => `export const ${name} = window.__ESENGINE_EDITOR__.${name};`
+).join('\n');
+
+export function editorShimPlugin(): esbuild.Plugin {
+ return {
+ name: 'editor-shim',
+ setup(build) {
+ build.onResolve({ filter: /^@esengine\/editor$/ }, () => {
+ return { path: '@esengine/editor', namespace: 'editor-shim' };
+ });
+ build.onLoad({ filter: /.*/, namespace: 'editor-shim' }, () => {
+ return { contents: EDITOR_SHIM_CODE, loader: 'js' };
+ });
+ },
+ };
+}
+
// =============================================================================
// Virtual FS Plugin
// =============================================================================
diff --git a/editor/src/scripting/types.ts b/editor/src/scripting/types.ts
index 2ec95e8fd..d59e30e46 100644
--- a/editor/src/scripting/types.ts
+++ b/editor/src/scripting/types.ts
@@ -13,12 +13,47 @@ export interface DirectoryEntry {
isFile: boolean;
}
+export interface FileStats {
+ size: number;
+ modified: Date | null;
+ created: Date | null;
+}
+
export interface NativeFS {
+ saveFile(content: string, defaultPath?: string): Promise<string | null>;
+ loadFile(): Promise<{ path: string; content: string } | null>;
+ selectDirectory(): Promise<string | null>;
+ createDirectory(path: string): Promise<boolean>;
+ exists(path: string): Promise<boolean>;
+ writeFile(path: string, content: string): Promise<boolean>;
+ writeBinaryFile(path: string, data: Uint8Array): Promise<boolean>;
readFile(path: string): Promise<string | null>;
- writeFile(path: string, content: string): Promise<void>;
+ readBinaryFile(path: string): Promise<Uint8Array | null>;
+ copyFile(src: string, dest: string): Promise<boolean>;
+ getFileStats(path: string): Promise<FileStats | null>;
+ openProject(): Promise<string | null>;
+ listDirectory(path: string): Promise<string[]>;
listDirectoryDetailed(path: string): Promise<DirectoryEntry[]>;
- exists(path: string): Promise<boolean>;
- createDirectory(path: string): Promise<void>;
+ watchDirectory(
+ path: string,
+ callback: (event: { type: 'create' | 'modify' | 'remove' | 'rename' | 'any'; paths: string[] }) => void,
+ options?: { recursive?: boolean }
+ ): Promise<() => void>;
+ openFolder(path: string): Promise<boolean>;
+ openFile?(path: string): Promise<void>;
+ showOpenDialog?(options: { title?: string; filters?: Array<{ name: string; extensions: string[] }> }): Promise<string[] | null>;
+ getResourcePath(): Promise<string>;
+ getEngineJs(): Promise<string>;
+ getEngineWasm(): Promise<Uint8Array>;
+ getEngineSingleJs(): Promise<string>;
+ getEngineWxgameJs(): Promise<string>;
+ getEngineWxgameWasm(): Promise<Uint8Array>;
+ getSdkWechatJs(): Promise<string>;
+ getSdkEsmJs(): Promise<string>;
+ getSdkEsmDts(): Promise<string>;
+ getSdkWasmJs(): Promise<string>;
+ getSdkWasmDts(): Promise<string>;
+ getEditorDts(): Promise<string>;
}
// =============================================================================