i18n.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { ReactiveCache } from '/imports/reactiveCache';
  2. import { TAPi18n } from '/imports/i18n';
  3. // We save the user language preference in the user profile, and use that to set
  4. // the language reactively. If the user is not connected we use the language
  5. // information provided by the browser, and default to english.
  6. Meteor.startup(async () => {
  7. let currentUser = ReactiveCache.getCurrentUser();
  8. // If we're still logging in, wait (#4967)
  9. if (!currentUser && Meteor.loggingIn()) {
  10. await new Promise((resolve) => {
  11. Tracker.autorun(() => {
  12. if (!Meteor.loggingIn()) {
  13. resolve();
  14. }
  15. });
  16. });
  17. currentUser = ReactiveCache.getCurrentUser();
  18. }
  19. // Select first available language
  20. const [language] = [
  21. // User profile
  22. currentUser?.profile?.language,
  23. // Browser locale
  24. navigator.languages?.at(0),
  25. navigator.language,
  26. navigator.userLanguage,
  27. ].filter(Boolean);
  28. if (language) {
  29. // Try with potentially complex language tag
  30. if (TAPi18n.isLanguageSupported(language)) {
  31. TAPi18n.setLanguage(language);
  32. } else if (language.includes('-')) {
  33. // Fallback to a general language
  34. const [general] = language.split('-');
  35. if (TAPi18n.isLanguageSupported(general)) {
  36. TAPi18n.setLanguage(general);
  37. }
  38. }
  39. }
  40. });