-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
3033 lines (2673 loc) · 145 KB
/
main.js
File metadata and controls
3033 lines (2673 loc) · 145 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
// <nowiki>
(function () {
const CiteUnseen = {
// ===============================
// PROPERTIES AND STATE
// ===============================
categorizedRules: null,
citeUnseenCategories: null,
citeUnseenCategoryTypes: null,
citeUnseenChecklists: null,
citeUnseenCategoryData: null,
citeUnseenDomainIgnore: {},
refs: [],
refLinks: [],
refCategories: {},
reflists: [],
convByVar: null,
vueApp: null,
currentSuggestionCitation: null,
_metaRules: null, // Stores rules loaded from meta.wikimedia.org
_localRules: null, // Stores rules loaded from local language wiki
// ===============================
// RULES OBJECT
// ===============================
ruleConfig: {
globalVars: [
'cite_unseen_categories',
'cite_unseen_domain_ignore',
'cite_unseen_additional_domains',
'cite_unseen_additional_strings',
'cite_unseen_dashboard',
'cite_unseen_show_suggestions',
'cite_unseen_hide_social_media_reliability_ratings'
],
mergeableProps: ['categories', 'domainIgnore', 'additionalDomains', 'additionalStrings'],
booleanProps: ['dashboard', 'showSuggestions', 'hideSocialMediaReliabilityRatings', 'showOtherLanguageReliabilityRatings'],
globalMapping: {
categories: 'cite_unseen_categories',
domainIgnore: 'cite_unseen_domain_ignore',
additionalDomains: 'cite_unseen_additional_domains',
additionalStrings: 'cite_unseen_additional_strings',
dashboard: 'cite_unseen_dashboard',
showSuggestions: 'cite_unseen_show_suggestions',
hideSocialMediaReliabilityRatings: 'cite_unseen_hide_social_media_reliability_ratings',
showOtherLanguageReliabilityRatings: 'cite_unseen_show_other_language_reliability_ratings'
}
},
// ===============================
// UTILITY FUNCTIONS
// ===============================
/**
* Parse a COinS string into an object
* @param {string} query - COinS string
* @returns {Object} Parsed object
*/
parseCoinsString: function (query) {
const result = {};
const pairs = query.split('&').filter(Boolean);
pairs.forEach(pair => {
const index = pair.indexOf('=');
const key = (index === -1 ? pair : pair.substring(0, index)).replace(/\+/g, ' ');
const value = (index === -1 ? '' : pair.substring(index + 1)).replace(/\+/g, ' ');
if (!result[key]) {
result[key] = value;
} else {
if (typeof result[key] === 'string') {
result[key] = [result[key]];
}
result[key].push(value);
}
});
return result;
},
/**
* Parse a date token into start/end range
* @param {string} token - Date token like "2020", "2020-06", or "2020-06-15"
* @returns {Object} Object with start and end Date objects
*/
parseDateToken: function (token) {
const parts = token.split("-");
if (parts.length === 1) {
// yyyy
const year = parseInt(parts[0], 10);
if (isNaN(year) || year < 1000 || year > 9999) {
throw new Error("Invalid year: " + parts[0]);
}
return {
start: new Date(year, 0, 1, 0, 0, 0, 0), // Start of Jan 1
end: new Date(year, 11, 31, 23, 59, 59, 999), // End of Dec 31
};
} else if (parts.length === 2) {
// yyyy-MM
const year = parseInt(parts[0], 10);
const month = parseInt(parts[1], 10) - 1;
if (isNaN(year) || isNaN(month) || year < 1000 || year > 9999 || month < 0 || month > 11) {
throw new Error("Invalid year-month: " + token);
}
const start = new Date(year, month, 1, 0, 0, 0, 0); // First day of month, start of day
const end = new Date(year, month + 1, 0, 23, 59, 59, 999); // Last day of month, end of day
return { start, end };
} else if (parts.length === 3) {
// yyyy-MM-dd
const year = parseInt(parts[0], 10);
const month = parseInt(parts[1], 10) - 1;
const day = parseInt(parts[2], 10);
if (isNaN(year) || isNaN(month) || isNaN(day) || year < 1000 || year > 9999 || month < 0 || month > 11 || day < 1 || day > 31) {
throw new Error("Invalid date: " + token);
}
const start = new Date(year, month, day, 0, 0, 0, 0); // Start of the day
const end = new Date(year, month, day, 23, 59, 59, 999); // End of the day
return { start, end };
} else {
throw new Error("Invalid date token format: " + token);
}
},
/**
* Translate a single rule (e.g. ">= 2010-01") into a predicate function.
* @param {string} rule - Single date rule with operator
* @returns {Function} Predicate function that takes a date and returns true/false
*/
ruleToPredicate: function (rule) {
rule = rule.trim();
const match = rule.match(/^(>=|<=|>|<|=)\s*(\d{4}(?:-\d{1,2})?(?:-\d{1,2})?)$/);
if (!match) {
throw new Error("Invalid rule format: " + rule);
}
const [, op, token] = match;
const { start, end } = CiteUnseen.parseDateToken(token);
switch (op) {
case ">=":
return d => d >= start;
case ">":
return d => d > end;
case "<=":
return d => d <= end;
case "<":
return d => d < start;
case "=":
return d => d >= start && d <= end;
default:
throw new Error("Unsupported operator: " + op);
}
},
/**
* Parse date rule string into predicate function
* @param {string} ruleString - Date rule, e.g. "<=2022-01-01,>=2020-01-01" (AND) or "<=2015;>=2017" (OR)
* @returns {Function|null} Predicate function or null if invalid
*/
parseDateRule: function (ruleString) {
const trimmedRule = ruleString.trim();
if (!trimmedRule) {
return null;
}
// Split by semicolons (OR groups)
const orGroups = trimmedRule.split(';').map(s => s.trim()).filter(Boolean);
const orGroupPredicates = [];
for (const orGroup of orGroups) {
// Within each OR group, split by commas (AND conditions)
const andConditions = orGroup.split(',').map(s => s.trim()).filter(Boolean);
const andPredicates = [];
for (let cond of andConditions) {
// Handle case where no operator is provided (default to '=')
if (!cond.match(/^(>=|<=|>|<|=)/)) {
cond = '=' + cond;
}
try {
const predicate = CiteUnseen.ruleToPredicate(cond);
andPredicates.push(predicate);
} catch (error) {
console.warn(`[Cite Unseen] ${error.message} in rule: "${orGroup}"`);
return null;
}
}
// Skip empty AND groups
if (andPredicates.length === 0) {
console.warn(`[Cite Unseen] Empty condition group in rule: "${orGroup}"`);
continue;
}
// Create predicate for this OR group
orGroupPredicates.push((date) => andPredicates.every(fn => fn(date)));
}
// If no valid OR groups found, return null
if (orGroupPredicates.length === 0) {
console.warn(`[Cite Unseen] No valid conditions found in rule: "${trimmedRule}"`);
return null;
}
return (inputDate) => {
const date = inputDate instanceof Date ? inputDate : new Date(inputDate);
if (isNaN(date.getTime())) {
return false;
}
return orGroupPredicates.some(fn => fn(date));
};
},
/**
* Escape special regex characters in string
* @param {string} string - String to escape
* @returns {string} Escaped string
*/
escapeRegex: function (string) {
if (typeof string !== 'string') {
console.warn('[Cite Unseen] escapeRegex called with non-string:', typeof string, string);
return String(string || '').replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}
return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
},
/**
* Build regular expression for URL matching
* @param {string} string - Domain string
* @returns {RegExp} URL matching regex
*/
urlRegex: function (string) {
return new RegExp('https?:\\/\\/([^\\/]*\\.)?' + CiteUnseen.escapeRegex(string) + '($|((?<=\\.)|\\/))');
},
/**
* Check if source author matches rule
* @param {Object} coins - COinS object
* @param {Object} rule - Rule object
* @returns {boolean} Whether author matches
*/
matchAuthor: function (coins, rule) {
if (!rule['author']) return false;
const authors = [];
// Extract authors from rft.au field
if (coins['rft.au']) {
authors.push(...CiteUnseen.ensureArray(coins['rft.au']));
}
// Extract authors from separate first/last name fields
if (coins['rft.aulast']) {
const lastNames = CiteUnseen.ensureArray(coins['rft.aulast']);
const firstNames = CiteUnseen.ensureArray(coins['rft.aufirst']);
const combinedAuthors = lastNames.map((lastName, i) => {
const firstName = firstNames[i] || '';
return firstName ? `${firstName} ${lastName}` : lastName;
});
authors.push(...combinedAuthors);
}
if (authors.length === 0) return false;
if (!rule._cachedAuthorRegex) {
rule._cachedAuthorRegex = new RegExp(rule['author'], 'i');
}
return authors.some(author => rule._cachedAuthorRegex.test(author));
},
/**
* Check if source publisher matches rule
* @param {Object} coins - COinS object
* @param {Object} rule - Rule object
* @returns {boolean} Whether publisher matches
*/
matchPublisher: function (coins, rule) {
const coinsPub = coins['rft.pub'] || coins['rft.jtitle'];
const coinsAuthor = coins['rft.au'] || coins['rft.aulast']; // Also consider author fields as potential publisher names
if (!(coinsPub || coinsAuthor) || !rule['pub']) return false;
const coinsPubCombined = CiteUnseen.ensureArray(coinsPub).concat(CiteUnseen.ensureArray(coinsAuthor));
if (!rule._cachedPublisherRegex) {
rule._cachedPublisherRegex = new RegExp(rule['pub'], 'i');
}
return CiteUnseen.ensureArray(coinsPubCombined).some(publisher =>
rule._cachedPublisherRegex.test(publisher)
);
},
/**
* Check if date in COinS object matches date rule
* @param {Object} coins - COinS object
* @param {Object} rule - Rule object
* @returns {boolean} Whether date matches rule
*/
matchDate: function (coins, rule) {
if (!rule['date']) {
return true;
}
const predicate = CiteUnseen.parseDateRule(rule['date']);
if (!predicate) {
return false;
}
if (!coins['rft.date']) {
return false;
}
return predicate(coins['rft.date']);
},
/**
* Check if source URL matches rule
* @param {Object} coins - COinS object
* @param {Object} rule - Rule object
* @returns {boolean} Whether URL matches
*/
matchUrl: function (coins, rule) {
if (typeof rule['url'] !== 'string' || rule['url'] === '') return false;
const rftIds = CiteUnseen.ensureArray(coins['rft_id']);
if (rftIds.length === 0) return false;
return rftIds.some(rftId => CiteUnseen.urlRegex(rule['url']).test(rftId));
},
/**
* Check if source's URL string matches rule
* @param {Object} coins - COinS object
* @param {Object} rule - Rule object
* @returns {boolean} Whether URL string matches
*/
matchUrlString: function (coins, rule) {
if (typeof rule['url_str'] !== 'string' || rule['url_str'] === '') return false;
const rftIds = CiteUnseen.ensureArray(coins['rft_id']);
if (rftIds.length === 0) return false;
return rftIds.some(rftId => rftId.includes(rule['url_str']));
},
/**
* Find matching reliability categories for a citation, prioritizing current language.
* Returns one match for current language, or all matches from other languages if none for current language.
* When there are conflicting evaluations within a language, defer to the one that has more conditions.
* @param {Object} coins - COinS object
* @param {Object} filteredCategorizedRules - Filtered rules by category
* @returns {Array} Array of match objects with type, name, and language
*/
findReliabilityMatch: function (coins, filteredCategorizedRules) {
const currentLanguage = mw.config.get('wgContentLanguage');
const languageMatches = {}, languageMultiCandidates = {}, languageCache = new Map();
// Function to extract language from checklist name
const getLanguage = (checklistName) => {
let language = languageCache.get(checklistName);
if (language === undefined) {
language = (checklistName.match(/^([a-z]{2})/) || [, 'unknown'])[1];
languageCache.set(checklistName, language);
}
return language;
};
// Function to add match to appropriate collection
const addMatch = (collection, language, matchData) => {
(collection[language] ||= []).push(matchData);
};
// Process all checklists to find matches
for (const [checklistType, checklists] of CiteUnseen.citeUnseenChecklists) {
for (const [checklistName, checklistID] of checklists) {
const rules = filteredCategorizedRules[checklistID];
if (!rules || !CiteUnseen.citeUnseenCategories[checklistID]) {
if (!rules) console.log('[Cite Unseen] ' + checklistID + ' is not in the ruleset.');
continue;
}
const language = getLanguage(checklistName);
let hasDirectMatch = false, hasConstrainedMatch = false;
for (const rule of rules) {
const specificity = (Boolean(rule['author']) ? 1.5 : 0.0) + (Boolean(rule['date']) ? 1.0 : 0.0) + (Boolean(rule['pub']) ? 0.7 : 0.0);
if (CiteUnseen.match(coins, rule)) {
hasDirectMatch = true;
addMatch(languageMatches, language, {
type: checklistType,
name: checklistName,
language: language,
spec: specificity
});
if (specificity === 0.0) break; // No need to check further if matched with no conditions
} else if (specificity > 0.0 && (CiteUnseen.matchUrl(coins, rule) || CiteUnseen.matchUrlString(coins, rule))) {
hasConstrainedMatch = true;
}
}
// Track multi candidates if no direct match but has constrained potential
if (!hasDirectMatch && hasConstrainedMatch) {
addMatch(languageMultiCandidates, language, {
type: 'multi',
name: checklistName,
language: language,
spec: -1.0 // Constrained match takes the least priority
});
}
}
}
// Function to select best match from multiple candidates
const selectBestMatch = (matches) => {
return matches.length === 1 ? matches[0] :
matches.reduce((best, current) => (current.spec > best.spec ? current : best));
};
// Function to create clean match object
const createCleanMatch = (match) => ({
type: match.type,
name: match.name,
language: match.language,
spec: match.spec
});
const results = { current: [], other: [] };
// Process direct matches
Object.entries(languageMatches).forEach(([language, matches]) => {
const cleanMatch = createCleanMatch(selectBestMatch(matches));
const targetArray = language === currentLanguage ? results.current : results.other;
targetArray.push(cleanMatch);
});
// Process multi candidates for languages without direct matches but has constrained potential
Object.entries(languageMultiCandidates).forEach(([language, multiCandidates]) => {
if (!languageMatches[language] && multiCandidates.length > 0) {
const cleanMatch = createCleanMatch(multiCandidates[0]);
const targetArray = language === currentLanguage ? results.current : results.other;
targetArray.push(cleanMatch);
}
});
if (window.cite_unseen_show_other_language_reliability_ratings === true) {
return results.current.concat(results.other);
} else {
return results.current.length > 0 ? results.current : results.other;
}
},
/**
* Find all matching type categories for a citation.
* @param {Object} coins - COinS object
* @param {Object} filteredCategorizedRules - Filtered rules by category
* @param {Array} typeCategories - Array of type categories to check
* @returns {Array} Array of matching category names
*/
findTypeMatches: function (coins, filteredCategorizedRules, typeCategories) {
const matches = [];
for (const category of typeCategories) {
let hasMatch = false;
// Check custom domains first
if (window.cite_unseen_additional_domains &&
window.cite_unseen_additional_domains[category] &&
window.cite_unseen_additional_domains[category].length > 0) {
const customDomains = CiteUnseen.ensureArray(window.cite_unseen_additional_domains[category]);
for (const domain of customDomains) {
const customRule = { 'url': domain };
if (CiteUnseen.match(coins, customRule)) {
hasMatch = true;
break;
}
}
}
// Check custom URL strings
if (!hasMatch && window.cite_unseen_additional_strings &&
window.cite_unseen_additional_strings[category] &&
window.cite_unseen_additional_strings[category].length > 0) {
const customStrings = CiteUnseen.ensureArray(window.cite_unseen_additional_strings[category]);
for (const urlStr of customStrings) {
const customRule = { 'url_str': urlStr };
if (CiteUnseen.match(coins, customRule)) {
hasMatch = true;
break;
}
}
}
// Check built-in categorizations
if (!hasMatch && filteredCategorizedRules[category]) {
for (const rule of filteredCategorizedRules[category]) {
if (CiteUnseen.match(coins, rule)) {
hasMatch = true;
break;
}
}
}
// Add to matches if match is found and category is enabled
if (hasMatch && CiteUnseen.citeUnseenCategories[category]) {
matches.push(category);
}
}
return matches;
},
/**
* Check if the source matches the rule.
* @param {Object} coins - COinS object
* @param {Object} rule - Rule
* @returns {boolean} Whether it matches the rule
*/
match: function (coins, rule) {
if (!rule) {
console.log("[Cite Unseen] There are empty rules in the ruleset.");
return false;
}
const matchFunctions = {
'author': CiteUnseen.matchAuthor,
'pub': CiteUnseen.matchPublisher,
'date': CiteUnseen.matchDate,
'url': CiteUnseen.matchUrl,
'url_str': CiteUnseen.matchUrlString,
};
for (const key of Object.keys(rule)) {
if (!matchFunctions[key]) {
console.log("[Cite Unseen] Unknown rule:");
console.log(rule);
continue;
}
if (!matchFunctions[key](coins, rule)) {
return false;
}
}
return true;
},
// ===============================
// ICON PROCESSING AND DISPLAY
// ===============================
/**
* Add icons to citation sources. Only executed once on page load.
*/
addIcons: function () {
const filteredCategorizedRules = {};
Object.keys(CiteUnseen.categorizedRules).forEach(key => {
const domainIgnoreList = CiteUnseen.citeUnseenDomainIgnore[key] || [];
filteredCategorizedRules[key] = CiteUnseen.categorizedRules[key].filter(rule => {
const domain = rule['url'];
const urlStr = rule['url_str'];
// If rule has url field, check if any domains match
if (domain) {
return !domainIgnoreList.includes(domain) &&
CiteUnseen.refLinks.some(link => link.includes(domain));
}
// If rule has url_str field, check if any links contain the string
if (urlStr) {
return CiteUnseen.refLinks.some(link => link.includes(urlStr));
}
});
});
const typeCategories = CiteUnseen.citeUnseenCategoryTypes;
CiteUnseen.refs.forEach(ref => {
// Insert icon area before the <cite> tag
const iconsDiv = CiteUnseen.createIconsDiv();
ref.cite.prepend(iconsDiv);
const processedCategories = new Set();
// Determine the source type based on the class name
const classList = ref.cite.classList;
const bookClasses = ["book", "journal", "encyclopaedia", "conference", "thesis", "magazine"];
const tvClasses = ["episode", "podcast", "media"];
const hasNewsClass = classList.contains("news");
// Check CSS-based classifications first
if (bookClasses.some(cls => classList.contains(cls))) {
if (CiteUnseen.citeUnseenCategories.books && !processedCategories.has("books")) {
CiteUnseen.processIcon(iconsDiv, "books");
processedCategories.add("books");
}
}
if (classList.contains("pressrelease")) {
if (CiteUnseen.citeUnseenCategories.press && !processedCategories.has("press")) {
CiteUnseen.processIcon(iconsDiv, "press");
processedCategories.add("press");
}
}
if (tvClasses.some(cls => classList.contains(cls))) {
if (CiteUnseen.citeUnseenCategories.tvPrograms && !processedCategories.has("tvPrograms")) {
CiteUnseen.processIcon(iconsDiv, "tvPrograms");
processedCategories.add("tvPrograms");
}
}
// If rft_id, check URL-based classifications
const rftIds = CiteUnseen.ensureArray(ref.coins['rft_id']);
if (rftIds.length > 0) {
// Find reliability and type matches
const reliabilityMatches = CiteUnseen.findReliabilityMatch(ref.coins, filteredCategorizedRules);
const typeMatches = CiteUnseen.findTypeMatches(ref.coins, filteredCategorizedRules, typeCategories);
const hideSocialMediaReliabilityRating = window.cite_unseen_hide_social_media_reliability_ratings === true && typeMatches.includes('social');
// Process reliability categories
for (const reliabilityMatch of reliabilityMatches) {
// If hiding social media reliability ratings, skip generic (spec=0) matches
if (hideSocialMediaReliabilityRating && reliabilityMatch.spec === 0.0) {
continue;
}
// We can show multiple icons from various language source evaluations,
// if current language wiki has none.
const reliabilityKey = `${reliabilityMatch.type}_${reliabilityMatch.language}`;
if (!processedCategories.has(reliabilityKey)) {
CiteUnseen.processIcon(iconsDiv, reliabilityMatch.type, reliabilityMatch.name, reliabilityMatch.language);
processedCategories.add(reliabilityKey);
processedCategories.add(reliabilityMatch.type);
}
}
// Process type categories
for (const typeMatch of typeMatches) {
if (!processedCategories.has(typeMatch)) {
CiteUnseen.processIcon(iconsDiv, typeMatch);
processedCategories.add(typeMatch);
}
}
}
if (rftIds.length === 0 || rftIds.some(id => id.startsWith('info:sid/'))) {
// If a template is already categorized as news via CSS but links are missing,
// treat it as news instead of falling back to unknown.
if (processedCategories.size === 0 && hasNewsClass && CiteUnseen.citeUnseenCategories.news) {
CiteUnseen.processIcon(iconsDiv, "news");
processedCategories.add("news");
}
}
if (CiteUnseen.citeUnseenCategories.unknown && processedCategories.size === 0) {
CiteUnseen.trackUnknownCitation(iconsDiv);
}
});
},
/**
* Add to count. Currently, it records regardless of whether it is in the reflist.
* @param {Element} node - The node
* @param {String} type - The type
*/
addToCount: function (node, type) {
CiteUnseen.citeUnseenCategoryData[type].count++;
},
/**
* Add an icon and tooltip to a node.
* @param {Element} node - The iconsDiv node
* @param {String} type - The type
* @param {String|null} checklist - The checklist
* @param {String|null} language - Language code for reliability icons
* @returns {Element} The iconNode element
*/
processIcon: function (node, type, checklist = null, language = null) {
const iconContainer = document.createElement("span");
iconContainer.classList.add("cite-unseen-icon-container");
const iconNode = document.createElement("img");
iconNode.classList.add("skin-invert");
iconNode.classList.add("cite-unseen-icon-" + type);
iconNode.classList.add("cite-unseen-icon");
iconNode.setAttribute("src", CiteUnseen.citeUnseenCategoryData[type].icon);
let message = CiteUnseen.convByVar(CiteUnseenI18n.categoryHints[type]);
if (checklist) {
const pageLink = CiteUnseen.citeUnseenData.resolveSourceToPageLink(checklist);
const displayName = pageLink || checklist;
message = CiteUnseen.convByVar(CiteUnseenI18n.citationTooltipPrefix) + ' ' + displayName +
CiteUnseen.convByVar(CiteUnseenI18n.citationTooltipSuffix) + ' ' + message + ' ' +
CiteUnseen.convByVar(CiteUnseenI18n.citationTooltipAction);
}
iconNode.setAttribute("alt", message);
iconNode.setAttribute("title", "[Cite Unseen] " + message);
CiteUnseen.addToCount(node, type);
if (checklist) {
// If there is a checklist, wrap the icon in a link.
const iconNodeLink = document.createElement("a");
const pageLink = CiteUnseen.citeUnseenData.resolveSourceToPageLink(checklist);
if (pageLink) {
const [lang, ...pageParts] = pageLink.split(':');
const fullPagePath = pageParts.join(':');
iconNodeLink.setAttribute("href", `//${lang}.wikipedia.org/wiki/${fullPagePath}`);
}
iconNodeLink.setAttribute("target", "_blank");
iconNodeLink.classList.add("cite-unseen-icon-link");
iconNodeLink.appendChild(iconNode);
// Add language indicator for reliability icons from different languages.
if (language && language !== mw.config.get('wgContentLanguage') && ['blacklisted', 'deprecated', 'generallyUnreliable', 'marginallyReliable', 'generallyReliable', 'multi'].includes(type)) {
const langIndicator = document.createElement("span");
langIndicator.classList.add("cite-unseen-lang-indicator");
langIndicator.textContent = language.toUpperCase();
iconNodeLink.appendChild(langIndicator);
}
iconContainer.appendChild(iconNodeLink);
node.appendChild(iconContainer);
} else {
iconContainer.appendChild(iconNode);
node.appendChild(iconContainer);
}
if (!CiteUnseen.refCategories[type]) {
CiteUnseen.refCategories[type] = [];
}
CiteUnseen.refCategories[type].push(node.parentNode);
return iconNode;
},
/**
* Track a citation as unknown.
* @param {Element} node - The iconsDiv node (parent of the citation)
*/
trackUnknownCitation: function (node) {
const type = "unknown";
CiteUnseen.addToCount(node, type);
if (!CiteUnseen.refCategories[type]) {
CiteUnseen.refCategories[type] = [];
}
CiteUnseen.refCategories[type].push(node.parentNode);
},
/**
* Parse a string containing the plural marker "(s)"
* @param {string} string - The string to parse
* @param {number} value - The value used to determine plural form
* @return {string} - The parsed string
*/
parseI18nPlural: function (string, value) {
return string.replace(/\(s\)/g, value === 1 ? '' : 's');
},
// ===============================
// UI AND DASHBOARD
// ===============================
/**
* Show the settings button for Cite Unseen configuration.
* @param {boolean} minerva - Whether the Minerva skin is used
* @returns {Element} The settings button element
*/
createSettingsButton: function (minerva) {
const settingsButton = document.createElement('a');
if (minerva) {
settingsButton.classList.add('cdx-button', 'cdx-button--size-large', 'cdx-button--fake-button', 'cdx-button--fake-button--enabled', 'cdx-button--icon-only', 'cdx-button--weight-quiet');
// Settings icon
const icon = document.createElement('span');
icon.classList.add('skin-invert', 'minerva-icon');
icon.classList.add('cite-unseen-minerva-icon', 'cite-unseen-minerva-settings-icon');
settingsButton.appendChild(icon);
} else {
settingsButton.classList.add('cite-unseen-edit-style');
// Settings label
const label = document.createElement('span');
label.textContent = CiteUnseen.convByVar(CiteUnseenI18n.settingsButton);
settingsButton.appendChild(label);
}
settingsButton.onclick = function (e) {
e.preventDefault();
CiteUnseen.openSettingsDialog();
};
settingsButton.setAttribute('title', CiteUnseen.convByVar(CiteUnseenI18n.settingsButtonTooltip));
return settingsButton;
},
/**
* Create a dashboard for a specific reflist
* @param {Object} reflistData - The reflist data object
*/
createDashboardForReflist: function (reflistData) {
// Calculate category counts
const reflistCategoryCounts = CiteUnseen.calculateCategoryCountsForReflist(reflistData);
const hasCategorizations = Object.values(reflistCategoryCounts).some(count => count > 0);
if (!hasCategorizations) {
return; // Don't create dashboard if no categorizations
}
const dashboard = {
div: document.createElement('div'),
header: document.createElement('div'),
total: document.createElement('div'),
clearAll: null,
cats: document.createElement('div'),
reflistData: reflistData
};
reflistData.dashboard = dashboard;
dashboard.div.classList.add('cite-unseen-dashboard');
dashboard.header.classList.add('cite-unseen-dashboard-header');
// 'Clear All' button
const clearAllButton = document.createElement('span');
clearAllButton.className = 'cite-unseen-clear-all-header cite-unseen-hidden';
clearAllButton.innerText = CiteUnseen.convByVar(CiteUnseenI18n.clearAllFilters);
clearAllButton.setAttribute('title', CiteUnseen.convByVar(CiteUnseenI18n.clearAllFiltersTooltip));
clearAllButton.setAttribute('role', 'button');
clearAllButton.setAttribute('tabindex', '0');
clearAllButton.onclick = function () {
CiteUnseen.clearAllFiltersForReflist(dashboard.reflistData);
};
clearAllButton.onkeydown = function (e) {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
clearAllButton.onclick();
}
};
dashboard.clearAll = clearAllButton;
// Cache the total citation count
reflistData.totalCitations = reflistData.element.querySelectorAll('li').length;
// Show citation count
CiteUnseen.updateFilteredCountForReflist(dashboard, reflistData.totalCitations, reflistData.totalCitations);
dashboard.total.classList.add('cite-unseen-dashboard-total');
// Add total and clear all button to header
dashboard.header.appendChild(dashboard.total);
dashboard.header.appendChild(clearAllButton);
dashboard.div.appendChild(dashboard.header);
dashboard.cats.classList.add('cite-unseen-dashboard-cats');
dashboard.div.appendChild(dashboard.cats);
// Insert the dashboard before this reflist
const parentElement = reflistData.element.parentNode;
if (parentElement) {
let insertPosition = reflistData.element;
// If the reflist is preceded by a floated element, insert before that.
// Note: On jawiki, there is a {{脚注ヘルプ}} that often floats right before the reflist.
if (insertPosition.previousElementSibling && window.getComputedStyle(insertPosition.previousElementSibling).float !== 'none') {
insertPosition = insertPosition.previousElementSibling;
}
if (insertPosition.previousElementSibling && insertPosition.previousElementSibling.classList.contains('cite-unseen-dashboard')) {
return; // Dashboard already exists (duplication)
}
parentElement.insertBefore(dashboard.div, insertPosition);
}
CiteUnseen.updateDashboardCategories(dashboard, reflistCategoryCounts);
},
/**
* Calculate category counts for a specific reflist
* @param {Object} reflistData - The reflist data object
* @returns {Object} Category counts for this reflist
*/
calculateCategoryCountsForReflist: function (reflistData) {
const counts = {};
// Get all category types
const categoryTypes = CiteUnseen.getAllCategoryTypes(); // Order doesn't matter here
// Initialize all category counts to 0
for (const category of categoryTypes) {
counts[category] = 0;
}
// Count citations in this reflist by category
for (const ref of reflistData.refs) {
// Find which categories this citation belongs to
for (const category in CiteUnseen.refCategories) {
const categoryNodes = CiteUnseen.refCategories[category];
if (categoryNodes && categoryNodes.includes(ref.cite)) {
counts[category]++;
// Store the reference to this category for this reflist
if (!reflistData.categories[category]) {
reflistData.categories[category] = [];
}
reflistData.categories[category].push(ref.cite);
}
}
}
return counts;
},
/**
* Get all category types used in the system.
* The order only matters when displaying in the dashboard.
* @returns {Array} Array of all category type strings
*/
getAllCategoryTypes: function () {
return [...CiteUnseen.citeUnseenChecklists.flatMap(x => x[0]).toReversed(), ...CiteUnseen.citeUnseenCategoryTypes, 'unknown'];
},
/**
* Update dashboard categories display for a specific dashboard
* @param {Object} dashboard - The dashboard object
* @param {Object} categoryCounts - Category counts for this reflist
*/
updateDashboardCategories: function (dashboard, categoryCounts) {
// Clear existing categories
dashboard.cats.innerHTML = '';
// List each type of source in order
const categoryTypes = CiteUnseen.getAllCategoryTypes(); // Order matters here
for (const category of categoryTypes) {
const count = categoryCounts[category] || 0;
if (count > 0) {
const countNode = document.createElement('div');
countNode.setAttribute('data-category', category);
countNode.classList.add('cite-unseen-category-item');
const countIcon = document.createElement('img');
countIcon.alt = CiteUnseen.convByVar(CiteUnseenI18n.categoryHints[category]);
countIcon.src = CiteUnseen.citeUnseenCategoryData[category].icon;
countIcon.width = '17';
countIcon.classList.add("skin-invert");
countIcon.classList.add('cite-unseen-category-icon');
const countText = document.createElement('span');
const categoryLabel = CiteUnseen.convByVar(CiteUnseenI18n.categoryLabels[category]);
// Handle plural for English
const labelText = mw.config.get('wgContentLanguage') === 'en' ?
CiteUnseen.parseI18nPlural(categoryLabel, count) :
categoryLabel;
countText.innerText = count + ' ' + labelText;
countText.classList.add('cite-unseen-category-text');
countNode.onclick = function () {
CiteUnseen.toggleCategoryFilterForReflist(dashboard.reflistData, category);
};
countNode.setAttribute('role', 'button');
countNode.setAttribute('tabindex', '0');
countNode.setAttribute('aria-pressed', 'false');
countNode.setAttribute('title', CiteUnseen.convByVar(CiteUnseenI18n.filterToggleTooltip));
countNode.onkeydown = function (e) {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
countNode.onclick();
}
};
countNode.appendChild(countIcon);
countNode.appendChild(countText);
dashboard.cats.appendChild(countNode);
}
}
},
/**
* Get the appropriate container element for a citation (usually the <li> element)
* @param {Element} citationElement - The citation element
* @returns {Element} The container element to show/hide
*/
getCitationContainer: function (citationElement) {
// Find closest li element
const listItem = citationElement.closest('li');
// Return the list item if found, otherwise use the citation element itself
return listItem || citationElement;
},
/**
* Toggle a category filter on/off for a specific reflist
* @param {Object} reflistData - The reflist data object
* @param {string} category - Citation category to toggle
*/
toggleCategoryFilterForReflist: function (reflistData, category) {
if (!reflistData || !reflistData.selectedCategories || !category) {
console.warn('[Cite Unseen] Invalid parameters provided to toggleCategoryFilterForReflist');
return;
}
if (reflistData.selectedCategories.has(category)) {