-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathi18n-setup.ts
64 lines (50 loc) · 2.24 KB
/
i18n-setup.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { createI18n } from 'vue-i18n'
import { Cookie } from '@nimiq/utils'
// import { setLanguage as setVueComponentsLanguage } from '@nimiq/vue3-components'
const DEFAULT_LANGUAGE = 'en'
export const SUPPORTED_LANGUAGES = ['de', 'en', 'es', 'pt', 'nl', 'tr', 'uk', 'fr']
const loadedLanguages: string[] = []
// Note: additional config is applied at compile time in vite.config.ts, see
// https://vue-i18n.intlify.dev/guide/advanced/optimization.html#feature-build-flags
export const i18nRegistration = createI18n({
locale: DEFAULT_LANGUAGE, // set locale (2 letters format: 'en')
fallbackLocale: DEFAULT_LANGUAGE, // fallback locale if no translation found
silentTranslationWarn: true, // disable the "no translation found" warning
})
export const i18n = i18nRegistration.global
if (import.meta.env.PROD)
// trick to not show numbers instead of string before language is loaded
i18n.missing = (locale, key) => /^[0-9]+$/.test(key) ? '' : key
// load and set language
export async function setLanguage(lang: string): Promise<string> {
if (!SUPPORTED_LANGUAGES.includes(lang))
lang = DEFAULT_LANGUAGE
// setVueComponentsLanguage(lang);
if (!loadedLanguages.includes(lang)) {
// For dynamic filename `${lang}.po` specify our folder to please @rollup/plugin-dynamic-import-vars.
const messages = await import(`../i18n/${lang}.po`).then(module => module.default)
i18n.setLocaleMessage(lang, messages)
loadedLanguages.push(lang)
}
Cookie.setCookie('lang', lang, { samesite: 'lax' })
i18n.locale = lang
document.documentElement.setAttribute('lang', lang)
return lang
}
// Return the language stored in the `lang` cookie. Fallback to the browser language
export function detectLanguage(): string {
const langCookie = Cookie.getCookie('lang')
const fallbackLang = window.navigator.language.split('-')[0]
let lang = langCookie || fallbackLang
// If the language is not supported set it to the default one
if (!SUPPORTED_LANGUAGES.includes(lang))
lang = DEFAULT_LANGUAGE
return lang
}
// If the user changed the language in another window/tab then load and enable new language
function onTabFocus() {
const lang = detectLanguage()
if (i18n.locale !== lang)
setLanguage(lang)
}
window.addEventListener('focus', onTabFocus)