|
| 1 | +import fs from 'fs'; |
| 2 | +import { parseStringPromise } from 'xml2js'; |
| 3 | + |
| 4 | +class AuraI18n { |
| 5 | + constructor(defaultLang = 'en', localePath = './locales') { |
| 6 | + this.defaultLang = defaultLang; |
| 7 | + this.localePath = localePath; |
| 8 | + this.translations = {}; |
| 9 | + this.modules = ['ui', 'notif', 'tooltip']; // default modules |
| 10 | + this.currentLang = defaultLang; |
| 11 | + } |
| 12 | + |
| 13 | + // Detect user language |
| 14 | + detectLanguage() { |
| 15 | + const lang = navigator.language || navigator.userLanguage || this.defaultLang; |
| 16 | + return lang.split('-')[0]; |
| 17 | + } |
| 18 | + |
| 19 | + // Load a single .xlf file |
| 20 | + async loadXLF(filePath) { |
| 21 | + const xmlData = fs.readFileSync(filePath, 'utf8'); |
| 22 | + const result = await parseStringPromise(xmlData); |
| 23 | + const transUnits = result.xliff.file[0].body[0]['trans-unit']; |
| 24 | + const map = {}; |
| 25 | + transUnits.forEach(unit => { |
| 26 | + const id = unit.$.id; |
| 27 | + map[id] = unit.target[0]; |
| 28 | + }); |
| 29 | + return map; |
| 30 | + } |
| 31 | + |
| 32 | + // Load translations for a module |
| 33 | + async loadModule(moduleName, lang) { |
| 34 | + const filePath = `${this.localePath}/${moduleName}-${lang}.xlf`; |
| 35 | + try { |
| 36 | + const moduleTranslations = await this.loadXLF(filePath); |
| 37 | + this.translations = { ...this.translations, ...moduleTranslations }; |
| 38 | + } catch (err) { |
| 39 | + console.warn(`Failed to load ${moduleName} for ${lang}. Falling back to default.`); |
| 40 | + if (lang !== this.defaultLang) { |
| 41 | + await this.loadModule(moduleName, this.defaultLang); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + // Load all modules for a language |
| 47 | + async loadLanguage(lang) { |
| 48 | + this.translations = {}; |
| 49 | + this.currentLang = lang; |
| 50 | + for (const module of this.modules) { |
| 51 | + await this.loadModule(module, lang); |
| 52 | + } |
| 53 | + this.translateUI(); |
| 54 | + } |
| 55 | + |
| 56 | + // Apply translations to the UI |
| 57 | + translateUI() { |
| 58 | + document.querySelectorAll('[data-i18n]').forEach(el => { |
| 59 | + const key = el.getAttribute('data-i18n'); |
| 60 | + el.textContent = this.translations[key] || el.textContent; |
| 61 | + }); |
| 62 | + } |
| 63 | + |
| 64 | + // Initialize module |
| 65 | + async init(modules = ['ui', 'notif', 'tooltip']) { |
| 66 | + this.modules = modules; |
| 67 | + const lang = this.detectLanguage(); |
| 68 | + await this.loadLanguage(lang); |
| 69 | + } |
| 70 | + |
| 71 | + // Switch language dynamically |
| 72 | + async switchLanguage(lang) { |
| 73 | + await this.loadLanguage(lang); |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +export default AuraI18n; |
0 commit comments