import _ from './util' ; import uiState from './ui_state' ; import LanguageList from '../languages/languages.json' ; LanguageList . sort ( ( a , b ) => { if ( a . language < b . language ) { return - 1 ; } else if ( a . language > b . language ) { return 1 ; } return 0 ; } ) ; const tuple = < T extends string [ ] > ( ... args ) => args ; const LocaleList = tuple ( ... LanguageList . map ( e => e . code ) ) ; type LocaleType = typeof LocaleList [ number ] ; let currentLocale ; const noTranslateKey = '_tr_' ; interface LoadedLanguageType { [ key ] : any ; } const loadedLanguages = { en : require ( '../languages/en.json' ) , } ; function __tr ( locale , key , args ) { let lookup = loadedLanguages [ locale ] ; const keys = key . split ( '.' ) ; for ( let i = 0 ; i < keys . length ; i ++ ) { const v = keys [ i ] ; if ( v . includes ( '@' ) ) { if ( v . endsWith ( '_@c' ) ) { lookup = lookup [ v ] ; for ( let j = 0 ; j < args . length ; j ++ ) { lookup = lookup . replace ( '${' + j + '}' , args [ j ] ) ; } return lookup ; } else if ( v . endsWith ( '_@mf' ) ) { return _ . template ( lookup [ v ] ) ( args [ 0 ] ) ; } else if ( v . endsWith ( '_@link' ) ) { return translateLink ( lookup [ v ] , args [ 0 ] ) ; } } lookup = lookup [ v ] ; } return lookup ; } function translateLink ( text , link ) { const email = '<a href="mailto:lic@bugeyedmonkeys.com" target="_blank">lic@bugeyedmonkeys.com</a>' ; return text . replace ( '$email{}' , email ) . replace ( '$link{' , `<a href="${ link }" target="_blank">` ) . replace ( '}' , '</a>' ) ; } function translate ( key , ... args ) { if ( key . startsWith ( noTranslateKey ) ) { return key . replace ( noTranslateKey , '' ) ; } if ( key . startsWith ( 'ctrl+' ) ) { return translate ( 'glossary.ctrl' ) + ' + ' + key . charAt ( key . length - 1 ) . toUpperCase ( ) ; } let res ; if ( currentLocale && currentLocale !== 'en' ) { try { res = __tr ( currentLocale , key , args ) ; } catch ( e ) { console . log ( `Locale ${ currentLocale } missing translation key: ${ key }` ) ; res = null ; } } if ( res == null ) { try { res = __tr ( 'en' , key , args ) ; } catch ( e ) { throw 'Invalid translation key lookup: ' + key ; } } if ( res == null ) { throw 'Invalid translation key lookup: ' + key ; } return res ; } function getLocale ( ) { return currentLocale ; } function setLocale ( locale ) { if ( locale == null ) { return ; } currentLocale = locale ; uiState . set ( 'locale' , locale ) ; if ( ! ( loadedLanguages . hasOwnProperty ( locale ) ) ) { loadedLanguages [ locale ] = require ( `../languages/${ locale }.json` ) ; } } function restoreLanguage ( ) { setLocale ( uiState . get ( 'locale' ) ) ; } function noTranslate ( str ) { return noTranslateKey + str ; } restoreLanguage ( ) ; export { translate as tr , getLocale , setLocale , LanguageList , noTranslate , } ;