locale.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { ref } from 'vue'
  3. import { defineStore } from 'pinia'
  4. import type { LastArrayElement } from 'type-fest'
  5. import log from '#shared/utils/log.ts'
  6. import localeForBrowserLanguage from '#shared/i18n/localeForBrowserLanguage.ts'
  7. import getAvailableLocales from '#shared/i18n/availableLocales.ts'
  8. import type { LocalesQuery } from '#shared/graphql/types.ts'
  9. import { useTranslationsStore } from './translations.ts'
  10. type Locale = LastArrayElement<LocalesQuery['locales']>
  11. export const useLocaleStore = defineStore(
  12. 'locale',
  13. () => {
  14. const localeData = ref<Maybe<Locale>>(null)
  15. const locales = ref<Maybe<LocalesQuery['locales']>>(null)
  16. const loadLocales = async (): Promise<void> => {
  17. if (locales.value) return
  18. locales.value = await getAvailableLocales()
  19. }
  20. const setLocale = async (locale?: string): Promise<void> => {
  21. await loadLocales()
  22. let newLocaleData
  23. if (locale) {
  24. newLocaleData = locales.value?.find((elem) => {
  25. return elem.locale === locale
  26. })
  27. }
  28. if (!newLocaleData)
  29. newLocaleData = localeForBrowserLanguage(locales.value || [])
  30. log.debug('localeStore.setLocale()', newLocaleData)
  31. // Update the translation store, when the locale is different.
  32. if (localeData.value?.locale !== newLocaleData.locale) {
  33. await useTranslationsStore().load(newLocaleData.locale)
  34. localeData.value = newLocaleData
  35. document.documentElement.setAttribute('dir', newLocaleData.dir)
  36. document.documentElement.setAttribute('lang', newLocaleData.locale)
  37. }
  38. }
  39. return {
  40. locales,
  41. localeData,
  42. setLocale,
  43. loadLocales,
  44. }
  45. },
  46. {
  47. requiresAuth: false,
  48. },
  49. )