forked from shuyu-labs/WebCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileSearchPanel.razor
More file actions
389 lines (349 loc) · 16.7 KB
/
FileSearchPanel.razor
File metadata and controls
389 lines (349 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
@using WebCodeCli.Domain.Domain.Model
@using WebCodeCli.Domain.Domain.Service
@using System.Text.Json
@inject IFileSearchService FileSearchService
@inject ICliExecutorService CliExecutorService
@inject ILocalizationService L
<div class="h-full flex flex-col bg-white">
<!-- 头部:搜索表单 -->
<div class="p-3 sm:p-4 border-b border-gray-200 flex-shrink-0 space-y-3">
<!-- 调试信息 -->
@if (!string.IsNullOrEmpty(_debugMessage))
{
<div class="bg-blue-50 border-l-4 border-blue-500 text-blue-700 px-3 py-2 rounded text-xs">
<strong>@T("fileSearch.debugLabel"):</strong> @_debugMessage
</div>
}
<!-- 搜索输入 -->
<div class="flex items-center gap-2">
<input type="text"
@bind="_searchTerm"
@bind:event="oninput"
@onkeydown="HandleKeyDown"
placeholder="@T("fileSearch.searchPlaceholder")"
class="flex-1 px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-gray-500" />
<button @onclick="PerformSearch"
disabled="@_isSearching"
class="btn-primary px-4 py-2 text-sm flex items-center gap-2 disabled:opacity-50 hover:opacity-90 active:scale-95 transition-all">
@if (_isSearching)
{
<div class="animate-spin h-4 w-4 border-2 border-white rounded-full border-t-transparent"></div>
}
else
{
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
</svg>
}
@T("common.search")
</button>
</div>
<!-- 搜索选项 -->
<div class="flex flex-wrap items-center gap-3 text-sm">
<label class="flex items-center gap-1.5 cursor-pointer">
<input type="checkbox" @bind="_options.CaseSensitive" class="rounded" />
<span>@T("fileSearch.caseSensitive")</span>
</label>
<label class="flex items-center gap-1.5 cursor-pointer">
<input type="checkbox" @bind="_options.WholeWord" class="rounded" />
<span>@T("fileSearch.wholeWord")</span>
</label>
<label class="flex items-center gap-1.5 cursor-pointer">
<input type="checkbox" @bind="_options.UseRegex" class="rounded" />
<span>@T("fileSearch.regex")</span>
</label>
<div class="flex items-center gap-2 ml-auto">
<label class="text-gray-600">@T("fileSearch.fileType"):</label>
<input type="text"
@bind="_fileTypeFilter"
@bind:event="oninput"
placeholder="@T("fileSearch.fileTypePlaceholder")"
class="px-2 py-1 border border-gray-200 rounded text-xs w-32" />
</div>
</div>
</div>
<!-- 内容区域:搜索结果 -->
<div class="flex-1 overflow-y-auto p-4">
@if (_searchResults == null)
{
<!-- 初始状态 -->
<div class="flex flex-col items-center justify-center h-full text-gray-400">
<div class="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mb-4">
<svg class="w-10 h-10 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
</svg>
</div>
<p class="text-base font-semibold text-gray-600">@T("fileSearch.initialTitle")</p>
<p class="text-sm mt-2 text-gray-500">@T("fileSearch.initialDesc")</p>
</div>
}
else if (!_searchResults.Any())
{
<!-- 无结果 -->
<div class="flex flex-col items-center justify-center h-full text-gray-400">
<div class="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mb-4">
<svg class="w-10 h-10 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
</svg>
</div>
<p class="text-base font-semibold text-gray-600">@T("fileSearch.noResultsTitle")</p>
<p class="text-sm mt-2 text-gray-500">@T("fileSearch.noResultsDesc")</p>
</div>
}
else
{
<!-- 搜索结果统计 -->
<div class="mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200">
<div class="flex items-center justify-between text-sm">
<span class="text-gray-700">
@T("fileSearch.resultsSummary", ("count", _searchResults.Count.ToString()))
</span>
<span class="text-gray-500">
@T("fileSearch.filesSummary", ("count", _searchResults.Select(r => r.FilePath).Distinct().Count().ToString()))
</span>
</div>
</div>
<!-- 结果列表(按文件分组) -->
<div class="space-y-4">
@foreach (var fileGroup in _searchResults.GroupBy(r => r.FilePath))
{
<div class="border border-gray-200 rounded-lg overflow-hidden">
<!-- 文件头部 -->
<div class="bg-gray-50 px-4 py-2 border-b border-gray-200 flex items-center justify-between">
<div class="flex items-center gap-2">
<svg class="w-4 h-4 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"></path>
</svg>
<span class="font-semibold text-gray-800 text-sm">@fileGroup.Key</span>
</div>
<span class="text-xs text-gray-500">@T("fileSearch.matchesInFile", ("count", fileGroup.Count().ToString()))</span>
</div>
<!-- 匹配行列表 -->
<div class="divide-y divide-gray-100">
@foreach (var result in fileGroup.Take(10))
{
<div class="px-4 py-3 hover:bg-gray-50 transition-colors">
<div class="flex items-start gap-3">
<span class="flex-shrink-0 text-xs font-mono text-gray-500 bg-gray-100 px-2 py-1 rounded">
@result.LineNumber
</span>
<div class="flex-1 min-w-0">
<pre class="text-sm font-mono text-gray-800 whitespace-pre-wrap break-all">@HighlightMatches(result)</pre>
@if (result.ContextLines.Any())
{
<div class="mt-2 text-xs text-gray-500 space-y-1">
@foreach (var contextLine in result.ContextLines.Where(c => !c.IsMatch))
{
<div class="flex items-start gap-2">
<span class="text-gray-400 font-mono">@contextLine.LineNumber</span>
<pre class="font-mono opacity-60 flex-1">@contextLine.Content</pre>
</div>
}
</div>
}
</div>
</div>
</div>
}
@if (fileGroup.Count() > 10)
{
<div class="px-4 py-2 bg-gray-50 text-center text-xs text-gray-500">
@T("fileSearch.moreMatches", ("count", (fileGroup.Count() - 10).ToString()))
</div>
}
</div>
</div>
}
</div>
}
</div>
</div>
@code {
[Parameter]
public string SessionId { get; set; } = string.Empty;
private string _searchTerm = string.Empty;
private string _fileTypeFilter = string.Empty;
private SearchOptions _options = new();
private List<SearchResult>? _searchResults = null;
private bool _isSearching = false;
private string _debugMessage = string.Empty;
// 本地化相关
private Dictionary<string, string> _translations = new();
private string _currentLanguage = "zh-CN";
protected override async Task OnInitializedAsync()
{
await LoadTranslationsAsync();
Console.WriteLine($"[FileSearchPanel] 组件已初始化,SessionId: {SessionId}");
_debugMessage = T("fileSearch.debugLoaded", ("id", SessionId));
}
private async Task PerformSearch()
{
Console.WriteLine($"[FileSearchPanel] PerformSearch 被调用,搜索词: '{_searchTerm}'");
_debugMessage = T("fileSearch.debugSearching", ("term", _searchTerm));
StateHasChanged();
await Task.Delay(10); // 确保UI更新
if (string.IsNullOrWhiteSpace(_searchTerm))
{
Console.WriteLine("[FileSearchPanel] 搜索词为空,返回");
_debugMessage = T("fileSearch.debugEmpty");
StateHasChanged();
return;
}
_isSearching = true;
_searchResults = null;
StateHasChanged();
try
{
var workspacePath = CliExecutorService.GetSessionWorkspacePath(SessionId);
Console.WriteLine($"[FileSearchPanel] 工作区路径: {workspacePath}");
_debugMessage = T("fileSearch.debugWorkspacePath", ("path", workspacePath));
StateHasChanged();
if (string.IsNullOrEmpty(workspacePath) || !Directory.Exists(workspacePath))
{
Console.WriteLine($"[FileSearchPanel] 工作区路径无效或不存在");
_debugMessage = T("fileSearch.debugWorkspaceInvalid", ("path", workspacePath));
_searchResults = new List<SearchResult>();
return;
}
// 设置文件类型过滤
_options.FileTypeFilter = _fileTypeFilter;
Console.WriteLine($"[FileSearchPanel] 文件类型过滤: {_fileTypeFilter}");
// 执行搜索
if (_options.UseRegex)
{
Console.WriteLine("[FileSearchPanel] 使用正则表达式搜索");
_debugMessage = T("fileSearch.debugRegexSearch");
StateHasChanged();
_searchResults = await FileSearchService.SearchByRegexAsync(workspacePath, _searchTerm, _options);
}
else
{
Console.WriteLine("[FileSearchPanel] 使用普通文本搜索");
_debugMessage = T("fileSearch.debugTextSearch");
StateHasChanged();
_searchResults = await FileSearchService.SearchInFilesAsync(workspacePath, _searchTerm, _options);
}
Console.WriteLine($"[FileSearchPanel] 搜索完成,找到 {_searchResults?.Count ?? 0} 个结果");
_debugMessage = T("fileSearch.debugCompleted", ("count", (_searchResults?.Count ?? 0).ToString()));
}
catch (Exception ex)
{
Console.WriteLine($"[FileSearchPanel] 搜索失败: {ex.Message}");
Console.WriteLine($"[FileSearchPanel] 异常堆栈: {ex.StackTrace}");
_debugMessage = T("fileSearch.debugFailed", ("message", ex.Message));
_searchResults = new List<SearchResult>();
}
finally
{
_isSearching = false;
StateHasChanged();
}
}
private async Task HandleKeyDown(KeyboardEventArgs e)
{
if (e.Key == "Enter")
{
await PerformSearch();
}
}
private MarkupString HighlightMatches(SearchResult result)
{
if (!result.Matches.Any())
{
return new MarkupString(System.Web.HttpUtility.HtmlEncode(result.LineContent));
}
var html = new System.Text.StringBuilder();
var lastIndex = 0;
foreach (var match in result.Matches.OrderBy(m => m.Start))
{
// 添加匹配前的文本
if (match.Start > lastIndex)
{
html.Append(System.Web.HttpUtility.HtmlEncode(result.LineContent.Substring(lastIndex, match.Start - lastIndex)));
}
// 添加高亮的匹配文本
var length = match.End - match.Start;
html.Append("<mark class=\"bg-yellow-200 text-yellow-900 font-semibold px-1 rounded\">");
html.Append(System.Web.HttpUtility.HtmlEncode(result.LineContent.Substring(match.Start, length)));
html.Append("</mark>");
lastIndex = match.End;
}
// 添加剩余文本
if (lastIndex < result.LineContent.Length)
{
html.Append(System.Web.HttpUtility.HtmlEncode(result.LineContent.Substring(lastIndex)));
}
return new MarkupString(html.ToString());
}
#region 本地化辅助方法
private async Task LoadTranslationsAsync()
{
try
{
_currentLanguage = await L.GetCurrentLanguageAsync();
var allTranslations = await L.GetAllTranslationsAsync(_currentLanguage);
_translations = FlattenTranslations(allTranslations);
}
catch (Exception ex)
{
Console.WriteLine($"[文件搜索] 加载翻译资源失败: {ex.Message}");
}
}
private Dictionary<string, string> FlattenTranslations(Dictionary<string, object> source, string prefix = "")
{
var result = new Dictionary<string, string>();
foreach (var kvp in source)
{
var key = string.IsNullOrEmpty(prefix) ? kvp.Key : $"{prefix}.{kvp.Key}";
if (kvp.Value is JsonElement jsonElement)
{
if (jsonElement.ValueKind == JsonValueKind.Object)
{
var nested = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonElement.GetRawText());
if (nested != null)
{
foreach (var item in FlattenTranslations(nested, key))
{
result[item.Key] = item.Value;
}
}
}
else if (jsonElement.ValueKind == JsonValueKind.String)
{
result[key] = jsonElement.GetString() ?? key;
}
}
else if (kvp.Value is Dictionary<string, object> dict)
{
foreach (var item in FlattenTranslations(dict, key))
{
result[item.Key] = item.Value;
}
}
else if (kvp.Value is string str)
{
result[key] = str;
}
}
return result;
}
private string T(string key)
{
if (_translations.TryGetValue(key, out var translation))
{
return translation;
}
var parts = key.Split('.');
return parts.Length > 0 ? parts[^1] : key;
}
private string T(string key, params (string name, string value)[] parameters)
{
var text = T(key);
foreach (var (name, value) in parameters)
{
text = text.Replace($"{{{name}}}", value);
}
return text;
}
#endregion
}