-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch-renderer.js
More file actions
1140 lines (981 loc) · 38.1 KB
/
Copy pathsearch-renderer.js
File metadata and controls
1140 lines (981 loc) · 38.1 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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 文件类型定义
const FILE_TYPES = {
images: ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp', '.ico', '.tiff'],
documents: ['.pdf', '.doc', '.docx', '.txt', '.rtf', '.odt', '.xls', '.xlsx', '.ppt', '.pptx', '.csv'],
videos: ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.m4v'],
audio: ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.wma', '.m4a'],
archives: ['.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz']
};
// 多语言字典
const i18n = {
'zh-CN': {
title: '文件搜索工具',
appTitle: '文件搜索工具',
headerTitle: '快速文件搜索',
headerSubtitle: '高效搜索文件,支持智能范围缩小和多种文件类型过滤',
folderPlaceholder: '输入要搜索的文件夹路径 (例如: C:\\Users\\Desktop)',
browseBtn: '浏览',
searchPlaceholder: '输入文件名或关键词 (可选)',
searchBtn: '搜索',
stopBtn: '停止',
fileTypeLabel: '文件类型:',
filterAll: '全部',
filterImages: '图像',
filterDocuments: '文档',
filterVideos: '视频',
filterAudio: '音频',
filterArchives: '压缩包',
foundLabel: '找到文件:',
scannedLabel: '已扫描:',
timeLabel: '搜索时间:',
resultsTitle: '搜索结果',
sortDefault: '默认排序',
sortNameAsc: '按名称 (A-Z)',
sortNameDesc: '按名称 (Z-A)',
sortDateDesc: '按日期 (最新)',
sortDateAsc: '按日期 (最旧)',
sortSizeDesc: '按大小 (从大到小)',
sortSizeAsc: '按大小 (从小到大)',
exportBtn: '导出',
clearBtn: '清空结果',
emptyState: '开始搜索以查看结果',
cancelBtn: '取消',
confirmBtn: '确定',
// 动态文本
alertTitle: '提示',
errorTitle: '错误',
warningTitle: '警告',
inputFolderReq: '请输入文件夹路径',
searchSearching: '正在搜索...',
searchStopped: '搜索已停止',
searchError: '搜索出错: ',
searchDone: '搜索完成! 找到 {0} 个文件',
scanning: '正在扫描: ',
size: '大小',
type: '类型',
createTime: '创建时间',
modTime: '修改时间',
accessTime: '访问时间',
noExt: '无扩展名',
openFolderTip: '打开文件夹',
openFileTip: '浏览文件',
propsTip: '查看属性',
exportEmpty: '没有可导出的文件',
exportWarnLarge: '您将导出超过 2GB 的文件或整个磁盘内容!\n总大小: {0}\n请输入 "Yes" 确认操作:',
exportWarnTypeYes: '请输入 "Yes" 以继续',
exportDestReq: '请选择导出目标文件夹',
exportDestSame: '导出目标文件夹不能是搜索目录或其子目录!',
exporting: '正在导出文件...',
exportDone: '导出完成!成功: {0}, 失败: {1}',
exportError: '导出出错: '
},
'en': {
title: 'File Search Tool',
appTitle: 'File Search Tool',
headerTitle: 'Fast File Search',
headerSubtitle: 'Efficiently search files with smart scoping and type filtering',
folderPlaceholder: 'Enter folder path to search (e.g. C:\\Users\\Desktop)',
browseBtn: 'Browse',
searchPlaceholder: 'Enter filename or keywords (optional)',
searchBtn: 'Search',
stopBtn: 'Stop',
fileTypeLabel: 'File Types:',
filterAll: 'All',
filterImages: 'Images',
filterDocuments: 'Documents',
filterVideos: 'Videos',
filterAudio: 'Audio',
filterArchives: 'Archives',
foundLabel: 'Found:',
scannedLabel: 'Scanned:',
timeLabel: 'Search Time:',
resultsTitle: 'Search Results',
sortDefault: 'Default Sort',
sortNameAsc: 'Name (A-Z)',
sortNameDesc: 'Name (Z-A)',
sortDateDesc: 'Date (Newest)',
sortDateAsc: 'Date (Oldest)',
sortSizeDesc: 'Size (Large-Small)',
sortSizeAsc: 'Size (Small-Large)',
exportBtn: 'Export',
clearBtn: 'Clear',
emptyState: 'Start searching to see results',
cancelBtn: 'Cancel',
confirmBtn: 'OK',
// Dynamic texts
alertTitle: 'Info',
errorTitle: 'Error',
warningTitle: 'Warning',
inputFolderReq: 'Please enter a folder path',
searchSearching: 'Searching...',
searchStopped: 'Search stopped',
searchError: 'Search error: ',
searchDone: 'Search complete! Found {0} files',
scanning: 'Scanning: ',
size: 'Size',
type: 'Type',
createTime: 'Created',
modTime: 'Modified',
accessTime: 'Accessed',
noExt: 'No Extension',
openFolderTip: 'Open Folder',
openFileTip: 'Open File',
propsTip: 'Properties',
exportEmpty: 'No files to export',
exportWarnLarge: 'You are about to export more than 2GB or an entire disk!\nTotal size: {0}\nPlease type "Yes" to confirm:',
exportWarnTypeYes: 'Please type "Yes" to continue',
exportDestReq: 'Please select an export destination folder',
exportDestSame: 'Destination folder cannot be inside the search directory!',
exporting: 'Exporting files...',
exportDone: 'Export complete! Success: {0}, Failed: {1}',
exportError: 'Export error: '
}
};
let currentLang = 'zh-CN';
let currentTheme = 'light';
function t(key, ...args) {
let text = i18n[currentLang][key] || key;
args.forEach((arg, i) => {
text = text.replace(`{${i}}`, arg);
});
return text;
}
function updateI18n() {
document.querySelectorAll('[data-i18n]').forEach(el => {
el.textContent = t(el.getAttribute('data-i18n'));
});
document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
el.placeholder = t(el.getAttribute('data-i18n-placeholder'));
});
// Update sort options
const sortSelect = document.getElementById('sortSelect');
if (sortSelect) {
Array.from(sortSelect.options).forEach(opt => {
opt.text = t(opt.getAttribute('data-i18n'));
});
}
}
// Custom Modal Implementation
const modalOverlay = document.getElementById('customModal');
const modalTitle = document.getElementById('modalTitle');
const modalContent = document.getElementById('modalContent');
const modalInputContainer = document.getElementById('modalInputContainer');
const modalInput = document.getElementById('modalInput');
const modalCancelBtn = document.getElementById('modalCancelBtn');
const modalOkBtn = document.getElementById('modalOkBtn');
let modalResolve = null;
function showModal({ title, content, type = 'alert' }) {
return new Promise((resolve) => {
modalTitle.textContent = title;
modalContent.textContent = content;
modalInputContainer.style.display = type === 'prompt' ? 'block' : 'none';
modalCancelBtn.style.display = (type === 'confirm' || type === 'prompt') ? 'block' : 'none';
if (type === 'prompt') {
modalInput.value = '';
setTimeout(() => modalInput.focus(), 100);
}
modalResolve = resolve;
modalOverlay.classList.add('active');
});
}
function closeModal(result) {
modalOverlay.classList.remove('active');
if (modalResolve) {
modalResolve(result);
modalResolve = null;
}
}
modalOkBtn.addEventListener('click', () => {
if (modalInputContainer.style.display === 'block') {
closeModal(modalInput.value);
} else {
closeModal(true);
}
});
modalCancelBtn.addEventListener('click', () => {
closeModal(false);
});
async function customAlert(content, title) {
await showModal({ title: title || t('alertTitle'), content, type: 'alert' });
}
async function customConfirm(content, title) {
return await showModal({ title: title || t('alertTitle'), content, type: 'confirm' });
}
async function customPrompt(content, title) {
return await showModal({ title: title || t('alertTitle'), content, type: 'prompt' });
}
// 全局状态
let searchState = {
isSearching: false,
shouldStop: false,
foundFiles: [],
selectedFiles: new Set(), // 选中的文件
scannedPaths: new Set(),
startTime: null,
scannedCount: 0,
currentSort: 'default',
displayedCount: 0, // 当前显示的文件数量
batchSize: 1000, // 每批显示1000个
virtualScroll: {
itemHeight: 88, // 每个结果项的高度
visibleCount: 20, // 可见项数量
startIndex: 0,
endIndex: 20
}
};
// DOM 元素
const elements = {
folderPath: document.getElementById('folderPath'),
searchQuery: document.getElementById('searchQuery'),
searchBtn: document.getElementById('searchBtn'),
stopBtn: document.getElementById('stopBtn'),
browseFolderBtn: document.getElementById('browseFolderBtn'),
progressBar: document.getElementById('progressBar'),
statusMessage: document.getElementById('statusMessage'),
statsBar: document.getElementById('statsBar'),
foundCount: document.getElementById('foundCount'),
scannedCount: document.getElementById('scannedCount'),
searchTime: document.getElementById('searchTime'),
resultsContainer: document.getElementById('resultsContainer'),
resultsList: document.getElementById('resultsList'),
clearResultsBtn: document.getElementById('clearResultsBtn'),
exportBtn: document.getElementById('exportBtn'),
deleteBtn: document.getElementById('deleteBtn'),
selectAllBtn: document.getElementById('selectAllBtn'),
sortSelect: document.getElementById('sortSelect'),
filterAll: document.getElementById('filterAll'),
filterImages: document.getElementById('filterImages'),
filterDocuments: document.getElementById('filterDocuments'),
filterVideos: document.getElementById('filterVideos'),
filterAudio: document.getElementById('filterAudio'),
filterArchives: document.getElementById('filterArchives'),
langToggleBtn: document.getElementById('langToggleBtn'),
themeToggleBtn: document.getElementById('themeToggleBtn')
};
// 语言切换
elements.langToggleBtn.addEventListener('click', () => {
currentLang = currentLang === 'zh-CN' ? 'en' : 'zh-CN';
updateI18n();
if (!searchState.isSearching && searchState.foundFiles.length > 0) {
renderResults();
}
});
// 主题切换
elements.themeToggleBtn.addEventListener('click', () => {
currentTheme = currentTheme === 'light' ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', currentTheme);
});
// 文件类型过滤器管理
elements.filterAll.addEventListener('change', (e) => {
if (e.target.checked) {
elements.filterImages.checked = false;
elements.filterDocuments.checked = false;
elements.filterVideos.checked = false;
elements.filterAudio.checked = false;
elements.filterArchives.checked = false;
}
});
[elements.filterImages, elements.filterDocuments, elements.filterVideos,
elements.filterAudio, elements.filterArchives].forEach(checkbox => {
checkbox.addEventListener('change', (e) => {
if (e.target.checked) {
elements.filterAll.checked = false;
}
});
});
// 浏览文件夹
elements.browseFolderBtn.addEventListener('click', async () => {
const path = await window.electronAPI.selectFolder();
if (path) {
elements.folderPath.value = path;
}
});
// 搜索按钮
elements.searchBtn.addEventListener('click', () => {
startSearch();
});
// 停止按钮
elements.stopBtn.addEventListener('click', () => {
stopSearch();
});
// 清空结果按钮
elements.clearResultsBtn.addEventListener('click', () => {
clearResults();
});
// 全选按钮
elements.selectAllBtn.addEventListener('click', () => {
toggleSelectAll();
});
// 删除按钮
elements.deleteBtn.addEventListener('click', async () => {
await deleteSelectedFiles();
});
// 回车键搜索
elements.searchQuery.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
startSearch();
}
});
// 排序切换
elements.sortSelect.addEventListener('change', (e) => {
searchState.currentSort = e.target.value;
renderResults();
});
// 导出按钮
elements.exportBtn.addEventListener('click', async () => {
const filesToExport = searchState.selectedFiles.size > 0
? Array.from(searchState.selectedFiles).map(path => searchState.foundFiles.find(f => f.path === path))
: searchState.foundFiles;
if (filesToExport.length === 0) {
await customAlert(t('exportEmpty'), t('alertTitle'));
return;
}
let totalSize = 0;
filesToExport.forEach(f => totalSize += f.size);
const pathStr = elements.folderPath.value.trim();
const isRoot = /^[a-zA-Z]:\\?$/.test(pathStr) || pathStr === '/' || pathStr === '\\';
const isLarge = totalSize > 2 * 1024 * 1024 * 1024; // 2GB
if (isRoot || isLarge) {
const input = await customPrompt(t('exportWarnLarge', formatFileSize(totalSize)), t('warningTitle'));
if (input !== 'Yes') {
await customAlert(t('exportWarnTypeYes'), t('alertTitle'));
return;
}
}
const destPath = await window.electronAPI.selectFolder();
if (!destPath) {
return;
}
// 检查目标路径不能是搜索路径
if (destPath.startsWith(elements.folderPath.value.trim())) {
await customAlert(t('exportDestSame'), t('errorTitle'));
return;
}
// 显示导出进度
elements.progressBar.style.display = 'block';
updateStatus(t('exporting'), true);
try {
const result = await window.electronAPI.exportFiles({
files: filesToExport,
destFolder: destPath
});
elements.progressBar.style.display = 'none';
await customAlert(t('exportDone', result.successCount, result.failCount), t('alertTitle'));
updateStatus('');
} catch (error) {
elements.progressBar.style.display = 'none';
console.error('Export error:', error);
await customAlert(t('exportError') + error.message, t('errorTitle'));
updateStatus('');
}
});
// 加载更多结果
function loadMoreResults() {
const currentDisplayed = searchState.displayedCount;
const totalFiles = searchState.foundFiles.length;
if (currentDisplayed >= totalFiles) {
return; // 已经全部显示
}
// 获取排序后的文件列表
let files = [...searchState.foundFiles];
const sort = searchState.currentSort;
if (sort === 'nameAsc') {
files.sort((a, b) => a.name.localeCompare(b.name));
} else if (sort === 'nameDesc') {
files.sort((a, b) => b.name.localeCompare(a.name));
} else if (sort === 'dateDesc') {
files.sort((a, b) => new Date(b.mtime) - new Date(a.mtime));
} else if (sort === 'dateAsc') {
files.sort((a, b) => new Date(a.mtime) - new Date(b.mtime));
} else if (sort === 'sizeDesc') {
files.sort((a, b) => b.size - a.size);
} else if (sort === 'sizeAsc') {
files.sort((a, b) => a.size - b.size);
}
// 计算要显示的范围
const endIndex = Math.min(currentDisplayed + searchState.batchSize, totalFiles);
const filesToShow = files.slice(currentDisplayed, endIndex);
// 移除"继续显示"按钮
const existingBtn = elements.resultsList.querySelector('.load-more-container');
if (existingBtn) {
existingBtn.remove();
}
// 批量添加到DOM
const fragment = document.createDocumentFragment();
filesToShow.forEach(file => {
fragment.appendChild(createResultItem(file));
});
elements.resultsList.appendChild(fragment);
// 更新显示计数
searchState.displayedCount = endIndex;
// 更新"继续显示"按钮
updateLoadMoreButton();
}
// 添加"继续显示"按钮
function addLoadMoreButton(remainingCount) {
// 先移除已存在的按钮,避免重复
const existingBtn = elements.resultsList.querySelector('.load-more-container');
if (existingBtn) {
existingBtn.remove();
}
const container = document.createElement('div');
container.className = 'load-more-container';
container.innerHTML = `
<button class="btn btn-primary load-more-btn">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
<span>继续显示 (剩余 ${remainingCount} 个文件)</span>
</button>
`;
const btn = container.querySelector('.load-more-btn');
btn.addEventListener('click', loadMoreResults);
elements.resultsList.appendChild(container);
}
// 更新"继续显示"按钮状态
function updateLoadMoreButton() {
const existingBtn = elements.resultsList.querySelector('.load-more-container');
// 检查是否需要显示按钮
const shouldShow = searchState.displayedCount >= searchState.batchSize &&
searchState.foundFiles.length > searchState.displayedCount;
if (shouldShow) {
const remaining = searchState.foundFiles.length - searchState.displayedCount;
if (existingBtn) {
// 更新现有按钮的文本
const span = existingBtn.querySelector('span');
if (span) {
span.textContent = `继续显示 (剩余 ${remaining} 个文件)`;
}
} else {
// 添加新按钮
addLoadMoreButton(remaining);
}
} else {
// 移除按钮
if (existingBtn) {
existingBtn.remove();
}
}
}
// 删除选中的文件
async function deleteSelectedFiles() {
if (searchState.selectedFiles.size === 0) {
await customAlert('请先选择要删除的文件', t('alertTitle'));
return;
}
const confirmed = await customConfirm(
`确定要删除选中的 ${searchState.selectedFiles.size} 个文件吗?\n此操作不可恢复!`,
t('warningTitle')
);
if (!confirmed) return;
const filesToDelete = Array.from(searchState.selectedFiles).map(path =>
searchState.foundFiles.find(f => f.path === path)
);
elements.progressBar.style.display = 'block';
updateStatus('正在删除文件...', true);
try {
const result = await window.electronAPI.deleteFiles({
files: filesToDelete
});
elements.progressBar.style.display = 'none';
await customAlert(`删除完成! 成功: ${result.successCount}, 失败: ${result.failCount}`, t('alertTitle'));
// 从结果中移除已删除的文件
searchState.foundFiles = searchState.foundFiles.filter(f => !searchState.selectedFiles.has(f.path));
searchState.selectedFiles.clear();
// 重新渲染结果
searchState.displayedCount = 0;
renderResults();
updateStats();
updateStatus('');
} catch (error) {
elements.progressBar.style.display = 'none';
console.error('Delete error:', error);
await customAlert('删除出错: ' + error.message, t('errorTitle'));
updateStatus('');
}
}
// 全选/取消全选
function toggleSelectAll() {
if (searchState.selectedFiles.size === searchState.foundFiles.length) {
// 取消全选
searchState.selectedFiles.clear();
} else {
// 全选
searchState.foundFiles.forEach(f => searchState.selectedFiles.add(f.path));
}
updateSelectAllButton();
renderResults();
}
// 更新全选按钮文本
function updateSelectAllButton() {
const btn = elements.selectAllBtn;
if (searchState.selectedFiles.size === searchState.foundFiles.length && searchState.foundFiles.length > 0) {
btn.textContent = '取消全选';
} else {
btn.textContent = `全选 (${searchState.selectedFiles.size}/${searchState.foundFiles.length})`;
}
}
// 开始搜索
async function startSearch() {
const folderPath = elements.folderPath.value.trim();
if (!folderPath) {
await customAlert(t('inputFolderReq'), t('alertTitle'));
return;
}
// 重置状态
searchState = {
isSearching: true,
shouldStop: false,
foundFiles: [],
selectedFiles: new Set(),
scannedPaths: new Set(),
startTime: Date.now(),
scannedCount: 0,
currentSort: elements.sortSelect.value,
displayedCount: 0,
batchSize: 1000,
virtualScroll: {
itemHeight: 88,
visibleCount: 20,
startIndex: 0,
endIndex: 20
}
};
// 更新UI
elements.searchBtn.style.display = 'none';
elements.stopBtn.style.display = 'flex';
elements.progressBar.style.display = 'block';
elements.statsBar.style.display = 'flex';
elements.resultsContainer.style.display = 'block';
elements.resultsList.innerHTML = '';
searchState.displayedCount = 0; // 重置显示计数
updateStats();
// 获取过滤器
const filters = getActiveFilters();
const searchQuery = elements.searchQuery.value.trim().toLowerCase();
// 开始搜索
updateStatus(t('searchSearching'), true);
try {
await window.electronAPI.searchFiles({
folderPath,
searchQuery,
filters
});
} catch (error) {
console.error('搜索错误:', error);
updateStatus(t('searchError') + error.message, false);
}
}
// 停止搜索
function stopSearch() {
searchState.shouldStop = true;
searchState.isSearching = false;
elements.searchBtn.style.display = 'flex';
elements.stopBtn.style.display = 'none';
elements.progressBar.style.display = 'none';
// 清除节流定时器并立即渲染剩余结果
if (addResultThrottle) {
clearTimeout(addResultThrottle);
addResultThrottle = null;
}
// 渲染所有待处理的结果
if (pendingResults.length > 0) {
if (searchState.currentSort === 'default') {
const canAddMore = searchState.displayedCount < searchState.batchSize;
if (canAddMore) {
const toAdd = pendingResults.slice(0, searchState.batchSize - searchState.displayedCount);
const fragment = document.createDocumentFragment();
toAdd.forEach(file => {
fragment.appendChild(createResultItem(file));
});
elements.resultsList.appendChild(fragment);
searchState.displayedCount += toAdd.length;
}
}
pendingResults = [];
}
// 更新"继续显示"按钮
updateLoadMoreButton();
updateStatus(t('searchStopped'), false);
updateSelectAllButton();
window.electronAPI.stopSearch();
}
// 清空结果
function clearResults() {
searchState.foundFiles = [];
searchState.selectedFiles.clear();
searchState.scannedPaths.clear();
searchState.scannedCount = 0;
searchState.displayedCount = 0;
elements.resultsList.innerHTML = `
<div class="empty-state">
<svg viewBox="0 0 24 24">
<circle cx="11" cy="11" r="8"/>
<path d="m21 21-4.35-4.35"/>
</svg>
<p>${t('emptyState')}</p>
</div>
`;
elements.resultsContainer.style.display = 'none';
elements.statsBar.style.display = 'none';
updateStats();
updateSelectAllButton();
updateStatus('', false);
}
// 获取激活的过滤器
function getActiveFilters() {
if (elements.filterAll.checked) {
return null; // 搜索所有文件
}
const filters = [];
if (elements.filterImages.checked) filters.push(...FILE_TYPES.images);
if (elements.filterDocuments.checked) filters.push(...FILE_TYPES.documents);
if (elements.filterVideos.checked) filters.push(...FILE_TYPES.videos);
if (elements.filterAudio.checked) filters.push(...FILE_TYPES.audio);
if (elements.filterArchives.checked) filters.push(...FILE_TYPES.archives);
return filters.length > 0 ? filters : null;
}
// 更新统计信息
function updateStats() {
elements.foundCount.textContent = searchState.foundFiles.length;
elements.scannedCount.textContent = searchState.scannedCount;
if (searchState.startTime) {
const elapsed = ((Date.now() - searchState.startTime) / 1000).toFixed(1);
elements.searchTime.textContent = elapsed + 's';
}
}
// 更新状态消息
function updateStatus(message, showSpinner = false) {
if (showSpinner) {
elements.statusMessage.innerHTML = `
<div class="loading-spinner"></div>
<span>${escapeHtml(message)}</span>
`;
} else {
elements.statusMessage.textContent = message;
}
}
// 添加搜索结果并渲染 (优化版 - 使用节流)
let addResultThrottle = null;
let pendingResults = [];
function addResult(fileInfo) {
if (searchState.scannedPaths.has(fileInfo.path)) {
return;
}
searchState.scannedPaths.add(fileInfo.path);
searchState.foundFiles.push(fileInfo);
pendingResults.push(fileInfo);
// 节流渲染 - 每100ms或累积50个结果才渲染一次
if (!addResultThrottle) {
addResultThrottle = setTimeout(() => {
if (searchState.currentSort === 'default' && pendingResults.length > 0) {
// 只渲染在显示范围内的结果
const canAddMore = searchState.displayedCount < searchState.batchSize;
if (canAddMore) {
const toAdd = pendingResults.slice(0, searchState.batchSize - searchState.displayedCount);
const fragment = document.createDocumentFragment();
toAdd.forEach(file => {
fragment.appendChild(createResultItem(file));
});
elements.resultsList.appendChild(fragment);
searchState.displayedCount += toAdd.length;
}
// 检查是否需要显示"继续显示"按钮
updateLoadMoreButton();
pendingResults = [];
}
updateStats();
updateSelectAllButton();
addResultThrottle = null;
}, 100);
}
}
// 批量添加结果 (新增)
function addResultsBatch(files) {
const newFiles = [];
files.forEach(fileInfo => {
if (!searchState.scannedPaths.has(fileInfo.path)) {
searchState.scannedPaths.add(fileInfo.path);
searchState.foundFiles.push(fileInfo);
newFiles.push(fileInfo);
}
});
// 如果是默认排序,直接追加(但要考虑显示限制)
if (searchState.currentSort === 'default' && newFiles.length > 0) {
const canAddMore = searchState.displayedCount < searchState.batchSize;
if (canAddMore) {
const toAdd = newFiles.slice(0, searchState.batchSize - searchState.displayedCount);
const fragment = document.createDocumentFragment();
toAdd.forEach(file => {
fragment.appendChild(createResultItem(file));
});
elements.resultsList.appendChild(fragment);
searchState.displayedCount += toAdd.length;
}
}
// 更新"继续显示"按钮
updateLoadMoreButton();
updateStats();
updateSelectAllButton();
}
function renderResults() {
elements.resultsList.innerHTML = '';
if (searchState.foundFiles.length === 0) {
elements.resultsList.innerHTML = `
<div class="empty-state">
<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
<p>${t('emptyState')}</p>
</div>`;
searchState.displayedCount = 0;
return;
}
// 排序逻辑
let files = [...searchState.foundFiles];
const sort = searchState.currentSort;
if (sort === 'nameAsc') {
files.sort((a, b) => a.name.localeCompare(b.name));
} else if (sort === 'nameDesc') {
files.sort((a, b) => b.name.localeCompare(a.name));
} else if (sort === 'dateDesc') {
files.sort((a, b) => new Date(b.mtime) - new Date(a.mtime));
} else if (sort === 'dateAsc') {
files.sort((a, b) => new Date(a.mtime) - new Date(b.mtime));
} else if (sort === 'sizeDesc') {
files.sort((a, b) => b.size - a.size);
} else if (sort === 'sizeAsc') {
files.sort((a, b) => a.size - b.size);
}
// 渲染,考虑到性能,使用 DocumentFragment
const fragment = document.createDocumentFragment();
// 首次只显示1000条
const limit = Math.min(files.length, searchState.batchSize);
for (let i = 0; i < limit; i++) {
fragment.appendChild(createResultItem(files[i]));
}
elements.resultsList.appendChild(fragment);
// 更新显示计数
searchState.displayedCount = limit;
// 更新"继续显示"按钮
updateLoadMoreButton();
updateSelectAllButton();
}
// 创建结果项
function createResultItem(fileInfo) {
const item = document.createElement('div');
item.className = 'result-item';
const isSelected = searchState.selectedFiles.has(fileInfo.path);
const icon = getFileIcon(fileInfo.ext);
// 获取当前搜索关键词用于高亮
const searchQuery = elements.searchQuery.value.trim().toLowerCase();
const highlightedName = highlightText(fileInfo.name, searchQuery);
const highlightedPath = highlightText(fileInfo.dir, searchQuery);
item.innerHTML = `
<div class="file-checkbox">
<input type="checkbox" ${isSelected ? 'checked' : ''} data-path="${escapeHtml(fileInfo.path)}">
</div>
<div class="file-icon">
${icon}
</div>
<div class="file-info">
<div class="file-name">${highlightedName}</div>
<div class="file-path">${highlightedPath}</div>
<div class="file-meta">
${t('type')}: ${fileInfo.ext || t('noExt')} |
${t('size')}: ${formatFileSize(fileInfo.size)} |
${t('modTime')}: ${formatDate(fileInfo.mtime)}
</div>
</div>
<div class="file-actions">
<button class="action-btn" title="${t('openFolderTip')}" data-action="openFolder" data-path="${escapeHtml(fileInfo.dir)}">
<svg viewBox="0 0 24 24">
<path d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"/>
</svg>
</button>
<button class="action-btn" title="${t('openFileTip')}" data-action="openFile" data-path="${escapeHtml(fileInfo.path)}">
<svg viewBox="0 0 24 24">
<path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/>
<polyline points="14 2 14 8 20 8"/>
</svg>
</button>
<button class="action-btn" title="${t('propsTip')}" data-action="showProperties" data-info='${escapeHtml(JSON.stringify(fileInfo))}'>
<svg viewBox="0 0 24 24">
<circle cx="12" cy="12" r="10"/>
<line x1="12" y1="16" x2="12" y2="12"/>
<line x1="12" y1="8" x2="12.01" y2="8"/>
</svg>
</button>
</div>
`;
// 复选框事件
const checkbox = item.querySelector('input[type="checkbox"]');
checkbox.addEventListener('change', (e) => {
const path = e.target.dataset.path;
if (e.target.checked) {
searchState.selectedFiles.add(path);
} else {
searchState.selectedFiles.delete(path);
}
updateSelectAllButton();
});
// 添加事件监听
item.querySelectorAll('.action-btn').forEach(btn => {
btn.addEventListener('click', handleAction);
});
return item;
}
// 高亮文本中的关键词
function highlightText(text, query) {
if (!query) {
return escapeHtml(text);
}
const escapedText = escapeHtml(text);
const lowerText = text.toLowerCase();
const lowerQuery = query.toLowerCase();
let result = '';
let lastIndex = 0;
let index = lowerText.indexOf(lowerQuery);
while (index !== -1) {
result += escapeHtml(text.substring(lastIndex, index));
result += `<span class="highlight">${escapeHtml(text.substring(index, index + query.length))}</span>`;
lastIndex = index + query.length;
index = lowerText.indexOf(lowerQuery, lastIndex);
}
result += escapeHtml(text.substring(lastIndex));
return result;
}
// 处理操作按钮
async function handleAction(e) {
const action = e.currentTarget.dataset.action;
const path = e.currentTarget.dataset.path;
const info = e.currentTarget.dataset.info;
switch (action) {
case 'openFolder':
await window.electronAPI.openFolder(path);
break;
case 'openFile':
await window.electronAPI.openFile(path);
break;
case 'showProperties':
showProperties(JSON.parse(info));
break;
}
}
// 显示文件属性
async function showProperties(fileInfo) {
const props = `
${t('appTitle')}: ${fileInfo.name}