-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
704 lines (596 loc) · 23.4 KB
/
content.js
File metadata and controls
704 lines (596 loc) · 23.4 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
// content.js - Optimized translation with batching, caching, and dynamic content support
//=============================================================================
// STATE & CONFIGURATION
//=============================================================================
let isTranslating = false;
let translationStartTime = null; // Track when translation started
const translationCache = new Map(); // In-memory cache: "fromLang|toLang|text" -> translation
const processedNodes = new WeakSet(); // Track nodes we've already translated
let mutationObserver = null;
let pendingNodes = []; // Queue for MutationObserver
let pendingTimeout = null;
// Configuration
const CONFIG = {
BATCH_MAX_CHARS: 4000, // Max characters per batch request
BATCH_MAX_ITEMS: 40, // Max items per batch
CONCURRENT_REQUESTS: 4, // Parallel request limit
MUTATION_DEBOUNCE_MS: 300, // Debounce time for dynamic content
RETRY_ATTEMPTS: 3,
RETRY_BASE_DELAY_MS: 250,
TRANSLATION_TIMEOUT_MS: 30000, // 30 second timeout for entire translation (reduced from 60s)
};
console.log('[Translator] Content script loaded, version 2.3.0');
// Korean detection regex (Hangul syllables, Jamo, compatibility Jamo)
const KOREAN_REGEX = /[\uAC00-\uD7AF\u1100-\u11FF\u3130-\u318F]/;
// Skip patterns: only ASCII, numbers, punctuation, whitespace
const SKIP_REGEX = /^[\x00-\x7F]*$/; // Pure ASCII
// Check if translation is stuck and reset if needed
function checkAndResetStuckState() {
if (isTranslating && translationStartTime) {
const elapsed = Date.now() - translationStartTime;
if (elapsed > CONFIG.TRANSLATION_TIMEOUT_MS) {
console.warn(`[Translator] Translation appears stuck (${elapsed}ms), resetting state`);
isTranslating = false;
translationStartTime = null;
return true; // Was stuck
}
}
return false;
}
//=============================================================================
// TRANSLATION BACKEND (Abstracted for Phase 2)
//=============================================================================
const TranslationBackend = {
// Translate a batch of texts, returns array of translations in same order
async translateBatch(texts, fromLang, toLang) {
// Try Google first, fallback to MyMemory
try {
const results = await this.googleBatchTranslate(texts, fromLang, toLang);
if (results && results.length === texts.length) {
return results;
}
} catch (error) {
console.log('[Translator] Google batch failed, trying MyMemory:', error.message);
}
// Fallback: translate individually with MyMemory
try {
const results = await Promise.all(
texts.map(text => this.myMemoryTranslate(text, fromLang, toLang))
);
return results;
} catch (error) {
console.log('[Translator] MyMemory fallback failed:', error.message);
return texts; // Return originals on complete failure
}
},
// Google Translate with multi-q batching
async googleBatchTranslate(texts, fromLang, toLang) {
// Build URL with multiple q parameters
const baseUrl = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${fromLang}&tl=${toLang}&dt=t`;
const qParams = texts.map(t => `&q=${encodeURIComponent(t)}`).join('');
const url = baseUrl + qParams;
const response = await this.fetchWithRetry(url);
const data = await response.json();
// Parse response - Google returns nested arrays
// For single q: data[0] = [[translation, original, ...], ...]
// For multi q: data[0] = array of translation segments per input
if (!data || !data[0]) {
throw new Error('Invalid Google response structure');
}
// Handle single vs multiple inputs
if (texts.length === 1) {
// Single input: data[0] contains segments for that one text
const segments = data[0];
const translation = segments.map(seg => seg[0]).join('');
return [translation];
} else {
// Multiple inputs: each data[0][i] might be segments for text[i]
// Actually, Google's multi-q returns all translations concatenated in data[0]
// We need to use a delimiter approach for reliable splitting
// Fallback to glue-string method for multiple texts
return this.googleGlueBatchTranslate(texts, fromLang, toLang);
}
},
// Glue-string batching for reliable multi-text translation
async googleGlueBatchTranslate(texts, fromLang, toLang) {
const DELIMITER = '\n{{SPLIT}}\n';
const combined = texts.join(DELIMITER);
const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${fromLang}&tl=${toLang}&dt=t&q=${encodeURIComponent(combined)}`;
const response = await this.fetchWithRetry(url);
const data = await response.json();
if (!data || !data[0]) {
throw new Error('Invalid Google response');
}
// Reconstruct full translation from segments
let fullTranslation = '';
for (const segment of data[0]) {
if (segment[0]) {
fullTranslation += segment[0];
}
}
// Split by delimiter (Google sometimes modifies it slightly)
const delimiterPattern = /\s*\{\{SPLIT\}\}\s*/gi;
const translations = fullTranslation.split(delimiterPattern);
// Validate we got the right count
if (translations.length !== texts.length) {
console.warn(`[Translator] Glue batch mismatch: expected ${texts.length}, got ${translations.length}`);
// If close, pad or truncate; if way off, throw
if (Math.abs(translations.length - texts.length) <= 2) {
while (translations.length < texts.length) {
translations.push(texts[translations.length]); // Use original
}
return translations.slice(0, texts.length);
}
throw new Error('Batch translation count mismatch');
}
return translations;
},
// MyMemory single translation (used as fallback)
async myMemoryTranslate(text, fromLang, toLang) {
const langPair = `${fromLang}|${toLang}`;
const url = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(text)}&langpair=${langPair}`;
try {
const response = await this.fetchWithRetry(url);
const data = await response.json();
if (data?.responseData?.translatedText) {
return data.responseData.translatedText;
}
} catch (error) {
console.log('[Translator] MyMemory error:', error.message);
}
return text; // Return original on failure
},
// Fetch with exponential backoff retry and timeout
async fetchWithRetry(url, attempt = 1) {
const FETCH_TIMEOUT_MS = 15000; // 15 second timeout per request
try {
// Create abort controller for timeout
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
const response = await fetch(url, { signal: controller.signal });
clearTimeout(timeoutId);
if (response.status === 429 || response.status === 503) {
if (attempt < CONFIG.RETRY_ATTEMPTS) {
const delay = CONFIG.RETRY_BASE_DELAY_MS * Math.pow(2, attempt - 1);
const jitter = Math.random() * 100;
console.log(`[Translator] Rate limited, retrying in ${delay}ms (attempt ${attempt})`);
await new Promise(r => setTimeout(r, delay + jitter));
return this.fetchWithRetry(url, attempt + 1);
}
throw new Error(`Rate limited after ${attempt} attempts`);
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response;
} catch (error) {
// Handle timeout specifically
if (error.name === 'AbortError') {
console.warn(`[Translator] Request timeout (attempt ${attempt})`);
}
if (attempt < CONFIG.RETRY_ATTEMPTS) {
const delay = CONFIG.RETRY_BASE_DELAY_MS * Math.pow(2, attempt - 1);
await new Promise(r => setTimeout(r, delay));
return this.fetchWithRetry(url, attempt + 1);
}
throw error;
}
}
};
//=============================================================================
// TRANSLATION PIPELINE
//=============================================================================
// Check if text should be translated based on language heuristics
function shouldTranslate(text, fromLang) {
const trimmed = text.trim();
// Skip empty or very short
if (trimmed.length === 0) return false;
if (trimmed.length === 1 && !KOREAN_REGEX.test(trimmed)) return false;
// Skip pure ASCII (numbers, English, punctuation) when source is Korean
if (fromLang === 'ko' || fromLang === 'auto') {
if (SKIP_REGEX.test(trimmed) && !KOREAN_REGEX.test(trimmed)) {
return false;
}
// For Korean source, require at least some Hangul
if (fromLang === 'ko' && !KOREAN_REGEX.test(trimmed)) {
return false;
}
}
return true;
}
// Generate cache key
function getCacheKey(text, fromLang, toLang) {
return `${fromLang}|${toLang}|${text.trim()}`;
}
// Track if title has been translated to avoid repeated translations
let titleTranslated = false;
// Translate document.title (lives in <head>, not walked by TreeWalker)
async function translateDocumentTitle(fromLang, toLang) {
if (titleTranslated) return;
const title = document.title;
if (!title || !shouldTranslate(title, fromLang)) {
console.log('[Translator] Title does not need translation');
return;
}
// Check cache first
const cacheKey = getCacheKey(title, fromLang, toLang);
if (translationCache.has(cacheKey)) {
document.title = translationCache.get(cacheKey);
titleTranslated = true;
console.log('[Translator] Title translated (cached):', document.title);
return;
}
// Translate
try {
const results = await TranslationBackend.translateBatch([title], fromLang, toLang);
if (results && results[0] && results[0] !== title) {
translationCache.set(cacheKey, results[0]);
document.title = results[0];
titleTranslated = true;
console.log('[Translator] Title translated:', document.title);
}
} catch (error) {
console.log('[Translator] Failed to translate title:', error.message);
}
}
// Collect all translatable text nodes from a root element
function collectTextNodes(root = document.body) {
const walker = document.createTreeWalker(
root,
NodeFilter.SHOW_TEXT,
{
acceptNode: function(node) {
// Skip script, style, noscript
const tag = node.parentElement?.tagName;
if (tag === 'SCRIPT' || tag === 'STYLE' || tag === 'NOSCRIPT') {
return NodeFilter.FILTER_REJECT;
}
// Skip already processed nodes
if (processedNodes.has(node)) {
return NodeFilter.FILTER_REJECT;
}
// Skip empty nodes
if (node.nodeValue.trim().length === 0) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
}
);
const nodes = [];
let node;
while (node = walker.nextNode()) {
nodes.push(node);
}
return nodes;
}
// Main translation function
// silent = true suppresses status popups (used for MutationObserver background translations)
async function translatePageContent(fromLang, toLang, nodes = null, silent = false) {
// Check if previous translation is stuck and reset if needed
if (isTranslating) {
const wasStuck = checkAndResetStuckState();
if (!wasStuck) {
console.log('[Translator] Translation already in progress');
return;
}
// If it was stuck, we continue with new translation
}
isTranslating = true;
translationStartTime = Date.now(); // Track start time for stuck detection
const startTime = performance.now();
const sourceLang = fromLang || 'ko';
const targetLang = toLang || 'en';
try {
// Translate document title first (only for manual/initial translations, not MutationObserver)
if (!nodes && !silent) {
await translateDocumentTitle(sourceLang, targetLang);
}
// Collect nodes if not provided (initial translation vs dynamic update)
const textNodes = nodes || collectTextNodes();
if (textNodes.length === 0) {
console.log('[Translator] No text nodes to translate');
isTranslating = false;
return;
}
if (!silent) {
showTranslationStatus(`Analyzing ${textNodes.length} text elements...`);
}
console.log(`[Translator] Found ${textNodes.length} text nodes`);
// Step 1: Deduplicate - group nodes by their text content
const textGroups = new Map(); // normalized text -> [nodes]
let skippedCount = 0;
for (const node of textNodes) {
const text = node.nodeValue.trim();
if (!shouldTranslate(text, sourceLang)) {
skippedCount++;
processedNodes.add(node); // Mark as processed so we don't revisit
continue;
}
if (!textGroups.has(text)) {
textGroups.set(text, []);
}
textGroups.get(text).push(node);
}
const uniqueTexts = Array.from(textGroups.keys());
console.log(`[Translator] ${uniqueTexts.length} unique texts (${skippedCount} skipped)`);
if (uniqueTexts.length === 0) {
// Silent mode: don't show "Nothing to translate" popup
if (!silent) {
// Even for manual, this is often not useful - just log it
console.log('[Translator] Nothing to translate');
}
isTranslating = false;
return;
}
// Step 2: Check cache and separate hits from misses
const cacheHits = new Map();
const cacheMisses = [];
for (const text of uniqueTexts) {
const cacheKey = getCacheKey(text, sourceLang, targetLang);
if (translationCache.has(cacheKey)) {
cacheHits.set(text, translationCache.get(cacheKey));
} else {
cacheMisses.push(text);
}
}
console.log(`[Translator] Cache: ${cacheHits.size} hits, ${cacheMisses.length} misses`);
// Step 3: Batch translate cache misses
if (cacheMisses.length > 0) {
if (!silent) {
showTranslationStatus(`Translating ${cacheMisses.length} unique texts...`);
}
// Create batches respecting size limits
const batches = createBatches(cacheMisses);
console.log(`[Translator] Created ${batches.length} batches`);
// Process batches with concurrency limit
const translations = await processWithConcurrency(
batches,
async (batch) => {
return TranslationBackend.translateBatch(batch, sourceLang, targetLang);
},
CONFIG.CONCURRENT_REQUESTS,
(completed, total) => {
if (!silent) {
const progress = Math.round((completed / total) * 100);
showTranslationStatus(`Translating... ${progress}%`);
}
}
);
// Flatten results and update cache
let idx = 0;
for (const batch of batches) {
const batchResults = translations[idx++];
for (let i = 0; i < batch.length; i++) {
const original = batch[i];
const translated = batchResults[i];
const cacheKey = getCacheKey(original, sourceLang, targetLang);
translationCache.set(cacheKey, translated);
cacheHits.set(original, translated);
}
}
}
// Step 4: Apply translations to DOM
let translatedCount = 0;
for (const [originalText, nodes] of textGroups) {
const translation = cacheHits.get(originalText);
if (translation && translation !== originalText) {
for (const node of nodes) {
// Preserve surrounding whitespace from original nodeValue
const original = node.nodeValue;
const leadingSpace = original.match(/^\s*/)[0];
const trailingSpace = original.match(/\s*$/)[0];
node.nodeValue = leadingSpace + translation + trailingSpace;
translatedCount++;
}
}
// Mark all nodes as processed
for (const node of nodes) {
processedNodes.add(node);
}
}
// Step 5: Report results
const elapsed = Math.round(performance.now() - startTime);
console.log(`[Translator] Done: ${translatedCount} nodes translated in ${elapsed}ms`);
console.log(`[Translator] Stats: ${uniqueTexts.length} unique, ${cacheHits.size - cacheMisses.length} cached, ${cacheMisses.length} fetched`);
if (!silent) {
showTranslationStatus(`Translated ${translatedCount} items (${elapsed}ms)`, true);
}
// Update icon to green
chrome.runtime.sendMessage({ type: 'updateIcon', status: 'green' }, () => {
if (chrome.runtime.lastError) {
// Ignore - tab might be closing
}
});
// Start observing for dynamic content if not already
startMutationObserver(sourceLang, targetLang);
} catch (error) {
console.error('[Translator] Translation error:', error);
if (!silent) {
showTranslationStatus('Translation failed: ' + error.message, false);
}
} finally {
isTranslating = false;
translationStartTime = null; // Clear tracking time
}
}
// Create batches respecting character and item limits
function createBatches(texts) {
const batches = [];
let currentBatch = [];
let currentChars = 0;
for (const text of texts) {
const textChars = text.length;
// Start new batch if limits exceeded
if (currentBatch.length >= CONFIG.BATCH_MAX_ITEMS ||
(currentChars + textChars > CONFIG.BATCH_MAX_CHARS && currentBatch.length > 0)) {
batches.push(currentBatch);
currentBatch = [];
currentChars = 0;
}
currentBatch.push(text);
currentChars += textChars + 10; // +10 for delimiter overhead
}
if (currentBatch.length > 0) {
batches.push(currentBatch);
}
return batches;
}
// Process items with concurrency limit
async function processWithConcurrency(items, processor, limit, onProgress) {
const results = new Array(items.length);
let nextIndex = 0;
let completedCount = 0;
async function worker() {
while (nextIndex < items.length) {
const index = nextIndex++;
results[index] = await processor(items[index]);
completedCount++;
if (onProgress) {
onProgress(completedCount, items.length);
}
}
}
// Start workers up to limit
const workers = [];
for (let i = 0; i < Math.min(limit, items.length); i++) {
workers.push(worker());
}
await Promise.all(workers);
return results;
}
//=============================================================================
// MUTATION OBSERVER (Dynamic Content)
//=============================================================================
function startMutationObserver(fromLang, toLang) {
if (mutationObserver) return; // Already running
mutationObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (node.nodeType === Node.TEXT_NODE) {
if (!processedNodes.has(node) && node.nodeValue.trim().length > 0) {
pendingNodes.push(node);
}
} else if (node.nodeType === Node.ELEMENT_NODE) {
// Collect text nodes from added elements
const textNodes = collectTextNodes(node);
pendingNodes.push(...textNodes);
}
}
}
// Debounce: wait for mutations to settle before translating
if (pendingNodes.length > 0 && !pendingTimeout) {
pendingTimeout = setTimeout(() => {
const nodesToTranslate = [...pendingNodes];
pendingNodes = [];
pendingTimeout = null;
if (nodesToTranslate.length > 0 && !isTranslating) {
console.log(`[Translator] MutationObserver: translating ${nodesToTranslate.length} new nodes`);
translatePageContent(fromLang, toLang, nodesToTranslate, true); // silent = true
}
}, CONFIG.MUTATION_DEBOUNCE_MS);
}
});
mutationObserver.observe(document.body, {
childList: true,
subtree: true
});
console.log('[Translator] MutationObserver started');
}
function stopMutationObserver() {
if (mutationObserver) {
mutationObserver.disconnect();
mutationObserver = null;
console.log('[Translator] MutationObserver stopped');
}
}
//=============================================================================
// UI HELPERS
//=============================================================================
function showTranslationStatus(message, isComplete) {
let statusDiv = document.getElementById('translation-status');
if (!statusDiv) {
statusDiv = document.createElement('div');
statusDiv.id = 'translation-status';
statusDiv.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
padding: 12px 18px;
background-color: #333;
color: white;
border-radius: 8px;
z-index: 999999;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
font-size: 13px;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
transition: opacity 0.3s ease;
`;
document.body.appendChild(statusDiv);
}
statusDiv.textContent = message;
statusDiv.style.opacity = '1';
if (isComplete !== undefined) {
statusDiv.style.backgroundColor = isComplete ? '#1a73e8' : '#d93025';
setTimeout(() => {
statusDiv.style.opacity = '0';
setTimeout(() => statusDiv.remove(), 300);
}, 2500);
}
}
//=============================================================================
// PAGE LANGUAGE DETECTION
//=============================================================================
function detectPageLanguage() {
const htmlLang = document.documentElement.lang;
const detectedLang = htmlLang ? htmlLang.split('-')[0].toLowerCase() : null;
chrome.storage.sync.get(['fromLang'], (settings) => {
const targetLang = settings.fromLang || 'ko';
let status = 'gray';
if (detectedLang && detectedLang !== 'en' && detectedLang !== targetLang) {
status = 'red';
} else if (detectedLang === targetLang) {
status = 'red';
}
chrome.runtime.sendMessage({ type: 'updateIcon', status: status }, () => {
if (chrome.runtime.lastError) {
// Ignore
}
});
});
}
//=============================================================================
// MESSAGE HANDLING
//=============================================================================
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log('[Translator] Message received:', message.type, 'from:', message.fromLang, 'to:', message.toLang);
if (message.type === 'translate' || message.type === 'autoTranslate') {
// Always check and reset stuck state before starting
checkAndResetStuckState();
// Send response immediately, then run translation async
sendResponse({ success: true, received: true });
// Small delay to ensure response is sent before heavy work
setTimeout(() => {
console.log('[Translator] Starting translation...');
translatePageContent(message.fromLang, message.toLang);
}, 10);
} else if (message.type === 'resetTranslation') {
stopMutationObserver();
titleTranslated = false; // Reset title tracking
location.reload();
sendResponse({ success: true });
}
return true;
});
//=============================================================================
// INITIALIZATION
//=============================================================================
// Detect language on load (but let background handle auto-translate trigger)
window.addEventListener('load', () => {
console.log('[Translator] Page loaded');
detectPageLanguage();
});
// Initial detection for already-loaded pages
if (document.readyState === 'complete') {
detectPageLanguage();
}