-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
464 lines (394 loc) · 13.3 KB
/
content.js
File metadata and controls
464 lines (394 loc) · 13.3 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
// Wikipedia Birthplace Corrector - Content Script
// Replaces Soviet-era birthplace designations with modern country names
(function() {
'use strict';
let isEnabled = true;
let isProcessing = false;
const PROCESSED_ATTR = 'data-antitankie-processed';
// Initialize: Check if extension is enabled
try {
chrome.runtime.sendMessage({ type: 'getState' }, (response) => {
if (chrome.runtime.lastError) {
isEnabled = true;
processPage();
return;
}
if (response && typeof response.enabled !== 'undefined') {
isEnabled = response.enabled;
} else {
isEnabled = true;
}
if (isEnabled) {
processPage();
}
});
} catch (e) {
isEnabled = true;
processPage();
}
// Also run on DOMContentLoaded as a fallback
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
if (isEnabled && !document.querySelector('[' + PROCESSED_ATTR + ']')) {
processPage();
}
});
}
// Listen for state changes from popup
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'toggleState') {
isEnabled = message.enabled;
if (isEnabled) {
processPage();
}
sendResponse({ success: true });
}
});
/**
* Main processing function - finds and replaces SSR references
*/
function processPage() {
if (!isEnabled || isProcessing) {
return;
}
isProcessing = true;
try {
let replacementCount = 0;
const targetElements = findTargetElements();
targetElements.forEach(element => {
if (element.hasAttribute(PROCESSED_ATTR)) {
return;
}
if (element.closest('[' + PROCESSED_ATTR + ']')) {
return;
}
const result = processElement(element);
if (result.changed) {
replacementCount += result.count;
element.setAttribute(PROCESSED_ATTR, 'true');
addVisualIndicator(element);
}
});
if (replacementCount > 0) {
try {
chrome.runtime.sendMessage({
type: 'incrementCount',
count: replacementCount
});
} catch (e) {
// Silently fail if background not available
}
}
} finally {
isProcessing = false;
}
}
/**
* Find all elements that should be processed
*/
function findTargetElements() {
const elements = [];
const infoboxes = document.querySelectorAll('.infobox');
infoboxes.forEach(infobox => {
const headers = infobox.querySelectorAll('th');
headers.forEach(th => {
const thText = th.textContent.trim();
if (thText === 'Born' || thText.startsWith('Born')) {
const td = th.nextElementSibling;
if (td && td.tagName === 'TD') {
elements.push(td);
}
}
});
const birthplaceElements = infobox.querySelectorAll('[class*="birthplace"]');
birthplaceElements.forEach(el => elements.push(el));
const cells = infobox.querySelectorAll('td, th');
cells.forEach(cell => {
if (window.AntiTankieReplacements &&
window.AntiTankieReplacements.containsSSRReference(cell.textContent)) {
elements.push(cell);
}
});
});
return elements;
}
/**
* Process a single element - replace text and links
*/
function processElement(element) {
let changed = false;
let count = 0;
if (!window.AntiTankieReplacements) {
console.warn('AntiTankieReplacements not loaded');
return { changed: false, count: 0 };
}
if (!window.AntiTankieReplacements.containsSSRReference(element.textContent)) {
return { changed: false, count: 0 };
}
// Process text nodes - handle both linked and plain text SSR references
const walker = document.createTreeWalker(
element,
NodeFilter.SHOW_TEXT,
null,
false
);
const textNodesToProcess = [];
let node;
while (node = walker.nextNode()) {
if (window.AntiTankieReplacements.containsSSRReference(node.textContent)) {
textNodesToProcess.push(node);
}
}
textNodesToProcess.forEach(textNode => {
const originalText = textNode.textContent;
const ssrMatch = window.AntiTankieReplacements.findSSRInText(originalText);
const parent = textNode.parentNode;
const isInsideLink = parent && parent.tagName === 'A';
if (ssrMatch && !isInsideLink) {
// Split the text and create a link
const parts = originalText.split(ssrMatch.ssrName);
const beforeText = parts[0];
const afterText = parts.slice(1).join(ssrMatch.ssrName);
let cleanAfterText = window.AntiTankieReplacements.removeSovietUnionReferences(afterText);
const link = document.createElement('a');
link.href = ssrMatch.wikiPath;
link.title = ssrMatch.modernName;
link.textContent = ssrMatch.modernName;
const beforeNode = document.createTextNode(beforeText);
const afterNode = document.createTextNode(cleanAfterText);
parent.insertBefore(beforeNode, textNode);
parent.insertBefore(link, textNode);
parent.insertBefore(afterNode, textNode);
parent.removeChild(textNode);
changed = true;
count++;
} else {
const newText = window.AntiTankieReplacements.replaceSSRNames(originalText);
if (originalText !== newText) {
textNode.textContent = newText;
changed = true;
count++;
}
}
});
// Process links - collect links to process/remove
const links = Array.from(element.querySelectorAll('a[href*="/wiki/"]'));
const linksToRemove = [];
links.forEach(link => {
const originalHref = link.getAttribute('href');
const shouldRemove = window.AntiTankieReplacements.shouldRemoveUrl(originalHref);
if (shouldRemove) {
linksToRemove.push(link);
changed = true;
count++;
return;
}
const newHref = window.AntiTankieReplacements.replaceSSRUrl(originalHref);
if (originalHref !== newHref) {
link.setAttribute('href', newHref);
changed = true;
count++;
}
if (window.AntiTankieReplacements.containsSSRReference(link.textContent)) {
const originalLinkText = link.textContent;
const newLinkText = window.AntiTankieReplacements.replaceSSRNames(originalLinkText);
if (originalLinkText !== newLinkText) {
link.textContent = newLinkText;
changed = true;
count++;
}
}
});
// Remove Soviet Union links and clean up surrounding text
linksToRemove.forEach(link => {
const prevSibling = link.previousSibling;
if (prevSibling && prevSibling.nodeType === Node.TEXT_NODE) {
const prevText = prevSibling.textContent;
if (prevText.endsWith(', ')) {
prevSibling.textContent = prevText.slice(0, -2);
} else if (prevText.endsWith(',')) {
prevSibling.textContent = prevText.slice(0, -1);
}
}
link.remove();
});
// Remove reference brackets like [a], [1], [note 1] etc.
removeReferenceBrackets(element);
ensureProperFormatting(element);
return { changed, count };
}
/**
* Remove reference links/brackets from the element
* These are typically <sup> elements with references that no longer make sense
*/
function removeReferenceBrackets(element) {
// Find all sup elements containing reference links
const sups = element.querySelectorAll('sup.reference, sup.noprint');
sups.forEach(sup => {
// Clean up any preceding whitespace
const prevSibling = sup.previousSibling;
if (prevSibling && prevSibling.nodeType === Node.TEXT_NODE) {
prevSibling.textContent = prevSibling.textContent.trimEnd();
}
sup.remove();
});
// Also remove standalone reference links that might not be in <sup>
const refLinks = element.querySelectorAll('a[href^="#cite_note"], a[href^="#ref"]');
refLinks.forEach(link => {
const parent = link.parentNode;
// If parent is a <sup>, remove the whole sup
if (parent && parent.tagName === 'SUP') {
const prevSibling = parent.previousSibling;
if (prevSibling && prevSibling.nodeType === Node.TEXT_NODE) {
prevSibling.textContent = prevSibling.textContent.trimEnd();
}
parent.remove();
} else {
// Just remove the link itself
link.remove();
}
});
}
/**
* Ensure proper formatting with commas between location parts
*/
function ensureProperFormatting(element) {
const birthplaceSpan = element.querySelector('.birthplace') || element;
const links = Array.from(birthplaceSpan.querySelectorAll('a[href*="/wiki/"]')).filter(link => {
const href = link.getAttribute('href') || '';
return !/\/wiki\/\d{4}$/.test(href) &&
!/\/wiki\/(January|February|March|April|May|June|July|August|September|October|November|December)/.test(href);
});
for (let i = 0; i < links.length - 1; i++) {
const currentLink = links[i];
const nextLink = links[i + 1];
let node = currentLink.nextSibling;
let hasComma = false;
let textNode = null;
while (node && node !== nextLink) {
if (node.nodeType === Node.TEXT_NODE) {
if (node.textContent.includes(',')) {
hasComma = true;
}
textNode = node;
}
node = node.nextSibling;
}
if (!hasComma && textNode) {
const text = textNode.textContent.trim();
if (text === '' || text === ' ') {
textNode.textContent = ', ';
}
} else if (!hasComma && !textNode) {
const comma = document.createTextNode(', ');
currentLink.parentNode.insertBefore(comma, nextLink);
}
}
}
/**
* Add visual indicator to corrected elements
*/
function addVisualIndicator(element) {
element.style.borderLeft = '3px solid #4CAF50';
element.style.paddingLeft = '8px';
element.setAttribute('title', 'Birthplace corrected by Wikipedia Birthplace Corrector');
if (element.querySelector('.antitankie-checkmark')) {
return;
}
const icon = document.createElement('span');
icon.className = 'antitankie-checkmark';
icon.textContent = ' ✓';
icon.style.cssText = `
color: #4CAF50;
font-size: 0.85em;
opacity: 0.8;
cursor: help;
white-space: nowrap;
`;
icon.setAttribute('title', 'Soviet-era location name corrected to modern country');
const birthplaceSpan = element.querySelector('.birthplace');
if (birthplaceSpan) {
birthplaceSpan.appendChild(icon);
return;
}
const links = element.querySelectorAll('a[href*="/wiki/"]');
let lastLocationLink = null;
links.forEach(link => {
const href = link.getAttribute('href') || '';
if (!/\/wiki\/\d{4}/.test(href) && !/\/wiki\/(January|February|March|April|May|June|July|August|September|October|November|December)/.test(href)) {
lastLocationLink = link;
}
});
if (lastLocationLink) {
lastLocationLink.insertAdjacentElement('afterend', icon);
return;
}
const brs = element.querySelectorAll('br');
if (brs.length > 0) {
const br = brs[0];
let sibling = br.nextSibling;
while (sibling) {
if (sibling.nodeType === Node.ELEMENT_NODE) {
sibling.appendChild(icon);
return;
} else if (sibling.nodeType === Node.TEXT_NODE && sibling.textContent.trim()) {
sibling.parentNode.insertBefore(icon, sibling.nextSibling);
return;
}
sibling = sibling.nextSibling;
}
}
element.appendChild(icon);
}
/**
* Set up MutationObserver to watch for dynamic content changes
*/
function setupMutationObserver() {
const observer = new MutationObserver((mutations) => {
if (!isEnabled || isProcessing) return;
let shouldReprocess = false;
mutations.forEach(mutation => {
const target = mutation.target;
if (target.nodeType === Node.ELEMENT_NODE && target.hasAttribute(PROCESSED_ATTR)) {
return;
}
if (target.parentElement && target.parentElement.hasAttribute(PROCESSED_ATTR)) {
return;
}
if (mutation.addedNodes.length > 0) {
mutation.addedNodes.forEach(node => {
if (node.nodeType === Node.ELEMENT_NODE) {
if (node.classList && node.classList.contains('antitankie-checkmark')) {
return;
}
if (node.classList && (node.classList.contains('infobox') ||
node.querySelector('.infobox:not([' + PROCESSED_ATTR + '])'))) {
shouldReprocess = true;
}
}
});
}
});
if (shouldReprocess) {
clearTimeout(observer.reprocessTimeout);
observer.reprocessTimeout = setTimeout(() => {
processPage();
}, 500);
}
});
observer.observe(document.body, {
childList: true,
subtree: true,
characterData: false
});
return observer;
}
// Start observing after initial page load
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
setupMutationObserver();
});
} else {
setupMutationObserver();
}
})();