initializeLocale.tsx 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 'sentry/locale';
  5. import {Config} from 'sentry/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. * - User's system language code (from request)
  41. * - "en" as default
  42. */
  43. export async function initializeLocale(config: Config) {
  44. let queryString: qs.ParsedQuery = {};
  45. // Parse query string for `lang`
  46. try {
  47. queryString = qs.parse(window.location.search) || {};
  48. } catch {
  49. // ignore if this fails to parse
  50. // this can happen if we have an invalid query string
  51. // e.g. unencoded "%"
  52. }
  53. const queryStringLang = Array.isArray(queryString.lang)
  54. ? queryString.lang[0]
  55. : queryString.lang;
  56. const languageCode =
  57. queryStringLang || config.user?.options?.language || config.languageCode || 'en';
  58. try {
  59. const translations = await getTranslations(languageCode);
  60. setLocale(translations);
  61. // No need to import english
  62. if (languageCode !== 'en') {
  63. await import(`moment/locale/${languageCode}`);
  64. moment.locale(languageCode);
  65. }
  66. } catch (err) {
  67. Sentry.captureException(err);
  68. }
  69. }