localisation.tsx 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { I18n, i18n } from '@lingui/core';
  2. import { I18nProvider as LinguiI18nProvider } from '@lingui/react';
  3. import React, { useState } from 'react';
  4. import { messages } from '../../locales/en/messages';
  5. let i18nInstance: I18n;
  6. export function getI18n(locale = 'en') {
  7. if (i18nInstance) {
  8. return i18nInstance;
  9. }
  10. i18n.load(locale, messages);
  11. // Browser support for Intl.PluralRules is good and covers what we support in .browserlistrc,
  12. // but because this could potentially be in a the critical path of loading the frontend lets
  13. // be extra careful
  14. // If this isnt loaded, Lingui will log a warning and plurals will not be translated correctly.
  15. const supportsPluralRules = 'Intl' in window && 'PluralRules' in Intl;
  16. if (supportsPluralRules) {
  17. const pluralsOrdinal = new Intl.PluralRules(locale, { type: 'ordinal' });
  18. const pluralsCardinal = new Intl.PluralRules(locale, { type: 'cardinal' });
  19. i18n.loadLocaleData(locale, {
  20. plurals(count: number, ordinal: boolean) {
  21. return (ordinal ? pluralsOrdinal : pluralsCardinal).select(count);
  22. },
  23. });
  24. }
  25. i18n.activate(locale);
  26. i18nInstance = i18n;
  27. return i18nInstance;
  28. }
  29. interface I18nProviderProps {
  30. children: React.ReactNode;
  31. }
  32. export function I18nProvider({ children }: I18nProviderProps) {
  33. const [i18nRef] = useState(() => getI18n());
  34. return <LinguiI18nProvider i18n={i18nRef}>{children}</LinguiI18nProvider>;
  35. }