import { EventManager , Inject , Service } from "@bluelibs/core" ; import * as Polyglot from "node-polyglot" ; import { IXUII18NBundleConfig } from "../../defs" ; import { I18N_CONFIG_TOKEN } from "../../constants" ; import { LocaleChangedEvent } from "../events" ; export type I18NConfig = Record < string , I18NMessages > ; export type I18NMessages = { [ key ] : string | I18NMessages ; } ; @ Service ( ) export class I18NService { public polyglots = new Map < string , Polyglot > ( ) ; constructor ( @ Inject ( I18N_CONFIG_TOKEN ) protected readonly config , protected readonly eventManager ) { if ( config . polyglots ) { config . polyglots . forEach ( ( polyglotConfig ) => { this . polyglots . set ( polyglotConfig . locale , new Polyglot ( polyglotConfig ) ) ; } ) ; } this . setLocale ( config . defaultLocale ) ; } protected activePolyglot : Polyglot = null ; param locale param messages param prefix extend ( locale , messages , prefix ? ) { this . getPolyglot ( locale ) . extend ( messages , prefix ) ; } param configs returns store ( configs ) { if ( ! Array . isArray ( configs ) ) { return this . store ( [ configs ] ) ; } configs . forEach ( ( config ) => { for ( const locale in config ) { this . extend ( locale , config [ locale ] ) ; } } ) ; } param locale setLocale ( locale ) { this . activePolyglot = this . getPolyglot ( locale ) ; this . eventManager . emit ( new LocaleChangedEvent ( { locale } ) ) ; } param string param options returns t = ( string , options ? ) => { return this . activePolyglot . t ( string , options ) ; } ; param locale returns getPolyglot ( locale ) { let polyglot = this . polyglots . get ( locale ) ; if ( ! polyglot ) { polyglot = new Polyglot ( { locale } ) ; this . polyglots . set ( locale , polyglot ) ; } return polyglot ; } }