refactor(editor): 提取行为树编辑器为独立包并重构编辑器架构 (#216)

* refactor(editor): 提取行为树编辑器为独立包并重构编辑器架构

* feat(editor): 添加插件市场功能

* feat(editor): 重构插件市场以支持版本管理和ZIP打包

* feat(editor): 重构插件发布流程并修复React渲染警告

* fix(plugin): 修复插件发布和市场的路径不一致问题

* feat: 重构插件发布流程并添加插件删除功能

* fix(editor): 完善插件删除功能并修复多个关键问题

* fix(auth): 修复自动登录与手动登录的竞态条件问题

* feat(editor): 重构插件管理流程

* feat(editor): 支持 ZIP 文件直接发布插件

- 新增 PluginSourceParser 解析插件源
- 重构发布流程支持文件夹和 ZIP 两种方式
- 优化发布向导 UI

* feat(editor): 插件市场支持多版本安装

- 插件解压到项目 plugins 目录
- 新增 Tauri 后端安装/卸载命令
- 支持选择任意版本安装
- 修复打包逻辑,保留完整 dist 目录结构

* feat(editor): 个人中心支持多版本管理

- 合并同一插件的不同版本
- 添加版本历史展开/折叠功能
- 禁止有待审核 PR 时更新插件

* fix(editor): 修复 InspectorRegistry 服务注册

- InspectorRegistry 实现 IService 接口
- 注册到 Core.services 供插件使用

* feat(behavior-tree-editor): 完善插件注册和文件操作

- 添加文件创建模板和操作处理器
- 实现右键菜单创建行为树功能
- 修复文件读取权限问题(使用 Tauri 命令)
- 添加 BehaviorTreeEditorPanel 组件
- 修复 rollup 配置支持动态导入

* feat(plugin): 完善插件构建和发布流程

* fix(behavior-tree-editor): 完整恢复编辑器并修复 Toast 集成

* fix(behavior-tree-editor): 修复节点选中、连线跟随和文件加载问题并优化性能

* fix(behavior-tree-editor): 修复端口连接失败问题并优化连线样式

* refactor(behavior-tree-editor): 移除调试面板功能简化代码结构

* refactor(behavior-tree-editor): 清理冗余代码合并重复逻辑

* feat(behavior-tree-editor): 完善编辑器核心功能增强扩展性

* fix(lint): 修复ESLint错误确保CI通过

* refactor(behavior-tree-editor): 优化编辑器工具栏和编译器功能

* refactor(behavior-tree-editor): 清理技术债务,优化代码质量

* fix(editor-app): 修复字符串替换安全问题
This commit is contained in:
YHH
2025-11-18 14:46:51 +08:00
committed by GitHub
parent eac660b1a0
commit bce3a6e253
251 changed files with 26144 additions and 8844 deletions

View File

@@ -1,5 +1,5 @@
import { useState, useEffect, useRef } from 'react';
import { Folder, File, FileCode, FileJson, FileImage, FileText, FolderOpen, Copy, Trash2, Edit3, LayoutGrid, List, ChevronsUp } from 'lucide-react';
import { Folder, File, FileCode, FileJson, FileImage, FileText, FolderOpen, Copy, Trash2, Edit3, LayoutGrid, List, ChevronsUp, RefreshCw } from 'lucide-react';
import { Core } from '@esengine/ecs-framework';
import { MessageHub, FileActionRegistry } from '@esengine/editor-core';
import { TauriAPI, DirectoryEntry } from '../api/tauri';
@@ -43,6 +43,11 @@ export function AssetBrowser({ projectPath, locale, onOpenScene }: AssetBrowserP
position: { x: number; y: number };
asset: AssetItem;
} | null>(null);
const [renameDialog, setRenameDialog] = useState<{
asset: AssetItem;
newName: string;
} | null>(null);
const [deleteConfirmDialog, setDeleteConfirmDialog] = useState<AssetItem | null>(null);
const translations = {
en: {
@@ -251,6 +256,61 @@ export function AssetBrowser({ projectPath, locale, onOpenScene }: AssetBrowserP
}
};
const handleRename = async (asset: AssetItem, newName: string) => {
if (!newName.trim() || newName === asset.name) {
setRenameDialog(null);
return;
}
try {
const lastSlash = Math.max(asset.path.lastIndexOf('/'), asset.path.lastIndexOf('\\'));
const parentPath = asset.path.substring(0, lastSlash);
const newPath = `${parentPath}/${newName}`;
await TauriAPI.renameFileOrFolder(asset.path, newPath);
// 刷新当前目录
if (currentPath) {
await loadAssets(currentPath);
}
// 更新选中路径
if (selectedPath === asset.path) {
setSelectedPath(newPath);
}
setRenameDialog(null);
} catch (error) {
console.error('Failed to rename:', error);
alert(`重命名失败: ${error}`);
}
};
const handleDelete = async (asset: AssetItem) => {
try {
if (asset.type === 'folder') {
await TauriAPI.deleteFolder(asset.path);
} else {
await TauriAPI.deleteFile(asset.path);
}
// 刷新当前目录
if (currentPath) {
await loadAssets(currentPath);
}
// 清除选中状态
if (selectedPath === asset.path) {
setSelectedPath(null);
}
setDeleteConfirmDialog(null);
} catch (error) {
console.error('Failed to delete:', error);
alert(`删除失败: ${error}`);
}
};
const handleContextMenu = (e: React.MouseEvent, asset: AssetItem) => {
e.preventDefault();
setContextMenu({
@@ -262,7 +322,6 @@ export function AssetBrowser({ projectPath, locale, onOpenScene }: AssetBrowserP
const getContextMenuItems = (asset: AssetItem): ContextMenuItem[] => {
const items: ContextMenuItem[] = [];
// 打开
if (asset.type === 'file') {
items.push({
label: locale === 'zh' ? '打开' : 'Open',
@@ -292,6 +351,28 @@ export function AssetBrowser({ projectPath, locale, onOpenScene }: AssetBrowserP
items.push({ label: '', separator: true, onClick: () => {} });
}
if (asset.type === 'folder' && fileActionRegistry) {
const templates = fileActionRegistry.getCreationTemplates();
if (templates.length > 0) {
items.push({ label: '', separator: true, onClick: () => {} });
for (const template of templates) {
items.push({
label: `${locale === 'zh' ? '新建' : 'New'} ${template.label}`,
icon: template.icon,
onClick: async () => {
const fileName = `${template.defaultFileName}.${template.extension}`;
const filePath = `${asset.path}/${fileName}`;
const content = await template.createContent(fileName);
await TauriAPI.writeFileContent(filePath, content);
if (currentPath) {
await loadAssets(currentPath);
}
}
});
}
}
}
// 在文件管理器中显示
items.push({
label: locale === 'zh' ? '在文件管理器中显示' : 'Show in Explorer',
@@ -323,10 +404,13 @@ export function AssetBrowser({ projectPath, locale, onOpenScene }: AssetBrowserP
label: locale === 'zh' ? '重命名' : 'Rename',
icon: <Edit3 size={16} />,
onClick: () => {
// TODO: 实现重命名功能
console.log('Rename:', asset.path);
setRenameDialog({
asset,
newName: asset.name
});
setContextMenu(null);
},
disabled: true
disabled: false
});
// 删除
@@ -334,10 +418,10 @@ export function AssetBrowser({ projectPath, locale, onOpenScene }: AssetBrowserP
label: locale === 'zh' ? '删除' : 'Delete',
icon: <Trash2 size={16} />,
onClick: () => {
// TODO: 实现删除功能
console.log('Delete:', asset.path);
setDeleteConfirmDialog(asset);
setContextMenu(null);
},
disabled: true
disabled: false
});
return items;
@@ -482,6 +566,39 @@ export function AssetBrowser({ projectPath, locale, onOpenScene }: AssetBrowserP
>
<ChevronsUp size={14} />
</button>
<button
onClick={() => {
if (currentPath) {
loadAssets(currentPath);
}
if (showDetailView) {
detailViewFileTreeRef.current?.refresh();
} else {
treeOnlyViewFileTreeRef.current?.refresh();
}
}}
style={{
padding: '6px 8px',
background: 'transparent',
border: '1px solid #3e3e3e',
color: '#cccccc',
cursor: 'pointer',
transition: 'all 0.2s ease',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
borderRadius: '3px'
}}
onMouseEnter={(e) => {
e.currentTarget.style.background = '#2a2d2e';
}}
onMouseLeave={(e) => {
e.currentTarget.style.background = 'transparent';
}}
title="刷新资产列表"
>
<RefreshCw size={14} />
</button>
<input
type="text"
className="asset-search"
@@ -605,6 +722,117 @@ export function AssetBrowser({ projectPath, locale, onOpenScene }: AssetBrowserP
onClose={() => setContextMenu(null)}
/>
)}
{/* 重命名对话框 */}
{renameDialog && (
<div className="dialog-overlay" onClick={() => setRenameDialog(null)}>
<div className="dialog-content" onClick={(e) => e.stopPropagation()}>
<div className="dialog-header">
<h3>{locale === 'zh' ? '重命名' : 'Rename'}</h3>
</div>
<div className="dialog-body">
<input
type="text"
value={renameDialog.newName}
onChange={(e) => setRenameDialog({ ...renameDialog, newName: e.target.value })}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleRename(renameDialog.asset, renameDialog.newName);
} else if (e.key === 'Escape') {
setRenameDialog(null);
}
}}
autoFocus
style={{
width: '100%',
padding: '8px',
backgroundColor: '#2d2d2d',
border: '1px solid #3e3e3e',
borderRadius: '4px',
color: '#cccccc',
fontSize: '13px'
}}
/>
</div>
<div className="dialog-footer">
<button
onClick={() => setRenameDialog(null)}
style={{
padding: '6px 16px',
backgroundColor: '#3e3e3e',
border: 'none',
borderRadius: '4px',
color: '#cccccc',
cursor: 'pointer',
marginRight: '8px'
}}
>
{locale === 'zh' ? '取消' : 'Cancel'}
</button>
<button
onClick={() => handleRename(renameDialog.asset, renameDialog.newName)}
style={{
padding: '6px 16px',
backgroundColor: '#0e639c',
border: 'none',
borderRadius: '4px',
color: '#ffffff',
cursor: 'pointer'
}}
>
{locale === 'zh' ? '确定' : 'OK'}
</button>
</div>
</div>
</div>
)}
{/* 删除确认对话框 */}
{deleteConfirmDialog && (
<div className="dialog-overlay" onClick={() => setDeleteConfirmDialog(null)}>
<div className="dialog-content" onClick={(e) => e.stopPropagation()}>
<div className="dialog-header">
<h3>{locale === 'zh' ? '确认删除' : 'Confirm Delete'}</h3>
</div>
<div className="dialog-body">
<p style={{ margin: 0, color: '#cccccc' }}>
{locale === 'zh'
? `确定要删除 "${deleteConfirmDialog.name}" 吗?此操作不可撤销。`
: `Are you sure you want to delete "${deleteConfirmDialog.name}"? This action cannot be undone.`}
</p>
</div>
<div className="dialog-footer">
<button
onClick={() => setDeleteConfirmDialog(null)}
style={{
padding: '6px 16px',
backgroundColor: '#3e3e3e',
border: 'none',
borderRadius: '4px',
color: '#cccccc',
cursor: 'pointer',
marginRight: '8px'
}}
>
{locale === 'zh' ? '取消' : 'Cancel'}
</button>
<button
onClick={() => handleDelete(deleteConfirmDialog)}
style={{
padding: '6px 16px',
backgroundColor: '#c53030',
border: 'none',
borderRadius: '4px',
color: '#ffffff',
cursor: 'pointer'
}}
>
{locale === 'zh' ? '删除' : 'Delete'}
</button>
</div>
</div>
</div>
)}
</div>
);
}

View File

@@ -1,831 +0,0 @@
import { useState } from 'react';
import { Clipboard, Edit2, Trash2, ChevronDown, ChevronRight, Globe, Save, Folder, FileCode } from 'lucide-react';
import { save } from '@tauri-apps/plugin-dialog';
import { invoke } from '@tauri-apps/api/core';
import { Core } from '@esengine/ecs-framework';
import type { BlackboardValueType } from '@esengine/behavior-tree';
import { GlobalBlackboardService } from '@esengine/behavior-tree';
import { GlobalBlackboardTypeGenerator } from '../generators/GlobalBlackboardTypeGenerator';
import { createLogger } from '@esengine/ecs-framework';
const logger = createLogger('BehaviorTreeBlackboard');
type SimpleBlackboardType = 'number' | 'string' | 'boolean' | 'object';
interface BlackboardVariable {
key: string;
value: any;
type: SimpleBlackboardType;
}
interface BehaviorTreeBlackboardProps {
variables: Record<string, any>;
initialVariables?: Record<string, any>;
globalVariables?: Record<string, any>;
onVariableChange: (key: string, value: any) => void;
onVariableAdd: (key: string, value: any, type: SimpleBlackboardType) => void;
onVariableDelete: (key: string) => void;
onVariableRename?: (oldKey: string, newKey: string) => void;
onGlobalVariableChange?: (key: string, value: any) => void;
onGlobalVariableAdd?: (key: string, value: any, type: BlackboardValueType) => void;
onGlobalVariableDelete?: (key: string) => void;
projectPath?: string;
hasUnsavedGlobalChanges?: boolean;
onSaveGlobal?: () => void;
}
/**
* 行为树黑板变量面板
*
* 用于管理和调试行为树运行时的黑板变量
*/
export const BehaviorTreeBlackboard: React.FC<BehaviorTreeBlackboardProps> = ({
variables,
initialVariables,
globalVariables,
onVariableChange,
onVariableAdd,
onVariableDelete,
onVariableRename,
onGlobalVariableChange,
onGlobalVariableAdd,
onGlobalVariableDelete,
projectPath,
hasUnsavedGlobalChanges,
onSaveGlobal
}) => {
const [viewMode, setViewMode] = useState<'local' | 'global'>('local');
const isModified = (key: string): boolean => {
if (!initialVariables) return false;
return JSON.stringify(variables[key]) !== JSON.stringify(initialVariables[key]);
};
const handleExportTypeScript = async () => {
try {
const globalBlackboard = Core.services.resolve(GlobalBlackboardService);
const config = globalBlackboard.exportConfig();
const tsCode = GlobalBlackboardTypeGenerator.generate(config);
const outputPath = await save({
filters: [{
name: 'TypeScript',
extensions: ['ts']
}],
defaultPath: 'GlobalBlackboard.ts'
});
if (outputPath) {
await invoke('write_file_content', {
path: outputPath,
content: tsCode
});
logger.info('TypeScript 类型定义已导出', outputPath);
}
} catch (error) {
logger.error('导出 TypeScript 失败', error);
}
};
const [isAdding, setIsAdding] = useState(false);
const [newKey, setNewKey] = useState('');
const [newValue, setNewValue] = useState('');
const [newType, setNewType] = useState<BlackboardVariable['type']>('string');
const [editingKey, setEditingKey] = useState<string | null>(null);
const [editingNewKey, setEditingNewKey] = useState('');
const [editValue, setEditValue] = useState('');
const [editType, setEditType] = useState<BlackboardVariable['type']>('string');
const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(new Set());
const handleAddVariable = () => {
if (!newKey.trim()) return;
let parsedValue: any = newValue;
if (newType === 'number') {
parsedValue = parseFloat(newValue) || 0;
} else if (newType === 'boolean') {
parsedValue = newValue === 'true';
} else if (newType === 'object') {
try {
parsedValue = JSON.parse(newValue);
} catch {
parsedValue = {};
}
}
if (viewMode === 'global' && onGlobalVariableAdd) {
const globalType = newType as BlackboardValueType;
onGlobalVariableAdd(newKey, parsedValue, globalType);
} else {
onVariableAdd(newKey, parsedValue, newType);
}
setNewKey('');
setNewValue('');
setIsAdding(false);
};
const handleStartEdit = (key: string, value: any) => {
setEditingKey(key);
setEditingNewKey(key);
const currentType = getVariableType(value);
setEditType(currentType);
setEditValue(typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value));
};
const handleSaveEdit = (key: string) => {
const newKey = editingNewKey.trim();
if (!newKey) return;
let parsedValue: any = editValue;
if (editType === 'number') {
parsedValue = parseFloat(editValue) || 0;
} else if (editType === 'boolean') {
parsedValue = editValue === 'true' || editValue === '1';
} else if (editType === 'object') {
try {
parsedValue = JSON.parse(editValue);
} catch {
return;
}
}
if (viewMode === 'global' && onGlobalVariableChange) {
if (newKey !== key && onGlobalVariableDelete) {
onGlobalVariableDelete(key);
}
onGlobalVariableChange(newKey, parsedValue);
} else {
if (newKey !== key && onVariableRename) {
onVariableRename(key, newKey);
}
onVariableChange(newKey, parsedValue);
}
setEditingKey(null);
};
const toggleGroup = (groupName: string) => {
setCollapsedGroups((prev) => {
const newSet = new Set(prev);
if (newSet.has(groupName)) {
newSet.delete(groupName);
} else {
newSet.add(groupName);
}
return newSet;
});
};
const getVariableType = (value: any): BlackboardVariable['type'] => {
if (typeof value === 'number') return 'number';
if (typeof value === 'boolean') return 'boolean';
if (typeof value === 'object') return 'object';
return 'string';
};
const currentVariables = viewMode === 'global' ? (globalVariables || {}) : variables;
const variableEntries = Object.entries(currentVariables);
const currentOnDelete = viewMode === 'global' ? onGlobalVariableDelete : onVariableDelete;
const groupedVariables: Record<string, Array<{ fullKey: string; varName: string; value: any }>> = variableEntries.reduce((groups, [key, value]) => {
const parts = key.split('.');
const groupName = (parts.length > 1 && parts[0]) ? parts[0] : 'default';
const varName = parts.length > 1 ? parts.slice(1).join('.') : key;
if (!groups[groupName]) {
groups[groupName] = [];
}
const group = groups[groupName];
if (group) {
group.push({ fullKey: key, varName, value });
}
return groups;
}, {} as Record<string, Array<{ fullKey: string; varName: string; value: any }>>);
const groupNames = Object.keys(groupedVariables).sort((a, b) => {
if (a === 'default') return 1;
if (b === 'default') return -1;
return a.localeCompare(b);
});
return (
<div style={{
height: '100%',
display: 'flex',
flexDirection: 'column',
backgroundColor: '#1e1e1e',
color: '#cccccc'
}}>
<style>{`
.blackboard-list::-webkit-scrollbar {
width: 8px;
}
.blackboard-list::-webkit-scrollbar-track {
background: #1e1e1e;
}
.blackboard-list::-webkit-scrollbar-thumb {
background: #3c3c3c;
border-radius: 4px;
}
.blackboard-list::-webkit-scrollbar-thumb:hover {
background: #4c4c4c;
}
`}</style>
{/* 标题栏 */}
<div style={{
backgroundColor: 'rgba(0, 0, 0, 0.5)',
borderBottom: '1px solid #333'
}}>
<div style={{
padding: '10px 12px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center'
}}>
<div style={{
fontSize: '13px',
fontWeight: 'bold',
display: 'flex',
alignItems: 'center',
gap: '6px',
color: '#ccc'
}}>
<Clipboard size={14} />
<span>Blackboard</span>
</div>
<div style={{
display: 'flex',
backgroundColor: '#1e1e1e',
borderRadius: '3px',
overflow: 'hidden'
}}>
<button
onClick={() => setViewMode('local')}
style={{
padding: '3px 8px',
backgroundColor: viewMode === 'local' ? '#0e639c' : 'transparent',
border: 'none',
color: viewMode === 'local' ? '#fff' : '#888',
cursor: 'pointer',
fontSize: '10px',
display: 'flex',
alignItems: 'center',
gap: '3px'
}}
>
<Clipboard size={11} />
Local
</button>
<button
onClick={() => setViewMode('global')}
style={{
padding: '3px 8px',
backgroundColor: viewMode === 'global' ? '#0e639c' : 'transparent',
border: 'none',
color: viewMode === 'global' ? '#fff' : '#888',
cursor: 'pointer',
fontSize: '10px',
display: 'flex',
alignItems: 'center',
gap: '3px'
}}
>
<Globe size={11} />
Global
</button>
</div>
</div>
{/* 工具栏 */}
<div style={{
padding: '8px 12px',
backgroundColor: '#252525',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
gap: '8px'
}}>
<div style={{
flex: 1,
fontSize: '10px',
color: '#888',
display: 'flex',
alignItems: 'center',
gap: '4px',
minWidth: 0,
overflow: 'hidden'
}}>
{viewMode === 'global' && projectPath ? (
<>
<Folder size={10} style={{ flexShrink: 0 }} />
<span style={{
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
}}>.ecs/global-blackboard.json</span>
</>
) : (
<span>
{viewMode === 'local' ? '当前行为树的本地变量' : '所有行为树共享的全局变量'}
</span>
)}
</div>
<div style={{
display: 'flex',
alignItems: 'center',
gap: '4px',
flexShrink: 0
}}>
{viewMode === 'global' && onSaveGlobal && (
<>
<button
onClick={hasUnsavedGlobalChanges ? onSaveGlobal : undefined}
disabled={!hasUnsavedGlobalChanges}
style={{
padding: '4px 6px',
backgroundColor: hasUnsavedGlobalChanges ? '#ff9800' : '#4caf50',
border: 'none',
borderRadius: '3px',
color: '#fff',
cursor: hasUnsavedGlobalChanges ? 'pointer' : 'not-allowed',
display: 'flex',
alignItems: 'center',
opacity: hasUnsavedGlobalChanges ? 1 : 0.7
}}
title={hasUnsavedGlobalChanges ? '点击保存全局配置' : '全局配置已保存'}
>
<Save size={12} />
</button>
<button
onClick={handleExportTypeScript}
style={{
padding: '4px 6px',
backgroundColor: '#9c27b0',
border: 'none',
borderRadius: '3px',
color: '#fff',
cursor: 'pointer',
display: 'flex',
alignItems: 'center'
}}
title="导出为 TypeScript 类型定义"
>
<FileCode size={12} />
</button>
</>
)}
<button
onClick={() => setIsAdding(true)}
style={{
padding: '4px 6px',
backgroundColor: '#0e639c',
border: 'none',
borderRadius: '3px',
color: '#fff',
cursor: 'pointer',
fontSize: '11px',
display: 'flex',
alignItems: 'center'
}}
title="添加变量"
>
+
</button>
</div>
</div>
</div>
{/* 变量列表 */}
<div className="blackboard-list" style={{
flex: 1,
overflowY: 'auto',
padding: '10px'
}}>
{variableEntries.length === 0 && !isAdding && (
<div style={{
textAlign: 'center',
color: '#666',
fontSize: '12px',
padding: '20px'
}}>
No variables yet. Click "Add" to create one.
</div>
)}
{groupNames.map((groupName) => {
const isCollapsed = collapsedGroups.has(groupName);
const groupVars = groupedVariables[groupName];
if (!groupVars) return null;
return (
<div key={groupName} style={{ marginBottom: '8px' }}>
{groupName !== 'default' && (
<div
onClick={() => toggleGroup(groupName)}
style={{
display: 'flex',
alignItems: 'center',
gap: '4px',
padding: '4px 6px',
backgroundColor: '#252525',
borderRadius: '3px',
cursor: 'pointer',
marginBottom: '4px',
userSelect: 'none'
}}
>
{isCollapsed ? <ChevronRight size={14} /> : <ChevronDown size={14} />}
<span style={{
fontSize: '11px',
fontWeight: 'bold',
color: '#888'
}}>
{groupName} ({groupVars.length})
</span>
</div>
)}
{!isCollapsed && groupVars.map(({ fullKey: key, varName, value }) => {
const type = getVariableType(value);
const isEditing = editingKey === key;
const handleDragStart = (e: React.DragEvent) => {
const variableData = {
variableName: key,
variableValue: value,
variableType: type
};
e.dataTransfer.setData('application/blackboard-variable', JSON.stringify(variableData));
e.dataTransfer.effectAllowed = 'copy';
};
const typeColor =
type === 'number' ? '#4ec9b0' :
type === 'boolean' ? '#569cd6' :
type === 'object' ? '#ce9178' : '#d4d4d4';
const displayValue = type === 'object' ?
JSON.stringify(value) :
String(value);
const truncatedValue = displayValue.length > 30 ?
displayValue.substring(0, 30) + '...' :
displayValue;
return (
<div
key={key}
draggable={!isEditing}
onDragStart={handleDragStart}
style={{
marginBottom: '6px',
padding: '6px 8px',
backgroundColor: '#2d2d2d',
borderRadius: '3px',
borderLeft: `3px solid ${typeColor}`,
cursor: isEditing ? 'default' : 'grab'
}}
>
{isEditing ? (
<div>
<div style={{
fontSize: '10px',
color: '#666',
marginBottom: '4px'
}}>
Name
</div>
<input
type="text"
value={editingNewKey}
onChange={(e) => setEditingNewKey(e.target.value)}
style={{
width: '100%',
padding: '4px',
marginBottom: '4px',
backgroundColor: '#1e1e1e',
border: '1px solid #3c3c3c',
borderRadius: '2px',
color: '#9cdcfe',
fontSize: '11px',
fontFamily: 'monospace'
}}
placeholder="Variable name (e.g., player.health)"
/>
<div style={{
fontSize: '10px',
color: '#666',
marginBottom: '4px'
}}>
Type
</div>
<select
value={editType}
onChange={(e) => setEditType(e.target.value as BlackboardVariable['type'])}
style={{
width: '100%',
padding: '4px',
marginBottom: '4px',
backgroundColor: '#1e1e1e',
border: '1px solid #3c3c3c',
borderRadius: '2px',
color: '#cccccc',
fontSize: '10px'
}}
>
<option value="string">String</option>
<option value="number">Number</option>
<option value="boolean">Boolean</option>
<option value="object">Object (JSON)</option>
</select>
<div style={{
fontSize: '10px',
color: '#666',
marginBottom: '4px'
}}>
Value
</div>
<textarea
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
style={{
width: '100%',
minHeight: editType === 'object' ? '60px' : '24px',
padding: '4px',
backgroundColor: '#1e1e1e',
border: '1px solid #0e639c',
borderRadius: '2px',
color: '#cccccc',
fontSize: '11px',
fontFamily: 'monospace',
resize: 'vertical',
marginBottom: '4px'
}}
/>
<div style={{ display: 'flex', gap: '4px' }}>
<button
onClick={() => handleSaveEdit(key)}
style={{
padding: '3px 8px',
backgroundColor: '#0e639c',
border: 'none',
borderRadius: '2px',
color: '#fff',
cursor: 'pointer',
fontSize: '10px'
}}
>
Save
</button>
<button
onClick={() => setEditingKey(null)}
style={{
padding: '3px 8px',
backgroundColor: '#3c3c3c',
border: 'none',
borderRadius: '2px',
color: '#ccc',
cursor: 'pointer',
fontSize: '10px'
}}
>
Cancel
</button>
</div>
</div>
) : (
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
gap: '8px'
}}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{
fontSize: '11px',
color: '#9cdcfe',
fontWeight: 'bold',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
display: 'flex',
alignItems: 'center',
gap: '4px'
}}>
{varName} <span style={{
color: '#666',
fontWeight: 'normal',
fontSize: '10px'
}}>({type})</span>
{viewMode === 'local' && isModified(key) && (
<span style={{
fontSize: '9px',
color: '#ffbb00',
backgroundColor: 'rgba(255, 187, 0, 0.15)',
padding: '1px 4px',
borderRadius: '2px'
}} title="运行时修改的值,停止后会恢复">
</span>
)}
</div>
<div style={{
fontSize: '10px',
fontFamily: 'monospace',
color: typeColor,
marginTop: '2px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
backgroundColor: (viewMode === 'local' && isModified(key)) ? 'rgba(255, 187, 0, 0.1)' : 'transparent',
padding: '1px 3px',
borderRadius: '2px'
}} title={(viewMode === 'local' && isModified(key)) ? `初始值: ${JSON.stringify(initialVariables?.[key])}\n当前值: ${displayValue}` : displayValue}>
{truncatedValue}
</div>
</div>
<div style={{
display: 'flex',
gap: '2px',
flexShrink: 0
}}>
<button
onClick={() => handleStartEdit(key, value)}
style={{
padding: '2px',
backgroundColor: 'transparent',
border: 'none',
color: '#ccc',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
}}
title="Edit"
>
<Edit2 size={12} />
</button>
<button
onClick={() => currentOnDelete && currentOnDelete(key)}
style={{
padding: '2px',
backgroundColor: 'transparent',
border: 'none',
color: '#f44336',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
}}
title="Delete"
>
<Trash2 size={12} />
</button>
</div>
</div>
)}
</div>
);
})}
</div>
);
})}
{/* 添加新变量表单 */}
{isAdding && (
<div style={{
padding: '12px',
backgroundColor: '#2d2d2d',
borderRadius: '4px',
borderLeft: '3px solid #0e639c'
}}>
<div style={{
fontSize: '13px',
fontWeight: 'bold',
marginBottom: '10px',
color: '#9cdcfe'
}}>
New Variable
</div>
<input
type="text"
placeholder="Variable name"
value={newKey}
onChange={(e) => setNewKey(e.target.value)}
style={{
width: '100%',
padding: '6px',
marginBottom: '8px',
backgroundColor: '#1e1e1e',
border: '1px solid #3c3c3c',
borderRadius: '3px',
color: '#cccccc',
fontSize: '12px'
}}
/>
<select
value={newType}
onChange={(e) => setNewType(e.target.value as BlackboardVariable['type'])}
style={{
width: '100%',
padding: '6px',
marginBottom: '8px',
backgroundColor: '#1e1e1e',
border: '1px solid #3c3c3c',
borderRadius: '3px',
color: '#cccccc',
fontSize: '12px'
}}
>
<option value="string">String</option>
<option value="number">Number</option>
<option value="boolean">Boolean</option>
<option value="object">Object (JSON)</option>
</select>
<textarea
placeholder={
newType === 'object' ? '{"key": "value"}' :
newType === 'boolean' ? 'true or false' :
newType === 'number' ? '0' : 'value'
}
value={newValue}
onChange={(e) => setNewValue(e.target.value)}
style={{
width: '100%',
minHeight: newType === 'object' ? '80px' : '30px',
padding: '6px',
marginBottom: '8px',
backgroundColor: '#1e1e1e',
border: '1px solid #3c3c3c',
borderRadius: '3px',
color: '#cccccc',
fontSize: '12px',
fontFamily: 'monospace',
resize: 'vertical'
}}
/>
<div style={{ display: 'flex', gap: '5px' }}>
<button
onClick={handleAddVariable}
style={{
padding: '6px 12px',
backgroundColor: '#0e639c',
border: 'none',
borderRadius: '3px',
color: '#fff',
cursor: 'pointer',
fontSize: '12px'
}}
>
Create
</button>
<button
onClick={() => {
setIsAdding(false);
setNewKey('');
setNewValue('');
}}
style={{
padding: '6px 12px',
backgroundColor: '#3c3c3c',
border: 'none',
borderRadius: '3px',
color: '#ccc',
cursor: 'pointer',
fontSize: '12px'
}}
>
Cancel
</button>
</div>
</div>
)}
</div>
{/* 底部信息 */}
<div style={{
padding: '8px 15px',
borderTop: '1px solid #333',
fontSize: '11px',
color: '#666',
backgroundColor: '#2d2d2d',
display: 'flex',
alignItems: 'center',
gap: '8px'
}}>
<span>
{viewMode === 'local' ? 'Local' : 'Global'}: {variableEntries.length} variable{variableEntries.length !== 1 ? 's' : ''}
</span>
</div>
</div>
);
};

View File

@@ -1,669 +0,0 @@
import React, { useEffect, useMemo } from 'react';
import { NodeTemplate } from '@esengine/behavior-tree';
import { RotateCcw } from 'lucide-react';
import { useBehaviorTreeStore, BehaviorTreeNode, ROOT_NODE_ID } from '../stores/behaviorTreeStore';
import { useUIStore } from '../application/state/UIStore';
import { useToast } from './Toast';
import { BlackboardValue } from '../domain/models/Blackboard';
import { BehaviorTreeCanvas } from '../presentation/components/behavior-tree/canvas/BehaviorTreeCanvas';
import { ConnectionLayer } from '../presentation/components/behavior-tree/connections/ConnectionLayer';
import { NodeFactory } from '../infrastructure/factories/NodeFactory';
import { BehaviorTreeValidator } from '../infrastructure/validation/BehaviorTreeValidator';
import { useNodeOperations } from '../presentation/hooks/useNodeOperations';
import { useConnectionOperations } from '../presentation/hooks/useConnectionOperations';
import { useCommandHistory } from '../presentation/hooks/useCommandHistory';
import { useNodeDrag } from '../presentation/hooks/useNodeDrag';
import { usePortConnection } from '../presentation/hooks/usePortConnection';
import { useKeyboardShortcuts } from '../presentation/hooks/useKeyboardShortcuts';
import { useDropHandler } from '../presentation/hooks/useDropHandler';
import { useCanvasMouseEvents } from '../presentation/hooks/useCanvasMouseEvents';
import { useContextMenu } from '../application/hooks/useContextMenu';
import { useQuickCreateMenu } from '../application/hooks/useQuickCreateMenu';
import { EditorToolbar } from '../presentation/components/toolbar/EditorToolbar';
import { QuickCreateMenu } from '../presentation/components/menu/QuickCreateMenu';
import { NodeContextMenu } from '../presentation/components/menu/NodeContextMenu';
import { BehaviorTreeNode as BehaviorTreeNodeComponent } from '../presentation/components/behavior-tree/nodes/BehaviorTreeNode';
import { getPortPosition as getPortPositionUtil } from '../presentation/utils/portUtils';
import { useExecutionController } from '../presentation/hooks/useExecutionController';
import { useNodeTracking } from '../presentation/hooks/useNodeTracking';
import { useEditorState } from '../presentation/hooks/useEditorState';
import { useEditorHandlers } from '../presentation/hooks/useEditorHandlers';
import { ICON_MAP, ROOT_NODE_TEMPLATE, DEFAULT_EDITOR_CONFIG } from '../presentation/config/editorConstants';
import '../styles/BehaviorTreeNode.css';
type BlackboardVariables = Record<string, BlackboardValue>;
interface BehaviorTreeEditorProps {
onNodeSelect?: (node: BehaviorTreeNode) => void;
onNodeCreate?: (template: NodeTemplate, position: { x: number; y: number }) => void;
blackboardVariables?: BlackboardVariables;
projectPath?: string | null;
showToolbar?: boolean;
}
export const BehaviorTreeEditor: React.FC<BehaviorTreeEditorProps> = ({
onNodeSelect,
onNodeCreate,
blackboardVariables = {},
projectPath = null,
showToolbar = true
}) => {
const { showToast } = useToast();
// 数据 store行为树数据
const {
nodes,
connections,
connectingFrom,
connectingFromProperty,
connectingToPos,
isBoxSelecting,
boxSelectStart,
boxSelectEnd,
setNodes,
setConnections,
setConnectingFrom,
setConnectingFromProperty,
setConnectingToPos,
clearConnecting,
setIsBoxSelecting,
setBoxSelectStart,
setBoxSelectEnd,
clearBoxSelect,
triggerForceUpdate,
sortChildrenByPosition,
setBlackboardVariables,
setInitialBlackboardVariables,
setIsExecuting,
initialBlackboardVariables,
isExecuting,
saveNodesDataSnapshot,
restoreNodesData,
nodeExecutionStatuses,
nodeExecutionOrders
} = useBehaviorTreeStore();
// UI store选中、拖拽、画布状态
const {
selectedNodeIds,
draggingNodeId,
dragStartPositions,
isDraggingNode,
canvasOffset,
canvasScale,
dragDelta,
setSelectedNodeIds,
startDragging,
stopDragging,
setIsDraggingNode,
resetView,
setDragDelta
} = useUIStore();
// 依赖注入 - 基础设施
const nodeFactory = useMemo(() => new NodeFactory(), []);
const validator = useMemo(() => new BehaviorTreeValidator(), []);
// 命令历史管理(创建 CommandManager
const { commandManager, canUndo, canRedo, undo, redo } = useCommandHistory();
// 应用层 hooks使用统一的 commandManager
const nodeOperations = useNodeOperations(nodeFactory, validator, commandManager);
const connectionOperations = useConnectionOperations(validator, commandManager);
// 右键菜单
const { contextMenu, setContextMenu, handleNodeContextMenu, handleCanvasContextMenu, closeContextMenu } = useContextMenu();
// 组件挂载和连线变化时强制更新,确保连线能正确渲染
useEffect(() => {
if (nodes.length > 0 || connections.length > 0) {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
triggerForceUpdate();
});
});
}
}, [nodes.length, connections.length]);
// 点击其他地方关闭右键菜单
useEffect(() => {
const handleClick = () => {
if (contextMenu.visible) {
closeContextMenu();
}
};
if (contextMenu.visible) {
document.addEventListener('click', handleClick);
return () => document.removeEventListener('click', handleClick);
}
}, [contextMenu.visible, closeContextMenu]);
const {
canvasRef,
stopExecutionRef,
executorRef,
selectedConnection,
setSelectedConnection
} = useEditorState();
const {
executionMode,
executionLogs,
executionSpeed,
tickCount,
handlePlay,
handlePause,
handleStop,
handleStep,
handleReset,
handleSpeedChange,
setExecutionLogs,
controller
} = useExecutionController({
rootNodeId: ROOT_NODE_ID,
projectPath,
blackboardVariables,
nodes,
connections,
initialBlackboardVariables,
onBlackboardUpdate: setBlackboardVariables,
onInitialBlackboardSave: setInitialBlackboardVariables,
onExecutingChange: setIsExecuting,
onSaveNodesDataSnapshot: saveNodesDataSnapshot,
onRestoreNodesData: restoreNodesData
});
executorRef.current = controller['executor'] || null;
const { uncommittedNodeIds } = useNodeTracking({
nodes,
executionMode
});
// 快速创建菜单
const {
quickCreateMenu,
setQuickCreateMenu,
handleQuickCreateNode
} = useQuickCreateMenu({
nodeOperations,
connectionOperations,
canvasRef,
canvasOffset,
canvasScale,
connectingFrom,
connectingFromProperty,
clearConnecting,
nodes,
setNodes,
connections,
executionMode,
onStop: () => stopExecutionRef.current?.(),
onNodeCreate,
showToast
});
// 节点拖拽
const {
handleNodeMouseDown,
handleNodeMouseMove,
handleNodeMouseUp
} = useNodeDrag({
canvasRef,
canvasOffset,
canvasScale,
nodes,
selectedNodeIds,
draggingNodeId,
dragStartPositions,
isDraggingNode,
dragDelta,
nodeOperations,
setSelectedNodeIds,
startDragging,
stopDragging,
setIsDraggingNode,
setDragDelta,
setIsBoxSelecting,
setBoxSelectStart,
setBoxSelectEnd,
sortChildrenByPosition
});
// 端口连接
const {
handlePortMouseDown,
handlePortMouseUp,
handleNodeMouseUpForConnection
} = usePortConnection({
canvasRef,
canvasOffset,
canvasScale,
nodes,
connections,
connectingFrom,
connectingFromProperty,
connectionOperations,
setConnectingFrom,
setConnectingFromProperty,
clearConnecting,
sortChildrenByPosition,
showToast
});
// 键盘快捷键
useKeyboardShortcuts({
selectedNodeIds,
selectedConnection,
connections,
nodeOperations,
connectionOperations,
setSelectedNodeIds,
setSelectedConnection
});
// 拖放处理
const {
isDragging,
handleDrop,
handleDragOver,
handleDragLeave,
handleDragEnter
} = useDropHandler({
canvasRef,
canvasOffset,
canvasScale,
nodeOperations,
onNodeCreate
});
// 画布鼠标事件
const {
handleCanvasMouseMove,
handleCanvasMouseUp,
handleCanvasMouseDown
} = useCanvasMouseEvents({
canvasRef,
canvasOffset,
canvasScale,
connectingFrom,
connectingToPos,
isBoxSelecting,
boxSelectStart,
boxSelectEnd,
nodes,
selectedNodeIds,
quickCreateMenu,
setConnectingToPos,
setIsBoxSelecting,
setBoxSelectStart,
setBoxSelectEnd,
setSelectedNodeIds,
setSelectedConnection,
setQuickCreateMenu,
clearConnecting,
clearBoxSelect,
showToast
});
const {
handleNodeClick,
handleResetView,
handleClearCanvas
} = useEditorHandlers({
isDraggingNode,
selectedNodeIds,
setSelectedNodeIds,
setNodes,
setConnections,
resetView,
triggerForceUpdate,
onNodeSelect,
rootNodeId: ROOT_NODE_ID,
rootNodeTemplate: ROOT_NODE_TEMPLATE
});
const getPortPosition = (nodeId: string, propertyName?: string, portType: 'input' | 'output' = 'output') =>
getPortPositionUtil(canvasRef, canvasOffset, canvasScale, nodes, nodeId, propertyName, portType);
stopExecutionRef.current = handleStop;
return (
<div style={{
width: '100%',
height: '100%',
flex: 1,
backgroundColor: '#1e1e1e',
position: 'relative',
overflow: 'hidden',
display: 'flex',
flexDirection: 'column'
}}>
<style>{`
@keyframes pulse {
0%, 100% {
transform: translate(-50%, -50%) scale(1);
}
50% {
transform: translate(-50%, -50%) scale(1.02);
}
}
`}</style>
{/* 画布区域容器 */}
<div style={{
flex: 1,
position: 'relative',
minHeight: 0,
overflow: 'hidden'
}}>
{/* 画布 */}
<BehaviorTreeCanvas
ref={canvasRef}
config={DEFAULT_EDITOR_CONFIG}
onDrop={handleDrop}
onDragOver={handleDragOver}
onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave}
onMouseDown={handleCanvasMouseDown}
onMouseMove={(e) => {
handleNodeMouseMove(e);
handleCanvasMouseMove(e);
}}
onMouseUp={(e) => {
handleNodeMouseUp();
handleCanvasMouseUp(e);
}}
onMouseLeave={(e) => {
handleNodeMouseUp();
handleCanvasMouseUp(e);
}}
onContextMenu={handleCanvasContextMenu}
>
{/* 连接线层 */}
<ConnectionLayer
connections={connections}
nodes={nodes}
selectedConnection={selectedConnection}
getPortPosition={getPortPosition}
onConnectionClick={(e, fromId, toId) => {
setSelectedConnection({ from: fromId, to: toId });
setSelectedNodeIds([]);
}}
/>
{/* 正在拖拽的连接线预览 */}
<svg style={{
position: 'absolute',
top: 0,
left: 0,
width: '10000px',
height: '10000px',
pointerEvents: 'none',
zIndex: 1,
overflow: 'visible'
}}>
{/* 正在拖拽的连接线 */}
{connectingFrom && connectingToPos && (() => {
const fromNode = nodes.find((n: BehaviorTreeNode) => n.id === connectingFrom);
if (!fromNode) return null;
let x1, y1;
let pathD: string;
const x2 = connectingToPos.x;
const y2 = connectingToPos.y;
// 判断是否是属性连接
const isPropertyConnection = !!connectingFromProperty;
const fromIsBlackboard = fromNode.data.nodeType === 'blackboard-variable';
const color = isPropertyConnection ? '#9c27b0' : '#0e639c';
if (isPropertyConnection && fromIsBlackboard) {
// 黑板变量节点的右侧输出引脚
x1 = fromNode.position.x + 75;
y1 = fromNode.position.y;
// 使用水平贝塞尔曲线
const controlX1 = x1 + (x2 - x1) * 0.5;
const controlX2 = x1 + (x2 - x1) * 0.5;
pathD = `M ${x1} ${y1} C ${controlX1} ${y1}, ${controlX2} ${y2}, ${x2} ${y2}`;
} else {
// 节点连接:从底部输出端口
x1 = fromNode.position.x;
y1 = fromNode.position.y + 30;
const controlY = y1 + (y2 - y1) * 0.5;
pathD = `M ${x1} ${y1} C ${x1} ${controlY}, ${x2} ${controlY}, ${x2} ${y2}`;
}
return (
<path
d={pathD}
stroke={color}
strokeWidth="2"
fill="none"
strokeDasharray="5,5"
style={{ pointerEvents: 'none' }}
/>
);
})()}
</svg>
{/* 框选矩形 */}
{isBoxSelecting && boxSelectStart && boxSelectEnd && (() => {
const minX = Math.min(boxSelectStart.x, boxSelectEnd.x);
const maxX = Math.max(boxSelectStart.x, boxSelectEnd.x);
const minY = Math.min(boxSelectStart.y, boxSelectEnd.y);
const maxY = Math.max(boxSelectStart.y, boxSelectEnd.y);
const width = maxX - minX;
const height = maxY - minY;
return (
<div style={{
position: 'absolute',
left: `${minX}px`,
top: `${minY}px`,
width: `${width}px`,
height: `${height}px`,
backgroundColor: 'rgba(14, 99, 156, 0.15)',
border: '2px solid rgba(14, 99, 156, 0.6)',
borderRadius: '4px',
pointerEvents: 'none',
zIndex: 999
}} />
);
})()}
{/* 节点列表 */}
{nodes.map((node: BehaviorTreeNode) => {
const isSelected = selectedNodeIds.includes(node.id);
const isBeingDragged = dragStartPositions.has(node.id);
const executionStatus = nodeExecutionStatuses.get(node.id);
const executionOrder = nodeExecutionOrders.get(node.id);
return (
<BehaviorTreeNodeComponent
key={node.id}
node={node}
isSelected={isSelected}
isBeingDragged={isBeingDragged}
dragDelta={dragDelta}
uncommittedNodeIds={uncommittedNodeIds}
blackboardVariables={blackboardVariables}
initialBlackboardVariables={initialBlackboardVariables}
isExecuting={isExecuting}
executionStatus={executionStatus}
executionOrder={executionOrder}
connections={connections}
nodes={nodes}
executorRef={executorRef}
iconMap={ICON_MAP}
draggingNodeId={draggingNodeId}
onNodeClick={handleNodeClick}
onContextMenu={handleNodeContextMenu}
onNodeMouseDown={handleNodeMouseDown}
onNodeMouseUpForConnection={handleNodeMouseUpForConnection}
onPortMouseDown={handlePortMouseDown}
onPortMouseUp={handlePortMouseUp}
/>
);
})}
{/* 拖拽提示 - 相对于画布视口 */}
{isDragging && (
<div style={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
padding: '20px 40px',
backgroundColor: 'rgba(14, 99, 156, 0.2)',
border: '2px dashed #0e639c',
borderRadius: '8px',
color: '#0e639c',
fontSize: '16px',
fontWeight: 'bold',
pointerEvents: 'none',
zIndex: 1000
}}>
</div>
)}
{/* 空状态提示 - 相对于画布视口 */}
{nodes.length === 1 && !isDragging && (
<div style={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
textAlign: 'center',
color: '#666',
fontSize: '14px',
pointerEvents: 'none'
}}>
<div style={{ fontSize: '48px', marginBottom: '20px' }}>👇</div>
<div style={{ marginBottom: '10px' }}> Root </div>
<div style={{ fontSize: '12px', color: '#555' }}>
Root
</div>
</div>
)}
</BehaviorTreeCanvas>
{/* 运行控制工具栏 */}
{showToolbar && (
<EditorToolbar
executionMode={executionMode}
canUndo={canUndo}
canRedo={canRedo}
onPlay={handlePlay}
onPause={handlePause}
onStop={handleStop}
onStep={handleStep}
onReset={handleReset}
onUndo={undo}
onRedo={redo}
onResetView={handleResetView}
onClearCanvas={handleClearCanvas}
/>
)}
{/* 快速创建菜单 */}
<QuickCreateMenu
visible={quickCreateMenu.visible}
position={quickCreateMenu.position}
searchText={quickCreateMenu.searchText}
selectedIndex={quickCreateMenu.selectedIndex}
mode={quickCreateMenu.mode}
iconMap={ICON_MAP}
onSearchChange={(text) => setQuickCreateMenu(prev => ({
...prev,
searchText: text
}))}
onIndexChange={(index) => setQuickCreateMenu(prev => ({
...prev,
selectedIndex: index
}))}
onNodeSelect={handleQuickCreateNode}
onClose={() => {
setQuickCreateMenu({
visible: false,
position: { x: 0, y: 0 },
searchText: '',
selectedIndex: 0,
mode: 'create',
replaceNodeId: null
});
clearConnecting();
}}
/>
{/* 状态栏 */}
<div style={{
position: 'absolute',
bottom: '0',
left: '0',
right: '0',
padding: '8px 15px',
backgroundColor: 'rgba(45, 45, 45, 0.95)',
borderTop: '1px solid #333',
fontSize: '12px',
color: '#999',
display: 'flex',
justifyContent: 'space-between'
}}>
<div>: {nodes.length}</div>
<div style={{ display: 'flex', gap: '20px', alignItems: 'center' }}>
{executionMode === 'running' && (
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
<RotateCcw size={14} />
Tick: {tickCount}
</div>
)}
<div>{selectedNodeIds.length > 0 ? `已选择 ${selectedNodeIds.length} 个节点` : '未选择节点'}</div>
</div>
</div>
</div>
{/* 右键菜单 */}
<NodeContextMenu
visible={contextMenu.visible}
position={contextMenu.position}
nodeId={contextMenu.nodeId}
onReplaceNode={() => {
setQuickCreateMenu({
visible: true,
position: contextMenu.position,
searchText: '',
selectedIndex: 0,
mode: 'replace',
replaceNodeId: contextMenu.nodeId
});
setContextMenu({ ...contextMenu, visible: false });
}}
onDeleteNode={() => {
if (contextMenu.nodeId) {
nodeOperations.deleteNode(contextMenu.nodeId);
setContextMenu({ ...contextMenu, visible: false });
}
}}
onCreateNode={() => {
setQuickCreateMenu({
visible: true,
position: contextMenu.position,
searchText: '',
selectedIndex: 0,
mode: 'create',
replaceNodeId: null
});
setContextMenu({ ...contextMenu, visible: false });
}}
/>
</div>
);
};

