i18n.js 1.2 KB

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