This repository has been archived on 2024-02-08. You can view files and clone it, but cannot push or open issues or pull requests.
frontend/src/i18n/index.ts

78 lines
2.0 KiB
TypeScript
Raw Normal View History

import {createI18n} from 'vue-i18n'
import langEN from './lang/en.json'
2022-10-10 19:44:59 +00:00
export const SUPPORTED_LOCALES = {
'en': 'English',
'de-DE': 'Deutsch',
'de-swiss': 'Schwizertütsch',
'ru-RU': 'Русский',
'fr-FR': 'Français',
'vi-VN': 'Tiếng Việt',
'it-IT': 'Italiano',
2021-10-27 16:27:47 +00:00
'cs-CZ': 'Čeština',
'pl-PL': 'Polski',
'nl-NL': 'Nederlands',
'pt-PT': 'Português',
'zh-CN': '中文',
2022-12-22 12:05:42 +00:00
'no-NO': 'Norsk Bokmål',
2023-06-21 18:12:56 +00:00
'es-ES': 'Español',
2023-06-21 18:14:21 +00:00
'da-DK': 'Dansk',
'ja-JP': '日本語',
'hu-HU': 'Magyar',
'ar-SA': 'اَلْعَرَبِيَّةُ',
'sl-SI': 'Slovenščina',
// IMPORTANT: Also add new languages to useDayjsLanguageSync
2022-10-17 11:14:07 +00:00
} as const
2022-10-10 19:44:59 +00:00
export type SupportedLocale = keyof typeof SUPPORTED_LOCALES
export const DEFAULT_LANGUAGE: SupportedLocale= 'en'
export type ISOLanguage = string
2022-10-17 11:14:07 +00:00
// we load all messages async
2022-10-10 19:44:59 +00:00
export const i18n = createI18n({
fallbackLocale: DEFAULT_LANGUAGE,
legacy: false,
2022-10-10 19:44:59 +00:00
messages: {
2022-10-17 11:14:07 +00:00
[DEFAULT_LANGUAGE]: langEN,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
2022-10-10 19:44:59 +00:00
} as Record<SupportedLocale, any>,
})
2023-06-12 16:01:56 +00:00
export async function setLanguage(lang: SupportedLocale): Promise<SupportedLocale | undefined> {
if (!lang) {
2022-10-10 19:44:59 +00:00
throw new Error()
}
// do not change language to the current one
if (i18n.global.locale.value === lang) {
return
}
// If the language hasn't been loaded yet
if (!i18n.global.availableLocales.includes(lang)) {
try {
const messages = await import(`./lang/${lang}.json`)
i18n.global.setLocaleMessage(lang, messages.default)
} catch (e) {
console.error(`Failed to load language ${lang}:`, e)
return setLanguage(getBrowserLanguage())
}
}
i18n.global.locale.value = lang
document.documentElement.lang = lang
return lang
}
2023-06-12 16:01:56 +00:00
export function getBrowserLanguage(): SupportedLocale {
2022-10-26 13:42:44 +00:00
const browserLanguage = navigator.language
2022-10-17 11:14:07 +00:00
const language = Object.keys(SUPPORTED_LOCALES).find(langKey => {
2022-10-10 19:44:59 +00:00
return langKey === browserLanguage || langKey.startsWith(browserLanguage + '-')
2022-10-17 11:14:07 +00:00
}) as SupportedLocale | undefined
2022-10-10 19:44:59 +00:00
return language || DEFAULT_LANGUAGE
}