View File

@@ -1,336 +0,0 @@
import React, { useEffect, useRef, useState } from 'react';
import { Trash2, Copy } from 'lucide-react';
interface ExecutionLog {
timestamp: number;
message: string;
level: 'info' | 'success' | 'error' | 'warning';
nodeId?: string;
}
interface BehaviorTreeExecutionPanelProps {
logs: ExecutionLog[];
onClearLogs: () => void;
isRunning: boolean;
tickCount: number;
executionSpeed: number;
onSpeedChange: (speed: number) => void;
}
export const BehaviorTreeExecutionPanel: React.FC<BehaviorTreeExecutionPanelProps> = ({
logs,
onClearLogs,
isRunning,
tickCount,
executionSpeed,
onSpeedChange
}) => {
const logContainerRef = useRef<HTMLDivElement>(null);
const [copySuccess, setCopySuccess] = useState(false);
// 自动滚动到底部
useEffect(() => {
if (logContainerRef.current) {
logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;
}
}, [logs]);
const getLevelColor = (level: string) => {
switch (level) {
case 'success': return '#4caf50';
case 'error': return '#f44336';
case 'warning': return '#ff9800';
default: return '#2196f3';
}
};
const getLevelIcon = (level: string) => {
switch (level) {
case 'success': return '✓';
case 'error': return '✗';
case 'warning': return '⚠';
default: return '';
}
};
const formatTime = (timestamp: number) => {
const date = new Date(timestamp);
return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}.${date.getMilliseconds().toString().padStart(3, '0')}`;
};
const handleCopyLogs = () => {
const logsText = logs.map((log) =>
`${formatTime(log.timestamp)} ${getLevelIcon(log.level)} ${log.message}`
).join('\n');
navigator.clipboard.writeText(logsText).then(() => {
setCopySuccess(true);
setTimeout(() => setCopySuccess(false), 2000);
}).catch((err) => {
console.error('复制失败:', err);
});
};
return (
<div style={{
width: '100%',
height: '100%',
display: 'flex',
flexDirection: 'column',
backgroundColor: '#1e1e1e',
color: '#d4d4d4',
fontFamily: 'Consolas, monospace',
fontSize: '12px'
}}>
{/* 标题栏 */}
<div style={{
padding: '8px 12px',
borderBottom: '1px solid #333',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
backgroundColor: '#252526'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
<span style={{ fontWeight: 'bold' }}></span>
{isRunning && (
<div style={{
display: 'flex',
alignItems: 'center',
gap: '6px',
padding: '2px 8px',
backgroundColor: '#4caf50',
borderRadius: '3px',
fontSize: '11px'
}}>
<div style={{
width: '6px',
height: '6px',
borderRadius: '50%',
backgroundColor: '#fff',
animation: 'pulse 1s infinite'
}} />
</div>
)}
<span style={{ color: '#888', fontSize: '11px' }}>
Tick: {tickCount}
</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
{/* 速度控制 */}
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<span style={{ color: '#888', fontSize: '11px', minWidth: '60px' }}>
: {executionSpeed.toFixed(2)}x
</span>
<div style={{ display: 'flex', gap: '4px' }}>
<button
onClick={() => onSpeedChange(0.05)}
style={{
padding: '2px 6px',
fontSize: '10px',
backgroundColor: executionSpeed === 0.05 ? '#0e639c' : 'transparent',
border: '1px solid #555',
borderRadius: '2px',
color: '#d4d4d4',
cursor: 'pointer'
}}
title="超慢速 (每秒3次)"
>
0.05x
</button>
<button
onClick={() => onSpeedChange(0.2)}
style={{
padding: '2px 6px',
fontSize: '10px',
backgroundColor: executionSpeed === 0.2 ? '#0e639c' : 'transparent',
border: '1px solid #555',
borderRadius: '2px',
color: '#d4d4d4',
cursor: 'pointer'
}}
title="慢速 (每秒12次)"
>
0.2x
</button>
<button
onClick={() => onSpeedChange(1.0)}
style={{
padding: '2px 6px',
fontSize: '10px',
backgroundColor: executionSpeed === 1.0 ? '#0e639c' : 'transparent',
border: '1px solid #555',
borderRadius: '2px',
color: '#d4d4d4',
cursor: 'pointer'
}}
title="正常速度 (每秒60次)"
>
1.0x
</button>
</div>
<input
type="range"
min="0.01"
max="2"
step="0.01"
value={executionSpeed}
onChange={(e) => onSpeedChange(parseFloat(e.target.value))}
style={{
width: '80px',
accentColor: '#0e639c'
}}
title="调整执行速度"
/>
</div>
<button
onClick={handleCopyLogs}
style={{
padding: '6px',
backgroundColor: copySuccess ? '#4caf50' : 'transparent',
border: '1px solid #555',
borderRadius: '3px',
color: logs.length === 0 ? '#666' : '#d4d4d4',
cursor: logs.length === 0 ? 'not-allowed' : 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: '11px',
opacity: logs.length === 0 ? 0.5 : 1,
transition: 'background-color 0.2s'
}}
title={copySuccess ? '已复制!' : '复制日志'}
disabled={logs.length === 0}
>
<Copy size={12} />
</button>
<button
onClick={onClearLogs}
style={{
padding: '6px',
backgroundColor: 'transparent',
border: '1px solid #555',
borderRadius: '3px',
color: '#d4d4d4',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: '11px'
}}
title="清空日志"
>
<Trash2 size={12} />
</button>
</div>
</div>
{/* 日志内容 */}
<div
ref={logContainerRef}
className="execution-panel-logs"
style={{
flex: 1,
overflowY: 'auto',
padding: '8px',
backgroundColor: '#1e1e1e'
}}
>
{logs.length === 0 ? (
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
color: '#666',
fontSize: '13px'
}}>
Play
</div>
) : (
logs.map((log, index) => (
<div
key={index}
style={{
display: 'flex',
gap: '8px',
padding: '4px 0',
borderBottom: index < logs.length - 1 ? '1px solid #2a2a2a' : 'none'
}}
>
<span style={{
color: '#666',
fontSize: '11px',
minWidth: '80px'
}}>
{formatTime(log.timestamp)}
</span>
<span style={{
color: getLevelColor(log.level),
fontWeight: 'bold',
minWidth: '16px'
}}>
{getLevelIcon(log.level)}
</span>
<span style={{
flex: 1,
color: log.level === 'error' ? '#f44336' : '#d4d4d4'
}}>
{log.message}
</span>
</div>
))
)}
</div>
{/* 底部状态栏 */}
<div style={{
padding: '6px 12px',
borderTop: '1px solid #333',
backgroundColor: '#252526',
fontSize: '11px',
color: '#888',
display: 'flex',
justifyContent: 'space-between'
}}>
<span>{logs.length} </span>
<span>{isRunning ? '正在运行' : '已停止'}</span>
</div>
<style>{`
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
/* 自定义滚动条样式 */
.execution-panel-logs::-webkit-scrollbar {
width: 8px;
}
.execution-panel-logs::-webkit-scrollbar-track {
background: #1e1e1e;
}
.execution-panel-logs::-webkit-scrollbar-thumb {
background: #424242;
border-radius: 4px;
}
.execution-panel-logs::-webkit-scrollbar-thumb:hover {
background: #4e4e4e;
}
/* Firefox 滚动条样式 */
.execution-panel-logs {
scrollbar-width: thin;
scrollbar-color: #424242 #1e1e1e;
}
`}</style>
</div>
);
};

View File

@@ -1,99 +0,0 @@
import { useState, useEffect } from 'react';
import '../styles/BehaviorTreeNameDialog.css';
interface BehaviorTreeNameDialogProps {
isOpen: boolean;
onConfirm: (name: string) => void;
onCancel: () => void;
defaultName?: string;
}
export const BehaviorTreeNameDialog: React.FC<BehaviorTreeNameDialogProps> = ({
isOpen,
onConfirm,
onCancel,
defaultName = ''
}) => {
const [name, setName] = useState(defaultName);
const [error, setError] = useState('');
useEffect(() => {
if (isOpen) {
setName(defaultName);
setError('');
}
}, [isOpen, defaultName]);
if (!isOpen) return null;
const validateName = (value: string): boolean => {
if (!value.trim()) {
setError('行为树名称不能为空');
return false;
}
const invalidChars = /[<>:"/\\|?*]/;
if (invalidChars.test(value)) {
setError('名称包含非法字符(不能包含 < > : " / \\ | ? *');
return false;
}
setError('');
return true;
};
const handleConfirm = () => {
if (validateName(name)) {
onConfirm(name.trim());
}
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
handleConfirm();
} else if (e.key === 'Escape') {
onCancel();
}
};
const handleNameChange = (value: string) => {
setName(value);
if (error) {
validateName(value);
}
};
return (
<div className="dialog-overlay">
<div className="dialog-content">
<div className="dialog-header">
<h3></h3>
</div>
<div className="dialog-body">
<label htmlFor="btree-name">:</label>
<input
id="btree-name"
type="text"
value={name}
onChange={(e) => handleNameChange(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="请输入行为树名称"
autoFocus
/>
{error && <div className="dialog-error">{error}</div>}
<div className="dialog-hint">
将保存到项目目录: .ecs/behaviors/{name || '名称'}.btree
</div>
</div>
<div className="dialog-footer">
<button onClick={onCancel} className="dialog-button dialog-button-secondary">
</button>
<button onClick={handleConfirm} className="dialog-button dialog-button-primary">
</button>
</div>
</div>
</div>
);
};

View File

@@ -1,281 +0,0 @@
import React, { useState, useEffect, useMemo } from 'react';
import { NodeTemplates, NodeTemplate } from '@esengine/behavior-tree';
import { Core } from '@esengine/ecs-framework';
import { EditorPluginManager, MessageHub } from '@esengine/editor-core';
import { NodeIcon } from './NodeIcon';
interface BehaviorTreeNodePaletteProps {
onNodeSelect?: (template: NodeTemplate) => void;
}
/**
* 获取节点类型对应的颜色
*/
const getTypeColor = (type: string): string => {
switch (type) {
case 'composite': return '#1976d2';
case 'action': return '#388e3c';
case 'condition': return '#d32f2f';
case 'decorator': return '#fb8c00';
case 'blackboard': return '#8e24aa';
default: return '#7b1fa2';
}
};
/**
* 行为树节点面板
*
* 显示所有可用的行为树节点模板,支持拖拽创建
*/
export const BehaviorTreeNodePalette: React.FC<BehaviorTreeNodePaletteProps> = ({
onNodeSelect
}) => {
const [selectedCategory, setSelectedCategory] = useState<string>('all');
const [allTemplates, setAllTemplates] = useState<NodeTemplate[]>([]);
// 获取所有节点模板(包括插件提供的)
const loadAllTemplates = () => {
console.log('[BehaviorTreeNodePalette] 开始加载节点模板');
try {
const pluginManager = Core.services.resolve(EditorPluginManager);
const allPlugins = pluginManager.getAllEditorPlugins();
console.log('[BehaviorTreeNodePalette] 找到插件数量:', allPlugins.length);
// 合并所有插件的节点模板
const templates: NodeTemplate[] = [];
for (const plugin of allPlugins) {
if (plugin.getNodeTemplates) {
console.log('[BehaviorTreeNodePalette] 从插件获取模板:', plugin.name);
const pluginTemplates = plugin.getNodeTemplates();
console.log('[BehaviorTreeNodePalette] 插件提供的模板数量:', pluginTemplates.length);
if (pluginTemplates.length > 0) {
console.log('[BehaviorTreeNodePalette] 第一个模板:', pluginTemplates[0].displayName);
}
templates.push(...pluginTemplates);
}
}
// 如果没有插件提供模板,回退到装饰器注册的模板
if (templates.length === 0) {
console.log('[BehaviorTreeNodePalette] 没有插件提供模板,使用默认模板');
templates.push(...NodeTemplates.getAllTemplates());
}
console.log('[BehaviorTreeNodePalette] 总共加载了', templates.length, '个模板');
setAllTemplates(templates);
} catch (error) {
console.error('[BehaviorTreeNodePalette] 加载模板失败:', error);
// 如果无法访问插件管理器,使用默认模板
setAllTemplates(NodeTemplates.getAllTemplates());
}
};
// 初始加载
useEffect(() => {
loadAllTemplates();
}, []);
// 监听语言变化事件
useEffect(() => {
try {
const messageHub = Core.services.resolve(MessageHub);
console.log('[BehaviorTreeNodePalette] 订阅 locale:changed 事件');
const unsubscribe = messageHub.subscribe('locale:changed', (data: any) => {
console.log('[BehaviorTreeNodePalette] 收到 locale:changed 事件:', data);
// 语言变化时重新加载模板
loadAllTemplates();
});
return () => {
console.log('[BehaviorTreeNodePalette] 取消订阅 locale:changed 事件');
unsubscribe();
};
} catch (error) {
console.error('[BehaviorTreeNodePalette] 订阅事件失败:', error);
// 如果无法访问 MessageHub忽略
}
}, []);
// 按类别分组(排除根节点类别)
const categories = useMemo(() =>
['all', ...new Set(allTemplates
.filter((t) => t.category !== '根节点')
.map((t) => t.category))]
, [allTemplates]);
const filteredTemplates = useMemo(() =>
(selectedCategory === 'all'
? allTemplates
: allTemplates.filter((t) => t.category === selectedCategory))
.filter((t) => t.category !== '根节点')
, [allTemplates, selectedCategory]);
const handleNodeClick = (template: NodeTemplate) => {
onNodeSelect?.(template);
};
const handleDragStart = (e: React.DragEvent, template: NodeTemplate) => {
const templateJson = JSON.stringify(template);
e.dataTransfer.setData('application/behavior-tree-node', templateJson);
e.dataTransfer.setData('text/plain', templateJson);
e.dataTransfer.effectAllowed = 'copy';
const dragImage = e.currentTarget as HTMLElement;
if (dragImage) {
e.dataTransfer.setDragImage(dragImage, 50, 25);
}
};
return (
<div style={{
display: 'flex',
flexDirection: 'column',
height: '100%',
backgroundColor: '#1e1e1e',
color: '#cccccc',
fontFamily: 'sans-serif'
}}>
<style>{`
.node-palette-list::-webkit-scrollbar {
width: 8px;
}
.node-palette-list::-webkit-scrollbar-track {
background: #1e1e1e;
}
.node-palette-list::-webkit-scrollbar-thumb {
background: #3c3c3c;
border-radius: 4px;
}
.node-palette-list::-webkit-scrollbar-thumb:hover {
background: #4c4c4c;
}
`}</style>
{/* 类别选择器 */}
<div style={{
padding: '10px',
borderBottom: '1px solid #333',
display: 'flex',
flexWrap: 'wrap',
gap: '5px'
}}>
{categories.map((category) => (
<button
key={category}
onClick={() => setSelectedCategory(category)}
style={{
padding: '5px 10px',
backgroundColor: selectedCategory === category ? '#0e639c' : '#3c3c3c',
color: '#cccccc',
border: 'none',
borderRadius: '3px',
cursor: 'pointer',
fontSize: '12px'
}}
>
{category}
</button>
))}
</div>
{/* 节点列表 */}
<div className="node-palette-list" style={{
flex: 1,
overflowY: 'auto',
padding: '10px'
}}>
{filteredTemplates.map((template, index) => {
const className = template.className || '';
return (
<div
key={index}
draggable={true}
onDragStart={(e) => handleDragStart(e, template)}
onClick={() => handleNodeClick(template)}
style={{
padding: '10px',
marginBottom: '8px',
backgroundColor: '#2d2d2d',
borderLeft: `4px solid ${getTypeColor(template.type || '')}`,
borderRadius: '3px',
cursor: 'grab',
transition: 'all 0.2s',
userSelect: 'none',
WebkitUserSelect: 'none'
}}
onMouseEnter={(e) => {
e.currentTarget.style.backgroundColor = '#3d3d3d';
e.currentTarget.style.transform = 'translateX(2px)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = '#2d2d2d';
e.currentTarget.style.transform = 'translateX(0)';
}}
onMouseDown={(e) => {
e.currentTarget.style.cursor = 'grabbing';
}}
onMouseUp={(e) => {
e.currentTarget.style.cursor = 'grab';
}}
>
<div style={{
display: 'flex',
alignItems: 'flex-start',
marginBottom: '5px',
pointerEvents: 'none',
gap: '8px'
}}>
{template.icon && (
<span style={{ display: 'flex', alignItems: 'center', paddingTop: '2px' }}>
<NodeIcon iconName={template.icon} size={16} />
</span>
)}
<div style={{ flex: 1 }}>
<div style={{ fontSize: '14px', fontWeight: '500', marginBottom: '2px' }}>
{template.displayName}
</div>
{className && (
<div style={{
color: '#666',
fontSize: '10px',
fontFamily: 'Consolas, Monaco, monospace',
opacity: 0.8
}}>
{className}
</div>
)}
</div>
</div>
<div style={{
fontSize: '12px',
color: '#999',
lineHeight: '1.4',
pointerEvents: 'none'
}}>
{template.description}
</div>
<div style={{
marginTop: '5px',
fontSize: '11px',
color: '#666',
pointerEvents: 'none'
}}>
{template.category}
</div>
</div>
);
})}
</div>
{/* 帮助提示 */}
<div style={{
padding: '10px',
borderTop: '1px solid #333',
fontSize: '11px',
color: '#666',
textAlign: 'center'
}}>
</div>
</div>
);
};

View File

@@ -1,400 +0,0 @@
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { NodeTemplate, PropertyDefinition } from '@esengine/behavior-tree';
import {
List, GitBranch, Layers, Shuffle,
RotateCcw, Repeat, CheckCircle, XCircle, CheckCheck, HelpCircle, Snowflake, Timer,
Clock, FileText, Edit, Calculator, Code,
Equal, Dices, Settings, Database, FolderOpen, TreePine,
LucideIcon
} from 'lucide-react';
import { AssetPickerDialog } from './AssetPickerDialog';
const iconMap: Record<string, LucideIcon> = {
List, GitBranch, Layers, Shuffle,
RotateCcw, Repeat, CheckCircle, XCircle, CheckCheck, HelpCircle, Snowflake, Timer,
Clock, FileText, Edit, Calculator, Code,
Equal, Dices, Settings, Database, TreePine
};
interface BehaviorTreeNodePropertiesProps {
selectedNode?: {
template: NodeTemplate;
data: Record<string, any>;
};
onPropertyChange?: (propertyName: string, value: any) => void;
projectPath?: string | null;
}
/**
* 行为树节点属性编辑器
*
* 根据节点模板动态生成属性编辑界面
*/
export const BehaviorTreeNodeProperties: React.FC<BehaviorTreeNodePropertiesProps> = ({
selectedNode,
onPropertyChange,
projectPath
}) => {
const { t } = useTranslation();
const [assetPickerOpen, setAssetPickerOpen] = useState(false);
const [assetPickerProperty, setAssetPickerProperty] = useState<string | null>(null);
const [isComposing, setIsComposing] = useState(false);
const [localValues, setLocalValues] = useState<Record<string, any>>({});
// 当节点切换时,清空本地状态
React.useEffect(() => {
setLocalValues({});
}, [selectedNode?.template.className]);
if (!selectedNode) {
return (
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
color: '#666',
fontSize: '14px'
}}>
{t('behaviorTree.noNodeSelected')}
</div>
);
}
const { template, data } = selectedNode;
const handleChange = (propName: string, value: any) => {
if (!isComposing) {
onPropertyChange?.(propName, value);
}
};
const handleInputChange = (propName: string, value: any) => {
setLocalValues(prev => ({ ...prev, [propName]: value }));
if (!isComposing) {
onPropertyChange?.(propName, value);
}
};
const handleCompositionStart = () => {
setIsComposing(true);
};
const handleCompositionEnd = (propName: string, value: any) => {
setIsComposing(false);
onPropertyChange?.(propName, value);
};
const renderProperty = (prop: PropertyDefinition) => {
const propName = prop.name;
const hasLocalValue = propName in localValues;
const value = hasLocalValue ? localValues[propName] : (data[prop.name] ?? prop.defaultValue);
switch (prop.type) {
case 'string':
case 'variable':
return (
<input
type="text"
value={value || ''}
onChange={(e) => handleInputChange(propName, e.target.value)}
onCompositionStart={handleCompositionStart}
onCompositionEnd={(e) => handleCompositionEnd(propName, (e.target as HTMLInputElement).value)}
onBlur={(e) => onPropertyChange?.(propName, e.target.value)}
placeholder={prop.description}
style={{
width: '100%',
padding: '6px',
backgroundColor: '#3c3c3c',
border: '1px solid #555',
borderRadius: '3px',
color: '#cccccc',
fontSize: '13px'
}}
/>
);
case 'number':
return (
<input
type="number"
value={value ?? ''}
onChange={(e) => handleChange(prop.name, parseFloat(e.target.value))}
min={prop.min}
max={prop.max}
step={prop.step || 1}
placeholder={prop.description}
style={{
width: '100%',
padding: '6px',
backgroundColor: '#3c3c3c',
border: '1px solid #555',
borderRadius: '3px',
color: '#cccccc',
fontSize: '13px'
}}
/>
);
case 'boolean':
return (
<label style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}>
<input
type="checkbox"
checked={value || false}
onChange={(e) => handleChange(prop.name, e.target.checked)}
style={{ marginRight: '8px' }}
/>
<span style={{ fontSize: '13px' }}>{prop.description || '启用'}</span>
</label>
);
case 'select':
return (
<select
value={value || ''}
onChange={(e) => handleChange(prop.name, e.target.value)}
style={{
width: '100%',
padding: '6px',
backgroundColor: '#3c3c3c',
border: '1px solid #555',
borderRadius: '3px',
color: '#cccccc',
fontSize: '13px'
}}
>
<option value="">...</option>
{prop.options?.map((opt, idx) => (
<option key={idx} value={opt.value}>
{opt.label}
</option>
))}
</select>
);
case 'code':
return (
<textarea
value={value || ''}
onChange={(e) => handleInputChange(propName, e.target.value)}
onCompositionStart={handleCompositionStart}
onCompositionEnd={(e) => handleCompositionEnd(propName, (e.target as HTMLTextAreaElement).value)}
onBlur={(e) => onPropertyChange?.(propName, e.target.value)}
placeholder={prop.description}
rows={5}
style={{
width: '100%',
padding: '6px',
backgroundColor: '#3c3c3c',
border: '1px solid #555',
borderRadius: '3px',
color: '#cccccc',
fontSize: '13px',
fontFamily: 'monospace',
resize: 'vertical'
}}
/>
);
case 'blackboard':
return (
<div style={{ display: 'flex', gap: '5px' }}>
<input
type="text"
value={value || ''}
onChange={(e) => handleInputChange(propName, e.target.value)}
onCompositionStart={handleCompositionStart}
onCompositionEnd={(e) => handleCompositionEnd(propName, (e.target as HTMLInputElement).value)}
onBlur={(e) => onPropertyChange?.(propName, e.target.value)}
placeholder="黑板变量名"
style={{
flex: 1,
padding: '6px',
backgroundColor: '#3c3c3c',
border: '1px solid #555',
borderRadius: '3px',
color: '#cccccc',
fontSize: '13px'
}}
/>
<button
style={{
padding: '6px 12px',
backgroundColor: '#0e639c',
border: 'none',
borderRadius: '3px',
color: '#fff',
cursor: 'pointer',
fontSize: '12px'
}}
>
</button>
</div>
);
case 'asset':
return (
<div>
<div style={{ display: 'flex', gap: '5px' }}>
<input
type="text"
value={value || ''}
onChange={(e) => handleChange(prop.name, e.target.value)}
placeholder={prop.description || '资产ID'}
style={{
flex: 1,
padding: '6px',
backgroundColor: '#3c3c3c',
border: '1px solid #555',
borderRadius: '3px',
color: '#cccccc',
fontSize: '13px'
}}
/>
<button
onClick={() => {
setAssetPickerProperty(prop.name);
setAssetPickerOpen(true);
}}
disabled={!projectPath}
title={!projectPath ? '请先打开项目' : '浏览资产'}
style={{
padding: '6px 12px',
backgroundColor: projectPath ? '#0e639c' : '#555',
border: 'none',
borderRadius: '3px',
color: '#fff',
cursor: projectPath ? 'pointer' : 'not-allowed',
fontSize: '12px',
display: 'flex',
alignItems: 'center',
gap: '4px'
}}
>
<FolderOpen size={14} />
</button>
</div>
{!projectPath && (
<div style={{
marginTop: '5px',
fontSize: '11px',
color: '#f48771',
lineHeight: '1.4'
}}>
使
</div>
)}
</div>
);
default:
return null;
}
};
return (
<div style={{
height: '100%',
backgroundColor: '#1e1e1e',
color: '#cccccc',
fontFamily: 'sans-serif',
display: 'flex',
flexDirection: 'column'
}}>
{/* 节点信息 */}
<div style={{
padding: '15px',
borderBottom: '1px solid #333'
}}>
<div style={{
display: 'flex',
alignItems: 'center',
marginBottom: '10px'
}}>
{template.icon && (() => {
const IconComponent = iconMap[template.icon];
return IconComponent ? (
<IconComponent
size={24}
color={template.color || '#cccccc'}
style={{ marginRight: '10px' }}
/>
) : (
<span style={{ marginRight: '10px', fontSize: '24px' }}>
{template.icon}
</span>
);
})()}
<div>
<h3 style={{ margin: 0, fontSize: '16px' }}>{template.displayName}</h3>
<div style={{ fontSize: '11px', color: '#666', marginTop: '2px' }}>
{template.category}
</div>
</div>
</div>
<div style={{ fontSize: '13px', color: '#999', lineHeight: '1.5' }}>
{template.description}
</div>
</div>
{/* 属性列表 */}
<div style={{
flex: 1,
overflowY: 'auto',
padding: '15px'
}}>
{template.properties.length === 0 ? (
<div style={{ color: '#666', fontSize: '13px', textAlign: 'center', paddingTop: '20px' }}>
{t('behaviorTree.noConfigurableProperties')}
</div>
) : (
template.properties.map((prop, index) => (
<div key={index} style={{ marginBottom: '20px' }}>
<label
style={{
display: 'block',
marginBottom: '8px',
fontSize: '13px',
fontWeight: 'bold',
color: '#cccccc',
cursor: prop.description ? 'help' : 'default'
}}
title={prop.description}
>
{prop.label}
{prop.required && (
<span style={{ color: '#f48771', marginLeft: '4px' }}>*</span>
)}
</label>
{renderProperty(prop)}
</div>
))
)}
</div>
{/* 资产选择器对话框 */}
{assetPickerOpen && projectPath && assetPickerProperty && (
<AssetPickerDialog
projectPath={projectPath}
fileExtension="btree"
assetBasePath=".ecs/behaviors"
locale={t('locale') === 'zh' ? 'zh' : 'en'}
onSelect={(assetId) => {
// AssetPickerDialog 返回 assetId不含扩展名相对于 .ecs/behaviors 的路径)
handleChange(assetPickerProperty, assetId);
setAssetPickerOpen(false);
setAssetPickerProperty(null);
}}
onClose={() => {
setAssetPickerOpen(false);
setAssetPickerProperty(null);
}}
/>
)}
</div>
);
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,141 @@
import { useState, useEffect } from 'react';
import { X, Cpu } from 'lucide-react';
import { ICompiler, CompileResult, CompilerContext } from '@esengine/editor-core';
import '../styles/CompileDialog.css';
interface CompileDialogProps<TOptions = unknown> {
isOpen: boolean;
onClose: () => void;
compiler: ICompiler<TOptions>;
context: CompilerContext;
initialOptions?: TOptions;
}
export function CompileDialog<TOptions = unknown>({
isOpen,
onClose,
compiler,
context,
initialOptions
}: CompileDialogProps<TOptions>) {
const [options, setOptions] = useState<TOptions>(initialOptions as TOptions);
const [isCompiling, setIsCompiling] = useState(false);
const [result, setResult] = useState<CompileResult | null>(null);
const [validationError, setValidationError] = useState<string | null>(null);
useEffect(() => {
if (isOpen && initialOptions) {
setOptions(initialOptions);
setResult(null);
setValidationError(null);
}
}, [isOpen, initialOptions]);
useEffect(() => {
if (compiler.validateOptions && options) {
const error = compiler.validateOptions(options);
setValidationError(error);
}
}, [options, compiler]);
if (!isOpen) return null;
const handleCompile = async () => {
if (validationError) {
return;
}
setIsCompiling(true);
setResult(null);
try {
const compileResult = await compiler.compile(options, context);
setResult(compileResult);
} catch (error) {
setResult({
success: false,
message: `编译失败: ${error}`,
errors: [String(error)]
});
} finally {
setIsCompiling(false);
}
};
return (
<div className="compile-dialog-overlay">
<div className="compile-dialog">
<div className="compile-dialog-header">
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<Cpu size={20} />
<h3>{compiler.name}</h3>
</div>
<button onClick={onClose} className="compile-dialog-close">
<X size={20} />
</button>
</div>
<div className="compile-dialog-content">
{compiler.description && (
<div className="compile-dialog-description">
{compiler.description}
</div>
)}
{compiler.createConfigUI && compiler.createConfigUI(setOptions, context)}
{validationError && (
<div className="compile-dialog-error">
{validationError}
</div>
)}
{result && (
<div className={`compile-dialog-result ${result.success ? 'success' : 'error'}`}>
<div className="compile-dialog-result-message">
{result.message}
</div>
{result.outputFiles && result.outputFiles.length > 0 && (
<div className="compile-dialog-output-files">
<div style={{ fontWeight: 600, marginBottom: '8px' }}>:</div>
{result.outputFiles.map((file, index) => (
<div key={index} className="compile-dialog-output-file">
{file}
</div>
))}
</div>
)}
{result.errors && result.errors.length > 0 && (
<div className="compile-dialog-errors">
<div style={{ fontWeight: 600, marginBottom: '8px' }}>:</div>
{result.errors.map((error, index) => (
<div key={index} className="compile-dialog-error-item">
{error}
</div>
))}
</div>
)}
</div>
)}
</div>
<div className="compile-dialog-footer">
<button
onClick={onClose}
className="compile-dialog-btn compile-dialog-btn-cancel"
disabled={isCompiling}
>
</button>
<button
onClick={handleCompile}
className="compile-dialog-btn compile-dialog-btn-primary"
disabled={isCompiling || !!validationError}
>
{isCompiling ? '编译中...' : '编译'}
</button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,244 @@
import { useState, useEffect, useRef, useCallback } from 'react';
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 '../styles/CompilerConfigDialog.css';
interface DirectoryEntry {
name: string;
path: string;
is_dir: boolean;
}
interface CompilerConfigDialogProps {
isOpen: boolean;
compilerId: string;
projectPath: string | null;
currentFileName?: string;
onClose: () => void;
onCompileComplete?: (result: CompileResult) => void;
}
export const CompilerConfigDialog: React.FC<CompilerConfigDialogProps> = ({
isOpen,
compilerId,
projectPath,
currentFileName,
onClose,
onCompileComplete
}) => {
const [compiler, setCompiler] = useState<ICompiler | null>(null);
const [options, setOptions] = useState<unknown>(null);
const [isCompiling, setIsCompiling] = useState(false);
const [compileResult, setCompileResult] = useState<CompileResult | null>(null);
const optionsRef = useRef<unknown>(null);
useEffect(() => {
if (isOpen && compilerId) {
try {
const registry = Core.services.resolve(CompilerRegistry);
console.log('[CompilerConfigDialog] Registry resolved:', registry);
console.log('[CompilerConfigDialog] Available compilers:', registry.getAll().map(c => c.id));
const comp = registry.get(compilerId);
console.log(`[CompilerConfigDialog] Looking for compiler: ${compilerId}, found:`, comp);
setCompiler(comp || null);
} catch (error) {
console.error('[CompilerConfigDialog] Failed to resolve CompilerRegistry:', error);
setCompiler(null);
}
}
}, [isOpen, compilerId]);
const handleOptionsChange = useCallback((newOptions: unknown) => {
optionsRef.current = newOptions;
setOptions(newOptions);
}, []);
const createFileSystem = (): IFileSystem => ({
readFile: async (path: string) => {
return await invoke<string>('read_file_content', { path });
},
writeFile: async (path: string, content: string) => {
await invoke('write_file_content', { path, content });
},
writeBinary: async (path: string, data: Uint8Array) => {
await invoke('write_binary_file', { filePath: path, content: Array.from(data) });
},
exists: async (path: string) => {
return await invoke<boolean>('path_exists', { path });
},
createDirectory: async (path: string) => {
await invoke('create_directory', { path });
},
listDirectory: async (path: string): Promise<FileEntry[]> => {
const entries = await invoke<DirectoryEntry[]>('list_directory', { path });
return entries.map(e => ({
name: e.name,
path: e.path,
isDirectory: e.is_dir
}));
},
deleteFile: async (path: string) => {
await invoke('delete_file', { path });
},
deleteDirectory: async (path: string) => {
await invoke('delete_folder', { path });
},
scanFiles: async (dir: string, pattern: string) => {
// Check if directory exists, create if not
const dirExists = await invoke<boolean>('path_exists', { path: dir });
if (!dirExists) {
await invoke('create_directory', { path: dir });
return []; // New directory has no files
}
const entries = await invoke<DirectoryEntry[]>('list_directory', { path: dir });
const ext = pattern.replace(/\*/g, '');
return entries
.filter(e => !e.is_dir && e.name.endsWith(ext))
.map(e => e.name.replace(ext, ''));
}
});
const createDialog = (): IDialog => ({
openDialog: async (opts) => {
const result = await tauriOpen({
directory: opts.directory,
multiple: opts.multiple,
title: opts.title,
defaultPath: opts.defaultPath
});
return result;
},
saveDialog: async (opts) => {
const result = await tauriSave({
title: opts.title,
defaultPath: opts.defaultPath,
filters: opts.filters
});
return result;
},
showMessage: async (title: string, message: string, type?: 'info' | 'warning' | 'error') => {
await tauriMessage(message, { title, kind: type || 'info' });
},
showConfirm: async (title: string, message: string) => {
return await tauriConfirm(message, { title });
}
});
const createContext = (): CompilerContext => ({
projectPath,
moduleContext: {
fileSystem: createFileSystem(),
dialog: createDialog()
},
getService: <T extends IService>(serviceClass: ServiceType<T>): T | undefined => {
try {
return Core.services.resolve(serviceClass);
} catch {
return undefined;
}
}
});
const handleCompile = async () => {
if (!compiler || !optionsRef.current) return;
setIsCompiling(true);
setCompileResult(null);
try {
const context = createContext();
const result = await compiler.compile(optionsRef.current, context);
setCompileResult(result);
onCompileComplete?.(result);
if (result.success) {
setTimeout(() => {
onClose();
}, 2000);
}
} catch (error) {
setCompileResult({
success: false,
message: `编译失败: ${error}`,
errors: [String(error)]
});
} finally {
setIsCompiling(false);
}
};
if (!isOpen) return null;
const context = createContext();
return (
<div className="compiler-dialog-overlay">
<div className="compiler-dialog">
<div className="compiler-dialog-header">
<h3>{compiler?.name || '编译器配置'}</h3>
<button className="close-button" onClick={onClose}>
<X size={18} />
</button>
</div>
<div className="compiler-dialog-body">
{compiler?.createConfigUI ? (
compiler.createConfigUI(handleOptionsChange, context)
) : (
<div className="no-config">
{compiler ? '该编译器没有配置界面' : '编译器未找到'}
</div>
)}
</div>
{compileResult && (
<div className={`compile-result ${compileResult.success ? 'success' : 'error'}`}>
<div className="result-message">{compileResult.message}</div>
{compileResult.outputFiles && compileResult.outputFiles.length > 0 && (
<div className="output-files">
{compileResult.outputFiles.length}
</div>
)}
{compileResult.errors && compileResult.errors.length > 0 && (
<div className="error-list">
{compileResult.errors.map((err, i) => (
<div key={i} className="error-item">{err}</div>
))}
</div>
)}
</div>
)}
<div className="compiler-dialog-footer">
<button
className="cancel-button"
onClick={onClose}
disabled={isCompiling}
>
</button>
<button
className="compile-button"
onClick={handleCompile}
disabled={isCompiling || !compiler || !options}
>
{isCompiling ? (
<>
<Loader2 size={16} className="spinning" />
...
</>
) : (
<>
<Play size={16} />
</>
)}
</button>
</div>
</div>
</div>
);
};

View File

@@ -1,7 +1,7 @@
import { useState, useEffect, useRef, useMemo, memo } from 'react';
import { LogService, LogEntry } from '@esengine/editor-core';
import { LogLevel } from '@esengine/ecs-framework';
import { Trash2, AlertCircle, Info, AlertTriangle, XCircle, Bug, Search, Maximize2, ChevronRight, ChevronDown, Wifi } from 'lucide-react';
import { Trash2, AlertCircle, Info, AlertTriangle, XCircle, Bug, Search, Wifi } from 'lucide-react';
import { JsonViewer } from './JsonViewer';
import '../styles/ConsolePanel.css';
@@ -9,114 +9,73 @@ interface ConsolePanelProps {
logService: LogService;
}
interface ParsedLogData {
isJSON: boolean;
jsonStr?: string;
extracted?: { prefix: string; json: string; suffix: string } | null;
const MAX_LOGS = 1000;
// 提取JSON检测和格式化逻辑
function tryParseJSON(message: string): { isJSON: boolean; parsed?: unknown } {
try {
const parsed: unknown = JSON.parse(message);
return { isJSON: true, parsed };
} catch {
return { isJSON: false };
}
}
const LogEntryItem = memo(({
log,
isExpanded,
onToggleExpand,
onOpenJsonViewer,
parsedData
}: {
// 格式化时间
function formatTime(date: Date): string {
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
const ms = date.getMilliseconds().toString().padStart(3, '0');
return `${hours}:${minutes}:${seconds}.${ms}`;
}
// 日志等级图标
function getLevelIcon(level: LogLevel) {
switch (level) {
case LogLevel.Debug:
return <Bug size={14} />;
case LogLevel.Info:
return <Info size={14} />;
case LogLevel.Warn:
return <AlertTriangle size={14} />;
case LogLevel.Error:
case LogLevel.Fatal:
return <XCircle size={14} />;
default:
return <AlertCircle size={14} />;
}
}
// 日志等级样式类
function getLevelClass(level: LogLevel): string {
switch (level) {
case LogLevel.Debug:
return 'log-entry-debug';
case LogLevel.Info:
return 'log-entry-info';
case LogLevel.Warn:
return 'log-entry-warn';
case LogLevel.Error:
case LogLevel.Fatal:
return 'log-entry-error';
default:
return '';
}
}
// 单个日志条目组件
const LogEntryItem = memo(({ log, onOpenJsonViewer }: {
log: LogEntry;
isExpanded: boolean;
onToggleExpand: (id: number) => void;
onOpenJsonViewer: (jsonStr: string) => void;
parsedData: ParsedLogData;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onOpenJsonViewer: (data: any) => void;
}) => {
const getLevelIcon = (level: LogLevel) => {
switch (level) {
case LogLevel.Debug:
return <Bug size={14} />;
case LogLevel.Info:
return <Info size={14} />;
case LogLevel.Warn:
return <AlertTriangle size={14} />;
case LogLevel.Error:
case LogLevel.Fatal:
return <XCircle size={14} />;
default:
return <AlertCircle size={14} />;
}
};
const getLevelClass = (level: LogLevel): string => {
switch (level) {
case LogLevel.Debug:
return 'log-entry-debug';
case LogLevel.Info:
return 'log-entry-info';
case LogLevel.Warn:
return 'log-entry-warn';
case LogLevel.Error:
case LogLevel.Fatal:
return 'log-entry-error';
default:
return '';
}
};
const formatTime = (date: Date): string => {
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
const ms = date.getMilliseconds().toString().padStart(3, '0');
return `${hours}:${minutes}:${seconds}.${ms}`;
};
const formatMessage = (message: string, isExpanded: boolean, parsedData: ParsedLogData): JSX.Element => {
const MAX_PREVIEW_LENGTH = 200;
const { isJSON, jsonStr, extracted } = parsedData;
const shouldTruncate = message.length > MAX_PREVIEW_LENGTH && !isExpanded;
return (
<div className="log-message-container">
<div className="log-message-text">
{shouldTruncate ? (
<>
{extracted && extracted.prefix && <span>{extracted.prefix} </span>}
<span className="log-message-preview">
{message.substring(0, MAX_PREVIEW_LENGTH)}...
</span>
</>
) : (
<span>{message}</span>
)}
</div>
{isJSON && jsonStr && (
<button
className="log-open-json-btn"
onClick={(e) => {
e.stopPropagation();
onOpenJsonViewer(jsonStr);
}}
title="Open in JSON Viewer"
>
<Maximize2 size={12} />
</button>
)}
</div>
);
};
const shouldShowExpander = log.message.length > 200;
const { isJSON, parsed } = useMemo(() => tryParseJSON(log.message), [log.message]);
const shouldTruncate = log.message.length > 200;
const [isExpanded, setIsExpanded] = useState(false);
return (
<div
className={`log-entry ${getLevelClass(log.level)} ${log.source === 'remote' ? 'log-entry-remote' : ''} ${isExpanded ? 'log-entry-expanded' : ''}`}
>
{shouldShowExpander && (
<div
className="log-entry-expander"
onClick={() => onToggleExpand(log.id)}
>
{isExpanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
</div>
)}
<div className={`log-entry ${getLevelClass(log.level)} ${log.source === 'remote' ? 'log-entry-remote' : ''}`}>
<div className="log-entry-icon">
{getLevelIcon(log.level)}
</div>
@@ -132,7 +91,45 @@ const LogEntryItem = memo(({
</div>
)}
<div className="log-entry-message">
{formatMessage(log.message, isExpanded, parsedData)}
<div className="log-message-container">
<div className="log-message-text">
{shouldTruncate && !isExpanded ? (
<>
<span className="log-message-preview">
{log.message.substring(0, 200)}...
</span>
<button
className="log-expand-btn"
onClick={() => setIsExpanded(true)}
>
Show more
</button>
</>
) : (
<>
<span>{log.message}</span>
{shouldTruncate && (
<button
className="log-expand-btn"
onClick={() => setIsExpanded(false)}
>
Show less
</button>
)}
</>
)}
</div>
{isJSON && parsed !== undefined && (
<button
className="log-open-json-btn"
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onClick={() => onOpenJsonViewer(parsed as any)}
title="Open in JSON Viewer"
>
JSON
</button>
)}
</div>
</div>
</div>
);
@@ -140,10 +137,9 @@ const LogEntryItem = memo(({
LogEntryItem.displayName = 'LogEntryItem';
const MAX_LOGS = 1000;
export function ConsolePanel({ logService }: ConsolePanelProps) {
const [logs, setLogs] = useState<LogEntry[]>([]);
// 状态管理
const [logs, setLogs] = useState<LogEntry[]>(() => logService.getLogs().slice(-MAX_LOGS));
const [filter, setFilter] = useState('');
const [levelFilter, setLevelFilter] = useState<Set<LogLevel>>(new Set([
LogLevel.Debug,
@@ -154,37 +150,30 @@ export function ConsolePanel({ logService }: ConsolePanelProps) {
]));
const [showRemoteOnly, setShowRemoteOnly] = useState(false);
const [autoScroll, setAutoScroll] = useState(true);
const [expandedLogs, setExpandedLogs] = useState<Set<number>>(new Set());
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const [jsonViewerData, setJsonViewerData] = useState<any>(null);
const logContainerRef = useRef<HTMLDivElement>(null);
// 订阅日志更新
useEffect(() => {
setLogs(logService.getLogs().slice(-MAX_LOGS));
const unsubscribe = logService.subscribe((entry) => {
setLogs((prev) => {
const newLogs = [...prev, entry];
if (newLogs.length > MAX_LOGS) {
return newLogs.slice(-MAX_LOGS);
}
return newLogs;
return newLogs.length > MAX_LOGS ? newLogs.slice(-MAX_LOGS) : newLogs;
});
});
return unsubscribe;
}, [logService]);
// 自动滚动
useEffect(() => {
if (autoScroll && logContainerRef.current) {
logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;
}
}, [logs, autoScroll]);
const handleClear = () => {
logService.clear();
setLogs([]);
};
// 处理滚动
const handleScroll = () => {
if (logContainerRef.current) {
const { scrollTop, scrollHeight, clientHeight } = logContainerRef.current;
@@ -193,6 +182,13 @@ export function ConsolePanel({ logService }: ConsolePanelProps) {
}
};
// 清空日志
const handleClear = () => {
logService.clear();
setLogs([]);
};
// 切换等级过滤
const toggleLevelFilter = (level: LogLevel) => {
const newFilter = new Set(levelFilter);
if (newFilter.has(level)) {
@@ -203,129 +199,7 @@ export function ConsolePanel({ logService }: ConsolePanelProps) {
setLevelFilter(newFilter);
};
// 使用ref保存缓存避免每次都重新计算
const parsedLogsCacheRef = useRef<Map<number, ParsedLogData>>(new Map());
const extractJSON = useMemo(() => {
return (message: string): { prefix: string; json: string; suffix: string } | null => {
// 快速路径:如果消息太短,直接返回
if (message.length < 2) return null;
const jsonStartChars = ['{', '['];
let startIndex = -1;
for (const char of jsonStartChars) {
const index = message.indexOf(char);
if (index !== -1 && (startIndex === -1 || index < startIndex)) {
startIndex = index;
}
}
if (startIndex === -1) return null;
// 使用栈匹配算法更高效地找到JSON边界
const startChar = message[startIndex];
const endChar = startChar === '{' ? '}' : ']';
let depth = 0;
let inString = false;
let escape = false;
for (let i = startIndex; i < message.length; i++) {
const char = message[i];
if (escape) {
escape = false;
continue;
}
if (char === '\\') {
escape = true;
continue;
}
if (char === '"') {
inString = !inString;
continue;
}
if (inString) continue;
if (char === startChar) {
depth++;
} else if (char === endChar) {
depth--;
if (depth === 0) {
// 找到匹配的结束符
const possibleJson = message.substring(startIndex, i + 1);
try {
JSON.parse(possibleJson);
return {
prefix: message.substring(0, startIndex).trim(),
json: possibleJson,
suffix: message.substring(i + 1).trim()
};
} catch {
return null;
}
}
}
}
return null;
};
}, []);
const parsedLogsCache = useMemo(() => {
const cache = parsedLogsCacheRef.current;
// 只处理新增的日志
for (const log of logs) {
// 如果已经缓存过,跳过
if (cache.has(log.id)) continue;
try {
JSON.parse(log.message);
cache.set(log.id, {
isJSON: true,
jsonStr: log.message,
extracted: null
});
} catch {
const extracted = extractJSON(log.message);
if (extracted) {
try {
JSON.parse(extracted.json);
cache.set(log.id, {
isJSON: true,
jsonStr: extracted.json,
extracted
});
} catch {
cache.set(log.id, {
isJSON: false,
extracted
});
}
} else {
cache.set(log.id, {
isJSON: false,
extracted: null
});
}
}
}
// 清理不再需要的缓存(日志被删除)
const logIds = new Set(logs.map((log) => log.id));
for (const cachedId of cache.keys()) {
if (!logIds.has(cachedId)) {
cache.delete(cachedId);
}
}
return cache;
}, [logs, extractJSON]);
// 过滤日志
const filteredLogs = useMemo(() => {
return logs.filter((log) => {
if (!levelFilter.has(log.level)) return false;
@@ -337,25 +211,7 @@ export function ConsolePanel({ logService }: ConsolePanelProps) {
});
}, [logs, levelFilter, showRemoteOnly, filter]);
const toggleLogExpand = (logId: number) => {
const newExpanded = new Set(expandedLogs);
if (newExpanded.has(logId)) {
newExpanded.delete(logId);
} else {
newExpanded.add(logId);
}
setExpandedLogs(newExpanded);
};
const openJsonViewer = (jsonStr: string) => {
try {
const parsed = JSON.parse(jsonStr);
setJsonViewerData(parsed);
} catch {
console.error('Failed to parse JSON:', jsonStr);
}
};
// 统计各等级日志数量
const levelCounts = useMemo(() => ({
[LogLevel.Debug]: logs.filter((l) => l.level === LogLevel.Debug).length,
[LogLevel.Info]: logs.filter((l) => l.level === LogLevel.Info).length,
@@ -446,10 +302,7 @@ export function ConsolePanel({ logService }: ConsolePanelProps) {
<LogEntryItem
key={log.id}
log={log}
isExpanded={expandedLogs.has(log.id)}
onToggleExpand={toggleLogExpand}
onOpenJsonViewer={openJsonViewer}
parsedData={parsedLogsCache.get(log.id) || { isJSON: false }}
onOpenJsonViewer={setJsonViewerData}
/>
))
)}

View File

@@ -30,6 +30,7 @@ interface FileTreeProps {
export interface FileTreeHandle {
collapseAll: () => void;
refresh: () => void;
}
export const FileTree = forwardRef<FileTreeHandle, FileTreeProps>(({ rootPath, onSelectFile, selectedPath, messageHub, searchQuery, showFiles = true }, ref) => {
@@ -69,7 +70,8 @@ export const FileTree = forwardRef<FileTreeHandle, FileTreeProps>(({ rootPath, o
};
useImperativeHandle(ref, () => ({
collapseAll
collapseAll,
refresh: refreshTree
}));
useEffect(() => {

View File

@@ -1,149 +1,10 @@
import { useCallback, ReactNode, useRef, useEffect, useState } from 'react';
import { Layout, Model, TabNode, IJsonModel, Actions, IJsonTabSetNode, IJsonRowNode, Action, IJsonTabNode, DockLocation } from 'flexlayout-react';
import { useCallback, useRef, useEffect, useState } from 'react';
import { Layout, Model, TabNode, IJsonModel, Actions, Action, DockLocation } from 'flexlayout-react';
import 'flexlayout-react/style/light.css';
import '../styles/FlexLayoutDock.css';
import { LayoutMerger, LayoutBuilder, FlexDockPanel } from '../shared/layout';
/**
* 合并保存的布局和新的默认布局
* 保留用户的布局调整(大小、位置等),同时添加新面板并移除已关闭的面板
*/
function mergeLayouts(savedLayout: IJsonModel, defaultLayout: IJsonModel, currentPanels: FlexDockPanel[]): IJsonModel {
// 获取当前所有面板ID
const currentPanelIds = new Set(currentPanels.map(p => p.id));
// 收集保存布局中存在的面板ID
const savedPanelIds = new Set<string>();
const collectPanelIds = (node: any) => {
if (node.type === 'tab' && node.id) {
savedPanelIds.add(node.id);
}
if (node.children) {
node.children.forEach((child: any) => collectPanelIds(child));
}
};
collectPanelIds(savedLayout.layout);
// 同时收集borders中的面板ID
if (savedLayout.borders) {
savedLayout.borders.forEach((border: any) => {
if (border.children) {
collectPanelIds({ children: border.children });
}
});
}
// 找出新增的面板和已移除的面板
const newPanelIds = Array.from(currentPanelIds).filter(id => !savedPanelIds.has(id));
const removedPanelIds = Array.from(savedPanelIds).filter(id => !currentPanelIds.has(id));
// 克隆保存的布局
const mergedLayout = JSON.parse(JSON.stringify(savedLayout));
// 确保borders为空不保留最小化状态
if (mergedLayout.borders) {
mergedLayout.borders = mergedLayout.borders.map((border: any) => ({
...border,
children: []
}));
}
// 第一步:移除已关闭的面板
if (removedPanelIds.length > 0) {
const removePanels = (node: any): boolean => {
if (!node.children) return false;
// 过滤掉已移除的tab
if (node.type === 'tabset' || node.type === 'row') {
const originalLength = node.children.length;
node.children = node.children.filter((child: any) => {
if (child.type === 'tab') {
return !removedPanelIds.includes(child.id);
}
return true;
});
// 如果有tab被移除调整selected索引
if (node.type === 'tabset' && node.children.length < originalLength) {
if (node.selected >= node.children.length) {
node.selected = Math.max(0, node.children.length - 1);
}
}
// 递归处理子节点
node.children.forEach((child: any) => removePanels(child));
return node.children.length < originalLength;
}
return false;
};
removePanels(mergedLayout.layout);
}
// 第二步:如果没有新面板,直接返回清理后的布局
if (newPanelIds.length === 0) {
return mergedLayout;
}
// 第三步:在默认布局中找到新面板的配置
const newPanelTabs: IJsonTabNode[] = [];
const findNewPanels = (node: any) => {
if (node.type === 'tab' && node.id && newPanelIds.includes(node.id)) {
newPanelTabs.push(node);
}
if (node.children) {
node.children.forEach((child: any) => findNewPanels(child));
}
};
findNewPanels(defaultLayout.layout);
// 第四步将新面板添加到中心区域的第一个tabset
const addNewPanelsToCenter = (node: any): boolean => {
if (node.type === 'tabset') {
// 检查是否是中心区域的tabset通过检查是否包含非hierarchy/asset/inspector/console面板
const hasNonSidePanel = node.children?.some((child: any) => {
const id = child.id || '';
return !id.includes('hierarchy') &&
!id.includes('asset') &&
!id.includes('inspector') &&
!id.includes('console');
});
if (hasNonSidePanel && node.children) {
// 添加新面板到这个tabset
node.children.push(...newPanelTabs);
// 选中最后添加的面板
node.selected = node.children.length - 1;
return true;
}
}
if (node.children) {
for (const child of node.children) {
if (addNewPanelsToCenter(child)) {
return true;
}
}
}
return false;
};
// 尝试添加新面板到中心区域
if (!addNewPanelsToCenter(mergedLayout.layout)) {
// 如果没有找到合适的tabset使用默认布局
return defaultLayout;
}
return mergedLayout;
}
export interface FlexDockPanel {
id: string;
title: string;
content: ReactNode;
closable?: boolean;
}
export type { FlexDockPanel };
interface FlexLayoutDockContainerProps {
panels: FlexDockPanel[];
@@ -158,170 +19,7 @@ export function FlexLayoutDockContainer({ panels, onPanelClose, activePanelId }:
const previousPanelTitlesRef = useRef<Map<string, string>>(new Map());
const createDefaultLayout = useCallback((): IJsonModel => {
const hierarchyPanels = panels.filter((p) => p.id.includes('hierarchy'));
const assetPanels = panels.filter((p) => p.id.includes('asset'));
const rightPanels = panels.filter((p) => p.id.includes('inspector'));
const bottomPanels = panels.filter((p) => p.id.includes('console'));
const centerPanels = panels.filter((p) =>
!hierarchyPanels.includes(p) && !assetPanels.includes(p) && !rightPanels.includes(p) && !bottomPanels.includes(p)
);
// Build center column children
const centerColumnChildren: (IJsonTabSetNode | IJsonRowNode)[] = [];
if (centerPanels.length > 0) {
// 找到要激活的tab的索引
let activeTabIndex = 0;
if (activePanelId) {
const index = centerPanels.findIndex((p) => p.id === activePanelId);
if (index !== -1) {
activeTabIndex = index;
}
}
centerColumnChildren.push({
type: 'tabset',
weight: 70,
selected: activeTabIndex,
enableMaximize: true,
children: centerPanels.map((p) => ({
type: 'tab',
name: p.title,
id: p.id,
component: p.id,
enableClose: p.closable !== false
}))
});
}
if (bottomPanels.length > 0) {
centerColumnChildren.push({
type: 'tabset',
weight: 30,
enableMaximize: true,
children: bottomPanels.map((p) => ({
type: 'tab',
name: p.title,
id: p.id,
component: p.id,
enableClose: p.closable !== false
}))
});
}
// Build main row children
const mainRowChildren: (IJsonTabSetNode | IJsonRowNode)[] = [];
// 左侧列:场景层级和资产面板垂直排列(五五分)
if (hierarchyPanels.length > 0 || assetPanels.length > 0) {
const leftColumnChildren: IJsonTabSetNode[] = [];
if (hierarchyPanels.length > 0) {
leftColumnChildren.push({
type: 'tabset',
weight: 50,
enableMaximize: true,
children: hierarchyPanels.map((p) => ({
type: 'tab',
name: p.title,
id: p.id,
component: p.id,
enableClose: p.closable !== false
}))
});
}
if (assetPanels.length > 0) {
leftColumnChildren.push({
type: 'tabset',
weight: 50,
enableMaximize: true,
children: assetPanels.map((p) => ({
type: 'tab',
name: p.title,
id: p.id,
component: p.id,
enableClose: p.closable !== false
}))
});
}
mainRowChildren.push({
type: 'row',
weight: 20,
children: leftColumnChildren
});
}
if (centerColumnChildren.length > 0) {
if (centerColumnChildren.length === 1) {
const centerChild = centerColumnChildren[0];
if (centerChild && centerChild.type === 'tabset') {
mainRowChildren.push({
type: 'tabset',
weight: 60,
enableMaximize: true,
children: centerChild.children
} as IJsonTabSetNode);
} else if (centerChild) {
mainRowChildren.push({
type: 'row',
weight: 60,
children: centerChild.children
} as IJsonRowNode);
}
} else {
mainRowChildren.push({
type: 'row',
weight: 60,
children: centerColumnChildren
});
}
}
if (rightPanels.length > 0) {
mainRowChildren.push({
type: 'tabset',
weight: 20,
enableMaximize: true,
children: rightPanels.map((p) => ({
type: 'tab',
name: p.title,
id: p.id,
component: p.id,
enableClose: p.closable !== false
}))
});
}
return {
global: {
tabEnableClose: true,
tabEnableRename: false,
tabSetEnableMaximize: true,
tabSetEnableDrop: true,
tabSetEnableDrag: true,
tabSetEnableDivide: true,
borderEnableDrop: true,
borderAutoSelectTabWhenOpen: true,
borderAutoSelectTabWhenClosed: true
},
borders: [
{
type: 'border',
location: 'bottom',
size: 200,
children: []
},
{
type: 'border',
location: 'right',
size: 300,
children: []
}
],
layout: {
type: 'row',
weight: 100,
children: mainRowChildren
}
};
return LayoutBuilder.createDefaultLayout(panels, activePanelId);
}, [panels, activePanelId]);
const [model, setModel] = useState<Model>(() => {
@@ -440,7 +138,7 @@ export function FlexLayoutDockContainer({ panels, onPanelClose, activePanelId }:
if (previousLayoutJsonRef.current && previousIds) {
try {
const savedLayout = JSON.parse(previousLayoutJsonRef.current);
const mergedLayout = mergeLayouts(savedLayout, defaultLayout, panels);
const mergedLayout = LayoutMerger.merge(savedLayout, defaultLayout, panels);
const newModel = Model.fromJson(mergedLayout);
setModel(newModel);
return;

View File

@@ -0,0 +1,263 @@
import { useState } from 'react';
import { Github, AlertCircle, CheckCircle, Loader, ExternalLink } from 'lucide-react';
import { GitHubService } from '../services/GitHubService';
import { open } from '@tauri-apps/plugin-shell';
import '../styles/GitHubAuth.css';
interface GitHubAuthProps {
githubService: GitHubService;
onSuccess: () => void;
locale: string;
}
export function GitHubAuth({ githubService, onSuccess, locale }: GitHubAuthProps) {
const [useOAuth, setUseOAuth] = useState(true);
const [githubToken, setGithubToken] = useState('');
const [userCode, setUserCode] = useState('');
const [verificationUri, setVerificationUri] = useState('');
const [authStatus, setAuthStatus] = useState<'idle' | 'pending' | 'authorized' | 'error'>('idle');
const [error, setError] = useState('');
const t = (key: string) => {
const translations: Record<string, Record<string, string>> = {
zh: {
githubLogin: 'GitHub 登录',
oauthLogin: 'OAuth 登录(推荐)',
tokenLogin: 'Token 登录',
oauthStep1: '1. 点击"开始授权"按钮',
oauthStep2: '2. 在浏览器中打开 GitHub 授权页面',
oauthStep3: '3. 输入下方显示的代码并授权',
startAuth: '开始授权',
authorizing: '等待授权中...',
authorized: '授权成功!',
authFailed: '授权失败',
userCode: '授权码',
copyCode: '复制代码',
openBrowser: '打开浏览器',
tokenLabel: 'GitHub Personal Access Token',
tokenPlaceholder: '粘贴你的 GitHub Token',
tokenHint: '需要 repo 和 workflow 权限',
createToken: '创建 Token',
login: '登录',
back: '返回'
},
en: {
githubLogin: 'GitHub Login',
oauthLogin: 'OAuth Login (Recommended)',
tokenLogin: 'Token Login',
oauthStep1: '1. Click "Start Authorization"',
oauthStep2: '2. Open GitHub authorization page in browser',
oauthStep3: '3. Enter the code shown below and authorize',
startAuth: 'Start Authorization',
authorizing: 'Waiting for authorization...',
authorized: 'Authorized!',
authFailed: 'Authorization failed',
userCode: 'Authorization Code',
copyCode: 'Copy Code',
openBrowser: 'Open Browser',
tokenLabel: 'GitHub Personal Access Token',
tokenPlaceholder: 'Paste your GitHub Token',
tokenHint: 'Requires repo and workflow permissions',
createToken: 'Create Token',
login: 'Login',
back: 'Back'
}
};
return translations[locale]?.[key] || translations.en?.[key] || key;
};
const handleOAuthLogin = async () => {
setAuthStatus('pending');
setError('');
try {
console.log('[GitHubAuth] Starting OAuth login...');
const deviceCodeResp = await githubService.requestDeviceCode();
console.log('[GitHubAuth] Device code received:', deviceCodeResp.user_code);
setUserCode(deviceCodeResp.user_code);
setVerificationUri(deviceCodeResp.verification_uri);
console.log('[GitHubAuth] Opening browser...');
await open(deviceCodeResp.verification_uri);
console.log('[GitHubAuth] Starting authentication polling...');
await githubService.authenticateWithDeviceFlow(
deviceCodeResp.device_code,
deviceCodeResp.interval,
(status) => {
console.log('[GitHubAuth] Auth status changed:', status);
setAuthStatus(status === 'pending' ? 'pending' : status === 'authorized' ? 'authorized' : 'error');
}
);
console.log('[GitHubAuth] Authorization successful!');
setAuthStatus('authorized');
setTimeout(() => {
onSuccess();
}, 1000);
} catch (err) {
console.error('[GitHubAuth] OAuth failed:', err);
setAuthStatus('error');
const errorMessage = err instanceof Error ? err.message : 'OAuth authorization failed';
const fullError = err instanceof Error && err.stack ? `${errorMessage}\n\nDetails: ${err.stack}` : errorMessage;
setError(fullError);
}
};
const handleTokenAuth = async () => {
if (!githubToken.trim()) {
setError(locale === 'zh' ? '请输入 Token' : 'Please enter a token');
return;
}
try {
await githubService.authenticate(githubToken);
setError('');
onSuccess();
} catch (err) {
console.error('[GitHubAuth] Token auth failed:', err);
setError(locale === 'zh' ? '认证失败,请检查你的 Token' : 'Authentication failed. Please check your token.');
}
};
const copyToClipboard = async (text: string) => {
try {
await navigator.clipboard.writeText(text);
} catch (err) {
console.error('Failed to copy:', err);
}
};
const openCreateTokenPage = async () => {
await githubService.openAuthorizationPage();
};
return (
<div className="github-auth">
<Github size={48} style={{ color: '#0366d6' }} />
<p>{t('githubLogin')}</p>
<div className="auth-tabs">
<button
className={`auth-tab ${useOAuth ? 'active' : ''}`}
onClick={() => setUseOAuth(true)}
>
{t('oauthLogin')}
</button>
<button
className={`auth-tab ${!useOAuth ? 'active' : ''}`}
onClick={() => setUseOAuth(false)}
>
{t('tokenLogin')}
</button>
</div>
{useOAuth ? (
<div className="oauth-auth">
{authStatus === 'idle' && (
<>
<div className="oauth-instructions">
<p>{t('oauthStep1')}</p>
<p>{t('oauthStep2')}</p>
<p>{t('oauthStep3')}</p>
</div>
<button className="btn-primary" onClick={handleOAuthLogin}>
<Github size={16} />
{t('startAuth')}
</button>
</>
)}
{authStatus === 'pending' && (
<div className="oauth-pending">
<Loader size={48} className="spinning" style={{ color: '#0366d6' }} />
<h4>{t('authorizing')}</h4>
{userCode && (
<div className="user-code-display">
<label>{t('userCode')}</label>
<div className="code-box">
<span className="code-text">{userCode}</span>
<button
className="btn-copy"
onClick={() => copyToClipboard(userCode)}
title={t('copyCode')}
>
📋
</button>
</div>
<button
className="btn-link"
onClick={() => open(verificationUri)}
>
<ExternalLink size={14} />
{t('openBrowser')}
</button>
</div>
)}
</div>
)}
{authStatus === 'authorized' && (
<div className="oauth-success">
<CheckCircle size={48} style={{ color: '#34c759' }} />
<h4>{t('authorized')}</h4>
</div>
)}
{authStatus === 'error' && (
<div className="oauth-error">
<AlertCircle size={48} style={{ color: '#ff3b30' }} />
<h4>{t('authFailed')}</h4>
{error && (
<div className="error-details">
<pre>{error}</pre>
</div>
)}
<button className="btn-secondary" onClick={() => setAuthStatus('idle')}>
{t('back')}
</button>
</div>
)}
</div>
) : (
<div className="token-auth">
<div className="form-group">
<label>{t('tokenLabel')}</label>
<input
type="password"
value={githubToken}
onChange={(e) => setGithubToken(e.target.value)}
placeholder={t('tokenPlaceholder')}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleTokenAuth();
}
}}
/>
<small>{t('tokenHint')}</small>
</div>
<button className="btn-link" onClick={openCreateTokenPage}>
<ExternalLink size={14} />
{t('createToken')}
</button>
<button className="btn-primary" onClick={handleTokenAuth}>
{t('login')}
</button>
</div>
)}
{error && !useOAuth && (
<div className="error-message">
<AlertCircle size={16} />
{error}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,45 @@
import { X } from 'lucide-react';
import { GitHubService } from '../services/GitHubService';
import { GitHubAuth } from './GitHubAuth';
import '../styles/GitHubLoginDialog.css';
interface GitHubLoginDialogProps {
githubService: GitHubService;
onClose: () => void;
locale: string;
}
export function GitHubLoginDialog({ githubService, onClose, locale }: GitHubLoginDialogProps) {
const t = (key: string) => {
const translations: Record<string, Record<string, string>> = {
zh: {
title: 'GitHub 登录'
},
en: {
title: 'GitHub Login'
}
};
return translations[locale]?.[key] || translations.en?.[key] || key;
};
return (
<div className="github-login-overlay" onClick={onClose}>
<div className="github-login-dialog" onClick={(e) => e.stopPropagation()}>
<div className="github-login-header">
<h2>{t('title')}</h2>
<button className="github-login-close" onClick={onClose}>
<X size={20} />
</button>
</div>
<div className="github-login-content">
<GitHubAuth
githubService={githubService}
onSuccess={onClose}
locale={locale}
/>
</div>
</div>
</div>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -33,6 +33,7 @@ interface MenuBarProps {
onToggleDevtools?: () => void;
onOpenAbout?: () => void;
onCreatePlugin?: () => void;
onReloadPlugins?: () => void;
}
export function MenuBar({
@@ -53,7 +54,8 @@ export function MenuBar({
onOpenSettings,
onToggleDevtools,
onOpenAbout,
onCreatePlugin
onCreatePlugin,
onReloadPlugins
}: MenuBarProps) {
const [openMenu, setOpenMenu] = useState<string | null>(null);
const [pluginMenuItems, setPluginMenuItems] = useState<PluginMenuItem[]>([]);
@@ -147,6 +149,7 @@ export function MenuBar({
pluginManager: 'Plugin Manager',
tools: 'Tools',
createPlugin: 'Create Plugin',
reloadPlugins: 'Reload Plugins',
portManager: 'Port Manager',
settings: 'Settings',
help: 'Help',
@@ -181,6 +184,7 @@ export function MenuBar({
pluginManager: '插件管理器',
tools: '工具',
createPlugin: '创建插件',
reloadPlugins: '重新加载插件',
portManager: '端口管理器',
settings: '设置',
help: '帮助',
@@ -231,6 +235,7 @@ export function MenuBar({
],
tools: [
{ label: t('createPlugin'), onClick: onCreatePlugin },
{ label: t('reloadPlugins'), shortcut: 'Ctrl+R', onClick: onReloadPlugins },
{ separator: true },
{ label: t('portManager'), onClick: onOpenPortManager },
{ separator: true },

View File

@@ -1,15 +1,32 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useMemo } from 'react';
import { EditorPluginManager, IEditorPluginMetadata, EditorPluginCategory } from '@esengine/editor-core';
import * as LucideIcons from 'lucide-react';
import { Package, CheckCircle, XCircle, Search, Grid, List, ChevronDown, ChevronRight, X, RefreshCw } from 'lucide-react';
import {
Package,
CheckCircle,
XCircle,
Search,
Grid,
List,
ChevronDown,
ChevronRight,
X,
RefreshCw,
ShoppingCart
} from 'lucide-react';
import { PluginMarketPanel } from './PluginMarketPanel';
import { PluginMarketService } from '../services/PluginMarketService';
import { GitHubService } from '../services/GitHubService';
import '../styles/PluginManagerWindow.css';
interface PluginManagerWindowProps {
pluginManager: EditorPluginManager;
githubService: GitHubService;
onClose: () => void;
onRefresh?: () => Promise<void>;
onOpen?: () => void;
locale: string;
projectPath: string | null;
}
const categoryIcons: Record<EditorPluginCategory, string> = {
@@ -20,7 +37,7 @@ const categoryIcons: Record<EditorPluginCategory, string> = {
[EditorPluginCategory.ImportExport]: 'Package'
};
export function PluginManagerWindow({ pluginManager, onClose, onRefresh, onOpen, locale }: PluginManagerWindowProps) {
export function PluginManagerWindow({ pluginManager, githubService, onClose, onRefresh, onOpen, locale, projectPath }: PluginManagerWindowProps) {
const t = (key: string) => {
const translations: Record<string, Record<string, string>> = {
zh: {
@@ -43,7 +60,9 @@ export function PluginManagerWindow({ pluginManager, onClose, onRefresh, onOpen,
categoryWindows: '窗口',
categoryInspectors: '检查器',
categorySystem: '系统',
categoryImportExport: '导入/导出'
categoryImportExport: '导入/导出',
tabInstalled: '已安装',
tabMarketplace: '插件市场'
},
en: {
title: 'Plugin Manager',
@@ -65,7 +84,9 @@ export function PluginManagerWindow({ pluginManager, onClose, onRefresh, onOpen,
categoryWindows: 'Windows',
categoryInspectors: 'Inspectors',
categorySystem: 'System',
categoryImportExport: 'Import/Export'
categoryImportExport: 'Import/Export',
tabInstalled: 'Installed',
tabMarketplace: 'Marketplace'
}
};
return translations[locale]?.[key] || translations.en?.[key] || key;
@@ -81,6 +102,7 @@ export function PluginManagerWindow({ pluginManager, onClose, onRefresh, onOpen,
};
return t(categoryKeys[category]);
};
const [activeTab, setActiveTab] = useState<'installed' | 'marketplace'>('installed');
const [plugins, setPlugins] = useState<IEditorPluginMetadata[]>([]);
const [filter, setFilter] = useState('');
const [viewMode, setViewMode] = useState<'grid' | 'list'>('list');
@@ -89,6 +111,13 @@ export function PluginManagerWindow({ pluginManager, onClose, onRefresh, onOpen,
);
const [isRefreshing, setIsRefreshing] = useState(false);
const marketService = useMemo(() => new PluginMarketService(pluginManager), [pluginManager]);
// 设置项目路径到 marketService
useEffect(() => {
marketService.setProjectPath(projectPath);
}, [projectPath, marketService]);
const updatePluginList = () => {
const allPlugins = pluginManager.getAllPluginMetadata();
setPlugins(allPlugins);
@@ -154,13 +183,16 @@ export function PluginManagerWindow({ pluginManager, onClose, onRefresh, onOpen,
);
});
const pluginsByCategory = filteredPlugins.reduce((acc, plugin) => {
if (!acc[plugin.category]) {
acc[plugin.category] = [];
}
acc[plugin.category].push(plugin);
return acc;
}, {} as Record<EditorPluginCategory, IEditorPluginMetadata[]>);
const pluginsByCategory = filteredPlugins.reduce(
(acc, plugin) => {
if (!acc[plugin.category]) {
acc[plugin.category] = [];
}
acc[plugin.category].push(plugin);
return acc;
},
{} as Record<EditorPluginCategory, IEditorPluginMetadata[]>
);
const enabledCount = plugins.filter((p) => p.enabled).length;
const disabledCount = plugins.filter((p) => !p.enabled).length;
@@ -185,9 +217,7 @@ export function PluginManagerWindow({ pluginManager, onClose, onRefresh, onOpen,
{plugin.enabled ? <CheckCircle size={18} /> : <XCircle size={18} />}
</button>
</div>
{plugin.description && (
<div className="plugin-card-description">{plugin.description}</div>
)}
{plugin.description && <div className="plugin-card-description">{plugin.description}</div>}
<div className="plugin-card-footer">
<span className="plugin-card-category">
{(() => {
@@ -218,9 +248,7 @@ export function PluginManagerWindow({ pluginManager, onClose, onRefresh, onOpen,
{plugin.displayName}
<span className="plugin-list-version">v{plugin.version}</span>
</div>
{plugin.description && (
<div className="plugin-list-description">{plugin.description}</div>
)}
{plugin.description && <div className="plugin-list-description">{plugin.description}</div>}
</div>
<div className="plugin-list-status">
{plugin.enabled ? (
@@ -253,118 +281,157 @@ export function PluginManagerWindow({ pluginManager, onClose, onRefresh, onOpen,
</button>
</div>
<div className="plugin-toolbar">
<div className="plugin-toolbar-left">
<div className="plugin-search">
<Search size={14} />
<input
type="text"
placeholder={t('searchPlaceholder')}
value={filter}
onChange={(e) => setFilter(e.target.value)}
/>
</div>
</div>
<div className="plugin-toolbar-right">
<div className="plugin-stats">
<span className="stat-item enabled">
<CheckCircle size={14} />
{enabledCount} {t('enabled')}
</span>
<span className="stat-item disabled">
<XCircle size={14} />
{disabledCount} {t('disabled')}
</span>
</div>
{onRefresh && (
<button
className="plugin-refresh-btn"
onClick={handleRefresh}
disabled={isRefreshing}
title={t('refreshPluginList')}
style={{
padding: '6px 12px',
display: 'flex',
alignItems: 'center',
gap: '6px',
backgroundColor: '#0e639c',
border: 'none',
borderRadius: '4px',
color: '#fff',
cursor: isRefreshing ? 'not-allowed' : 'pointer',
fontSize: '12px',
opacity: isRefreshing ? 0.6 : 1
}}
>
<RefreshCw size={14} className={isRefreshing ? 'spinning' : ''} />
{t('refresh')}
</button>
)}
<div className="plugin-view-mode">
<button
className={viewMode === 'list' ? 'active' : ''}
onClick={() => setViewMode('list')}
title={t('listView')}
>
<List size={14} />
</button>
<button
className={viewMode === 'grid' ? 'active' : ''}
onClick={() => setViewMode('grid')}
title={t('gridView')}
>
<Grid size={14} />
</button>
</div>
</div>
<div className="plugin-manager-tabs">
<button
className={`plugin-manager-tab ${activeTab === 'installed' ? 'active' : ''}`}
onClick={() => setActiveTab('installed')}
>
<Package size={16} />
{t('tabInstalled')}
</button>
<button
className={`plugin-manager-tab ${activeTab === 'marketplace' ? 'active' : ''}`}
onClick={() => setActiveTab('marketplace')}
>
<ShoppingCart size={16} />
{t('tabMarketplace')}
</button>
</div>
<div className="plugin-content">
{plugins.length === 0 ? (
<div className="plugin-empty">
<Package size={48} />
<p>{t('noPlugins')}</p>
{activeTab === 'installed' && (
<>
<div className="plugin-toolbar">
<div className="plugin-toolbar-left">
<div className="plugin-search">
<Search size={14} />
<input
type="text"
placeholder={t('searchPlaceholder')}
value={filter}
onChange={(e) => setFilter(e.target.value)}
/>
</div>
</div>
<div className="plugin-toolbar-right">
<div className="plugin-stats">
<span className="stat-item enabled">
<CheckCircle size={14} />
{enabledCount} {t('enabled')}
</span>
<span className="stat-item disabled">
<XCircle size={14} />
{disabledCount} {t('disabled')}
</span>
</div>
{onRefresh && (
<button
className="plugin-refresh-btn"
onClick={handleRefresh}
disabled={isRefreshing}
title={t('refreshPluginList')}
style={{
padding: '6px 12px',
display: 'flex',
alignItems: 'center',
gap: '6px',
backgroundColor: '#0e639c',
border: 'none',
borderRadius: '4px',
color: '#fff',
cursor: isRefreshing ? 'not-allowed' : 'pointer',
fontSize: '12px',
opacity: isRefreshing ? 0.6 : 1
}}
>
<RefreshCw size={14} className={isRefreshing ? 'spinning' : ''} />
{t('refresh')}
</button>
)}
<div className="plugin-view-mode">
<button
className={viewMode === 'list' ? 'active' : ''}
onClick={() => setViewMode('list')}
title={t('listView')}
>
<List size={14} />
</button>
<button
className={viewMode === 'grid' ? 'active' : ''}
onClick={() => setViewMode('grid')}
title={t('gridView')}
>
<Grid size={14} />
</button>
</div>
</div>
</div>
) : (
<div className="plugin-categories">
{Object.entries(pluginsByCategory).map(([category, categoryPlugins]) => {
const cat = category as EditorPluginCategory;
const isExpanded = expandedCategories.has(cat);
return (
<div key={category} className="plugin-category">
<div
className="plugin-category-header"
onClick={() => toggleCategory(cat)}
>
<button className="plugin-category-toggle">
{isExpanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
</button>
<span className="plugin-category-icon">
{(() => {
const CategoryIcon = (LucideIcons as any)[categoryIcons[cat]];
return CategoryIcon ? <CategoryIcon size={16} /> : null;
})()}
</span>
<span className="plugin-category-name">{getCategoryName(cat)}</span>
<span className="plugin-category-count">
{categoryPlugins.length}
</span>
</div>
<div
className="plugin-content"
style={{ display: activeTab === 'installed' ? 'block' : 'none' }}
>
{plugins.length === 0 ? (
<div className="plugin-empty">
<Package size={48} />
<p>{t('noPlugins')}</p>
</div>
) : (
<div className="plugin-categories">
{Object.entries(pluginsByCategory).map(([category, categoryPlugins]) => {
const cat = category as EditorPluginCategory;
const isExpanded = expandedCategories.has(cat);
{isExpanded && (
<div className={`plugin-category-content ${viewMode}`}>
{viewMode === 'grid'
? categoryPlugins.map(renderPluginCard)
: categoryPlugins.map(renderPluginList)}
return (
<div key={category} className="plugin-category">
<div
className="plugin-category-header"
onClick={() => toggleCategory(cat)}
>
<button className="plugin-category-toggle">
{isExpanded ? (
<ChevronDown size={16} />
) : (
<ChevronRight size={16} />
)}
</button>
<span className="plugin-category-icon">
{(() => {
const CategoryIcon = (LucideIcons as any)[
categoryIcons[cat]
];
return CategoryIcon ? <CategoryIcon size={16} /> : null;
})()}
</span>
<span className="plugin-category-name">{getCategoryName(cat)}</span>
<span className="plugin-category-count">
{categoryPlugins.length}
</span>
</div>
{isExpanded && (
<div className={`plugin-category-content ${viewMode}`}>
{viewMode === 'grid'
? categoryPlugins.map(renderPluginCard)
: categoryPlugins.map(renderPluginList)}
</div>
)}
</div>
)}
</div>
);
})}
);
})}
</div>
)}
</div>
)}
</div>
</>
)}
{activeTab === 'marketplace' && (
<PluginMarketPanel
marketService={marketService}
locale={locale}
projectPath={projectPath}
onReloadPlugins={onRefresh}
/>
)}
</div>
</div>
);

View File

@@ -0,0 +1,440 @@
import { useState, useEffect } from 'react';
import * as LucideIcons from 'lucide-react';
import {
Package,
Search,
Download,
CheckCircle,
ExternalLink,
Github,
Star,
AlertCircle,
RefreshCw,
Filter
} from 'lucide-react';
import { open } from '@tauri-apps/plugin-shell';
import type { PluginMarketService, PluginMarketMetadata } from '../services/PluginMarketService';
import '../styles/PluginMarketPanel.css';
interface PluginMarketPanelProps {
marketService: PluginMarketService;
locale: string;
projectPath: string | null;
onReloadPlugins?: () => Promise<void>;
}
export function PluginMarketPanel({ marketService, locale, projectPath, onReloadPlugins }: PluginMarketPanelProps) {
const t = (key: string) => {
const translations: Record<string, Record<string, string>> = {
zh: {
title: '插件市场',
searchPlaceholder: '搜索插件...',
loading: '加载中...',
loadError: '无法连接到插件市场',
loadErrorDesc: '可能是网络连接问题,请检查您的网络设置后重试',
retry: '重试',
noPlugins: '没有找到插件',
install: '安装',
installed: '已安装',
update: '更新',
uninstall: '卸载',
viewSource: '查看源码',
official: '官方',
verified: '认证',
community: '社区',
filterAll: '全部',
filterOfficial: '官方插件',
filterCommunity: '社区插件',
categoryAll: '全部分类',
installing: '安装中...',
uninstalling: '卸载中...',
useDirectSource: '使用直连源',
useDirectSourceTip: '启用后直接从GitHub获取数据绕过CDN缓存适合测试',
latest: '最新',
releaseNotes: '更新日志',
selectVersion: '选择版本',
noProjectOpen: '请先打开一个项目'
},
en: {
title: 'Plugin Marketplace',
searchPlaceholder: 'Search plugins...',
loading: 'Loading...',
loadError: 'Unable to connect to plugin marketplace',
loadErrorDesc: 'This might be a network connection issue. Please check your network settings and try again',
retry: 'Retry',
noPlugins: 'No plugins found',
install: 'Install',
installed: 'Installed',
update: 'Update',
uninstall: 'Uninstall',
viewSource: 'View Source',
official: 'Official',
verified: 'Verified',
community: 'Community',
filterAll: 'All',
filterOfficial: 'Official',
filterCommunity: 'Community',
categoryAll: 'All Categories',
installing: 'Installing...',
uninstalling: 'Uninstalling...',
useDirectSource: 'Direct Source',
useDirectSourceTip: 'Fetch data directly from GitHub, bypassing CDN cache (for testing)',
latest: 'Latest',
releaseNotes: 'Release Notes',
selectVersion: 'Select Version',
noProjectOpen: 'Please open a project first'
}
};
return translations[locale]?.[key] || translations.en?.[key] || key;
};
const [plugins, setPlugins] = useState<PluginMarketMetadata[]>([]);
const [filteredPlugins, setFilteredPlugins] = useState<PluginMarketMetadata[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [searchQuery, setSearchQuery] = useState('');
const [typeFilter, setTypeFilter] = useState<'all' | 'official' | 'community'>('all');
const [categoryFilter, setCategoryFilter] = useState<string>('all');
const [installingPlugins, setInstallingPlugins] = useState<Set<string>>(new Set());
const [useDirectSource, setUseDirectSource] = useState(marketService.isUsingDirectSource());
useEffect(() => {
loadPlugins();
}, []);
useEffect(() => {
filterPlugins();
}, [plugins, searchQuery, typeFilter, categoryFilter]);
const loadPlugins = async (bypassCache: boolean = false) => {
setLoading(true);
setError(null);
try {
const pluginList = await marketService.fetchPluginList(bypassCache);
setPlugins(pluginList);
} catch (err) {
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
setLoading(false);
}
};
const filterPlugins = () => {
let filtered = plugins;
if (searchQuery) {
const query = searchQuery.toLowerCase();
filtered = filtered.filter(
(p) =>
p.name.toLowerCase().includes(query) ||
p.description.toLowerCase().includes(query) ||
p.tags?.some((tag) => tag.toLowerCase().includes(query))
);
}
if (typeFilter !== 'all') {
filtered = filtered.filter((p) => p.category_type === typeFilter);
}
if (categoryFilter !== 'all') {
filtered = filtered.filter((p) => p.category === categoryFilter);
}
setFilteredPlugins(filtered);
};
const handleToggleDirectSource = () => {
const newValue = !useDirectSource;
setUseDirectSource(newValue);
marketService.setUseDirectSource(newValue);
loadPlugins(true);
};
const handleInstall = async (plugin: PluginMarketMetadata, version?: string) => {
if (!projectPath) {
alert(t('noProjectOpen') || 'Please open a project first');
return;
}
setInstallingPlugins((prev) => new Set(prev).add(plugin.id));
try {
await marketService.installPlugin(plugin, version, onReloadPlugins);
setPlugins([...plugins]);
} catch (error) {
console.error('Failed to install plugin:', error);
alert(`Failed to install ${plugin.name}: ${error}`);
} finally {
setInstallingPlugins((prev) => {
const next = new Set(prev);
next.delete(plugin.id);
return next;
});
}
};
const handleUninstall = async (plugin: PluginMarketMetadata) => {
if (!confirm(`Are you sure you want to uninstall ${plugin.name}?`)) {
return;
}
setInstallingPlugins((prev) => new Set(prev).add(plugin.id));
try {
await marketService.uninstallPlugin(plugin.id, onReloadPlugins);
setPlugins([...plugins]);
} catch (error) {
console.error('Failed to uninstall plugin:', error);
alert(`Failed to uninstall ${plugin.name}: ${error}`);
} finally {
setInstallingPlugins((prev) => {
const next = new Set(prev);
next.delete(plugin.id);
return next;
});
}
};
const categories = ['all', ...Array.from(new Set(plugins.map((p) => p.category)))];
if (loading) {
return (
<div className="plugin-market-loading">
<RefreshCw size={32} className="spinning" />
<p>{t('loading')}</p>
</div>
);
}
if (error) {
return (
<div className="plugin-market-error">
<AlertCircle size={64} className="error-icon" />
<h3>{t('loadError')}</h3>
<p className="error-description">{t('loadErrorDesc')}</p>
<div className="error-details">
<p className="error-message">{error}</p>
</div>
<button className="retry-button" onClick={() => loadPlugins(true)}>
<RefreshCw size={16} />
{t('retry')}
</button>
</div>
);
}
return (
<div className="plugin-market-panel">
<div className="plugin-market-toolbar">
<div className="plugin-market-search">
<Search size={16} />
<input
type="text"
placeholder={t('searchPlaceholder')}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
<div className="plugin-market-filters">
<select
value={typeFilter}
onChange={(e) => setTypeFilter(e.target.value as any)}
className="plugin-market-filter-select"
>
<option value="all">{t('filterAll')}</option>
<option value="official">{t('filterOfficial')}</option>
<option value="community">{t('filterCommunity')}</option>
</select>
<select
value={categoryFilter}
onChange={(e) => setCategoryFilter(e.target.value)}
className="plugin-market-filter-select"
>
<option value="all">{t('categoryAll')}</option>
{categories
.filter((c) => c !== 'all')
.map((category) => (
<option key={category} value={category}>
{category}
</option>
))}
</select>
<label className="plugin-market-direct-source-toggle" title={t('useDirectSourceTip')}>
<input
type="checkbox"
checked={useDirectSource}
onChange={handleToggleDirectSource}
/>
<span className="toggle-label">{t('useDirectSource')}</span>
</label>
<button className="plugin-market-refresh" onClick={() => loadPlugins(true)} title={t('retry')}>
<RefreshCw size={16} />
</button>
</div>
</div>
<div className="plugin-market-content">
{filteredPlugins.length === 0 ? (
<div className="plugin-market-empty">
<Package size={48} />
<p>{t('noPlugins')}</p>
</div>
) : (
<div className="plugin-market-grid">
{filteredPlugins.map((plugin) => (
<PluginMarketCard
key={plugin.id}
plugin={plugin}
isInstalled={marketService.isInstalled(plugin.id)}
hasUpdate={marketService.hasUpdate(plugin)}
isInstalling={installingPlugins.has(plugin.id)}
onInstall={(version) => handleInstall(plugin, version)}
onUninstall={() => handleUninstall(plugin)}
t={t}
/>
))}
</div>
)}
</div>
</div>
);
}
interface PluginMarketCardProps {
plugin: PluginMarketMetadata;
isInstalled: boolean;
hasUpdate: boolean;
isInstalling: boolean;
onInstall: (version?: string) => void;
onUninstall: () => void;
t: (key: string) => string;
}
function PluginMarketCard({
plugin,
isInstalled,
hasUpdate,
isInstalling,
onInstall,
onUninstall,
t
}: PluginMarketCardProps) {
const [selectedVersion, setSelectedVersion] = useState(plugin.latestVersion);
const [showVersions, setShowVersions] = useState(false);
const IconComponent = plugin.icon ? (LucideIcons as any)[plugin.icon] : Package;
const selectedVersionData = plugin.versions.find((v) => v.version === selectedVersion);
const multipleVersions = plugin.versions.length > 1;
return (
<div className="plugin-market-card">
<div className="plugin-market-card-header">
<div className="plugin-market-card-icon">
<IconComponent size={32} />
</div>
<div className="plugin-market-card-info">
<div className="plugin-market-card-title">
<span>{plugin.name}</span>
{plugin.verified && (
<span className="plugin-market-badge official" title={t('official')}>
<CheckCircle size={14} />
</span>
)}
</div>
<div className="plugin-market-card-meta">
<span className="plugin-market-card-author">
<Github size={12} />
{plugin.author.name}
</span>
{multipleVersions ? (
<select
className="plugin-market-version-select"
value={selectedVersion}
onChange={(e) => setSelectedVersion(e.target.value)}
onClick={(e) => e.stopPropagation()}
title={t('selectVersion')}
>
{plugin.versions.map((v) => (
<option key={v.version} value={v.version}>
v{v.version} {v.version === plugin.latestVersion ? `(${t('latest')})` : ''}
</option>
))}
</select>
) : (
<span className="plugin-market-card-version">v{plugin.latestVersion}</span>
)}
</div>
</div>
</div>
<div className="plugin-market-card-description">{plugin.description}</div>
{selectedVersionData && selectedVersionData.changes && (
<details className="plugin-market-version-changes">
<summary>{t('releaseNotes')}</summary>
<p>{selectedVersionData.changes}</p>
</details>
)}
{plugin.tags && plugin.tags.length > 0 && (
<div className="plugin-market-card-tags">
{plugin.tags.slice(0, 3).map((tag) => (
<span key={tag} className="plugin-market-tag">
{tag}
</span>
))}
</div>
)}
<div className="plugin-market-card-footer">
<button
className="plugin-market-card-link"
onClick={async (e) => {
e.stopPropagation();
try {
await open(plugin.repository.url);
} catch (error) {
console.error('Failed to open URL:', error);
}
}}
>
<ExternalLink size={14} />
{t('viewSource')}
</button>
<div className="plugin-market-card-actions">
{isInstalling ? (
<button className="plugin-market-btn installing" disabled>
<RefreshCw size={14} className="spinning" />
{isInstalled ? t('uninstalling') : t('installing')}
</button>
) : isInstalled ? (
<>
{hasUpdate && (
<button className="plugin-market-btn update" onClick={() => onInstall(plugin.latestVersion)}>
<Download size={14} />
{t('update')}
</button>
)}
<button className="plugin-market-btn installed" onClick={onUninstall}>
<CheckCircle size={14} />
{t('uninstall')}
</button>
</>
) : (
<button className="plugin-market-btn install" onClick={() => onInstall(selectedVersion)}>
<Download size={14} />
{t('install')}
</button>
)}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,948 @@
import { useState } from 'react';
import { X, AlertCircle, CheckCircle, Loader, ExternalLink, FolderOpen, FileArchive } from 'lucide-react';
import { open as openDialog } from '@tauri-apps/plugin-dialog';
import { GitHubService } from '../services/GitHubService';
import { GitHubAuth } from './GitHubAuth';
import { PluginPublishService, type PluginPublishInfo, type PublishProgress } from '../services/PluginPublishService';
import { PluginBuildService, type BuildProgress } from '../services/PluginBuildService';
import { PluginSourceParser, type ParsedPluginInfo } from '../services/PluginSourceParser';
import { open } from '@tauri-apps/plugin-shell';
import { EditorPluginCategory, type IEditorPluginMetadata } from '@esengine/editor-core';
import '../styles/PluginPublishWizard.css';
interface PluginPublishWizardProps {
githubService: GitHubService;
onClose: () => void;
locale: string;
inline?: boolean; // 是否内联显示(在 tab 中)而不是弹窗
}
type Step = 'auth' | 'selectSource' | 'info' | 'building' | 'confirm' | 'publishing' | 'success' | 'error';
type SourceType = 'folder' | 'zip';
function calculateNextVersion(currentVersion: string): string {
const parts = currentVersion.split('.').map(Number);
if (parts.length !== 3 || parts.some(isNaN)) return currentVersion;
const [major, minor, patch] = parts;
return `${major}.${minor}.${(patch ?? 0) + 1}`;
}
export function PluginPublishWizard({ githubService, onClose, locale, inline = false }: PluginPublishWizardProps) {
const [publishService] = useState(() => new PluginPublishService(githubService));
const [buildService] = useState(() => new PluginBuildService());
const [sourceParser] = useState(() => new PluginSourceParser());
const [step, setStep] = useState<Step>(githubService.isAuthenticated() ? 'selectSource' : 'auth');
const [sourceType, setSourceType] = useState<SourceType | null>(null);
const [parsedPluginInfo, setParsedPluginInfo] = useState<ParsedPluginInfo | null>(null);
const [publishInfo, setPublishInfo] = useState<Partial<PluginPublishInfo>>({
category: 'community',
tags: []
});
const [prUrl, setPrUrl] = useState('');
const [error, setError] = useState('');
const [buildLog, setBuildLog] = useState<string[]>([]);
const [buildProgress, setBuildProgress] = useState<BuildProgress | null>(null);
const [publishProgress, setPublishProgress] = useState<PublishProgress | null>(null);
const [builtZipPath, setBuiltZipPath] = useState<string>('');
const [existingPR, setExistingPR] = useState<{ number: number; url: string } | null>(null);
const [existingVersions, setExistingVersions] = useState<string[]>([]);
const [suggestedVersion, setSuggestedVersion] = useState<string>('');
const [existingManifest, setExistingManifest] = useState<any>(null);
const [isUpdate, setIsUpdate] = useState(false);
const t = (key: string) => {
const translations: Record<string, Record<string, string>> = {
zh: {
title: '发布插件到市场',
updateTitle: '更新插件版本',
stepAuth: '步骤 1: GitHub 登录',
stepSelectSource: '步骤 2: 选择插件源',
stepInfo: '步骤 3: 插件信息',
stepInfoUpdate: '步骤 3: 版本更新',
stepBuilding: '步骤 4: 构建打包',
stepConfirm: '步骤 5: 确认发布',
stepConfirmNoBuilding: '步骤 4: 确认发布',
githubLogin: 'GitHub 登录',
oauthLogin: 'OAuth 登录(推荐)',
tokenLogin: 'Token 登录',
oauthInstructions: '点击下方按钮开始授权:',
oauthStep1: '1. 点击"开始授权"按钮',
oauthStep2: '2. 在浏览器中打开 GitHub 授权页面',
oauthStep3: '3. 输入下方显示的代码并授权',
oauthStep4: '4. 授权完成后会自动跳转',
startAuth: '开始授权',
authorizing: '等待授权中...',
authorized: '授权成功!',
authFailed: '授权失败',
userCode: '授权码',
copyCode: '复制代码',
openBrowser: '打开浏览器',
tokenLabel: 'GitHub Personal Access Token',
tokenPlaceholder: '粘贴你的 GitHub Token',
tokenHint: '需要 repo 和 workflow 权限',
createToken: '创建 Token',
login: '登录',
switchToToken: '使用 Token 登录',
switchToOAuth: '使用 OAuth 登录',
selectSource: '选择插件源',
selectSourceDesc: '选择插件的来源类型',
selectFolder: '选择源代码文件夹',
selectFolderDesc: '选择包含你的插件源代码的文件夹(需要有 package.json系统将自动构建',
selectZip: '选择 ZIP 文件',
selectZipDesc: '选择已构建好的插件 ZIP 包(必须包含 package.json 和 dist 目录)',
zipRequirements: 'ZIP 文件要求',
zipStructure: 'ZIP 结构',
zipStructureDetails: 'ZIP 文件必须包含以下内容:',
zipFile1: 'package.json - 插件元数据',
zipFile2: 'dist/ - 构建后的代码目录(包含 index.esm.js',
zipExample: '示例结构',
zipBuildScript: '打包脚本',
zipBuildScriptDesc: '可以使用以下命令打包:',
recommendFolder: '💡 建议使用"源代码文件夹"方式,系统会自动构建',
browseFolder: '浏览文件夹',
browseZip: '浏览 ZIP 文件',
selectedFolder: '已选择文件夹',
selectedZip: '已选择 ZIP',
sourceTypeFolder: '源代码文件夹',
sourceTypeZip: 'ZIP 文件',
pluginInfo: '插件信息',
version: '版本号',
currentVersion: '当前版本',
suggestedVersion: '建议版本',
versionHistory: '版本历史',
updatePlugin: '更新插件',
newPlugin: '新插件',
category: '分类',
official: '官方',
community: '社区',
repositoryUrl: '仓库地址',
repositoryPlaceholder: 'https://github.com/username/repo',
releaseNotes: '更新说明',
releaseNotesPlaceholder: '描述这个版本的变更...',
tags: '标签(逗号分隔)',
tagsPlaceholder: 'ui, tool, editor',
homepage: '主页 URL可选',
next: '下一步',
back: '上一步',
build: '构建并打包',
building: '构建中...',
confirm: '确认发布',
publishing: '发布中...',
publishSuccess: '发布成功!',
publishError: '发布失败',
buildError: '构建失败',
prCreated: 'Pull Request 已创建',
viewPR: '查看 PR',
close: '关闭',
buildingStep1: '正在安装依赖...',
buildingStep2: '正在构建项目...',
buildingStep3: '正在打包 ZIP...',
publishingStep1: '正在 Fork 仓库...',
publishingStep2: '正在创建分支...',
publishingStep3: '正在上传文件...',
publishingStep4: '正在创建 Pull Request...',
confirmMessage: '确认要发布以下插件?',
reviewMessage: '你的插件提交已创建 PR维护者将进行审核。审核通过后插件将自动发布到市场。',
existingPRDetected: '检测到现有 PR',
existingPRMessage: '该插件已有待审核的 PR #{{number}}。点击"确认"将更新现有 PR不会创建新的 PR。',
viewExistingPR: '查看现有 PR'
},
en: {
title: 'Publish Plugin to Marketplace',
updateTitle: 'Update Plugin Version',
stepAuth: 'Step 1: GitHub Authentication',
stepSelectSource: 'Step 2: Select Plugin Source',
stepInfo: 'Step 3: Plugin Information',
stepInfoUpdate: 'Step 3: Version Update',
stepBuilding: 'Step 4: Build & Package',
stepConfirm: 'Step 5: Confirm Publication',
stepConfirmNoBuilding: 'Step 4: Confirm Publication',
githubLogin: 'GitHub Login',
oauthLogin: 'OAuth Login (Recommended)',
tokenLogin: 'Token Login',
oauthInstructions: 'Click the button below to start authorization:',
oauthStep1: '1. Click "Start Authorization"',
oauthStep2: '2. Open GitHub authorization page in browser',
oauthStep3: '3. Enter the code shown below and authorize',
oauthStep4: '4. Authorization will complete automatically',
startAuth: 'Start Authorization',
authorizing: 'Waiting for authorization...',
authorized: 'Authorized!',
authFailed: 'Authorization failed',
userCode: 'Authorization Code',
copyCode: 'Copy Code',
openBrowser: 'Open Browser',
tokenLabel: 'GitHub Personal Access Token',
tokenPlaceholder: 'Paste your GitHub Token',
tokenHint: 'Requires repo and workflow permissions',
createToken: 'Create Token',
login: 'Login',
switchToToken: 'Use Token Login',
switchToOAuth: 'Use OAuth Login',
selectSource: 'Select Plugin Source',
selectSourceDesc: 'Choose the plugin source type',
selectFolder: 'Select Source Folder',
selectFolderDesc: 'Select the folder containing your plugin source code (must have package.json, will be built automatically)',
selectZip: 'Select ZIP File',
selectZipDesc: 'Select a pre-built plugin ZIP package (must contain package.json and dist directory)',
zipRequirements: 'ZIP File Requirements',
zipStructure: 'ZIP Structure',
zipStructureDetails: 'The ZIP file must contain:',
zipFile1: 'package.json - Plugin metadata',
zipFile2: 'dist/ - Built code directory (with index.esm.js)',
zipExample: 'Example Structure',
zipBuildScript: 'Build Script',
zipBuildScriptDesc: 'You can use the following commands to package:',
recommendFolder: '💡 Recommended: Use "Source Folder" mode for automatic build',
browseFolder: 'Browse Folder',
browseZip: 'Browse ZIP File',
selectedFolder: 'Selected Folder',
selectedZip: 'Selected ZIP',
sourceTypeFolder: 'Source Folder',
sourceTypeZip: 'ZIP File',
pluginInfo: 'Plugin Information',
version: 'Version',
currentVersion: 'Current Version',
suggestedVersion: 'Suggested Version',
versionHistory: 'Version History',
updatePlugin: 'Update Plugin',
newPlugin: 'New Plugin',
category: 'Category',
official: 'Official',
community: 'Community',
repositoryUrl: 'Repository URL',
repositoryPlaceholder: 'https://github.com/username/repo',
releaseNotes: 'Release Notes',
releaseNotesPlaceholder: 'Describe the changes in this version...',
tags: 'Tags (comma separated)',
tagsPlaceholder: 'ui, tool, editor',
homepage: 'Homepage URL (optional)',
next: 'Next',
back: 'Back',
build: 'Build & Package',
building: 'Building...',
confirm: 'Confirm & Publish',
publishing: 'Publishing...',
publishSuccess: 'Published Successfully!',
publishError: 'Publication Failed',
buildError: 'Build Failed',
prCreated: 'Pull Request Created',
viewPR: 'View PR',
close: 'Close',
buildingStep1: 'Installing dependencies...',
buildingStep2: 'Building project...',
buildingStep3: 'Packaging ZIP...',
publishingStep1: 'Forking repository...',
publishingStep2: 'Creating branch...',
publishingStep3: 'Uploading files...',
publishingStep4: 'Creating Pull Request...',
confirmMessage: 'Confirm publishing this plugin?',
reviewMessage:
'Your plugin submission has been created as a PR. Maintainers will review it. Once approved, the plugin will be published to the marketplace.',
existingPRDetected: 'Existing PR Detected',
existingPRMessage: 'This plugin already has a pending PR #{{number}}. Clicking "Confirm" will update the existing PR (no new PR will be created).',
viewExistingPR: 'View Existing PR'
}
};
return translations[locale]?.[key] || translations.en?.[key] || key;
};
const handleAuthSuccess = () => {
setStep('selectSource');
};
/**
* 选择并解析插件源(文件夹或 ZIP
* 统一处理逻辑,避免代码重复
*/
const handleSelectSource = async (type: SourceType) => {
setError('');
setSourceType(type);
try {
let parsedInfo: ParsedPluginInfo;
if (type === 'folder') {
// 选择文件夹
const selected = await openDialog({
directory: true,
multiple: false,
title: t('selectFolder')
});
if (!selected) return;
// 使用 PluginSourceParser 解析文件夹
parsedInfo = await sourceParser.parseFromFolder(selected as string);
} else {
// 选择 ZIP 文件
const selected = await openDialog({
directory: false,
multiple: false,
title: t('selectZip'),
filters: [
{
name: 'ZIP Files',
extensions: ['zip']
}
]
});
if (!selected) return;
// 使用 PluginSourceParser 解析 ZIP
parsedInfo = await sourceParser.parseFromZip(selected as string);
}
// 验证 package.json
sourceParser.validatePackageJson(parsedInfo.packageJson);
setParsedPluginInfo(parsedInfo);
// 检测已发布的版本
await checkExistingVersions(parsedInfo.packageJson);
// 检测是否已有待审核的 PR
await checkExistingPR(parsedInfo.packageJson);
// 进入下一步
setStep('info');
} catch (err) {
console.error('[PluginPublishWizard] Failed to parse plugin source:', err);
setError(err instanceof Error ? err.message : 'Failed to parse plugin source');
}
};
/**
* 检测插件是否已发布,获取版本信息
*/
const checkExistingVersions = async (packageJson: { name: string; version: string }) => {
try {
const pluginId = sourceParser.generatePluginId(packageJson.name);
const manifestContent = await githubService.getFileContent(
'esengine',
'ecs-editor-plugins',
`plugins/community/${pluginId}/manifest.json`,
'main'
);
const manifest = JSON.parse(manifestContent);
if (Array.isArray(manifest.versions)) {
const versions = manifest.versions.map((v: any) => v.version);
setExistingVersions(versions);
setExistingManifest(manifest);
setIsUpdate(true);
// 计算建议版本号
const latestVersion = manifest.latestVersion || versions[0];
const suggested = calculateNextVersion(latestVersion);
setSuggestedVersion(suggested);
// 更新模式:自动填充现有信息
setPublishInfo((prev) => ({
...prev,
version: suggested,
repositoryUrl: manifest.repository?.url || '',
category: manifest.category_type || 'community',
tags: manifest.tags || [],
homepage: manifest.homepage
}));
} else {
// 首次发布
resetToNewPlugin(packageJson.version);
}
} catch (err) {
console.log('[PluginPublishWizard] No existing versions found, this is a new plugin');
resetToNewPlugin(packageJson.version);
}
};
/**
* 重置为新插件状态
*/
const resetToNewPlugin = (version: string) => {
setExistingVersions([]);
setExistingManifest(null);
setIsUpdate(false);
setPublishInfo((prev) => ({
...prev,
version
}));
};
/**
* 检测是否已有待审核的 PR
*/
const checkExistingPR = async (packageJson: { name: string; version: string }) => {
try {
const user = githubService.getUser();
if (user) {
const branchName = `add-plugin-${packageJson.name}-v${packageJson.version}`;
const headBranch = `${user.login}:${branchName}`;
const pr = await githubService.findPullRequestByBranch('esengine', 'ecs-editor-plugins', headBranch);
if (pr) {
setExistingPR({ number: pr.number, url: pr.html_url });
} else {
setExistingPR(null);
}
}
} catch (err) {
console.log('[PluginPublishWizard] Failed to check existing PR:', err);
setExistingPR(null);
}
};
/**
* 从信息填写步骤进入下一步
* - 如果是 ZIP直接跳到确认发布
* - 如果是文件夹,需要先构建
*/
const handleNext = () => {
if (!publishInfo.version || !publishInfo.repositoryUrl || !publishInfo.releaseNotes) {
setError('Please fill in all required fields');
return;
}
if (!parsedPluginInfo) {
setError('Plugin source not selected');
return;
}
// ZIP 文件已经构建好,直接跳到确认步骤
if (parsedPluginInfo.sourceType === 'zip' && parsedPluginInfo.zipPath) {
setBuiltZipPath(parsedPluginInfo.zipPath);
setStep('confirm');
} else {
// 文件夹需要构建
setStep('building');
handleBuild();
}
};
/**
* 构建插件(仅对文件夹源有效)
*/
const handleBuild = async () => {
if (!parsedPluginInfo || parsedPluginInfo.sourceType !== 'folder') {
setError('Cannot build: plugin source is not a folder');
setStep('error');
return;
}
setBuildLog([]);
setBuildProgress(null);
setError('');
buildService.setProgressCallback((progress) => {
console.log('[PluginPublishWizard] Build progress:', progress);
setBuildProgress(progress);
if (progress.step === 'install') {
setBuildLog((prev) => {
if (prev[prev.length - 1] !== t('buildingStep1')) {
return [...prev, t('buildingStep1')];
}
return prev;
});
} else if (progress.step === 'build') {
setBuildLog((prev) => {
if (prev[prev.length - 1] !== t('buildingStep2')) {
return [...prev, t('buildingStep2')];
}
return prev;
});
} else if (progress.step === 'package') {
setBuildLog((prev) => {
if (prev[prev.length - 1] !== t('buildingStep3')) {
return [...prev, t('buildingStep3')];
}
return prev;
});
} else if (progress.step === 'complete') {
setBuildLog((prev) => [...prev, t('buildComplete')]);
}
if (progress.output) {
console.log('[Build output]', progress.output);
}
});
try {
const zipPath = await buildService.buildPlugin(parsedPluginInfo.sourcePath);
console.log('[PluginPublishWizard] Build completed, ZIP at:', zipPath);
setBuiltZipPath(zipPath);
setStep('confirm');
} catch (err) {
console.error('[PluginPublishWizard] Build failed:', err);
setError(err instanceof Error ? err.message : 'Unknown error');
setStep('error');
}
};
/**
* 发布插件到市场
*/
const handlePublish = async () => {
setStep('publishing');
setError('');
setPublishProgress(null);
// 设置进度回调
publishService.setProgressCallback((progress) => {
setPublishProgress(progress);
});
try {
// 验证必填字段
if (!publishInfo.version || !publishInfo.repositoryUrl || !publishInfo.releaseNotes) {
throw new Error('Missing required fields');
}
// 验证插件源
if (!parsedPluginInfo) {
throw new Error('Plugin source not selected');
}
// 验证 ZIP 路径
if (!builtZipPath) {
throw new Error('Plugin ZIP file not available');
}
const { packageJson } = parsedPluginInfo;
const pluginMetadata: IEditorPluginMetadata = {
name: packageJson.name,
displayName: packageJson.description || packageJson.name,
description: packageJson.description || '',
version: packageJson.version,
category: EditorPluginCategory.Tool,
icon: 'Package',
enabled: true,
installedAt: Date.now()
};
const fullPublishInfo: PluginPublishInfo = {
pluginMetadata,
version: publishInfo.version || packageJson.version,
releaseNotes: publishInfo.releaseNotes || '',
repositoryUrl: publishInfo.repositoryUrl || '',
category: publishInfo.category || 'community',
tags: publishInfo.tags,
homepage: publishInfo.homepage,
screenshots: publishInfo.screenshots
};
console.log('[PluginPublishWizard] Publishing with info:', fullPublishInfo);
console.log('[PluginPublishWizard] Built ZIP path:', builtZipPath);
const prUrl = await publishService.publishPlugin(fullPublishInfo, builtZipPath);
setPrUrl(prUrl);
setStep('success');
} catch (err) {
console.error('[PluginPublishWizard] Publish failed:', err);
setError(err instanceof Error ? err.message : 'Unknown error');
setStep('error');
}
};
const openPR = async () => {
if (prUrl) {
await open(prUrl);
}
};
const wizardContent = (
<div className={inline ? "plugin-publish-wizard inline" : "plugin-publish-wizard"} onClick={(e) => inline ? undefined : e.stopPropagation()}>
<div className="plugin-publish-header">
<h2>{t('title')}</h2>
{!inline && (
<button className="plugin-publish-close" onClick={onClose}>
<X size={20} />
</button>
)}
</div>
<div className="plugin-publish-content">
{step === 'auth' && (
<div className="publish-step">
<h3>{t('stepAuth')}</h3>
<GitHubAuth
githubService={githubService}
onSuccess={handleAuthSuccess}
locale={locale}
/>
</div>
)}
{step === 'selectSource' && (
<div className="publish-step">
<h3>{t('stepSelectSource')}</h3>
<p>{t('selectSourceDesc')}</p>
<div className="source-type-selection">
<button
className={`source-type-btn ${sourceType === 'folder' ? 'active' : ''}`}
onClick={() => handleSelectSource('folder')}
>
<FolderOpen size={24} />
<div className="source-type-info">
<strong>{t('sourceTypeFolder')}</strong>
<p>{t('selectFolderDesc')}</p>
</div>
</button>
<button
className={`source-type-btn ${sourceType === 'zip' ? 'active' : ''}`}
onClick={() => handleSelectSource('zip')}
>
<FileArchive size={24} />
<div className="source-type-info">
<strong>{t('sourceTypeZip')}</strong>
<p>{t('selectZipDesc')}</p>
</div>
</button>
</div>
{/* ZIP 文件要求说明 */}
<details className="zip-requirements-details">
<summary>
<AlertCircle size={16} />
{t('zipRequirements')}
</summary>
<div className="zip-requirements-content">
<div className="requirement-section">
<h4>{t('zipStructure')}</h4>
<p>{t('zipStructureDetails')}</p>
<ul>
<li><code>package.json</code> - {t('zipFile1')}</li>
<li><code>dist/</code> - {t('zipFile2')}</li>
</ul>
</div>
<div className="requirement-section">
<h4>{t('zipBuildScript')}</h4>
<p>{t('zipBuildScriptDesc')}</p>
<pre className="build-script-example">
{`npm install
npm run build
# 然后将 package.json 和 dist/ 目录一起压缩为 ZIP
# ZIP 结构:
# plugin.zip
# ├── package.json
# └── dist/
# └── index.esm.js`}
</pre>
</div>
<div className="recommendation-notice">
{t('recommendFolder')}
</div>
</div>
</details>
{parsedPluginInfo && (
<div className="selected-source">
{parsedPluginInfo.sourceType === 'folder' ? (
<FolderOpen size={20} />
) : (
<FileArchive size={20} />
)}
<div className="source-details">
<span className="source-path">{parsedPluginInfo.sourcePath}</span>
<span className="source-name">{parsedPluginInfo.packageJson.name} v{parsedPluginInfo.packageJson.version}</span>
</div>
</div>
)}
{error && (
<div className="error-message">
<AlertCircle size={16} />
{error}
</div>
)}
{parsedPluginInfo && (
<div className="button-group">
<button className="btn-secondary" onClick={() => setStep('auth')}>
{t('back')}
</button>
</div>
)}
</div>
)}
{step === 'info' && (
<div className="publish-step">
<h3>{t('stepInfo')}</h3>
{existingPR && (
<div className="existing-pr-notice">
<AlertCircle size={20} />
<div className="notice-content">
<strong>{t('existingPRDetected')}</strong>
<p>{t('existingPRMessage').replace('{{number}}', String(existingPR.number))}</p>
<button
className="btn-link"
onClick={() => open(existingPR.url)}
>
<ExternalLink size={16} />
{t('viewExistingPR')}
</button>
</div>
</div>
)}
<div className="form-group">
<label>{t('version')} *</label>
{isUpdate && (
<div className="version-info">
<div className="version-notice">
<CheckCircle size={16} />
<span>{t('updatePlugin')}: {existingManifest?.name} v{existingVersions[0]}</span>
</div>
{suggestedVersion && (
<button
type="button"
className="btn-version-suggest"
onClick={() => setPublishInfo({ ...publishInfo, version: suggestedVersion })}
>
{t('suggestedVersion')}: {suggestedVersion}
</button>
)}
</div>
)}
<input
type="text"
value={publishInfo.version || ''}
onChange={(e) => setPublishInfo({ ...publishInfo, version: e.target.value })}
placeholder="1.0.0"
/>
{isUpdate && (
<details className="version-history">
<summary>{t('versionHistory')} ({existingVersions.length})</summary>
<ul>
{existingVersions.map((v) => (
<li key={v}>v{v}</li>
))}
</ul>
</details>
)}
</div>
<div className="form-group">
<label>{t('releaseNotes')} *</label>
<textarea
rows={4}
value={publishInfo.releaseNotes || ''}
onChange={(e) => setPublishInfo({ ...publishInfo, releaseNotes: e.target.value })}
placeholder={t('releaseNotesPlaceholder')}
/>
</div>
{!isUpdate && (
<>
<div className="form-group">
<label>{t('category')} *</label>
<select
value={publishInfo.category}
onChange={(e) =>
setPublishInfo({ ...publishInfo, category: e.target.value as 'official' | 'community' })
}
>
<option value="community">{t('community')}</option>
<option value="official">{t('official')}</option>
</select>
</div>
<div className="form-group">
<label>{t('repositoryUrl')} *</label>
<input
type="text"
value={publishInfo.repositoryUrl || ''}
onChange={(e) => setPublishInfo({ ...publishInfo, repositoryUrl: e.target.value })}
placeholder={t('repositoryPlaceholder')}
/>
</div>
<div className="form-group">
<label>{t('tags')}</label>
<input
type="text"
value={publishInfo.tags?.join(', ') || ''}
onChange={(e) =>
setPublishInfo({
...publishInfo,
tags: e.target.value
.split(',')
.map((t) => t.trim())
.filter(Boolean)
})
}
placeholder={t('tagsPlaceholder')}
/>
</div>
</>
)}
{error && (
<div className="error-message">
<AlertCircle size={16} />
{error}
</div>
)}
<div className="button-group">
<button className="btn-secondary" onClick={() => setStep('selectSource')}>
{t('back')}
</button>
<button className="btn-primary" onClick={handleNext}>
{sourceType === 'zip' ? t('next') : t('build')}
</button>
</div>
</div>
)}
{step === 'building' && (
<div className="publish-step publishing">
<Loader size={48} className="spinning" />
<h3>{t('building')}</h3>
<div className="build-log">
{buildLog.map((log, i) => (
<div key={i} className="log-line">
<CheckCircle size={16} style={{ color: '#34c759', flexShrink: 0 }} />
<span>{log}</span>
</div>
))}
</div>
</div>
)}
{step === 'confirm' && (
<div className="publish-step">
<h3>{t('stepConfirm')}</h3>
<p>{t('confirmMessage')}</p>
{existingPR && (
<div className="existing-pr-notice">
<AlertCircle size={20} />
<div className="notice-content">
<strong>{t('existingPRDetected')}</strong>
<p>{t('existingPRMessage').replace('{{number}}', String(existingPR.number))}</p>
<button
className="btn-link"
onClick={() => open(existingPR.url)}
>
<ExternalLink size={16} />
{t('viewExistingPR')}
</button>
</div>
</div>
)}
<div className="confirm-details">
<div className="detail-row">
<span className="detail-label">{t('selectSource')}:</span>
<span className="detail-value">
{parsedPluginInfo?.sourceType === 'zip' ? t('selectedZip') : t('selectedFolder')}: {parsedPluginInfo?.sourcePath}
</span>
</div>
<div className="detail-row">
<span className="detail-label">{t('version')}:</span>
<span className="detail-value">{publishInfo.version}</span>
</div>
<div className="detail-row">
<span className="detail-label">{t('category')}:</span>
<span className="detail-value">{t(publishInfo.category!)}</span>
</div>
<div className="detail-row">
<span className="detail-label">{t('repositoryUrl')}:</span>
<span className="detail-value">{publishInfo.repositoryUrl}</span>
</div>
{builtZipPath && (
<div className="detail-row">
<span className="detail-label">Package Path:</span>
<span className="detail-value" style={{ fontSize: '12px', wordBreak: 'break-all' }}>
{builtZipPath}
</span>
</div>
)}
</div>
<div className="button-group">
<button className="btn-secondary" onClick={() => setStep('info')}>
{t('back')}
</button>
<button className="btn-primary" onClick={handlePublish}>
{t('confirm')}
</button>
</div>
</div>
)}
{step === 'publishing' && (
<div className="publish-step publishing">
<Loader size={48} className="spinning" />
<h3>{t('publishing')}</h3>
{publishProgress && (
<div className="publish-progress">
<div className="progress-bar">
<div
className="progress-fill"
style={{ width: `${publishProgress.progress}%` }}
/>
</div>
<p className="progress-message">{publishProgress.message}</p>
<p className="progress-percent">{publishProgress.progress}%</p>
</div>
)}
</div>
)}
{step === 'success' && (
<div className="publish-step success">
<CheckCircle size={48} style={{ color: '#34c759' }} />
<h3>{t('publishSuccess')}</h3>
<p>{t('prCreated')}</p>
<p className="review-message">{t('reviewMessage')}</p>
<button className="btn-link" onClick={openPR}>
<ExternalLink size={14} />
{t('viewPR')}
</button>
<button className="btn-primary" onClick={onClose}>
{t('close')}
</button>
</div>
)}
{step === 'error' && (
<div className="publish-step error">
<AlertCircle size={48} style={{ color: '#ff3b30' }} />
<h3>{t('publishError')}</h3>
<p>{error}</p>
<div className="button-group">
<button className="btn-secondary" onClick={() => setStep('info')}>
{t('back')}
</button>
<button className="btn-primary" onClick={onClose}>
{t('close')}
</button>
</div>
</div>
)}
</div>
</div>
);
return inline ? wizardContent : (
<div className="plugin-publish-overlay" onClick={onClose}>
{wizardContent}
</div>
);
}

