initializeLocale.tsx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import * as Sentry from '@sentry/react';
  2. import * as moment from 'moment';
  3. import * as qs from 'query-string';
  4. import {DEFAULT_LOCALE_DATA, setLocale} from 'app/locale';
  5. import {Config} from 'app/types';
  6. // zh-cn => zh_CN
  7. function convertToDjangoLocaleFormat(language: string) {
  8. const [left, right] = language.split('-');
  9. return left + (right ? '_' + right.toUpperCase() : '');
  10. }
  11. async function getTranslations(language: string) {
  12. language = convertToDjangoLocaleFormat(language);
  13. // No need to load the english locale
  14. if (language === 'en') {
  15. return DEFAULT_LOCALE_DATA;
  16. }
  17. try {
  18. return await import(`sentry-locale/${language}/LC_MESSAGES/django.po`);
  19. } catch (e) {
  20. Sentry.withScope(scope => {
  21. scope.setLevel(Sentry.Severity.Warning);
  22. scope.setFingerprint(['sentry-locale-not-found']);
  23. scope.setExtra('locale', language);
  24. Sentry.captureException(e);
  25. });
  26. // Default locale if not found
  27. return DEFAULT_LOCALE_DATA;
  28. }
  29. }
  30. /**
  31. * Initialize locale
  32. *
  33. * This *needs* to be initialized as early as possible (e.g. before `app/locale` is used),
  34. * otherwise the rest of the application will fail to load.
  35. *
  36. * Priority:
  37. *
  38. * - URL params (`?lang=en`)
  39. * - User configuration options
  40. * - "en" as default
  41. */
  42. export async function initializeLocale(config: Config) {
  43. let queryString: qs.ParsedQuery = {};
  44. // Parse query string for `lang`
  45. try {
  46. queryString = qs.parse(window.location.search) || {};
  47. } catch {
  48. // ignore if this fails to parse
  49. // this can happen if we have an invalid query string
  50. // e.g. unencoded "%"
  51. }
  52. const queryStringLang = Array.isArray(queryString.lang)
  53. ? queryString.lang[0]
  54. : queryString.lang;
  55. const languageCode = queryStringLang || config.languageCode || 'en';
  56. try {
  57. const translations = await getTranslations(languageCode);
  58. setLocale(translations);
  59. // No need to import english
  60. if (languageCode !== 'en') {
  61. await import(`moment/locale/${languageCode}`);
  62. moment.locale(languageCode);
  63. }
  64. } catch (err) {
  65. Sentry.captureException(err);
  66. }
  67. }