-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
772 lines (649 loc) · 28.5 KB
/
main.js
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
document.addEventListener('alpine:init', () => {
// 初始化 IndexedDB
let db;
const initDB = () => {
const request = indexedDB.open('LogGrepDB', 1);
request.onerror = (event) => {
console.error('IndexedDB error:', event.target.error);
};
request.onupgradeneeded = (event) => {
db = event.target.result;
if (!db.objectStoreNames.contains('contextLines')) {
const store = db.createObjectStore('contextLines', { keyPath: 'id', autoIncrement: true });
store.createIndex('lineNumber', 'lineNumber', { unique: false });
store.createIndex('fileName', 'fileName', { unique: false });
}
};
request.onsuccess = (event) => {
db = event.target.result;
};
};
initDB();
Alpine.data('appData', () => ({
// State
shouldStop: false,
inputMethod: 'file',
fileInput: null,
files: [],
textInput: '',
includeInput: '',
includeInputCase: false,
excludeInput: '',
excludeInputCase: false,
hideInput: '',
hideInputCase: false,
resultLineCount: -1,
isWrap: false,
outputLimit: 1000,
contextLimit: 0,
isProcessing: false,
selectedLineId: null,
urlInput: '',
isChromeExtension: false,
init() {
// 从 URL 参数中获取初始值
const params = new URLSearchParams(window.location.search);
const initialInputMethod = params.get('inputMethod');
const initialUrl = params.get('url');
const isChromeExtension = params.get('isChromeExtension');
if (initialInputMethod) {
this.inputMethod = initialInputMethod;
}
if (initialUrl) {
this.urlInput = initialUrl;
}
if (isChromeExtension) {
this.isChromeExtension = true;
}
},
// Setters
setInputMethod() {
this.inputMethod = this.$el.value;
},
setTextInput() {
this.textInput = this.$el.value;
},
setUrlInput() {
this.urlInput = this.$el.value;
},
setIncludeInput() {
this.includeInput = this.$el.value;
},
setIncludeInputCase() {
this.includeInputCase = this.$el.checked;
},
setExcludeInput() {
this.excludeInput = this.$el.value;
},
setExcludeInputCase() {
this.excludeInputCase = this.$el.checked;
},
setHideInput() {
this.hideInput = this.$el.value;
},
setHideInputCase() {
this.hideInputCase = this.$el.checked;
},
setOutputLimit() {
this.outputLimit = parseInt(this.$el.value);
},
setContextLimit() {
this.contextLimit = parseInt(this.$el.value);
},
// Computed properties
showProcessingButton() {
return this.isProcessing;
},
showResultActions() {
return this.resultLineCount > 0;
},
showResults() {
return this.resultLineCount > -1;
},
showSelectedFiles() {
return this.files.length > 1;
},
isSearchDisabled() {
return this.isProcessing ||
(this.inputMethod === 'file' && !this.fileInput) ||
(this.inputMethod === 'text' && !this.textInput) ||
(this.inputMethod === 'url' && !this.urlInput);
},
getWrapStyle() {
return this.isWrap ? 'white-space: pre-wrap' : 'white-space: pre';
},
getWrapButtonText() {
return this.isWrap ? 'Nowrap' : 'Wrap';
},
isFileInputDisabled() {
return this.inputMethod !== 'file';
},
isTextInputDisabled() {
return this.inputMethod !== 'text';
},
isUrlInputDisabled() {
return this.inputMethod !== 'url';
},
isFileInputEnabled() {
return this.inputMethod === 'file';
},
isUrlInputEnabled() {
return this.inputMethod === 'url';
},
isTextInputEnabled() {
return this.inputMethod === 'text';
},
getTextInputSectionCss() {
return this.inputMethod === 'text' ? 'width:20%' : 'width:80%';
},
isInputMethodChecked() {
return this.inputMethod === this.$el.value;
},
isOutputLimitSelected() {
return this.outputLimit === parseInt(this.$el.value);
},
isContextLimitSelected() {
return this.contextLimit === parseInt(this.$el.value);
},
// Methods
clearContextStore() {
const transaction = db.transaction(['contextLines'], 'readwrite');
const store = transaction.objectStore('contextLines');
store.clear();
},
async showContext(lineId) {
if (!db || this.contextLimit <= 0) return;
// 如果点击的是同一行,则隐藏上下文
if (this.selectedLineId === lineId) {
document.querySelectorAll('.context-line').forEach(el => el.remove());
document.querySelectorAll('.matched-line').forEach(el => el.classList.remove('selected'));
this.selectedLineId = null;
return;
}
// 移除之前的上下文行和选中状态
document.querySelectorAll('.context-line').forEach(el => el.remove());
document.querySelectorAll('.matched-line').forEach(el => el.classList.remove('selected'));
// 设置新的选中行
this.selectedLineId = lineId;
const clickedDiv = document.querySelector(`[data-line-id="${lineId}"]`);
if (clickedDiv) {
clickedDiv.classList.add('selected');
}
const transaction = db.transaction(['contextLines'], 'readonly');
const store = transaction.objectStore('contextLines');
const request = store.get(parseInt(lineId));
request.onsuccess = (event) => {
const data = event.target.result;
if (!data || !clickedDiv) return;
// 按相对位置排序上下文行
const contextLines = data.contextLines
.filter(line => line.relativePosition !== 0) // 排除匹配行本身
.filter(line => Math.abs(line.relativePosition) <= this.contextLimit) // 限制上下文范围
.sort((a, b) => a.relativePosition - b.relativePosition); // 按相对位置排序
// 分离前后上下文行
const beforeLines = contextLines.filter(line => line.relativePosition < 0);
const afterLines = contextLines.filter(line => line.relativePosition > 0);
// 创建一个文档片段来提高性能
const fragment = document.createDocumentFragment();
// 先添加前面的上下文行(按照从上到下的顺序)
beforeLines.forEach(({text}) => {
const contextDiv = document.createElement('div');
contextDiv.className = 'context-line';
contextDiv.textContent = text;
if (data.fileName) {
contextDiv.title = `From: ${data.fileName}`;
}
fragment.appendChild(contextDiv);
});
// 添加匹配的行的克隆
const matchedLine = document.createElement('div');
matchedLine.className = 'matched-line selected';
matchedLine.textContent = data.matchedLine;
matchedLine.dataset.lineId = lineId;
if (data.fileName) {
matchedLine.title = `From: ${data.fileName}`;
}
// 重要:确保绑定双击事件
matchedLine.ondblclick = () => this.showContext(lineId);
fragment.appendChild(matchedLine);
// 添加后面的上下文行
afterLines.forEach(({text}) => {
const contextDiv = document.createElement('div');
contextDiv.className = 'context-line';
contextDiv.textContent = text;
if (data.fileName) {
contextDiv.title = `From: ${data.fileName}`;
}
fragment.appendChild(contextDiv);
});
// 替换原始的匹配行
clickedDiv.parentNode.insertBefore(fragment, clickedDiv);
clickedDiv.remove();
};
},
stopProcessing() {
this.shouldStop = true;
this.isProcessing = false;
},
reset() {
this.inputMethod = this.isChromeExtension ? 'url' : 'file';
this.textInput = '';
this.urlInput = '';
this.fileInput = null;
this.clearResult();
document.getElementById('fileInput').value = '';
this.files = [];
this.shouldStop = false;
this.resultLineCount = -1;
},
toggleWrap() {
this.isWrap = !this.isWrap;
},
clearResult() {
document.getElementById('result').innerHTML = '';
this.resultLineCount = 0;
},
async renderResult() {
this.clearResult();
this.clearContextStore();
this.isProcessing = true;
this.shouldStop = false;
this.selectedLineId = null;
if (this.inputMethod === 'url') {
this.renderFromUrlInput();
} else if (this.inputMethod === 'file') {
this.renderFromFileInput(this.files);
} else {
this.renderFromTextInput();
}
},
async renderFromUrlInput() {
try {
// 分割多行 URL 并过滤空行
const urls = this.urlInput.split('\n')
.map(url => url.trim())
.filter(url => url);
// 并行下载所有文件
const downloadPromises = urls.map(async url => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const blob = await response.blob();
const fileName = url.split('?')[0].split('/').pop() || 'downloaded.log';
return new File([blob], fileName);
} catch (error) {
console.log(`Error fetching URL: ${url}`, error);
const resultDiv = document.getElementById('result');
resultDiv.innerHTML += `<div class="error">Error fetching URL ${url}: ${error.message}</div>`;
return null;
}
});
// 等待所有下载完成
const files = (await Promise.all(downloadPromises))
.filter(file => file !== null); // 过滤掉下载失败的文件
if (files.length > 0) {
this.renderFromFileInput(files);
} else {
throw new Error('No files were successfully downloaded');
}
} catch (error) {
console.log('Error processing URLs:', error);
const resultDiv = document.getElementById('result');
resultDiv.innerHTML += `<div class="error">Error processing URLs: ${error.message}</div>`;
this.isProcessing = false;
}
},
renderFromTextInput() {
const { includeRegexes, excludeRegexes, hideRegexes } = this.buildRegexes();
const lines = this.textInput.split("\n");
// 使用与文件处理相同的逻辑
if (this.contextLimit > 0) {
// 先找到所有匹配的行
const matchedIndexes = [];
lines.forEach((line, index) => {
if (this.resultLineCount >= this.outputLimit) return;
const include = includeRegexes.every(regex => regex.test(line));
const exclude = excludeRegexes.every(regex => !regex.test(line));
if (include && exclude) {
matchedIndexes.push(index);
}
});
// 处理每个匹配的行及其上下文
for (const index of matchedIndexes) {
if (this.resultLineCount >= this.outputLimit) break;
const line = lines[index];
let processedLine = line;
hideRegexes.forEach(regex => {
processedLine = processedLine.replace(regex, "");
});
// 存储上下文到 IndexedDB
const contextStart = Math.max(0, index - this.contextLimit);
const contextEnd = Math.min(lines.length - 1, index + this.contextLimit);
// 创建带有相对位置的上下文行数组
const contextLines = [];
for (let i = contextStart; i <= contextEnd; i++) {
contextLines.push({
text: lines[i],
relativePosition: i - index // 相对于匹配行的位置
});
}
const lineId = this.resultLineCount + 1;
const transaction = db.transaction(['contextLines'], 'readwrite');
const store = transaction.objectStore('contextLines');
store.add({
id: lineId,
fileName: null,
contextLines: contextLines,
matchedLine: line
});
// 写入匹配的行
const resultDiv = document.getElementById('result');
const lineDiv = document.createElement('div');
lineDiv.textContent = processedLine;
lineDiv.className = 'matched-line';
lineDiv.dataset.lineId = lineId;
lineDiv.ondblclick = () => this.showContext(lineId);
resultDiv.appendChild(lineDiv);
this.resultLineCount++;
}
} else {
// 如果不需要上下文,使用原来的逻辑
for (let line of lines) {
if (this.resultLineCount >= this.outputLimit) break;
this.processLine(line, includeRegexes, excludeRegexes, hideRegexes);
}
}
this.isProcessing = false;
},
buildRegexes() {
const includeKeywords = this.includeInput.trim().split(" ").filter(Boolean);
const excludeKeywords = this.excludeInput.trim().split(" ").filter(Boolean);
const hideTexts = this.hideInput.trim().split(" ").filter(Boolean);
return {
includeRegexes: includeKeywords.map(key => new RegExp(key, this.includeInputCase ? 'i' : '')),
excludeRegexes: excludeKeywords.map(key => new RegExp(key, this.excludeInputCase ? 'i' : '')),
hideRegexes: hideTexts.map(key => new RegExp(key, this.hideInputCase ? 'i' : ''))
};
},
processLine(line, includeRegexes, excludeRegexes, hideRegexes, fileName) {
const include = includeRegexes.every(regex => regex.test(line));
const exclude = excludeRegexes.every(regex => !regex.test(line));
if (include && exclude) {
hideRegexes.forEach(regex => {
line = line.replace(regex, "");
});
this.writeLine(line, fileName);
}
},
onFileChanged(event) {
const files = Array.from(event.target.files);
if (files.length > 0) {
this.files = files.sort((a, b) => a.name.localeCompare(b.name));
this.fileInput = event.target;
this.inputMethod = 'file';
}
},
renderFromFileInput(files) {
if (!files.length) return;
const processNextFile = (index) => {
if (index >= files.length || this.resultLineCount >= this.outputLimit) {
this.isProcessing = false;
return;
}
const file = files[index];
const fileName = file.name.toLowerCase();
const onComplete = () => {
processNextFile(index + 1);
};
if (fileName.endsWith('.gz')) {
this.processGzFile(file, onComplete);
} else if (fileName.endsWith('.zip')) {
this.processZipFile(file, onComplete);
} else {
this.processTextFile(file, onComplete);
}
};
processNextFile(0);
},
processGzFile(file, onComplete) {
const chunkSize = 1024 * 1024;
let offset = 0;
const reader = new FileReader();
const gunzip = new pako.Inflate({to: 'string'});
gunzip.onData = chunk => {
this.processChunk(chunk, file.name);
if (this.resultLineCount >= this.outputLimit) {
reader.abort();
this.isProcessing = false;
onComplete();
}
};
reader.onload = e => {
gunzip.push(new Uint8Array(e.target.result), false);
offset += chunkSize;
if (offset < file.size && this.resultLineCount < this.outputLimit) {
readNextChunk();
} else {
gunzip.push(new Uint8Array(), true);
onComplete();
}
};
const readNextChunk = () => {
reader.readAsArrayBuffer(file.slice(offset, offset + chunkSize));
};
readNextChunk();
},
processZipFile(file, onComplete) {
const reader = new FileReader();
reader.onload = async (e) => {
try {
if (this.shouldStop) {
this.isProcessing = false;
onComplete();
return;
}
const zip = await JSZip.loadAsync(e.target.result);
const entries = Object.values(zip.files).filter(entry => !entry.dir);
entries.sort((a, b) => a.name.localeCompare(b.name));
// 使用 Promise.all 并行处理所有文件
await Promise.all(entries.map(async (entry) => {
if (this.shouldStop || this.resultLineCount >= this.outputLimit) {
return;
}
try {
const blob = await entry.async('blob');
const zipFile = new File([blob], entry.name);
const fullName = `${file.name}/${entry.name}`;
await new Promise((resolve) => {
this.processTextFile(zipFile, () => {
resolve();
}, fullName);
});
} catch (error) {
console.error(`Error processing entry ${entry.name}:`, error);
}
}));
onComplete();
} catch (error) {
console.error('Error processing ZIP file:', error);
onComplete();
} finally {
// 在 finally 块中设置 isProcessing,确保总是被执行
this.isProcessing = false;
}
};
reader.onerror = () => {
console.error('Error reading ZIP file');
this.isProcessing = false;
onComplete();
};
reader.readAsArrayBuffer(file);
},
processTextFile(file, onComplete, fullName = null) {
const chunkSize = 1024 * 1024;
let offset = 0;
const reader = new FileReader();
reader.onload = e => {
if (this.shouldStop || this.resultLineCount >= this.outputLimit) {
this.isProcessing = false;
onComplete();
return;
}
this.processChunk(e.target.result, fullName || file.name);
offset += chunkSize;
if (offset < file.size) {
readNextChunk();
} else {
onComplete();
}
};
const readNextChunk = () => {
reader.readAsText(file.slice(offset, offset + chunkSize));
};
readNextChunk();
},
processChunk(chunk, fileName) {
const { includeRegexes, excludeRegexes, hideRegexes } = this.buildRegexes();
const lines = chunk.split("\n");
// 如果需要上下文,存储所有行
if (this.contextLimit > 0) {
// 先找到所有匹配的行
const matchedIndexes = [];
lines.forEach((line, index) => {
if (this.shouldStop || this.resultLineCount >= this.outputLimit) return;
const include = includeRegexes.every(regex => regex.test(line));
const exclude = excludeRegexes.every(regex => !regex.test(line));
if (include && exclude) {
matchedIndexes.push(index);
}
});
// 处理每个匹配的行及其上下文
for (const index of matchedIndexes) {
if (this.shouldStop || this.resultLineCount >= this.outputLimit) break;
const line = lines[index];
let processedLine = line;
hideRegexes.forEach(regex => {
processedLine = processedLine.replace(regex, "");
});
// 存储上下文到 IndexedDB
const contextStart = Math.max(0, index - this.contextLimit);
const contextEnd = Math.min(lines.length - 1, index + this.contextLimit);
// 创建带有相对位置的上下文行数组
const contextLines = [];
for (let i = contextStart; i <= contextEnd; i++) {
contextLines.push({
text: lines[i],
relativePosition: i - index // 相对于匹配行的位置
});
}
const lineId = this.resultLineCount + 1;
const transaction = db.transaction(['contextLines'], 'readwrite');
const store = transaction.objectStore('contextLines');
store.add({
id: lineId,
fileName: fileName,
contextLines: contextLines,
matchedLine: line
});
// 写入匹配的行
const resultDiv = document.getElementById('result');
const lineDiv = document.createElement('div');
lineDiv.textContent = processedLine;
lineDiv.className = 'matched-line';
if (fileName) {
lineDiv.title = `From: ${fileName}`;
}
lineDiv.dataset.lineId = lineId;
lineDiv.ondblclick = () => this.showContext(lineId);
resultDiv.appendChild(lineDiv);
this.resultLineCount++;
}
} else {
// 如果不需要上下文,直接处理每一行
lines.forEach(line => {
if (this.shouldStop || this.resultLineCount >= this.outputLimit) return;
this.processLine(line, includeRegexes, excludeRegexes, hideRegexes, fileName);
});
}
},
writeLine(line, fileName) {
const resultDiv = document.getElementById('result');
const lineDiv = document.createElement('div');
lineDiv.textContent = line;
lineDiv.className = 'matched-line';
if (fileName) {
lineDiv.title = `From: ${fileName}`;
}
// 只有在需要上下文时才添加双击事件
if (this.contextLimit > 0) {
const lineId = this.resultLineCount + 1;
lineDiv.dataset.lineId = lineId;
lineDiv.ondblclick = () => this.showContext(lineId);
}
resultDiv.appendChild(lineDiv);
this.resultLineCount++;
},
sortResult() {
const direction = this.$el.value;
const resultDiv = document.getElementById('result');
// 移除所有上下文行
document.querySelectorAll('.context-line').forEach(el => el.remove());
// 保存文本内容和文件名
const lines = Array.from(resultDiv.children).map(div => ({
text: div.textContent,
fileName: div.title.replace('From: ', ''),
lineId: div.dataset.lineId,
isSelected: div.classList.contains('selected')
}));
// 按文本内容排序
lines.sort((a, b) => direction === 'asc' ?
a.text.localeCompare(b.text) :
b.text.localeCompare(a.text)
);
// 清除当前结果
resultDiv.innerHTML = '';
// 重新渲染排序后的结果
lines.forEach(line => {
const lineDiv = document.createElement('div');
lineDiv.textContent = line.text;
lineDiv.className = 'matched-line';
if (line.isSelected) {
lineDiv.classList.add('selected');
}
if (line.fileName) {
lineDiv.title = `From: ${line.fileName}`;
}
if (line.lineId) {
lineDiv.dataset.lineId = line.lineId;
lineDiv.ondblclick = () => this.showContext(line.lineId);
}
resultDiv.appendChild(lineDiv);
});
},
saveResult() {
const resultDiv = document.getElementById('result');
const lines = Array.from(resultDiv.children).map(div => {
const fileName = div.title ? ` [${div.title.replace('From: ', '')}]` : '';
return `${div.textContent}${fileName}`;
});
const content = lines.join('\n');
const blob = new Blob([content], { type: 'text/plain' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'grep_result.txt';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
},
copyToInput() {
const resultDiv = document.getElementById('result');
const lines = Array.from(resultDiv.children).map(div => div.textContent);
this.textInput = lines.join('\n');
this.inputMethod = 'text';
}
}))
})