This commit is contained in:
Baobhan Sith
2025-04-21 00:56:29 +08:00
parent 32d1f89bb7
commit 492d0ee8dd
12 changed files with 1331 additions and 430 deletions
@@ -2,6 +2,7 @@ import { Database } from 'sqlite3';
import * as schemaSql from './schema'; import * as schemaSql from './schema';
import * as appearanceRepository from '../repositories/appearance.repository'; import * as appearanceRepository from '../repositories/appearance.repository';
import * as terminalThemeRepository from '../repositories/terminal-theme.repository'; import * as terminalThemeRepository from '../repositories/terminal-theme.repository';
import * as settingsRepository from '../repositories/settings.repository'; // <-- Import settings repository
import { presetTerminalThemes } from '../config/preset-themes-definition'; import { presetTerminalThemes } from '../config/preset-themes-definition';
import { runDb } from './connection'; // Import runDb for init functions import { runDb } from './connection'; // Import runDb for init functions
@@ -16,20 +17,7 @@ export interface TableDefinition {
// --- Initialization Functions --- // --- Initialization Functions ---
/** // Remove the old initSettingsTable function, as the logic is now in the repository
* Initializes default settings in the settings table.
*/
const initSettingsTable = async (db: Database): Promise<void> => {
const defaultSettings = [
{ key: 'ipWhitelistEnabled', value: 'false' },
{ key: 'ipWhitelist', value: '' }
];
for (const setting of defaultSettings) {
// Use INSERT OR IGNORE to avoid errors if settings already exist
await runDb(db, "INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", [setting.key, setting.value]);
}
console.log('[DB Init] 默认 settings 初始化检查完成。');
};
/** /**
* Initializes preset terminal themes. * Initializes preset terminal themes.
@@ -66,7 +54,7 @@ export const tableDefinitions: TableDefinition[] = [
{ {
name: 'settings', name: 'settings',
sql: schemaSql.createSettingsTableSQL, sql: schemaSql.createSettingsTableSQL,
init: initSettingsTable init: settingsRepository.ensureDefaultSettingsExist // <-- Use the function from the repository
}, },
{ name: 'audit_logs', sql: schemaSql.createAuditLogsTableSQL }, { name: 'audit_logs', sql: schemaSql.createAuditLogsTableSQL },
{ name: 'api_keys', sql: schemaSql.createApiKeysTableSQL }, { name: 'api_keys', sql: schemaSql.createApiKeysTableSQL },
@@ -1,8 +1,10 @@
// packages/backend/src/repositories/settings.repository.ts // packages/backend/src/repositories/settings.repository.ts
import { getDbInstance, runDb, getDb as getDbRow, allDb } from '../database/connection'; // Import new async helpers import { getDbInstance, runDb, getDb as getDbRow, allDb } from '../database/connection';
import { SidebarConfig } from '../types/settings.types'; // <-- Correct import path
import * as sqlite3 from 'sqlite3'; // Import sqlite3 for Database type hint
// Remove top-level db instance // Define keys for specific settings
// const db = getDb(); const SIDEBAR_CONFIG_KEY = 'sidebarConfig';
export interface Setting { export interface Setting {
key: string; key: string;
@@ -93,3 +95,94 @@ export const settingsRepository = {
} }
}, },
}; };
// --- Specific Setting Getters/Setters ---
/**
* 获取侧栏配置
* @returns Promise<SidebarConfig> - Returns the parsed config or default
*/
export const getSidebarConfig = async (): Promise<SidebarConfig> => {
const defaultValue: SidebarConfig = { left: [], right: [] };
try {
const jsonString = await settingsRepository.getSetting(SIDEBAR_CONFIG_KEY);
if (jsonString) {
try {
const config = JSON.parse(jsonString);
// Basic validation
if (config && Array.isArray(config.left) && Array.isArray(config.right)) {
// TODO: Add deeper validation if needed (e.g., check if items are valid PaneName)
return config as SidebarConfig;
}
console.warn(`[SettingsRepo] Invalid sidebarConfig format found in DB: ${jsonString}. Returning default.`);
} catch (parseError) {
console.error(`[SettingsRepo] Failed to parse sidebarConfig JSON from DB: ${jsonString}`, parseError);
}
}
} catch (error) {
console.error(`[SettingsRepo] Error fetching sidebar config setting (key: ${SIDEBAR_CONFIG_KEY}):`, error);
}
// Return default if not found, invalid, or error occurred
return defaultValue;
};
/**
* 设置侧栏配置
* @param config - The sidebar configuration object
*/
export const setSidebarConfig = async (config: SidebarConfig): Promise<void> => {
try {
// Basic validation before stringifying
if (!config || typeof config !== 'object' || !Array.isArray(config.left) || !Array.isArray(config.right)) {
throw new Error('Invalid sidebar config object provided.');
}
// TODO: Add deeper validation if needed (e.g., check PaneName validity)
const jsonString = JSON.stringify(config);
await settingsRepository.setSetting(SIDEBAR_CONFIG_KEY, jsonString);
} catch (error) {
console.error(`[SettingsRepo] Error setting sidebar config (key: ${SIDEBAR_CONFIG_KEY}):`, error);
throw new Error('Failed to save sidebar configuration.');
}
};
// --- Initialization ---
/**
* Ensures default settings exist in the settings table.
* This function should be called during database initialization.
* @param db - The active database instance
*/
export const ensureDefaultSettingsExist = async (db: sqlite3.Database): Promise<void> => {
const defaultSettings: Record<string, string> = {
language: 'en', // Default language
ipWhitelistEnabled: 'false',
ipWhitelist: '',
maxLoginAttempts: '5',
loginBanDuration: '300', // 5 minutes in seconds
focusSwitcherSequence: JSON.stringify(["quickCommandsSearch", "commandHistorySearch", "fileManagerSearch", "commandInput", "terminalSearch"]), // Default focus sequence
navBarVisible: 'true', // Default nav bar visibility
layoutTree: 'null', // Default layout tree (null initially)
autoCopyOnSelect: 'false', // Default auto copy setting
showPopupFileEditor: 'false', // Default popup editor setting
shareFileEditorTabs: 'true', // Default editor tab sharing
dockerStatusIntervalSeconds: '5', // Default Docker refresh interval
dockerDefaultExpand: 'false', // Default Docker expand state
statusMonitorIntervalSeconds: '3', // Default Status Monitor interval
[SIDEBAR_CONFIG_KEY]: JSON.stringify({ left: [], right: [] }), // Default sidebar config
// Add other default settings here
};
const nowSeconds = Math.floor(Date.now() / 1000);
const sqlInsertOrIgnore = `INSERT OR IGNORE INTO settings (key, value, created_at, updated_at) VALUES (?, ?, ?, ?)`;
console.log('[SettingsRepo] Ensuring default settings exist...');
try {
for (const [key, value] of Object.entries(defaultSettings)) {
await runDb(db, sqlInsertOrIgnore, [key, value, nowSeconds, nowSeconds]);
}
console.log('[SettingsRepo] Default settings check complete.');
} catch (err: any) {
console.error(`[SettingsRepo] Error ensuring default settings:`, err.message);
throw new Error(`Failed to ensure default settings: ${err.message}`);
}
};
@@ -1,4 +1,5 @@
import { settingsRepository, Setting } from '../repositories/settings.repository'; import { settingsRepository, Setting, getSidebarConfig as getSidebarConfigFromRepo, setSidebarConfig as setSidebarConfigInRepo } from '../repositories/settings.repository'; // Import specific repo functions
import { SidebarConfig, PaneName, UpdateSidebarConfigDto } from '../types/settings.types'; // <-- Correct import path
// +++ 定义默认的焦点切换顺序 +++ // +++ 定义默认的焦点切换顺序 +++
const DEFAULT_FOCUS_SEQUENCE = ["quickCommandsSearch", "commandHistorySearch", "fileManagerSearch", "commandInput", "terminalSearch"]; const DEFAULT_FOCUS_SEQUENCE = ["quickCommandsSearch", "commandHistorySearch", "fileManagerSearch", "commandInput", "terminalSearch"];
@@ -291,5 +292,68 @@ export const settingsService = {
console.error(`[Service] Error calling settingsRepository.setSetting for key ${STATUS_MONITOR_INTERVAL_SECONDS_KEY}:`, error); console.error(`[Service] Error calling settingsRepository.setSetting for key ${STATUS_MONITOR_INTERVAL_SECONDS_KEY}:`, error);
throw new Error('Failed to save status monitor interval setting.'); throw new Error('Failed to save status monitor interval setting.');
} }
} // *** 最后的方法后面不需要逗号 *** }, // *** 确保这里有逗号 ***
};
// --- Sidebar Config Specific Functions ---
/**
* 获取侧栏配置
* @returns Promise<SidebarConfig>
*/
async getSidebarConfig(): Promise<SidebarConfig> {
console.log('[SettingsService] Getting sidebar config...');
// Directly call the specific repository function
const config = await getSidebarConfigFromRepo();
console.log('[SettingsService] Returning sidebar config:', config);
return config;
},
/**
* 设置侧栏配置
* @param configDto - The sidebar configuration object from DTO
* @returns Promise<void>
*/
async setSidebarConfig(configDto: UpdateSidebarConfigDto): Promise<void> {
console.log('[SettingsService] Setting sidebar config:', configDto);
// --- Validation ---
if (!configDto || typeof configDto !== 'object' || !Array.isArray(configDto.left) || !Array.isArray(configDto.right)) {
throw new Error('无效的侧栏配置格式。必须包含 left 和 right 数组。');
}
// Validate PaneName (using the type imported)
const validPaneNames: Set<PaneName> = new Set([
'connections', 'terminal', 'commandBar', 'fileManager',
'editor', 'statusMonitor', 'commandHistory', 'quickCommands',
'dockerManager'
]);
const validatePaneArray = (arr: any[], side: string) => {
if (!arr.every(item => typeof item === 'string' && validPaneNames.has(item as PaneName))) {
const invalidItems = arr.filter(item => typeof item !== 'string' || !validPaneNames.has(item as PaneName));
throw new Error(`侧栏配置 (${side}) 包含无效的面板名称: ${invalidItems.join(', ')}`);
}
};
validatePaneArray(configDto.left, 'left');
validatePaneArray(configDto.right, 'right');
// Prevent duplicates (optional, uncomment if needed)
// const allPanes = [...configDto.left, ...configDto.right];
// const uniquePanes = new Set(allPanes);
// if (allPanes.length !== uniquePanes.size) {
// throw new Error('侧栏配置中不允许包含重复的面板。');
// }
// Prepare the data in the exact SidebarConfig format expected by the repo
const configToSave: SidebarConfig = {
left: configDto.left,
right: configDto.right,
};
// Directly call the specific repository function
await setSidebarConfigInRepo(configToSave);
console.log('[SettingsService] Sidebar config successfully set.');
} // <-- No comma after the last method in the object
}; // <-- End of settingsService object definition
@@ -1,9 +1,10 @@
import { Request, Response } from 'express'; import { Request, Response } from 'express';
import { settingsService } from '../services/settings.service'; import { settingsService } from '../services/settings.service';
import { AuditLogService } from '../services/audit.service'; // 引入 AuditLogService import { AuditLogService } from '../services/audit.service'; // 引入 AuditLogService
import { ipBlacklistService } from '../services/ip-blacklist.service'; // 引入 IP 黑名单服务 import { ipBlacklistService } from '../services/ip-blacklist.service';
import { UpdateSidebarConfigDto } from '../types/settings.types'; // <-- Correct import path
const auditLogService = new AuditLogService(); // 实例化 AuditLogService const auditLogService = new AuditLogService();
export const settingsController = { export const settingsController = {
/** /**
@@ -291,5 +292,59 @@ export const settingsController = {
console.error('[Controller] 设置终端选中自动复制时出错:', error); console.error('[Controller] 设置终端选中自动复制时出错:', error);
res.status(500).json({ message: '设置终端选中自动复制失败', error: error.message }); res.status(500).json({ message: '设置终端选中自动复制失败', error: error.message });
} }
} // *** 最后的方法后面不需要逗号 *** }, // *** 确保这里有逗号 ***
};
// --- Sidebar Config Controller Methods ---
/**
* 获取侧栏配置
*/
async getSidebarConfig(req: Request, res: Response): Promise<void> {
try {
console.log('[Controller] Received request to get sidebar config.');
const config = await settingsService.getSidebarConfig();
console.log('[Controller] Sending sidebar config to client:', config);
res.json(config);
} catch (error: any) {
console.error('[Controller] 获取侧栏配置时出错:', error);
res.status(500).json({ message: '获取侧栏配置失败', error: error.message });
}
},
/**
* 设置侧栏配置
*/
async setSidebarConfig(req: Request, res: Response): Promise<void> {
console.log('[Controller] Received request to set sidebar config.');
try {
const configDto: UpdateSidebarConfigDto = req.body;
console.log('[Controller] Request body:', configDto);
// --- DTO Validation (Basic) ---
// More specific validation happens in the service layer
if (!configDto || typeof configDto !== 'object' || !Array.isArray(configDto.left) || !Array.isArray(configDto.right)) {
console.warn('[Controller] Invalid sidebar config format received:', configDto);
res.status(400).json({ message: '无效的请求体,应为包含 left 和 right 数组的 JSON 对象' });
return;
}
console.log('[Controller] Calling settingsService.setSidebarConfig...');
await settingsService.setSidebarConfig(configDto);
console.log('[Controller] settingsService.setSidebarConfig completed successfully.');
// auditLogService.logAction('SIDEBAR_CONFIG_UPDATED'); // Optional: Add audit log
console.log('[Controller] Sending success response.');
res.status(200).json({ message: '侧栏配置已成功更新' });
} catch (error: any) {
console.error('[Controller] 设置侧栏配置时出错:', error);
// Handle specific validation errors from the service
if (error.message.includes('无效的面板名称') || error.message.includes('无效的侧栏配置格式')) {
res.status(400).json({ message: `设置侧栏配置失败: ${error.message}` });
} else {
res.status(500).json({ message: '设置侧栏配置失败', error: error.message });
}
}
} // <-- No comma after the last method
}; // <-- End of settingsController object
@@ -43,4 +43,11 @@ router.get('/auto-copy-on-select', settingsController.getAutoCopyOnSelect);
// PUT /api/v1/settings/auto-copy-on-select - 更新设置 // PUT /api/v1/settings/auto-copy-on-select - 更新设置
router.put('/auto-copy-on-select', settingsController.setAutoCopyOnSelect); router.put('/auto-copy-on-select', settingsController.setAutoCopyOnSelect);
// +++ 新增:侧栏配置路由 +++
// GET /api/v1/settings/sidebar - 获取侧栏配置
router.get('/sidebar', settingsController.getSidebarConfig);
// PUT /api/v1/settings/sidebar - 更新侧栏配置
router.put('/sidebar', settingsController.setSidebarConfig);
export default router; export default router;
@@ -1,5 +1,8 @@
import type { ITheme } from 'xterm'; import type { ITheme } from 'xterm';
// 定义所有可用面板的名称 (后端独立定义)
export type PaneName = 'connections' | 'terminal' | 'commandBar' | 'fileManager' | 'editor' | 'statusMonitor' | 'commandHistory' | 'quickCommands' | 'dockerManager';
/** /**
* 外观设置数据结构 * 外观设置数据结构
*/ */
@@ -0,0 +1,19 @@
// packages/backend/src/types/settings.types.ts
// Define PaneName here as it's logically related to layout/sidebar settings
export type PaneName = 'connections' | 'terminal' | 'commandBar' | 'fileManager' | 'editor' | 'statusMonitor' | 'commandHistory' | 'quickCommands' | 'dockerManager';
/**
* 侧栏配置数据结构 (Managed by Settings Repository/Service)
*/
export interface SidebarConfig {
left: PaneName[];
right: PaneName[];
}
/**
* 用于更新侧栏配置的 DTO
*/
export interface UpdateSidebarConfigDto extends SidebarConfig {} // Simple alias for now, can add validation later
// You can add other settings-related types here if needed
@@ -1,9 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted, type Ref, reactive } from 'vue'; // 导入 reactive import { ref, computed, watch, type Ref } from 'vue'; // Removed reactive as it wasn't used after style removal
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useLayoutStore, type LayoutNode, type PaneName } from '../stores/layout.store'; import { useLayoutStore, type LayoutNode, type PaneName } from '../stores/layout.store';
import draggable from 'vuedraggable'; import draggable from 'vuedraggable';
import LayoutNodeEditor from './LayoutNodeEditor.vue'; // *** 导入节点编辑器 *** import LayoutNodeEditor from './LayoutNodeEditor.vue';
// --- Props --- // --- Props ---
const props = defineProps({ const props = defineProps({
@@ -21,67 +21,69 @@ const { t } = useI18n();
const layoutStore = useLayoutStore(); const layoutStore = useLayoutStore();
// --- State --- // --- State ---
// 创建布局树的本地副本,以便在不直接修改 store 的情况下进行编辑
const localLayoutTree: Ref<LayoutNode | null> = ref(null); const localLayoutTree: Ref<LayoutNode | null> = ref(null);
// 标记是否有更改未保存
const hasChanges = ref(false); const hasChanges = ref(false);
const localSidebarPanes: Ref<{ left: PaneName[], right: PaneName[] }> = ref({ left: [], right: [] });
// --- Dialog State --- // --- Dialog State ---
const dialogRef = ref<HTMLElement | null>(null); // 对话框元素的引用 const dialogRef = ref<HTMLElement | null>(null);
// 移除 initialDialogState, width, height 从 dialogStyle
// dialogStyle 现在不再需要,因为定位由 overlay flex 处理,尺寸由 CSS 处理
// const dialogStyle = reactive({
// top: '50%',
// left: '50%',
// transform: 'translate(-50%, -50%)', // 初始居中
// position: 'absolute' as 'absolute', // 显式设置定位
// });
// 移除 Resizing 相关的状态
// const isResizing = ref(false);
// const resizeHandle = ref<string | null>(null);
// const startDragPos = { x: 0, y: 0 };
// const startDialogRect = { width: 0, height: 0, top: 0, left: 0 };
// const minDialogSize = { width: 400, height: 300 }; // 移至 CSS
// --- Watchers --- // --- Watchers ---
// 当弹窗可见时,从 store 加载当前布局并计算初始位置
watch(() => props.isVisible, (newValue) => { watch(() => props.isVisible, (newValue) => {
if (newValue) { if (newValue) {
// 加载布局 // Load main layout
if (layoutStore.layoutTree) { if (layoutStore.layoutTree) {
localLayoutTree.value = JSON.parse(JSON.stringify(layoutStore.layoutTree)); localLayoutTree.value = JSON.parse(JSON.stringify(layoutStore.layoutTree));
} else {
localLayoutTree.value = null; // Ensure it's null if store is null
} }
hasChanges.value = false; // Load sidebar config
console.log('[LayoutConfigurator] 弹窗打开,已加载当前布局到本地副本。'); if (layoutStore.sidebarPanes) {
localSidebarPanes.value = JSON.parse(JSON.stringify(layoutStore.sidebarPanes));
// 弹窗打开时的逻辑 (不再需要设置样式) } else {
console.log('[LayoutConfigurator] Dialog opened.'); localSidebarPanes.value = { left: [], right: [] }; // Default
// 移除 requestAnimationFrame 和尺寸/位置计算逻辑 }
hasChanges.value = false; // Reset changes flag on open
console.log('[LayoutConfigurator] Dialog opened, loaded layout and sidebar config.');
} else { } else {
localLayoutTree.value = null; // 关闭时清空本地副本 localLayoutTree.value = null;
// 移除 isResizing 和事件监听器移除 (因为 resizing 功能已移除) localSidebarPanes.value = { left: [], right: [] };
// isResizing.value = false; console.log('[LayoutConfigurator] Dialog closed.');
// window.removeEventListener('mousemove', handleMouseMove);
// window.removeEventListener('mouseup', handleMouseUp);
} }
}, /*{ immediate: true }*/); // 移除 immediate: true 解决初始化顺序问题 });
// 监听本地布局树的变化,标记有未保存更改 // Watch for changes in the main layout tree
watch(localLayoutTree, (newValue, oldValue) => { watch(localLayoutTree, (newValue, oldValue) => {
// 确保不是初始化加载触发的 watch // Check if it's not the initial load and the dialog is visible
if (oldValue !== null && props.isVisible) { if (oldValue !== undefined && oldValue !== null && props.isVisible) {
hasChanges.value = true; // Use stringify for a simple deep comparison
console.log('[LayoutConfigurator] 本地布局已更改。'); if (JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
console.log('[LayoutConfigurator] Main layout tree changed.');
hasChanges.value = true;
}
} }
}, { deep: true }); }, { deep: true });
// --- Helper Function for Local Tree --- // Watch for changes in the sidebar configuration
// 递归查找本地布局树中所有使用的面板组件名称 watch(localSidebarPanes, (newValue, oldValue) => {
function getLocalUsedPaneNames(node: LayoutNode | null): Set<PaneName> { // Check if it's not the initial load and the dialog is visible
if (oldValue !== undefined && props.isVisible) {
const newJson = JSON.stringify(newValue);
const oldJson = JSON.stringify(oldValue);
console.log('[LayoutConfigurator Watcher] localSidebarPanes changed.');
// Use stringify for a simple deep comparison, including order changes
if (newJson !== oldJson) {
console.log('[LayoutConfigurator Watcher] Sidebar panes changed, setting hasChanges.');
hasChanges.value = true;
}
}
}, { deep: true });
// --- Helper Functions ---
function getMainLayoutUsedPaneNames(node: LayoutNode | null): Set<PaneName> {
const usedNames = new Set<PaneName>(); const usedNames = new Set<PaneName>();
if (!node) return usedNames; if (!node) return usedNames;
function traverse(currentNode: LayoutNode) { function traverse(currentNode: LayoutNode) {
if (currentNode.type === 'pane' && currentNode.component) { if (currentNode.type === 'pane' && currentNode.component) {
usedNames.add(currentNode.component); usedNames.add(currentNode.component);
@@ -89,24 +91,26 @@ function getLocalUsedPaneNames(node: LayoutNode | null): Set<PaneName> {
currentNode.children.forEach(traverse); currentNode.children.forEach(traverse);
} }
} }
traverse(node); traverse(node);
return usedNames; return usedNames;
} }
function getAllLocalUsedPaneNames(mainNode: LayoutNode | null, sidebars: { left: PaneName[], right: PaneName[] }): Set<PaneName> {
const usedNames = getMainLayoutUsedPaneNames(mainNode);
sidebars.left.forEach(pane => usedNames.add(pane));
sidebars.right.forEach(pane => usedNames.add(pane));
return usedNames;
}
// --- Computed --- // --- Computed ---
// const availablePanes = computed(() => layoutStore.availablePanes); // 旧的,基于 store const allPossiblePanes = computed(() => layoutStore.allPossiblePanes);
const allPossiblePanes = computed(() => layoutStore.allPossiblePanes); // 获取所有可能的面板
// *** 新增:计算当前配置器预览中可用的面板 ***
const configuratorAvailablePanes = computed(() => { const configuratorAvailablePanes = computed(() => {
const localUsed = getLocalUsedPaneNames(localLayoutTree.value); const localUsed = getAllLocalUsedPaneNames(localLayoutTree.value, localSidebarPanes.value);
return allPossiblePanes.value.filter(pane => !localUsed.has(pane)); return allPossiblePanes.value.filter(pane => !localUsed.has(pane));
}); });
// Panel Labels for display
// 将 PaneName 映射到用户友好的中文标签
const paneLabels = computed(() => ({ const paneLabels = computed(() => ({
connections: t('layout.pane.connections', '连接列表'), connections: t('layout.pane.connections', '连接列表'),
terminal: t('layout.pane.terminal', '终端'), terminal: t('layout.pane.terminal', '终端'),
@@ -116,7 +120,7 @@ const paneLabels = computed(() => ({
statusMonitor: t('layout.pane.statusMonitor', '状态监视器'), statusMonitor: t('layout.pane.statusMonitor', '状态监视器'),
commandHistory: t('layout.pane.commandHistory', '命令历史'), commandHistory: t('layout.pane.commandHistory', '命令历史'),
quickCommands: t('layout.pane.quickCommands', '快捷指令'), quickCommands: t('layout.pane.quickCommands', '快捷指令'),
dockerManager: t('layout.pane.dockerManager', 'Docker 管理器'), // 添加 dockerManager dockerManager: t('layout.pane.dockerManager', 'Docker 管理器'),
})); }));
// --- Methods --- // --- Methods ---
@@ -131,122 +135,145 @@ const closeDialog = () => {
}; };
const saveLayout = () => { const saveLayout = () => {
// Save main layout
if (localLayoutTree.value) { if (localLayoutTree.value) {
layoutStore.updateLayoutTree(localLayoutTree.value); layoutStore.updateLayoutTree(localLayoutTree.value);
hasChanges.value = false; console.log('[LayoutConfigurator] Main layout saved to Store.');
console.log('[LayoutConfigurator] 布局已保存到 Store。');
emit('close'); // 保存后关闭
} else { } else {
console.error('[LayoutConfigurator] 无法保存,本地布局树为空。'); // Handle potentially empty layout based on store logic
layoutStore.updateLayoutTree(null); // Assuming null is valid for empty
console.log('[LayoutConfigurator] Main layout is empty, saved null to Store.');
} }
// Save sidebar config
const sidebarConfigToSave = JSON.parse(JSON.stringify(localSidebarPanes.value));
console.log('[LayoutConfigurator] Preparing to save sidebar config:', sidebarConfigToSave); // Log before sending
layoutStore.updateSidebarPanes(sidebarConfigToSave);
console.log('[LayoutConfigurator] Sidebar config sent to Store.');
hasChanges.value = false;
emit('close');
}; };
const resetToDefault = () => { const resetToDefault = () => {
if (confirm(t('layoutConfigurator.confirmReset', '确定要恢复默认布局吗?当前更改将丢失。'))) { if (confirm(t('layoutConfigurator.confirmReset', '确定要恢复默认布局和侧栏配置吗?当前更改将丢失。'))) {
// 调用 store 中获取系统默认布局的方法 // Reset main layout
const defaultLayout = layoutStore.getSystemDefaultLayout(); const defaultLayout = layoutStore.getSystemDefaultLayout();
// 直接将获取到的默认布局(深拷贝)赋值给本地副本
localLayoutTree.value = JSON.parse(JSON.stringify(defaultLayout)); localLayoutTree.value = JSON.parse(JSON.stringify(defaultLayout));
hasChanges.value = true; // 标记为有更改,因为是重置操作
console.log('[LayoutConfigurator] 已重置为系统默认布局。'); // Reset sidebar config (assuming store provides a default or empty)
const defaultSidebarPanes = layoutStore.getSystemDefaultSidebarPanes(); // Get default from store
localSidebarPanes.value = JSON.parse(JSON.stringify(defaultSidebarPanes));
console.log('[LayoutConfigurator] Reset to default layout and sidebar panes.');
hasChanges.value = true; // Mark as changed after reset
} }
}; };
// --- Resizing Methods (Removed) --- // Clone function for dragging available panes
// Resizing functionality is removed to allow content-based sizing.
// --- Drag & Drop Methods (for panes, unchanged) ---
// 克隆函数:当从可用列表拖拽时,创建新的 LayoutNode 对象
const clonePane = (paneName: PaneName): LayoutNode => { const clonePane = (paneName: PaneName): LayoutNode => {
console.log(`[LayoutConfigurator] 克隆面板: ${paneName}`); console.log(`[LayoutConfigurator] Cloning pane: ${paneName}`);
return { return {
id: layoutStore.generateId(), // 使用 store 中的函数生成新 ID id: layoutStore.generateId(),
type: 'pane', type: 'pane',
component: paneName, component: paneName,
size: 50, // 默认大小,可以后续调整 size: 50, // Default size, can be adjusted later
}; };
}; };
// 移除旧的 handleDragStart // Handle updates from LayoutNodeEditor (for main layout)
// const handleDragStart = (event: DragEvent, paneName: PaneName) => { ... }
// 移除旧的预览区域 drop/dragover 处理,由 LayoutNodeEditor 内部处理
// const handleDropOnPreview = (event: DragEvent) => { ... };
// const handleDragOverPreview = (event: DragEvent) => { ... };
// *** 新增:处理来自 LayoutNodeEditor 的更新事件 ***
const handleNodeUpdate = (updatedNode: LayoutNode) => { const handleNodeUpdate = (updatedNode: LayoutNode) => {
// 因为 LayoutNodeEditor 是直接操作 localLayoutTree 的副本, console.log('[LayoutConfigurator] Received node update from editor:', updatedNode);
// 理论上 v-model 绑定应该能处理更新。 // Assuming the update is for the root node for simplicity
// 但为了明确和处理可能的深层更新问题,我们直接替换根节点。 // v-model on LayoutNodeEditor might handle this, but explicit update is safer
// 注意:这假设 LayoutNodeEditor 只会 emit 根节点的更新事件, localLayoutTree.value = updatedNode;
// 或者我们需要一个更复杂的查找和替换逻辑。 // No need to set hasChanges here, the watcher on localLayoutTree handles it
// 简单的做法是,只要有更新,就认为整个 localLayoutTree 可能变了。
// vuedraggable 的 v-model 应该能处理大部分情况)
// 暂时只打印日志,依赖 v-model 的更新
console.log('[LayoutConfigurator] Received node update:', updatedNode);
// 如果 v-model 更新不完全,可能需要手动更新:
localLayoutTree.value = updatedNode; // 强制更新整个树
}; };
// *** 新增:处理来自 LayoutNodeEditor 的移除事件 *** // Handle remove requests from LayoutNodeEditor (for main layout)
// 递归查找并移除指定索引的节点
function findAndRemoveNode(node: LayoutNode | null, parentNodeId: string | undefined, nodeIndex: number): LayoutNode | null { function findAndRemoveNode(node: LayoutNode | null, parentNodeId: string | undefined, nodeIndex: number): LayoutNode | null {
if (!node) return null; if (!node) return null;
// 如果当前节点是目标节点的父节点
if (node.id === parentNodeId && node.type === 'container' && node.children && node.children[nodeIndex]) { if (node.id === parentNodeId && node.type === 'container' && node.children && node.children[nodeIndex]) {
const updatedChildren = [...node.children]; const updatedChildren = [...node.children];
updatedChildren.splice(nodeIndex, 1); updatedChildren.splice(nodeIndex, 1);
console.log(`[LayoutConfigurator] Removed node at index ${nodeIndex} from parent ${parentNodeId}`); console.log(`[LayoutConfigurator] Removed node at index ${nodeIndex} from parent ${parentNodeId}`);
// 如果移除后容器为空,可以选择移除容器自身,这里暂时保留空容器
return { ...node, children: updatedChildren }; return { ...node, children: updatedChildren };
} }
// 递归查找子节点
if (node.type === 'container' && node.children) { if (node.type === 'container' && node.children) {
const updatedChildren = node.children.map(child => findAndRemoveNode(child, parentNodeId, nodeIndex)); const updatedChildren = node.children.map(child => findAndRemoveNode(child, parentNodeId, nodeIndex));
// 检查是否有子节点被更新(即目标节点在更深层被找到并移除) if (updatedChildren.some((child, index) => child !== node.children![index])) {
if (updatedChildren.some((child, index) => child !== node.children![index])) { return { ...node, children: updatedChildren.filter(Boolean) as LayoutNode[] };
return { ...node, children: updatedChildren.filter(Boolean) as LayoutNode[] }; }
}
} }
return node;
return node; // 未找到或未修改,返回原节点
} }
const handleNodeRemove = (payload: { parentNodeId: string | undefined; nodeIndex: number }) => { const handleNodeRemove = (payload: { parentNodeId: string | undefined; nodeIndex: number }) => {
console.log('[LayoutConfigurator] Received node remove request:', payload); console.log('[LayoutConfigurator] Received node remove request:', payload);
if (payload.parentNodeId === undefined && payload.nodeIndex === 0) { if (payload.parentNodeId === undefined && payload.nodeIndex === 0) {
// 尝试移除根节点,不允许或清空布局
if (confirm('确定要清空整个布局吗?')) { if (confirm('确定要清空整个布局吗?')) {
localLayoutTree.value = null; // 或者设置为空容器 localLayoutTree.value = null;
// No need to set hasChanges here, the watcher on localLayoutTree handles it
} }
} else if (payload.parentNodeId) { } else if (payload.parentNodeId) {
localLayoutTree.value = findAndRemoveNode(localLayoutTree.value, payload.parentNodeId, payload.nodeIndex); localLayoutTree.value = findAndRemoveNode(localLayoutTree.value, payload.parentNodeId, payload.nodeIndex);
// No need to set hasChanges here, the watcher on localLayoutTree handles it
} else { } else {
console.warn('[LayoutConfigurator] Invalid remove payload:', payload); console.warn('[LayoutConfigurator] Invalid remove payload:', payload);
} }
}; };
// Remove pane from sidebar list
const removeSidebarPane = (side: 'left' | 'right', index: number) => {
localSidebarPanes.value[side].splice(index, 1);
console.log(`[LayoutConfigurator] Removed pane from ${side} sidebar at index ${index}.`);
// Explicitly set hasChanges flag
hasChanges.value = true;
};
// Handler for vuedraggable end event to ensure changes flag is set and handle added items
const onDraggableChange = (event: any, side: 'left' | 'right') => { // Add side parameter
console.log(`[LayoutConfigurator] Draggable change event detected on ${side} sidebar:`, event);
// Check if an element was added to the sidebar list
if (event.added) {
const addedElement = event.added.element;
const targetList = localSidebarPanes.value[side]; // Use the side parameter directly
const addedIndex = event.added.newIndex;
// Check if the added element is a LayoutNode object (dragged from available panes)
if (targetList && typeof addedElement === 'object' && addedElement !== null && addedElement.type === 'pane' && typeof addedElement.component === 'string') {
// Replace the added LayoutNode object with its component name (PaneName)
targetList.splice(addedIndex, 1, addedElement.component);
console.log(`[LayoutConfigurator] Replaced added LayoutNode at index ${addedIndex} on ${side} sidebar with PaneName: ${addedElement.component}`);
} else {
console.log(`[LayoutConfigurator] Added event detected on ${side} sidebar, but element was not a LayoutNode:`, addedElement);
}
} else if (event.moved || event.removed) {
console.log(`[LayoutConfigurator] Item moved or removed within/from ${side} sidebar.`);
}
// Ensure changes flag is set for any modification (add, remove, move)
hasChanges.value = true;
};
</script> </script>
<template> <template>
<div v-if="isVisible" class="layout-configurator-overlay" @click.self="closeDialog"> <div v-if="isVisible" class="layout-configurator-overlay" @click.self="closeDialog">
<!-- 移除 :style 绑定尺寸和定位由 CSS 控制 -->
<div ref="dialogRef" class="layout-configurator-dialog"> <div ref="dialogRef" class="layout-configurator-dialog">
<!-- Resize Handles Removed -->
<header class="dialog-header"> <header class="dialog-header">
<h2>{{ t('layoutConfigurator.title', '配置工作区布局') }}</h2> <h2>{{ t('layoutConfigurator.title', '配置工作区布局') }}</h2>
<button class="close-button" @click="closeDialog" :title="t('common.close', '关闭')">&times;</button> <button class="close-button" @click="closeDialog" :title="t('common.close', '关闭')">&times;</button>
</header> </header>
<main class="dialog-content"> <!-- Grid Layout -->
<main class="dialog-content-grid">
<!-- Available Panes -->
<section class="available-panes-section"> <section class="available-panes-section">
<h3>{{ t('layoutConfigurator.availablePanes', '可用面板') }}</h3> <h3>{{ t('layoutConfigurator.availablePanes', '可用面板') }}</h3>
<!-- *** 使用 draggable 包裹列表 *** -->
<draggable <draggable
:list="configuratorAvailablePanes" :list="configuratorAvailablePanes"
tag="ul" tag="ul"
@@ -257,28 +284,23 @@ const handleNodeRemove = (payload: { parentNodeId: string | undefined; nodeIndex
:clone="clonePane" :clone="clonePane"
> >
<template #item="{ element }: { element: PaneName }"> <template #item="{ element }: { element: PaneName }">
<li <li class="available-pane-item">
class="available-pane-item"
>
<i class="fas fa-grip-vertical drag-handle"></i> <i class="fas fa-grip-vertical drag-handle"></i>
{{ paneLabels[element] || element }} {{ paneLabels[element] || element }}
</li> </li>
</template> </template>
<template #footer> <template #footer>
<li v-if="configuratorAvailablePanes.length === 0" class="no-available-panes"> <!-- *** 使用新的计算属性 *** --> <li v-if="configuratorAvailablePanes.length === 0" class="no-available-panes">
{{ t('layoutConfigurator.noAvailablePanes', '所有面板都已在布局中') }} {{ t('layoutConfigurator.noAvailablePanes', '所有面板都已在布局中') }}
</li> </li>
</template> </template>
</draggable> </draggable>
</section> </section>
<section <!-- Main Layout Preview -->
class="layout-preview-section" <section class="layout-preview-section">
> <h3>{{ t('layoutConfigurator.layoutPreview', '主布局预览(拖拽到此处)') }}</h3>
<h3>{{ t('layoutConfigurator.layoutPreview', '布局预览(拖拽到此处)') }}</h3> <div class="preview-area main-layout-area">
<div class="preview-area">
<!-- *** 使用 LayoutNodeEditor 渲染预览 *** -->
<LayoutNodeEditor <LayoutNodeEditor
v-if="localLayoutTree" v-if="localLayoutTree"
:node="localLayoutTree" :node="localLayoutTree"
@@ -287,8 +309,9 @@ const handleNodeRemove = (payload: { parentNodeId: string | undefined; nodeIndex
:pane-labels="paneLabels" :pane-labels="paneLabels"
@update:node="handleNodeUpdate" @update:node="handleNodeUpdate"
@removeNode="handleNodeRemove" @removeNode="handleNodeRemove"
:group="'layout-items'"
/> />
<p v-else style="text-align: center; color: #aaa; margin-top: 50px;"> <p v-else class="empty-placeholder">
{{ t('layoutConfigurator.emptyLayout', '布局为空,请从左侧拖拽面板或添加容器。') }} {{ t('layoutConfigurator.emptyLayout', '布局为空,请从左侧拖拽面板或添加容器。') }}
</p> </p>
</div> </div>
@@ -296,9 +319,68 @@ const handleNodeRemove = (payload: { parentNodeId: string | undefined; nodeIndex
<button @click="resetToDefault" class="button-secondary"> <button @click="resetToDefault" class="button-secondary">
{{ t('layoutConfigurator.resetDefault', '恢复默认') }} {{ t('layoutConfigurator.resetDefault', '恢复默认') }}
</button> </button>
</div> </div>
</section> </section>
<!-- Sidebar Configuration Container -->
<div class="sidebar-container">
<!-- Left Sidebar Config -->
<section class="sidebar-config-section left-sidebar-section">
<h3>{{ t('layoutConfigurator.leftSidebar', '左侧栏面板') }}</h3>
<draggable
:list="localSidebarPanes.left"
tag="ul"
class="sidebar-panes-list"
:item-key="(element: PaneName) => `left-${element}`"
group="layout-items"
:sort="true"
@change="(event) => onDraggableChange(event, 'left')"
>
<template #item="{ element, index }: { element: PaneName, index: number }">
<li class="sidebar-pane-item">
<i class="fas fa-grip-vertical drag-handle"></i>
<!-- Correctly display translated label -->
<span>{{ paneLabels[element] || element }}</span>
<button @click="removeSidebarPane('left', index)" class="remove-sidebar-btn" :title="t('common.remove', '移除')">&times;</button>
</li>
</template>
<template #footer>
<li v-if="localSidebarPanes.left.length === 0" class="empty-placeholder sidebar-empty">
{{ t('layoutConfigurator.dropHere', '从可用面板拖拽到此处') }}
</li>
</template>
</draggable>
</section>
<!-- Right Sidebar Config -->
<section class="sidebar-config-section right-sidebar-section">
<h3>{{ t('layoutConfigurator.rightSidebar', '右侧栏面板') }}</h3>
<draggable
:list="localSidebarPanes.right"
tag="ul"
class="sidebar-panes-list"
:item-key="(element: PaneName) => `right-${element}`"
group="layout-items"
:sort="true"
@change="(event) => onDraggableChange(event, 'right')"
>
<template #item="{ element, index }: { element: PaneName, index: number }">
<li class="sidebar-pane-item">
<i class="fas fa-grip-vertical drag-handle"></i>
<!-- Correctly display translated label -->
<span>{{ paneLabels[element] || element }}</span>
<button @click="removeSidebarPane('right', index)" class="remove-sidebar-btn" :title="t('common.remove', '移除')">&times;</button>
</li>
</template>
<template #footer>
<li v-if="localSidebarPanes.right.length === 0" class="empty-placeholder sidebar-empty">
{{ t('layoutConfigurator.dropHere', '从可用面板拖拽到此处') }}
</li>
</template>
</draggable>
</section>
</div>
</main> </main>
<footer class="dialog-footer"> <footer class="dialog-footer">
@@ -320,39 +402,29 @@ const handleNodeRemove = (payload: { parentNodeId: string | undefined; nodeIndex
height: 100%; height: 100%;
background-color: rgba(0, 0, 0, 0.6); background-color: rgba(0, 0, 0, 0.6);
display: flex; display: flex;
/* 使用 Flexbox 居中 */
display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
z-index: 1000; z-index: 1000;
/* 移除 pointer-events: none; */
} }
.layout-configurator-dialog { .layout-configurator-dialog {
background-color: #fff; background-color: #fff;
border-radius: 8px; border-radius: 8px;
box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3); box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
/* 让宽度和高度自适应内容 */ width: auto;
width: auto; /* 或移除 */ height: auto;
height: auto; /* 或移除 */ min-width: 800px; /* Adjusted min-width */
/* 添加最大/最小尺寸限制 */ min-height: 600px; /* Adjusted min-height */
min-width: 500px; /* 根据需要调整 */ max-width: 95vw;
min-height: 400px; /* 根据需要调整 */ max-height: 90vh;
max-width: 90vw; /* 视口宽度的90% */
max-height: 90vh; /* 视口高度的90% */
display: flex; display: flex;
flex-direction: column; flex-direction: column;
/* overflow: hidden; */ /* 改为 auto 或 visible 以允许内容撑开 */ overflow: auto;
overflow: auto; /* 如果内容可能超出 max-height/max-width */ position: relative;
position: relative; /* 改为 relative,因为 overlay flex 负责居中 */
/* 移除 top, left, transform, position: absolute */
/* 允许 dialog 接收点击事件 */
pointer-events: auto; pointer-events: auto;
cursor: default; /* 保持默认光标 */ cursor: default;
} }
/* 移除 body.resizing 样式 */
.dialog-header { .dialog-header {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
@@ -381,23 +453,51 @@ const handleNodeRemove = (payload: { parentNodeId: string | undefined; nodeIndex
color: #333; color: #333;
} }
.dialog-content { /* Grid Layout for Dialog Content */
.dialog-content-grid {
flex-grow: 1; flex-grow: 1;
padding: 1.5rem; padding: 1.5rem;
overflow-y: auto; /* 允许内容区滚动 */ overflow-y: auto;
display: flex; /* 左右布局 */ display: grid;
grid-template-columns: 220px 1fr;
grid-template-rows: auto 1fr;
grid-template-areas:
"available main"
"available sidebars";
gap: 1.5rem; gap: 1.5rem;
min-height: 450px;
} }
.available-panes-section { .available-panes-section {
flex: 1; /* 占据一部分空间 */ grid-area: available;
min-width: 200px; display: flex;
flex-direction: column;
overflow-y: auto;
border-right: 1px solid #eee; border-right: 1px solid #eee;
padding-right: 1.5rem; padding-right: 1.5rem;
min-width: 200px; /* Ensure minimum width */
} }
.layout-preview-section { .layout-preview-section {
flex: 2; /* 占据更多空间 */ grid-area: main;
display: flex;
flex-direction: column;
min-width: 350px;
min-height: 250px;
}
.sidebar-container {
grid-area: sidebars;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1.5rem;
border-top: 1px solid #eee;
padding-top: 1rem;
margin-top: 1rem;
min-height: 150px;
}
.sidebar-config-section {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
} }
@@ -414,6 +514,7 @@ h3 {
list-style: none; list-style: none;
padding: 0; padding: 0;
margin: 0; margin: 0;
flex-grow: 1; /* Allow list to take available space */
} }
.available-pane-item { .available-pane-item {
@@ -450,18 +551,15 @@ h3 {
padding: 0.5rem 0; padding: 0.5rem 0;
} }
.preview-area { .preview-area.main-layout-area {
flex-grow: 1; flex-grow: 1;
border: 2px dashed #ced4da; border: 2px dashed #ced4da;
border-radius: 4px; border-radius: 4px;
padding: 1rem; padding: 1rem;
background-color: #f8f9fa; background-color: #f8f9fa;
min-height: 300px; /* 保证预览区有一定高度 */ display: flex;
display: flex; /* 用于内部占位符居中 */
flex-direction: column; flex-direction: column;
/* justify-content: center; */ /* 移除,让内容从顶部开始 */ overflow: auto;
/* align-items: center; */ /* 移除 */
overflow: auto; /* 如果预览内容复杂,允许滚动 */
} }
.preview-actions { .preview-actions {
@@ -479,7 +577,7 @@ h3 {
background-color: #f8f9fa; background-color: #f8f9fa;
} }
/* 通用按钮样式 */ /* Button Styles */
.button-primary, .button-primary,
.button-secondary { .button-secondary {
padding: 0.5rem 1rem; padding: 0.5rem 1rem;
@@ -512,7 +610,86 @@ h3 {
background-color: #dee2e6; background-color: #dee2e6;
} }
/* Sidebar List Styles */
.sidebar-panes-list {
list-style: none;
padding: 0;
margin: 0;
min-height: 120px;
background-color: #f8f9fa;
border: 1px dashed #ced4da;
border-radius: 4px;
padding: 0.5rem;
flex-grow: 1;
overflow-y: auto;
}
/* --- Resize Handle Styles (Removed) --- */ .sidebar-pane-item {
padding: 0.5rem 0.8rem;
margin-bottom: 0.5rem;
background-color: #e9ecef;
border: 1px solid #dee2e6;
border-radius: 4px;
cursor: grab;
display: flex;
align-items: center;
justify-content: space-between;
transition: background-color 0.2s ease;
}
.sidebar-pane-item:hover {
background-color: #d8dde2;
}
.sidebar-pane-item:active {
cursor: grabbing;
background-color: #ced4da;
}
.sidebar-pane-item .drag-handle {
margin-right: 0.5rem;
color: #6c757d;
cursor: grab;
}
.sidebar-pane-item:active .drag-handle {
cursor: grabbing;
}
/* Ensure text span takes available space */
.sidebar-pane-item span {
flex-grow: 1; /* Allow text to take space */
margin-right: 0.5rem; /* Space before remove button */
overflow: hidden; /* Prevent long text overflow */
text-overflow: ellipsis;
white-space: nowrap;
}
.remove-sidebar-btn {
background: none;
border: none;
color: #adb5bd;
font-size: 1.2rem;
cursor: pointer;
padding: 0 0.3rem;
line-height: 1;
flex-shrink: 0; /* Prevent button from shrinking */
}
.remove-sidebar-btn:hover {
color: #dc3545; /* Red on hover */
}
.empty-placeholder {
text-align: center;
color: #aaa;
padding: 2rem 1rem;
font-style: italic;
font-size: 0.9em;
width: 100%;
}
.sidebar-empty {
padding: 1rem;
min-height: 50px;
display: flex;
align-items: center;
justify-content: center;
}
</style> </style>
@@ -1,12 +1,13 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, defineAsyncComponent, type PropType, type Component } from 'vue'; import { computed, defineAsyncComponent, type PropType, type Component, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; // <-- Import useI18n
// 添加依赖 font-awesome // 添加依赖 font-awesome
import '@fortawesome/fontawesome-free/css/all.min.css'; import '@fortawesome/fontawesome-free/css/all.min.css';
import { Splitpanes, Pane } from 'splitpanes'; import { Splitpanes, Pane } from 'splitpanes';
import { useLayoutStore, type LayoutNode, type PaneName } from '../stores/layout.store'; import { useLayoutStore, type LayoutNode, type PaneName } from '../stores/layout.store';
import { useSessionStore } from '../stores/session.store'; import { useSessionStore } from '../stores/session.store';
import { storeToRefs } from 'pinia'; import { storeToRefs } from 'pinia';
import { defineEmits } from 'vue'; // *** 新增:导入 defineEmits *** import { defineEmits } from 'vue';
// --- Props --- // --- Props ---
const props = defineProps({ const props = defineProps({
@@ -14,6 +15,11 @@ const props = defineProps({
type: Object as PropType<LayoutNode>, type: Object as PropType<LayoutNode>,
required: true, required: true,
}, },
// 新增:标识是否为顶层渲染器
isRootRenderer: {
type: Boolean,
default: false,
},
// 传递必要的上下文数据,避免在递归中重复获取 // 传递必要的上下文数据,避免在递归中重复获取
activeSessionId: { activeSessionId: {
type: String as PropType<string | null>, type: String as PropType<string | null>,
@@ -59,7 +65,13 @@ const emit = defineEmits({
// --- Setup --- // --- Setup ---
const layoutStore = useLayoutStore(); const layoutStore = useLayoutStore();
const sessionStore = useSessionStore(); const sessionStore = useSessionStore();
const { t } = useI18n(); // <-- Get translation function
const { activeSession } = storeToRefs(sessionStore); const { activeSession } = storeToRefs(sessionStore);
const { sidebarPanes } = storeToRefs(layoutStore);
// --- Sidebar State ---
const activeLeftSidebarPane = ref<PaneName | null>(null);
const activeRightSidebarPane = ref<PaneName | null>(null);
// --- Component Mapping --- // --- Component Mapping ---
// 使用 defineAsyncComponent 优化加载,并映射 PaneName 到实际组件 // 使用 defineAsyncComponent 优化加载,并映射 PaneName 到实际组件
@@ -76,18 +88,40 @@ const componentMap: Record<PaneName, Component> = {
}; };
// --- Computed --- // --- Computed ---
// 获取当前节点对应的组件实例 // 获取当前节点对应的组件实例 (用于主布局)
const currentComponent = computed(() => { const currentMainComponent = computed(() => {
if (props.layoutNode.type === 'pane' && props.layoutNode.component) { if (props.layoutNode.type === 'pane' && props.layoutNode.component) {
return componentMap[props.layoutNode.component] || null; return componentMap[props.layoutNode.component] || null;
} }
return null; return null;
}); });
// 为特定组件计算需要传递的 Props // 获取当前激活的左侧侧栏组件实例
const currentLeftSidebarComponent = computed(() => {
return activeLeftSidebarPane.value ? componentMap[activeLeftSidebarPane.value] : null;
});
// 获取当前激活的右侧侧栏组件实例
const currentRightSidebarComponent = computed(() => {
return activeRightSidebarPane.value ? componentMap[activeRightSidebarPane.value] : null;
});
// 面板标签 (Similar to LayoutConfigurator)
const paneLabels = computed(() => ({
connections: t('layout.pane.connections', '连接列表'),
terminal: t('layout.pane.terminal', '终端'),
commandBar: t('layout.pane.commandBar', '命令栏'),
fileManager: t('layout.pane.fileManager', '文件管理器'),
editor: t('layout.pane.editor', '编辑器'),
statusMonitor: t('layout.pane.statusMonitor', '状态监视器'),
commandHistory: t('layout.pane.commandHistory', '命令历史'),
quickCommands: t('layout.pane.quickCommands', '快捷指令'),
dockerManager: t('layout.pane.dockerManager', 'Docker 管理器'),
}));
// 为特定组件计算需要传递的 Props (主布局)
// 注意:这是一个简化示例,实际可能需要更复杂的逻辑来传递正确的 props // 注意:这是一个简化示例,实际可能需要更复杂的逻辑来传递正确的 props
// 例如,Terminal, FileManager, StatusMonitor 需要当前 activeSession 的数据
// Editor 需要根据共享模式决定数据来源
const componentProps = computed(() => { const componentProps = computed(() => {
const componentName = props.layoutNode.component; const componentName = props.layoutNode.component;
const currentActiveSession = activeSession.value; // 获取当前活动会话 const currentActiveSession = activeSession.value; // 获取当前活动会话
@@ -193,9 +227,32 @@ const componentProps = computed(() => {
} }
}); });
// 为侧栏组件计算 Props (可能需要简化或根据组件调整)
const sidebarComponentProps = computed(() => (paneName: PaneName | null) => {
if (!paneName) return {};
// 侧栏组件通常不需要像主布局那样复杂的事件转发和 session 依赖
// 这里可以返回一个通用的 props 对象,或者根据 paneName 返回特定 props
// 示例:只传递 class
return { class: 'sidebar-pane-content' };
// 如果侧栏组件也需要 session 信息或事件:
/*
switch (paneName) {
case 'connections':
return {
class: 'sidebar-pane-content',
onConnectRequest: (id: number) => emit('connect-request', id),
// ... 其他 connections 需要的 props
};
// ... 其他 case
default:
return { class: 'sidebar-pane-content' };
}
*/
});
// --- Methods --- // --- Methods ---
// 处理 Splitpanes 大小调整事件,更新 layoutStore 中的节点 size // 处理 Splitpanes 大小调整事件
// @resized 事件参数是一个包含 panes 数组的对象
const handlePaneResize = (eventData: { panes: Array<{ size: number; [key: string]: any }> }) => { const handlePaneResize = (eventData: { panes: Array<{ size: number; [key: string]: any }> }) => {
console.log('Splitpanes resized event object:', eventData); // 打印整个事件对象 console.log('Splitpanes resized event object:', eventData); // 打印整个事件对象
const paneSizes = eventData.panes; // 从事件对象中提取 panes 数组 const paneSizes = eventData.panes; // 从事件对象中提取 panes 数组
@@ -219,151 +276,319 @@ const handlePaneResize = (eventData: { panes: Array<{ size: number; [key: string
} }
}; };
// 打开/切换侧栏面板
const toggleSidebarPane = (side: 'left' | 'right', paneName: PaneName) => {
if (side === 'left') {
activeLeftSidebarPane.value = activeLeftSidebarPane.value === paneName ? null : paneName;
if (activeLeftSidebarPane.value) activeRightSidebarPane.value = null; // Close other side
} else {
activeRightSidebarPane.value = activeRightSidebarPane.value === paneName ? null : paneName;
if (activeRightSidebarPane.value) activeLeftSidebarPane.value = null; // Close other side
}
};
// 关闭所有侧栏
const closeSidebars = () => {
activeLeftSidebarPane.value = null;
activeRightSidebarPane.value = null;
};
// 监听 activeSessionId 的变化,如果会话切换,则关闭侧栏 (可选行为)
watch(() => props.activeSessionId, () => {
// closeSidebars(); // 取消注释以在切换会话时关闭侧栏
});
// --- Debug Watcher for sidebarPanes from store ---
watch(sidebarPanes, (newVal) => {
console.log('[LayoutRenderer] Received updated sidebarPanes from store:', JSON.parse(JSON.stringify(newVal)));
}, { deep: true, immediate: true }); // Immediate to log initial value
// --- Icon Helper ---
const getIconClasses = (paneName: PaneName): string[] => {
switch (paneName) {
case 'connections': return ['fas', 'fa-network-wired'];
case 'fileManager': return ['fas', 'fa-folder-open'];
case 'commandHistory': return ['fas', 'fa-history'];
case 'quickCommands': return ['fas', 'fa-bolt'];
case 'dockerManager': return ['fab', 'fa-docker']; // Use 'fab' for Docker
case 'editor': return ['fas', 'fa-file-alt'];
case 'statusMonitor': return ['fas', 'fa-tachometer-alt'];
// Add other specific icons here if needed
default: return ['fas', 'fa-question-circle']; // Default icon
}
};
</script> </script>
<template> <template>
<div class="layout-renderer" :data-node-id="layoutNode.id"> <div class="layout-renderer-wrapper">
<!-- 如果是容器节点 --> <!-- Left Sidebar Buttons (Only render if root) -->
<template v-if="layoutNode.type === 'container' && layoutNode.children && layoutNode.children.length > 0"> <div class="sidebar-buttons left-sidebar-buttons" v-if="isRootRenderer && sidebarPanes.left.length > 0">
<splitpanes <button
:horizontal="layoutNode.direction === 'vertical'" v-for="pane in sidebarPanes.left"
class="default-theme" :key="`left-${pane}`"
style="height: 100%; width: 100%;" @click="toggleSidebarPane('left', pane)"
@resized="handlePaneResize" :class="{ active: activeLeftSidebarPane === pane }"
> :title="paneLabels[pane] || pane"
<pane
v-for="childNode in layoutNode.children"
:key="childNode.id"
:size="childNode.size ?? (100 / layoutNode.children.length)"
:min-size="5"
class="layout-pane-wrapper"
> >
<!-- 递归调用自身来渲染子节点并转发所有必要的事件 --> <!-- Use helper function for icons -->
<LayoutRenderer <i :class="getIconClasses(pane)"></i>
:layout-node="childNode" </button>
:active-session-id="activeSessionId" </div>
:editor-tabs="editorTabs"
:active-editor-tab-id="activeEditorTabId"
@send-command="emit('sendCommand', $event)"
@terminal-input="emit('terminalInput', $event)"
@terminal-resize="emit('terminalResize', $event)"
@terminal-ready="emit('terminal-ready', $event)"
@close-editor-tab="emit('closeEditorTab', $event)"
@activate-editor-tab="emit('activateEditorTab', $event)"
@update-editor-content="emit('updateEditorContent', $event)"
@save-editor-tab="emit('saveEditorTab', $event)"
@connect-request="emit('connect-request', $event)"
@open-new-session="emit('open-new-session', $event)"
@request-add-connection="() => { // 添加日志
console.log(`[LayoutRenderer ${props.layoutNode.id}] Received recursive 'request-add-connection', emitting upwards.`);
emit('request-add-connection');
}"
@request-edit-connection="emit('request-edit-connection', $event)"
@search="emit('search', $event)"
@find-next="emit('find-next')"
@find-previous="emit('find-previous')"
@close-search="emit('close-search')"
/>
</pane>
</splitpanes>
</template>
<!-- 如果是面板节点 --> <!-- Main Layout Area -->
<template v-else-if="layoutNode.type === 'pane'"> <div class="main-layout-area">
<!-- Terminal 需要 keep-alive 处理 --> <div class="layout-renderer" :data-node-id="layoutNode.id">
<template v-if="layoutNode.component === 'terminal'"> <!-- 如果是容器节点 -->
<keep-alive> <template v-if="layoutNode.type === 'container' && layoutNode.children && layoutNode.children.length > 0">
<component <splitpanes
v-if="activeSession" :horizontal="layoutNode.direction === 'vertical'"
:is="currentComponent" class="default-theme"
:key="activeSessionId" style="height: 100%; width: 100%;"
v-bind="componentProps" @resized="handlePaneResize"
>
<pane
v-for="childNode in layoutNode.children"
:key="childNode.id"
:size="childNode.size ?? (100 / layoutNode.children.length)"
:min-size="5"
class="layout-pane-wrapper"
>
<!-- 递归调用自身来渲染子节点并转发所有必要的事件 -->
<LayoutRenderer
:layout-node="childNode"
:is-root-renderer="false"
:active-session-id="activeSessionId"
:editor-tabs="editorTabs"
:active-editor-tab-id="activeEditorTabId"
@send-command="emit('sendCommand', $event)"
@terminal-input="emit('terminalInput', $event)"
@terminal-resize="emit('terminalResize', $event)"
@terminal-ready="emit('terminal-ready', $event)"
@close-editor-tab="emit('closeEditorTab', $event)"
@activate-editor-tab="emit('activateEditorTab', $event)"
@update-editor-content="emit('updateEditorContent', $event)"
@save-editor-tab="emit('saveEditorTab', $event)"
@connect-request="emit('connect-request', $event)"
@open-new-session="emit('open-new-session', $event)"
@request-add-connection="() => { // 添加日志
console.log(`[LayoutRenderer ${props.layoutNode.id}] Received recursive 'request-add-connection', emitting upwards.`);
emit('request-add-connection');
}"
@request-edit-connection="emit('request-edit-connection', $event)"
@search="emit('search', $event)"
@find-next="emit('find-next')"
@find-previous="emit('find-previous')"
@close-search="emit('close-search')"
/> />
</keep-alive> </pane>
<div v-if="!activeSession" class="pane-placeholder empty-session"> </splitpanes>
<div class="empty-session-content"> </template>
<i class="fas fa-terminal-slash"></i>
<i class="fas fa-plug"></i> <!-- 如果是面板节点 -->
<span>无活动会话</span> <template v-else-if="layoutNode.type === 'pane'">
<div class="empty-session-tip">请先连接一个会话</div> <!-- Terminal 需要 keep-alive 处理 -->
</div> <template v-if="layoutNode.component === 'terminal'">
</div> <keep-alive>
</template> <component
<!-- FileManager 需要 keep-alive 处理 --> v-if="activeSession"
<template v-else-if="layoutNode.component === 'fileManager'"> :is="currentMainComponent"
<keep-alive> :key="activeSessionId"
<component v-bind="componentProps"
v-if="activeSession" />
:is="currentComponent" </keep-alive>
:key="activeSessionId" <div v-if="!activeSession" class="pane-placeholder empty-session">
v-bind="componentProps" <div class="empty-session-content">
/> <i class="fas fa-plug"></i>
</keep-alive> <span>无活动会话</span>
<div v-if="!activeSession" class="pane-placeholder empty-session"> <div class="empty-session-tip">请先连接一个会话</div>
<div class="empty-session-content"> </div>
<i class="fas fa-plug"></i> </div>
<span>无活动会话</span> </template>
<div class="empty-session-tip">请先连接一个会话</div> <!-- FileManager 需要 keep-alive 处理 -->
</div> <template v-else-if="layoutNode.component === 'fileManager'">
</div> <keep-alive>
</template> <component
<!-- StatusMonitor 仅在有活动会话时渲染,并添加 key (无 keep-alive) --> v-if="activeSession"
<template v-else-if="layoutNode.component === 'statusMonitor'"> :is="currentMainComponent"
<component :key="activeSessionId"
v-if="activeSession" v-bind="componentProps"
:is="currentComponent" />
:key="activeSessionId" </keep-alive>
v-bind="componentProps" <div v-if="!activeSession" class="pane-placeholder empty-session">
/> <div class="empty-session-content">
<div v-else class="pane-placeholder empty-session"> <i class="fas fa-plug"></i>
<div class="empty-session-content"> <span>无活动会话</span>
<i class="fas fa-plug"></i> <div class="empty-session-tip">请先连接一个会话</div>
<span>无活动会话</span> </div>
<div class="empty-session-tip">请先连接一个会话</div> </div>
</div> </template>
</div> <!-- StatusMonitor 仅在有活动会话时渲染,并添加 key (无 keep-alive) -->
</template> <template v-else-if="layoutNode.component === 'statusMonitor'">
<!-- 其他面板正常渲染 (不依赖 activeSession 的) --> <component
<template v-else-if="currentComponent"> v-if="activeSession"
<!-- 特别处理 connections 组件以添加事件监听器 --> :is="currentMainComponent"
<component :key="activeSessionId"
v-if="layoutNode.component === 'connections'" v-bind="componentProps"
:is="currentComponent" />
v-bind="componentProps" <div v-else class="pane-placeholder empty-session">
@request-add-connection="() => { <div class="empty-session-content">
console.log(`[LayoutRenderer ${props.layoutNode.id}] Template received 'request-add-connection', emitting upwards.`); <i class="fas fa-plug"></i>
emit('request-add-connection'); <span>无活动会话</span>
}" <div class="empty-session-tip">请先连接一个会话</div>
/> </div>
<!-- 渲染 CommandInputBar --> </div>
<component </template>
v-else-if="layoutNode.component === 'commandBar'" <!-- 其他面板正常渲染 (不依赖 activeSession 的) -->
:is="currentComponent" <template v-else-if="currentMainComponent">
v-bind="componentProps" <!-- 特别处理 connections 组件以添加事件监听器 -->
/> <component
<!-- 渲染其他组件 --> v-if="layoutNode.component === 'connections'"
<component :is="currentMainComponent"
v-else v-bind="componentProps"
:is="currentComponent" @request-add-connection="() => {
v-bind="componentProps" console.log(`[LayoutRenderer ${props.layoutNode.id}] Template received 'request-add-connection', emitting upwards.`);
/> emit('request-add-connection');
</template> }"
<!-- 如果找不到组件 --> />
<div v-else class="pane-placeholder error"> <!-- 渲染 CommandInputBar -->
无效面板组件: {{ layoutNode.component || '未指定' }} (ID: {{ layoutNode.id }}) <component
v-else-if="layoutNode.component === 'commandBar'"
:is="currentMainComponent"
v-bind="componentProps"
/>
<!-- 渲染其他组件 -->
<component
v-else
:is="currentMainComponent"
v-bind="componentProps"
/>
</template>
<!-- 如果找不到主布局组件 -->
<div v-else class="pane-placeholder error">
无效面板组件: {{ layoutNode.component || '未指定' }} (ID: {{ layoutNode.id }})
</div>
</template>
<!-- 如果节点类型未知或无效 -->
<template v-else>
<div class="pane-placeholder error">
无效布局节点 (ID: {{ layoutNode.id }})
</div>
</template>
</div> </div>
</template> </div>
<!-- Sidebar Panels Overlay -->
<div
v-if="activeLeftSidebarPane || activeRightSidebarPane"
class="sidebar-overlay"
@click="closeSidebars"
></div>
<!-- Left Sidebar Panel -->
<div :class="['sidebar-panel', 'left-sidebar-panel', { active: !!activeLeftSidebarPane }]">
<button class="close-sidebar-btn" @click="closeSidebars" title="Close Sidebar">&times;</button>
<component
v-if="currentLeftSidebarComponent"
:is="currentLeftSidebarComponent"
:key="`left-panel-${activeLeftSidebarPane}`"
v-bind="sidebarComponentProps(activeLeftSidebarPane)"
/>
</div>
<!-- Right Sidebar Panel -->
<div :class="['sidebar-panel', 'right-sidebar-panel', { active: !!activeRightSidebarPane }]">
<button class="close-sidebar-btn" @click="closeSidebars" title="Close Sidebar">&times;</button>
<component
v-if="currentRightSidebarComponent"
:is="currentRightSidebarComponent"
:key="`right-panel-${activeRightSidebarPane}`"
v-bind="sidebarComponentProps(activeRightSidebarPane)"
/>
</div>
<!-- Right Sidebar Buttons (Only render if root) -->
<div class="sidebar-buttons right-sidebar-buttons" v-if="isRootRenderer && sidebarPanes.right.length > 0">
<button
v-for="pane in sidebarPanes.right"
:key="`right-${pane}`"
@click="toggleSidebarPane('right', pane)"
:class="{ active: activeRightSidebarPane === pane }"
:title="paneLabels[pane] || pane"
>
<!-- Use helper function for icons -->
<i :class="getIconClasses(pane)"></i>
</button>
</div>
<!-- 如果节点类型未知或无效 -->
<template v-else>
<div class="pane-placeholder error">
无效布局节点 (ID: {{ layoutNode.id }})
</div>
</template>
</div> </div>
</template> </template>
<style scoped> <style scoped>
.layout-renderer-wrapper {
position: relative; /* Needed for absolute positioning of sidebars */
display: flex;
height: 100%;
width: 100%;
overflow: hidden;
}
.sidebar-buttons {
display: flex;
flex-direction: column;
background-color: var(--sidebar-bg-color, #f8f9fa); /* Use theme variable or default */
padding: 5px 0;
z-index: 10; /* Above main layout but below panels */
flex-shrink: 0; /* Prevent buttons from shrinking */
}
.left-sidebar-buttons {
border-right: 1px solid var(--border-color, #dee2e6);
}
.right-sidebar-buttons {
border-left: 1px solid var(--border-color, #dee2e6);
}
.sidebar-buttons button {
background: none;
border: none;
color: var(--text-color-secondary, #6c757d);
padding: 10px 8px;
cursor: pointer;
font-size: 1.1rem; /* Slightly smaller icons */
line-height: 1;
transition: background-color 0.2s, color 0.2s;
display: flex;
justify-content: center;
align-items: center;
width: 40px; /* Fixed width for buttons */
height: 40px; /* Fixed height for buttons */
margin-bottom: 4px; /* Space between buttons */
}
.sidebar-buttons button:hover {
background-color: var(--hover-bg-color, #e9ecef);
color: var(--text-color-primary, #343a40);
}
.sidebar-buttons button.active {
background-color: var(--primary-color, #007bff);
color: white;
}
.sidebar-buttons button.active:hover {
background-color: var(--primary-color-dark, #0056b3); /* Darker primary on hover when active */
}
.main-layout-area {
flex-grow: 1;
height: 100%;
overflow: hidden; /* Prevent main layout from overflowing */
position: relative; /* Needed for potential internal absolute elements */
}
.layout-renderer { .layout-renderer {
height: 100%; height: 100%;
width: 100%; width: 100%;
@@ -447,14 +672,114 @@ const handlePaneResize = (eventData: { panes: Array<{ size: number; [key: string
} }
/* Splitpanes 默认主题样式调整 (如果需要覆盖全局样式) */ /* Sidebar Panel Styles */
/* :deep(.splitpanes.default-theme .splitpanes__splitter) { */ .sidebar-overlay {
/* background-color: #ccc; */ position: fixed; /* Use fixed to cover the whole viewport */
/* } */ top: 0;
/* :deep(.splitpanes--vertical > .splitpanes__splitter) { */ left: 0;
/* width: 7px; */ width: 100%;
/* } */ height: 100%;
/* :deep(.splitpanes--horizontal > .splitpanes__splitter) { */ background-color: rgba(0, 0, 0, 0.4);
/* height: 7px; */ z-index: 100; /* Below panel, above main content */
/* } */ opacity: 0;
visibility: hidden;
transition: opacity 0.3s ease, visibility 0s linear 0.3s;
}
/* Show overlay when either panel is active */
.layout-renderer-wrapper:has(.sidebar-panel.active) .sidebar-overlay {
opacity: 1;
visibility: visible;
transition: opacity 0.3s ease, visibility 0s linear 0s;
}
.sidebar-panel {
position: fixed; /* Use fixed for viewport positioning */
top: 0; /* Adjust if you have a fixed header */
bottom: 0; /* Adjust if you have a fixed footer */
width: 350px; /* Adjust width as needed */
max-width: 80vw;
background-color: var(--app-bg-color, white);
/* box-shadow: 0 0 15px rgba(0, 0, 0, 0.2); */ /* <-- 移除阴影以隐藏边缘 */
z-index: 110; /* Above overlay */
transform: translateX(-100%); /* Start hidden */
transition: transform 0.3s ease-in-out;
display: flex;
flex-direction: column;
overflow: hidden; /* Prevent content overflow */
}
.left-sidebar-panel {
left: 0;
transform: translateX(-100%);
border-right: 1px solid var(--border-color, #dee2e6);
}
.left-sidebar-panel.active {
transform: translateX(0);
}
.right-sidebar-panel {
right: 0;
transform: translateX(100%);
border-left: 1px solid var(--border-color, #dee2e6);
}
.right-sidebar-panel.active {
transform: translateX(0);
}
.close-sidebar-btn {
position: absolute;
top: 5px;
right: 10px;
background: none;
border: none;
font-size: 1.8rem;
color: var(--text-color-secondary, #aaa);
cursor: pointer;
padding: 0;
line-height: 1;
z-index: 1; /* Above panel content */
}
.close-sidebar-btn:hover {
color: var(--text-color-primary, #333);
}
/* Style for the content inside the sidebar panel */
:deep(.sidebar-pane-content) {
flex-grow: 1;
overflow-y: auto; /* Allow scrolling within the panel */
padding: 1rem; /* Add some padding */
padding-top: 2.5rem; /* Add padding to avoid close button overlap */
}
</style>
<style> /* Global styles for splitpanes if needed, or scoped with :deep() */
.splitpanes.default-theme .splitpanes__pane {
background-color: var(--app-bg-color); /* Ensure panes match app background */
}
.splitpanes.default-theme .splitpanes__splitter {
background-color: var(--border-color, #dee2e6);
border-left: 1px solid var(--border-color-lighter, #f1f3f5); /* Example lighter border */
border-right: 1px solid var(--border-color-darker, #ced4da); /* Example darker border */
box-sizing: border-box;
transition: background-color 0.2s ease-out;
}
.splitpanes.default-theme .splitpanes__splitter:hover {
background-color: var(--primary-color-light, #a0cfff); /* Lighter primary on hover */
}
.splitpanes.default-theme .splitpanes__splitter::before,
.splitpanes.default-theme .splitpanes__splitter::after {
background-color: var(--text-color-secondary, #6c757d); /* Adjust handle color */
}
.splitpanes--vertical > .splitpanes__splitter {
width: 6px; /* Adjust width */
border-left: 1px solid var(--border-color-darker, #ced4da);
border-right: 1px solid var(--border-color-lighter, #f1f3f5);
}
.splitpanes--horizontal > .splitpanes__splitter {
height: 6px; /* Adjust height */
border-top: 1px solid var(--border-color-darker, #ced4da);
border-bottom: 1px solid var(--border-color-lighter, #f1f3f5);
}
</style> </style>
+9 -4
View File
@@ -675,12 +675,17 @@
"remove": "移除" "remove": "移除"
}, },
"layoutConfigurator": { "layoutConfigurator": {
"title": "布局配置器", "title": "配置工作区布局",
"availablePanes": "可用面板", "availablePanes": "可用面板",
"layoutPreview": "布局预览", "layoutPreview": "布局预览(拖拽到此处)",
"resetDefault": "重置为默认布局", "resetDefault": "恢复默认",
"noAvailablePanes": "所有面板都已在布局中", "noAvailablePanes": "所有面板都已在布局中",
"emptyLayout": "布局为空,请从左侧拖拽面板或添加容器。" "emptyLayout": "布局为空,请从左侧拖拽面板或添加容器。",
"leftSidebar": "左侧栏面板",
"rightSidebar": "右侧栏面板",
"dropHere": "从可用面板拖拽到此处",
"confirmClose": "有未保存的更改,确定要关闭吗?",
"confirmReset": "确定要恢复默认布局和侧栏配置吗?当前更改将丢失。"
}, },
"auditLog": { "auditLog": {
"title": "审计日志", "title": "审计日志",
+257 -93
View File
@@ -18,6 +18,7 @@ export interface LayoutNode {
// 本地存储的 Key // 本地存储的 Key
const LAYOUT_STORAGE_KEY = 'nexus_terminal_layout_config'; const LAYOUT_STORAGE_KEY = 'nexus_terminal_layout_config';
const SIDEBAR_STORAGE_KEY = 'nexus_terminal_sidebar_config'; // 新增侧栏配置 Key
// 生成唯一 ID 的辅助函数 // 生成唯一 ID 的辅助函数
function generateId(): string { function generateId(): string {
@@ -67,8 +68,14 @@ const getDefaultLayout = (): LayoutNode => ({
], ],
}); });
// 递归查找布局树中所有使用的面板组件名称 // 定义默认侧栏配置
function getUsedPaneNames(node: LayoutNode | null): Set<PaneName> { const getDefaultSidebarPanes = (): { left: PaneName[], right: PaneName[] } => ({
left: [],
right: [],
});
// 递归查找主布局树中使用的面板
function getMainLayoutUsedPaneNames(node: LayoutNode | null): Set<PaneName> {
const usedNames = new Set<PaneName>(); const usedNames = new Set<PaneName>();
if (!node) return usedNames; if (!node) return usedNames;
@@ -84,12 +91,43 @@ function getUsedPaneNames(node: LayoutNode | null): Set<PaneName> {
return usedNames; return usedNames;
} }
// 获取所有使用的面板(主布局 + 侧栏)
function getAllUsedPaneNames(mainNode: LayoutNode | null, sidebars: { left: PaneName[], right: PaneName[] }): Set<PaneName> {
const usedNames = getMainLayoutUsedPaneNames(mainNode);
sidebars.left.forEach(pane => usedNames.add(pane));
sidebars.right.forEach(pane => usedNames.add(pane));
return usedNames;
}
// --- Validation Helper ---
// Checks if a value is a valid PaneName
function isValidPaneName(value: any, allPanes: PaneName[]): value is PaneName {
return typeof value === 'string' && allPanes.includes(value as PaneName);
}
// Checks if an array contains only unique, valid PaneName strings
function isValidPaneNameArray(arr: any, allPanes: PaneName[]): arr is PaneName[] {
if (!Array.isArray(arr)) return false;
const seen = new Set<PaneName>();
for (const item of arr) {
if (!isValidPaneName(item, allPanes) || seen.has(item)) {
return false; // Not a valid PaneName or duplicate found
}
seen.add(item);
}
return true; // All items are unique and valid PaneNames
}
// 定义 Store // 定义 Store
export const useLayoutStore = defineStore('layout', () => { export const useLayoutStore = defineStore('layout', () => {
// --- 状态 --- // --- 状态 ---
// 核心状态:存储当前布局树结构 // 布局树结构
const layoutTree: Ref<LayoutNode | null> = ref(null); const layoutTree: Ref<LayoutNode | null> = ref(null);
// 存储所有理论上可用的面板名称 // 侧栏面板配置
const sidebarPanes: Ref<{ left: PaneName[], right: PaneName[] }> = ref(getDefaultSidebarPanes());
// 所有理论上可用的面板名称
const allPossiblePanes: Ref<PaneName[]> = ref([ const allPossiblePanes: Ref<PaneName[]> = ref([
'connections', 'terminal', 'commandBar', 'fileManager', 'connections', 'terminal', 'commandBar', 'fileManager',
'editor', 'statusMonitor', 'commandHistory', 'quickCommands', 'editor', 'statusMonitor', 'commandHistory', 'quickCommands',
@@ -101,73 +139,154 @@ export const useLayoutStore = defineStore('layout', () => {
const isHeaderVisible: Ref<boolean> = ref(true); // 默认可见 const isHeaderVisible: Ref<boolean> = ref(true); // 默认可见
// --- 计算属性 --- // --- 计算属性 ---
// 计算当前布局中正在使用的面板 // 计算当前布局和侧栏中正在使用的所有面板
const usedPanes: ComputedRef<Set<PaneName>> = computed(() => getUsedPaneNames(layoutTree.value)); const usedPanes: ComputedRef<Set<PaneName>> = computed(() => getAllUsedPaneNames(layoutTree.value, sidebarPanes.value));
// 计算当前未在布局中使用的面板(可用于配置器中添加) // 计算当前未在布局或侧栏中使用的面板(可用于配置器中添加)
const availablePanes: ComputedRef<PaneName[]> = computed(() => { const availablePanes: ComputedRef<PaneName[]> = computed(() => {
const used = usedPanes.value; const used = usedPanes.value;
return allPossiblePanes.value.filter(pane => !used.has(pane)); return allPossiblePanes.value.filter(pane => !used.has(pane));
}); });
// --- Actions --- // --- Actions ---
// 初始化布局:优先尝试从后端加载,然后 localStorage,最后默认布局 // 初始化布局和侧栏配置
async function initializeLayout() { async function initializeLayout() {
let loadedFromBackend = false; let layoutLoadedFromBackend = false;
// 1. 尝试从后端加载 let sidebarLoadedFromBackend = false;
// 1. 尝试从后端加载主布局
try { try {
console.log('[Layout Store] Attempting to load layout from backend...'); console.log('[Layout Store] Attempting to load layout from backend...');
const response = await apiClient.get<LayoutNode | null>('/settings/layout'); // 使用 apiClient const response = await apiClient.get<LayoutNode | null>('/settings/layout'); // 使用 apiClient
if (response.data) { if (response.data) {
// TODO: 在这里添加对 response.data 的结构验证,确保它符合 LayoutNode 接口 // TODO: 在这里添加对 response.data 的结构验证,确保它符合 LayoutNode 接口
layoutTree.value = response.data; layoutTree.value = response.data;
loadedFromBackend = true; layoutLoadedFromBackend = true;
console.log('[Layout Store] 从后端加载布局成功。'); console.log('[Layout Store] 主布局从后端加载成功。');
// 可选:如果后端加载成功,可以更新 localStorage // 更新 localStorage
try { try {
localStorage.setItem(LAYOUT_STORAGE_KEY, JSON.stringify(response.data)); localStorage.setItem(LAYOUT_STORAGE_KEY, JSON.stringify(response.data));
} catch (lsError) { } catch (lsError) {
console.error('[Layout Store] 保存后端布局到 localStorage 失败:', lsError); console.error('[Layout Store] 保存后端布局到 localStorage 失败:', lsError);
} }
} else { } else {
console.log('[Layout Store] 后端未返回布局数据。'); console.log('[Layout Store] 后端未返回布局数据。');
} }
} catch (error) { } catch (error) {
console.error('[Layout Store] 从后端加载布局失败:', error); console.error('[Layout Store] 从后端加载布局失败:', error);
// 加载失败,继续尝试 localStorage
} }
// 2. 如果后端加载成功,尝试从 localStorage 加载 // 2. 尝试从后端加载侧栏配置 (假设 API 端点为 /settings/sidebar)
if (!loadedFromBackend) { try {
console.log('[Layout Store] Attempting to load layout from localStorage...'); console.log('[Layout Store] Attempting to load sidebar config from backend...');
const response = await apiClient.get<{ left: any[], right: any[] } | null>('/settings/sidebar'); // Load as any[] first
// --- Add Validation ---
if (response.data &&
isValidPaneNameArray(response.data.left, allPossiblePanes.value) &&
isValidPaneNameArray(response.data.right, allPossiblePanes.value))
{
sidebarPanes.value = response.data as { left: PaneName[], right: PaneName[] }; // Cast after validation
sidebarLoadedFromBackend = true;
console.log('[Layout Store] 侧栏配置从后端加载成功并通过验证。');
// 更新 localStorage
try {
localStorage.setItem(SIDEBAR_STORAGE_KEY, JSON.stringify(response.data));
} catch (lsError) {
console.error('[Layout Store] 保存后端侧栏配置到 localStorage 失败:', lsError);
}
} else { // Handles the case where the 'if' at line 184 failed
if (response.data) { // Check if data existed but failed validation
console.log('[Layout Store] 后端返回的侧栏配置数据格式无效或包含无效/重复面板名称。');
} else { // No data was returned from the backend
console.log('[Layout Store] 后端未返回侧栏配置数据。');
}
}
} catch (error) {
console.error('[Layout Store] 从后端加载侧栏配置失败:', error);
}
// 3. 如果主布局后端未加载成功,尝试从 localStorage 加载
if (!layoutLoadedFromBackend) {
console.log('[Layout Store] Attempting to load main layout from localStorage...');
try { try {
const savedLayout = localStorage.getItem(LAYOUT_STORAGE_KEY); const savedLayout = localStorage.getItem(LAYOUT_STORAGE_KEY);
if (savedLayout) { if (savedLayout) {
const parsedLayout = JSON.parse(savedLayout) as LayoutNode; const parsedLayout = JSON.parse(savedLayout) as LayoutNode;
// TODO: 添加验证逻辑确保加载的布局结构有效 // TODO: 添加验证逻辑
layoutTree.value = parsedLayout; layoutTree.value = parsedLayout;
console.log('[Layout Store] 从 localStorage 加载布局成功。'); console.log('[Layout Store] 主布局从 localStorage 加载成功。');
} else { } else {
// 3. 如果 localStorage 也没有,使用默认布局 // 4. 如果 localStorage 也没有,使用默认布局
layoutTree.value = getDefaultLayout(); layoutTree.value = getDefaultLayout();
console.log('[Layout Store] 未找到保存的布局,使用默认布局。'); console.log('[Layout Store] 未找到保存的布局,使用默认布局。');
} }
} catch (error) { } catch (error) {
console.error('[Layout Store] 从 localStorage 加载或解析布局失败:', error); console.error('[Layout Store] 从 localStorage 加载或解析布局失败:', error);
layoutTree.value = getDefaultLayout(); // 出错时回退到默认布局 layoutTree.value = getDefaultLayout();
} }
} }
// 5. 如果侧栏配置后端未加载成功,尝试从 localStorage 加载
if (!sidebarLoadedFromBackend) {
console.log('[Layout Store] Attempting to load sidebar config from localStorage...');
try {
const savedSidebars = localStorage.getItem(SIDEBAR_STORAGE_KEY);
if (savedSidebars) {
const parsedSidebars = JSON.parse(savedSidebars) as { left: any[], right: any[] }; // Parse as any[] first
// --- Add Validation ---
if (parsedSidebars &&
isValidPaneNameArray(parsedSidebars.left, allPossiblePanes.value) &&
isValidPaneNameArray(parsedSidebars.right, allPossiblePanes.value))
{
sidebarPanes.value = parsedSidebars as { left: PaneName[], right: PaneName[] }; // Cast after validation
console.log('[Layout Store] 侧栏配置从 localStorage 加载成功并通过验证。');
} else {
console.warn('[Layout Store] localStorage 中的侧栏配置格式无效或包含无效/重复面板名称,使用默认值。');
sidebarPanes.value = getDefaultSidebarPanes();
}
} else {
// 6. 如果 localStorage 也没有,使用默认侧栏配置
sidebarPanes.value = getDefaultSidebarPanes();
console.log('[Layout Store] 未找到保存的侧栏配置,使用默认配置。');
}
} catch (error) {
console.error('[Layout Store] 从 localStorage 加载或解析侧栏配置失败:', error);
sidebarPanes.value = getDefaultSidebarPanes();
}
}
} }
// 更新整个布局树(通常由配置器保存时调用) // 更新整个布局树(通常由配置器保存时调用)
function updateLayoutTree(newTree: LayoutNode) { function updateLayoutTree(newTree: LayoutNode | null) { // <-- Allow null
// 可选:添加验证逻辑 // 可选:添加验证逻辑 (如果 newTree 不是 null)
layoutTree.value = newTree; if (newTree) {
console.log('[Layout Store] 布局树已更新。'); // TODO: Add validation for LayoutNode structure if needed
}
layoutTree.value = newTree; // Assign null or the new tree
console.log('[Layout Store] 布局树已更新。 New tree:', newTree);
// 保存将在 watch 中自动触发 // 保存将在 watch 中自动触发
} }
// 新增:递归查找并更新节点大小 // 新增:更新侧栏配置
function updateSidebarPanes(newPanes: { left: PaneName[], right: PaneName[] }) {
// --- Add Validation ---
if (newPanes &&
isValidPaneNameArray(newPanes.left, allPossiblePanes.value) &&
isValidPaneNameArray(newPanes.right, allPossiblePanes.value))
{
sidebarPanes.value = newPanes as { left: PaneName[], right: PaneName[] }; // Assign validated data
// Log the value immediately after update
console.log('[Layout Store] 侧栏配置已通过验证并更新。 New sidebarPanes value:', JSON.parse(JSON.stringify(sidebarPanes.value)));
// 保存将在 watch 中自动触发
} else {
console.error('[Layout Store] updateSidebarPanes 接收到无效的侧栏配置数据,未更新状态:', newPanes);
// 可选:抛出错误或通知用户
}
}
// 递归查找并更新节点大小
function findAndUpdateNodeSize(node: LayoutNode | null, nodeId: string, childrenSizes: { index: number; size: number }[]): LayoutNode | null { function findAndUpdateNodeSize(node: LayoutNode | null, nodeId: string, childrenSizes: { index: number; size: number }[]): LayoutNode | null {
if (!node) return null; if (!node) return null;
if (node.id === nodeId && node.type === 'container' && node.children) { if (node.id === nodeId && node.type === 'container' && node.children) {
@@ -257,84 +376,129 @@ export const useLayoutStore = defineStore('layout', () => {
return getDefaultLayout(); // 直接调用内部函数 return getDefaultLayout(); // 直接调用内部函数
} }
// 新增 Action: 将当前布局树持久化到后端和 localStorage // 新增 Action: 获取系统内置的默认侧栏配置
function getSystemDefaultSidebarPanes(): { left: PaneName[], right: PaneName[] } {
console.log('[Layout Store] Getting system default sidebar panes.');
return getDefaultSidebarPanes();
}
// 新增 Action: 将当前主布局树持久化到后端和 localStorage
async function persistLayoutTree() { async function persistLayoutTree() {
if (!layoutTree.value) { if (!layoutTree.value) {
console.warn('[Layout Store] persistLayoutTree: layoutTree is null, cannot persist.'); console.warn('[Layout Store] persistLayoutTree: layoutTree is null, cannot persist.');
// 可选:如果布局为空,是否也通知后端?或者删除后端设置 // TODO: 考虑是否需要删除后端设置或发送空布局
// await axios.delete('/api/v1/settings/layout'); // 示例:删除后端设置 // await apiClient.put('/settings/layout', null); // 发送 null 或空对象
localStorage.removeItem(LAYOUT_STORAGE_KEY); // 保持移除本地存储 localStorage.removeItem(LAYOUT_STORAGE_KEY);
return; return;
} }
const layoutToSave = JSON.stringify(layoutTree.value); const layoutToSave = JSON.stringify(layoutTree.value);
// 1. 保存到后端 // 1. 保存到后端
try { try {
console.log('[Layout Store] Attempting to save layout to backend...'); console.log('[Layout Store] Attempting to save main layout to backend...');
await apiClient.put('/settings/layout', layoutTree.value); // 使用 apiClient // Send the layoutTree value directly (which can be null)
console.log('[Layout Store] 布局已成功保存到后端。'); await apiClient.put('/settings/layout', layoutTree.value);
console.log('[Layout Store] 主布局已成功保存到后端 (sent value):', layoutTree.value);
} catch (error) { } catch (error) {
console.error('[Layout Store] 保存布局到后端失败:', error); console.error('[Layout Store] 保存布局到后端失败:', error);
// 可以考虑添加用户提示
} }
// 2. 保存到 localStorage
// 2. 保存到 localStorage (作为备份或离线支持)
try { try {
// If layoutTree.value is null, layoutToSave will be 'null'
localStorage.setItem(LAYOUT_STORAGE_KEY, layoutToSave); localStorage.setItem(LAYOUT_STORAGE_KEY, layoutToSave);
console.log('[Layout Store] 布局已自动保存到 localStorage。'); console.log('[Layout Store] 布局已自动保存到 localStorage (saved value):', layoutToSave);
} catch (error) { } catch (error) {
console.error('[Layout Store] 保存布局到 localStorage 失败:', error); console.error('[Layout Store] 保存布局到 localStorage 失败:', error);
} }
} }
// --- 持久化 --- // 新增 Action: 将当前侧栏配置持久化到后端和 localStorage
// 监听 layoutTree 的变化,并调用持久化方法 async function persistSidebarPanes() {
// 添加防抖以避免过于频繁的 API 调用 const sidebarsToSave = JSON.stringify(sidebarPanes.value);
let debounceTimer: ReturnType<typeof setTimeout> | null = null; // 1. 保存到后端 (假设 API 端点为 /settings/sidebar)
watch( try {
layoutTree, console.log('[Layout Store] Attempting to save sidebar config to backend...');
(newTree, oldTree) => { await apiClient.put('/settings/sidebar', sidebarPanes.value); // 新 API 端点
// 避免初始化时触发 (虽然 initializeLayout 已经是 async,但以防万一) console.log('[Layout Store] 侧栏配置已成功保存到后端。');
if (oldTree === undefined) return; } catch (error) {
// 只有在实际发生变化时才触发持久化 console.error('[Layout Store] 保存侧栏配置到后端失败:', error);
if (JSON.stringify(newTree) !== JSON.stringify(oldTree)) { }
console.log('[Layout Store] Layout tree changed, scheduling persistence...'); // 2. 保存到 localStorage
if (debounceTimer) { try {
clearTimeout(debounceTimer); localStorage.setItem(SIDEBAR_STORAGE_KEY, sidebarsToSave);
} console.log('[Layout Store] 侧栏配置已自动保存到 localStorage。');
debounceTimer = setTimeout(() => { } catch (error) {
persistLayoutTree(); console.error('[Layout Store] 保存侧栏配置到 localStorage 失败:', error);
}, 1000); // 1秒防抖 }
} }
},
{ deep: true }
);
// --- 初始化 ---
// Store 创建时自动初始化布局
initializeLayout();
// --- 返回 --- // --- 持久化 Watchers ---
return { let layoutDebounceTimer: ReturnType<typeof setTimeout> | null = null;
layoutTree, let sidebarDebounceTimer: ReturnType<typeof setTimeout> | null = null;
availablePanes, // 供配置器使用
usedPanes, // 可用于调试或内部逻辑 // 监听主布局树变化
updateLayoutTree, watch(
initializeLayout, // 允许外部重置或重新加载 layoutTree,
updateNodeSizes, // *** 新增:暴露更新大小的 action *** (newTree, oldTree) => {
// 暴露 generateId 供配置器使用(如果需要) if (oldTree === undefined) return; // 避免初始化触发
generateId, if (JSON.stringify(newTree) !== JSON.stringify(oldTree)) {
// 暴露 allPossiblePanes 供配置器显示所有选项 console.log('[Layout Store] Main layout tree changed, scheduling persistence...');
allPossiblePanes, if (layoutDebounceTimer) clearTimeout(layoutDebounceTimer);
// 新增:暴露布局可见性状态和切换方法 layoutDebounceTimer = setTimeout(() => {
isLayoutVisible, persistLayoutTree();
toggleLayoutVisibility, }, 1000); // 1秒防抖
// 新增:暴露主导航栏可见性状态和操作 }
isHeaderVisible, },
loadHeaderVisibility, { deep: true }
toggleHeaderVisibility, );
// 新增:暴露获取默认布局的方法
getSystemDefaultLayout, // 监听侧栏配置变化
}; watch(
sidebarPanes,
(newPanes, oldPanes) => {
if (oldPanes === undefined) return; // 避免初始化触发
if (JSON.stringify(newPanes) !== JSON.stringify(oldPanes)) {
console.log('[Layout Store] Sidebar panes changed, scheduling persistence...');
if (sidebarDebounceTimer) clearTimeout(sidebarDebounceTimer);
sidebarDebounceTimer = setTimeout(() => {
persistSidebarPanes();
}, 1000); // 1秒防抖
}
},
{ deep: true }
);
// --- 初始化 ---
// Store 创建时自动初始化布局和侧栏
initializeLayout();
// 单独加载 Header 可见性(如果需要与布局初始化分开)
loadHeaderVisibility();
// --- 返回 ---
return {
// State
layoutTree,
sidebarPanes, // <--- 暴露侧栏状态
allPossiblePanes,
isLayoutVisible,
isHeaderVisible,
// Computed
availablePanes,
usedPanes,
// Actions
updateLayoutTree,
updateSidebarPanes, // <--- 暴露侧栏更新 action
initializeLayout,
updateNodeSizes,
generateId,
toggleLayoutVisibility,
loadHeaderVisibility,
toggleHeaderVisibility,
getSystemDefaultLayout,
getSystemDefaultSidebarPanes, // <--- 暴露获取默认侧栏配置的方法
// Persist actions (可选暴露,如果需要手动触发)
// persistLayoutTree,
// persistSidebarPanes,
};
}); });
@@ -328,6 +328,7 @@ const handleCloseEditorTab = (tabId: string) => {
<div class="main-content-area"> <div class="main-content-area">
<LayoutRenderer <LayoutRenderer
v-if="layoutTree" v-if="layoutTree"
:is-root-renderer="true"
:layout-node="layoutTree" :layout-node="layoutTree"
:active-session-id="activeSessionId" :active-session-id="activeSessionId"
class="layout-renderer-wrapper" class="layout-renderer-wrapper"