-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1718 lines (1451 loc) · 58.3 KB
/
content.js
File metadata and controls
1718 lines (1451 loc) · 58.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
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
/**
* Discord Message Translator - Content Script
* Author: Tomáš Mark
*
* Automatically translates Discord messages to the page language
*/
// ============================================================================
// CONFIGURATION
// ============================================================================
const CONFIG = {
// Debug settings
DEBUG_ENABLED: false, // Master switch for all debug logging
DEBUG_VERBOSE: false, // Extra detailed logs (element detection, viewport checks, etc.)
DEBUG_API_REQUESTS: false, // Log API requests and responses
DEBUG_TRANSLATIONS: false, // Log translation progress
DEBUG_PERFORMANCE: false, // Log timing and performance info
// DEBUG_ENABLED: true, // Master switch for all debug logging
// DEBUG_VERBOSE: true, // Extra detailed logs (element detection, viewport checks, etc.)
// DEBUG_API_REQUESTS: true, // Log API requests and responses
// DEBUG_TRANSLATIONS: true, // Log translation progress
// DEBUG_PERFORMANCE: true, // Log timing and performance info
// Translation settings
API_DELAY_MS: 50, // Delay between translation requests
CYCLE_DELAY_MS: 2000, // Delay between processing cycles
TARGET_LANGUAGE: 'cs', // Target language (Czech)
TRANSLATION_ALTERNATIVES: 3, // LibreTranslate alternatives count
LIBRETRANSLATE_API_KEY: '', // Set if your LibreTranslate requires an API key
// UI settings
DEBUG_STYLING: false, // Yellow background + red border for translations
MANUAL_TRANSLATION: true, // Enable manual translation with flag icon click
};
// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const logger = {
debug: (...args) => {
if (CONFIG.DEBUG_ENABLED && CONFIG.DEBUG_VERBOSE) {
console.debug('[Discord Translator]', ...args);
}
},
log: (...args) => {
if (CONFIG.DEBUG_ENABLED) {
console.log('[Discord Translator]', ...args);
}
},
warn: (...args) => {
if (CONFIG.DEBUG_ENABLED) {
console.warn('[Discord Translator]', ...args);
}
},
error: (...args) => {
// Always log errors
console.error('[Discord Translator]', ...args);
},
api: (...args) => {
if (CONFIG.DEBUG_ENABLED && CONFIG.DEBUG_API_REQUESTS) {
console.log('[Discord Translator] 🌐', ...args);
}
},
translate: (...args) => {
if (CONFIG.DEBUG_ENABLED && CONFIG.DEBUG_TRANSLATIONS) {
console.log('[Discord Translator] 🔄', ...args);
}
},
perf: (...args) => {
if (CONFIG.DEBUG_ENABLED && CONFIG.DEBUG_PERFORMANCE) {
console.log('[Discord Translator] ⚡', ...args);
}
}
};
// ============================================================================
// TRANSLATION SERVICE
// ============================================================================
class TranslationService {
/**
* Prepare translation request for LibreTranslate API (self-hosted)
*/
static prepareBatchTranslation(texts, options = {}) {
const targetLang = options.to || 'en';
const sourceLang = options.from || 'auto';
// LibreTranslate uses single text per request
const text = texts[0]; // We're already sending one text at a time
// LibreTranslate requires POST with JSON body
const url = 'http://127.0.0.1:5000/translate';
const data = JSON.stringify({
q: text,
source: sourceLang,
target: targetLang,
format: 'text',
alternatives: CONFIG.TRANSLATION_ALTERNATIVES,
api_key: CONFIG.LIBRETRANSLATE_API_KEY
});
return { url, data };
}
/**
* Format batch translation response from Google Translate API
*/
static formatBatchResponse(originalTexts, response) {
const results = {};
try {
if (Array.isArray(response) && response[0]) {
originalTexts.forEach((originalText, index) => {
const translated = response[0][index];
if (translated && translated[0]) {
results[index] = {
before: originalText,
after: translated[0],
detectedLanguage: translated[1] || 'unknown'
};
}
});
}
} catch (error) {
logger.error('Error formatting translation response:', error);
}
return results;
}
}
// ============================================================================
// CONTENT SCRIPT CONTEXT MANAGER
// ============================================================================
class ContentScriptContext {
constructor(scriptName) {
this.scriptName = scriptName;
this.abortController = new AbortController();
this.isTopFrame = window.self === window.top;
this.receivedMessageIds = new Set();
if (this.isTopFrame) {
this.stopOldScripts();
this.listenForNewerScripts({ ignoreFirstEvent: true });
} else {
this.listenForNewerScripts();
}
}
get signal() {
return this.abortController.signal;
}
get isValid() {
return !this.signal.aborted && chrome.runtime?.id != null;
}
get isInvalid() {
return !this.isValid;
}
onInvalidated(callback) {
this.signal.addEventListener('abort', callback);
return () => this.signal.removeEventListener('abort', callback);
}
stopOldScripts() {
const messageType = `${chrome.runtime.id}:content-script-started`;
window.postMessage({
type: messageType,
contentScriptName: this.scriptName,
messageId: Math.random().toString(36).slice(2)
}, '*');
}
listenForNewerScripts(options = {}) {
let isFirst = true;
const messageType = `${chrome.runtime.id}:content-script-started`;
const handler = (event) => {
if (event.data?.type === messageType &&
event.data?.contentScriptName === this.scriptName &&
!this.receivedMessageIds.has(event.data?.messageId)) {
this.receivedMessageIds.add(event.data.messageId);
const shouldIgnore = isFirst && options.ignoreFirstEvent;
isFirst = false;
if (!shouldIgnore) {
this.abortController.abort('Newer script detected');
logger.debug(`Content script "${this.scriptName}" invalidated by newer instance`);
}
}
};
window.addEventListener('message', handler);
this.onInvalidated(() => window.removeEventListener('message', handler));
}
}
// ============================================================================
// DISCORD MESSAGE TRANSLATOR
// ============================================================================
class DiscordTranslator {
constructor(context) {
this.context = context;
this.translationCache = new Map(); // text -> translation (persistent across channels)
this.processedMessages = new Set(); // Set of message IDs that have been processed (cleared on channel change)
this.messageTranslations = new Map(); // messageId -> { text, translation, element }
this.PROCESSED_ATTRIBUTE = 'discord-translator-processed';
this.TRANSLATION_CLASS = 'discord-translator-translation';
this.FLAG_ICON_CLASS = 'discord-translator-flag-icon';
this.FLAG_CONTAINER_CLASS = 'discord-translator-flag-container';
this.currentChannelId = null; // Track current channel
this.isTranslating = false; // Flag to prevent multiple concurrent translations
this.scrollTimeout = null; // Debounce scroll events
this.isActive = true; // Translator automatically active for Discord
this.processingInterval = null; // Interval for processing messages
// Inject CSS for flag icons
this.injectFlagIconStyles();
}
/**
* Inject CSS styles for flag icons
*/
injectFlagIconStyles() {
if (document.getElementById('discord-translator-flag-styles')) {
return; // Already injected
}
const styleElement = document.createElement('style');
styleElement.id = 'discord-translator-flag-styles';
styleElement.textContent = `
.${this.FLAG_CONTAINER_CLASS} {
display: inline-flex;
align-items: center;
opacity: 0.5;
transition: opacity 0.3s ease;
position: absolute;
right: 0%;
top: 50%;
transform: translateY(-50%);
z-index: 10;
pointer-events: auto;
}
/* Make parent message have relative positioning for absolute child */
[class*="markup"] {
position: relative;
}
.${this.FLAG_CONTAINER_CLASS}:hover {
opacity: 1;
}
.${this.FLAG_ICON_CLASS} {
cursor: pointer;
font-size: 20.72px;
padding: 0;
border-radius: 4px;
transition: all 0.3s ease;
user-select: none;
display: inline-flex;
align-items: center;
justify-content: center;
background: transparent;
border: none;
width: 22.68px;
height: 22.68px;
color: var(--text-muted, #747f8d);
position: relative;
}
.${this.FLAG_ICON_CLASS}:hover {
background: rgba(88, 101, 242, 0.15);
color: #5865f2;
transform: scale(1.0);
box-shadow: none;
}
/* Better visibility in different Discord themes */
[data-theme="light"] .${this.FLAG_ICON_CLASS}:hover {
background: rgba(88, 101, 242, 0.12);
box-shadow: 0 1px 3px rgba(88, 101, 242, 0.25);
}
[data-theme="dark"] .${this.FLAG_ICON_CLASS}:hover {
background: rgba(88, 101, 242, 0.18);
box-shadow: 0 2px 4px rgba(88, 101, 242, 0.15);
}
.${this.FLAG_ICON_CLASS}:active {
transform: scale(0.95);
background: rgba(88, 101, 242, 0.25);
}
.${this.FLAG_ICON_CLASS}:focus {
outline: none;
background: rgba(88, 101, 242, 0.1);
box-shadow: 0 0 0 2px rgba(88, 101, 242, 0.3);
}
.${this.FLAG_ICON_CLASS}.translating {
opacity: 0.5;
cursor: wait;
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0%, 100% { opacity: 0.5; }
50% { opacity: 0.8; }
}
.${this.FLAG_ICON_CLASS} svg {
width: 100%;
height: 100%;
border-radius: 2px;
}
`;
document.head.appendChild(styleElement);
logger.debug('Flag icon styles injected');
}
async start() {
logger.log('='.repeat(60));
logger.log('Discord Translator initialized by Tomáš Mark');
logger.log('='.repeat(60));
logger.log('Configuration:');
logger.log(` Debug Enabled: ${CONFIG.DEBUG_ENABLED}`);
logger.log(` Debug Verbose: ${CONFIG.DEBUG_VERBOSE}`);
logger.log(` Debug API: ${CONFIG.DEBUG_API_REQUESTS}`);
logger.log(` Target Language: ${CONFIG.TARGET_LANGUAGE}`);
logger.log(` API Delay: ${CONFIG.API_DELAY_MS}ms`);
logger.log(` Cycle Delay: ${CONFIG.CYCLE_DELAY_MS}ms`);
logger.log(` Debug Styling: ${CONFIG.DEBUG_STYLING ? 'ON (yellow+red)' : 'OFF (subtle gray)'}`);
logger.log(` Manual Translation: ${CONFIG.MANUAL_TRANSLATION ? 'ON (flag icons)' : 'OFF (auto-translate)'}`);
logger.log('='.repeat(60));
// Get initial state from background (but default to ON)
await this.checkState();
// Listen for state changes (for manual toggle if needed)
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
try {
const { type, args } = JSON.parse(message);
if (type === 'stateChanged') {
const [isActive] = args;
this.setActive(isActive);
sendResponse(JSON.stringify({ success: true }));
}
} catch (error) {
logger.error('Error handling message:', error);
}
return true;
});
// Wait for Discord to load messages
await delay(3000);
// Always start processing automatically on Discord
logger.log('🚀 Starting automatic message translation...');
await this.startProcessing();
}
/**
* Check current state from background
*/
async checkState() {
// Check if chrome runtime is still valid
if (!chrome?.runtime?.id) {
logger.error('Chrome runtime not available');
this.isActive = true; // Default to ON for automatic translation
return;
}
try {
const response = await chrome.runtime.sendMessage(JSON.stringify({
type: 'getState',
args: []
}));
const state = JSON.parse(response);
this.isActive = state.isActive ?? true; // Default to ON if undefined
logger.log(`📊 Current state: ${this.isActive ? 'ON (automatic)' : 'OFF'}`);
} catch (error) {
logger.error('Error checking state:', error);
this.isActive = true; // Default to ON on error for automatic translation
}
}
/**
* Set translator active state
*/
setActive(isActive) {
this.isActive = isActive;
logger.log(`🔄 Translator ${isActive ? 'activated' : 'deactivated'}`);
if (isActive) {
this.startProcessing();
} else {
this.stopProcessing();
}
}
/**
* Start processing messages
*/
async startProcessing() {
if (this.processingInterval) {
return; // Already running
}
logger.log('▶️ Starting message processing loop...');
// Process immediately
await this.processMessages();
// Then process periodically
this.processingInterval = setInterval(async () => {
if (this.isActive) {
await this.processMessages();
}
}, CONFIG.CYCLE_DELAY_MS);
}
/**
* Stop processing messages
*/
stopProcessing() {
if (this.processingInterval) {
clearInterval(this.processingInterval);
this.processingInterval = null;
logger.log('⏸️ Message processing stopped');
}
}
/**
* Send stats to background
*/
async sendStats() {
// Check if chrome runtime is still valid
if (!chrome?.runtime?.id) {
logger.debug('Chrome runtime not available, skipping stats update');
return;
}
try {
await chrome.runtime.sendMessage(JSON.stringify({
type: 'updateStats',
args: [{
translated: this.messageTranslations.size,
cached: this.translationCache.size
}]
}));
} catch (error) {
// Background might not be ready or extension was reloaded, ignore
logger.debug('Failed to send stats:', error.message);
}
}
/**
* Get unique ID for a message element
* Uses Discord's message ID from parent container
*/
getMessageId(markupElement) {
// Try to find parent message container with ID
let current = markupElement;
while (current && current !== document.body) {
// Discord message IDs are in format: chat-messages-{channelId}-{messageId}
if (current.id && current.id.includes('chat-messages-')) {
return current.id;
}
// Also check for message content ID
if (current.id && current.id.startsWith('message-content-')) {
return current.id;
}
current = current.parentElement;
}
// Fallback: use text content hash + position
const text = markupElement.textContent.trim();
const position = Array.from(document.querySelectorAll('[class*="markup"]')).indexOf(markupElement);
return `msg-${this.simpleHash(text)}-${position}`;
}
/**
* Simple hash function for text
*/
simpleHash(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return Math.abs(hash).toString(36);
}
/**
* Check if element is visible in viewport
*/
isElementVisible(element) {
const rect = element.getBoundingClientRect();
const windowHeight = window.innerHeight || document.documentElement.clientHeight;
const windowWidth = window.innerWidth || document.documentElement.clientWidth;
// Element is visible if any part is in viewport
const vertInView = (rect.top <= windowHeight) && ((rect.top + rect.height) >= 0);
const horInView = (rect.left <= windowWidth) && ((rect.left + rect.width) >= 0);
return vertInView && horInView;
}
/**
* Get current Discord channel ID from URL or DOM
*/
getCurrentChannelId() {
// Method 1: From URL (most reliable)
const urlMatch = window.location.pathname.match(/\/channels\/(\d+)\/(\d+)/);
if (urlMatch) {
return urlMatch[2]; // Return channel ID (second number)
}
// Method 2: From DOM - look for channel name element
const channelName = document.querySelector('[class*="title"]');
if (channelName) {
return `channel-${this.simpleHash(channelName.textContent)}`;
}
return 'unknown-channel';
}
/**
* Check if channel changed and reset processed messages if needed
*/
checkChannelChange() {
const newChannelId = this.getCurrentChannelId();
if (this.currentChannelId !== newChannelId) {
logger.log(`📺 Channel changed: ${this.currentChannelId || 'none'} → ${newChannelId}`);
// Clear processed messages (but keep translation cache for speed)
this.processedMessages.clear();
this.messageTranslations.clear();
logger.log(`🗑️ Cleared processed messages (${this.translationCache.size} translations in cache)`);
this.currentChannelId = newChannelId;
return true; // Channel changed
}
return false; // Same channel
}
/**
* Add clickable translation icons to messages for manual translation
*/
async addFlagIcons() {
// Use the best selector that finds message content reliably
const allMessages = document.querySelectorAll('[class*="markup"]');
logger.debug(`Found ${allMessages.length} total messages to check for translation icons`);
let flagsAdded = 0;
let flagsSkipped = 0;
for (const messageElement of allMessages) {
try {
const messageId = this.getMessageId(messageElement);
// Skip messages being edited
if (this.isMessageBeingEdited(messageElement)) {
flagsSkipped++;
continue;
}
// Skip if already has flag icon
if (this.processedMessages.has(messageId)) {
flagsSkipped++;
continue;
}
// Check if flag already exists near this message
if (this.hasFlagNearby(messageElement)) {
this.processedMessages.add(messageId);
flagsSkipped++;
continue;
}
// Skip if message is already translated
if (this.messageTranslations.has(messageId)) {
this.processedMessages.add(messageId);
flagsSkipped++;
continue;
}
// Skip embeds and replies (same logic as in processMessages)
if (this.shouldSkipMessage(messageElement)) {
continue;
}
// Skip if no content
const hasContent = messageElement.textContent.trim().length > 0;
if (!hasContent) {
continue;
}
// Only add flag to visible messages
if (!this.isElementVisible(messageElement)) {
continue;
}
// Debug message structure if needed
this.analyzeMessageStructure(messageElement);
// Find a good place to add the translation icon
const flagContainer = this.createFlagIcon(messageElement, messageId);
if (flagContainer) {
flagsAdded++;
this.processedMessages.add(messageId);
}
} catch (error) {
logger.error('Error adding translation icon:', error);
}
}
logger.log(`� Translation icons: ${flagsAdded} added, ${flagsSkipped} skipped`);
}
/**
* Check if message is being edited
*/
isMessageBeingEdited(messageElement) {
// Check if the message element itself contains edit fields
if (messageElement.querySelector('textarea, [contenteditable="true"]')) {
return true;
}
// Check parent message container
let parent = messageElement.parentElement;
let depth = 0;
while (parent && parent !== document.body && depth < 10) {
// Check if this is a message container
if (parent.role === 'article' || parent.classList?.contains('message')) {
// Check if it contains edit fields
if (parent.querySelector('textarea, [contenteditable="true"]')) {
return true;
}
break; // Found message container, stop searching
}
parent = parent.parentElement;
depth++;
}
return false;
}
/**
* Check if message should be skipped (embeds, replies, etc.)
*/
shouldSkipMessage(messageElement) {
const messageId = this.getMessageId(messageElement);
// Skip messages being edited
if (this.isMessageBeingEdited(messageElement)) {
logger.debug(`⏭️ Skipping message being edited [${messageId}]`);
return true;
}
// Skip embeds
let current = messageElement.parentElement;
while (current && current !== document.body) {
const classList = current.classList ? Array.from(current.classList).join(' ') : '';
const className = current.className || '';
if (classList.includes('embed') ||
classList.includes('messageAccessories') ||
classList.includes('container') && classList.includes('embedWrapper') ||
className.includes('embed') ||
current.id?.includes('message-accessories')) {
logger.debug(`⏭️ Skipping embed element [${messageId}]`);
return true;
}
current = current.parentElement;
}
// Skip replies/quotes
let parent = messageElement.parentElement;
while (parent && parent !== document.body) {
const classList = parent.classList ? Array.from(parent.classList).join(' ') : '';
if (classList.includes('repliedMessage') ||
classList.includes('repliedText') ||
parent.id?.startsWith('message-reply-context')) {
logger.debug(`⏭️ Skipping quoted/reply element [${messageId}]`);
return true;
}
parent = parent.parentElement;
}
return false;
}
/**
* Create and insert a clickable Czech flag icon next to a message
*/
createFlagIcon(messageElement, messageId) {
try {
logger.debug(`Creating flag icon for message [${messageId}]`);
const targetParent = messageElement.parentElement;
if (!targetParent) {
logger.debug(`No parent found for message [${messageId}]`);
return null;
}
const flagContainer = this.createFlagElement(messageElement, messageId);
// Simply add the flag after the message element as a sibling
// DO NOT wrap or move the original message element to avoid conflicts with Discord's edit functionality
if (messageElement.nextSibling) {
targetParent.insertBefore(flagContainer, messageElement.nextSibling);
} else {
targetParent.appendChild(flagContainer);
}
logger.debug(`Flag icon placed for [${messageId}]`);
return flagContainer;
} catch (error) {
logger.error(`Error creating flag icon for message [${messageId}]:`, error);
return null;
}
}
/**
* Check if flag can be placed inline with message
*/
canPlaceInline(messageElement) {
const style = window.getComputedStyle(messageElement);
const parent = messageElement.parentElement;
const parentStyle = window.getComputedStyle(parent);
return (
style.display.includes('inline') ||
parentStyle.display === 'flex' ||
parent.tagName.toLowerCase() === 'span'
);
}
/**
* Find the message wrapper/container in Discord's structure
*/
findMessageWrapper(messageElement) {
let current = messageElement.parentElement;
let depth = 0;
const maxDepth = 5; // Prevent infinite loops
while (current && current !== document.body && depth < maxDepth) {
const classList = Array.from(current.classList || []).join(' ');
const className = current.className || '';
// Look for Discord message content patterns
if (
classList.includes('messageContent') ||
classList.includes('markup') && current !== messageElement ||
className.includes('content') ||
current.querySelector('[class*="timestamp"]') // Messages usually have timestamps nearby
) {
logger.debug(`Found wrapper at depth ${depth}:`, current.className);
return current;
}
current = current.parentElement;
depth++;
}
return null;
}
/**
* Check if there's already a flag icon near this message
*/
hasFlagNearby(messageElement) {
// Check siblings
const parent = messageElement.parentElement;
if (!parent) return false;
// Check next/previous siblings
const siblings = Array.from(parent.children);
const messageIndex = siblings.indexOf(messageElement);
// Check 2 siblings in each direction
for (let i = Math.max(0, messageIndex - 2); i <= Math.min(siblings.length - 1, messageIndex + 2); i++) {
const sibling = siblings[i];
if (sibling.classList?.contains(this.FLAG_CONTAINER_CLASS) ||
sibling.querySelector(`.${this.FLAG_CONTAINER_CLASS}`)) {
return true;
}
}
// Check if parent contains a flag
return parent.querySelector(`.${this.FLAG_CONTAINER_CLASS}`) !== null;
}
/**
* Debug helper - analyze message structure for flag placement
*/
analyzeMessageStructure(messageElement) {
if (!CONFIG.DEBUG_ENABLED) return;
const messageId = this.getMessageId(messageElement);
const parent = messageElement.parentElement;
const style = window.getComputedStyle(messageElement);
const parentStyle = window.getComputedStyle(parent);
logger.debug(`Message structure analysis [${messageId}]:`, {
element: messageElement.tagName,
elementClass: messageElement.className,
elementDisplay: style.display,
parent: parent.tagName,
parentClass: parent.className,
parentDisplay: parentStyle.display,
canPlaceInline: this.canPlaceInline(messageElement),
hasWrapper: !!this.findMessageWrapper(messageElement),
hasFlagNearby: this.hasFlagNearby(messageElement)
});
}
/**
* Create the flag icon element
*/
createFlagElement(messageElement, messageId) {
const flagContainer = document.createElement('span');
flagContainer.className = this.FLAG_CONTAINER_CLASS;
const flagIcon = document.createElement('button');
flagIcon.className = this.FLAG_ICON_CLASS;
flagIcon.title = 'Přeložit do češtiny';
flagIcon.setAttribute('data-message-id', messageId);
// Create translation icon SVG (subtle language swap icon)
flagIcon.innerHTML = `
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" fill="currentColor">
<path opacity="0.6" d="M12.87 15.07l-2.54-2.51.03-.03A17.52 17.52 0 0 0 14.07 6H17V4h-7V2H8v2H1v2h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z"/>
</svg>
`;
// Add click handler
flagIcon.addEventListener('click', (event) => {
event.preventDefault();
event.stopPropagation();
this.translateSingleMessage(messageElement, messageId, flagIcon);
});
flagContainer.appendChild(flagIcon);
return flagContainer;
}
/**
* Translate a single message when flag is clicked
*/
async translateSingleMessage(messageElement, messageId, flagIcon) {
try {
logger.log(`🔄 Translating message on demand [${messageId}]`);
// Check if already translated
if (this.messageTranslations.has(messageId)) {
logger.log(`⏭️ Message [${messageId}] already translated - removing icon`);
// Remove the translation icon since message is already translated
this.removeTranslationIcon(flagIcon);
return;
}
// Add loading state
flagIcon.classList.add('translating');
flagIcon.title = 'Překládám...';
// Change to loading icon
flagIcon.innerHTML = `
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" fill="currentColor">
<circle cx="12" cy="12" r="2" opacity="0.8">
<animate attributeName="r" values="2;6;2" dur="1.2s" repeatCount="indefinite"/>
<animate attributeName="opacity" values="0.8;0.2;0.8" dur="1.2s" repeatCount="indefinite"/>
</circle>
<path opacity="0.4" d="M12.87 15.07l-2.54-2.51.03-.03A17.52 17.52 0 0 0 14.07 6H17V4h-7V2H8v2H1v2h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z"/>
</svg>
`;
// Extract text content
const textContent = this.extractCleanText(messageElement);
if (!textContent || textContent.trim().length === 0) {
logger.debug(`⏭️ No text to translate [${messageId}]`);
flagIcon.classList.remove('translating');
flagIcon.title = 'Žádný text k překladu';
// Reset to original translation icon
flagIcon.innerHTML = `
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" fill="currentColor">
<path opacity="0.6" d="M12.87 15.07l-2.54-2.51.03-.03A17.52 17.52 0 0 0 14.07 6H17V4h-7V2H8v2H1v2h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z"/>
</svg>
`;
return;
}
// Check cache first
if (this.translationCache.has(textContent)) {
const cachedTranslation = this.translationCache.get(textContent);
this.displaySingleTranslation(messageElement, cachedTranslation, messageId);
// Remove the translation icon since message is now translated (from cache)
this.removeTranslationIcon(flagIcon);
logger.log(`✅ Message [${messageId}] translated from cache and icon removed`);
return;
}
// Translate using API
const translation = await this.translateText(textContent);
if (translation && translation.trim().length > 0) {
// Cache translation
this.translationCache.set(textContent, translation);
// Display translation
this.displaySingleTranslation(messageElement, translation, messageId);
// Remove the translation icon since message is now translated
this.removeTranslationIcon(flagIcon);
logger.log(`✅ Message [${messageId}] translated successfully and icon removed`);
} else {
throw new Error('Empty translation received');
}
} catch (error) {
logger.error(`❌ Error translating message [${messageId}]:`, error);
flagIcon.classList.remove('translating');
flagIcon.title = 'Chyba při překladu ❌';
// Change to error icon (subtle error with translation icon)
flagIcon.innerHTML = `
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" fill="currentColor">
<path opacity="0.3" d="M12.87 15.07l-2.54-2.51.03-.03A17.52 17.52 0 0 0 14.07 6H17V4h-7V2H8v2H1v2h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7l1.62-4.33L19.12 17h-3.24z"/>
<circle fill="#f44336" cx="18" cy="6" r="4"/>
<path fill="white" d="M16 4.5l4 4M20 4.5l-4 4" stroke="white" stroke-width="1" stroke-linecap="round"/>
</svg>
`;
}
}
/**
* Extract clean text from message element
*/
extractCleanText(element) {
const clone = element.cloneNode(true);
// Remove Discord-specific elements including code blocks
const elementsToRemove = clone.querySelectorAll(
'[class*="repliedMessage"], ' +
'[class*="repliedText"], ' +
'[class*="embed"], ' +
'pre, code, ' +
'img, video, audio'
);
elementsToRemove.forEach(el => el.remove());
let text = clone.textContent || '';
// Remove URLs
text = text.replace(/https?:\/\/[^\s]+/g, '');
return text.trim();
}
/**
* Translate text using the API
*/
async translateText(text) {
try {
const { url, data } = TranslationService.prepareBatchTranslation([text], {
to: CONFIG.TARGET_LANGUAGE,
from: 'auto'
});
logger.api(`🌐 Translating: "${text.substring(0, 50)}..."`);