localeForBrowserLanguage.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. // Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. import type { LastArrayElement } from 'type-fest'
  3. import type { LocalesQuery } from '@shared/graphql/types'
  4. import { EnumTextDirection } from '@shared/graphql/types'
  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