Repository navigation
Expand file tree
/
Copy pathbootstrap.js
More file actions
1087 lines (966 loc) · 31 KB
/
Copy pathbootstrap.js
File metadata and controls
1087 lines (966 loc) · 31 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
var CollectionDedupCESI;
const ADDON_NAME = "分类去重(CESI)";
const DEFAULT_DUP_COLLECTION_NAME = "重复文献(当前分类)";
const PREF_INCLUDE_SUBCOLLECTIONS_BY_DEFAULT = "extensions.cesiCollectionDedup.includeSubcollectionsByDefault";
const PREF_DUP_COLLECTION_NAME = "extensions.cesiCollectionDedup.duplicatesCollectionName";
const TOOLS_MENUITEM_ID = "cesi-collection-dedup-tools-menuitem";
const CONTEXT_MENUITEM_ID = "cesi-collection-dedup-context-menuitem";
const CONTEXT_SEPARATOR_ID = "cesi-collection-dedup-context-separator";
const RESULTS_WINDOW_WIDTH = 1080;
const RESULTS_WINDOW_HEIGHT = 760;
const YIELD_EVERY = 150;
function log(message) {
Zotero.debug(ADDON_NAME + ": " + message);
}
function install() {
log("Installed");
}
async function startup({ id, version, rootURI }) {
log("Starting " + version);
CollectionDedupCESI = new CollectionDedupPlugin({ id, version, rootURI });
await CollectionDedupCESI.registerPreferencePane();
CollectionDedupCESI.addToAllWindows();
}
function onMainWindowLoad({ window }) {
if (CollectionDedupCESI) {
CollectionDedupCESI.addToWindow(window);
}
}
function onMainWindowUnload({ window }) {
if (CollectionDedupCESI) {
CollectionDedupCESI.removeFromWindow(window);
}
}
function shutdown() {
log("Shutting down");
if (CollectionDedupCESI) {
CollectionDedupCESI.removeFromAllWindows();
CollectionDedupCESI.unregisterPreferencePane();
CollectionDedupCESI = undefined;
}
}
function uninstall() {
log("Uninstalled");
}
function CollectionDedupPlugin(context) {
this.id = context.id;
this.version = context.version;
this.rootURI = context.rootURI;
this._windowHooks = new WeakMap();
this._preferencePaneID = null;
}
CollectionDedupPlugin.prototype.registerPreferencePane = async function () {
if (!Zotero.PreferencePanes || !Zotero.PreferencePanes.register) {
log("Preference pane API is unavailable");
return;
}
this._preferencePaneID = await Zotero.PreferencePanes.register({
pluginID: this.id,
src: this.rootURI + "preferences.xhtml",
stylesheets: [this.rootURI + "preferences.css"],
label: ADDON_NAME,
helpURL: "https://github.com/GuotuanWang/cesi"
});
};
CollectionDedupPlugin.prototype.unregisterPreferencePane = function () {
if (!this._preferencePaneID || !Zotero.PreferencePanes || !Zotero.PreferencePanes.unregister) {
return;
}
try {
Zotero.PreferencePanes.unregister(this._preferencePaneID);
}
catch (error) {
log("Failed to unregister preference pane: " + error);
}
this._preferencePaneID = null;
};
CollectionDedupPlugin.prototype.addToAllWindows = function () {
for (let window of Zotero.getMainWindows()) {
this.addToWindow(window);
}
};
CollectionDedupPlugin.prototype.removeFromAllWindows = function () {
for (let window of Zotero.getMainWindows()) {
this.removeFromWindow(window);
}
};
CollectionDedupPlugin.prototype.addToWindow = function (window) {
if (!window || !window.document) {
return;
}
if (this._windowHooks.has(window)) {
return;
}
let document = window.document;
let onCommand = async () => {
await this.runFromWindow(window);
};
let toolsMenuItem = null;
let toolsPopup = document.getElementById("menu_ToolsPopup");
if (toolsPopup && !document.getElementById(TOOLS_MENUITEM_ID)) {
toolsMenuItem = this._createMenuItem(document);
toolsMenuItem.id = TOOLS_MENUITEM_ID;
toolsMenuItem.setAttribute("label", "在所选分类中查找重复文献...");
toolsMenuItem.className = "menu-type-library";
toolsMenuItem.addEventListener("command", onCommand);
toolsPopup.appendChild(toolsMenuItem);
}
let contextMenuItem = null;
let contextSeparator = null;
let contextPopup = document.getElementById("zotero-collectionmenu");
let onContextPopupShowing = null;
if (contextPopup && !document.getElementById(CONTEXT_MENUITEM_ID)) {
contextSeparator = this._createSeparator(document);
contextSeparator.id = CONTEXT_SEPARATOR_ID;
contextSeparator.hidden = true;
contextMenuItem = this._createMenuItem(document);
contextMenuItem.id = CONTEXT_MENUITEM_ID;
contextMenuItem.setAttribute("label", "在所选分类中查找重复文献...");
contextMenuItem.hidden = true;
contextMenuItem.addEventListener("command", onCommand);
onContextPopupShowing = () => {
let hasCollection = !!this._getSelectedCollection(window);
contextMenuItem.hidden = !hasCollection;
contextSeparator.hidden = !hasCollection;
contextMenuItem.disabled = !hasCollection;
};
contextPopup.addEventListener("popupshowing", onContextPopupShowing);
// Append to the end to avoid shifting Zotero's internal fixed menu indexes.
contextPopup.appendChild(contextSeparator);
contextPopup.appendChild(contextMenuItem);
}
this._windowHooks.set(window, {
onCommand,
onContextPopupShowing,
toolsMenuItem,
contextMenuItem,
contextSeparator
});
};
CollectionDedupPlugin.prototype.removeFromWindow = function (window) {
if (!window || !window.document) {
return;
}
let hooks = this._windowHooks.get(window);
let document = window.document;
let toolsMenuItem = document.getElementById(TOOLS_MENUITEM_ID);
if (toolsMenuItem) {
if (hooks && hooks.onCommand) {
toolsMenuItem.removeEventListener("command", hooks.onCommand);
}
toolsMenuItem.remove();
}
let contextMenuItem = document.getElementById(CONTEXT_MENUITEM_ID);
if (contextMenuItem) {
if (hooks && hooks.onCommand) {
contextMenuItem.removeEventListener("command", hooks.onCommand);
}
contextMenuItem.remove();
}
let contextSeparator = document.getElementById(CONTEXT_SEPARATOR_ID);
if (contextSeparator) {
contextSeparator.remove();
}
let contextPopup = document.getElementById("zotero-collectionmenu");
if (contextPopup && hooks && hooks.onContextPopupShowing) {
contextPopup.removeEventListener("popupshowing", hooks.onContextPopupShowing);
}
if (hooks) {
this._windowHooks.delete(window);
}
};
CollectionDedupPlugin.prototype.runFromWindow = async function (window) {
try {
let selectedCollection = this._getSelectedCollection(window);
if (!selectedCollection) {
Services.prompt.alert(
window,
ADDON_NAME,
"请先在左侧面板中仅选择一个分类。"
);
return;
}
let includeSubcollections = this._promptIncludeSubcollections(window, selectedCollection);
if (includeSubcollections === null) {
return;
}
log("Scanning collection " + selectedCollection.id + " (includeSubcollections=" + includeSubcollections + ")");
let scanResult = await this._scanDuplicates(selectedCollection, includeSubcollections);
this._openResultsWindow(window, scanResult);
}
catch (error) {
this._showErrorWindow(window, "扫描重复文献失败", error);
}
};
CollectionDedupPlugin.prototype._createMenuItem = function (document) {
if (document.createXULElement) {
return document.createXULElement("menuitem");
}
return document.createElement("menuitem");
};
CollectionDedupPlugin.prototype._createSeparator = function (document) {
if (document.createXULElement) {
return document.createXULElement("menuseparator");
}
return document.createElement("menuseparator");
};
CollectionDedupPlugin.prototype._getSelectedCollection = function (window) {
if (!window || !window.ZoteroPane) {
return null;
}
// Zotero 10 supports multiple collection-tree selections and removed the
// singular getter. This action intentionally remains scoped to exactly one
// collection, while the fallback preserves Zotero 7–9 compatibility.
if (typeof window.ZoteroPane.getSelectedCollections === "function") {
let collections = window.ZoteroPane.getSelectedCollections();
return collections.length === 1 ? collections[0] : null;
}
if (typeof window.ZoteroPane.getSelectedCollection === "function") {
return window.ZoteroPane.getSelectedCollection();
}
return null;
};
CollectionDedupPlugin.prototype._promptIncludeSubcollections = function (window, collection) {
let includeState = { value: this._getIncludeSubcollectionsDefault() };
let path = this._getCollectionPath(collection);
let proceed = Services.prompt.confirmCheck(
window,
ADDON_NAME,
"是否在该分类范围内扫描重复文献?\n\n分类:" + path + "\n\n仅扫描常规文献条目(已排除笔记/附件/注释)。",
"包含子分类",
includeState
);
if (!proceed) {
return null;
}
return includeState.value;
};
CollectionDedupPlugin.prototype._getIncludeSubcollectionsDefault = function () {
return this._getBoolPref(PREF_INCLUDE_SUBCOLLECTIONS_BY_DEFAULT, false);
};
CollectionDedupPlugin.prototype._getDuplicatesCollectionName = function () {
let value = this._getStringPref(PREF_DUP_COLLECTION_NAME, DEFAULT_DUP_COLLECTION_NAME);
value = this._singleLine(value);
return value || DEFAULT_DUP_COLLECTION_NAME;
};
CollectionDedupPlugin.prototype._getBoolPref = function (prefName, fallback) {
try {
return Services.prefs.getBoolPref(prefName, fallback);
}
catch (error) {
return fallback;
}
};
CollectionDedupPlugin.prototype._getStringPref = function (prefName, fallback) {
try {
return Services.prefs.getStringPref(prefName, fallback);
}
catch (error) {
return fallback;
}
};
CollectionDedupPlugin.prototype._scanDuplicates = async function (selectedCollection, includeSubcollections) {
let scopeCollections = this._collectScopeCollections(selectedCollection, includeSubcollections);
let scopeCollectionIDs = new Set(scopeCollections.map(collection => collection.id));
let collectionPathMap = new Map();
for (let collection of scopeCollections) {
collectionPathMap.set(collection.id, this._getCollectionPath(collection));
}
let records = [];
let seenItemIDs = new Set();
let scannedCounter = 0;
for (let collection of scopeCollections) {
let childItems = collection.getChildItems(false, false);
for (let item of childItems) {
if (!item || !item.isRegularItem || !item.isRegularItem()) {
continue;
}
if (seenItemIDs.has(item.id)) {
continue;
}
seenItemIDs.add(item.id);
records.push(this._buildRecord(item, scopeCollectionIDs, collectionPathMap));
scannedCounter++;
if (scannedCounter % YIELD_EVERY === 0) {
await this._yieldToUI();
}
}
}
let duplicateGroups = await this._findDuplicateGroups(records);
duplicateGroups.sort((a, b) => {
if (b.items.length !== a.items.length) {
return b.items.length - a.items.length;
}
return a.keep.item.id - b.keep.item.id;
});
return {
selectedCollection,
selectedCollectionPath: this._getCollectionPath(selectedCollection),
includeSubcollections,
scopeCollectionIDs,
scannedCount: records.length,
duplicateGroupCount: duplicateGroups.length,
duplicateGroups,
createdAt: new Date().toISOString()
};
};
CollectionDedupPlugin.prototype._collectScopeCollections = function (rootCollection, includeSubcollections) {
if (!includeSubcollections) {
return [rootCollection];
}
let collections = [];
let queue = [rootCollection];
let seen = new Set();
while (queue.length) {
let collection = queue.shift();
if (!collection || seen.has(collection.id)) {
continue;
}
seen.add(collection.id);
collections.push(collection);
let children = collection.getChildCollections(false, false);
for (let child of children) {
queue.push(child);
}
}
return collections;
};
CollectionDedupPlugin.prototype._buildRecord = function (item, scopeCollectionIDs, collectionPathMap) {
let title = this._stringField(item, "title");
let dateValue = this._stringField(item, "date");
let doi = this._normalizeDOI(this._stringField(item, "DOI"));
let isbns = this._normalizeISBNList(this._stringField(item, "ISBN"));
let creators = item.getCreators ? item.getCreators() : [];
let creatorNorm = this._normalizeFirstCreator(creators);
let year = this._extractYear(dateValue);
let dateAdded = this._normalizeDateAdded(item);
let dateCompleteness = this._dateCompletenessScore(dateValue);
let titleNorm = this._normalizeTitle(title);
let scopePaths = this._getScopePathsForItem(item, scopeCollectionIDs, collectionPathMap);
return {
item,
title,
titleNorm,
year,
doi,
isbns,
creatorNorm,
dateValue,
dateCompleteness,
dateAdded,
titleLength: title.length,
scopePaths
};
};
CollectionDedupPlugin.prototype._findDuplicateGroups = async function (records) {
if (records.length < 2) {
return [];
}
let uf = new UnionFind(records.length);
let processed = 0;
let doiIndex = new Map();
for (let i = 0; i < records.length; i++) {
let record = records[i];
if (record.doi) {
if (doiIndex.has(record.doi)) {
uf.union(i, doiIndex.get(record.doi));
}
else {
doiIndex.set(record.doi, i);
}
}
processed++;
if (processed % YIELD_EVERY === 0) {
await this._yieldToUI();
}
}
let isbnIndex = new Map();
for (let i = 0; i < records.length; i++) {
let record = records[i];
for (let isbn of record.isbns) {
if (isbnIndex.has(isbn)) {
uf.union(i, isbnIndex.get(isbn));
}
else {
isbnIndex.set(isbn, i);
}
}
processed++;
if (processed % YIELD_EVERY === 0) {
await this._yieldToUI();
}
}
let titleBuckets = new Map();
for (let i = 0; i < records.length; i++) {
let key = records[i].titleNorm;
if (!key) {
continue;
}
if (!titleBuckets.has(key)) {
titleBuckets.set(key, []);
}
titleBuckets.get(key).push(i);
}
let pairChecks = 0;
for (let bucket of titleBuckets.values()) {
if (bucket.length < 2) {
continue;
}
for (let i = 0; i < bucket.length - 1; i++) {
let leftIndex = bucket[i];
let left = records[leftIndex];
for (let j = i + 1; j < bucket.length; j++) {
let rightIndex = bucket[j];
let right = records[rightIndex];
if (this._matchesByTitleYearCreator(left, right)) {
uf.union(leftIndex, rightIndex);
}
pairChecks++;
if (pairChecks % 2000 === 0) {
await this._yieldToUI();
}
}
}
}
let groupsByRoot = new Map();
for (let i = 0; i < records.length; i++) {
let root = uf.find(i);
if (!groupsByRoot.has(root)) {
groupsByRoot.set(root, []);
}
groupsByRoot.get(root).push(records[i]);
if (i > 0 && i % YIELD_EVERY === 0) {
await this._yieldToUI();
}
}
let duplicateGroups = [];
for (let recordsInGroup of groupsByRoot.values()) {
if (recordsInGroup.length < 2) {
continue;
}
recordsInGroup.sort((a, b) => a.item.id - b.item.id);
let keep = this._pickBestRecord(recordsInGroup);
let duplicates = recordsInGroup.filter(record => record.item.id !== keep.item.id);
duplicateGroups.push({
keep,
items: recordsInGroup,
duplicates
});
}
return duplicateGroups;
};
CollectionDedupPlugin.prototype._matchesByTitleYearCreator = function (left, right) {
if (!left.titleNorm || left.titleNorm !== right.titleNorm) {
return false;
}
let yearMatches = false;
if (left.year && right.year) {
yearMatches = Math.abs(left.year - right.year) <= 1;
}
else {
yearMatches = true;
}
if (!yearMatches) {
return false;
}
let creatorMatches = false;
if (left.creatorNorm && right.creatorNorm) {
creatorMatches = left.creatorNorm === right.creatorNorm;
}
else {
creatorMatches = true;
}
return creatorMatches;
};
CollectionDedupPlugin.prototype._pickBestRecord = function (records) {
let sorted = records.slice().sort((a, b) => this._compareRecordsForKeep(a, b));
return sorted[0];
};
CollectionDedupPlugin.prototype._compareRecordsForKeep = function (left, right) {
let leftHasDOI = !!left.doi;
let rightHasDOI = !!right.doi;
if (leftHasDOI !== rightHasDOI) {
return leftHasDOI ? -1 : 1;
}
let leftHasISBN = left.isbns.length > 0;
let rightHasISBN = right.isbns.length > 0;
if (leftHasISBN !== rightHasISBN) {
return leftHasISBN ? -1 : 1;
}
if (left.titleLength !== right.titleLength) {
return right.titleLength - left.titleLength;
}
if (left.dateCompleteness !== right.dateCompleteness) {
return right.dateCompleteness - left.dateCompleteness;
}
if (left.dateAdded !== right.dateAdded) {
if (!left.dateAdded) {
return 1;
}
if (!right.dateAdded) {
return -1;
}
return left.dateAdded.localeCompare(right.dateAdded);
}
return left.item.id - right.item.id;
};
CollectionDedupPlugin.prototype._getScopePathsForItem = function (item, scopeCollectionIDs, collectionPathMap) {
let scopePaths = [];
let seen = new Set();
let collectionIDs = item.getCollections ? item.getCollections(false) : [];
for (let collectionID of collectionIDs) {
if (!scopeCollectionIDs.has(collectionID)) {
continue;
}
let path = collectionPathMap.get(collectionID);
if (path && !seen.has(path)) {
seen.add(path);
scopePaths.push(path);
}
}
scopePaths.sort();
return scopePaths;
};
CollectionDedupPlugin.prototype._normalizeTitle = function (title) {
if (!title) {
return "";
}
let normalized = String(title).toLowerCase();
try {
normalized = normalized.replace(/[^\p{L}\p{N}\s]+/gu, " ");
}
catch (e) {
normalized = normalized.replace(/[^a-z0-9\s]+/g, " ");
}
normalized = normalized.replace(/\s+/g, " ").trim();
return normalized;
};
CollectionDedupPlugin.prototype._normalizeNamePart = function (value) {
if (!value) {
return "";
}
let normalized = String(value).toLowerCase();
try {
normalized = normalized.replace(/[^\p{L}\p{N}\s]+/gu, " ");
}
catch (e) {
normalized = normalized.replace(/[^a-z0-9\s]+/g, " ");
}
return normalized.replace(/\s+/g, " ").trim();
};
CollectionDedupPlugin.prototype._normalizeFirstCreator = function (creators) {
if (!creators || creators.length === 0) {
return "";
}
let creator = creators[0] || {};
let lastName = this._normalizeNamePart(creator.lastName || creator.name || "");
let firstName = this._normalizeNamePart(creator.firstName || "");
let firstInitial = firstName ? firstName[0] : "";
if (!lastName) {
return "";
}
return firstInitial ? (lastName + "|" + firstInitial) : lastName;
};
CollectionDedupPlugin.prototype._extractYear = function (dateValue) {
if (!dateValue) {
return null;
}
let match = String(dateValue).match(/(?:^|\D)(\d{4})(?:\D|$)/);
if (!match) {
return null;
}
let year = parseInt(match[1], 10);
if (!Number.isFinite(year) || year < 1000 || year > 9999) {
return null;
}
return year;
};
CollectionDedupPlugin.prototype._normalizeDOI = function (doiValue) {
if (!doiValue) {
return "";
}
let doi = String(doiValue).trim().toLowerCase();
doi = doi.replace(/^https?:\/\/(dx\.)?doi\.org\//, "");
doi = doi.replace(/^doi:\s*/i, "");
return doi;
};
CollectionDedupPlugin.prototype._normalizeISBNList = function (isbnValue) {
if (!isbnValue) {
return [];
}
let values = new Set();
let rawParts = String(isbnValue).split(/[\s,;|]+/);
for (let part of rawParts) {
let normalized = part.replace(/[^0-9xX]/g, "").toUpperCase();
if (normalized.length === 10 || normalized.length === 13) {
values.add(normalized);
}
}
return Array.from(values).sort();
};
CollectionDedupPlugin.prototype._normalizeDateAdded = function (item) {
let value = "";
if (item && item.dateAdded) {
value = String(item.dateAdded);
}
if (!value && item && item.getField) {
value = String(item.getField("dateAdded") || "");
}
return value.trim();
};
CollectionDedupPlugin.prototype._dateCompletenessScore = function (dateValue) {
if (!dateValue) {
return 0;
}
let value = String(dateValue).trim();
if (!value) {
return 0;
}
let score = 0;
if (/\d{4}/.test(value)) {
score += 1;
}
if (/\d{4}[-\/]\d{1,2}/.test(value) || /(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i.test(value)) {
score += 1;
}
if (/\d{4}[-\/]\d{1,2}[-\/]\d{1,2}/.test(value)) {
score += 1;
}
return score;
};
CollectionDedupPlugin.prototype._stringField = function (item, fieldName) {
if (!item || !item.getField) {
return "";
}
let value = item.getField(fieldName);
return value ? String(value).trim() : "";
};
CollectionDedupPlugin.prototype._getCollectionPath = function (collection) {
if (!collection) {
return "";
}
let parts = [collection.name || "(未命名分类)"];
let currentParentID = collection.parentID;
while (currentParentID) {
let parent = Zotero.Collections.get(currentParentID);
if (!parent) {
break;
}
parts.unshift(parent.name || "(未命名分类)");
currentParentID = parent.parentID;
}
let library = Zotero.Libraries.get(collection.libraryID);
let path = parts.join(" / ");
if (library && library.name) {
return library.name + " / " + path;
}
return path;
};
CollectionDedupPlugin.prototype._yieldToUI = async function () {
await new Promise(resolve => {
Services.tm.dispatchToMainThread(resolve);
});
};
CollectionDedupPlugin.prototype._openResultsWindow = function (parentWindow, scanResult) {
let resultWindow = parentWindow.openDialog(
"about:blank",
"",
"chrome,resizable,centerscreen,width=" + RESULTS_WINDOW_WIDTH + ",height=" + RESULTS_WINDOW_HEIGHT
);
let render = () => {
this._renderResultsWindow(resultWindow, parentWindow, scanResult);
};
if (resultWindow.document && resultWindow.document.readyState === "complete") {
render();
}
else {
resultWindow.addEventListener("load", render, { once: true });
}
};
CollectionDedupPlugin.prototype._renderResultsWindow = function (resultWindow, parentWindow, scanResult) {
let document = resultWindow.document;
resultWindow.document.title = ADDON_NAME + " - 扫描结果";
let body = document.body || document.createElement("body");
if (!document.body) {
document.documentElement.appendChild(body);
}
body.innerHTML = "";
let style = document.createElement("style");
style.textContent = [
"body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; margin: 14px; color: #1f2937; background: #f8fafc; }",
"h1 { font-size: 18px; margin: 0 0 10px; }",
".summary { background: #ffffff; border: 1px solid #cbd5e1; border-radius: 8px; padding: 10px; margin-bottom: 10px; }",
".actions { display: flex; gap: 8px; margin-bottom: 10px; flex-wrap: wrap; }",
"button { border: 1px solid #94a3b8; border-radius: 6px; background: #fff; color: #0f172a; padding: 8px 10px; cursor: pointer; }",
"button.primary { background: #0f766e; border-color: #0f766e; color: #fff; }",
"button.warn { background: #b91c1c; border-color: #b91c1c; color: #fff; }",
"button:disabled { opacity: 0.6; cursor: default; }",
"textarea { width: 100%; min-height: 470px; border: 1px solid #cbd5e1; border-radius: 8px; padding: 10px; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 12px; line-height: 1.4; background: #ffffff; }",
".note { margin-bottom: 8px; color: #334155; }",
".status { margin-top: 10px; border: 1px solid #cbd5e1; background: #ffffff; border-radius: 8px; padding: 10px; white-space: pre-wrap; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 12px; }"
].join("\n");
document.head.appendChild(style);
let header = document.createElement("h1");
header.textContent = "重复文献扫描结果";
body.appendChild(header);
let summary = document.createElement("div");
summary.className = "summary";
summary.textContent = this._buildSummaryText(scanResult);
body.appendChild(summary);
let note = document.createElement("div");
note.className = "note";
note.textContent = "“移入重复分类”操作仅将重复项添加到子分类,不会从原有分类中移除。";
body.appendChild(note);
let actions = document.createElement("div");
actions.className = "actions";
body.appendChild(actions);
let moveBtn = document.createElement("button");
moveBtn.className = "primary";
moveBtn.textContent = "创建“" + this._getDuplicatesCollectionName() + "”并移入重复副本";
actions.appendChild(moveBtn);
let trashBtn = document.createElement("button");
trashBtn.className = "warn";
trashBtn.textContent = "将重复项移入回收站(保留最佳项)";
actions.appendChild(trashBtn);
let closeBtn = document.createElement("button");
closeBtn.textContent = "关闭";
closeBtn.addEventListener("click", () => resultWindow.close());
actions.appendChild(closeBtn);
let details = document.createElement("textarea");
details.readOnly = true;
details.value = this._buildDetailsText(scanResult);
body.appendChild(details);
let statusBox = document.createElement("div");
statusBox.className = "status";
statusBox.textContent = "就绪。";
body.appendChild(statusBox);
let setBusy = busy => {
moveBtn.disabled = busy;
trashBtn.disabled = busy;
closeBtn.disabled = busy;
};
let runAction = async action => {
try {
setBusy(true);
statusBox.textContent = "执行中...";
let message = await action();
statusBox.textContent = message || "完成。";
}
catch (error) {
statusBox.textContent = this._errorText(error);
}
finally {
setBusy(false);
}
};
moveBtn.addEventListener("click", () => {
runAction(async () => {
return await this._actionMoveCopies(parentWindow, scanResult);
});
});
trashBtn.addEventListener("click", () => {
runAction(async () => {
return await this._actionTrashDuplicates(parentWindow, scanResult);
});
});
};
CollectionDedupPlugin.prototype._buildSummaryText = function (scanResult) {
return [
"所选分类:" + scanResult.selectedCollectionPath,
"包含子分类:" + (scanResult.includeSubcollections ? "是" : "否"),
"扫描的常规条目数:" + scanResult.scannedCount,
"重复组数量:" + scanResult.duplicateGroupCount
].join("\n");
};
CollectionDedupPlugin.prototype._buildDetailsText = function (scanResult) {
let lines = [];
lines.push(this._buildSummaryText(scanResult));
lines.push("");
if (scanResult.duplicateGroupCount === 0) {
lines.push("在所选范围内未发现重复文献。");
return lines.join("\n");
}
for (let i = 0; i < scanResult.duplicateGroups.length; i++) {
let group = scanResult.duplicateGroups[i];
lines.push("第 " + (i + 1) + " 组(" + group.items.length + " 条)- 保留 itemID " + group.keep.item.id);
for (let record of group.items) {
let isKeep = record.item.id === group.keep.item.id;
let marker = isKeep ? "[保留]" : "[重复]";
let yearText = record.year ? String(record.year) : "";
let doiText = record.doi || "";
let pathText = record.scopePaths.length ? record.scopePaths.join(" ; ") : "(无范围内分类路径)";
lines.push(
" " + marker
+ " itemID=" + record.item.id
+ " | 标题=" + this._singleLine(record.title)
+ " | 年份=" + yearText
+ " | DOI=" + doiText
+ " | 分类路径=" + pathText
);
}
lines.push("");
}
return lines.join("\n");
};
CollectionDedupPlugin.prototype._singleLine = function (value) {
if (!value) {
return "";
}
return String(value).replace(/\s+/g, " ").trim();
};
CollectionDedupPlugin.prototype._collectDuplicateItemIDs = function (scanResult) {
let ids = [];
for (let group of scanResult.duplicateGroups) {
for (let record of group.duplicates) {
ids.push(record.item.id);
}
}
return ids;
};
CollectionDedupPlugin.prototype._actionMoveCopies = async function (window, scanResult) {
if (scanResult.duplicateGroupCount === 0) {
return "没有可移入的重复组。";
}
let duplicateItemIDs = this._collectDuplicateItemIDs(scanResult);
if (!duplicateItemIDs.length) {
return "没有可移入的重复条目。";
}
let proceed = Services.prompt.confirm(
window,
ADDON_NAME,
"将会在所选分类下创建/使用子分类“" + this._getDuplicatesCollectionName() + "”,并向其中添加 "
+ duplicateItemIDs.length + " 条重复文献。\n\n"
+ "此操作不会从原有分类中移除这些条目。\n\n是否继续?"
);
if (!proceed) {
return "已取消。";
}
let targetCollection = await this._getOrCreateDuplicatesCollection(scanResult.selectedCollection, this._getDuplicatesCollectionName());
let moved = 0;
for (let i = 0; i < duplicateItemIDs.length; i += 250) {
let chunk = duplicateItemIDs.slice(i, i + 250);
await targetCollection.addItems(chunk);
moved += chunk.length;
await this._yieldToUI();
}
return [
"已完成。",
"已添加到分类:" + this._getCollectionPath(targetCollection),
"新增条目数:" + moved
].join("\n");
};
CollectionDedupPlugin.prototype._getOrCreateDuplicatesCollection = async function (parentCollection, collectionName) {
let children = parentCollection.getChildCollections(false, false);
for (let child of children) {
if ((child.name || "") === collectionName) {
return child;
}
}
let collection = new Zotero.Collection();
collection.libraryID = parentCollection.libraryID;
collection.parentID = parentCollection.id;
collection.name = collectionName;
let collectionID = await collection.saveTx();
return Zotero.Collections.get(collectionID);
};
CollectionDedupPlugin.prototype._actionTrashDuplicates = async function (window, scanResult) {
if (scanResult.duplicateGroupCount === 0) {
return "没有可移入回收站的重复组。";
}
let duplicateItemIDs = this._collectDuplicateItemIDs(scanResult);
if (!duplicateItemIDs.length) {
return "没有可移入回收站的重复条目。";
}
let proceed = Services.prompt.confirm(
window,
ADDON_NAME,
"将把 " + duplicateItemIDs.length + " 条重复文献移入回收站,并在每个重复组保留一条最佳项。\n\n"
+ "是否继续?"
);
if (!proceed) {
return "已取消。";
}
await Zotero.Items.trashTx(duplicateItemIDs);
return [
"已完成。",