import dayjs from 'dayjs' ; import 'dayjs/locale/de' ; import 'dayjs/locale/en' ; import 'dayjs/locale/ja' ; import i18next , { TFunctionKeys } from 'i18next' ; import { action , observable } from 'mobx' ; import { initReactI18next } from 'react-i18next' ; import { environment } from '../../environment' ; import { ActionProps , createActionBindings } from '../../lib/ActionBinding' ; import { Store } from '../../lib/Store' ; import { DEFAULT_LOCALE , I18nActions , SUPPORTED_LOCALES } from './index' ; import { SupportedLocale } from './types' ; import { isSupportedLocale } from './utils' ; interface I18nNextResources { [ key ] : object ; } export class I18nStore extends Store { @ observable public locale : SupportedLocale ; private readonly actions : I18nActions ; constructor ( actions , requestedLocale ? ) { super ( ) ; let locale = requestedLocale ; const isLocaleSet = ! ! locale ; const isCorrectLocale = isLocaleSet && isSupportedLocale ( locale ) ; if ( ! isLocaleSet || ( isLocaleSet && ! isCorrectLocale ) ) { if ( environment . IS_CLIENT ) { locale = this . getInitialLocale ( ) ; } else { locale = DEFAULT_LOCALE ; } } Object . assign ( this , { actions , locale , } ) ; this . registerActions ( createActionBindings ( [ [ this . actions . switchLocale , this . switchLocale ] ] ) ) ; } public async start ( ) { super . start ( ) ; const resources = { } ; SUPPORTED_LOCALES . forEach ( ( l ) => { resources [ l ] = { '404' : require ( `./translations/404/${ l }` ) , } ; } ) ; await i18next . use ( initReactI18next ) . init ( { initImmediate : false , interpolation : { escapeValue : false , } , lng : this . locale , ns : [ '404' , 'translation' ] , resources : { [ this . locale ] : Object . assign ( resources [ this . locale ] , { translation : require ( `./translations/${ this . locale }.json` ) , } ) , } , } ) ; dayjs . locale ( this . locale ) ; } param key public translate ( key ) { return i18next . t ( key ) ; } @ action public switchLocale = async ( params ) : Promise < void > => { if ( isSupportedLocale ( params . locale ) ) { this . locale = params . locale ; localStorage . setItem ( 'locale' , params . locale ) ; } } ; private getInitialLocale ( ) { const localSetting = localStorage . getItem ( 'locale' ) ; if ( localSetting && isSupportedLocale ( localSetting ) ) { return localSetting ; } const [ browserSetting ] = navigator . language . split ( '-' ) ; if ( isSupportedLocale ( browserSetting ) ) { return browserSetting ; } return DEFAULT_LOCALE ; } }