dsh-gufa-code 1.3.60 → 1.3.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/host/fs.js CHANGED
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import { createHash, randomUUID } from 'node:crypto'
6
6
  import { createReadStream } from 'node:fs'
7
- import { access, cp, lstat, mkdir, open, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
7
+ import { access, cp, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
8
8
  import { execFile } from 'node:child_process'
9
9
  import { promisify } from 'node:util'
10
10
  import { constants } from 'node:fs'
@@ -241,6 +241,198 @@ export function register(router, env) {
241
241
  })
242
242
 
243
243
  /** 把系统剪贴板里的文件匹配回项目内已有文件(供聊天框「粘贴文件→@引用」使用)。 */
244
+ /** 全项目文本搜索(左侧「搜索」面板用)。返回按文件分组、带上行列号的匹配。 */
245
+ router.method('fs.search', async (body) => {
246
+ const project = env.projects.ensure(typeof body.root === 'string' ? body.root : '')
247
+ const root = project.root
248
+ const rawQuery = typeof body.query === 'string' ? body.query : ''
249
+ const query = rawQuery.slice(0, 200)
250
+ if (query === '') return { query: '', files: [], total: 0, truncated: false, scanned: 0, viaGit: false }
251
+ const options = body.options !== null && typeof body.options === 'object' ? body.options : {}
252
+ const caseSensitive = options.caseSensitive === true
253
+ const useRegex = options.regex === true
254
+ const clampInt = (value, fallback, min, max) => {
255
+ const number = Number(value)
256
+ if (!Number.isFinite(number)) return fallback
257
+ return Math.min(Math.max(Math.trunc(number), min), max)
258
+ }
259
+ const maxFiles = clampInt(options.maxFiles, 200, 1, 500)
260
+ const maxMatches = clampInt(options.maxMatches, 500, 1, 2000)
261
+ const maxScanned = clampInt(options.maxScanned, 20000, 100, 100000)
262
+ const fileSizeLimit = 2 * 1024 * 1024
263
+ const timeBudget = 12000
264
+ const startedAt = Date.now()
265
+ let regex = null
266
+ let needle = ''
267
+ if (useRegex) {
268
+ try {
269
+ regex = new RegExp(query, caseSensitive ? 'g' : 'gi')
270
+ } catch (error) {
271
+ throw new ApiError('bad-regex', `正则表达式无效:${error.message}`, 400)
272
+ }
273
+ } else {
274
+ needle = caseSensitive ? query : query.toLowerCase()
275
+ }
276
+ const EXCLUDED = new Set([
277
+ 'node_modules', '.git', 'dist', 'build', 'out', '.next', 'vendor', 'target', '.venv', 'venv',
278
+ '__pycache__', '.idea', '.cache', '.turbo', '.parcel-cache', '.svelte-kit', '.nuxt', '.output',
279
+ 'coverage', '.gradle', 'DerivedData', 'Pods', '.tox', '.mypy_cache', '.pytest_cache', '.ruff_cache',
280
+ '.electron-cache', '.npm-cache', '.pip-cache', '.yarn', '.pnpm-store', '.pnpm',
281
+ ])
282
+ /* 明显是二进制的扩展名:不读文件,避免把大量图片/压缩包计入扫描数 */
283
+ const SKIP_EXT = new Set([
284
+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'ico', 'icns', 'bmp', 'tiff', 'pdf', 'zip', 'gz', 'tgz', 'tar', '7z', 'rar', 'dmg', 'iso',
285
+ 'mp4', 'mp3', 'wav', 'mov', 'avi', 'mkv', 'flac', 'jar', 'class', 'o', 'a', 'so', 'dylib', 'dll', 'exe', 'bin', 'dat',
286
+ 'woff', 'woff2', 'ttf', 'otf', 'eot', 'wasm', 'pyc', 'node',
287
+ ])
288
+ const extensionOf = (rel) => {
289
+ const base = String(rel).split('/').pop() ?? ''
290
+ const dot = base.lastIndexOf('.')
291
+ return dot <= 0 ? '' : base.slice(dot + 1).toLowerCase()
292
+ }
293
+ const files = []
294
+ let total = 0
295
+ let scanned = 0
296
+ let truncated = false
297
+ const readMatches = (line) => {
298
+ const raw = []
299
+ if (regex !== null) {
300
+ regex.lastIndex = 0
301
+ let match
302
+ while ((match = regex.exec(line)) !== null) {
303
+ if (match[0].length === 0) {
304
+ regex.lastIndex += 1
305
+ continue
306
+ }
307
+ raw.push([match.index, match.index + match[0].length])
308
+ if (raw.length >= 50) break
309
+ }
310
+ return raw
311
+ }
312
+ const haystack = caseSensitive ? line : line.toLowerCase()
313
+ let from = 0
314
+ while (raw.length < 50) {
315
+ const index = haystack.indexOf(needle, from)
316
+ if (index === -1) break
317
+ raw.push([index, index + needle.length])
318
+ from = index + Math.max(needle.length, 1)
319
+ }
320
+ return raw
321
+ }
322
+ const searchFile = async (rel) => {
323
+ const absolute = join(root, rel)
324
+ const info = await stat(absolute).catch(() => undefined)
325
+ if (info === undefined || !info.isFile() || info.size > fileSizeLimit) return []
326
+ let buffer
327
+ try {
328
+ buffer = await readFile(absolute)
329
+ } catch {
330
+ return []
331
+ }
332
+ if (buffer.includes(0)) return []
333
+ const lines = buffer.toString('utf8').split(/\r?\n/)
334
+ const matches = []
335
+ for (let index = 0; index < lines.length && matches.length < 50; index += 1) {
336
+ const line = lines[index]
337
+ for (const range of readMatches(line)) {
338
+ if (matches.length >= 50 || total >= maxMatches) break
339
+ const WINDOW = 300
340
+ const windowStart = line.length > WINDOW ? Math.max(0, Math.min(line.length - WINDOW, range[0] - 80)) : 0
341
+ matches.push({
342
+ line: index + 1,
343
+ column: range[0] + 1,
344
+ start: range[0] - windowStart,
345
+ end: range[1] - windowStart,
346
+ text: line.slice(windowStart, windowStart + WINDOW),
347
+ })
348
+ total += 1
349
+ }
350
+ }
351
+ return matches
352
+ }
353
+ const acceptFile = async (rel) => {
354
+ const matches = await searchFile(rel)
355
+ if (matches.length === 0) return
356
+ files.push({ path: rel, matches })
357
+ }
358
+ /* Git 项目用 git ls-files 拿文件清单(快、尊重 .gitignore、包含未跟踪文件);
359
+ 非 Git 项目才走目录遍历。 */
360
+ let isGitRepo = project.isGit === true
361
+ if (!isGitRepo) {
362
+ try {
363
+ const dotGit = await stat(join(root, '.git'))
364
+ isGitRepo = dotGit.isDirectory() || dotGit.isFile()
365
+ } catch {
366
+ isGitRepo = false
367
+ }
368
+ }
369
+ let candidates = null
370
+ if (isGitRepo) {
371
+ try {
372
+ const { stdout } = await runCommand('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
373
+ cwd: root,
374
+ maxBuffer: 64 * 1024 * 1024,
375
+ timeout: 15000,
376
+ })
377
+ candidates = stdout.split('\0').filter((item) => item !== '')
378
+ candidates.sort((a, b) => a.localeCompare(b))
379
+ } catch {
380
+ candidates = null
381
+ }
382
+ }
383
+ if (candidates !== null) {
384
+ for (const rel of candidates) {
385
+ if (files.length >= maxFiles || total >= maxMatches || scanned >= maxScanned || Date.now() - startedAt > timeBudget) {
386
+ truncated = true
387
+ break
388
+ }
389
+ if (SKIP_EXT.has(extensionOf(rel))) continue
390
+ scanned += 1
391
+ await acceptFile(rel)
392
+ }
393
+ if (!truncated && files.length >= maxFiles) truncated = true
394
+ } else {
395
+ const queue = ['']
396
+ let head = 0
397
+ while (head < queue.length) {
398
+ if (files.length >= maxFiles || total >= maxMatches || scanned >= maxScanned || Date.now() - startedAt > timeBudget) {
399
+ truncated = true
400
+ break
401
+ }
402
+ const dirRel = queue[head]
403
+ head += 1
404
+ let entries
405
+ try {
406
+ entries = await readdir(join(root, dirRel), { withFileTypes: true })
407
+ } catch {
408
+ continue
409
+ }
410
+ entries.sort((a, b) => String(a.name).localeCompare(String(b.name)))
411
+ for (const entry of entries) {
412
+ if (entry.isDirectory()) {
413
+ if (!EXCLUDED.has(entry.name)) queue.push(dirRel === '' ? entry.name : `${dirRel}/${entry.name}`)
414
+ continue
415
+ }
416
+ if (!entry.isFile() || EXCLUDED.has(entry.name)) continue
417
+ const rel = dirRel === '' ? entry.name : `${dirRel}/${entry.name}`
418
+ if (SKIP_EXT.has(extensionOf(rel))) continue
419
+ if (scanned >= maxScanned) {
420
+ truncated = true
421
+ break
422
+ }
423
+ scanned += 1
424
+ await acceptFile(rel)
425
+ if (files.length >= maxFiles || total >= maxMatches) {
426
+ truncated = true
427
+ break
428
+ }
429
+ }
430
+ }
431
+ }
432
+ files.sort((a, b) => a.path.localeCompare(b.path))
433
+ return { query, files, total, truncated, scanned, viaGit: candidates !== null }
434
+ })
435
+
244
436
  router.method('fs.matchFiles', async (body) => {
245
437
  const root = await projectOf(env, body)
246
438
  const wanted = Array.isArray(body.files)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-gufa-code",
3
- "version": "1.3.60",
3
+ "version": "1.3.62",
4
4
  "description": "古法编程 · AI 辅助:一键把 DSH 主面板变成 VS Code 风格 IDE(Monaco 编辑器、文件树、Git、SSH、真实终端 + 右侧官方会话);主张亲手写、每个改动心中有数,AI 是助理、你是第一责任人",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
@@ -252,6 +252,7 @@ if (windowStub.__GUFA_CODE__?.G?.shortcutAction !== undefined) {
252
252
  G0.shortcutAction(mod({ key: 'e', code: 'KeyE', shiftKey: true })) === 'panelExplorer' &&
253
253
  G0.shortcutAction(mod({ key: 'g', code: 'KeyG', shiftKey: true })) === 'panelGit' &&
254
254
  G0.shortcutAction(mod({ key: 'h', code: 'KeyH', shiftKey: true })) === 'panelSsh')
255
+ check('shortcut: Cmd/Ctrl+Shift+F = panelSearch', G0.shortcutAction(mod({ key: 'f', code: 'KeyF', shiftKey: true })) === 'panelSearch')
255
256
  check('shortcut: Shift+Cmd/Ctrl+` = newTerminal', G0.shortcutAction(mod({ code: 'Backquote', shiftKey: true })) === 'newTerminal')
256
257
  check('shortcut: Cmd/Ctrl+/ = shortcuts help', G0.shortcutAction(mod({ key: '/', code: 'Slash' })) === 'shortcuts')
257
258
  check('shortcut: no modifier ignored', G0.shortcutAction({ ...base, key: 'k', code: 'KeyK' }) === null)
@@ -111,6 +111,32 @@ try {
111
111
  const afterDelete = await call(router, 'fs.list', { root, path: 'src' })
112
112
  check('delete applied', !afterDelete.entries.some((entry) => entry.name === 'helper.ts'))
113
113
 
114
+ console.log('fs.search')
115
+ await call(router, 'fs.create', { root, path: 'search.txt', kind: 'file' })
116
+ await call(router, 'fs.write', { root, path: 'search.txt', content: 'Alpha beta\nBETA gamma\nbeta BETA\n' })
117
+ await call(router, 'fs.create', { root, path: 'node_modules', kind: 'dir' }).catch(() => {})
118
+ await call(router, 'fs.create', { root, path: 'node_modules/hidden.txt', kind: 'file' }).catch(() => {})
119
+ await call(router, 'fs.write', { root, path: 'node_modules/hidden.txt', content: 'beta hidden\n' }).catch(() => {})
120
+ const searchAll = await call(router, 'fs.search', { root, query: 'beta' })
121
+ check('search finds file', searchAll.files.some((file) => file.path === 'search.txt'))
122
+ check('search total (case-insensitive)', searchAll.total === 4, String(searchAll.total))
123
+ check('search excludes node_modules', !searchAll.files.some((file) => file.path.startsWith('node_modules/')))
124
+ const searchFile = searchAll.files.find((file) => file.path === 'search.txt')
125
+ check('search line numbers', searchFile.matches[0].line === 1 && searchFile.matches[0].column === 7, JSON.stringify(searchFile.matches[0]))
126
+ const searchCased = await call(router, 'fs.search', { root, query: 'beta', options: { caseSensitive: true } })
127
+ check('search case sensitive', searchCased.total === 2, String(searchCased.total))
128
+ const searchRegex = await call(router, 'fs.search', { root, query: 'b(eta|ETA)', options: { regex: true } })
129
+ check('search regex', searchRegex.total === 4, String(searchRegex.total))
130
+ let badRegex = false
131
+ try {
132
+ await call(router, 'fs.search', { root, query: '([', options: { regex: true } })
133
+ } catch (error) {
134
+ badRegex = error.code === 'bad-regex'
135
+ }
136
+ check('search invalid regex rejected', badRegex)
137
+ await call(router, 'fs.delete', { root, path: 'search.txt' }).catch(() => {})
138
+ await call(router, 'fs.delete', { root, path: 'node_modules' }).catch(() => {})
139
+
114
140
  console.log('git.status / stage / commit')
115
141
  execFileSync('git', ['init', '-q'], { cwd: projectDir })
116
142
  execFileSync('git', ['config', 'user.email', 'selftest@example.com'], { cwd: projectDir })
@@ -126,6 +152,9 @@ try {
126
152
  check('working tree clean after commit', clean.changes.length === 0, JSON.stringify(clean.changes))
127
153
  const log = await call(router, 'git.log', { root, limit: 5 })
128
154
  check('commit in log', log.commits.length === 1 && log.commits[0].subject === 'feat: selftest')
155
+ const gitSearch = await call(router, 'fs.search', { root, query: 'answer' })
156
+ check('search uses git file list', gitSearch.viaGit === true, String(gitSearch.viaGit))
157
+ check('search finds committed file', gitSearch.files.some((file) => file.path === 'src/main.ts'))
129
158
  writeFileSync(join(projectDir, 'src/main.ts'), 'const answer = 43\n')
130
159
  const diff = await call(router, 'git.diff', { root, path: 'src/main.ts' })
131
160
  check('diff contains change', diff.patch.includes('43'))
@@ -112,6 +112,7 @@ const DICT_ZH = {
112
112
  'shortcuts.toggleSidebar': '显示 / 隐藏左侧栏',
113
113
  'shortcuts.closeTab': '关闭当前标签页',
114
114
  'shortcuts.explorer': '聚焦资源管理器',
115
+ 'shortcuts.search': '聚焦全局搜索',
115
116
  'shortcuts.git': '聚焦源代码管理',
116
117
  'shortcuts.ssh': '聚焦 SSH 主机',
117
118
  'shortcuts.newTerminal': '新建终端',
@@ -176,12 +177,23 @@ const DICT_ZH = {
176
177
  'app.manualPath': '或直接输入路径',
177
178
  'app.pathPlaceholder': '例如 /Users/me/project',
178
179
  'activity.explorer': '资源管理器',
180
+ 'activity.search': '搜索',
179
181
  'activity.git': '源代码管理',
180
182
  'activity.ssh': 'SSH 远程',
181
183
  'activity.terminal': '终端',
182
184
  'activity.chat': '古法 AI 助手',
183
185
  'activity.collapseChat': '收起 AI 面板',
184
186
  'activity.expandChat': '展开 AI 面板',
187
+ 'search.placeholder': '搜索项目中的文本,回车立即搜索',
188
+ 'search.caseSensitive': '区分大小写',
189
+ 'search.regex': '使用正则表达式',
190
+ 'search.clear': '清空搜索',
191
+ 'search.searching': '搜索中…',
192
+ 'search.idle': '输入关键字搜索整个项目',
193
+ 'search.noResult': '没有找到匹配结果',
194
+ 'search.summary': '{count} 个结果 · {files} 个文件',
195
+ 'search.truncated': '结果过多已截断,请缩小范围',
196
+ 'search.error': '搜索失败',
185
197
  'explorer.empty': '目录为空',
186
198
  'explorer.newFile': '新建文件',
187
199
  'explorer.newFolder': '新建文件夹',
@@ -341,6 +353,7 @@ const DICT_EN = {
341
353
  'shortcuts.toggleSidebar': 'Toggle sidebar',
342
354
  'shortcuts.closeTab': 'Close current tab',
343
355
  'shortcuts.explorer': 'Focus explorer',
356
+ 'shortcuts.search': 'Focus search',
344
357
  'shortcuts.git': 'Focus source control',
345
358
  'shortcuts.ssh': 'Focus SSH hosts',
346
359
  'shortcuts.newTerminal': 'New terminal',
@@ -396,12 +409,23 @@ const DICT_EN = {
396
409
  'app.manualPath': 'Or type a path',
397
410
  'app.pathPlaceholder': 'e.g. /Users/me/project',
398
411
  'activity.explorer': 'Explorer',
412
+ 'activity.search': 'Search',
399
413
  'activity.git': 'Source control',
400
414
  'activity.ssh': 'SSH',
401
415
  'activity.terminal': 'Terminal',
402
416
  'activity.chat': 'Gufa AI',
403
417
  'activity.collapseChat': 'Collapse AI panel',
404
418
  'activity.expandChat': 'Expand AI panel',
419
+ 'search.placeholder': 'Search text across the project (Enter to run)',
420
+ 'search.caseSensitive': 'Match case',
421
+ 'search.regex': 'Use regular expression',
422
+ 'search.clear': 'Clear search',
423
+ 'search.searching': 'Searching…',
424
+ 'search.idle': 'Type a keyword to search the whole project',
425
+ 'search.noResult': 'No matches found',
426
+ 'search.summary': '{count} results · {files} files',
427
+ 'search.truncated': 'Too many results, truncated — narrow the query',
428
+ 'search.error': 'Search failed',
405
429
  'explorer.empty': 'Folder is empty',
406
430
  'explorer.newFile': 'New file',
407
431
  'explorer.newFolder': 'New folder',
@@ -1651,6 +1675,29 @@ html[data-platform=darwin][data-fullscreen] .gufa-titlebar{height:44px;padding-l
1651
1675
  .gufa-explorer-notice{margin:4px 10px 0;padding:3px 8px;border-radius:6px;font-size:11px;line-height:1.5;color:var(--gufa-text);
1652
1676
  background:color-mix(in srgb, var(--gufa-accent) 14%, transparent);border:0.5px solid color-mix(in srgb, var(--gufa-accent) 40%, transparent);
1653
1677
  overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1678
+ /* ── 搜索面板(全局文本搜索) ───────────────────────────────────────── */
1679
+ .gufa-search-bar{display:flex;flex-direction:column;gap:6px;padding:6px 8px;border-bottom:1px solid var(--gufa-border);flex:0 0 auto}
1680
+ .gufa-search-input-wrap{display:flex;align-items:center;gap:6px;height:28px;padding:0 8px;border-radius:7px;border:1px solid var(--gufa-border);background:var(--gufa-layer2);color:var(--gufa-text-dim)}
1681
+ .gufa-search-input-wrap:focus-within{border-color:var(--gufa-accent)}
1682
+ .gufa-search-input{flex:1 1 auto;min-width:0;height:100%;border:0;background:transparent;color:var(--gufa-text);font-size:12px;outline:none}
1683
+ .gufa-search-input::placeholder{color:var(--gufa-text-dim)}
1684
+ .gufa-search-toggles{display:flex;align-items:center;gap:5px;min-height:22px}
1685
+ .gufa-search-toggle{height:22px;min-width:25px;padding:0 5px;border-radius:5px;border:1px solid var(--gufa-border);background:transparent;color:var(--gufa-text-dim);font:600 11px ui-monospace,Menlo,Consolas,monospace;cursor:pointer}
1686
+ .gufa-search-toggle:hover{color:var(--gufa-text);background:var(--gufa-hover)}
1687
+ .gufa-search-toggle[data-active]{background:var(--gufa-accent);border-color:var(--gufa-accent);color:#fff}
1688
+ .gufa-search-summary{margin-left:auto;font-size:11px;color:var(--gufa-text-dim);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
1689
+ .gufa-search-file{margin:0 6px}
1690
+ .gufa-search-file-head{display:flex;align-items:center;gap:5px;width:100%;height:24px;padding:0 6px;border:0;background:transparent;color:var(--gufa-text);border-radius:5px;cursor:pointer;text-align:left}
1691
+ .gufa-search-file-head:hover{background:var(--gufa-hover)}
1692
+ .gufa-search-file-name{flex:0 0 auto;max-width:55%;font-size:12px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1693
+ .gufa-search-file-dir{flex:1 1 auto;min-width:0;font-size:10.5px;color:var(--gufa-text-dim);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1694
+ .gufa-search-file-count{flex:0 0 auto;font-size:10.5px;color:var(--gufa-text-dim);border:1px solid var(--gufa-border);border-radius:999px;padding:0 6px;line-height:15px}
1695
+ .gufa-search-match{display:flex;align-items:baseline;gap:8px;width:100%;padding:2px 6px 2px 24px;border:0;background:transparent;color:var(--gufa-text-dim);cursor:pointer;border-radius:5px;text-align:left}
1696
+ .gufa-search-match:hover{background:var(--gufa-hover);color:var(--gufa-text)}
1697
+ .gufa-search-line{flex:0 0 auto;min-width:24px;text-align:right;font:11px ui-monospace,Menlo,Consolas,monospace;opacity:.65}
1698
+ .gufa-search-text{flex:1 1 auto;min-width:0;font:11.5px ui-monospace,Menlo,Consolas,monospace;white-space:pre;overflow:hidden;text-overflow:ellipsis}
1699
+ .gufa-search-hit{background:rgba(192,57,43,.38);color:var(--gufa-text);border-radius:2px;padding:0 1px}
1700
+
1654
1701
  .gufa-tree-chevron{width:14px;flex:0 0 auto;opacity:.7;display:flex;align-items:center;justify-content:center}
1655
1702
  .gufa-tree-icon{width:15px;flex:0 0 auto;opacity:.85;display:flex;align-items:center;justify-content:center}
1656
1703
  .gufa-tree-badge{font-size:10px;color:var(--gufa-accent);flex:0 0 auto;font-weight:600}
@@ -533,6 +533,7 @@
533
533
  const propsRef = useRef(props)
534
534
  const activePathRef = useRef(activePath)
535
535
  const statusRef = useRef('loading')
536
+ const pendingRevealRef = useRef(null)
536
537
 
537
538
  /** idle → loading → ready / error */
538
539
  const [status, setStatus] = useState('loading')
@@ -970,6 +971,17 @@
970
971
  }
971
972
  }
972
973
  reportCursor()
974
+ const pending = pendingRevealRef.current
975
+ if (pending !== null && pending !== undefined && pending.path === targetTab.path) {
976
+ pendingRevealRef.current = null
977
+ try {
978
+ editor.setPosition({ lineNumber: pending.line, column: pending.column })
979
+ editor.revealLineInCenter(pending.line)
980
+ editor.focus()
981
+ } catch {
982
+ /* ignore */
983
+ }
984
+ }
973
985
  /* 打开/切换文件不抢焦点:只有用户点击编辑区时才进入键盘编辑 */
974
986
  }
975
987
  } else if (targetTab !== null) {
@@ -977,6 +989,31 @@
977
989
  }
978
990
  }, [status, tabs, activePath, root, reportCursor, disposeAllModels, disposeModelAt])
979
991
 
992
+ /* 搜索面板点击结果 → 打开文件并跳到对应行列(由 App 通过 bus 发来) */
993
+ useEffect(() => {
994
+ if (G.bus === null || G.bus === undefined || typeof G.bus.on !== 'function') return undefined
995
+ return G.bus.on('editor:reveal', (detail) => {
996
+ const editor = editorRef.current
997
+ if (editor === null || editor === undefined) return
998
+ const rawLine = Number(detail?.line)
999
+ const rawColumn = Number(detail?.column)
1000
+ const line = Number.isFinite(rawLine) ? Math.max(1, Math.trunc(rawLine)) : 1
1001
+ const column = Number.isFinite(rawColumn) ? Math.max(1, Math.trunc(rawColumn)) : 1
1002
+ const path = typeof detail?.path === 'string' && detail.path !== '' ? detail.path : null
1003
+ if (path !== null && modelPathRef.current !== path) {
1004
+ pendingRevealRef.current = { path, line, column }
1005
+ return
1006
+ }
1007
+ try {
1008
+ editor.setPosition({ lineNumber: line, column })
1009
+ editor.revealLineInCenter(line)
1010
+ editor.focus()
1011
+ } catch (error) {
1012
+ /* ignore */
1013
+ }
1014
+ })
1015
+ }, [])
1016
+
980
1017
  /* ── Git diff 视图:Monaco DiffEditor(未暂存的一侧可编辑并保存) ── */
981
1018
  useEffect(() => {
982
1019
  const disposeDiff = () => {
@@ -510,6 +510,219 @@ G.MenuItem = function MenuItem(props) {
510
510
  )
511
511
  }
512
512
 
513
+ /* ── 全局搜索(左侧「搜索」面板) ──────────────────────────────────────── */
514
+ G.SearchPanel = function SearchPanel(props) {
515
+ const t = G.useT()
516
+ const root = props.root
517
+ const [query, setQuery] = useState('')
518
+ const [caseSensitive, setCaseSensitive] = useState(false)
519
+ const [regex, setRegex] = useState(false)
520
+ const [status, setStatus] = useState('idle')
521
+ const [result, setResult] = useState(null)
522
+ const [error, setError] = useState('')
523
+ const [collapsed, setCollapsed] = useState({})
524
+ const inputRef = useRef(null)
525
+ const requestRef = useRef(0)
526
+
527
+ const focusInput = useCallback(() => {
528
+ const node = inputRef.current
529
+ if (node === null || node === undefined) return
530
+ try {
531
+ node.focus()
532
+ if (typeof node.select === 'function') node.select()
533
+ } catch {
534
+ /* ignore */
535
+ }
536
+ }, [])
537
+
538
+ const runSearch = useCallback(async (value) => {
539
+ const text = String(value ?? '').trim()
540
+ if (text === '' || typeof root !== 'string' || root === '') {
541
+ requestRef.current += 1
542
+ setResult(null)
543
+ setStatus('idle')
544
+ setError('')
545
+ return
546
+ }
547
+ const seq = requestRef.current + 1
548
+ requestRef.current = seq
549
+ setStatus('loading')
550
+ setError('')
551
+ try {
552
+ const value = await G.api('fs.search', {
553
+ root,
554
+ query: text,
555
+ options: { caseSensitive, regex, maxFiles: 200, maxMatches: 500 },
556
+ })
557
+ if (seq !== requestRef.current) return
558
+ setResult(value)
559
+ setStatus('ready')
560
+ } catch (err) {
561
+ if (seq !== requestRef.current) return
562
+ setResult(null)
563
+ setError(G.errorText(err))
564
+ setStatus('error')
565
+ }
566
+ }, [root, caseSensitive, regex])
567
+
568
+ /* 输入防抖搜索(回车立即搜索) */
569
+ useEffect(() => {
570
+ if (typeof root !== 'string' || root === '') return undefined
571
+ const text = query.trim()
572
+ if (text === '') {
573
+ setResult(null)
574
+ setStatus('idle')
575
+ setError('')
576
+ return undefined
577
+ }
578
+ const timer = window.setTimeout(() => { void runSearch(text) }, 320)
579
+ return () => window.clearTimeout(timer)
580
+ }, [query, runSearch, root])
581
+
582
+ /* 快捷键/按钮打开搜索面板时聚焦输入框 */
583
+ useEffect(() => {
584
+ if (G.bus === null || G.bus === undefined || typeof G.bus.on !== 'function') return undefined
585
+ return G.bus.on('search:focus', focusInput)
586
+ }, [focusInput])
587
+
588
+ useEffect(() => {
589
+ if (props.active === true) focusInput()
590
+ }, [props.active, focusInput])
591
+
592
+ const summary = (() => {
593
+ if (status === 'loading') return t('search.searching')
594
+ if (status === 'error' || result === null) return ''
595
+ if (result.total === 0) return result.truncated === true ? t('search.truncated') : t('search.noResult')
596
+ const base = t('search.summary', { count: result.total, files: result.files.length })
597
+ return result.truncated === true ? `${base} · ${t('search.truncated')}` : base
598
+ })()
599
+
600
+ const highlight = (match) => {
601
+ const text = typeof match.text === 'string' ? match.text : ''
602
+ const start = Number.isFinite(match.start) ? match.start : -1
603
+ const end = Number.isFinite(match.end) ? match.end : -1
604
+ if (start < 0 || end <= start || start >= text.length) return [text]
605
+ const safeEnd = Math.min(end, text.length)
606
+ return [
607
+ text.slice(0, start),
608
+ h('mark', { key: 'hit', className: 'gufa-search-hit' }, text.slice(start, safeEnd)),
609
+ text.slice(safeEnd),
610
+ ]
611
+ }
612
+
613
+ const body = (() => {
614
+ if (typeof root !== 'string' || root === '') {
615
+ return h('div', { className: 'gufa-hint', style: { padding: '10px 12px' } }, t('explorer.openProjectFirst'))
616
+ }
617
+ if (error !== '') {
618
+ return h('div', { className: 'gufa-error-banner', style: { margin: '8px' } }, h(G.Icon, { name: 'warn', size: 12 }), h('span', null, `${t('search.error')}:${error}`))
619
+ }
620
+ if (status === 'idle') return h('div', { className: 'gufa-hint', style: { padding: '10px 12px' } }, t('search.idle'))
621
+ if (status === 'loading') return h('div', { className: 'gufa-hint', style: { padding: '10px 12px', display: 'flex', gap: 8, alignItems: 'center' } }, h(G.Spinner), t('search.searching'))
622
+ if (result === null || result.total === 0) {
623
+ const emptyText = result !== null && result.truncated === true ? t('search.truncated') : t('search.noResult')
624
+ return h('div', { className: 'gufa-hint', style: { padding: '10px 12px' } }, emptyText)
625
+ }
626
+ return h(
627
+ 'div',
628
+ { className: 'gufa-search-results' },
629
+ ...result.files.map((file) => {
630
+ const isCollapsed = collapsed[file.path] === true
631
+ return h(
632
+ 'div',
633
+ { key: file.path, className: 'gufa-search-file' },
634
+ h(
635
+ 'button',
636
+ {
637
+ type: 'button',
638
+ className: 'gufa-search-file-head',
639
+ title: file.path,
640
+ onClick: () => setCollapsed((current) => ({ ...current, [file.path]: !isCollapsed })),
641
+ },
642
+ h(G.Icon, { name: isCollapsed ? 'chevron-right' : 'chevron-down', size: 11 }),
643
+ h('span', { className: 'gufa-search-file-name' }, G.basename(file.path)),
644
+ h('span', { className: 'gufa-search-file-dir' }, G.dirname(file.path)),
645
+ h('span', { className: 'gufa-search-file-count' }, String(file.matches.length)),
646
+ ),
647
+ isCollapsed
648
+ ? null
649
+ : file.matches.map((match, index) =>
650
+ h(
651
+ 'button',
652
+ {
653
+ key: `${file.path}:${match.line}:${match.column}:${index}`,
654
+ type: 'button',
655
+ className: 'gufa-search-match',
656
+ title: `${file.path}:${match.line}:${match.column}`,
657
+ onClick: () => props.onOpenFile?.(file.path, match.line, match.column),
658
+ },
659
+ h('span', { className: 'gufa-search-line' }, String(match.line)),
660
+ h('span', { className: 'gufa-search-text' }, ...highlight(match)),
661
+ ),
662
+ ),
663
+ )
664
+ }),
665
+ )
666
+ })()
667
+
668
+ return h(
669
+ 'div',
670
+ { className: 'gufa-search-panel', style: { display: 'flex', flexDirection: 'column', flex: '1 1 auto', minHeight: 0 } },
671
+ h('div', { className: 'gufa-panel-head' }, h('span', { className: 'gufa-panel-head-title' }, t('activity.search'))),
672
+ h(
673
+ 'div',
674
+ { className: 'gufa-search-bar' },
675
+ h(
676
+ 'div',
677
+ { className: 'gufa-search-input-wrap' },
678
+ h(G.Icon, { name: 'search', size: 13 }),
679
+ h('input', {
680
+ ref: inputRef,
681
+ className: 'gufa-search-input',
682
+ type: 'text',
683
+ value: query,
684
+ placeholder: t('search.placeholder'),
685
+ spellCheck: false,
686
+ onChange: (event) => setQuery(event.target.value),
687
+ onKeyDown: (event) => {
688
+ if (event.key === 'Enter') {
689
+ event.preventDefault()
690
+ void runSearch(query)
691
+ } else if (event.key === 'Escape') {
692
+ event.preventDefault()
693
+ setQuery('')
694
+ inputRef.current?.blur?.()
695
+ }
696
+ },
697
+ }),
698
+ query === ''
699
+ ? null
700
+ : h(G.IconButton, { title: t('search.clear'), onClick: () => { setQuery(''); focusInput() } }, h(G.Icon, { name: 'close', size: 11 })),
701
+ ),
702
+ h(
703
+ 'div',
704
+ { className: 'gufa-search-toggles' },
705
+ h('button', {
706
+ type: 'button',
707
+ className: 'gufa-search-toggle',
708
+ 'data-active': caseSensitive ? '' : undefined,
709
+ title: t('search.caseSensitive'),
710
+ onClick: () => setCaseSensitive((value) => !value),
711
+ }, 'Aa'),
712
+ h('button', {
713
+ type: 'button',
714
+ className: 'gufa-search-toggle',
715
+ 'data-active': regex ? '' : undefined,
716
+ title: t('search.regex'),
717
+ onClick: () => setRegex((value) => !value),
718
+ }, '.*'),
719
+ h('span', { className: 'gufa-search-summary', title: summary }, summary),
720
+ ),
721
+ ),
722
+ h('div', { className: 'gufa-panel-body gufa-scroll' }, body),
723
+ )
724
+ }
725
+
513
726
  /* ── 源代码管理(Git) ─────────────────────────────────────────────────── */
514
727
  G.GitPanel = function GitPanel(props) {
515
728
  const t = G.useT()
@@ -46,6 +46,7 @@ G.shortcutAction = function shortcutAction(event) {
46
46
  }
47
47
  if (event.shiftKey === true) {
48
48
  if (key === 'e') return 'panelExplorer'
49
+ if (key === 'f') return 'panelSearch'
49
50
  if (key === 'g') return 'panelGit'
50
51
  if (key === 'h' || key === 'u') return 'panelSsh'
51
52
  if (key === 'b') return 'toggleSidebar'
@@ -160,6 +161,7 @@ const GUFA_SHORTCUT_COMMANDS = [
160
161
  { action: 'toggleSidebar', id: 'gufa.ide.toggleSidebar', labelKey: 'shortcuts.toggleSidebar', code: 'KeyB', modifiers: ['primary', 'shift'], regions: ['page', 'editable'] },
161
162
  { action: 'closeTab', id: 'gufa.ide.closeTab', labelKey: 'shortcuts.closeTab', code: 'KeyW', modifiers: ['primary', 'shift'], regions: ['page', 'editable'] },
162
163
  { action: 'panelExplorer', id: 'gufa.ide.panelExplorer', labelKey: 'shortcuts.explorer', code: 'KeyE', modifiers: ['primary', 'shift'], regions: ['page', 'editable'] },
164
+ { action: 'panelSearch', id: 'gufa.ide.panelSearch', labelKey: 'shortcuts.search', code: 'KeyF', modifiers: ['primary', 'shift'], regions: ['page', 'editable'] },
163
165
  { action: 'panelGit', id: 'gufa.ide.panelGit', labelKey: 'shortcuts.git', code: 'KeyG', modifiers: ['primary', 'shift'], regions: ['page', 'editable'] },
164
166
  { action: 'panelSsh', id: 'gufa.ide.panelSsh', labelKey: 'shortcuts.ssh', code: 'KeyU', modifiers: ['primary', 'shift'], regions: ['page', 'editable'] },
165
167
  { action: 'newTerminal', id: 'gufa.ide.newTerminal', labelKey: 'shortcuts.newTerminal', code: 'Backquote', modifiers: ['control', 'shift'], regions: ['page', 'editable', 'terminal'] },
@@ -480,6 +482,7 @@ G.SHORTCUTS = [
480
482
  { action: 'toggleSidebar', labelKey: 'shortcuts.toggleSidebar', keys: ['B'], shift: false },
481
483
  { action: 'closeTab', labelKey: 'shortcuts.closeTab', keys: ['W'], shift: false },
482
484
  { action: 'panelExplorer', labelKey: 'shortcuts.explorer', keys: ['E'], shift: true },
485
+ { action: 'panelSearch', labelKey: 'shortcuts.search', keys: ['F'], shift: true },
483
486
  { action: 'panelGit', labelKey: 'shortcuts.git', keys: ['G'], shift: true },
484
487
  { action: 'panelSsh', labelKey: 'shortcuts.ssh', keys: ['U'], shift: true },
485
488
  { action: 'newTerminal', labelKey: 'shortcuts.newTerminal', keys: ['`'], shift: true, macText: '⌃⇧`', otherText: 'Ctrl+Shift+`' },