locale.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { defineStore } from 'pinia'
  3. import { effectScope, ref } from 'vue'
  4. import { useLocalesLazyQuery } from '#shared/graphql/queries/locales.api.ts'
  5. import type {
  6. LocalesQuery,
  7. LocalesQueryVariables,
  8. } from '#shared/graphql/types.ts'
  9. import localeForBrowserLanguage from '#shared/i18n/localeForBrowserLanguage.ts'
  10. import { QueryHandler } from '#shared/server/apollo/handler/index.ts'
  11. import log from '#shared/utils/log.ts'
  12. import { useTranslationsStore } from './translations.ts'
  13. import type { LastArrayElement } from 'type-fest'
  14. type Locale = LastArrayElement<LocalesQuery['locales']>
  15. let localesQuery: QueryHandler<LocalesQuery, LocalesQueryVariables>
  16. const getLocalesQuery = () => {
  17. if (localesQuery) return localesQuery
  18. const scope = effectScope()
  19. scope.run(() => {
  20. localesQuery = new QueryHandler(useLocalesLazyQuery({ onlyActive: true }))
  21. })
  22. return localesQuery
  23. }
  24. export const useLocaleStore = defineStore(
  25. 'locale',
  26. () => {
  27. const localeData = ref<Maybe<Locale>>(null)
  28. const locales = ref<Maybe<LocalesQuery['locales']>>(null)
  29. const loadLocales = async (): Promise<void> => {
  30. if (locales.value) return
  31. const currentQuery = getLocalesQuery()
  32. const { data: result } = await currentQuery.query()
  33. locales.value = result?.locales || null
  34. }
  35. const setLocale = async (locale?: string): Promise<void> => {
  36. await loadLocales()
  37. let newLocaleData
  38. if (locale) {
  39. newLocaleData = locales.value?.find((elem) => {
  40. return elem.locale === locale
  41. })
  42. }
  43. if (!newLocaleData)
  44. newLocaleData = localeForBrowserLanguage(locales.value || [])
  45. log.debug('localeStore.setLocale()', newLocaleData)
  46. // Update the translation store, when the locale is different.
  47. if (localeData.value?.locale !== newLocaleData.locale) {
  48. await useTranslationsStore().load(newLocaleData.locale)
  49. localeData.value = newLocaleData
  50. document.documentElement.setAttribute('dir', newLocaleData.dir)
  51. document.documentElement.setAttribute('lang', newLocaleData.locale)
  52. }
  53. }
  54. return {
  55. locales,
  56. localeData,
  57. setLocale,
  58. loadLocales,
  59. }
  60. },
  61. {
  62. requiresAuth: false,
  63. },
  64. )