feat: add i18n support for Italian, Spanish, Portuguese and Russian
This commit is contained in:
48
js/i18n.js
48
js/i18n.js
@@ -5,9 +5,28 @@
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {'de' | 'en' | 'fr'} Locale
|
||||
* @typedef {'de' | 'en' | 'fr' | 'it' | 'es' | 'pt' | 'ru'} Locale
|
||||
*/
|
||||
|
||||
/**
|
||||
* Mapping from short locale codes (used in frontend) to
|
||||
* Directus long locale codes (used in categories_translations etc.)
|
||||
* @type {Object<Locale, string>}
|
||||
*/
|
||||
const LOCALE_TO_DIRECTUS = {
|
||||
de: 'de-DE',
|
||||
en: 'en-US',
|
||||
fr: 'fr-FR',
|
||||
it: 'it-IT',
|
||||
es: 'es-ES',
|
||||
pt: 'pt-BR',
|
||||
ru: 'ru-RU'
|
||||
}
|
||||
|
||||
const DIRECTUS_TO_LOCALE = Object.fromEntries(
|
||||
Object.entries(LOCALE_TO_DIRECTUS).map(([k, v]) => [v, k])
|
||||
)
|
||||
|
||||
/**
|
||||
* I18n Service class
|
||||
* @class
|
||||
@@ -21,7 +40,7 @@ class I18n {
|
||||
/** @type {Locale} */
|
||||
this.fallbackLocale = 'de'
|
||||
/** @type {Locale[]} */
|
||||
this.supportedLocales = ['de', 'en', 'fr']
|
||||
this.supportedLocales = ['de', 'en', 'fr', 'it', 'es', 'pt', 'ru']
|
||||
/** @type {Set<Function>} */
|
||||
this.subscribers = new Set()
|
||||
/** @type {boolean} */
|
||||
@@ -198,12 +217,35 @@ class I18n {
|
||||
const names = {
|
||||
de: 'Deutsch',
|
||||
en: 'English',
|
||||
fr: 'Français'
|
||||
fr: 'Français',
|
||||
it: 'Italiano',
|
||||
es: 'Español',
|
||||
pt: 'Português',
|
||||
ru: 'Русский'
|
||||
}
|
||||
return names[locale] || locale
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Directus language code for a frontend locale
|
||||
* @param {Locale} [locale] - Frontend locale (defaults to current)
|
||||
* @returns {string} Directus language code (e.g. 'de-DE')
|
||||
*/
|
||||
getDirectusLocale(locale) {
|
||||
return LOCALE_TO_DIRECTUS[locale || this.currentLocale] || LOCALE_TO_DIRECTUS[this.fallbackLocale]
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the frontend locale for a Directus language code
|
||||
* @param {string} directusCode - Directus code (e.g. 'it-IT')
|
||||
* @returns {Locale}
|
||||
*/
|
||||
fromDirectusLocale(directusCode) {
|
||||
return DIRECTUS_TO_LOCALE[directusCode] || directusCode?.split('-')[0] || this.fallbackLocale
|
||||
}
|
||||
}
|
||||
|
||||
export const i18n = new I18n()
|
||||
export const t = (key, params) => i18n.t(key, params)
|
||||
export const getCurrentLanguage = () => i18n.getLocale()
|
||||
export { LOCALE_TO_DIRECTUS, DIRECTUS_TO_LOCALE }
|
||||
|
||||
Reference in New Issue
Block a user