|
| 1 | +import { BasePlugin, PluginRegistry, createEmitter } from '@embedpdf/core'; |
| 2 | +import { |
| 3 | + I18nCapability, |
| 4 | + I18nPluginConfig, |
| 5 | + I18nState, |
| 6 | + Locale, |
| 7 | + LocaleCode, |
| 8 | + LocaleChangeEvent, |
| 9 | + TranslationKey, |
| 10 | +} from './types'; |
| 11 | +import { |
| 12 | + I18nAction, |
| 13 | + setLocale as setLocaleAction, |
| 14 | + registerLocale as registerLocaleAction, |
| 15 | +} from './actions'; |
| 16 | + |
| 17 | +export class I18nPlugin extends BasePlugin< |
| 18 | + I18nPluginConfig, |
| 19 | + I18nCapability, |
| 20 | + I18nState, |
| 21 | + I18nAction |
| 22 | +> { |
| 23 | + static readonly id = 'i18n' as const; |
| 24 | + |
| 25 | + private config: I18nPluginConfig; |
| 26 | + private locales = new Map<LocaleCode, Locale>(); |
| 27 | + private readonly localeChange$ = createEmitter<LocaleChangeEvent>(); |
| 28 | + |
| 29 | + constructor(id: string, registry: PluginRegistry, config: I18nPluginConfig) { |
| 30 | + super(id, registry); |
| 31 | + |
| 32 | + this.config = config; |
| 33 | + |
| 34 | + // Register all provided locales |
| 35 | + config.locales.forEach((locale) => { |
| 36 | + this.locales.set(locale.code, locale); |
| 37 | + this.dispatch(registerLocaleAction(locale.code)); |
| 38 | + }); |
| 39 | + |
| 40 | + // Set initial locale |
| 41 | + this.dispatch(setLocaleAction(config.defaultLocale)); |
| 42 | + } |
| 43 | + |
| 44 | + async initialize(): Promise<void> { |
| 45 | + this.logger.info('I18nPlugin', 'Initialize', 'I18n plugin initialized'); |
| 46 | + } |
| 47 | + |
| 48 | + async destroy(): Promise<void> { |
| 49 | + this.localeChange$.clear(); |
| 50 | + super.destroy(); |
| 51 | + } |
| 52 | + |
| 53 | + protected buildCapability(): I18nCapability { |
| 54 | + return { |
| 55 | + t: (key, params) => this.translate(key, params), |
| 56 | + setLocale: (locale) => this.setLocale(locale), |
| 57 | + getLocale: () => this.state.currentLocale, |
| 58 | + getAvailableLocales: () => [...this.state.availableLocales], |
| 59 | + getLocaleInfo: (code) => this.locales.get(code) ?? null, |
| 60 | + registerLocale: (locale) => this.registerLocale(locale), |
| 61 | + hasLocale: (code) => this.locales.has(code), |
| 62 | + onLocaleChange: this.localeChange$.on, |
| 63 | + }; |
| 64 | + } |
| 65 | + |
| 66 | + // ───────────────────────────────────────────────────────── |
| 67 | + // Translation Logic |
| 68 | + // ───────────────────────────────────────────────────────── |
| 69 | + |
| 70 | + private translate(key: TranslationKey, params?: Record<string, string | number>): string { |
| 71 | + const locale = this.locales.get(this.state.currentLocale); |
| 72 | + const fallbackLocale = this.config.fallbackLocale |
| 73 | + ? this.locales.get(this.config.fallbackLocale) |
| 74 | + : null; |
| 75 | + |
| 76 | + // Try current locale |
| 77 | + let value = this.getNestedValue(locale?.translations, key); |
| 78 | + |
| 79 | + // Try fallback locale |
| 80 | + if (!value && fallbackLocale) { |
| 81 | + value = this.getNestedValue(fallbackLocale.translations, key); |
| 82 | + } |
| 83 | + |
| 84 | + // If still not found, return the key itself (with warning) |
| 85 | + if (!value) { |
| 86 | + this.logger.warn('I18nPlugin', 'MissingTranslation', `Translation not found for key: ${key}`); |
| 87 | + return key; |
| 88 | + } |
| 89 | + |
| 90 | + // Interpolate parameters |
| 91 | + return this.interpolate(value, params); |
| 92 | + } |
| 93 | + |
| 94 | + private getNestedValue(obj: any, path: string): string | undefined { |
| 95 | + if (!obj) return undefined; |
| 96 | + |
| 97 | + const parts = path.split('.'); |
| 98 | + let current = obj; |
| 99 | + |
| 100 | + for (const part of parts) { |
| 101 | + if (current === undefined || current === null) return undefined; |
| 102 | + current = current[part]; |
| 103 | + } |
| 104 | + |
| 105 | + return typeof current === 'string' ? current : undefined; |
| 106 | + } |
| 107 | + |
| 108 | + private interpolate(str: string, params?: Record<string, string | number>): string { |
| 109 | + if (!params) return str; |
| 110 | + |
| 111 | + // Replace {key} with params[key] |
| 112 | + return str.replace(/\{(\w+)\}/g, (match, key) => { |
| 113 | + const value = params[key]; |
| 114 | + return value !== undefined ? String(value) : match; |
| 115 | + }); |
| 116 | + } |
| 117 | + |
| 118 | + // ───────────────────────────────────────────────────────── |
| 119 | + // Locale Management |
| 120 | + // ───────────────────────────────────────────────────────── |
| 121 | + |
| 122 | + private setLocale(locale: LocaleCode): void { |
| 123 | + if (!this.locales.has(locale)) { |
| 124 | + this.logger.warn('I18nPlugin', 'LocaleNotFound', `Locale '${locale}' is not registered`); |
| 125 | + return; |
| 126 | + } |
| 127 | + |
| 128 | + const previousLocale = this.state.currentLocale; |
| 129 | + if (previousLocale === locale) return; // No change |
| 130 | + |
| 131 | + this.dispatch(setLocaleAction(locale)); |
| 132 | + |
| 133 | + this.localeChange$.emit({ |
| 134 | + previousLocale, |
| 135 | + currentLocale: locale, |
| 136 | + }); |
| 137 | + |
| 138 | + this.logger.info('I18nPlugin', 'LocaleChanged', `Locale changed to: ${locale}`); |
| 139 | + } |
| 140 | + |
| 141 | + private registerLocale(locale: Locale): void { |
| 142 | + if (this.locales.has(locale.code)) { |
| 143 | + this.logger.warn( |
| 144 | + 'I18nPlugin', |
| 145 | + 'LocaleAlreadyRegistered', |
| 146 | + `Locale '${locale.code}' is already registered`, |
| 147 | + ); |
| 148 | + return; |
| 149 | + } |
| 150 | + |
| 151 | + this.locales.set(locale.code, locale); |
| 152 | + this.dispatch(registerLocaleAction(locale.code)); |
| 153 | + |
| 154 | + this.logger.info('I18nPlugin', 'LocaleRegistered', `Locale registered: ${locale.code}`); |
| 155 | + } |
| 156 | +} |
0 commit comments