-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathi18next-implementation-backend.js
More file actions
784 lines (674 loc) · 24.2 KB
/
Copy pathi18next-implementation-backend.js
File metadata and controls
784 lines (674 loc) · 24.2 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
/**
* La Tanda - i18next Implementation with Backend Language Preferences
* Version: 2.0.0 (Enhanced with backend sync)
*
* Features:
* - Backend-stored language preferences for authenticated users
* - Graceful fallback to localStorage → navigator → default
* - Automatic sync on login/logout events
* - Non-blocking page load (async language detection)
* - Error handling and retry logic
* - Floating language selector UI
*/
// Configuration
const I18N_CONFIG = {
API_BASE_URL: 'https://latanda.online',
ENDPOINTS: {
USER_PROFILE: '/api/user/profile',
USER_PREFERENCES: '/api/users/preferences'
},
STORAGE_KEYS: {
AUTH_TOKEN: 'auth_token', // Primary auth token (matches auth system)
ALT_AUTH_TOKEN: 'authToken', // Alternative token location
LANGUAGE: 'latanda_language'
},
SUPPORTED_LANGUAGES: ['en', 'es', 'pt'],
DEFAULT_LANGUAGE: 'es',
CACHE_TTL: 5 * 60 * 1000, // 5 minutes
REQUEST_TIMEOUT: 5000 // 5 seconds
};
// Language preference cache
let languageCache = {
value: null,
timestamp: null,
isAuthenticated: false
};
/**
* Get authentication token from localStorage
* Checks both primary and alternative token locations
*/
function getAuthToken() {
return localStorage.getItem(I18N_CONFIG.STORAGE_KEYS.AUTH_TOKEN) ||
localStorage.getItem(I18N_CONFIG.STORAGE_KEYS.ALT_AUTH_TOKEN);
}
/**
* Check if user is authenticated
*/
function isAuthenticated() {
const token = getAuthToken();
return !!token;
}
/**
* Make API request with timeout
*/
async function makeAPIRequest(endpoint, options = {}) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), I18N_CONFIG.REQUEST_TIMEOUT);
try {
const response = await fetch(`${I18N_CONFIG.API_BASE_URL}${endpoint}`, {
...options,
signal: controller.signal,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(`API request failed: ${response.status} ${response.statusText}`);
}
return await response.json();
} catch (error) {
clearTimeout(timeoutId);
if (error.name === 'AbortError') {
throw new Error('API request timeout');
}
throw error;
}
}
/**
* Fetch user language preference from backend
* Returns null if unavailable or on error
*/
async function fetchUserLanguageFromBackend() {
const token = getAuthToken();
if (!token) {
console.debug('[i18n] No auth token - skipping backend language fetch');
return null;
}
try {
console.log('[i18n] Fetching user language preference from backend...');
const data = await makeAPIRequest(I18N_CONFIG.ENDPOINTS.USER_PROFILE, {
headers: {
'Authorization': `Bearer ${token}`
}
});
// Handle different response structures
const language = data.user?.preferred_language ||
data.data?.user?.preferred_language ||
data.preferred_language ||
null;
if (language && I18N_CONFIG.SUPPORTED_LANGUAGES.includes(language)) {
console.log(`[i18n] Backend language preference: ${language}`);
// Update cache
languageCache = {
value: language,
timestamp: Date.now(),
isAuthenticated: true
};
return language;
}
console.warn('[i18n] Backend returned invalid or missing language preference');
return null;
} catch (error) {
console.warn('[i18n] Failed to fetch user language preference from backend:', error.message);
return null;
}
}
/**
* Save user language preference to backend
*/
async function saveUserLanguageToBackend(language) {
const token = getAuthToken();
if (!token) {
console.debug('[i18n] No auth token - skipping backend language save');
return false;
}
try {
console.log(`[i18n] Saving language preference to backend: ${language}`);
await makeAPIRequest(I18N_CONFIG.ENDPOINTS.USER_PREFERENCES, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ preferred_language: language })
});
console.log('[i18n] Language preference saved to backend successfully');
// Update cache
languageCache = {
value: language,
timestamp: Date.now(),
isAuthenticated: true
};
return true;
} catch (error) {
console.error('[i18n] Failed to save language preference to backend:', error.message);
return false;
}
}
/**
* Get cached language preference if valid
*/
function getCachedLanguage() {
if (!languageCache.value || !languageCache.timestamp) {
return null;
}
const age = Date.now() - languageCache.timestamp;
if (age > I18N_CONFIG.CACHE_TTL) {
console.debug('[i18n] Language cache expired');
return null;
}
// Verify cache matches auth state
if (languageCache.isAuthenticated !== isAuthenticated()) {
console.debug('[i18n] Language cache invalidated - auth state changed');
return null;
}
console.debug(`[i18n] Using cached language: ${languageCache.value}`);
return languageCache.value;
}
/**
* Invalidate language cache
*/
function invalidateLanguageCache() {
console.debug('[i18n] Language cache invalidated');
languageCache = {
value: null,
timestamp: null,
isAuthenticated: false
};
}
/**
* Get user language preference with fallback chain
* Priority: Cache → Backend → localStorage → navigator → default
*/
async function getUserLanguagePreference() {
// v3.0: Platform is Honduras-only — always Spanish
return 'es';
console.log('[i18n] Detecting user language preference...');
// 1. Check cache first (fastest)
const cachedLang = getCachedLanguage();
if (cachedLang) {
return cachedLang;
}
// 2. If authenticated, try backend
if (isAuthenticated()) {
const backendLang = await fetchUserLanguageFromBackend();
if (backendLang) {
// Sync with localStorage for offline fallback
localStorage.setItem(I18N_CONFIG.STORAGE_KEYS.LANGUAGE, backendLang);
return backendLang;
}
}
// 3. Fallback to localStorage
const storedLang = localStorage.getItem(I18N_CONFIG.STORAGE_KEYS.LANGUAGE);
if (storedLang && I18N_CONFIG.SUPPORTED_LANGUAGES.includes(storedLang)) {
console.log(`[i18n] Using localStorage language: ${storedLang}`);
// Cache for subsequent calls
languageCache = {
value: storedLang,
timestamp: Date.now(),
isAuthenticated: isAuthenticated()
};
return storedLang;
}
// 4. Final fallback to platform default (Honduras = es)
console.log(`[i18n] Using default language: ${I18N_CONFIG.DEFAULT_LANGUAGE}`);
return I18N_CONFIG.DEFAULT_LANGUAGE;
}
/**
* Update language selector button to reflect current language
*/
function updateLanguageSelectorButton(lang) {
const languages = {
'en': { name: 'English', flag: '🇺🇸' },
'es': { name: 'Español', flag: '🇭🇳' },
'pt': { name: 'Português', flag: '🇧🇷' }
};
const toggle = document.getElementById('i18n-toggle');
if (!toggle || !languages[lang]) return;
const flagEl = toggle.querySelector('.i18n-flag');
const codeEl = toggle.querySelector('.i18n-code');
if (flagEl) flagEl.textContent = languages[lang].flag;
if (codeEl) codeEl.textContent = lang.toUpperCase();
document.querySelectorAll('.i18n-option').forEach(option => {
const optLang = option.getAttribute('data-lang');
const checkMark = option.querySelector('.i18n-check');
if (optLang === lang) {
option.classList.add('active');
if (!checkMark) {
option.insertAdjacentHTML('beforeend', '<span class="i18n-check">✓</span>');
}
} else {
option.classList.remove('active');
if (checkMark) checkMark.remove();
}
});
}
/**
* Change language and sync to backend if authenticated
*/
async function changeLanguage(newLanguage) {
console.log(`[i18n] Changing language to: ${newLanguage}`);
// Validate language
if (!I18N_CONFIG.SUPPORTED_LANGUAGES.includes(newLanguage)) {
console.error(`[i18n] Unsupported language: ${newLanguage}`);
return false;
}
try {
// Always update localStorage as backup
localStorage.setItem(I18N_CONFIG.STORAGE_KEYS.LANGUAGE, newLanguage);
// Update backend if authenticated (don't block on this)
if (isAuthenticated()) {
saveUserLanguageToBackend(newLanguage).catch(error => {
console.warn('[i18n] Backend language save failed (non-blocking):', error);
});
} else {
// Update cache for non-authenticated users
languageCache = {
value: newLanguage,
timestamp: Date.now(),
isAuthenticated: false
};
}
// Change language in i18next
if (typeof i18next !== 'undefined') {
await i18next.changeLanguage(newLanguage);
console.log(`[i18n] Language changed successfully to: ${newLanguage}`);
// Retranslate page
translatePage();
// Update language selector button
updateLanguageSelectorButton(newLanguage);
// Dispatch event for components to react
document.dispatchEvent(new CustomEvent('i18n:languageChanged', {
detail: { language: newLanguage }
}));
}
return true;
} catch (error) {
console.error('[i18n] Failed to change language:', error);
return false;
}
}
/**
* Handle login event - fetch and apply user's language preference
*/
async function handleLogin() {
console.log('[i18n] Login detected - fetching user language preference');
// Invalidate cache to force fresh fetch
invalidateLanguageCache();
try {
const userLang = await getUserLanguagePreference();
// Apply language if different from current
if (typeof i18next !== 'undefined' && userLang !== i18next.language) {
await changeLanguage(userLang);
}
} catch (error) {
console.error('[i18n] Error handling login language sync:', error);
}
}
/**
* Handle logout event - fall back to localStorage/browser default
*/
function handleLogout() {
console.log('[i18n] Logout detected - resetting language preference');
// Invalidate cache
invalidateLanguageCache();
// Keep localStorage language but remove backend association
const storedLang = localStorage.getItem(I18N_CONFIG.STORAGE_KEYS.LANGUAGE);
if (storedLang && I18N_CONFIG.SUPPORTED_LANGUAGES.includes(storedLang)) {
console.log(`[i18n] Maintaining localStorage language after logout: ${storedLang}`);
}
}
/**
* Initialize i18next with backend-aware language detection
*/
async function initializeI18next() {
console.log('[i18n] Initializing i18next with backend language detection...');
try {
// Get user language preference (async but non-blocking)
const userLang = await getUserLanguagePreference();
console.log(`[i18n] Initializing with language: ${userLang}`);
// Initialize i18next
await i18next
.use(i18nextHttpBackend)
.use(i18nextBrowserLanguageDetector)
.init({
lng: userLang,
fallbackLng: I18N_CONFIG.DEFAULT_LANGUAGE,
supportedLngs: I18N_CONFIG.SUPPORTED_LANGUAGES,
debug: false,
backend: {
loadPath: '/translations/{{lng}}.json',
crossDomain: false
},
detection: {
// Disable automatic detection since we handle it manually
order: [],
caches: []
},
interpolation: {
escapeValue: false
},
initImmediate: false
});
console.log('✅ [i18n] i18next initialized successfully');
console.log(`🌐 [i18n] Active language: ${i18next.language}`);
// Translate page
translatePage();
// Phase 7: Start observer for dynamic content
startI18nObserver();
// Create language selector
// createLanguageSelector(); // Disabled: language selector now in profile dropdown
// Dispatch ready event
document.dispatchEvent(new CustomEvent('i18n:ready', {
detail: {
language: i18next.language,
isAuthenticated: isAuthenticated()
}
}));
return true;
} catch (error) {
console.error('❌ [i18n] Failed to initialize:', error);
return false;
}
}
/**
* Translate all elements on the page
*/
function translateElement(element) {
const raw = element.getAttribute('data-i18n') || element.getAttribute('data-translate');
if (!raw) return false;
// Support attribute prefixes: [placeholder]key, [aria-label]key
const attrMatch = raw.match(/^\[([^\]]+)\](.+)$/);
if (attrMatch) {
const attr = attrMatch[1];
const key = attrMatch[2];
const translation = i18next.t(key);
if (translation && translation !== key) {
element.setAttribute(attr, translation);
return true;
}
return false;
}
const translation = i18next.t(raw);
if (translation && translation !== raw) {
if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {
if (element.hasAttribute('placeholder')) {
element.placeholder = translation;
} else {
element.value = translation;
}
} else {
element.textContent = translation;
}
return true;
}
return false;
}
function translatePage(root) {
const container = root || document;
const elements = container.querySelectorAll('[data-i18n], [data-translate]');
let totalTranslated = 0;
elements.forEach(el => { if (translateElement(el)) totalTranslated++; });
if (!root) console.log(`[i18n] Translated ${totalTranslated} elements`);
}
// Phase 7: MutationObserver — auto-translate dynamically added DOM nodes
function startI18nObserver() {
if (window._i18nObserver) return;
window._i18nObserver = new MutationObserver(function(mutations) {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (node.nodeType !== 1) continue;
// Translate the node itself if it has data-i18n
if (node.hasAttribute && node.hasAttribute('data-i18n')) {
translateElement(node);
}
// Translate any children with data-i18n
if (node.querySelectorAll) {
const children = node.querySelectorAll('[data-i18n], [data-translate]');
children.forEach(translateElement);
}
}
}
});
window._i18nObserver.observe(document.body, { childList: true, subtree: true });
}
/**
* Create floating language selector UI
*/
function createLanguageSelector() {
// Check if selector already exists
if (document.getElementById('i18next-language-selector')) {
return;
}
// Show selector on all pages (removed page restriction)
const languages = {
'en': { name: 'English', flag: '🇺🇸' },
'es': { name: 'Español', flag: '🇭🇳' },
'pt': { name: 'Português', flag: '🇧🇷' }
};
const currentLang = i18next.language || 'en';
// Create HTML
const selectorHTML = `
<div id="i18next-language-selector" class="i18n-selector">
<button class="i18n-btn" id="i18n-toggle" aria-label="Select Language">
<span class="i18n-flag">${languages[currentLang].flag}</span>
<span class="i18n-code">${currentLang.toUpperCase()}</span>
<svg class="i18n-chevron" width="12" height="12" viewBox="0 0 12 12">
<path d="M2 4L6 8L10 4" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
</svg>
</button>
<div class="i18n-dropdown" id="i18n-dropdown">
${Object.entries(languages).map(([code, lang]) => `
<button class="i18n-option ${code === currentLang ? 'active' : ''}"
data-lang="${code}">
<span class="i18n-flag">${lang.flag}</span>
<span class="i18n-name">${lang.name}</span>
${code === currentLang ? '<span class="i18n-check">✓</span>' : ''}
</button>
`).join('')}
</div>
</div>
<style>
.i18n-selector {
position: relative;
z-index: 100;
font-family: 'Inter', system-ui, sans-serif;
}
.i18n-btn {
display: flex;
align-items: center;
gap: 4px;
background: rgba(0, 0, 0, 0.3);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 6px 10px;
cursor: pointer;
transition: all 0.2s ease;
box-shadow: none;
}
.i18n-btn:hover {
background: rgba(15, 23, 42, 0.95);
border-color: rgba(0, 255, 255, 0.4);
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4);
transform: translateY(-1px);
}
.i18n-flag {
font-size: 16px;
line-height: 1;
}
.i18n-code {
font-size: 12px;
font-weight: 600;
color: #94a3b8;
}
.i18n-chevron {
color: #64748b;
transition: transform 0.2s ease;
}
.i18n-btn.active .i18n-chevron {
transform: rotate(180deg);
}
.i18n-dropdown {
position: absolute;
top: calc(100% + 8px);
right: 0;
min-width: 180px;
background: rgba(15, 23, 42, 0.97);
-webkit-backdrop-filter: blur(20px);
backdrop-filter: blur(20px);
border: 1px solid rgba(0, 255, 255, 0.2);
border-radius: 12px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
opacity: 0;
visibility: hidden;
transform: translateY(-10px);
transition: all 0.2s ease;
overflow: hidden;
}
.i18n-dropdown.show {
opacity: 1;
visibility: visible;
transform: translateY(0);
}
.i18n-option {
display: flex;
align-items: center;
gap: 12px;
width: 100%;
padding: 12px 16px;
background: transparent;
border: none;
cursor: pointer;
transition: all 0.15s ease;
text-align: left;
}
.i18n-option:hover {
background: rgba(0, 255, 255, 0.1);
}
.i18n-option.active {
background: rgba(0, 255, 255, 0.15);
}
.i18n-name {
flex: 1;
font-size: 14px;
font-weight: 500;
color: #e2e8f0;
}
.i18n-check {
color: #00d4aa;
font-weight: 700;
font-size: 16px;
}
@media (max-width: 768px) {
.i18n-selector {
top: 10px;
right: 10px;
}
}
</style>
`;
// Insert into page
// Insert into header-right if available, otherwise body
const headerRight = document.querySelector('.lt-header-right');
if (headerRight) {
headerRight.insertAdjacentHTML('afterbegin', selectorHTML);
} else {
document.body.insertAdjacentHTML('beforeend', selectorHTML);
};
// Setup event listeners
const btn = document.getElementById('i18n-toggle');
const dropdown = document.getElementById('i18n-dropdown');
// Toggle dropdown
btn.addEventListener('click', (e) => {
e.stopPropagation();
dropdown.classList.toggle('show');
btn.classList.toggle('active');
});
// Close dropdown when clicking outside
document.addEventListener('click', () => {
dropdown.classList.remove('show');
btn.classList.remove('active');
});
// Language selection
const options = document.querySelectorAll('.i18n-option');
console.log(`🔍 [i18n] Found ${options.length} language options`);
options.forEach(option => {
option.addEventListener('click', (e) => {
console.log('🖱️ [i18n] Language option clicked!');
e.stopPropagation();
const langCode = option.getAttribute('data-lang');
console.log('🔄 [i18n] Selected language:', langCode);
changeLanguage(langCode);
});
});
console.log('✅ [i18n] Language selector created with event listeners attached');
}
/**
* Setup event listeners for auth state changes
*/
function setupAuthEventListeners() {
// Listen for login events
document.addEventListener('auth:login', handleLogin);
document.addEventListener('user:login', handleLogin);
// Listen for logout events
document.addEventListener('auth:logout', handleLogout);
document.addEventListener('user:logout', handleLogout);
// Listen for token changes in localStorage
window.addEventListener('storage', (e) => {
if (e.key === I18N_CONFIG.STORAGE_KEYS.AUTH_TOKEN ||
e.key === I18N_CONFIG.STORAGE_KEYS.ALT_AUTH_TOKEN) {
if (e.newValue && !e.oldValue) {
// Login detected
handleLogin();
} else if (!e.newValue && e.oldValue) {
// Logout detected
handleLogout();
}
}
});
console.log('[i18n] Auth event listeners registered');
}
/**
* Initialize — called by components-loader.js after i18next CDN is loaded
* Can also self-init if loaded standalone
*/
window._initLaTandaI18n = function() {
if (typeof i18next === 'undefined') {
console.warn('[i18n] i18next not loaded yet — deferring init');
return;
}
setupAuthEventListeners();
initializeI18next();
};
// Self-init if loaded after i18next is already available
if (typeof i18next !== 'undefined') {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', window._initLaTandaI18n);
} else {
window._initLaTandaI18n();
}
}
/**
* Export public API
*/
window.LaTandaI18n = {
changeLanguage,
getCurrentLanguage: () => i18next?.language || I18N_CONFIG.DEFAULT_LANGUAGE,
isReady: () => typeof i18next !== 'undefined' && i18next.isInitialized,
translate: (key, options) => i18next?.t(key, options),
translatePage,
getUserLanguagePreference,
invalidateCache: invalidateLanguageCache,
config: I18N_CONFIG
};
// Global t() shorthand for inline JS usage
// Falls back to the key itself if i18next not loaded yet
window.t = function(key, options) {
if (typeof i18next !== 'undefined' && i18next.isInitialized) {
var result = i18next.t(key, options);
return result !== key ? result : (options && options.defaultValue) || key;
}
return (options && options.defaultValue) || key;
};
console.log('[i18n] LaTandaI18n module loaded');