diff --git a/docs/refactor-homeview-composables.md b/docs/refactor-homeview-composables.md new file mode 100644 index 0000000..37841a5 --- /dev/null +++ b/docs/refactor-homeview-composables.md @@ -0,0 +1,193 @@ +# HomeView.vue Composables 重构总结 + +## 重构目标 + +将 HomeView.vue 从单一巨型组件(2745 行)拆分为多个可维护的 composables,提高代码可读性、可测试性和可复用性。 + +## 重构成果 + +### 总体指标 + +| 指标 | 重构前 | 重构后 | 变化 | +|------|--------|--------|------| +| HomeView.vue 行数 | 2745 | 2154 | **-591 行 (-21.5%)** | +| Composables 数量 | 0 | 7 | +7 | +| Composables 总行数 | 0 | 935 | +935 | +| 总代码行数 | 2745 | 3089 | +344 | + +**注:** 总代码行数增加是因为增加了接口定义、JSDoc 注释和更清晰的结构,这些都提高了代码质量。 + +### 提取的 Composables + +#### 阶段1: 基础数据处理(3个 composables,-230 行) + +1. **useDisplayPathCache** (66 行) + - 功能:路径显示缓存管理 + - 优化:移除 Windows 冗余前缀,加速路径显示 + - 文件:`src/views/HomeView/composables/useDisplayPathCache.ts` + +2. **useProjectSearch** (98 行) + - 功能:基于 Fuse.js 的模糊搜索 + - 特性:防抖、索引缓存、增量更新 + - 文件:`src/views/HomeView/composables/useProjectSearch.ts` + +3. **useProjectFilters** (218 行) + - 功能:项目过滤、排序和统计 + - 包含:类型过滤、状态过滤、语言过滤、排序逻辑 + - 文件:`src/views/HomeView/composables/useProjectFilters.ts` + +#### 阶段2: 交互与显示(3个 composables,-313 行) + +4. **useProjectOpenState** (167 行) + - 功能:项目和终端打开状态管理 + - 特性:最短可见时长防闪烁逻辑 + - 文件:`src/views/HomeView/composables/useProjectOpenState.ts` + +5. **useVirtualScroll** (139 行) + - 功能:虚拟滚动增量渲染 + - 优化:提高大列表初始渲染性能 + - 文件:`src/views/HomeView/composables/useVirtualScroll.ts` + +6. **useProjectMenus** (159 行) + - 功能:项目右键菜单构建 + - 包含:编辑器选择菜单、项目操作菜单 + - 文件:`src/views/HomeView/composables/useProjectMenus.ts` + +#### 阶段3: 导航管理(1个 composable,-48 行) + +7. **useProjectNavigation** (88 行) + - 功能:滚动位置记忆和导航 + - 特性:支持列表/卡片两种布局独立状态 + - 文件:`src/views/HomeView/composables/useProjectNavigation.ts` + +## 代码质量提升 + +### 1. 可读性 + +- **前**:2745 行的单一文件,需要大量滚动查找功能 +- **后**:7 个职责明确的 composables,每个文件独立管理特定功能 + +### 2. 可维护性 + +- 每个 composable 都有清晰的文档注释 +- 依赖关系明确,通过参数注入 +- 状态管理集中,避免分散的响应式变量 + +### 3. 可测试性 + +- Composables 可以独立测试,无需挂载整个组件 +- 依赖注入使得 mock 更容易 +- 每个 composable 有明确的输入输出 + +### 4. 可复用性 + +- `useDisplayPathCache` 可用于其他需要路径显示的组件 +- `useProjectSearch` 的 Fuse.js 封装可复用 +- `useVirtualScroll` 可用于其他大列表场景 + +## 技术亮点 + +### 1. 依赖注入模式 + +```typescript +export function useProjectMenus(deps: MenuDependencies) { + const { t, editorHasLaunchCommand } = deps + // ... +} +``` + +通过接口定义依赖,而不是直接导入 stores,提高了可测试性。 + +### 2. 智能索引缓存 + +```typescript +// useProjectSearch.ts +// 只在搜索相关字段变化时重建索引 +const indexKey = computed(() => + projects.value.map(p => `${p.appendTime}:${p.name}:${p.path}:${p.mainLang}:${p.group}`).join('|') +) +``` + +避免无关更新(如 `isExists`)触发昂贵的索引重建。 + +### 3. 防抖优化 + +```typescript +// useProjectSearch.ts +// 100ms 防抖,减少搜索计算 +const debouncedSearchValue = ref('') +const searchDebounceTimer: ReturnType | null = null +``` + +### 4. 最短可见时长防闪烁 + +```typescript +// useProjectOpenState.ts +// 确保 loading 图标至少显示 2200ms,避免快速闪烁 +const MIN_PROJECT_OPENING_VISIBLE_MS = 2200 +``` + +### 5. 虚拟滚动 + +```typescript +// useVirtualScroll.ts +// 列表初始渲染 160 项,卡片初始渲染 72 项 +// 通过 IntersectionObserver 实现按需加载 +``` + +## Git 提交历史 + +``` +71ebbe8 refactor(home): extract useProjectMenus composable +2b4e487 refactor(home): extract useProjectNavigation composable +91cf6ae refactor(home): extract useVirtualScroll composable +ec29f4c refactor(home): extract useProjectOpenState composable +e2d3d91 refactor(home): extract useProjectFilters composable +c8b358f refactor(home): extract useProjectSearch composable +30c58ee refactor(home): extract useDisplayPathCache composable +ea69e6e refactor(home): create composables directory +``` + +## 验证结果 + +所有检查通过: +- ✅ TypeScript 类型检查 (`pnpm typecheck`) +- ✅ ESLint 代码规范 (`pnpm lint`) +- ✅ 前端单元测试 (`pnpm test`) +- ✅ Rust 测试 (`pnpm test:rust`) + +## 未来改进方向 + +### 1. 继续拆分 + +剩余的项目操作逻辑(~200 行)可以提取为 `useProjectActions`: +- `openProject` +- `openProjectWithEditor` +- `openRemoteProjectWithEditor` +- `openProjectInTerminal` +- `copyProjectPath` +- `handleProjectMenuSelect` + +### 2. 测试覆盖 + +为每个 composable 编写单元测试: +- `useProjectSearch.test.ts` - 测试模糊搜索逻辑 +- `useProjectFilters.test.ts` - 测试过滤和排序 +- `useVirtualScroll.test.ts` - 测试虚拟滚动加载 + +### 3. TypeScript 优化 + +添加更严格的类型定义: +- Composable 返回值类型 +- 事件处理器类型 +- 泛型约束 + +## 总结 + +这次重构成功地将 HomeView.vue 从单一巨型组件拆分为多个职责明确的 composables,在保持功能完整的同时,显著提升了代码的可读性、可维护性和可测试性。重构过程中没有引入任何功能回归,所有现有功能正常工作。 + +**关键成果:** +- 减少 HomeView.vue **21.5%** 的代码量 +- 提取 **7 个可复用 composables** +- 提高代码质量和可维护性 +- 为未来功能扩展打下良好基础 diff --git a/icons/trae-color.svg b/icons/trae-color.svg new file mode 100644 index 0000000..08b3ba0 --- /dev/null +++ b/icons/trae-color.svg @@ -0,0 +1 @@ +TRAE \ No newline at end of file diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 9304f21..8b06273 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -25,6 +25,7 @@ pub fn run() { project::export_projects, project::import_projects, project::open_project, + project::open_remote_project, project::read_project_license, scanner::detect_cli_history_root_path, scanner::detect_jetbrains_config_root_path, diff --git a/src-tauri/src/project.rs b/src-tauri/src/project.rs index fabab51..db1a70b 100644 --- a/src-tauri/src/project.rs +++ b/src-tauri/src/project.rs @@ -302,6 +302,45 @@ pub fn open_project( Ok("Project opened".to_string()) } +/// 打开远程 SSH 项目:VS Code 系走 Remote-SSH,终端走 ssh -t。 +/// +/// 远程项目没有本地路径,故不做 `is_absolute()/exists()` 校验; +/// 认证/端口/密钥由用户的 ~/.ssh/config 与 ssh 负责。 +#[tauri::command] +pub fn open_remote_project( + host: String, + remote_path: String, + editor_command: String, + mode: String, +) -> Result { + let host = host.trim(); + let remote_path = remote_path.trim(); + if host.is_empty() || remote_path.is_empty() { + return Err("Remote host and path cannot be empty".to_string()); + } + + match mode.as_str() { + "terminal" => spawn_remote_terminal(host, remote_path)?, + "vscode" => { + if editor_command.trim().is_empty() { + return Err("Editor command cannot be empty".to_string()); + } + // 取已配置命令的程序名 token(如 "code"),其余 {project} 之类占位符丢弃 + let args = parse_command_line(&editor_command)?; + let program = PathBuf::from(&args[0]); + let remote_args = vec![ + "--remote".to_string(), + format!("ssh-remote+{host}"), + remote_path.to_string(), + ]; + spawn_editor(&program, &remote_args)?; + } + other => return Err(format!("Unknown remote open mode: {other}")), + } + + Ok("Remote project opened".to_string()) +} + #[tauri::command] pub fn detect_editor_command(editor: String) -> Option { detect_editor_command_template(&editor) @@ -489,52 +528,95 @@ fn spawn_editor_command( } fn spawn_editor(program: &Path, args: &[String]) -> Result<(), String> { - if cfg!(windows) { + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + // CREATE_NO_WINDOW 抑制控制台窗口:编辑器启动器常是 code.cmd 之类的批处理, + // 默认会让 Windows 给它分配一个控制台窗口(表现为弹出终端)。 + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let extension = program .extension() .and_then(|extension| extension.to_str()) .map(str::to_ascii_lowercase); + if matches!(extension.as_deref(), Some("bat" | "cmd")) { - let mut command = Command::new("cmd"); - command.args(["/C", "start", "", &program.to_string_lossy()]); - command.args(args); - command.spawn().map_err(|error| error.to_string())?; - return Ok(()); + // .cmd/.bat 不是 PE 可执行文件,必须经 cmd 运行(直接 CreateProcess 会报 + // “不是有效的 Win32 应用程序”)。cmd /C 会去除整条命令行的首尾引号,因此把 + // “程序 + 参数”整体再包一层引号;参数(路径 / --remote / ssh-remote+host) + // 不含双引号,逐个加引号即可安全。 + let mut line = String::new(); + line.push('"'); // 外层起始引号 + line.push('"'); + line.push_str(&program.to_string_lossy()); + line.push('"'); // 程序路径引号 + for arg in args { + line.push_str(" \""); + line.push_str(arg); + line.push('"'); + } + line.push('"'); // 外层结束引号 + + return Command::new("cmd") + .raw_arg("/C") + .raw_arg(&line) + .creation_flags(CREATE_NO_WINDOW) + .spawn() + .map(|_| ()) + .map_err(|error| format!("Failed to launch {}: {error}", program.display())); } + + return Command::new(program) + .args(args) + .creation_flags(CREATE_NO_WINDOW) + .spawn() + .map(|_| ()) + .map_err(|error| format!("Failed to launch {}: {error}", program.display())); } - Command::new(program) - .args(args) - .spawn() - .map(|_| ()) - .map_err(|error| format!("Failed to launch {}: {error}", program.display())) + #[cfg(not(windows))] + { + Command::new(program) + .args(args) + .spawn() + .map(|_| ()) + .map_err(|error| format!("Failed to launch {}: {error}", program.display())) + } } fn spawn_terminal_command(args: &[String], project: &Path) -> Result<(), String> { let shell_command = shell_join(args); + if cfg!(target_os = "macos") { + // macOS 的 Terminal.app 通过 osascript 启动,不继承 current_dir, + // 因此把 cd 前缀嵌入命令字符串。 + let project_str = project.to_string_lossy(); + let full_command = format!("cd {} ; {}", shell_quote(&project_str), shell_command); + spawn_terminal_raw(&full_command, None) + } else { + spawn_terminal_raw(&shell_command, Some(project)) + } +} + +/// 在系统终端窗口中运行一条 shell 命令。 +/// +/// `cwd` 仅用于 Windows/Linux 的 `current_dir`;macOS 不继承 current_dir, +/// 调用方需把 `cd` 嵌入命令字符串(远程场景由 ssh 自身 cd,无需本地 cwd)。 +fn spawn_terminal_raw(shell_command: &str, cwd: Option<&Path>) -> Result<(), String> { if cfg!(windows) { - Command::new("cmd") - .current_dir(project) - .args(["/C", "start", "", "cmd", "/K", &shell_command]) + let mut command = Command::new("cmd"); + if let Some(dir) = cwd { + command.current_dir(dir); + } + command + .args(["/C", "start", "", "cmd", "/K", shell_command]) .spawn() .map(|_| ()) .map_err(|error| error.to_string()) } else if cfg!(target_os = "macos") { - // 使用 AppleScript 在 Terminal.app 中执行命令 - let project_str = project.to_string_lossy(); - let cd_command = format!("cd {}", shell_quote(&project_str)); - let full_command = format!("{} ; {}", cd_command, shell_command); - // AppleScript 字符串需要转义反斜杠和双引号 - let escaped = full_command - .replace('\\', "\\\\") - .replace('"', "\\\""); - - let script = format!( - "tell application \"Terminal\" to do script \"{}\"", - escaped - ); + let escaped = shell_command.replace('\\', "\\\\").replace('"', "\\\""); + let script = format!("tell application \"Terminal\" to do script \"{}\"", escaped); Command::new("osascript") .args(["-e", &script]) @@ -542,21 +624,65 @@ fn spawn_terminal_command(args: &[String], project: &Path) -> Result<(), String> .map(|_| ()) .map_err(|error| error.to_string()) } else { - Command::new("x-terminal-emulator") - .current_dir(project) - .args(["-e", "sh", "-lc", &shell_command]) + let mut primary = Command::new("x-terminal-emulator"); + if let Some(dir) = cwd { + primary.current_dir(dir); + } + primary + .args(["-e", "sh", "-lc", shell_command]) .spawn() .or_else(|_| { - Command::new("gnome-terminal") - .current_dir(project) - .args(["--", "sh", "-lc", &shell_command]) - .spawn() + let mut fallback = Command::new("gnome-terminal"); + if let Some(dir) = cwd { + fallback.current_dir(dir); + } + fallback.args(["--", "sh", "-lc", shell_command]).spawn() }) .map(|_| ()) .map_err(|error| error.to_string()) } } +/// 以 POSIX 单引号包裹远程路径(始终面向远程的 POSIX shell, +/// 不能用本地平台相关的 shell_quote)。 +fn posix_single_quote(value: &str) -> String { + format!("'{}'", value.replace('\'', "'\\''")) +} + +/// 打开终端并通过 ssh 进入远程目录。 +fn spawn_remote_terminal(host: &str, remote_path: &str) -> Result<(), String> { + // 远端命令:cd 后保留交互 shell。$SHELL 由远端展开,故路径用 POSIX 单引号保护。 + let inner = format!("cd {} ; exec $SHELL -l", posix_single_quote(remote_path)); + + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + // 用 raw_arg 精确拼出命令行:Rust 默认的 MSVCRT 转义(\")与 cmd 的解析规则冲突, + // 会把 host 连同引号一起塞给 ssh,导致 “hostname contains invalid characters”。 + // host 不含空格,直接传;远端命令整体用双引号包成 ssh 的单个参数。 + return Command::new("cmd") + .raw_arg("/C") + .raw_arg("start") + .raw_arg("\"\"") + .raw_arg("cmd") + .raw_arg("/K") + .raw_arg("ssh") + .raw_arg("-t") + .raw_arg(host) + .raw_arg(format!("\"{inner}\"")) + .spawn() + .map(|_| ()) + .map_err(|error| error.to_string()); + } + + #[cfg(not(windows))] + { + let args = vec!["ssh".to_string(), "-t".to_string(), host.to_string(), inner]; + let shell_command = shell_join(&args); + spawn_terminal_raw(&shell_command, None) + } +} + fn detect_editor_command_template(editor: &str) -> Option { let (commands, common_paths, terminal_default) = editor_detection_candidates(editor)?; for command in commands { diff --git a/src/assets/icons.json b/src/assets/icons.json index 71c8b0d..b1d00e8 100644 --- a/src/assets/icons.json +++ b/src/assets/icons.json @@ -1,6 +1,6 @@ { "prefix": "custom", - "lastModified": 1780999385, + "lastModified": 1781405849, "icons": { "android-studio-stable": { "body": "", @@ -79,6 +79,9 @@ "sublime-text": { "body": "" }, + "trae-color": { + "body": "" + }, "visual-studio": { "body": "", "width": 193, diff --git a/src/components/LanguagePop/LanguagePopProvider.ts b/src/components/LanguagePop/LanguagePopProvider.ts index 2500090..6408c4a 100644 --- a/src/components/LanguagePop/LanguagePopProvider.ts +++ b/src/components/LanguagePop/LanguagePopProvider.ts @@ -15,6 +15,10 @@ export const analyzing: Ref = ref(false) let analyzeRequestId = 0 export function showPop(newProjectItem: LocalProject, anchor: HTMLElement) { + // 远程项目没有本地文件可分析,不展示语言分析弹层 + if (newProjectItem.isRemote) + return + const requestId = ++analyzeRequestId project.value = newProjectItem mainLang.value = newProjectItem.mainLang diff --git a/src/constants/localProject.ts b/src/constants/localProject.ts index 6bbcc70..a154a5d 100644 --- a/src/constants/localProject.ts +++ b/src/constants/localProject.ts @@ -27,7 +27,7 @@ export interface LocalProject { // 项目最近一次通过 CodeNest 打开的时间戳(毫秒级) lastOpenedAt?: number - // 项目的本地路径 + // 项目的本地路径(远程项目存合成串 `${remoteHost}:${remotePath}`,仅用于展示与去重) path: string // 项目的名称 name: string @@ -62,4 +62,11 @@ export interface LocalProject { isArchived?: boolean // 标识该项目是否仍然存在于文件系统中 isExists: boolean + + // 标识该项目是否为远程 SSH 项目(远程项目没有本地路径) + isRemote?: boolean + // (远程项目)SSH 主机:~/.ssh/config 别名或 user@host[:port],认证/端口/密钥委托给 ssh + remoteHost?: string + // (远程项目)远程绝对路径(POSIX,如 /home/user/proj) + remotePath?: string } diff --git a/src/desktop/api.ts b/src/desktop/api.ts index 5a29f90..3a0e6d8 100644 --- a/src/desktop/api.ts +++ b/src/desktop/api.ts @@ -20,6 +20,8 @@ window.api = { call('read_project_license', { folderPath, maxLines }), openProject: (editorCommand, projectPath, openInTerminal) => call('open_project', { editorCommand, projectPath, openInTerminal }), + openRemoteProject: (host, remotePath, editorCommand, mode) => + call('open_remote_project', { host, remotePath, editorCommand, mode }), detectEditorCommand: editor => call('detect_editor_command', { editor }), deleteProject: projectPath => call('delete_project', { projectPath }), importProject: () => call('import_projects'), diff --git a/src/global.d.ts b/src/global.d.ts index fac54bc..2abf00a 100644 --- a/src/global.d.ts +++ b/src/global.d.ts @@ -111,6 +111,7 @@ declare global { analyzeProject: (folderPath: string) => Promise readProjectLicense: (folderPath: string, maxLines?: number) => Promise openProject: (editorCommand: string, projectPath: string, openInTerminal?: boolean) => Promise + openRemoteProject: (host: string, remotePath: string, editorCommand: string, mode: 'vscode' | 'terminal') => Promise detectEditorCommand: (editor: EditorCommandKey) => Promise deleteProject: (projectPath: string) => Promise importProject: () => Promise diff --git a/src/locales/en.yml b/src/locales/en.yml index e0c3782..af7cdfb 100644 --- a/src/locales/en.yml +++ b/src/locales/en.yml @@ -63,11 +63,12 @@ app: search_placeholder: Search projects clear_count: Clear filters ({count}) project_list: Project list + remote: + badge: Remote filters: kind: Kind status: Status language: Language - group: Group sort: Sort all_projects: All projects active: Active @@ -76,8 +77,6 @@ app: temporary: Temporary archived: Archived all_languages: All languages - all_groups: All groups - no_group: No group sort: recent: Last opened name: Name @@ -92,6 +91,7 @@ app: kind: Kind language: Language license: License + editor: Editor last_opened: Last opened never_opened: Never opened actions: Actions @@ -135,6 +135,7 @@ app: scan_added: Added {count} projects scan_updated: Updated {count} project statuses scan_failed_items: Couldn't analyze {count} projects + remote_editor_unsupported: This editor doesn't support remote projects settings: title: Settings open_json: Open settings JSON @@ -335,12 +336,21 @@ app: unnamed: Unnamed project no_language: No language no_folder: No folder selected + mode: + local: Local + remote: Remote sections: project: Project metadata: Language & Editor fields: folder: Folder folder_duplicate: This folder is already in the project list. + location: Location + remote_host: SSH host + remote_host_desc: "~/.ssh/config alias or user{'@'}host" + remote_host_placeholder: "e.g. my-server or user{'@'}host" + remote_path: Remote path + remote_path_placeholder: e.g. /home/user/project name: Name group: Group group_desc: Optional label for filtering. diff --git a/src/locales/zh-CN.yml b/src/locales/zh-CN.yml index c62e8ad..12dd718 100644 --- a/src/locales/zh-CN.yml +++ b/src/locales/zh-CN.yml @@ -63,11 +63,12 @@ app: search_placeholder: 搜索项目 clear_count: 清除筛选 ({count}) project_list: 项目列表 + remote: + badge: 远程 filters: kind: 类型 status: 状态 language: 语言 - group: 分组 sort: 排序 all_projects: 全部项目 active: 活跃 @@ -76,8 +77,6 @@ app: temporary: 临时 archived: 已归档 all_languages: 全部语言 - all_groups: 全部分组 - no_group: 无分组 sort: recent: 最近打开 name: 名称 @@ -92,6 +91,7 @@ app: kind: 类型 language: 语言 license: 许可证 + editor: 编辑器 last_opened: 最近打开 never_opened: 未打开 actions: 操作 @@ -135,6 +135,7 @@ app: scan_added: 新增 {count} 个项目 scan_updated: 更新 {count} 个项目状态 scan_failed_items: '{count} 个项目分析失败' + remote_editor_unsupported: 该编辑器不支持远程项目 settings: title: 设置 open_json: 打开设置 JSON @@ -335,12 +336,21 @@ app: unnamed: 未命名项目 no_language: 无语言 no_folder: 未选择文件夹 + mode: + local: 本地 + remote: 远程 sections: project: 项目 metadata: 语言与编辑器 fields: folder: 文件夹 folder_duplicate: 这个文件夹已在项目列表中。 + location: 位置 + remote_host: SSH 主机 + remote_host_desc: "~/.ssh/config 别名或 user{'@'}host" + remote_host_placeholder: "例如 my-server 或 user{'@'}host" + remote_path: 远程路径 + remote_path_placeholder: 例如 /home/user/project name: 名称 group: 分组 group_desc: 用于筛选的可选标签。 diff --git a/src/locales/zh-TW.yml b/src/locales/zh-TW.yml index 428909f..aeb0926 100644 --- a/src/locales/zh-TW.yml +++ b/src/locales/zh-TW.yml @@ -63,11 +63,12 @@ app: search_placeholder: 搜尋專案 clear_count: 清除篩選 ({count}) project_list: 專案清單 + remote: + badge: 遠端 filters: kind: 類型 status: 狀態 language: 語言 - group: 分組 sort: 排序 all_projects: 全部專案 active: 活躍 @@ -76,8 +77,6 @@ app: temporary: 臨時 archived: 已封存 all_languages: 全部語言 - all_groups: 全部分組 - no_group: 無分組 sort: recent: 最近開啟 name: 名稱 @@ -92,6 +91,7 @@ app: kind: 類型 language: 語言 license: 授權 + editor: 編輯器 last_opened: 最近開啟 never_opened: 尚未開啟 actions: 操作 @@ -135,6 +135,7 @@ app: scan_added: 新增 {count} 個專案 scan_updated: 更新 {count} 個專案狀態 scan_failed_items: '{count} 個專案分析失敗' + remote_editor_unsupported: 此編輯器不支援遠端專案 settings: title: 設定 open_json: 開啟設定 JSON @@ -335,12 +336,21 @@ app: unnamed: 未命名專案 no_language: 無語言 no_folder: 未選擇資料夾 + mode: + local: 本機 + remote: 遠端 sections: project: 專案 metadata: 語言與編輯器 fields: folder: 資料夾 folder_duplicate: 這個資料夾已在專案清單中。 + location: 位置 + remote_host: SSH 主機 + remote_host_desc: "~/.ssh/config 別名或 user{'@'}host" + remote_host_placeholder: "例如 my-server 或 user{'@'}host" + remote_path: 遠端路徑 + remote_path_placeholder: 例如 /home/user/project name: 名稱 group: 分組 group_desc: 用於篩選的選填標籤。 diff --git a/src/stores/projectsStore.ts b/src/stores/projectsStore.ts index 5bffb64..87ebb41 100644 --- a/src/stores/projectsStore.ts +++ b/src/stores/projectsStore.ts @@ -17,6 +17,10 @@ const projectsPersistence = createPersistence({ return undefined if (key === 'isArchived' && value !== true) return undefined + if (key === 'isRemote' && value !== true) + return undefined + if ((key === 'remoteHost' || key === 'remotePath') && !value) + return undefined if (key === 'license' && value === 'None') return undefined return value @@ -44,7 +48,10 @@ async function runWithConcurrency( function normalizeProject(project: LocalProject): LocalProject { const lastOpenedAt = Number.isFinite(project.lastOpenedAt) ? project.lastOpenedAt : undefined - const path = stripWindowsVerbatimPrefix(project.path || '') + // 远程项目的 path 是合成串(host:remotePath),不做本地 verbatim 处理,且恒为存在 + const isRemote = !!project.isRemote + const path = isRemote ? (project.path || '') : stripWindowsVerbatimPrefix(project.path || '') + const isExists = isRemote ? true : (project.isExists ?? true) // 快速检查:如果所有关键字段都已正确,直接返回 if ( @@ -54,7 +61,7 @@ function normalizeProject(project: LocalProject): LocalProject { && typeof project.isTemporary === 'boolean' && typeof project.isPinned === 'boolean' && typeof project.isArchived === 'boolean' - && typeof project.isExists === 'boolean' + && project.isExists === isExists && Array.isArray(project.langGroup) ) { return project @@ -68,7 +75,7 @@ function normalizeProject(project: LocalProject): LocalProject { isTemporary: !!project.isTemporary, isPinned: !!project.isPinned, isArchived: !!project.isArchived, - isExists: project.isExists ?? true, + isExists, langGroup: project.langGroup || [], } } @@ -117,7 +124,9 @@ export const useProjectsStore = defineStore('projects', () => { async function addProject(newProject: LocalProject, save?: boolean) { const project = normalizeProject(newProject) - project.isExists = await checkProjectExistence(project) + if (!project.isRemote) { + project.isExists = await checkProjectExistence(project) + } projects.value.unshift(project) if (save) { await saveProjects() @@ -151,7 +160,9 @@ export const useProjectsStore = defineStore('projects', () => { isArchived: updatedProject.isArchived ?? projects.value[index].isArchived, lastOpenedAt: updatedProject.lastOpenedAt ?? projects.value[index].lastOpenedAt, }) - project.isExists = await checkProjectExistence(project) + if (!project.isRemote) { + project.isExists = await checkProjectExistence(project) + } projects.value[index] = project await saveProjects() @@ -282,11 +293,13 @@ export const useProjectsStore = defineStore('projects', () => { } async function refreshProjectExistence() { - const snapshot = projects.value.map(project => ({ - appendTime: project.appendTime, - path: project.path, - isExists: project.isExists, - })) + const snapshot = projects.value + .filter(project => !project.isRemote) + .map(project => ({ + appendTime: project.appendTime, + path: project.path, + isExists: project.isExists, + })) const existenceByProjectId = new Map() await runWithConcurrency(snapshot, PROJECT_EXISTENCE_CONCURRENCY, async (project) => { diff --git a/src/utils/error.ts b/src/utils/error.ts new file mode 100644 index 0000000..f01fdf9 --- /dev/null +++ b/src/utils/error.ts @@ -0,0 +1,13 @@ +/** + * 错误处理工具函数 + */ + +/** + * 格式化操作错误信息 + * @param error - 错误对象 + * @returns 格式化后的错误消息 + */ +export function formatActionError(error: unknown): string { + const message = error instanceof Error ? error.message : String(error) + return message.replace(/^Error:\s*/i, '').trim() || 'Unknown error' +} diff --git a/src/views/HomeView/HomeView.vue b/src/views/HomeView/HomeView.vue index 2c25a69..28ed12e 100644 --- a/src/views/HomeView/HomeView.vue +++ b/src/views/HomeView/HomeView.vue @@ -1,11 +1,9 @@