import { createI18n, } from 'vue-i18n'; import fetcher from '@cloudron/pankow/fetcher.js'; import { API_ORIGIN } from './constants.js'; const translations = {}; const i18n = createI18n({ locale: 'en', // set locale fallbackLocale: 'en', // set fallback locale messages: translations, warnHtmlInMessage: 'off', // will replace our double {{}} to vue-i18n single brackets messageResolver: function (keys, key) { const message = key.split('.').reduce((o, k) => o && o[k] || null, keys); // if not found return null to fallback to resolving for english if (message === null) return null; // vue-js translation treats @ as linked data, so we have to replace them into a literal variable for now // https://vue-i18n.intlify.dev/guide/essentials/syntax.html#literal-interpolation return message.replaceAll('{{', '{').replaceAll('}}', '}').replaceAll('@', "{'@'}"); } }); // https://vue-i18n.intlify.dev/guide/advanced/lazy.html async function loadLanguage(lang) { try { const result = await fetcher.get(`${API_ORIGIN}/translation/${lang}.json`, { t: import.meta.env.VITE_CACHE_ID }); translations[lang] = result.body; } catch (e) { console.error(`Failed to load language file for ${lang}`, e); } } async function main() { // load at least fallback english await loadLanguage('en'); const locale = window.localStorage.NG_TRANSLATE_LANG_KEY || window.cloudron?.language; if (locale && locale !== 'en') { await loadLanguage(locale); if (i18n.mode === 'legacy') { i18n.global.locale = locale; } else { i18n.global.locale.value = locale; } } return i18n; } async function setLanguage(lang, profile = false) { // only change if we set the language also for the profile or the user has no profile language set if (profile) window.localStorage.NG_TRANSLATE_LANG_KEY = lang; else if (window.localStorage.NG_TRANSLATE_LANG_KEY) return; try { const result = await fetcher.get(`${API_ORIGIN}/translation/${lang}.json`, { t: import.meta.env.VITE_CACHE_ID }); i18n.global.setLocaleMessage(lang, result.body); } catch (e) { console.error(`Failed to load language file for ${lang}`, e); } i18n.global.locale = lang; } export default main; export { setLanguage };