Feature/tilemap editor (#237)

* feat: 添加 Tilemap 编辑器插件和组件生命周期支持

* feat(editor-core): 添加声明式插件注册 API

* feat(editor-core): 改进tiledmap结构合并tileset进tiledmapeditor

* feat: 添加 editor-runtime SDK 和插件系统改进

* fix(ci): 修复SceneResourceManager里变量未使用问题
This commit is contained in:
YHH
2025-11-25 22:23:19 +08:00
committed by GitHub
parent 551ca7805d
commit 3fb6f919f8
166 changed files with 54691 additions and 8674 deletions

View File

@@ -95,27 +95,40 @@ export function AssetBrowser({ projectPath, locale, onOpenScene }: AssetBrowserP
const unsubscribe = messageHub.subscribe('asset:reveal', async (data: any) => {
const filePath = data.path;
if (filePath) {
const lastSlashIndex = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
const dirPath = lastSlashIndex > 0 ? filePath.substring(0, lastSlashIndex) : null;
if (dirPath) {
if (!filePath || !projectPath) return;
// Convert relative path to absolute path if needed
let absoluteFilePath = filePath;
if (!filePath.includes(':') && !filePath.startsWith('/')) {
absoluteFilePath = `${projectPath}/${filePath}`.replace(/\\/g, '/');
}
const lastSlashIndex = Math.max(absoluteFilePath.lastIndexOf('/'), absoluteFilePath.lastIndexOf('\\'));
const dirPath = lastSlashIndex > 0 ? absoluteFilePath.substring(0, lastSlashIndex) : null;
if (dirPath) {
try {
const dirExists = await TauriAPI.pathExists(dirPath);
if (!dirExists) return;
setCurrentPath(dirPath);
// Load assets first, then set selection after list is populated
await loadAssets(dirPath);
setSelectedPaths(new Set([filePath]));
setSelectedPaths(new Set([absoluteFilePath]));
// Expand tree to reveal the file
if (showDetailView) {
detailViewFileTreeRef.current?.revealPath(filePath);
detailViewFileTreeRef.current?.revealPath(absoluteFilePath);
} else {
treeOnlyViewFileTreeRef.current?.revealPath(filePath);
treeOnlyViewFileTreeRef.current?.revealPath(absoluteFilePath);
}
} catch (error) {
console.error(`[AssetBrowser] Failed to reveal asset: ${absoluteFilePath}`, error);
}
}
});
return () => unsubscribe();
}, [showDetailView]);
}, [showDetailView, projectPath]);
const loadAssets = async (path: string) => {
setLoading(true);

View File

@@ -3,7 +3,7 @@ import { Core, IService, ServiceType } from '@esengine/ecs-framework';
import { CompilerRegistry, ICompiler, CompilerContext, CompileResult, IFileSystem, IDialog, FileEntry } from '@esengine/editor-core';
import { X, Play, Loader2 } from 'lucide-react';
import { open as tauriOpen, save as tauriSave, message as tauriMessage, confirm as tauriConfirm } from '@tauri-apps/plugin-dialog';
import { invoke } from '@tauri-apps/api/core';
import { invoke, convertFileSrc } from '@tauri-apps/api/core';
import '../styles/CompilerConfigDialog.css';
interface DirectoryEntry {
@@ -98,7 +98,11 @@ export const CompilerConfigDialog: React.FC<CompilerConfigDialogProps> = ({
return entries
.filter((e) => !e.is_dir && e.name.endsWith(ext))
.map((e) => e.name.replace(ext, ''));
}
},
convertToAssetUrl: (filePath: string) => {
return convertFileSrc(filePath);
},
dispose: () => {}
});
const createDialog = (): IDialog => ({
@@ -124,7 +128,8 @@ export const CompilerConfigDialog: React.FC<CompilerConfigDialogProps> = ({
},
showConfirm: async (title: string, message: string) => {
return await tauriConfirm(message, { title });
}
},
dispose: () => {}
});
const createContext = (): CompilerContext => ({

View File

@@ -91,7 +91,11 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit
};
const handlePropertyChange = (component: any, propertyName: string, value: any) => {
if (!selectedEntity) return;
console.log('[EntityInspector] handlePropertyChange called:', propertyName, value);
if (!selectedEntity) {
console.log('[EntityInspector] No selectedEntity, returning');
return;
}
// Actually update the component property
// 实际更新组件属性
@@ -103,6 +107,10 @@ export function EntityInspector({ entityStore: _entityStore, messageHub }: Entit
propertyName,
value
});
// Also publish scene:modified so other panels can react
console.log('[EntityInspector] Publishing scene:modified');
messageHub.publish('scene:modified', {});
};
const renderRemoteProperty = (key: string, value: any) => {

View File

@@ -92,10 +92,16 @@ export const FileTree = forwardRef<FileTreeHandle, FileTreeProps>(({ rootPath, o
// Expand tree to reveal a specific file path
const revealPath = async (targetPath: string) => {
if (!rootPath || !targetPath.startsWith(rootPath)) return;
if (!rootPath) return;
// Normalize paths to use forward slashes for comparison
const normalizedTargetPath = targetPath.replace(/\\/g, '/');
const normalizedRootPath = rootPath.replace(/\\/g, '/');
if (!normalizedTargetPath.startsWith(normalizedRootPath)) return;
// Get path segments between root and target
const relativePath = targetPath.substring(rootPath.length).replace(/^[/\\]/, '');
const relativePath = normalizedTargetPath.substring(normalizedRootPath.length).replace(/^[/\\]/, '');
const segments = relativePath.split(/[/\\]/);
// Build list of folder paths to expand
@@ -748,9 +754,20 @@ export const FileTree = forwardRef<FileTreeHandle, FileTreeProps>(({ rootPath, o
};
const renderNode = (node: TreeNode, level: number = 0) => {
const isSelected = selectedPaths
? selectedPaths.has(node.path)
: (internalSelectedPath || selectedPath) === node.path;
// Normalize paths for comparison (handle forward/backward slashes)
const normalizedNodePath = node.path.replace(/\\/g, '/');
const normalizedInternalPath = internalSelectedPath?.replace(/\\/g, '/');
const normalizedSelectedPath = selectedPath?.replace(/\\/g, '/');
// Check if this node is selected, normalizing paths for comparison
let isSelected = false;
if (selectedPaths) {
// Check both original path and normalized path in selectedPaths set
isSelected = selectedPaths.has(node.path) || selectedPaths.has(normalizedNodePath);
} else {
isSelected = (normalizedInternalPath || normalizedSelectedPath) === normalizedNodePath;
}
const isRenaming = renamingNode === node.path;
const indent = level * 16;

View File

@@ -215,6 +215,8 @@ export function Inspector({ entityStore: _entityStore, messageHub, inspectorRegi
propertyName,
value
});
// Also publish scene:modified so other panels can react to changes
messageHub.publish('scene:modified', {});
};
const renderRemoteProperty = (key: string, value: any) => {

View File

@@ -1,9 +1,11 @@
import { useState, useEffect, useRef } from 'react';
import { Component, Core } from '@esengine/ecs-framework';
import { PropertyMetadataService, PropertyMetadata, PropertyAction, MessageHub } from '@esengine/editor-core';
import { PropertyMetadataService, PropertyMetadata, PropertyAction, MessageHub, IFileSystemService } from '@esengine/editor-core';
import type { IFileSystem } from '@esengine/editor-core';
import { ChevronRight, ChevronDown, ArrowRight, Lock } from 'lucide-react';
import * as LucideIcons from 'lucide-react';
import { AnimationClipsFieldEditor } from '../infrastructure/field-editors/AnimationClipsFieldEditor';
import { AssetSaveDialog } from './dialogs/AssetSaveDialog';
import '../styles/PropertyInspector.css';
const animationClipsEditor = new AnimationClipsFieldEditor();
@@ -80,6 +82,12 @@ export function PropertyInspector({ component, entity, version, onChange, onActi
if (onChange) {
onChange(propertyName, value);
}
// Always publish scene:modified so other panels can react to changes
const messageHub = Core.services.resolve(MessageHub);
if (messageHub) {
messageHub.publish('scene:modified', {});
}
};
// Read value directly from component to avoid state sync issues
@@ -187,6 +195,7 @@ export function PropertyInspector({ component, entity, version, onChange, onActi
fileExtension={metadata.fileExtension}
readOnly={metadata.readOnly || !!controlledBy}
controlledBy={controlledBy}
entityId={entity?.id?.toString()}
onChange={(newValue) => handleChange(propertyName, newValue)}
/>
);
@@ -469,6 +478,7 @@ function ColorField({ label, value, readOnly, onChange }: ColorFieldProps) {
const v = Math.max(0, Math.min(100, 100 - ((e.clientY - rect.top) / rect.height) * 100));
const newColor = hsvToHex(hsv.h, s, v);
setTempColor(newColor);
onChange(newColor); // Real-time update
};
const handleHueChange = (e: React.MouseEvent<HTMLDivElement>) => {
@@ -476,6 +486,7 @@ function ColorField({ label, value, readOnly, onChange }: ColorFieldProps) {
const h = Math.max(0, Math.min(360, ((e.clientX - rect.left) / rect.width) * 360));
const newColor = hsvToHex(h, hsv.s, hsv.v);
setTempColor(newColor);
onChange(newColor); // Real-time update
};
return (
@@ -857,11 +868,90 @@ interface AssetDropFieldProps {
fileExtension?: string;
readOnly?: boolean;
controlledBy?: string;
entityId?: string;
onChange: (value: string) => void;
}
function AssetDropField({ label, value, fileExtension, readOnly, controlledBy, onChange }: AssetDropFieldProps) {
function AssetDropField({ label, value, fileExtension, readOnly, controlledBy, entityId, onChange }: AssetDropFieldProps) {
const [isDragging, setIsDragging] = useState(false);
const [showSaveDialog, setShowSaveDialog] = useState(false);
const canCreate = fileExtension && ['.tilemap.json', '.btree'].includes(fileExtension);
const handleCreate = () => {
setShowSaveDialog(true);
};
const handleSaveAsset = async (relativePath: string) => {
const fileSystem = Core.services.tryResolve<IFileSystem>(IFileSystemService);
const messageHub = Core.services.tryResolve(MessageHub);
if (!fileSystem) {
console.error('[AssetDropField] FileSystem service not available');
return;
}
try {
// Get absolute path from project
const projectService = Core.services.tryResolve(
(await import('@esengine/editor-core')).ProjectService
);
const currentProject = projectService?.getCurrentProject();
if (!currentProject) {
console.error('[AssetDropField] No project loaded');
return;
}
const absolutePath = `${currentProject.path}/${relativePath}`.replace(/\\/g, '/');
// Create default content based on file type
let defaultContent = '';
if (fileExtension === '.tilemap.json') {
defaultContent = JSON.stringify({
name: 'New Tilemap',
version: 2,
width: 20,
height: 15,
tileWidth: 16,
tileHeight: 16,
layers: [
{
id: 'default',
name: 'Layer 0',
visible: true,
opacity: 1,
data: new Array(20 * 15).fill(0)
}
],
tilesets: []
}, null, 2);
} else if (fileExtension === '.btree') {
defaultContent = JSON.stringify({
name: 'New Behavior Tree',
version: 1,
nodes: [],
connections: []
}, null, 2);
}
// Write file
await fileSystem.writeFile(absolutePath, defaultContent);
// Update component with relative path
onChange(relativePath);
// Open editor panel if tilemap
if (messageHub && fileExtension === '.tilemap.json' && entityId) {
const { useTilemapEditorStore } = await import('@esengine/tilemap-editor');
useTilemapEditorStore.getState().setEntityId(entityId);
messageHub.publish('dynamic-panel:open', { panelId: 'tilemap-editor', title: 'Tilemap Editor' });
}
console.log('[AssetDropField] Created asset:', relativePath);
} catch (error) {
console.error('[AssetDropField] Failed to create asset:', error);
}
};
const handleDragEnter = (e: React.DragEvent) => {
e.preventDefault();
@@ -890,8 +980,14 @@ function AssetDropField({ label, value, fileExtension, readOnly, controlledBy, o
if (assetPath) {
if (fileExtension) {
const extensions = fileExtension.split(',').map((ext) => ext.trim().toLowerCase());
const fileExt = assetPath.toLowerCase().split('.').pop();
if (fileExt && extensions.some((ext) => ext === `.${fileExt}` || ext === fileExt)) {
const lowerPath = assetPath.toLowerCase();
// Check if the path ends with any of the specified extensions
// This handles both simple extensions (.json) and compound extensions (.tilemap.json)
const isValidExtension = extensions.some((ext) => {
const normalizedExt = ext.startsWith('.') ? ext : `.${ext}`;
return lowerPath.endsWith(normalizedExt);
});
if (isValidExtension) {
onChange(assetPath);
}
} else {
@@ -943,6 +1039,18 @@ function AssetDropField({ label, value, fileExtension, readOnly, controlledBy, o
{value ? getFileName(value) : 'None'}
</span>
<div className="property-asset-actions">
{canCreate && !readOnly && !value && (
<button
className="property-asset-btn property-asset-btn-create"
onClick={(e) => {
e.stopPropagation();
handleCreate();
}}
title="创建新资产"
>
+
</button>
)}
{value && (
<button
className="property-asset-btn"
@@ -957,6 +1065,16 @@ function AssetDropField({ label, value, fileExtension, readOnly, controlledBy, o
)}
</div>
</div>
{/* Save Dialog */}
<AssetSaveDialog
isOpen={showSaveDialog}
onClose={() => setShowSaveDialog(false)}
onSave={handleSaveAsset}
title={fileExtension === '.tilemap.json' ? '创建 Tilemap 资产' : '创建资产'}
defaultFileName={fileExtension === '.tilemap.json' ? 'new-tilemap' : 'new-asset'}
fileExtension={fileExtension}
/>
</div>
);
}

View File

@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react';
import { Entity, Core } from '@esengine/ecs-framework';
import { EntityStoreService, MessageHub, SceneManagerService, CommandManager } from '@esengine/editor-core';
import { EntityStoreService, MessageHub, SceneManagerService, CommandManager, EntityCreationRegistry, EntityCreationTemplate } from '@esengine/editor-core';
import { useLocale } from '../hooks/useLocale';
import { Box, Layers, Wifi, Search, Plus, Trash2, Monitor, Globe, Image, Camera, Film } from 'lucide-react';
import { ProfilerService, RemoteEntity } from '../services/ProfilerService';
@@ -31,10 +31,32 @@ export function SceneHierarchy({ entityStore, messageHub, commandManager, isProf
const [contextMenu, setContextMenu] = useState<{ x: number; y: number; entityId: number | null } | null>(null);
const [draggedEntityId, setDraggedEntityId] = useState<number | null>(null);
const [dropTargetIndex, setDropTargetIndex] = useState<number | null>(null);
const [pluginTemplates, setPluginTemplates] = useState<EntityCreationTemplate[]>([]);
const { t, locale } = useLocale();
const isShowingRemote = viewMode === 'remote' && isRemoteConnected;
// Get entity creation templates from plugins
useEffect(() => {
const updateTemplates = () => {
const registry = Core.services.resolve(EntityCreationRegistry);
if (registry) {
setPluginTemplates(registry.getAll());
}
};
updateTemplates();
// Update when plugins are installed
const unsubInstalled = messageHub.subscribe('plugin:installed', updateTemplates);
const unsubUninstalled = messageHub.subscribe('plugin:uninstalled', updateTemplates);
return () => {
unsubInstalled();
unsubUninstalled();
};
}, [messageHub]);
// Subscribe to scene changes
useEffect(() => {
const sceneManager = Core.services.resolve(SceneManagerService);
@@ -535,6 +557,23 @@ export function SceneHierarchy({ entityStore, messageHub, commandManager, isProf
<Camera size={12} />
<span>{locale === 'zh' ? '创建相机' : 'Create Camera'}</span>
</button>
{pluginTemplates.length > 0 && (
<>
<div className="context-menu-divider" />
{pluginTemplates.map((template) => (
<button
key={template.id}
onClick={async () => {
await template.create(contextMenu.entityId ?? undefined);
closeContextMenu();
}}
>
{template.icon || <Plus size={12} />}
<span>{template.label}</span>
</button>
))}
</>
)}
{contextMenu.entityId && (
<>
<div className="context-menu-divider" />

View File

@@ -43,7 +43,7 @@ function generateRuntimeHtml(): string {
<canvas id="runtime-canvas"></canvas>
<script src="/runtime.browser.js"></script>
<script type="module">
import * as esEngine from '/engine.js';
import * as esEngine from '/es_engine.js';
(async function() {
try {
// Set canvas size before creating runtime
@@ -361,7 +361,8 @@ export function Viewport({ locale = 'en', messageHub }: ViewportProps) {
};
}, []);
// Sync camera state to engine
// Sync camera state to engine and publish camera:updated event
// 同步相机状态到引擎并发布 camera:updated 事件
useEffect(() => {
if (engine.state.initialized) {
EngineService.getInstance().setCamera({
@@ -370,6 +371,17 @@ export function Viewport({ locale = 'en', messageHub }: ViewportProps) {
zoom: camera2DZoom,
rotation: 0
});
// Publish camera update event for other systems
// 发布相机更新事件供其他系统使用
const hub = messageHubRef.current;
if (hub) {
hub.publish('camera:updated', {
x: camera2DOffset.x,
y: camera2DOffset.y,
zoom: camera2DZoom
});
}
}
}, [camera2DOffset, camera2DZoom, engine.state.initialized]);
@@ -473,11 +485,11 @@ export function Viewport({ locale = 'en', messageHub }: ViewportProps) {
}
};
const handleStop = () => {
const handleStop = async () => {
setPlayState('stopped');
engine.stop();
// Restore scene snapshot
EngineService.getInstance().restoreSceneSnapshot();
await EngineService.getInstance().restoreSceneSnapshot();
// Restore editor camera state
setCamera2DOffset({ x: editorCameraRef.current.x, y: editorCameraRef.current.y });
setCamera2DZoom(editorCameraRef.current.zoom);

View File

@@ -197,3 +197,119 @@
color: #666;
cursor: not-allowed;
}
/* Asset Save Dialog specific styles */
.asset-save-filename {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 16px;
border-top: 1px solid #333;
background: #252525;
}
.asset-save-filename label {
font-size: 12px;
color: #888;
white-space: nowrap;
}
.asset-save-filename input {
flex: 1;
background: #1a1a1a;
border: 1px solid #333;
border-radius: 4px;
padding: 6px 8px;
color: #e0e0e0;
font-size: 12px;
outline: none;
}
.asset-save-filename input:focus {
border-color: #1976d2;
}
.asset-save-extension {
font-size: 11px;
color: #666;
white-space: nowrap;
}
/* New folder styles */
.asset-save-new-folder-btn {
padding: 8px 16px;
border-top: 1px solid #333;
}
.asset-save-new-folder-btn button {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
background: #333;
border: none;
border-radius: 4px;
color: #e0e0e0;
font-size: 12px;
cursor: pointer;
}
.asset-save-new-folder-btn button:hover {
background: #444;
}
.asset-save-new-folder {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
border-top: 1px solid #333;
background: #252525;
}
.asset-save-new-folder input {
flex: 1;
background: #1a1a1a;
border: 1px solid #333;
border-radius: 4px;
padding: 6px 8px;
color: #e0e0e0;
font-size: 12px;
outline: none;
}
.asset-save-new-folder input:focus {
border-color: #1976d2;
}
.asset-save-new-folder button {
padding: 6px 12px;
border-radius: 4px;
font-size: 12px;
cursor: pointer;
border: none;
}
.asset-save-new-folder button:first-of-type {
background: #1976d2;
color: white;
}
.asset-save-new-folder button:first-of-type:hover {
background: #1565c0;
}
.asset-save-new-folder button:first-of-type:disabled {
background: #333;
color: #666;
cursor: not-allowed;
}
.asset-save-new-folder button:last-child {
background: #333;
color: #e0e0e0;
}
.asset-save-new-folder button:last-child:hover {
background: #444;
}

View File

@@ -149,19 +149,34 @@ export function AssetPickerDialog({
}
}, [toggleFolder]);
// Convert absolute path to relative path based on project root
const toRelativePath = useCallback((absolutePath: string): string => {
const projectService = Core.services.tryResolve(ProjectService);
const currentProject = projectService?.getCurrentProject();
if (currentProject) {
const projectPath = currentProject.path.replace(/\\/g, '/');
const normalizedAbsolute = absolutePath.replace(/\\/g, '/');
if (normalizedAbsolute.startsWith(projectPath)) {
// Return relative path from project root
return normalizedAbsolute.substring(projectPath.length + 1);
}
}
return absolutePath;
}, []);
const handleConfirm = useCallback(() => {
if (selectedPath) {
onSelect(selectedPath);
onSelect(toRelativePath(selectedPath));
onClose();
}
}, [selectedPath, onSelect, onClose]);
}, [selectedPath, onSelect, onClose, toRelativePath]);
const handleDoubleClick = useCallback((node: FileNode) => {
if (!node.isDirectory) {
onSelect(node.path);
onSelect(toRelativePath(node.path));
onClose();
}
}, [onSelect, onClose]);
}, [onSelect, onClose, toRelativePath]);
const getFileIcon = (name: string) => {
const ext = name.split('.').pop()?.toLowerCase();

View File

@@ -0,0 +1,374 @@
import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { X, Search, Folder, FolderOpen, FolderPlus } from 'lucide-react';
import { Core } from '@esengine/ecs-framework';
import { ProjectService, IFileSystemService } from '@esengine/editor-core';
import type { IFileSystem } from '@esengine/editor-core';
import './AssetPickerDialog.css';
interface AssetSaveDialogProps {
isOpen: boolean;
onClose: () => void;
onSave: (path: string) => void;
title?: string;
defaultFileName?: string;
fileExtension?: string; // e.g., '.tilemap.json'
placeholder?: string;
}
interface FileNode {
name: string;
path: string;
isDirectory: boolean;
children?: FileNode[];
}
export function AssetSaveDialog({
isOpen,
onClose,
onSave,
title = 'Save Asset',
defaultFileName = 'new-asset',
fileExtension = '',
placeholder = 'Search folders...'
}: AssetSaveDialogProps) {
const [searchTerm, setSearchTerm] = useState('');
const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());
const [selectedFolder, setSelectedFolder] = useState<string | null>(null);
const [fileName, setFileName] = useState(defaultFileName);
const [folders, setFolders] = useState<FileNode[]>([]);
const [loading, setLoading] = useState(false);
const [projectPath, setProjectPath] = useState('');
const [showNewFolderInput, setShowNewFolderInput] = useState(false);
const [newFolderName, setNewFolderName] = useState('');
// Load project folders
useEffect(() => {
if (!isOpen) return;
const loadFolders = async () => {
setLoading(true);
try {
const projectService = Core.services.tryResolve(ProjectService);
const fileSystem = Core.services.tryResolve<IFileSystem>(IFileSystemService);
const currentProject = projectService?.getCurrentProject();
if (projectService && currentProject && fileSystem) {
const projPath = currentProject.path;
setProjectPath(projPath);
const assetsPath = `${projPath}/assets`;
// Set default selected folder to assets
setSelectedFolder(assetsPath);
const buildTree = async (dirPath: string): Promise<FileNode[]> => {
const entries = await fileSystem.listDirectory(dirPath);
const nodes: FileNode[] = [];
for (const entry of entries) {
// Only include directories
if (entry.isDirectory) {
const node: FileNode = {
name: entry.name,
path: entry.path,
isDirectory: true
};
try {
node.children = await buildTree(entry.path);
} catch {
node.children = [];
}
nodes.push(node);
}
}
// Sort alphabetically
return nodes.sort((a, b) => a.name.localeCompare(b.name));
};
const tree = await buildTree(assetsPath);
// Add root assets folder
const rootNode: FileNode = {
name: 'assets',
path: assetsPath,
isDirectory: true,
children: tree
};
setFolders([rootNode]);
setExpandedFolders(new Set([assetsPath]));
}
} catch (error) {
console.error('Failed to load folders:', error);
} finally {
setLoading(false);
}
};
loadFolders();
setFileName(defaultFileName);
setSearchTerm('');
}, [isOpen, defaultFileName]);
// Filter folders based on search
const filteredFolders = useMemo(() => {
if (!searchTerm) return folders;
const filterNode = (node: FileNode): FileNode | null => {
const matchesSearch = node.name.toLowerCase().includes(searchTerm.toLowerCase());
if (node.children) {
const filteredChildren = node.children
.map(filterNode)
.filter((n): n is FileNode => n !== null);
if (filteredChildren.length > 0 || matchesSearch) {
return { ...node, children: filteredChildren };
}
}
return matchesSearch ? node : null;
};
return folders
.map(filterNode)
.filter((n): n is FileNode => n !== null);
}, [folders, searchTerm]);
const toggleFolder = useCallback((path: string) => {
setExpandedFolders((prev) => {
const next = new Set(prev);
if (next.has(path)) {
next.delete(path);
} else {
next.add(path);
}
return next;
});
}, []);
const handleSelectFolder = useCallback((node: FileNode) => {
setSelectedFolder(node.path);
if (!expandedFolders.has(node.path)) {
toggleFolder(node.path);
}
}, [expandedFolders, toggleFolder]);
// Convert absolute path to relative path based on project root
const toRelativePath = useCallback((absolutePath: string): string => {
if (projectPath) {
const normalizedProject = projectPath.replace(/\\/g, '/');
const normalizedAbsolute = absolutePath.replace(/\\/g, '/');
if (normalizedAbsolute.startsWith(normalizedProject)) {
return normalizedAbsolute.substring(normalizedProject.length + 1);
}
}
return absolutePath;
}, [projectPath]);
const handleSave = useCallback(() => {
if (selectedFolder && fileName) {
// Ensure file has correct extension
let finalFileName = fileName;
if (fileExtension && !finalFileName.endsWith(fileExtension)) {
finalFileName += fileExtension;
}
const fullPath = `${selectedFolder}/${finalFileName}`.replace(/\\/g, '/');
onSave(toRelativePath(fullPath));
onClose();
}
}, [selectedFolder, fileName, fileExtension, onSave, onClose, toRelativePath]);
const handleCreateFolder = useCallback(async () => {
if (!selectedFolder || !newFolderName.trim()) return;
const fileSystem = Core.services.tryResolve<IFileSystem>(IFileSystemService);
if (!fileSystem) return;
try {
const newFolderPath = `${selectedFolder}/${newFolderName.trim()}`.replace(/\\/g, '/');
await fileSystem.createDirectory(newFolderPath);
// Add new folder to tree
const addFolderToTree = (nodes: FileNode[]): FileNode[] => {
return nodes.map(node => {
if (node.path === selectedFolder) {
const newNode: FileNode = {
name: newFolderName.trim(),
path: newFolderPath,
isDirectory: true,
children: []
};
return {
...node,
children: [...(node.children || []), newNode].sort((a, b) => a.name.localeCompare(b.name))
};
}
if (node.children) {
return { ...node, children: addFolderToTree(node.children) };
}
return node;
});
};
setFolders(addFolderToTree(folders));
setSelectedFolder(newFolderPath);
setExpandedFolders(prev => new Set([...prev, selectedFolder]));
setShowNewFolderInput(false);
setNewFolderName('');
} catch (error) {
console.error('Failed to create folder:', error);
}
}, [selectedFolder, newFolderName, folders]);
const renderNode = (node: FileNode, depth: number = 0) => {
const isExpanded = expandedFolders.has(node.path);
const isSelected = selectedFolder === node.path;
return (
<div key={node.path}>
<div
className={`asset-picker-item ${isSelected ? 'selected' : ''}`}
style={{ paddingLeft: `${depth * 16 + 8}px` }}
onClick={() => handleSelectFolder(node)}
onDoubleClick={() => toggleFolder(node.path)}
>
<span className="asset-picker-item__icon">
{isExpanded ? <FolderOpen size={14} /> : <Folder size={14} />}
</span>
<span className="asset-picker-item__name">{node.name}</span>
</div>
{isExpanded && node.children && (
<div className="asset-picker-children">
{node.children.map((child) => renderNode(child, depth + 1))}
</div>
)}
</div>
);
};
const getDisplayPath = () => {
if (!selectedFolder) return '';
const relativePath = toRelativePath(selectedFolder);
let finalFileName = fileName;
if (fileExtension && !finalFileName.endsWith(fileExtension)) {
finalFileName += fileExtension;
}
return `${relativePath}/${finalFileName}`;
};
if (!isOpen) return null;
return (
<div className="asset-picker-overlay" onClick={onClose}>
<div className="asset-picker-dialog" onClick={(e) => e.stopPropagation()}>
<div className="asset-picker-header">
<h3>{title}</h3>
<button className="asset-picker-close" onClick={onClose}>
<X size={16} />
</button>
</div>
<div className="asset-picker-search">
<Search size={14} />
<input
type="text"
placeholder={placeholder}
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
<div className="asset-picker-content">
{loading ? (
<div className="asset-picker-loading">Loading folders...</div>
) : filteredFolders.length === 0 ? (
<div className="asset-picker-empty">No folders found</div>
) : (
<div className="asset-picker-tree">
{filteredFolders.map((node) => renderNode(node))}
</div>
)}
</div>
{/* New folder input */}
{showNewFolderInput && (
<div className="asset-save-new-folder">
<input
type="text"
value={newFolderName}
onChange={(e) => setNewFolderName(e.target.value)}
placeholder="New folder name"
autoFocus
onKeyDown={(e) => {
if (e.key === 'Enter') handleCreateFolder();
if (e.key === 'Escape') {
setShowNewFolderInput(false);
setNewFolderName('');
}
}}
/>
<button onClick={handleCreateFolder} disabled={!newFolderName.trim()}>
Create
</button>
<button onClick={() => {
setShowNewFolderInput(false);
setNewFolderName('');
}}>
Cancel
</button>
</div>
)}
{/* New folder button */}
{!showNewFolderInput && selectedFolder && (
<div className="asset-save-new-folder-btn">
<button onClick={() => setShowNewFolderInput(true)}>
<FolderPlus size={14} />
New Folder
</button>
</div>
)}
<div className="asset-save-filename">
<label>File name:</label>
<input
type="text"
value={fileName}
onChange={(e) => setFileName(e.target.value)}
placeholder="Enter file name"
autoFocus
/>
{fileExtension && (
<span className="asset-save-extension">{fileExtension}</span>
)}
</div>
<div className="asset-picker-footer">
<div className="asset-picker-selected">
{selectedFolder ? (
<span title={getDisplayPath()}>
{getDisplayPath()}
</span>
) : (
<span className="placeholder">Select a folder</span>
)}
</div>
<div className="asset-picker-actions">
<button className="btn-cancel" onClick={onClose}>
Cancel
</button>
<button
className="btn-confirm"
onClick={handleSave}
disabled={!selectedFolder || !fileName}
>
Save
</button>
</div>
</div>
</div>
</div>
);
}

View File

@@ -113,6 +113,16 @@
color: #f87171;
}
/* 创建按钮特殊样式 */
.asset-field__button--create {
color: #4ade80;
}
.asset-field__button--create:hover {
background: #1a3a1a;
color: #4ade80;
}
/* 禁用状态 */
.asset-field__container[disabled] {
opacity: 0.6;

View File

@@ -1,5 +1,5 @@
import React, { useState, useRef, useCallback } from 'react';
import { FileText, Search, X, FolderOpen, ArrowRight, Package } from 'lucide-react';
import { FileText, Search, X, FolderOpen, ArrowRight, Package, Plus } from 'lucide-react';
import { AssetPickerDialog } from '../../../components/dialogs/AssetPickerDialog';
import './AssetField.css';
@@ -11,6 +11,7 @@ interface AssetFieldProps {
placeholder?: string;
readonly?: boolean;
onNavigate?: (path: string) => void; // 导航到资产
onCreate?: () => void; // 创建新资产
}
export function AssetField({
@@ -20,7 +21,8 @@ export function AssetField({
fileExtension = '',
placeholder = 'None',
readonly = false,
onNavigate
onNavigate,
onCreate
}: AssetFieldProps) {
const [isDragging, setIsDragging] = useState(false);
const [isHovered, setIsHovered] = useState(false);
@@ -137,6 +139,20 @@ export function AssetField({
{/* 操作按钮组 */}
<div className="asset-field__actions">
{/* 创建按钮 */}
{onCreate && !readonly && !value && (
<button
className="asset-field__button asset-field__button--create"
onClick={(e) => {
e.stopPropagation();
onCreate();
}}
title="创建新资产"
>
<Plus size={12} />
</button>
)}
{/* 浏览按钮 */}
{!readonly && (
<button

View File

@@ -1,7 +1,7 @@
import { useState } from 'react';
import { Settings, ChevronDown, ChevronRight, X, Plus, Box } from 'lucide-react';
import { Entity, Component, Core, getComponentDependencies, getComponentTypeName, getComponentInstanceTypeName } from '@esengine/ecs-framework';
import { MessageHub, CommandManager, ComponentRegistry } from '@esengine/editor-core';
import { MessageHub, CommandManager, ComponentRegistry, ComponentActionRegistry } from '@esengine/editor-core';
import { PropertyInspector } from '../../PropertyInspector';
import { NotificationService } from '../../../services/NotificationService';
import { RemoveComponentCommand, UpdateComponentCommand, AddComponentCommand } from '../../../application/commands/component';
@@ -21,6 +21,7 @@ export function EntityInspector({ entity, messageHub, commandManager, componentV
const [localVersion, setLocalVersion] = useState(0);
const componentRegistry = Core.services.resolve(ComponentRegistry);
const componentActionRegistry = Core.services.resolve(ComponentActionRegistry);
const availableComponents = componentRegistry?.getAllComponents() || [];
const toggleComponentExpanded = (index: number) => {
@@ -252,6 +253,32 @@ export function EntityInspector({ entity, messageHub, commandManager, componentV
}
onAction={handlePropertyAction}
/>
{/* Dynamic component actions from plugins */}
{componentActionRegistry?.getActionsForComponent(componentName).map((action) => (
<button
key={action.id}
className="component-action-btn"
onClick={() => action.execute(component, entity)}
style={{
display: 'flex',
alignItems: 'center',
gap: '6px',
padding: '8px 12px',
width: '100%',
marginTop: '8px',
border: 'none',
borderRadius: '4px',
background: 'var(--accent-color, #0078d4)',
color: 'white',
cursor: 'pointer',
fontSize: '12px',
fontWeight: 500,
}}
>
{action.icon}
{action.label}
</button>
))}
</div>
)}
</div>