-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
5624 lines (4827 loc) · 191 KB
/
Copy pathapp.js
File metadata and controls
5624 lines (4827 loc) · 191 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
// Global state
let uploadedData = [];
let uploadedFiles = []; // v3.0: Track multiple file sources
let currentStep = 1;
let columnMapping = {};
let screeningResults = null;
let fileFormat = 'unknown';
let formatSource = 'Unknown';
let currentTheme = 'subtle';
// v1.5: Smart batch import system (4 mechanisms)
const SMART_IMPORT_CONFIG = {
MAX_CHUNK_SIZE: 5000, // 单批次最大记录数
CHECKPOINT_INTERVAL: 1000, // Checkpoint间隔
PARSE_CHUNK_SIZE: 50000, // 流式解析块大小(bytes)
MAX_RETRY: 3 // 最大重试次数
};
let importQueue = {
tasks: [], // 待导入任务队列
currentTask: null, // 当前执行任务
checkpoints: [], // Checkpoint记录
status: 'idle', // idle|running|paused|failed
progress: { total: 0, processed: 0, failed: 0 }
};
// v1.4: Project-level exclusion reason template (customizable & persisted)
const DEFAULT_EXCLUSION_REASONS = [
'人群不符',
'干预不符',
'对照不符',
'缺乏结局',
'数据不完整',
'研究设计不合适'
];
let exclusionReasons = [...DEFAULT_EXCLUSION_REASONS];
// v1.4: Explicit state split
let filterRules = null; // last used rules
let currentProjectId = null; // local project id for persistence
// v1.1: Multi-user collaboration variables
let projectCollaboration = {
reviewers: {},
decisions: {},
status: 'active',
createdAt: null,
lastSync: null
};
// v1.1: Dual-review session state
let currentUserSession = null;
let projectData = null;
let isDualReviewMode = false;
let currentReviewer = 'A';
let reviewerNames = { A: '审查员A', B: '审查员B' };
let dualReviewResults = { A: {}, B: {}, final: {} };
let collaborationSyncInterval = null;
const COLLAB_PROJECTS_KEY = 'prisma_projects';
const USER_SESSION_KEY = 'prisma_user_session';
// Color themes
const colorThemes = {
colorful: {
name: '活力彩色',
colors: {
identified: '#FF6B6B',
screened: '#4ECDC4',
included: '#45B7D1',
excluded: '#FFA07A',
duplicates: '#FFD93D',
text: '#2C3E50',
border: '#34495E'
}
},
blackwhite: {
name: '黑白',
colors: {
identified: '#1A1A1A',
screened: '#4D4D4D',
included: '#808080',
excluded: '#B3B3B3',
duplicates: '#E6E6E6',
text: '#000000',
border: '#333333'
}
},
subtle: {
name: '柔和',
colors: {
identified: '#8B4F8B',
screened: '#5B7C99',
included: '#6B8E6F',
excluded: '#C89B6B',
duplicates: '#A89968',
text: '#3E3E3E',
border: '#6B6B6B'
}
}
};
// Sample data for demonstration
const sampleData = [
{
title: "中医针灸对慢性疼痛的疗效研究",
abstract: "本研究探讨了针灸治疗慢性疼痛的临床效果,采用随机对照试验方法,结果显示针灸组疼痛评分显著低于对照组。",
year: 2020,
journal: "中华中医药杂志",
authors: "张三;李四",
doi: "10.1234/tcm.2020.001",
keywords: "中医;针灸;慢性疼痛"
},
{
title: "Acupuncture for chronic pain: systematic review",
abstract: "This systematic review evaluates the efficacy of acupuncture in treating chronic pain conditions. Meta-analysis shows significant pain reduction.",
year: 2021,
journal: "Pain Medicine",
authors: "Smith J, Johnson A",
doi: "10.5678/pain.2021.042",
keywords: "acupuncture;chronic pain;systematic review"
},
{
title: "医保支付方式改革与价值医疗",
abstract: "探讨医保支付方式改革对医疗服务价值导向的影响,采用差分中的差分方法评估政策效果。",
year: 2022,
journal: "中国卫生经济",
authors: "王五;赵六",
doi: "10.9012/che.2022.018",
keywords: "医保;支付方式;价值医疗;DID"
},
{
title: "Animal study of acupuncture mechanisms",
abstract: "This study investigates the neurobiological mechanisms of acupuncture using animal models. Rats were subjected to acupuncture treatment.",
year: 2019,
journal: "Neuroscience Letters",
authors: "Chen L, Wang M",
doi: "10.3456/neuro.2019.089",
keywords: "animal study;acupuncture;mechanisms"
},
{
title: "Editorial: Future of Traditional Chinese Medicine",
abstract: "This editorial discusses the future directions and challenges facing traditional Chinese medicine research and practice.",
year: 2023,
journal: "Journal of TCM",
authors: "Li H",
doi: "10.7890/jtcm.2023.005",
keywords: "editorial;traditional chinese medicine"
},
{
title: "Causal inference in health economics using AIPW",
abstract: "We apply augmented inverse probability weighting (AIPW) to estimate causal effects of medical insurance on healthcare utilization.",
year: 2022,
journal: "Health Economics",
authors: "Brown R, Davis K",
doi: "10.2468/he.2022.134",
keywords: "causal inference;AIPW;medical insurance"
},
{
title: "In vitro study of herbal medicine efficacy",
abstract: "Cell culture experiments demonstrate the anti-inflammatory effects of traditional herbal compounds in vitro.",
year: 2021,
journal: "Phytomedicine",
authors: "Liu Y, Zhou X",
doi: "10.1357/phyto.2021.067",
keywords: "in vitro;herbal medicine;cell culture"
},
{
title: "Protocol: RCT of acupuncture for migraine",
abstract: "This paper presents the study protocol for a randomized controlled trial evaluating acupuncture for migraine prevention.",
year: 2023,
journal: "Trials",
authors: "Martinez P, Garcia S",
doi: "10.8642/trials.2023.091",
keywords: "protocol;acupuncture;migraine;RCT"
},
{
title: "Overlap weighting for observational studies in medical insurance",
abstract: "We propose using overlap weighting to improve balance and efficiency in estimating treatment effects from medical insurance data.",
year: 2023,
journal: "Statistics in Medicine",
authors: "Wilson T, Anderson M",
doi: "10.9753/sim.2023.156",
keywords: "overlap weighting;medical insurance;causal inference"
},
{
title: "Case report: Rare complication of acupuncture",
abstract: "We report a case of pneumothorax following acupuncture treatment, highlighting the importance of proper technique and safety precautions.",
year: 2020,
journal: "Case Reports in Medicine",
authors: "Taylor E",
doi: "10.4826/crm.2020.023",
keywords: "case report;acupuncture;complication"
}
];
// Default rules
const defaultRules = {
time_window: {
start_year: 2000,
end_year: 2030
},
include_any: [
// v3.0: 默认为空,不进行关键词过滤
// 用户可以根据需要自行添加关键词
],
exclude: [
{ keyword: "animal study", reason: "不属于人群研究(动物实验)" },
{ keyword: "editorial", reason: "非研究性文献(社论/评论)" },
{ keyword: "protocol", reason: "仅研究方案,无结果" },
{ keyword: "in vitro", reason: "体外实验,非目标范围" },
{ keyword: "case report", reason: "病例报道,证据等级不足" }
],
language: {
allow: ["english", "chinese"]
},
required_one_of: ["title", "abstract"]
};
// v1.3: 研究方法自动识别函数
function guessStudyDesign(record) {
const text = ((record.title || '') + ' ' + (record.abstract || '')).toLowerCase();
// 随机对照试验
if (/randomized|randomised|随机(.{0,3})对照|双盲|三盲|单盲|rct\b/.test(text)) {
return '随机对照试验(RCT)';
}
// 系统综述/Meta分析
if (/systematic review|meta-analysis|meta analysis|系统综述|荟萃分析|meta\s?分析/.test(text)) {
return '系统综述/Meta分析';
}
// 队列研究
if (/cohort\s+study|cohort|prospective|队列研究|前瞻性(.{0,3})研究|回顾性(.{0,3})队列/.test(text)) {
return '队列研究';
}
// 病例对照研究
if (/case[-\s]?control|病例对照/.test(text)) {
return '病例对照研究';
}
// 横断面研究
if (/cross[-\s]?sectional|横断面研究|横断面调查/.test(text)) {
return '横断面研究';
}
// 临床试验(非随机)
if (/clinical trial|临床试验/.test(text) && !/random/.test(text)) {
return '临床试验(非随机)';
}
// 诊断性试验
if (/diagnostic\s+accuracy|sensitivity\s+and\s+specificity|诊断(.{0,3})准确性|诊断试验/.test(text)) {
return '诊断性试验研究';
}
// 动物实验
if (/animal\s+model|animal\s+study|in\s+vivo|动物模型|动物实验/.test(text)) {
return '动物实验研究';
}
// 体外实验
if (/in\s+vitro|cell\s+culture|体外实验|细胞实验/.test(text)) {
return '体外实验研究';
}
return '未标注';
}
// v1.3: 批量自动识别研究方法
function autoIdentifyStudyDesigns() {
if (!screeningResults || !screeningResults.included) {
showToast('请先完成文献筛选', 'warning');
return;
}
let identifiedCount = 0;
screeningResults.included.forEach(record => {
const design = guessStudyDesign(record);
if (design !== '未标注') {
record.studyDesign = design;
identifiedCount++;
}
});
// 刷新人工审查界面
displayFulltextReviewUI();
showToast(`✅ 已自动识别 ${identifiedCount}/${screeningResults.included.length} 篇文献的研究方法(建议人工核对)`, 'success');
}
// Initialize
function init() {
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
if (!uploadArea || !fileInput) {
console.error('Upload elements not found');
return;
}
uploadArea.addEventListener('click', () => fileInput.click());
uploadArea.addEventListener('dragover', (e) => {
e.preventDefault();
uploadArea.classList.add('dragover');
});
uploadArea.addEventListener('dragleave', () => {
uploadArea.classList.remove('dragover');
});
uploadArea.addEventListener('drop', (e) => {
e.preventDefault();
uploadArea.classList.remove('dragover');
// v3.0: Support multiple files | v1.5: Smart batch import
const files = Array.from(e.dataTransfer.files);
if (files.length > 0) handleMultipleFilesV15(files);
});
// v3.0: Change fileInput to support multiple files | v1.5: Smart batch import
fileInput.multiple = true;
fileInput.addEventListener('change', (e) => {
const files = Array.from(e.target.files);
if (files.length > 0) handleMultipleFilesV15(files);
});
// Initialize sliders (with safety check)
const ftExcludeRatio = document.getElementById('ftExcludeRatio');
const ftExcludeValue = document.getElementById('ftExcludeValue');
if (ftExcludeRatio && ftExcludeValue) {
ftExcludeRatio.addEventListener('input', (e) => {
ftExcludeValue.textContent = Math.round(e.target.value * 100) + '%';
});
}
// Initialize exclude list
loadExcludeItems();
// v1.4: Render exclusion template UI (Step 4)
renderExclusionTemplateButtons();
renderExclusionTemplateEditor();
currentUserSession = loadUserSession();
if (currentUserSession) {
initializeCollaborativeSession();
} else {
// v1.4: Restore last opened project (per-project persistence)
const restored = loadCurrentProjectStateFromLocalStorage();
if (restored) {
// If we have data, ensure UI gets refreshed
if (uploadedData && uploadedData.length > 0) {
if (!columnMapping || Object.keys(columnMapping).length === 0) {
try { detectColumns(); } catch (_) {}
}
try { displayUploadInfo(); } catch (_) {}
}
if (filterRules) {
try { setFormRules(filterRules); } catch (_) {}
}
if (screeningResults) {
try { displayResults(screeningResults); } catch (_) {}
setStep(3);
} else if (uploadedData && uploadedData.length > 0) {
setStep(2);
try { syncFormToYAML(); } catch (_) {}
try { displayRulesPreview(); } catch (_) {}
} else {
setStep(1);
}
}
}
// v1.4: Ensure Step4 entry button reflects readiness
updateStep4EntryLock();
}
function loadUserSession() {
try {
const raw = sessionStorage.getItem(USER_SESSION_KEY);
if (!raw) return null;
const session = JSON.parse(raw);
if (!session || !session.projectId || !session.role || !session.username) return null;
return session;
} catch (error) {
console.warn('Failed to parse collaborative session:', error);
return null;
}
}
function initializeCollaborativeSession() {
isDualReviewMode = true;
currentProjectId = currentUserSession.projectId;
localStorage.setItem('prisma_current_project_id', currentProjectId);
setReviewMode('dual');
loadProjectData();
if (!projectData) return;
applyCollaborativeProjectState();
startCollaborationSync();
}
function applyCollaborativeProjectState() {
if (!projectData) return;
const waitingDiv = document.getElementById('project-waiting');
if (waitingDiv) waitingDiv.remove();
currentProjectId = projectData.id || currentUserSession?.projectId || currentProjectId;
localStorage.setItem('prisma_current_project_id', currentProjectId);
restoreProjectState({
uploadedData: projectData.uploadedData || [],
uploadedFiles: projectData.uploadedFiles || [],
screeningResults: projectData.screeningResults || null,
columnMapping: projectData.columnMapping || {},
fileFormat: projectData.fileFormat || 'unknown',
formatSource: projectData.formatSource || 'Unknown',
currentStep: projectData.currentStep || inferCollaborativeStep(),
filterRules: projectData.filterRules || null,
exclusionReasons: projectData.exclusionReasons || [...DEFAULT_EXCLUSION_REASONS]
});
if (uploadedData && uploadedData.length > 0) {
if (!columnMapping || Object.keys(columnMapping).length === 0) {
try { detectColumns(); } catch (_) {}
}
try { displayUploadInfo(); } catch (_) {}
}
if (filterRules) {
try { setFormRules(filterRules); } catch (_) {}
}
if (screeningResults) {
try { displayResults(screeningResults); } catch (_) {}
const targetStep = Math.max(3, projectData.currentStep || inferCollaborativeStep());
setStep(targetStep);
if (targetStep >= 4) {
try { displayFulltextReviewUI(); } catch (_) {}
updateCollaborationStatus();
checkAndCalculateKappa();
}
} else if (uploadedData && uploadedData.length > 0) {
setStep(Math.max(2, projectData.currentStep || 2));
try { syncFormToYAML(); } catch (_) {}
try { displayRulesPreview(); } catch (_) {}
} else {
setStep(1);
}
updateCollaborationStatus();
}
function inferCollaborativeStep() {
if (screeningResults) {
return screeningResults.counts?.included !== undefined ? 4 : 3;
}
if (uploadedData && uploadedData.length > 0) return 2;
return 1;
}
function startCollaborationSync() {
if (collaborationSyncInterval) return;
window.addEventListener('storage', handleCollaborationStorageEvent);
collaborationSyncInterval = setInterval(() => {
syncCollaborativeProjectFromStorage(true);
}, 1500);
}
function handleCollaborationStorageEvent(event) {
if (event.key === COLLAB_PROJECTS_KEY) {
syncCollaborativeProjectFromStorage(true);
}
}
function syncCollaborativeProjectFromStorage(silent = false) {
if (!currentUserSession) return;
const projects = JSON.parse(localStorage.getItem(COLLAB_PROJECTS_KEY) || '{}');
const latestProject = projects[currentUserSession.projectId];
if (!latestProject) return;
const latestSync = latestProject.lastSync || latestProject.createdAt || '';
const currentSync = projectData?.lastSync || projectData?.createdAt || '';
if (projectData && latestSync === currentSync) return;
projectData = latestProject;
applyCollaborativeProjectState();
if (!silent) {
showToast('已同步最新协作项目状态', 'info');
}
}
// v3.0: Handle multiple file uploads
function handleMultipleFiles(files) {
const validExts = ['.csv', '.tsv', '.ris', '.bib', '.bibtex', '.txt', '.enw', '.rdf'];
const validFiles = files.filter(file => {
const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
return validExts.includes(ext);
});
if (validFiles.length === 0) {
// v4.0: Enhanced error message
showDetailedError('invalid_format', {
fileName: files[0].name,
supportedFormats: validExts
});
return;
}
if (validFiles.length !== files.length) {
showToast(`仅${validFiles.length}个文件格式有效,其他文件已跳过`, 'warning');
}
showLoading(`正在处理${validFiles.length}个文件...`);
showProgress(`正在上传文件...`, 0);
let processedCount = 0;
let allRecords = [];
let uploadedFilesInfo = [];
const processFile = (index) => {
if (index >= validFiles.length) {
// All files processed
if (allRecords.length === 0) {
hideProgress();
hideLoading();
showDetailedError('empty_file', { fileCount: validFiles.length });
return;
}
uploadedData = allRecords;
uploadedFiles = uploadedFilesInfo;
startNewProjectSession();
hideProgress();
setTimeout(() => {
detectColumns();
displayUploadInfo();
persistCurrentProjectState();
hideLoading();
showToast(`✅ 成功上传${validFiles.length}个文件,共${allRecords.length}条记录`, 'success');
addSuccessAnimation();
}, 500);
return;
}
const file = validFiles[index];
const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
const progress = Math.round((index / validFiles.length) * 100);
updateProgress(progress);
const reader = new FileReader();
reader.onload = (e) => {
try {
const text = e.target.result;
const fileData = {
name: file.name,
format: ext,
recordCount: 0,
source: 'Unknown'
};
// Parse file and get records
const records = parseFileContent(text, ext);
if (!records || records.length === 0) {
console.warn(`文件 ${file.name} 解析结果为空`);
}
fileData.recordCount = records.length;
// Detect source from format
switch (ext) {
case '.ris':
fileData.source = 'PubMed/Scopus/Endnote';
break;
case '.enw':
fileData.source = 'CNKI';
break;
case '.rdf':
fileData.source = 'Zotero';
break;
case '.csv':
case '.tsv':
fileData.source = 'Excel/Generic';
break;
case '.bib':
case '.bibtex':
fileData.source = 'Google Scholar/arXiv';
break;
default:
fileData.source = 'Unknown';
}
uploadedFilesInfo.push(fileData);
// Mark records with source for PRISMA identification stage
records.forEach(record => {
record._source = fileData.source;
record._sourceFile = file.name;
});
allRecords = allRecords.concat(records);
processFile(index + 1);
} catch (error) {
hideProgress();
hideLoading();
showDetailedError('parsing_error', {
fileName: file.name,
message: error.message,
line: error.line || '未知',
content: error.content || '未知'
});
console.error(`解析文件 ${file.name} 时出错:`, error);
}
};
reader.onerror = () => {
hideProgress();
hideLoading();
showDetailedError('invalid_format', {
fileName: file.name,
message: '文件读取失败,可能是文件已损坏或编码不正确'
});
};
reader.readAsText(file);
};
processFile(0);
}
// v1.5: Smart auto-batch import system
/**
* Mechanism 1: Stream/Chunk Parsing - 流式解析大文件
* 避免一次性加载50MB+文件到内存
*/
async function parseFileInChunks(file) {
const CHUNK_SIZE = SMART_IMPORT_CONFIG.PARSE_CHUNK_SIZE;
const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
return new Promise((resolve, reject) => {
const reader = new FileReader();
let allText = '';
let offset = 0;
const readChunk = () => {
const blob = file.slice(offset, offset + CHUNK_SIZE);
reader.readAsText(blob);
};
reader.onload = (e) => {
allText += e.target.result;
offset += CHUNK_SIZE;
if (offset < file.size) {
// 继续读取下一块
setTimeout(readChunk, 10); // 让主线程透气
} else {
// 全部读取完成,开始解析
try {
const records = parseFileContent(allText, ext);
resolve(records);
} catch (error) {
reject(error);
}
}
};
reader.onerror = reject;
readChunk();
});
}
/**
* Mechanism 2: Checkpoint - 分段事务提交
* 每N条记录创建checkpoint,失败可从上次成功点继续
*/
async function batchInsertWithCheckpoint(records, onProgress) {
const CHUNK_SIZE = SMART_IMPORT_CONFIG.MAX_CHUNK_SIZE;
const CHECKPOINT_INTERVAL = SMART_IMPORT_CONFIG.CHECKPOINT_INTERVAL;
let processedCount = 0;
let lastCheckpointCount = 0;
const checkpoints = [];
for (let i = 0; i < records.length; i += CHUNK_SIZE) {
const chunk = records.slice(i, Math.min(i + CHUNK_SIZE, records.length));
try {
// 批量插入当前chunk
await new Promise((resolve, reject) => {
// 这里调用IndexedDB worker批量插入
// 暂时用模拟实现
setTimeout(() => {
processedCount += chunk.length;
// 创建checkpoint
if (processedCount - lastCheckpointCount >= CHECKPOINT_INTERVAL) {
checkpoints.push({
count: processedCount,
timestamp: Date.now(),
status: 'success'
});
lastCheckpointCount = processedCount;
}
if (onProgress) {
onProgress(processedCount, records.length);
}
resolve();
}, 100);
});
} catch (error) {
// 记录失败checkpoint
checkpoints.push({
count: processedCount,
timestamp: Date.now(),
status: 'failed',
error: error.message
});
throw error;
}
}
return { processedCount, checkpoints };
}
/**
* Mechanism 3: Import Queue & Backpressure - 导入队列和背压控制
* Worker解析速度 > IndexedDB写入速度时,暂停解析避免内存爆炸
*/
class ImportQueueManager {
constructor() {
this.queue = [];
this.isProcessing = false;
this.maxQueueSize = 10000; // 队列最大长度
this.processedCount = 0;
this.onProgress = null;
}
async enqueue(records) {
// Backpressure: 队列过长时等待
while (this.queue.length > this.maxQueueSize) {
await new Promise(resolve => setTimeout(resolve, 100));
}
this.queue.push(...records);
if (!this.isProcessing) {
this.processQueue();
}
}
async processQueue() {
this.isProcessing = true;
while (this.queue.length > 0) {
const BATCH_SIZE = 500;
const batch = this.queue.splice(0, BATCH_SIZE);
try {
// 插入到IndexedDB
await this.insertBatch(batch);
this.processedCount += batch.length;
if (this.onProgress) {
this.onProgress(this.processedCount);
}
} catch (error) {
console.error('Batch insert failed:', error);
// 失败的batch重新入队(可选)
this.queue.unshift(...batch);
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
this.isProcessing = false;
}
async insertBatch(records) {
// 模拟IndexedDB插入
return new Promise(resolve => {
setTimeout(() => {
uploadedData.push(...records);
resolve();
}, 50);
});
}
reset() {
this.queue = [];
this.processedCount = 0;
this.isProcessing = false;
}
}
const importQueueManager = new ImportQueueManager();
/**
* Mechanism 4: Failure Recovery - 失败可恢复
* 记录已成功导入的文件/记录数,刷新页面可继续
*/
function saveImportProgress(state) {
try {
localStorage.setItem('import_progress', JSON.stringify({
files: state.files,
processedCount: state.processedCount,
totalCount: state.totalCount,
checkpoints: state.checkpoints,
timestamp: Date.now()
}));
} catch (e) {
console.warn('Failed to save import progress:', e);
}
}
function loadImportProgress() {
try {
const saved = localStorage.getItem('import_progress');
if (!saved) return null;
const progress = JSON.parse(saved);
// 检查是否是最近1小时内的进度
if (Date.now() - progress.timestamp < 3600000) {
return progress;
}
} catch (e) {
console.warn('Failed to load import progress:', e);
}
return null;
}
function clearImportProgress() {
localStorage.removeItem('import_progress');
}
/**
* Enhanced handleMultipleFiles with smart batch system
* 集成4大机制的智能上传函数
*/
async function handleMultipleFilesV15(files) {
const validExts = ['.csv', '.tsv', '.ris', '.bib', '.bibtex', '.txt', '.enw', '.rdf'];
const validFiles = files.filter(file => {
const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
return validExts.includes(ext);
});
if (validFiles.length === 0) {
showDetailedError('invalid_format', {
fileName: files[0].name,
supportedFormats: validExts
});
return;
}
// 检查是否有未完成的导入进度
const savedProgress = loadImportProgress();
if (savedProgress) {
const resume = confirm(`检测到未完成的导入任务(已导入${savedProgress.processedCount}/${savedProgress.totalCount}条),是否继续?`);
if (!resume) {
clearImportProgress();
}
}
showLoading(`正在智能处理${validFiles.length}个文件...`);
showProgress(`文件解析中...`, 0);
let allRecords = [];
let uploadedFilesInfo = [];
let totalRecords = 0;
try {
// Step 1: 流式解析所有文件
for (let i = 0; i < validFiles.length; i++) {
const file = validFiles[i];
updateProgress(Math.round((i / validFiles.length) * 30)); // 前30%用于解析
const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
const records = await parseFileInChunks(file);
const fileData = {
name: file.name,
format: ext,
recordCount: records.length,
source: detectSource(ext)
};
uploadedFilesInfo.push(fileData);
// 标记来源
records.forEach(record => {
record._source = fileData.source;
record._sourceFile = file.name;
});
allRecords = allRecords.concat(records);
}
totalRecords = allRecords.length;
updateProgress(30);
// Step 2: 智能分批导入(自动分批 + Checkpoint + 队列控制)
if (totalRecords <= SMART_IMPORT_CONFIG.MAX_CHUNK_SIZE) {
// 小于5000条,直接导入
uploadedData = allRecords;
updateProgress(100);
} else {
// 大于5000条,启动智能分批系统
showProgress(`正在分批导入${totalRecords}条记录(自动分${Math.ceil(totalRecords / SMART_IMPORT_CONFIG.MAX_CHUNK_SIZE)}批)...`, 30);
importQueueManager.reset();
importQueueManager.onProgress = (processed) => {
const percent = 30 + Math.round((processed / totalRecords) * 70);
updateProgress(percent);
// 保存进度
saveImportProgress({
files: uploadedFilesInfo,
processedCount: processed,
totalCount: totalRecords,
checkpoints: [],
timestamp: Date.now()
});
};
// 分批入队(Backpressure自动控制速度)
const ENQUEUE_BATCH = 1000;
for (let i = 0; i < allRecords.length; i += ENQUEUE_BATCH) {
const batch = allRecords.slice(i, Math.min(i + ENQUEUE_BATCH, allRecords.length));
await importQueueManager.enqueue(batch);
}
// 等待队列处理完成
while (importQueueManager.isProcessing || importQueueManager.queue.length > 0) {
await new Promise(resolve => setTimeout(resolve, 200));
}
}
uploadedFiles = uploadedFilesInfo;
startNewProjectSession();
clearImportProgress();
hideProgress();
setTimeout(() => {
detectColumns();
displayUploadInfo();
persistCurrentProjectState();
hideLoading();
// 提示分批信息
const batchCount = Math.ceil(totalRecords / SMART_IMPORT_CONFIG.MAX_CHUNK_SIZE);
const message = totalRecords > SMART_IMPORT_CONFIG.MAX_CHUNK_SIZE
? `✅ 智能分${batchCount}批导入成功!共${validFiles.length}个文件,${totalRecords}条记录`
: `✅ 成功上传${validFiles.length}个文件,共${totalRecords}条记录`;
showToast(message, 'success');
addSuccessAnimation();
}, 500);
} catch (error) {
hideProgress();
hideLoading();
showDetailedError('parsing_error', {
fileName: 'Multiple files',
message: error.message
});
console.error('Smart import failed:', error);
}
}
function detectSource(ext) {
switch (ext) {
case '.ris': return 'PubMed/Scopus/Endnote';
case '.enw': return 'CNKI';
case '.rdf': return 'Zotero';
case '.csv':
case '.tsv': return 'Excel/Generic';
case '.bib':
case '.bibtex': return 'Google Scholar/arXiv';
default: return 'Unknown';
}
}
// File handling
function handleFile(file) {
const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
const validExts = ['.csv', '.tsv', '.ris', '.bib', '.bibtex', '.txt', '.enw', '.rdf'];
if (!validExts.includes(ext)) {
showToast('不支持的文件格式,请上传 CSV, TSV, RIS, BibTeX, TXT, ENW 或 RDF 文件', 'error');
return;
}