Files
esengine/packages/editor-core/src/Services/LocaleService.ts

144 lines
3.7 KiB
TypeScript
Raw Normal View History

2025-10-14 23:56:54 +08:00
import type { IService } from '@esengine/ecs-framework';
import { Injectable } from '@esengine/ecs-framework';
import { createLogger } from '@esengine/ecs-framework';
const logger = createLogger('LocaleService');
export type Locale = 'en' | 'zh';
export interface Translations {
[key: string]: string | Translations;
}
/**
*
*
*
*/
@Injectable()
export class LocaleService implements IService {
private currentLocale: Locale = 'en';
private translations: Map<Locale, Translations> = new Map();
private changeListeners: Set<(locale: Locale) => void> = new Set();
constructor() {
const savedLocale = this.loadSavedLocale();
if (savedLocale) {
this.currentLocale = savedLocale;
}
}
/**
*
*/
public registerTranslations(locale: Locale, translations: Translations): void {
this.translations.set(locale, translations);
logger.info(`Registered translations for locale: ${locale}`);
}
/**
*
*/
public getCurrentLocale(): Locale {
return this.currentLocale;
}
/**
*
*/
public setLocale(locale: Locale): void {
if (!this.translations.has(locale)) {
logger.warn(`Translations not found for locale: ${locale}`);
return;
}
this.currentLocale = locale;
this.saveLocale(locale);
this.changeListeners.forEach((listener) => listener(locale));
2025-10-14 23:56:54 +08:00
logger.info(`Locale changed to: ${locale}`);
}
/**
*
*
* @param key - "menu.file.save"
* @param fallback - 退
*/
public t(key: string, fallback?: string): string {
const translations = this.translations.get(this.currentLocale);
if (!translations) {
return fallback || key;
}
const value = this.getNestedValue(translations, key);
if (typeof value === 'string') {
return value;
}
return fallback || key;
}
/**
*
*/
public onChange(listener: (locale: Locale) => void): () => void {
this.changeListeners.add(listener);
return () => {
this.changeListeners.delete(listener);
};
}
/**
*
*/
private getNestedValue(obj: Translations, path: string): string | Translations | undefined {
const keys = path.split('.');
let current: any = obj;
for (const key of keys) {
if (current && typeof current === 'object' && key in current) {
current = current[key];
} else {
return undefined;
}
}
return current;
}
/**
* localStorage
*/
private loadSavedLocale(): Locale | null {
try {
const saved = localStorage.getItem('editor-locale');
if (saved === 'en' || saved === 'zh') {
return saved;
}
} catch (error) {
logger.warn('Failed to load saved locale:', error);
}
return null;
}
/**
* localStorage
*/
private saveLocale(locale: Locale): void {
try {
localStorage.setItem('editor-locale', locale);
} catch (error) {
logger.warn('Failed to save locale:', error);
}
}
public dispose(): void {
this.translations.clear();
this.changeListeners.clear();
logger.info('LocaleService disposed');
}
}