~cytrogen/masto-fe

masto-fe/app/javascript/mastodon/locales/intl_provider.tsx -rw-r--r-- 1.4 KiB
f8dc013b — Cytrogen [feature] Add language selector to local settings 6 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { useEffect, useState } from "react";

import { IntlProvider as BaseIntlProvider } from "react-intl";

import { getLocale, isLocaleLoaded } from "./global_locale";
import { loadLocale } from "./load_locale";

function onProviderError(error: unknown) {
  // Silent the error, like upstream does
  if (process.env.NODE_ENV === "production") {
    return;
  }

  // This browser does not advertise Intl support for this locale, we only print a warning
  // As-per the spec, the browser should select the best matching locale
  if (
    error &&
    typeof error === "object" &&
    error instanceof Error &&
    error.message.match("MISSING_DATA")
  ) {
    console.warn(error.message);
  }

  console.error(error);
}

export const IntlProvider: React.FC<
  Omit<React.ComponentProps<typeof BaseIntlProvider>, "locale" | "messages">
> = ({ children, ...props }) => {
  const [localeLoaded, setLocaleLoaded] = useState(false);

  useEffect(() => {
    async function loadLocaleData() {
      if (!isLocaleLoaded()) {
        await loadLocale();
      }

      setLocaleLoaded(true);
    }
    void loadLocaleData();
  }, []);

  if (!localeLoaded) {
    return null;
  }

  const { locale, messages } = getLocale();

  return (
    <BaseIntlProvider
      locale={locale}
      messages={messages}
      onError={onProviderError}
      textComponent='span'
      {...props}
    >
      {children}
    </BaseIntlProvider>
  );
};