localeForBrowserLanguage.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import type { LocalesQuery } from '#shared/graphql/types.ts'
  3. import { EnumTextDirection } from '#shared/graphql/types.ts'
  4. import type { LastArrayElement } from 'type-fest'
  5. const localeForBrowserLanguage = (
  6. locales: LocalesQuery['locales'],
  7. ): LastArrayElement<LocalesQuery['locales']> => {
  8. const userLanguages = window.navigator.languages || [
  9. window.navigator.language,
  10. ]
  11. for (const userLanguage of userLanguages.values()) {
  12. const directMatch = locales.find((elem) => {
  13. return userLanguage.toLowerCase() === elem.locale
  14. })
  15. if (directMatch) return directMatch
  16. const alias = userLanguage.substr(0, 2).toLowerCase()
  17. const aliasMatch = locales.find((elem) => {
  18. return alias === elem.alias
  19. })
  20. if (aliasMatch) return aliasMatch
  21. }
  22. return {
  23. locale: 'en-us',
  24. alias: 'en',
  25. // eslint-disable-next-line zammad/zammad-detect-translatable-string
  26. name: 'English (United States)',
  27. dir: EnumTextDirection.Ltr,
  28. active: true,
  29. }
  30. }
  31. export default localeForBrowserLanguage