useI18n.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. export async function loadLocale(locale, supportedLocales) {
  2. const localeData = supportedLocales[locale]
  3. return typeof localeData === 'function' ? (await localeData()).default : localeData
  4. }
  5. export function useI18n(storage, initialLocale, emitter, supportedLocales) {
  6. const { getStore, setStore } = storage
  7. let translations = {}
  8. let locale = getStore('locale', initialLocale)
  9. const changeLocale = (newLocale, defaultLocale = initialLocale) => {
  10. loadLocale(newLocale, supportedLocales).then((i18n) => {
  11. translations.value = i18n
  12. setStore('locale', newLocale)
  13. locale.value = newLocale
  14. setStore('translations', i18n)
  15. if (Object.values(supportedLocales).length > 1) {
  16. emitter.emit('vf-toast-push', { label: 'The language is set to ' + newLocale })
  17. emitter.emit('vf-language-saved')
  18. }
  19. }).catch(e => {
  20. if (defaultLocale) {
  21. emitter.emit('vf-toast-push', { label: 'The selected locale is not yet supported!', type: 'error' })
  22. changeLocale(defaultLocale, null)
  23. } else {
  24. emitter.emit('vf-toast-push', { label: 'Locale cannot be loaded!', type: 'error' })
  25. }
  26. })
  27. }
  28. if (!getStore('locale') && !supportedLocales.length) {
  29. changeLocale(initialLocale)
  30. } else {
  31. translations.value = getStore('translations')
  32. }
  33. const sprintf = (str, ...argv) => !argv.length ? str : sprintf(str = str.replace('%s', argv.shift()), ...argv)
  34. function t(key, ...params) {
  35. if (translations.value && translations.value.hasOwnProperty(key)) {
  36. return sprintf(translations.value[key], ...params)
  37. }
  38. return sprintf(key, ...params)
  39. }
  40. return { t, changeLocale, locale }
  41. }