|
| 1 | +import { autoinject } from 'aurelia-framework'; |
| 2 | +import { I18N } from 'aurelia-i18n'; |
| 3 | +import { BindingSignaler } from 'aurelia-templating-resources'; |
| 4 | +import * as moment from 'moment/moment'; |
| 5 | + |
| 6 | +import { Logger, LogManager} from './logger.service'; |
| 7 | + |
| 8 | +export const LocaleChangedSignal: string = 'locale:changed'; |
| 9 | + |
| 10 | +@autoinject |
| 11 | +export class LanguageService { |
| 12 | + |
| 13 | + private logger: Logger; |
| 14 | + |
| 15 | + constructor( |
| 16 | + private i18n: I18N, |
| 17 | + private bindingSignaler: BindingSignaler |
| 18 | + ) { |
| 19 | + this.logger = LogManager.getLogger('LanguageService'); |
| 20 | + this.logger.debug('initialized'); |
| 21 | + this.logger.debug(`current locale: ${this.getCurrentLocale()}`); |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * Return the language: en, de, fr, it |
| 26 | + */ |
| 27 | + public getCurrentLang(): string { |
| 28 | + return this.getCurrentLocale().split('-')[0]; |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Get the list of all supported locales from our translations, |
| 33 | + * then get the current browser locale, if we have a translation |
| 34 | + * returns the language or fallback to default -> en |
| 35 | + */ |
| 36 | + public getCurrentUILanguage(): string { |
| 37 | + const supported = this.getSupportedLanguages(); |
| 38 | + const currentLanguage = this.getCurrentLang(); |
| 39 | + return supported.indexOf(currentLanguage) > -1 ? currentLanguage : 'en'; |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Get a list of current configured languages which has a translation. |
| 44 | + */ |
| 45 | + public getSupportedLanguages(): string[] { |
| 46 | + const languages = Object.keys(this.i18n.i18next.options.fallbackLng) |
| 47 | + .map(key => this.i18n.i18next.options.fallbackLng[key][0].split('-')[0]) |
| 48 | + .filter((value, index, array) => { |
| 49 | + return array.indexOf (value) === index; |
| 50 | + }); |
| 51 | + return languages; |
| 52 | + } |
| 53 | + |
| 54 | + public getCurrentLocale(): string { |
| 55 | + return this.i18n.getLocale(); |
| 56 | + } |
| 57 | + |
| 58 | + public setLocale(locale: string): void { |
| 59 | + moment.locale(locale); |
| 60 | + this.i18n.setLocale(locale); |
| 61 | + this.bindingSignaler.signal(LocaleChangedSignal); |
| 62 | + this.logger.debug(`changed locale to: ${locale}`); |
| 63 | + } |
| 64 | +} |
0 commit comments