musescore-downloader/src/i18n/index.ts

61 lines
1.4 KiB
TypeScript
Raw Normal View History

2020-11-05 05:22:15 +00:00
2020-11-24 11:01:02 +00:00
import isNodeJs from 'detect-node'
2020-11-05 05:22:15 +00:00
import en from './en'
2020-11-05 05:45:32 +00:00
import es from './es'
2021-01-02 12:41:46 +00:00
import it from './it'
2021-01-02 15:46:14 +00:00
import zh from './zh'
2020-11-05 05:22:15 +00:00
export interface LOCALE {
'PROCESSING' (): string;
'BTN_ERROR' (): string;
'DEPRECATION_NOTICE' (btnName: string): string;
'DOWNLOAD' (fileType: string): string;
'DOWNLOAD_AUDIO' (fileType: string): string;
'IND_PARTS' (): string;
'IND_PARTS_TOOLTIP' (): string;
2021-01-02 07:44:43 +00:00
'VIEW_IN_LIBRESCORE' (): string;
2021-01-02 15:46:14 +00:00
'FULL_SCORE' (): string;
2020-11-05 05:22:15 +00:00
}
const locales = (<L extends { [n: string]: LOCALE } /** type checking */> (l: L) => Object.freeze(l))({
en,
2020-11-05 05:45:32 +00:00
es,
2021-01-02 12:41:46 +00:00
it,
2021-01-02 15:46:14 +00:00
zh,
2020-11-05 05:22:15 +00:00
})
// detect browser language
const lang = (() => {
2020-11-24 11:01:02 +00:00
let userLangs: readonly string[]
if (!isNodeJs) {
userLangs = navigator.languages
} else {
const env = process.env
const l = env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE || ''
userLangs = [l.slice(0, 2)]
}
2020-11-05 05:22:15 +00:00
const names = Object.keys(locales)
2020-11-24 11:01:02 +00:00
const _lang = userLangs.find(l => {
2020-11-05 05:22:15 +00:00
// find the first occurrence of valid languages
return names.includes(l)
})
return _lang || 'en'
})()
export type STR_KEYS = keyof LOCALE
export type ALL_LOCALES = typeof locales
export type LANGS = keyof ALL_LOCALES
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export default function i18n<K extends STR_KEYS, L extends LANGS = 'en'> (key: K) {
const locale = locales[lang] as ALL_LOCALES[L]
return locale[key]
}