View File

@@ -0,0 +1,354 @@
import { useState } from 'react';
import { X, FolderOpen, Loader, CheckCircle, AlertCircle, RefreshCw } from 'lucide-react';
import { open as openDialog } from '@tauri-apps/plugin-dialog';
import type { GitHubService, PublishedPlugin } from '../services/GitHubService';
import { PluginPublishService, type PublishProgress } from '../services/PluginPublishService';
import { PluginBuildService, type BuildProgress } from '../services/PluginBuildService';
import { open } from '@tauri-apps/plugin-shell';
import { EditorPluginCategory } from '@esengine/editor-core';
import type { IEditorPluginMetadata } from '@esengine/editor-core';
import '../styles/PluginUpdateDialog.css';
interface PluginUpdateDialogProps {
plugin: PublishedPlugin;
githubService: GitHubService;
onClose: () => void;
onSuccess: () => void;
locale: string;
}
type Step = 'selectFolder' | 'info' | 'building' | 'publishing' | 'success' | 'error';
function calculateNextVersion(currentVersion: string): string {
const parts = currentVersion.split('.').map(Number);
if (parts.length !== 3 || parts.some(isNaN)) return currentVersion;
const [major, minor, patch] = parts;
return `${major}.${minor}.${(patch ?? 0) + 1}`;
}
export function PluginUpdateDialog({ plugin, githubService, onClose, onSuccess, locale }: PluginUpdateDialogProps) {
const [publishService] = useState(() => new PluginPublishService(githubService));
const [buildService] = useState(() => new PluginBuildService());
const [step, setStep] = useState<Step>('selectFolder');
const [pluginFolder, setPluginFolder] = useState('');
const [version, setVersion] = useState('');
const [releaseNotes, setReleaseNotes] = useState('');
const [suggestedVersion] = useState(() => calculateNextVersion(plugin.latestVersion));
const [error, setError] = useState('');
const [buildLog, setBuildLog] = useState<string[]>([]);
const [buildProgress, setBuildProgress] = useState<BuildProgress | null>(null);
const [publishProgress, setPublishProgress] = useState<PublishProgress | null>(null);
const [prUrl, setPrUrl] = useState('');
const t = (key: string) => {
const translations: Record<string, Record<string, string>> = {
zh: {
title: '更新插件',
currentVersion: '当前版本',
newVersion: '新版本号',
useSuggested: '使用建议版本',
releaseNotes: '更新说明',
releaseNotesPlaceholder: '描述这个版本的变更...',
selectFolder: '选择插件文件夹',
selectFolderDesc: '选择包含更新后插件源代码的文件夹',
browseFolder: '浏览文件夹',
selectedFolder: '已选择文件夹',
next: '下一步',
back: '上一步',
buildAndPublish: '构建并发布',
building: '构建中...',
publishing: '发布中...',
success: '更新成功!',
error: '更新失败',
viewPR: '查看 PR',
close: '关闭',
buildError: '构建失败',
publishError: '发布失败',
buildingStep1: '正在安装依赖...',
buildingStep2: '正在构建项目...',
buildingStep3: '正在打包 ZIP...',
publishingStep1: '正在 Fork 仓库...',
publishingStep2: '正在创建分支...',
publishingStep3: '正在上传文件...',
publishingStep4: '正在创建 Pull Request...',
reviewMessage: '你的插件更新已创建 PR维护者将进行审核。审核通过后新版本将自动发布到市场。'
},
en: {
title: 'Update Plugin',
currentVersion: 'Current Version',
newVersion: 'New Version',
useSuggested: 'Use Suggested',
releaseNotes: 'Release Notes',
releaseNotesPlaceholder: 'Describe the changes in this version...',
selectFolder: 'Select Plugin Folder',
selectFolderDesc: 'Select the folder containing your updated plugin source code',
browseFolder: 'Browse Folder',
selectedFolder: 'Selected Folder',
next: 'Next',
back: 'Back',
buildAndPublish: 'Build & Publish',
building: 'Building...',
publishing: 'Publishing...',
success: 'Update Successful!',
error: 'Update Failed',
viewPR: 'View PR',
close: 'Close',
buildError: 'Build Failed',
publishError: 'Publish Failed',
buildingStep1: 'Installing dependencies...',
buildingStep2: 'Building project...',
buildingStep3: 'Packaging ZIP...',
publishingStep1: 'Forking repository...',
publishingStep2: 'Creating branch...',
publishingStep3: 'Uploading files...',
publishingStep4: 'Creating Pull Request...',
reviewMessage: 'Your plugin update has been created as a PR. Maintainers will review it. Once approved, the new version will be published to the marketplace.'
}
};
return translations[locale]?.[key] || translations.en?.[key] || key;
};
const handleSelectFolder = async () => {
try {
const selected = await openDialog({
directory: true,
multiple: false,
title: t('selectFolder')
});
if (!selected) return;
setPluginFolder(selected as string);
setStep('info');
} catch (err) {
console.error('[PluginUpdateDialog] Failed to select folder:', err);
setError(err instanceof Error ? err.message : 'Failed to select folder');
}
};
const handleBuildAndPublish = async () => {
if (!version || !releaseNotes) {
alert('Please fill in all required fields');
return;
}
setStep('building');
setBuildLog([]);
setError('');
try {
buildService.setProgressCallback((progress) => {
setBuildProgress(progress);
if (progress.output) {
setBuildLog((prev) => [...prev, progress.output!]);
}
});
const zipPath = await buildService.buildPlugin(pluginFolder);
console.log('[PluginUpdateDialog] Build completed:', zipPath);
setStep('publishing');
publishService.setProgressCallback((progress) => {
setPublishProgress(progress);
});
const { readTextFile } = await import('@tauri-apps/plugin-fs');
const packageJsonPath = `${pluginFolder}/package.json`;
const packageJsonContent = await readTextFile(packageJsonPath);
const pkgJson = JSON.parse(packageJsonContent);
const pluginMetadata: IEditorPluginMetadata = {
name: pkgJson.name,
displayName: pkgJson.description || pkgJson.name,
description: pkgJson.description || '',
version: pkgJson.version,
category: EditorPluginCategory.Tool,
icon: 'Package',
enabled: true,
installedAt: Date.now()
};
const publishInfo = {
pluginMetadata,
version,
releaseNotes,
category: plugin.category_type as 'official' | 'community',
repositoryUrl: plugin.repositoryUrl || '',
tags: []
};
const prUrl = await publishService.publishPlugin(publishInfo, zipPath);
console.log('[PluginUpdateDialog] Update published:', prUrl);
setPrUrl(prUrl);
setStep('success');
onSuccess();
} catch (err) {
console.error('[PluginUpdateDialog] Failed to update plugin:', err);
setError(err instanceof Error ? err.message : 'Update failed');
setStep('error');
}
};
const renderStepContent = () => {
switch (step) {
case 'selectFolder':
return (
<div className="update-dialog-step">
<h3>{t('selectFolder')}</h3>
<p className="step-description">{t('selectFolderDesc')}</p>
<button className="btn-browse" onClick={handleSelectFolder}>
<FolderOpen size={16} />
{t('browseFolder')}
</button>
</div>
);
case 'info':
return (
<div className="update-dialog-step">
<div className="current-plugin-info">
<h4>{plugin.name}</h4>
<p>
{t('currentVersion')}: <strong>v{plugin.latestVersion}</strong>
</p>
</div>
{pluginFolder && (
<div className="selected-folder-info">
<FolderOpen size={16} />
<span>{pluginFolder}</span>
</div>
)}
<div className="form-group">
<label>{t('newVersion')} *</label>
<div className="version-input-group">
<input
type="text"
value={version}
onChange={(e) => setVersion(e.target.value)}
placeholder={suggestedVersion}
/>
<button
type="button"
className="btn-suggest"
onClick={() => setVersion(suggestedVersion)}
>
{t('useSuggested')} ({suggestedVersion})
</button>
</div>
</div>
<div className="form-group">
<label>{t('releaseNotes')} *</label>
<textarea
rows={6}
value={releaseNotes}
onChange={(e) => setReleaseNotes(e.target.value)}
placeholder={t('releaseNotesPlaceholder')}
/>
</div>
<div className="update-dialog-actions">
<button className="btn-back" onClick={() => setStep('selectFolder')}>
{t('back')}
</button>
<button
className="btn-primary"
onClick={handleBuildAndPublish}
disabled={!version || !releaseNotes}
>
{t('buildAndPublish')}
</button>
</div>
</div>
);
case 'building':
return (
<div className="update-dialog-step">
<h3>{t('building')}</h3>
{buildProgress && (
<div className="progress-container">
<p className="progress-message">{buildProgress.message}</p>
</div>
)}
{buildLog.length > 0 && (
<div className="build-log">
{buildLog.map((log, index) => (
<div key={index} className="log-line">
{log}
</div>
))}
</div>
)}
</div>
);
case 'publishing':
return (
<div className="update-dialog-step">
<h3>{t('publishing')}</h3>
{publishProgress && (
<div className="progress-container">
<div className="progress-bar">
<div className="progress-fill" style={{ width: `${publishProgress.progress}%` }} />
</div>
<p className="progress-message">{publishProgress.message}</p>
</div>
)}
</div>
);
case 'success':
return (
<div className="update-dialog-step success-step">
<CheckCircle size={64} className="success-icon" />
<h3>{t('success')}</h3>
<p className="success-message">{t('reviewMessage')}</p>
{prUrl && (
<button className="btn-view-pr" onClick={() => open(prUrl)}>
{t('viewPR')}
</button>
)}
<button className="btn-close" onClick={onClose}>
{t('close')}
</button>
</div>
);
case 'error':
return (
<div className="update-dialog-step error-step">
<AlertCircle size={64} className="error-icon" />
<h3>{t('error')}</h3>
<p className="error-message">{error}</p>
<button className="btn-close" onClick={onClose}>
{t('close')}
</button>
</div>
);
default:
return null;
}
};
return (
<div className="plugin-update-dialog-overlay">
<div className="plugin-update-dialog">
<div className="update-dialog-header">
<h2>{t('title')}: {plugin.name}</h2>
<button className="update-dialog-close" onClick={onClose}>
<X size={20} />
</button>
</div>
<div className="update-dialog-content">{renderStepContent()}</div>
</div>
</div>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,159 @@
import { useState, useRef, useEffect } from 'react';
import { Github, LogOut, User, LayoutDashboard, Loader2 } from 'lucide-react';
import type { GitHubService, GitHubUser } from '../services/GitHubService';
import '../styles/UserProfile.css';
interface UserProfileProps {
githubService: GitHubService;
onLogin: () => void;
onOpenDashboard: () => void;
locale: string;
}
export function UserProfile({ githubService, onLogin, onOpenDashboard, locale }: UserProfileProps) {
const [user, setUser] = useState<GitHubUser | null>(githubService.getUser());
const [showMenu, setShowMenu] = useState(false);
const [isLoadingUser, setIsLoadingUser] = useState(githubService.isLoadingUserInfo());
const menuRef = useRef<HTMLDivElement>(null);
const t = (key: string) => {
const translations: Record<string, Record<string, string>> = {
zh: {
login: '登录',
logout: '登出',
dashboard: '个人中心',
profile: '个人信息',
notLoggedIn: '未登录',
loadingUser: '加载中...'
},
en: {
login: 'Login',
logout: 'Logout',
dashboard: 'Dashboard',
profile: 'Profile',
notLoggedIn: 'Not logged in',
loadingUser: 'Loading...'
}
};
return translations[locale]?.[key] || translations.en?.[key] || key;
};
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
setShowMenu(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
useEffect(() => {
// 监听加载状态变化
const unsubscribe = githubService.onUserLoadStateChange((isLoading) => {
console.log('[UserProfile] User load state changed:', isLoading);
setIsLoadingUser(isLoading);
});
return unsubscribe;
}, [githubService]);
useEffect(() => {
// 监听认证状态变化
const checkUser = () => {
const currentUser = githubService.getUser();
setUser((prevUser) => {
if (currentUser && (!prevUser || currentUser.login !== prevUser.login)) {
console.log('[UserProfile] User state changed:', currentUser.login);
return currentUser;
} else if (!currentUser && prevUser) {
console.log('[UserProfile] User logged out');
return null;
}
return prevUser;
});
};
// 每秒检查一次用户状态
const interval = setInterval(checkUser, 1000);
return () => clearInterval(interval);
}, [githubService]);
const handleLogout = () => {
githubService.logout();
setUser(null);
setShowMenu(false);
};
if (!user) {
return (
<div className="user-profile">
<button
className="login-button"
onClick={onLogin}
disabled={isLoadingUser}
title={isLoadingUser ? t('loadingUser') : undefined}
>
{isLoadingUser ? (
<>
<Loader2 size={16} className="spinning" />
{t('loadingUser')}
</>
) : (
<>
<Github size={16} />
{t('login')}
</>
)}
</button>
</div>
);
}
return (
<div className="user-profile" ref={menuRef}>
<button className="user-avatar-button" onClick={() => setShowMenu(!showMenu)}>
{user.avatar_url ? (
<img src={user.avatar_url} alt={user.name} className="user-avatar" />
) : (
<div className="user-avatar-placeholder">
<User size={20} />
</div>
)}
<span className="user-name">{user.name || user.login}</span>
</button>
{showMenu && (
<div className="user-menu">
<div className="user-menu-header">
<img src={user.avatar_url} alt={user.name} className="user-menu-avatar" />
<div className="user-menu-info">
<div className="user-menu-name">{user.name || user.login}</div>
<div className="user-menu-login">@{user.login}</div>
</div>
</div>
<div className="user-menu-divider" />
<button
className="user-menu-item"
onClick={() => {
setShowMenu(false);
onOpenDashboard();
}}
>
<LayoutDashboard size={16} />
{t('dashboard')}
</button>
<button className="user-menu-item" onClick={handleLogout}>
<LogOut size={16} />
{t('logout')}
</button>
</div>
)}
</div>
);
}