更新图标及场景序列化系统
@@ -17,6 +17,7 @@
|
||||
"@esengine/ecs-framework": "file:../core",
|
||||
"@esengine/editor-core": "file:../editor-core",
|
||||
"@tauri-apps/api": "^2.2.0",
|
||||
"@tauri-apps/plugin-dialog": "^2.4.0",
|
||||
"@tauri-apps/plugin-shell": "^2.0.0",
|
||||
"json5": "^2.2.3",
|
||||
"lucide-react": "^0.545.0",
|
||||
|
||||
|
Before Width: | Height: | Size: 5.0 KiB After Width: | Height: | Size: 4.8 KiB |
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 865 B After Width: | Height: | Size: 915 B |
BIN
packages/editor-app/src-tauri/icons/64x64.png
Normal file
|
After Width: | Height: | Size: 2.1 KiB |
BIN
packages/editor-app/src-tauri/icons/Square107x107Logo.png
Normal file
|
After Width: | Height: | Size: 4.0 KiB |
BIN
packages/editor-app/src-tauri/icons/Square142x142Logo.png
Normal file
|
After Width: | Height: | Size: 5.4 KiB |
BIN
packages/editor-app/src-tauri/icons/Square150x150Logo.png
Normal file
|
After Width: | Height: | Size: 5.8 KiB |
BIN
packages/editor-app/src-tauri/icons/Square284x284Logo.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
BIN
packages/editor-app/src-tauri/icons/Square30x30Logo.png
Normal file
|
After Width: | Height: | Size: 888 B |
BIN
packages/editor-app/src-tauri/icons/Square310x310Logo.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
packages/editor-app/src-tauri/icons/Square44x44Logo.png
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
BIN
packages/editor-app/src-tauri/icons/Square71x71Logo.png
Normal file
|
After Width: | Height: | Size: 2.4 KiB |
BIN
packages/editor-app/src-tauri/icons/Square89x89Logo.png
Normal file
|
After Width: | Height: | Size: 3.0 KiB |
BIN
packages/editor-app/src-tauri/icons/StoreLogo.png
Normal file
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 6.3 KiB |
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 4.1 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 5.7 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 5.7 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
BIN
packages/editor-app/src-tauri/icons/icon.icns
Normal file
|
Before Width: | Height: | Size: 1.8 KiB After Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 26 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@1x.png
Normal file
|
After Width: | Height: | Size: 512 B |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@2x-1.png
Normal file
|
After Width: | Height: | Size: 1.2 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@2x.png
Normal file
|
After Width: | Height: | Size: 1.2 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-20x20@3x.png
Normal file
|
After Width: | Height: | Size: 2.0 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@1x.png
Normal file
|
After Width: | Height: | Size: 847 B |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@2x-1.png
Normal file
|
After Width: | Height: | Size: 1.9 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@2x.png
Normal file
|
After Width: | Height: | Size: 1.9 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-29x29@3x.png
Normal file
|
After Width: | Height: | Size: 2.8 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@1x.png
Normal file
|
After Width: | Height: | Size: 1.2 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@2x-1.png
Normal file
|
After Width: | Height: | Size: 2.6 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@2x.png
Normal file
|
After Width: | Height: | Size: 2.6 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-40x40@3x.png
Normal file
|
After Width: | Height: | Size: 4.6 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-512@2x.png
Normal file
|
After Width: | Height: | Size: 58 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-60x60@2x.png
Normal file
|
After Width: | Height: | Size: 4.6 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-60x60@3x.png
Normal file
|
After Width: | Height: | Size: 7.2 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-76x76@1x.png
Normal file
|
After Width: | Height: | Size: 2.5 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-76x76@2x.png
Normal file
|
After Width: | Height: | Size: 6.1 KiB |
BIN
packages/editor-app/src-tauri/icons/ios/AppIcon-83.5x83.5@2x.png
Normal file
|
After Width: | Height: | Size: 6.7 KiB |
@@ -34,6 +34,26 @@ fn export_binary(data: Vec<u8>, output_path: String) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn create_directory(path: String) -> Result<(), String> {
|
||||
std::fs::create_dir_all(&path)
|
||||
.map_err(|e| format!("Failed to create directory: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn write_file_content(path: String, content: String) -> Result<(), String> {
|
||||
std::fs::write(&path, content)
|
||||
.map_err(|e| format!("Failed to write file: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn path_exists(path: String) -> Result<bool, String> {
|
||||
use std::path::Path;
|
||||
Ok(Path::new(&path).exists())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn open_project_dialog(app: AppHandle) -> Result<Option<String>, String> {
|
||||
use tauri_plugin_dialog::DialogExt;
|
||||
@@ -46,6 +66,37 @@ async fn open_project_dialog(app: AppHandle) -> Result<Option<String>, String> {
|
||||
Ok(folder.map(|path| path.to_string()))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn save_scene_dialog(app: AppHandle, default_name: Option<String>) -> Result<Option<String>, String> {
|
||||
use tauri_plugin_dialog::DialogExt;
|
||||
|
||||
let mut dialog = app.dialog()
|
||||
.file()
|
||||
.set_title("Save ECS Scene")
|
||||
.add_filter("ECS Scene Files", &["ecs"]);
|
||||
|
||||
if let Some(name) = default_name {
|
||||
dialog = dialog.set_file_name(&name);
|
||||
}
|
||||
|
||||
let file = dialog.blocking_save_file();
|
||||
|
||||
Ok(file.map(|path| path.to_string()))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn open_scene_dialog(app: AppHandle) -> Result<Option<String>, String> {
|
||||
use tauri_plugin_dialog::DialogExt;
|
||||
|
||||
let file = app.dialog()
|
||||
.file()
|
||||
.set_title("Open ECS Scene")
|
||||
.add_filter("ECS Scene Files", &["ecs"])
|
||||
.blocking_pick_file();
|
||||
|
||||
Ok(file.map(|path| path.to_string()))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn scan_directory(path: String, pattern: String) -> Result<Vec<String>, String> {
|
||||
use glob::glob;
|
||||
@@ -300,7 +351,12 @@ fn main() {
|
||||
open_project,
|
||||
save_project,
|
||||
export_binary,
|
||||
create_directory,
|
||||
write_file_content,
|
||||
path_exists,
|
||||
open_project_dialog,
|
||||
save_scene_dialog,
|
||||
open_scene_dialog,
|
||||
scan_directory,
|
||||
read_file_content,
|
||||
list_directory,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { Core, Scene } from '@esengine/ecs-framework';
|
||||
import { EditorPluginManager, UIRegistry, MessageHub, SerializerRegistry, EntityStoreService, ComponentRegistry, LocaleService, ProjectService, ComponentDiscoveryService, ComponentLoaderService, PropertyMetadataService, LogService, SettingsRegistry } from '@esengine/editor-core';
|
||||
import { EditorPluginManager, UIRegistry, MessageHub, SerializerRegistry, EntityStoreService, ComponentRegistry, LocaleService, ProjectService, ComponentDiscoveryService, PropertyMetadataService, LogService, SettingsRegistry, SceneManagerService } from '@esengine/editor-core';
|
||||
import { SceneInspectorPlugin } from './plugins/SceneInspectorPlugin';
|
||||
import { ProfilerPlugin } from './plugins/ProfilerPlugin';
|
||||
import { StartupPage } from './components/StartupPage';
|
||||
@@ -13,10 +13,13 @@ import { ProfilerWindow } from './components/ProfilerWindow';
|
||||
import { PortManager } from './components/PortManager';
|
||||
import { SettingsWindow } from './components/SettingsWindow';
|
||||
import { AboutDialog } from './components/AboutDialog';
|
||||
import { ErrorDialog } from './components/ErrorDialog';
|
||||
import { ConfirmDialog } from './components/ConfirmDialog';
|
||||
import { Viewport } from './components/Viewport';
|
||||
import { MenuBar } from './components/MenuBar';
|
||||
import { DockContainer, DockablePanel } from './components/DockContainer';
|
||||
import { TauriAPI } from './api/tauri';
|
||||
import { TauriFileAPI } from './adapters/TauriFileAPI';
|
||||
import { SettingsService } from './services/SettingsService';
|
||||
import { checkForUpdatesOnStartup } from './utils/updater';
|
||||
import { useLocale } from './hooks/useLocale';
|
||||
@@ -44,6 +47,7 @@ function App() {
|
||||
const [logService, setLogService] = useState<LogService | null>(null);
|
||||
const [uiRegistry, setUiRegistry] = useState<UIRegistry | null>(null);
|
||||
const [settingsRegistry, setSettingsRegistry] = useState<SettingsRegistry | null>(null);
|
||||
const [sceneManager, setSceneManager] = useState<SceneManagerService | null>(null);
|
||||
const { t, locale, changeLocale } = useLocale();
|
||||
const [status, setStatus] = useState(t('header.status.initializing'));
|
||||
const [panels, setPanels] = useState<DockablePanel[]>([]);
|
||||
@@ -55,6 +59,14 @@ function App() {
|
||||
const [pluginUpdateTrigger, setPluginUpdateTrigger] = useState(0);
|
||||
const [isRemoteConnected, setIsRemoteConnected] = useState(false);
|
||||
const [isProfilerMode, setIsProfilerMode] = useState(false);
|
||||
const [errorDialog, setErrorDialog] = useState<{ title: string; message: string } | null>(null);
|
||||
const [confirmDialog, setConfirmDialog] = useState<{
|
||||
title: string;
|
||||
message: string;
|
||||
confirmText: string;
|
||||
cancelText: string;
|
||||
onConfirm: () => void;
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
// 禁用默认右键菜单
|
||||
@@ -72,12 +84,10 @@ function App() {
|
||||
useEffect(() => {
|
||||
if (messageHub) {
|
||||
const unsubscribeEnabled = messageHub.subscribe('plugin:enabled', () => {
|
||||
console.log('[App] Plugin enabled, updating panels');
|
||||
setPluginUpdateTrigger(prev => prev + 1);
|
||||
});
|
||||
|
||||
const unsubscribeDisabled = messageHub.subscribe('plugin:disabled', () => {
|
||||
console.log('[App] Plugin disabled, updating panels');
|
||||
setPluginUpdateTrigger(prev => prev + 1);
|
||||
});
|
||||
|
||||
@@ -94,13 +104,11 @@ function App() {
|
||||
const profilerService = (window as any).__PROFILER_SERVICE__;
|
||||
if (profilerService && profilerService.isConnected()) {
|
||||
if (!isRemoteConnected) {
|
||||
console.log('[App] Remote game connected');
|
||||
setIsRemoteConnected(true);
|
||||
setStatus(t('header.status.remoteConnected'));
|
||||
}
|
||||
} else {
|
||||
if (isRemoteConnected) {
|
||||
console.log('[App] Remote game disconnected');
|
||||
setIsRemoteConnected(false);
|
||||
if (projectLoaded) {
|
||||
const componentRegistry = Core.services.resolve(ComponentRegistry);
|
||||
@@ -123,13 +131,11 @@ function App() {
|
||||
const initializeEditor = async () => {
|
||||
// 使用 ref 防止 React StrictMode 的双重调用
|
||||
if (initRef.current) {
|
||||
console.log('[App] Already initialized via ref, skipping second initialization');
|
||||
return;
|
||||
}
|
||||
initRef.current = true;
|
||||
|
||||
try {
|
||||
console.log('[App] Starting editor initialization...');
|
||||
(window as any).__ECS_FRAMEWORK__ = await import('@esengine/ecs-framework');
|
||||
|
||||
const editorScene = new Scene();
|
||||
@@ -140,12 +146,13 @@ function App() {
|
||||
const serializerRegistry = new SerializerRegistry();
|
||||
const entityStore = new EntityStoreService(messageHub);
|
||||
const componentRegistry = new ComponentRegistry();
|
||||
const projectService = new ProjectService(messageHub);
|
||||
const fileAPI = new TauriFileAPI();
|
||||
const projectService = new ProjectService(messageHub, fileAPI);
|
||||
const componentDiscovery = new ComponentDiscoveryService(messageHub);
|
||||
const componentLoader = new ComponentLoaderService(messageHub, componentRegistry);
|
||||
const propertyMetadata = new PropertyMetadataService();
|
||||
const logService = new LogService();
|
||||
const settingsRegistry = new SettingsRegistry();
|
||||
const sceneManagerService = new SceneManagerService(messageHub, fileAPI, projectService);
|
||||
|
||||
// 监听远程日志事件
|
||||
window.addEventListener('profiler:remote-log', ((event: CustomEvent) => {
|
||||
@@ -160,10 +167,10 @@ function App() {
|
||||
Core.services.registerInstance(ComponentRegistry, componentRegistry);
|
||||
Core.services.registerInstance(ProjectService, projectService);
|
||||
Core.services.registerInstance(ComponentDiscoveryService, componentDiscovery);
|
||||
Core.services.registerInstance(ComponentLoaderService, componentLoader);
|
||||
Core.services.registerInstance(PropertyMetadataService, propertyMetadata);
|
||||
Core.services.registerInstance(LogService, logService);
|
||||
Core.services.registerInstance(SettingsRegistry, settingsRegistry);
|
||||
Core.services.registerInstance(SceneManagerService, sceneManagerService);
|
||||
|
||||
const pluginMgr = new EditorPluginManager();
|
||||
pluginMgr.initialize(coreInstance, Core.services);
|
||||
@@ -172,11 +179,6 @@ function App() {
|
||||
await pluginMgr.installEditor(new SceneInspectorPlugin());
|
||||
await pluginMgr.installEditor(new ProfilerPlugin());
|
||||
|
||||
console.log('[App] All plugins installed');
|
||||
console.log('[App] UIRegistry menu count:', uiRegistry.getAllMenus().length);
|
||||
console.log('[App] UIRegistry all menus:', uiRegistry.getAllMenus());
|
||||
console.log('[App] UIRegistry window menus:', uiRegistry.getChildMenus('window'));
|
||||
|
||||
messageHub.subscribe('ui:openWindow', (data: any) => {
|
||||
if (data.windowId === 'profiler') {
|
||||
setShowProfiler(true);
|
||||
@@ -185,8 +187,7 @@ function App() {
|
||||
}
|
||||
});
|
||||
|
||||
const greeting = await TauriAPI.greet('Developer');
|
||||
console.log(greeting);
|
||||
await TauriAPI.greet('Developer');
|
||||
|
||||
setInitialized(true);
|
||||
setPluginManager(pluginMgr);
|
||||
@@ -195,6 +196,7 @@ function App() {
|
||||
setLogService(logService);
|
||||
setUiRegistry(uiRegistry);
|
||||
setSettingsRegistry(settingsRegistry);
|
||||
setSceneManager(sceneManagerService);
|
||||
setStatus(t('header.status.ready'));
|
||||
|
||||
// Check for updates on startup (after 3 seconds)
|
||||
@@ -211,13 +213,11 @@ function App() {
|
||||
const handleOpenRecentProject = async (projectPath: string) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setLoadingMessage(locale === 'zh' ? '正在打开项目...' : 'Opening project...');
|
||||
setLoadingMessage(locale === 'zh' ? '步骤 1/2: 打开项目配置...' : 'Step 1/2: Opening project config...');
|
||||
|
||||
const projectService = Core.services.resolve(ProjectService);
|
||||
const discoveryService = Core.services.resolve(ComponentDiscoveryService);
|
||||
const loaderService = Core.services.resolve(ComponentLoaderService);
|
||||
|
||||
if (!projectService || !discoveryService || !loaderService) {
|
||||
if (!projectService) {
|
||||
console.error('Required services not available');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
@@ -231,31 +231,27 @@ function App() {
|
||||
body: JSON.stringify({ path: projectPath })
|
||||
});
|
||||
|
||||
setLoadingMessage(locale === 'zh' ? '正在扫描组件...' : 'Scanning components...');
|
||||
setStatus('Scanning components...');
|
||||
setStatus(t('header.status.projectOpened'));
|
||||
|
||||
const componentsPath = projectService.getComponentsPath();
|
||||
if (componentsPath) {
|
||||
const componentInfos = await discoveryService.scanComponents({
|
||||
basePath: componentsPath,
|
||||
pattern: '**/*.ts',
|
||||
scanFunction: TauriAPI.scanDirectory,
|
||||
readFunction: TauriAPI.readFileContent
|
||||
});
|
||||
setLoadingMessage(locale === 'zh' ? '步骤 2/2: 加载场景...' : 'Step 2/2: Loading scene...');
|
||||
|
||||
setLoadingMessage(locale === 'zh' ? `正在加载 ${componentInfos.length} 个组件...` : `Loading ${componentInfos.length} components...`);
|
||||
setStatus(`Loading ${componentInfos.length} components...`);
|
||||
const sceneManagerService = Core.services.resolve(SceneManagerService);
|
||||
const scenesPath = projectService.getScenesPath();
|
||||
if (scenesPath && sceneManagerService) {
|
||||
try {
|
||||
const sceneFiles = await TauriAPI.scanDirectory(scenesPath, '*.ecs');
|
||||
|
||||
const modulePathTransform = (filePath: string) => {
|
||||
const relativePath = filePath.replace(projectPath, '').replace(/\\/g, '/');
|
||||
return `/@user-project${relativePath}`;
|
||||
};
|
||||
if (sceneFiles.length > 0) {
|
||||
const defaultScenePath = projectService.getDefaultScenePath();
|
||||
const sceneToLoad = sceneFiles.find(f => f === defaultScenePath) || sceneFiles[0];
|
||||
|
||||
await loaderService.loadComponents(componentInfos, modulePathTransform);
|
||||
|
||||
setStatus(t('header.status.projectOpened') + ` (${componentInfos.length} components registered)`);
|
||||
} else {
|
||||
setStatus(t('header.status.projectOpened'));
|
||||
await sceneManagerService.openScene(sceneToLoad);
|
||||
} else {
|
||||
await sceneManagerService.newScene();
|
||||
}
|
||||
} catch (error) {
|
||||
await sceneManagerService.newScene();
|
||||
}
|
||||
}
|
||||
|
||||
const settings = SettingsService.getInstance();
|
||||
@@ -268,6 +264,14 @@ function App() {
|
||||
console.error('Failed to open project:', error);
|
||||
setStatus(t('header.status.failed'));
|
||||
setIsLoading(false);
|
||||
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
setErrorDialog({
|
||||
title: locale === 'zh' ? '打开项目失败' : 'Failed to Open Project',
|
||||
message: locale === 'zh'
|
||||
? `无法打开项目:\n${errorMessage}`
|
||||
: `Failed to open project:\n${errorMessage}`
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -283,7 +287,72 @@ function App() {
|
||||
};
|
||||
|
||||
const handleCreateProject = async () => {
|
||||
console.log('Create project not implemented yet');
|
||||
let selectedProjectPath: string | null = null;
|
||||
|
||||
try {
|
||||
selectedProjectPath = await TauriAPI.openProjectDialog();
|
||||
if (!selectedProjectPath) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setLoadingMessage(locale === 'zh' ? '正在创建项目...' : 'Creating project...');
|
||||
|
||||
const projectService = Core.services.resolve(ProjectService);
|
||||
if (!projectService) {
|
||||
console.error('ProjectService not available');
|
||||
setIsLoading(false);
|
||||
setErrorDialog({
|
||||
title: locale === 'zh' ? '创建项目失败' : 'Failed to Create Project',
|
||||
message: locale === 'zh' ? '项目服务不可用,请重启编辑器' : 'Project service is not available. Please restart the editor.'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await projectService.createProject(selectedProjectPath);
|
||||
|
||||
setLoadingMessage(locale === 'zh' ? '项目创建成功,正在打开...' : 'Project created, opening...');
|
||||
|
||||
await handleOpenRecentProject(selectedProjectPath);
|
||||
} catch (error) {
|
||||
console.error('Failed to create project:', error);
|
||||
setIsLoading(false);
|
||||
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
const pathToOpen = selectedProjectPath;
|
||||
|
||||
if (errorMessage.includes('already exists') && pathToOpen) {
|
||||
setConfirmDialog({
|
||||
title: locale === 'zh' ? '项目已存在' : 'Project Already Exists',
|
||||
message: locale === 'zh'
|
||||
? '该目录下已存在 ECS 项目,是否要打开该项目?'
|
||||
: 'An ECS project already exists in this directory. Do you want to open it?',
|
||||
confirmText: locale === 'zh' ? '打开项目' : 'Open Project',
|
||||
cancelText: locale === 'zh' ? '取消' : 'Cancel',
|
||||
onConfirm: () => {
|
||||
setConfirmDialog(null);
|
||||
setIsLoading(true);
|
||||
setLoadingMessage(locale === 'zh' ? '正在打开项目...' : 'Opening project...');
|
||||
handleOpenRecentProject(pathToOpen).catch((err) => {
|
||||
console.error('Failed to open project:', err);
|
||||
setIsLoading(false);
|
||||
setErrorDialog({
|
||||
title: locale === 'zh' ? '打开项目失败' : 'Failed to Open Project',
|
||||
message: locale === 'zh'
|
||||
? `无法打开项目:\n${err instanceof Error ? err.message : String(err)}`
|
||||
: `Failed to open project:\n${err instanceof Error ? err.message : String(err)}`
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
setStatus(locale === 'zh' ? '创建项目失败' : 'Failed to create project');
|
||||
setErrorDialog({
|
||||
title: locale === 'zh' ? '创建项目失败' : 'Failed to Create Project',
|
||||
message: locale === 'zh'
|
||||
? `无法创建项目:\n${errorMessage}`
|
||||
: `Failed to create project:\n${errorMessage}`
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleProfilerMode = async () => {
|
||||
@@ -292,20 +361,109 @@ function App() {
|
||||
setStatus(t('header.status.profilerMode') || 'Profiler Mode - Waiting for connection...');
|
||||
};
|
||||
|
||||
const handleNewScene = () => {
|
||||
console.log('New scene not implemented yet');
|
||||
const handleNewScene = async () => {
|
||||
if (!sceneManager) {
|
||||
console.error('SceneManagerService not available');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await sceneManager.newScene();
|
||||
setStatus(locale === 'zh' ? '已创建新场景' : 'New scene created');
|
||||
} catch (error) {
|
||||
console.error('Failed to create new scene:', error);
|
||||
setStatus(locale === 'zh' ? '创建场景失败' : 'Failed to create scene');
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenScene = () => {
|
||||
console.log('Open scene not implemented yet');
|
||||
const handleOpenScene = async () => {
|
||||
if (!sceneManager) {
|
||||
console.error('SceneManagerService not available');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await sceneManager.openScene();
|
||||
const sceneState = sceneManager.getSceneState();
|
||||
setStatus(locale === 'zh' ? `已打开场景: ${sceneState.sceneName}` : `Scene opened: ${sceneState.sceneName}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to open scene:', error);
|
||||
setStatus(locale === 'zh' ? '打开场景失败' : 'Failed to open scene');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveScene = () => {
|
||||
console.log('Save scene not implemented yet');
|
||||
const handleOpenSceneByPath = useCallback(async (scenePath: string) => {
|
||||
console.log('[App] handleOpenSceneByPath called with:', scenePath);
|
||||
|
||||
if (!sceneManager) {
|
||||
console.error('SceneManagerService not available');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('[App] Opening scene:', scenePath);
|
||||
await sceneManager.openScene(scenePath);
|
||||
const sceneState = sceneManager.getSceneState();
|
||||
console.log('[App] Scene opened, state:', sceneState);
|
||||
setStatus(locale === 'zh' ? `已打开场景: ${sceneState.sceneName}` : `Scene opened: ${sceneState.sceneName}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to open scene:', error);
|
||||
setStatus(locale === 'zh' ? '打开场景失败' : 'Failed to open scene');
|
||||
setErrorDialog({
|
||||
title: locale === 'zh' ? '打开场景失败' : 'Failed to Open Scene',
|
||||
message: locale === 'zh'
|
||||
? `无法打开场景:\n${error instanceof Error ? error.message : String(error)}`
|
||||
: `Failed to open scene:\n${error instanceof Error ? error.message : String(error)}`
|
||||
});
|
||||
}
|
||||
}, [sceneManager, locale]);
|
||||
|
||||
const handleSaveScene = async () => {
|
||||
if (!sceneManager) {
|
||||
console.error('SceneManagerService not available');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await sceneManager.saveScene();
|
||||
const sceneState = sceneManager.getSceneState();
|
||||
setStatus(locale === 'zh' ? `已保存场景: ${sceneState.sceneName}` : `Scene saved: ${sceneState.sceneName}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to save scene:', error);
|
||||
setStatus(locale === 'zh' ? '保存场景失败' : 'Failed to save scene');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveSceneAs = () => {
|
||||
console.log('Save scene as not implemented yet');
|
||||
const handleSaveSceneAs = async () => {
|
||||
if (!sceneManager) {
|
||||
console.error('SceneManagerService not available');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await sceneManager.saveSceneAs();
|
||||
const sceneState = sceneManager.getSceneState();
|
||||
setStatus(locale === 'zh' ? `已保存场景: ${sceneState.sceneName}` : `Scene saved: ${sceneState.sceneName}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to save scene as:', error);
|
||||
setStatus(locale === 'zh' ? '另存场景失败' : 'Failed to save scene as');
|
||||
}
|
||||
};
|
||||
|
||||
const handleExportScene = async () => {
|
||||
if (!sceneManager) {
|
||||
console.error('SceneManagerService not available');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await sceneManager.exportScene();
|
||||
const sceneState = sceneManager.getSceneState();
|
||||
setStatus(locale === 'zh' ? `已导出场景: ${sceneState.sceneName}` : `Scene exported: ${sceneState.sceneName}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to export scene:', error);
|
||||
setStatus(locale === 'zh' ? '导出场景失败' : 'Failed to export scene');
|
||||
}
|
||||
};
|
||||
|
||||
const handleCloseProject = () => {
|
||||
@@ -391,7 +549,7 @@ function App() {
|
||||
id: 'assets',
|
||||
title: locale === 'zh' ? '资产' : 'Assets',
|
||||
position: 'bottom',
|
||||
content: <AssetBrowser projectPath={currentProjectPath} locale={locale} />,
|
||||
content: <AssetBrowser projectPath={currentProjectPath} locale={locale} onOpenScene={handleOpenSceneByPath} />,
|
||||
closable: false
|
||||
},
|
||||
{
|
||||
@@ -436,7 +594,7 @@ function App() {
|
||||
console.log('[App] Loading plugin panels:', pluginPanels);
|
||||
setPanels([...corePanels, ...pluginPanels]);
|
||||
}
|
||||
}, [projectLoaded, entityStore, messageHub, logService, uiRegistry, pluginManager, locale, currentProjectPath, t, pluginUpdateTrigger, isProfilerMode]);
|
||||
}, [projectLoaded, entityStore, messageHub, logService, uiRegistry, pluginManager, locale, currentProjectPath, t, pluginUpdateTrigger, isProfilerMode, handleOpenSceneByPath]);
|
||||
|
||||
const handlePanelMove = (panelId: string, newPosition: any) => {
|
||||
setPanels(prevPanels =>
|
||||
@@ -477,6 +635,23 @@ function App() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{errorDialog && (
|
||||
<ErrorDialog
|
||||
title={errorDialog.title}
|
||||
message={errorDialog.message}
|
||||
onClose={() => setErrorDialog(null)}
|
||||
/>
|
||||
)}
|
||||
{confirmDialog && (
|
||||
<ConfirmDialog
|
||||
title={confirmDialog.title}
|
||||
message={confirmDialog.message}
|
||||
confirmText={confirmDialog.confirmText}
|
||||
cancelText={confirmDialog.cancelText}
|
||||
onConfirm={confirmDialog.onConfirm}
|
||||
onCancel={() => setConfirmDialog(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -543,6 +718,14 @@ function App() {
|
||||
{showAbout && (
|
||||
<AboutDialog onClose={() => setShowAbout(false)} locale={locale} />
|
||||
)}
|
||||
|
||||
{errorDialog && (
|
||||
<ErrorDialog
|
||||
title={errorDialog.title}
|
||||
message={errorDialog.message}
|
||||
onClose={() => setErrorDialog(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
41
packages/editor-app/src/adapters/TauriFileAPI.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import type { IFileAPI } from '@esengine/editor-core';
|
||||
import { TauriAPI } from '../api/tauri';
|
||||
|
||||
/**
|
||||
* Tauri 文件 API 适配器
|
||||
*
|
||||
* 实现 IFileAPI 接口,连接 editor-core 和 Tauri 后端
|
||||
*/
|
||||
export class TauriFileAPI implements IFileAPI {
|
||||
public async openSceneDialog(): Promise<string | null> {
|
||||
return await TauriAPI.openSceneDialog();
|
||||
}
|
||||
|
||||
public async saveSceneDialog(defaultName?: string): Promise<string | null> {
|
||||
return await TauriAPI.saveSceneDialog(defaultName);
|
||||
}
|
||||
|
||||
public async readFileContent(path: string): Promise<string> {
|
||||
return await TauriAPI.readFileContent(path);
|
||||
}
|
||||
|
||||
public async saveProject(path: string, data: string): Promise<void> {
|
||||
return await TauriAPI.saveProject(path, data);
|
||||
}
|
||||
|
||||
public async exportBinary(data: Uint8Array, path: string): Promise<void> {
|
||||
return await TauriAPI.exportBinary(data, path);
|
||||
}
|
||||
|
||||
public async createDirectory(path: string): Promise<void> {
|
||||
return await TauriAPI.createDirectory(path);
|
||||
}
|
||||
|
||||
public async writeFileContent(path: string, content: string): Promise<void> {
|
||||
return await TauriAPI.writeFileContent(path, content);
|
||||
}
|
||||
|
||||
public async pathExists(path: string): Promise<boolean> {
|
||||
return await TauriAPI.pathExists(path);
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,49 @@ export class TauriAPI {
|
||||
static async toggleDevtools(): Promise<void> {
|
||||
return await invoke<void>('toggle_devtools');
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开保存场景对话框
|
||||
* @param defaultName 默认文件名(可选)
|
||||
* @returns 用户选择的文件路径,取消则返回 null
|
||||
*/
|
||||
static async saveSceneDialog(defaultName?: string): Promise<string | null> {
|
||||
return await invoke<string | null>('save_scene_dialog', { defaultName });
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开场景文件选择对话框
|
||||
* @returns 用户选择的文件路径,取消则返回 null
|
||||
*/
|
||||
static async openSceneDialog(): Promise<string | null> {
|
||||
return await invoke<string | null>('open_scene_dialog');
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建目录
|
||||
* @param path 目录路径
|
||||
*/
|
||||
static async createDirectory(path: string): Promise<void> {
|
||||
return await invoke<void>('create_directory', { path });
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入文件内容
|
||||
* @param path 文件路径
|
||||
* @param content 文件内容
|
||||
*/
|
||||
static async writeFileContent(path: string, content: string): Promise<void> {
|
||||
return await invoke<void>('write_file_content', { path, content });
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查路径是否存在
|
||||
* @param path 文件或目录路径
|
||||
* @returns 路径是否存在
|
||||
*/
|
||||
static async pathExists(path: string): Promise<boolean> {
|
||||
return await invoke<boolean>('path_exists', { path });
|
||||
}
|
||||
}
|
||||
|
||||
export interface DirectoryEntry {
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
.modal-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-color: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.add-component-dialog {
|
||||
background-color: #2d2d2d;
|
||||
border-radius: 8px;
|
||||
width: 500px;
|
||||
max-width: 90%;
|
||||
max-height: 80vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.dialog-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid #404040;
|
||||
}
|
||||
|
||||
.dialog-header h3 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: #aaa;
|
||||
font-size: 24px;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
line-height: 20px;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
.close-btn:hover {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.dialog-content {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
padding: 16px 20px;
|
||||
}
|
||||
|
||||
.component-filter {
|
||||
width: 100%;
|
||||
padding: 8px 12px;
|
||||
background-color: #1e1e1e;
|
||||
border: 1px solid #404040;
|
||||
border-radius: 4px;
|
||||
color: #fff;
|
||||
font-size: 14px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.component-filter:focus {
|
||||
outline: none;
|
||||
border-color: #007acc;
|
||||
}
|
||||
|
||||
.component-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
min-height: 200px;
|
||||
max-height: 400px;
|
||||
}
|
||||
|
||||
.component-category {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.category-header {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: #888;
|
||||
text-transform: uppercase;
|
||||
margin-bottom: 8px;
|
||||
padding-bottom: 4px;
|
||||
border-bottom: 1px solid #404040;
|
||||
}
|
||||
|
||||
.component-option {
|
||||
padding: 10px 12px;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
margin-bottom: 4px;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
|
||||
.component-option:hover {
|
||||
background-color: #3a3a3a;
|
||||
}
|
||||
|
||||
.component-option.selected {
|
||||
background-color: #094771;
|
||||
border: 1px solid #007acc;
|
||||
}
|
||||
|
||||
.component-name {
|
||||
font-size: 14px;
|
||||
color: #fff;
|
||||
font-weight: 500;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.component-description {
|
||||
font-size: 12px;
|
||||
color: #aaa;
|
||||
}
|
||||
|
||||
.empty-message {
|
||||
color: #888;
|
||||
text-align: center;
|
||||
padding: 40px 20px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.dialog-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
padding: 16px 20px;
|
||||
border-top: 1px solid #404040;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 8px 16px;
|
||||
border-radius: 4px;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-cancel {
|
||||
background-color: #3a3a3a;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.btn-cancel:hover:not(:disabled) {
|
||||
background-color: #4a4a4a;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: #007acc;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.btn-primary:hover:not(:disabled) {
|
||||
background-color: #0098ff;
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Entity } from '@esengine/ecs-framework';
|
||||
import { ComponentRegistry, ComponentTypeInfo } from '@esengine/editor-core';
|
||||
import './AddComponent.css';
|
||||
|
||||
interface AddComponentProps {
|
||||
entity: Entity;
|
||||
componentRegistry: ComponentRegistry;
|
||||
onAdd: (componentName: string) => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export function AddComponent({ entity, componentRegistry, onAdd, onCancel }: AddComponentProps) {
|
||||
const [components, setComponents] = useState<ComponentTypeInfo[]>([]);
|
||||
const [selectedComponent, setSelectedComponent] = useState<string | null>(null);
|
||||
const [filter, setFilter] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (!componentRegistry) {
|
||||
console.error('ComponentRegistry is null');
|
||||
return;
|
||||
}
|
||||
|
||||
const allComponents = componentRegistry.getAllComponents();
|
||||
console.log('All registered components:', allComponents);
|
||||
|
||||
allComponents.forEach(comp => {
|
||||
console.log(`Component ${comp.name}: has type = ${!!comp.type}`);
|
||||
});
|
||||
|
||||
const existingComponentNames = entity.components.map(c => c.constructor.name);
|
||||
|
||||
const availableComponents = allComponents.filter(
|
||||
comp => comp.type && !existingComponentNames.includes(comp.name)
|
||||
);
|
||||
|
||||
console.log('Available components to add:', availableComponents);
|
||||
console.log('Components filtered out:', allComponents.filter(comp => !comp.type).map(c => c.name));
|
||||
setComponents(availableComponents);
|
||||
}, [entity, componentRegistry]);
|
||||
|
||||
const filteredComponents = components.filter(comp =>
|
||||
comp.name.toLowerCase().includes(filter.toLowerCase()) ||
|
||||
comp.category?.toLowerCase().includes(filter.toLowerCase())
|
||||
);
|
||||
|
||||
const handleAdd = () => {
|
||||
if (selectedComponent) {
|
||||
onAdd(selectedComponent);
|
||||
}
|
||||
};
|
||||
|
||||
const groupedComponents = filteredComponents.reduce((groups, comp) => {
|
||||
const category = comp.category || 'Other';
|
||||
if (!groups[category]) {
|
||||
groups[category] = [];
|
||||
}
|
||||
groups[category].push(comp);
|
||||
return groups;
|
||||
}, {} as Record<string, ComponentTypeInfo[]>);
|
||||
|
||||
return (
|
||||
<div className="modal-overlay" onClick={onCancel}>
|
||||
<div className="add-component-dialog" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="dialog-header">
|
||||
<h3>Add Component</h3>
|
||||
<button className="close-btn" onClick={onCancel}>×</button>
|
||||
</div>
|
||||
|
||||
<div className="dialog-content">
|
||||
<input
|
||||
type="text"
|
||||
className="component-filter"
|
||||
placeholder="Search components..."
|
||||
value={filter}
|
||||
onChange={(e) => setFilter(e.target.value)}
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
<div className="component-list">
|
||||
{Object.keys(groupedComponents).length === 0 ? (
|
||||
<div className="empty-message">No available components</div>
|
||||
) : (
|
||||
Object.entries(groupedComponents).map(([category, comps]) => (
|
||||
<div key={category} className="component-category">
|
||||
<div className="category-header">{category}</div>
|
||||
{comps.map(comp => (
|
||||
<div
|
||||
key={comp.name}
|
||||
className={`component-option ${selectedComponent === comp.name ? 'selected' : ''}`}
|
||||
onClick={() => setSelectedComponent(comp.name)}
|
||||
onDoubleClick={handleAdd}
|
||||
>
|
||||
<div className="component-name">{comp.name}</div>
|
||||
{comp.description && (
|
||||
<div className="component-description">{comp.description}</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="dialog-footer">
|
||||
<button className="btn btn-cancel" onClick={onCancel}>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-primary"
|
||||
onClick={handleAdd}
|
||||
disabled={!selectedComponent}
|
||||
>
|
||||
Add Component
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Core } from '@esengine/ecs-framework';
|
||||
import { MessageHub } from '@esengine/editor-core';
|
||||
import { TauriAPI, DirectoryEntry } from '../api/tauri';
|
||||
import { FileTree } from './FileTree';
|
||||
import { ResizablePanel } from './ResizablePanel';
|
||||
@@ -14,11 +16,12 @@ interface AssetItem {
|
||||
interface AssetBrowserProps {
|
||||
projectPath: string | null;
|
||||
locale: string;
|
||||
onOpenScene?: (scenePath: string) => void;
|
||||
}
|
||||
|
||||
type ViewMode = 'tree-split' | 'tree-only';
|
||||
|
||||
export function AssetBrowser({ projectPath, locale }: AssetBrowserProps) {
|
||||
export function AssetBrowser({ projectPath, locale, onOpenScene }: AssetBrowserProps) {
|
||||
const [viewMode, setViewMode] = useState<ViewMode>('tree-split');
|
||||
const [selectedPath, setSelectedPath] = useState<string | null>(null);
|
||||
const [assets, setAssets] = useState<AssetItem[]>([]);
|
||||
@@ -67,6 +70,29 @@ export function AssetBrowser({ projectPath, locale }: AssetBrowserProps) {
|
||||
}
|
||||
}, [projectPath, viewMode]);
|
||||
|
||||
// Listen for asset reveal requests
|
||||
useEffect(() => {
|
||||
const messageHub = Core.services.resolve(MessageHub);
|
||||
if (!messageHub) return;
|
||||
|
||||
const unsubscribe = messageHub.subscribe('asset:reveal', (data: any) => {
|
||||
const filePath = data.path;
|
||||
if (filePath) {
|
||||
setSelectedPath(filePath);
|
||||
|
||||
if (viewMode === 'tree-split') {
|
||||
const lastSlashIndex = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
|
||||
const dirPath = lastSlashIndex > 0 ? filePath.substring(0, lastSlashIndex) : null;
|
||||
if (dirPath) {
|
||||
loadAssets(dirPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return () => unsubscribe();
|
||||
}, [viewMode]);
|
||||
|
||||
const loadAssets = async (path: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
@@ -105,7 +131,11 @@ export function AssetBrowser({ projectPath, locale }: AssetBrowserProps) {
|
||||
};
|
||||
|
||||
const handleAssetDoubleClick = (asset: AssetItem) => {
|
||||
console.log('Open asset:', asset);
|
||||
if (asset.type === 'file' && asset.extension === 'ecs') {
|
||||
if (onOpenScene) {
|
||||
onOpenScene(asset.path);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const filteredAssets = searchQuery
|
||||
|
||||
37
packages/editor-app/src/components/ConfirmDialog.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import { X } from 'lucide-react';
|
||||
import '../styles/ConfirmDialog.css';
|
||||
|
||||
interface ConfirmDialogProps {
|
||||
title: string;
|
||||
message: string;
|
||||
confirmText: string;
|
||||
cancelText: string;
|
||||
onConfirm: () => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export function ConfirmDialog({ title, message, confirmText, cancelText, onConfirm, onCancel }: ConfirmDialogProps) {
|
||||
return (
|
||||
<div className="confirm-dialog-overlay" onClick={onCancel}>
|
||||
<div className="confirm-dialog" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="confirm-dialog-header">
|
||||
<h2>{title}</h2>
|
||||
<button className="close-btn" onClick={onCancel}>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="confirm-dialog-content">
|
||||
<p>{message}</p>
|
||||
</div>
|
||||
<div className="confirm-dialog-footer">
|
||||
<button className="confirm-dialog-btn cancel" onClick={onCancel}>
|
||||
{cancelText}
|
||||
</button>
|
||||
<button className="confirm-dialog-btn confirm" onClick={onConfirm}>
|
||||
{confirmText}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Entity, Core } from '@esengine/ecs-framework';
|
||||
import { EntityStoreService, MessageHub, ComponentRegistry } from '@esengine/editor-core';
|
||||
import { AddComponent } from './AddComponent';
|
||||
import { PropertyInspector } from './PropertyInspector';
|
||||
import { FileSearch, Plus, ChevronDown, ChevronRight, X, Settings } from 'lucide-react';
|
||||
import { FileSearch, ChevronDown, ChevronRight, X, Settings } from 'lucide-react';
|
||||
import '../styles/EntityInspector.css';
|
||||
|
||||
interface EntityInspectorProps {
|
||||
@@ -15,22 +14,21 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit
|
||||
const [selectedEntity, setSelectedEntity] = useState<Entity | null>(null);
|
||||
const [remoteEntity, setRemoteEntity] = useState<any | null>(null);
|
||||
const [remoteEntityDetails, setRemoteEntityDetails] = useState<any | null>(null);
|
||||
const [showAddComponent, setShowAddComponent] = useState(false);
|
||||
const [expandedComponents, setExpandedComponents] = useState<Set<number>>(new Set());
|
||||
const [componentVersion, setComponentVersion] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const handleSelection = (data: { entity: Entity | null }) => {
|
||||
setSelectedEntity(data.entity);
|
||||
setRemoteEntity(null);
|
||||
setRemoteEntityDetails(null);
|
||||
setShowAddComponent(false);
|
||||
setComponentVersion(0);
|
||||
};
|
||||
|
||||
const handleRemoteSelection = (data: { entity: any }) => {
|
||||
setRemoteEntity(data.entity);
|
||||
setRemoteEntityDetails(null);
|
||||
setSelectedEntity(null);
|
||||
setShowAddComponent(false);
|
||||
};
|
||||
|
||||
const handleEntityDetails = (event: Event) => {
|
||||
@@ -39,38 +37,26 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit
|
||||
setRemoteEntityDetails(details);
|
||||
};
|
||||
|
||||
const handleComponentChange = () => {
|
||||
setComponentVersion(prev => prev + 1);
|
||||
};
|
||||
|
||||
const unsubSelect = messageHub.subscribe('entity:selected', handleSelection);
|
||||
const unsubRemoteSelect = messageHub.subscribe('remote-entity:selected', handleRemoteSelection);
|
||||
const unsubComponentAdded = messageHub.subscribe('component:added', handleComponentChange);
|
||||
const unsubComponentRemoved = messageHub.subscribe('component:removed', handleComponentChange);
|
||||
|
||||
window.addEventListener('profiler:entity-details', handleEntityDetails);
|
||||
|
||||
return () => {
|
||||
unsubSelect();
|
||||
unsubRemoteSelect();
|
||||
unsubComponentAdded();
|
||||
unsubComponentRemoved();
|
||||
window.removeEventListener('profiler:entity-details', handleEntityDetails);
|
||||
};
|
||||
}, [messageHub]);
|
||||
|
||||
const handleAddComponent = (componentName: string) => {
|
||||
if (!selectedEntity) return;
|
||||
|
||||
const componentRegistry = Core.services.resolve(ComponentRegistry);
|
||||
if (!componentRegistry) {
|
||||
console.error('ComponentRegistry not found');
|
||||
return;
|
||||
}
|
||||
|
||||
const component = componentRegistry.createInstance(componentName);
|
||||
|
||||
if (component) {
|
||||
selectedEntity.addComponent(component);
|
||||
messageHub.publish('component:added', { entity: selectedEntity, component });
|
||||
setShowAddComponent(false);
|
||||
} else {
|
||||
console.error('Failed to create component instance for:', componentName);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveComponent = (index: number) => {
|
||||
if (!selectedEntity) return;
|
||||
const component = selectedEntity.components[index];
|
||||
@@ -481,19 +467,12 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit
|
||||
<div className="section-header">
|
||||
<Settings size={12} className="section-icon" />
|
||||
<span>Components ({components.length})</span>
|
||||
<button
|
||||
className="add-component-btn"
|
||||
onClick={() => setShowAddComponent(true)}
|
||||
title="Add Component"
|
||||
>
|
||||
<Plus size={12} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="section-content">
|
||||
{components.length === 0 ? (
|
||||
<div className="empty-state-small">No components</div>
|
||||
) : (
|
||||
<ul className="component-list">
|
||||
<ul className="component-list" key={componentVersion}>
|
||||
{components.map((component, index) => {
|
||||
const isExpanded = expandedComponents.has(index);
|
||||
return (
|
||||
@@ -534,15 +513,6 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showAddComponent && selectedEntity && (
|
||||
<AddComponent
|
||||
entity={selectedEntity}
|
||||
componentRegistry={Core.services.resolve(ComponentRegistry)}
|
||||
onAdd={handleAddComponent}
|
||||
onCancel={() => setShowAddComponent(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
31
packages/editor-app/src/components/ErrorDialog.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import { X } from 'lucide-react';
|
||||
import '../styles/ErrorDialog.css';
|
||||
|
||||
interface ErrorDialogProps {
|
||||
title: string;
|
||||
message: string;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function ErrorDialog({ title, message, onClose }: ErrorDialogProps) {
|
||||
return (
|
||||
<div className="error-dialog-overlay" onClick={onClose}>
|
||||
<div className="error-dialog" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="error-dialog-header">
|
||||
<h2>{title}</h2>
|
||||
<button className="close-btn" onClick={onClose}>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="error-dialog-content">
|
||||
<p>{message}</p>
|
||||
</div>
|
||||
<div className="error-dialog-footer">
|
||||
<button className="error-dialog-btn" onClick={onClose}>
|
||||
确定
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Entity } from '@esengine/ecs-framework';
|
||||
import { EntityStoreService, MessageHub } from '@esengine/editor-core';
|
||||
import { Entity, Core } from '@esengine/ecs-framework';
|
||||
import { EntityStoreService, MessageHub, SceneManagerService } from '@esengine/editor-core';
|
||||
import { useLocale } from '../hooks/useLocale';
|
||||
import { Box, Layers, Wifi, Search } from 'lucide-react';
|
||||
import { Box, Layers, Wifi, Search, Plus, Trash2 } from 'lucide-react';
|
||||
import { ProfilerService, RemoteEntity } from '../services/ProfilerService';
|
||||
import { confirm } from '@tauri-apps/plugin-dialog';
|
||||
import '../styles/SceneHierarchy.css';
|
||||
|
||||
interface SceneHierarchyProps {
|
||||
@@ -17,7 +18,51 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
|
||||
const [isRemoteConnected, setIsRemoteConnected] = useState(false);
|
||||
const [selectedId, setSelectedId] = useState<number | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const { t } = useLocale();
|
||||
const [sceneName, setSceneName] = useState<string>('Untitled');
|
||||
const [sceneFilePath, setSceneFilePath] = useState<string | null>(null);
|
||||
const [isSceneModified, setIsSceneModified] = useState<boolean>(false);
|
||||
const { t, locale } = useLocale();
|
||||
|
||||
// Subscribe to scene changes
|
||||
useEffect(() => {
|
||||
const sceneManager = Core.services.resolve(SceneManagerService);
|
||||
|
||||
const updateSceneInfo = () => {
|
||||
if (sceneManager) {
|
||||
const state = sceneManager.getSceneState();
|
||||
setSceneName(state.sceneName);
|
||||
setIsSceneModified(state.isModified);
|
||||
}
|
||||
};
|
||||
|
||||
updateSceneInfo();
|
||||
|
||||
const unsubLoaded = messageHub.subscribe('scene:loaded', (data: any) => {
|
||||
if (data.sceneName) {
|
||||
setSceneName(data.sceneName);
|
||||
setSceneFilePath(data.path || null);
|
||||
setIsSceneModified(data.isModified || false);
|
||||
} else {
|
||||
updateSceneInfo();
|
||||
}
|
||||
});
|
||||
const unsubNew = messageHub.subscribe('scene:new', () => {
|
||||
updateSceneInfo();
|
||||
});
|
||||
const unsubSaved = messageHub.subscribe('scene:saved', () => {
|
||||
updateSceneInfo();
|
||||
});
|
||||
const unsubModified = messageHub.subscribe('scene:modified', () => {
|
||||
updateSceneInfo();
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubLoaded();
|
||||
unsubNew();
|
||||
unsubSaved();
|
||||
unsubModified();
|
||||
};
|
||||
}, [messageHub]);
|
||||
|
||||
// Subscribe to local entity changes
|
||||
useEffect(() => {
|
||||
@@ -107,6 +152,57 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
|
||||
});
|
||||
};
|
||||
|
||||
const handleSceneNameClick = () => {
|
||||
if (sceneFilePath) {
|
||||
messageHub.publish('asset:reveal', { path: sceneFilePath });
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateEntity = () => {
|
||||
const scene = Core.scene;
|
||||
if (!scene) return;
|
||||
|
||||
const entityCount = entityStore.getAllEntities().length;
|
||||
const entityName = `Entity ${entityCount + 1}`;
|
||||
const entity = scene.createEntity(entityName);
|
||||
entityStore.addEntity(entity);
|
||||
entityStore.selectEntity(entity);
|
||||
};
|
||||
|
||||
const handleDeleteEntity = async () => {
|
||||
if (!selectedId) return;
|
||||
|
||||
const entity = entityStore.getEntity(selectedId);
|
||||
if (!entity) return;
|
||||
|
||||
const confirmed = await confirm(
|
||||
locale === 'zh'
|
||||
? `确定要删除实体 "${entity.name}" 吗?此操作无法撤销。`
|
||||
: `Are you sure you want to delete entity "${entity.name}"? This action cannot be undone.`,
|
||||
{
|
||||
title: locale === 'zh' ? '删除实体' : 'Delete Entity',
|
||||
kind: 'warning'
|
||||
}
|
||||
);
|
||||
|
||||
if (confirmed) {
|
||||
entity.destroy();
|
||||
entityStore.removeEntity(entity);
|
||||
}
|
||||
};
|
||||
|
||||
// Listen for Delete key
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Delete' && selectedId && !isRemoteConnected) {
|
||||
handleDeleteEntity();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [selectedId, isRemoteConnected]);
|
||||
|
||||
// Filter entities based on search query
|
||||
const filterRemoteEntities = (entityList: RemoteEntity[]): RemoteEntity[] => {
|
||||
if (!searchQuery.trim()) return entityList;
|
||||
@@ -153,6 +249,15 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
|
||||
<div className="hierarchy-header">
|
||||
<Layers size={16} className="hierarchy-header-icon" />
|
||||
<h3>{t('hierarchy.title')}</h3>
|
||||
<div
|
||||
className="scene-name-container clickable"
|
||||
onClick={handleSceneNameClick}
|
||||
title={sceneFilePath ? `${sceneName} - 点击跳转到文件` : sceneName}
|
||||
>
|
||||
<span className="scene-name">
|
||||
{sceneName}{isSceneModified ? '*' : ''}
|
||||
</span>
|
||||
</div>
|
||||
{showRemoteIndicator && (
|
||||
<div className="remote-indicator" title="Showing remote entities">
|
||||
<Wifi size={12} />
|
||||
@@ -168,6 +273,26 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{!isRemoteConnected && (
|
||||
<div className="hierarchy-toolbar">
|
||||
<button
|
||||
className="toolbar-btn"
|
||||
onClick={handleCreateEntity}
|
||||
title={locale === 'zh' ? '创建实体' : 'Create Entity'}
|
||||
>
|
||||
<Plus size={14} />
|
||||
<span>{locale === 'zh' ? '创建实体' : 'Create Entity'}</span>
|
||||
</button>
|
||||
<button
|
||||
className="toolbar-btn"
|
||||
onClick={handleDeleteEntity}
|
||||
disabled={!selectedId}
|
||||
title={locale === 'zh' ? '删除实体' : 'Delete Entity'}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="hierarchy-content scrollable">
|
||||
{displayEntities.length === 0 ? (
|
||||
<div className="empty-state">
|
||||
|
||||
@@ -18,7 +18,7 @@ export function StartupPage({ onOpenProject, onCreateProject, onOpenRecentProjec
|
||||
title: 'ECS Framework Editor',
|
||||
subtitle: 'Professional Game Development Tool',
|
||||
openProject: 'Open Project',
|
||||
createProject: 'Create New Project',
|
||||
createProject: 'Create Project',
|
||||
profilerMode: 'Profiler Mode',
|
||||
recentProjects: 'Recent Projects',
|
||||
noRecentProjects: 'No recent projects',
|
||||
@@ -49,19 +49,25 @@ export function StartupPage({ onOpenProject, onCreateProject, onOpenRecentProjec
|
||||
|
||||
<div className="startup-content">
|
||||
<div className="startup-actions">
|
||||
<button className="startup-action-btn primary" onClick={onProfilerMode}>
|
||||
<button className="startup-action-btn primary" onClick={onOpenProject}>
|
||||
<svg className="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
|
||||
<path d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
|
||||
<path d="M3 7V17C3 18.1046 3.89543 19 5 19H19C20.1046 19 21 18.1046 21 17V9C21 7.89543 20.1046 7 19 7H13L11 5H5C3.89543 5 3 5.89543 3 7Z" strokeWidth="2"/>
|
||||
</svg>
|
||||
<span>{t.profilerMode}</span>
|
||||
<span>{t.openProject}</span>
|
||||
</button>
|
||||
|
||||
<button className="startup-action-btn disabled" disabled title={t.comingSoon}>
|
||||
<button className="startup-action-btn" onClick={onCreateProject}>
|
||||
<svg className="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
|
||||
<path d="M12 5V19M5 12H19" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
|
||||
</svg>
|
||||
<span>{t.createProject}</span>
|
||||
<span className="badge-coming-soon">{t.comingSoon}</span>
|
||||
</button>
|
||||
|
||||
<button className="startup-action-btn" onClick={onProfilerMode}>
|
||||
<svg className="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
|
||||
<path d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
|
||||
</svg>
|
||||
<span>{t.profilerMode}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
128
packages/editor-app/src/styles/ConfirmDialog.css
Normal file
@@ -0,0 +1,128 @@
|
||||
.confirm-dialog-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 10000;
|
||||
animation: fadeIn 0.2s ease-out;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.confirm-dialog {
|
||||
background: var(--bg-secondary, #2a2a2a);
|
||||
border: 1px solid var(--border-color, #404040);
|
||||
border-radius: 8px;
|
||||
min-width: 400px;
|
||||
max-width: 600px;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
|
||||
animation: slideIn 0.2s ease-out;
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
transform: translateY(-20px);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.confirm-dialog-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid var(--border-color, #404040);
|
||||
}
|
||||
|
||||
.confirm-dialog-header h2 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary, #e0e0e0);
|
||||
}
|
||||
|
||||
.confirm-dialog-header .close-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-secondary, #999);
|
||||
cursor: pointer;
|
||||
padding: 4px;
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.confirm-dialog-header .close-btn:hover {
|
||||
background: var(--bg-hover, #3a3a3a);
|
||||
color: var(--text-primary, #fff);
|
||||
}
|
||||
|
||||
.confirm-dialog-content {
|
||||
padding: 20px;
|
||||
color: var(--text-primary, #e0e0e0);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.confirm-dialog-content p {
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.confirm-dialog-footer {
|
||||
padding: 12px 20px;
|
||||
border-top: 1px solid var(--border-color, #404040);
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.confirm-dialog-btn {
|
||||
padding: 8px 24px;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.confirm-dialog-btn.cancel {
|
||||
background: var(--bg-hover, #3a3a3a);
|
||||
color: var(--text-primary, #e0e0e0);
|
||||
}
|
||||
|
||||
.confirm-dialog-btn.cancel:hover {
|
||||
background: var(--bg-active, #4a4a4a);
|
||||
}
|
||||
|
||||
.confirm-dialog-btn.confirm {
|
||||
background: #4a9eff;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.confirm-dialog-btn.confirm:hover {
|
||||
background: #6bb0ff;
|
||||
}
|
||||
|
||||
.confirm-dialog-btn:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
height: 100%;
|
||||
background-color: var(--color-bg-base);
|
||||
color: var(--color-text-primary);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.inspector-header {
|
||||
|
||||
115
packages/editor-app/src/styles/ErrorDialog.css
Normal file
@@ -0,0 +1,115 @@
|
||||
.error-dialog-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 10000;
|
||||
animation: fadeIn 0.2s ease-out;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.error-dialog {
|
||||
background: var(--bg-secondary, #2a2a2a);
|
||||
border: 1px solid var(--border-color, #404040);
|
||||
border-radius: 8px;
|
||||
min-width: 400px;
|
||||
max-width: 600px;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
|
||||
animation: slideIn 0.2s ease-out;
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
transform: translateY(-20px);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.error-dialog-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid var(--border-color, #404040);
|
||||
}
|
||||
|
||||
.error-dialog-header h2 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: #ff4444;
|
||||
}
|
||||
|
||||
.error-dialog-header .close-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-secondary, #999);
|
||||
cursor: pointer;
|
||||
padding: 4px;
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.error-dialog-header .close-btn:hover {
|
||||
background: var(--bg-hover, #3a3a3a);
|
||||
color: var(--text-primary, #fff);
|
||||
}
|
||||
|
||||
.error-dialog-content {
|
||||
padding: 20px;
|
||||
color: var(--text-primary, #e0e0e0);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.error-dialog-content p {
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.error-dialog-footer {
|
||||
padding: 12px 20px;
|
||||
border-top: 1px solid var(--border-color, #404040);
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.error-dialog-btn {
|
||||
padding: 8px 24px;
|
||||
background: #ff4444;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.error-dialog-btn:hover {
|
||||
background: #ff6666;
|
||||
}
|
||||
|
||||
.error-dialog-btn:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
@@ -29,7 +29,42 @@
|
||||
color: var(--color-text-primary);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.scene-name-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 2px 8px;
|
||||
background-color: var(--color-bg-base);
|
||||
border: 1px solid var(--color-border-default);
|
||||
border-radius: var(--radius-sm);
|
||||
margin-left: auto;
|
||||
margin-right: var(--spacing-sm);
|
||||
transition: all var(--transition-fast);
|
||||
}
|
||||
|
||||
.scene-name-container.clickable {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.scene-name-container.clickable:hover {
|
||||
background-color: var(--color-bg-hover);
|
||||
border-color: var(--color-primary);
|
||||
}
|
||||
|
||||
.scene-name-container.clickable:hover .scene-name {
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
.scene-name {
|
||||
font-size: var(--font-size-xs);
|
||||
color: var(--color-text-secondary);
|
||||
font-weight: var(--font-weight-medium);
|
||||
max-width: 120px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
transition: color var(--transition-fast);
|
||||
}
|
||||
|
||||
.remote-indicator {
|
||||
@@ -74,6 +109,45 @@
|
||||
color: var(--color-text-tertiary);
|
||||
}
|
||||
|
||||
.hierarchy-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-xs);
|
||||
padding: var(--spacing-sm) var(--spacing-md);
|
||||
border-bottom: 1px solid var(--color-border-default);
|
||||
background-color: var(--color-bg-base);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.toolbar-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-xs);
|
||||
padding: var(--spacing-xs) var(--spacing-sm);
|
||||
background-color: var(--color-bg-elevated);
|
||||
border: 1px solid var(--color-border-default);
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--color-text-primary);
|
||||
font-size: var(--font-size-sm);
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
}
|
||||
|
||||
.toolbar-btn:hover:not(:disabled) {
|
||||
background-color: var(--color-bg-hover);
|
||||
border-color: var(--color-primary);
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
.toolbar-btn:active:not(:disabled) {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
.toolbar-btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.hierarchy-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
|
||||
@@ -3,15 +3,10 @@ import react from '@vitejs/plugin-react';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { transformSync } from 'esbuild';
|
||||
import JSON5 from 'json5';
|
||||
|
||||
const host = process.env.TAURI_DEV_HOST;
|
||||
|
||||
const userProjectPathMap = new Map<string, string>();
|
||||
const userProjectDependencies = new Map<string, Set<string>>();
|
||||
const cocosEnginePaths = new Map<string, string>();
|
||||
const allowedPaths = new Set<string>();
|
||||
|
||||
const editorPackageMapping = new Map<string, string>();
|
||||
|
||||
function loadEditorPackages() {
|
||||
@@ -36,7 +31,6 @@ function loadEditorPackages() {
|
||||
const entryPath = path.join(packagesDir, dir, mainFile);
|
||||
if (fs.existsSync(entryPath)) {
|
||||
editorPackageMapping.set(packageJson.name, entryPath);
|
||||
console.log(`[Vite] Mapped ${packageJson.name} -> ${entryPath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,95 +39,19 @@ function loadEditorPackages() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Vite] Loaded ${editorPackageMapping.size} editor packages`);
|
||||
}
|
||||
|
||||
loadEditorPackages();
|
||||
|
||||
function loadCocosEnginePath(projectPath: string) {
|
||||
try {
|
||||
const tsconfigPath = path.join(projectPath, 'tsconfig.json');
|
||||
if (!fs.existsSync(tsconfigPath)) {
|
||||
console.log('[Vite] No tsconfig.json found in user project');
|
||||
return;
|
||||
}
|
||||
|
||||
const tsconfigContent = fs.readFileSync(tsconfigPath, 'utf-8');
|
||||
const tsconfig = JSON5.parse(tsconfigContent);
|
||||
|
||||
if (tsconfig.extends) {
|
||||
const extendedPath = path.join(projectPath, tsconfig.extends);
|
||||
if (fs.existsSync(extendedPath)) {
|
||||
const extendedContent = fs.readFileSync(extendedPath, 'utf-8');
|
||||
const extendedConfig = JSON5.parse(extendedContent);
|
||||
|
||||
if (extendedConfig.compilerOptions?.paths?.['db://internal/*']) {
|
||||
const cocosInternalPaths = extendedConfig.compilerOptions.paths['db://internal/*'];
|
||||
if (cocosInternalPaths && cocosInternalPaths.length > 0) {
|
||||
let cocosEnginePath = cocosInternalPaths[0];
|
||||
cocosEnginePath = cocosEnginePath.replace(/[\/\\]\*$/, '');
|
||||
cocosEnginePath = cocosEnginePath.replace(/[\/\\]editor[\/\\]assets$/, '');
|
||||
|
||||
const exportsBasePath = path.join(cocosEnginePath, 'exports', 'base.ts');
|
||||
if (fs.existsSync(exportsBasePath)) {
|
||||
cocosEnginePaths.set(projectPath, exportsBasePath);
|
||||
allowedPaths.add(cocosEnginePath);
|
||||
console.log(`[Vite] Found Cocos Creator engine at: ${exportsBasePath}`);
|
||||
console.log(`[Vite] Added Cocos engine path to allowed paths: ${cocosEnginePath}`);
|
||||
} else {
|
||||
console.log(`[Vite] Cocos engine base.ts not found at: ${exportsBasePath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Vite] Failed to load Cocos engine path:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function loadUserProjectDependencies(projectPath: string) {
|
||||
try {
|
||||
const packageJsonPath = path.join(projectPath, 'package.json');
|
||||
if (!fs.existsSync(packageJsonPath)) {
|
||||
console.log('[Vite] No package.json found in user project');
|
||||
return;
|
||||
}
|
||||
|
||||
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
|
||||
const deps = new Set<string>();
|
||||
|
||||
if (packageJson.dependencies) {
|
||||
Object.keys(packageJson.dependencies).forEach(dep => deps.add(dep));
|
||||
}
|
||||
if (packageJson.devDependencies) {
|
||||
Object.keys(packageJson.devDependencies).forEach(dep => deps.add(dep));
|
||||
}
|
||||
|
||||
userProjectDependencies.set(projectPath, deps);
|
||||
console.log(`[Vite] Loaded ${deps.size} dependencies from user project`);
|
||||
|
||||
loadCocosEnginePath(projectPath);
|
||||
} catch (error) {
|
||||
console.error('[Vite] Failed to load user project dependencies:', error);
|
||||
}
|
||||
}
|
||||
|
||||
const userProjectPlugin = () => ({
|
||||
name: 'user-project-middleware',
|
||||
configureServer(server: any) {
|
||||
allowedPaths.add(path.resolve(__dirname, '..'));
|
||||
|
||||
server.middlewares.use(async (req: any, res: any, next: any) => {
|
||||
if (req.url?.startsWith('/@user-project/')) {
|
||||
console.log('[Vite] Received request:', req.url);
|
||||
const urlWithoutQuery = req.url.split('?')[0];
|
||||
const relativePath = decodeURIComponent(urlWithoutQuery.substring('/@user-project'.length));
|
||||
console.log('[Vite] Resolved relative path:', relativePath);
|
||||
|
||||
let projectPath: string | null = null;
|
||||
|
||||
for (const [, path] of userProjectPathMap) {
|
||||
projectPath = path;
|
||||
break;
|
||||
@@ -146,8 +64,6 @@ const userProjectPlugin = () => ({
|
||||
}
|
||||
|
||||
const filePath = path.join(projectPath, relativePath);
|
||||
console.log('[Vite] Looking for file:', filePath);
|
||||
console.log('[Vite] File exists:', fs.existsSync(filePath));
|
||||
|
||||
if (!fs.existsSync(filePath)) {
|
||||
console.error('[Vite] File not found:', filePath);
|
||||
@@ -163,7 +79,6 @@ const userProjectPlugin = () => ({
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('[Vite] Reading and transforming file:', filePath);
|
||||
let content = fs.readFileSync(filePath, 'utf-8');
|
||||
|
||||
editorPackageMapping.forEach((srcPath, packageName) => {
|
||||
@@ -175,43 +90,6 @@ const userProjectPlugin = () => ({
|
||||
);
|
||||
});
|
||||
|
||||
const deps = userProjectDependencies.get(projectPath);
|
||||
if (deps) {
|
||||
deps.forEach(dep => {
|
||||
if (editorPackageMapping.has(dep)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const depPath = path.join(projectPath, 'node_modules', dep);
|
||||
if (fs.existsSync(depPath)) {
|
||||
const packageJsonPath = path.join(depPath, 'package.json');
|
||||
if (fs.existsSync(packageJsonPath)) {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
|
||||
const mainFile = pkg.module || pkg.main || 'index.js';
|
||||
const entryPath = path.join(depPath, mainFile);
|
||||
|
||||
if (fs.existsSync(entryPath)) {
|
||||
const escapedDep = dep.replace(/\//g, '\\/').replace(/@/g, '\\@');
|
||||
const regex = new RegExp(`from\\s+['"]${escapedDep}['"]`, 'g');
|
||||
content = content.replace(
|
||||
regex,
|
||||
`from "/@fs/${entryPath.replace(/\\/g, '/')}"`
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略解析错误
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
content = content.replace(
|
||||
/from\s+['"]cc['"]/g,
|
||||
'from "/@cocos-shim"'
|
||||
);
|
||||
|
||||
const fileDir = path.dirname(filePath);
|
||||
const relativeImportRegex = /from\s+['"](\.\.?\/[^'"]+)['"]/g;
|
||||
content = content.replace(relativeImportRegex, (match, importPath) => {
|
||||
@@ -239,7 +117,6 @@ const userProjectPlugin = () => ({
|
||||
sourcefile: filePath,
|
||||
});
|
||||
|
||||
console.log('[Vite] Successfully transformed file:', filePath);
|
||||
res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
@@ -253,58 +130,12 @@ const userProjectPlugin = () => ({
|
||||
}
|
||||
|
||||
if (req.url === '/@ecs-framework-shim') {
|
||||
let projectPath: string | null = null;
|
||||
for (const [, p] of userProjectPathMap) {
|
||||
projectPath = p;
|
||||
break;
|
||||
}
|
||||
|
||||
if (projectPath) {
|
||||
const userFrameworkPath = path.join(projectPath, 'node_modules', '@esengine', 'ecs-framework', 'bin', 'index.js');
|
||||
if (fs.existsSync(userFrameworkPath)) {
|
||||
res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.end('export * from "/@fs/' + userFrameworkPath.replace(/\\/g, '/') + '";');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.end('export * from "/@fs/' + path.resolve(__dirname, '../core/src/index.ts').replace(/\\/g, '/') + '";');
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.url === '/@cocos-shim') {
|
||||
console.log('[Vite] Using Cocos Creator fallback shim (editor environment)');
|
||||
res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
|
||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||
res.end(`
|
||||
export default {};
|
||||
export class Node {}
|
||||
export class Component {}
|
||||
export class Vec2 {
|
||||
constructor(x = 0, y = 0) { this.x = x; this.y = y; }
|
||||
static distance(a, b) { return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2); }
|
||||
length() { return Math.sqrt(this.x ** 2 + this.y ** 2); }
|
||||
normalize() { const len = this.length(); if (len > 0) { this.x /= len; this.y /= len; } return this; }
|
||||
set(x, y) { this.x = x; this.y = y; return this; }
|
||||
}
|
||||
export class Vec3 {
|
||||
constructor(x = 0, y = 0, z = 0) { this.x = x; this.y = y; this.z = z; }
|
||||
static distance(a, b) { return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2); }
|
||||
length() { return Math.sqrt(this.x ** 2 + this.y ** 2 + this.z ** 2); }
|
||||
normalize() { const len = this.length(); if (len > 0) { this.x /= len; this.y /= len; this.z /= len; } return this; }
|
||||
set(x, y, z) { this.x = x; this.y = y; this.z = z; return this; }
|
||||
}
|
||||
export class Color { constructor(r = 255, g = 255, b = 255, a = 255) { this.r = r; this.g = g; this.b = b; this.a = a; } }
|
||||
export class Quat { constructor(x = 0, y = 0, z = 0, w = 1) { this.x = x; this.y = y; this.z = z; this.w = w; } }
|
||||
export function tween() { return { to() { return this; }, call() { return this; }, start() {} }; }
|
||||
export function v3(x, y, z) { return new Vec3(x, y, z); }
|
||||
`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.url === '/@user-project-set-path') {
|
||||
let body = '';
|
||||
req.on('data', (chunk: any) => {
|
||||
@@ -314,9 +145,6 @@ const userProjectPlugin = () => ({
|
||||
try {
|
||||
const { path: projectPath } = JSON.parse(body);
|
||||
userProjectPathMap.set('current', projectPath);
|
||||
allowedPaths.add(projectPath);
|
||||
loadUserProjectDependencies(projectPath);
|
||||
console.log('[Vite] User project path set to:', projectPath);
|
||||
res.statusCode = 200;
|
||||
res.end('OK');
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,140 +0,0 @@
|
||||
import type { IService } from '@esengine/ecs-framework';
|
||||
import { Injectable, Component } from '@esengine/ecs-framework';
|
||||
import { createLogger } from '@esengine/ecs-framework';
|
||||
import { MessageHub } from './MessageHub';
|
||||
import type { ComponentFileInfo } from './ComponentDiscoveryService';
|
||||
import { ComponentRegistry } from './ComponentRegistry';
|
||||
|
||||
const logger = createLogger('ComponentLoaderService');
|
||||
|
||||
export interface LoadedComponentInfo {
|
||||
fileInfo: ComponentFileInfo;
|
||||
componentClass: typeof Component;
|
||||
loadedAt: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ComponentLoaderService implements IService {
|
||||
private loadedComponents: Map<string, LoadedComponentInfo> = new Map();
|
||||
private messageHub: MessageHub;
|
||||
private componentRegistry: ComponentRegistry;
|
||||
|
||||
constructor(messageHub: MessageHub, componentRegistry: ComponentRegistry) {
|
||||
this.messageHub = messageHub;
|
||||
this.componentRegistry = componentRegistry;
|
||||
}
|
||||
|
||||
public async loadComponents(
|
||||
componentInfos: ComponentFileInfo[],
|
||||
modulePathTransform?: (filePath: string) => string
|
||||
): Promise<LoadedComponentInfo[]> {
|
||||
const loadedComponents: LoadedComponentInfo[] = [];
|
||||
|
||||
for (const componentInfo of componentInfos) {
|
||||
try {
|
||||
const loadedComponent = await this.loadComponent(componentInfo, modulePathTransform);
|
||||
if (loadedComponent) {
|
||||
loadedComponents.push(loadedComponent);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Failed to load component: ${componentInfo.fileName}`, error);
|
||||
}
|
||||
}
|
||||
|
||||
await this.messageHub.publish('components:loaded', {
|
||||
count: loadedComponents.length,
|
||||
components: loadedComponents
|
||||
});
|
||||
|
||||
return loadedComponents;
|
||||
}
|
||||
|
||||
public async loadComponent(
|
||||
componentInfo: ComponentFileInfo,
|
||||
modulePathTransform?: (filePath: string) => string
|
||||
): Promise<LoadedComponentInfo | null> {
|
||||
try {
|
||||
if (!componentInfo.className) {
|
||||
logger.warn(`No class name found for component: ${componentInfo.fileName}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
let componentClass: typeof Component | undefined;
|
||||
|
||||
if (modulePathTransform) {
|
||||
const modulePath = modulePathTransform(componentInfo.path);
|
||||
|
||||
try {
|
||||
const module = await import(/* @vite-ignore */ modulePath);
|
||||
|
||||
componentClass = module[componentInfo.className] || module.default;
|
||||
|
||||
if (!componentClass) {
|
||||
logger.warn(`Component class ${componentInfo.className} not found in module exports`);
|
||||
logger.warn(`Available exports: ${Object.keys(module).join(', ')}`);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Failed to import component module: ${modulePath}`, error);
|
||||
}
|
||||
}
|
||||
|
||||
this.componentRegistry.register({
|
||||
name: componentInfo.className,
|
||||
type: componentClass as any,
|
||||
category: componentInfo.className.includes('Transform') ? 'Transform' :
|
||||
componentInfo.className.includes('Render') || componentInfo.className.includes('Sprite') ? 'Rendering' :
|
||||
componentInfo.className.includes('Physics') || componentInfo.className.includes('RigidBody') ? 'Physics' :
|
||||
'Custom',
|
||||
description: `Component from ${componentInfo.fileName}`,
|
||||
metadata: {
|
||||
path: componentInfo.path,
|
||||
fileName: componentInfo.fileName
|
||||
}
|
||||
});
|
||||
|
||||
const loadedInfo: LoadedComponentInfo = {
|
||||
fileInfo: componentInfo,
|
||||
componentClass: (componentClass || Component) as any,
|
||||
loadedAt: Date.now()
|
||||
};
|
||||
|
||||
this.loadedComponents.set(componentInfo.path, loadedInfo);
|
||||
|
||||
return loadedInfo;
|
||||
} catch (error) {
|
||||
logger.error(`Failed to load component: ${componentInfo.fileName}`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public getLoadedComponents(): LoadedComponentInfo[] {
|
||||
return Array.from(this.loadedComponents.values());
|
||||
}
|
||||
|
||||
public unloadComponent(filePath: string): boolean {
|
||||
const loadedComponent = this.loadedComponents.get(filePath);
|
||||
|
||||
if (!loadedComponent || !loadedComponent.fileInfo.className) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.componentRegistry.unregister(loadedComponent.fileInfo.className);
|
||||
this.loadedComponents.delete(filePath);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public clearLoadedComponents(): void {
|
||||
for (const [filePath] of this.loadedComponents) {
|
||||
this.unloadComponent(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
private convertToModulePath(filePath: string): string {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
this.clearLoadedComponents();
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { IService } from '@esengine/ecs-framework';
|
||||
import { Injectable } from '@esengine/ecs-framework';
|
||||
import { createLogger } from '@esengine/ecs-framework';
|
||||
import { createLogger, Scene } from '@esengine/ecs-framework';
|
||||
import { MessageHub } from './MessageHub';
|
||||
import type { IFileAPI } from '../Types/IFileAPI';
|
||||
|
||||
const logger = createLogger('ProjectService');
|
||||
|
||||
@@ -19,6 +20,8 @@ export interface ProjectConfig {
|
||||
componentsPath?: string;
|
||||
componentPattern?: string;
|
||||
buildOutput?: string;
|
||||
scenesPath?: string;
|
||||
defaultScene?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
@@ -26,9 +29,55 @@ export class ProjectService implements IService {
|
||||
private currentProject: ProjectInfo | null = null;
|
||||
private projectConfig: ProjectConfig | null = null;
|
||||
private messageHub: MessageHub;
|
||||
private fileAPI: IFileAPI;
|
||||
|
||||
constructor(messageHub: MessageHub) {
|
||||
constructor(messageHub: MessageHub, fileAPI: IFileAPI) {
|
||||
this.messageHub = messageHub;
|
||||
this.fileAPI = fileAPI;
|
||||
}
|
||||
|
||||
public async createProject(projectPath: string): Promise<void> {
|
||||
try {
|
||||
const sep = projectPath.includes('\\') ? '\\' : '/';
|
||||
const configPath = `${projectPath}${sep}ecs-editor.config.json`;
|
||||
|
||||
const configExists = await this.fileAPI.pathExists(configPath);
|
||||
if (configExists) {
|
||||
throw new Error('ECS project already exists in this directory');
|
||||
}
|
||||
|
||||
const config: ProjectConfig = {
|
||||
projectType: 'cocos',
|
||||
componentsPath: 'components',
|
||||
componentPattern: '**/*.ts',
|
||||
buildOutput: 'temp/editor-components',
|
||||
scenesPath: 'ecs-scenes',
|
||||
defaultScene: 'main.ecs'
|
||||
};
|
||||
|
||||
await this.fileAPI.writeFileContent(configPath, JSON.stringify(config, null, 2));
|
||||
|
||||
const scenesPath = `${projectPath}${sep}${config.scenesPath}`;
|
||||
await this.fileAPI.createDirectory(scenesPath);
|
||||
|
||||
const defaultScenePath = `${scenesPath}${sep}${config.defaultScene}`;
|
||||
const emptyScene = new Scene();
|
||||
const sceneData = emptyScene.serialize({
|
||||
format: 'json',
|
||||
pretty: true,
|
||||
includeMetadata: true
|
||||
}) as string;
|
||||
await this.fileAPI.writeFileContent(defaultScenePath, sceneData);
|
||||
|
||||
await this.messageHub.publish('project:created', {
|
||||
path: projectPath
|
||||
});
|
||||
|
||||
logger.info('Project created', { path: projectPath });
|
||||
} catch (error) {
|
||||
logger.error('Failed to create project', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async openProject(projectPath: string): Promise<void> {
|
||||
@@ -91,6 +140,28 @@ export class ProjectService implements IService {
|
||||
return `${this.currentProject.path}${sep}${this.projectConfig.componentsPath}`;
|
||||
}
|
||||
|
||||
public getScenesPath(): string | null {
|
||||
if (!this.currentProject) {
|
||||
return null;
|
||||
}
|
||||
const scenesPath = this.projectConfig?.scenesPath || 'assets/scenes';
|
||||
const sep = this.currentProject.path.includes('\\') ? '\\' : '/';
|
||||
return `${this.currentProject.path}${sep}${scenesPath}`;
|
||||
}
|
||||
|
||||
public getDefaultScenePath(): string | null {
|
||||
if (!this.currentProject) {
|
||||
return null;
|
||||
}
|
||||
const scenesPath = this.getScenesPath();
|
||||
if (!scenesPath) {
|
||||
return null;
|
||||
}
|
||||
const defaultScene = this.projectConfig?.defaultScene || 'main.scene';
|
||||
const sep = this.currentProject.path.includes('\\') ? '\\' : '/';
|
||||
return `${scenesPath}${sep}${defaultScene}`;
|
||||
}
|
||||
|
||||
private async validateProject(projectPath: string): Promise<ProjectInfo> {
|
||||
const projectName = projectPath.split(/[\\/]/).pop() || 'Unknown Project';
|
||||
|
||||
@@ -118,7 +189,9 @@ export class ProjectService implements IService {
|
||||
projectType: 'cocos',
|
||||
componentsPath: '',
|
||||
componentPattern: '**/*.ts',
|
||||
buildOutput: 'temp/editor-components'
|
||||
buildOutput: 'temp/editor-components',
|
||||
scenesPath: 'ecs-scenes',
|
||||
defaultScene: 'main.ecs'
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
283
packages/editor-core/src/Services/SceneManagerService.ts
Normal file
@@ -0,0 +1,283 @@
|
||||
import type { IService } from '@esengine/ecs-framework';
|
||||
import { Injectable, Core, createLogger, SceneSerializer, Scene } from '@esengine/ecs-framework';
|
||||
import type { MessageHub } from './MessageHub';
|
||||
import type { IFileAPI } from '../Types/IFileAPI';
|
||||
import type { ProjectService } from './ProjectService';
|
||||
|
||||
const logger = createLogger('SceneManagerService');
|
||||
|
||||
export interface SceneState {
|
||||
currentScenePath: string | null;
|
||||
sceneName: string;
|
||||
isModified: boolean;
|
||||
isSaved: boolean;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SceneManagerService implements IService {
|
||||
private sceneState: SceneState = {
|
||||
currentScenePath: null,
|
||||
sceneName: 'Untitled',
|
||||
isModified: false,
|
||||
isSaved: false
|
||||
};
|
||||
|
||||
private unsubscribeHandlers: Array<() => void> = [];
|
||||
|
||||
constructor(
|
||||
private messageHub: MessageHub,
|
||||
private fileAPI: IFileAPI,
|
||||
private projectService?: ProjectService
|
||||
) {
|
||||
this.setupAutoModificationTracking();
|
||||
logger.info('SceneManagerService initialized');
|
||||
}
|
||||
|
||||
public async newScene(): Promise<void> {
|
||||
if (!await this.canClose()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const scene = Core.scene as Scene | null;
|
||||
if (!scene) {
|
||||
throw new Error('No active scene');
|
||||
}
|
||||
scene.entities.removeAllEntities();
|
||||
const systems = [...scene.systems];
|
||||
for (const system of systems) {
|
||||
scene.removeEntityProcessor(system);
|
||||
}
|
||||
|
||||
this.sceneState = {
|
||||
currentScenePath: null,
|
||||
sceneName: 'Untitled',
|
||||
isModified: false,
|
||||
isSaved: false
|
||||
};
|
||||
|
||||
await this.messageHub.publish('scene:new', {});
|
||||
logger.info('New scene created');
|
||||
}
|
||||
|
||||
public async openScene(filePath?: string): Promise<void> {
|
||||
if (!await this.canClose()) {
|
||||
return;
|
||||
}
|
||||
|
||||
let path: string | null | undefined = filePath;
|
||||
if (!path) {
|
||||
path = await this.fileAPI.openSceneDialog();
|
||||
if (!path) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const jsonData = await this.fileAPI.readFileContent(path);
|
||||
|
||||
const validation = SceneSerializer.validate(jsonData);
|
||||
if (!validation.valid) {
|
||||
throw new Error(`场景文件损坏: ${validation.errors?.join(', ')}`);
|
||||
}
|
||||
|
||||
const scene = Core.scene as Scene | null;
|
||||
if (!scene) {
|
||||
throw new Error('No active scene');
|
||||
}
|
||||
scene.deserialize(jsonData, {
|
||||
strategy: 'replace'
|
||||
});
|
||||
|
||||
const fileName = path.split(/[/\\]/).pop() || 'Untitled';
|
||||
const sceneName = fileName.replace('.ecs', '');
|
||||
|
||||
this.sceneState = {
|
||||
currentScenePath: path,
|
||||
sceneName,
|
||||
isModified: false,
|
||||
isSaved: true
|
||||
};
|
||||
|
||||
await this.messageHub.publish('scene:loaded', {
|
||||
path,
|
||||
sceneName,
|
||||
isModified: false,
|
||||
isSaved: true
|
||||
});
|
||||
logger.info(`Scene loaded: ${path}`);
|
||||
} catch (error) {
|
||||
logger.error('Failed to load scene:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async saveScene(): Promise<void> {
|
||||
if (!this.sceneState.currentScenePath) {
|
||||
await this.saveSceneAs();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const scene = Core.scene as Scene | null;
|
||||
if (!scene) {
|
||||
throw new Error('No active scene');
|
||||
}
|
||||
const jsonData = scene.serialize({
|
||||
format: 'json',
|
||||
pretty: true,
|
||||
includeMetadata: true
|
||||
}) as string;
|
||||
|
||||
await this.fileAPI.saveProject(this.sceneState.currentScenePath, jsonData);
|
||||
|
||||
this.sceneState.isModified = false;
|
||||
this.sceneState.isSaved = true;
|
||||
|
||||
await this.messageHub.publish('scene:saved', {
|
||||
path: this.sceneState.currentScenePath
|
||||
});
|
||||
logger.info(`Scene saved: ${this.sceneState.currentScenePath}`);
|
||||
} catch (error) {
|
||||
logger.error('Failed to save scene:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async saveSceneAs(filePath?: string): Promise<void> {
|
||||
let path: string | null | undefined = filePath;
|
||||
if (!path) {
|
||||
let defaultName = this.sceneState.sceneName || 'Untitled';
|
||||
|
||||
if (this.projectService?.isProjectOpen()) {
|
||||
const scenesPath = this.projectService.getScenesPath();
|
||||
if (scenesPath) {
|
||||
const sep = scenesPath.includes('\\') ? '\\' : '/';
|
||||
defaultName = `${scenesPath}${sep}${defaultName}`;
|
||||
}
|
||||
}
|
||||
|
||||
path = await this.fileAPI.saveSceneDialog(defaultName);
|
||||
if (!path) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!path.endsWith('.ecs')) {
|
||||
path += '.ecs';
|
||||
}
|
||||
|
||||
try {
|
||||
const scene = Core.scene as Scene | null;
|
||||
if (!scene) {
|
||||
throw new Error('No active scene');
|
||||
}
|
||||
const jsonData = scene.serialize({
|
||||
format: 'json',
|
||||
pretty: true,
|
||||
includeMetadata: true
|
||||
}) as string;
|
||||
|
||||
await this.fileAPI.saveProject(path, jsonData);
|
||||
|
||||
const fileName = path.split(/[/\\]/).pop() || 'Untitled';
|
||||
const sceneName = fileName.replace('.ecs', '');
|
||||
|
||||
this.sceneState = {
|
||||
currentScenePath: path,
|
||||
sceneName,
|
||||
isModified: false,
|
||||
isSaved: true
|
||||
};
|
||||
|
||||
await this.messageHub.publish('scene:saved', { path });
|
||||
logger.info(`Scene saved as: ${path}`);
|
||||
} catch (error) {
|
||||
logger.error('Failed to save scene as:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async exportScene(filePath?: string): Promise<void> {
|
||||
let path: string | null | undefined = filePath;
|
||||
if (!path) {
|
||||
let defaultName = (this.sceneState.sceneName || 'Untitled') + '.ecs.bin';
|
||||
|
||||
if (this.projectService?.isProjectOpen()) {
|
||||
const scenesPath = this.projectService.getScenesPath();
|
||||
if (scenesPath) {
|
||||
const sep = scenesPath.includes('\\') ? '\\' : '/';
|
||||
defaultName = `${scenesPath}${sep}${defaultName}`;
|
||||
}
|
||||
}
|
||||
|
||||
path = await this.fileAPI.saveSceneDialog(defaultName);
|
||||
if (!path) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!path.endsWith('.ecs.bin')) {
|
||||
path += '.ecs.bin';
|
||||
}
|
||||
|
||||
try {
|
||||
const scene = Core.scene as Scene | null;
|
||||
if (!scene) {
|
||||
throw new Error('No active scene');
|
||||
}
|
||||
const binaryData = scene.serialize({
|
||||
format: 'binary'
|
||||
}) as Uint8Array;
|
||||
|
||||
await this.fileAPI.exportBinary(binaryData, path);
|
||||
|
||||
await this.messageHub.publish('scene:exported', { path });
|
||||
logger.info(`Scene exported: ${path}`);
|
||||
} catch (error) {
|
||||
logger.error('Failed to export scene:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public getSceneState(): SceneState {
|
||||
return { ...this.sceneState };
|
||||
}
|
||||
|
||||
public markAsModified(): void {
|
||||
if (!this.sceneState.isModified) {
|
||||
this.sceneState.isModified = true;
|
||||
this.messageHub.publishSync('scene:modified', {});
|
||||
logger.debug('Scene marked as modified');
|
||||
}
|
||||
}
|
||||
|
||||
public async canClose(): Promise<boolean> {
|
||||
if (!this.sceneState.isModified) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private setupAutoModificationTracking(): void {
|
||||
const unsubscribeEntityAdded = this.messageHub.subscribe('entity:added', () => {
|
||||
this.markAsModified();
|
||||
});
|
||||
|
||||
const unsubscribeEntityRemoved = this.messageHub.subscribe('entity:removed', () => {
|
||||
this.markAsModified();
|
||||
});
|
||||
|
||||
this.unsubscribeHandlers.push(unsubscribeEntityAdded, unsubscribeEntityRemoved);
|
||||
|
||||
logger.debug('Auto modification tracking setup complete');
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
for (const unsubscribe of this.unsubscribeHandlers) {
|
||||
unsubscribe();
|
||||
}
|
||||
this.unsubscribeHandlers = [];
|
||||
logger.info('SceneManagerService disposed');
|
||||
}
|
||||
}
|
||||
61
packages/editor-core/src/Types/IFileAPI.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* 文件 API 接口
|
||||
*
|
||||
* 定义编辑器与文件系统交互的抽象接口
|
||||
* 具体实现由上层应用提供(如 TauriFileAPI)
|
||||
*/
|
||||
export interface IFileAPI {
|
||||
/**
|
||||
* 打开场景文件选择对话框
|
||||
* @returns 用户选择的文件路径,取消则返回 null
|
||||
*/
|
||||
openSceneDialog(): Promise<string | null>;
|
||||
|
||||
/**
|
||||
* 打开保存场景对话框
|
||||
* @param defaultName 默认文件名
|
||||
* @returns 用户选择的文件路径,取消则返回 null
|
||||
*/
|
||||
saveSceneDialog(defaultName?: string): Promise<string | null>;
|
||||
|
||||
/**
|
||||
* 读取文件内容
|
||||
* @param path 文件路径
|
||||
* @returns 文件内容(文本格式)
|
||||
*/
|
||||
readFileContent(path: string): Promise<string>;
|
||||
|
||||
/**
|
||||
* 保存项目文件
|
||||
* @param path 保存路径
|
||||
* @param data 文件内容(文本格式)
|
||||
*/
|
||||
saveProject(path: string, data: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* 导出二进制文件
|
||||
* @param data 二进制数据
|
||||
* @param path 保存路径
|
||||
*/
|
||||
exportBinary(data: Uint8Array, path: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* 创建目录
|
||||
* @param path 目录路径
|
||||
*/
|
||||
createDirectory(path: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* 写入文件内容
|
||||
* @param path 文件路径
|
||||
* @param content 文件内容
|
||||
*/
|
||||
writeFileContent(path: string, content: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* 检查路径是否存在
|
||||
* @param path 文件或目录路径
|
||||
* @returns 路径是否存在
|
||||
*/
|
||||
pathExists(path: string): Promise<boolean>;
|
||||
}
|
||||
@@ -16,8 +16,9 @@ export * from './Services/LocaleService';
|
||||
export * from './Services/PropertyMetadata';
|
||||
export * from './Services/ProjectService';
|
||||
export * from './Services/ComponentDiscoveryService';
|
||||
export * from './Services/ComponentLoaderService';
|
||||
export * from './Services/LogService';
|
||||
export * from './Services/SettingsRegistry';
|
||||
export * from './Services/SceneManagerService';
|
||||
|
||||
export * from './Types/UITypes';
|
||||
export * from './Types/IFileAPI';
|
||||
|
||||