load_locale.ts 1.1 KB

123456789101112131415161718192021222324252627282930
  1. import { Semaphore } from 'async-mutex';
  2. import type { LocaleData } from './global_locale';
  3. import { isLocaleLoaded, setLocale } from './global_locale';
  4. const localeLoadingSemaphore = new Semaphore(1);
  5. export async function loadLocale() {
  6. // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- we want to match empty strings
  7. const locale = document.querySelector<HTMLElement>('html')?.lang || 'en';
  8. // We use a Semaphore here so only one thing can try to load the locales at
  9. // the same time. If one tries to do it while its in progress, it will wait
  10. // for the initial load to finish before it is resumed (and will see that locale
  11. // data is already loaded)
  12. await localeLoadingSemaphore.runExclusive(async () => {
  13. // if the locale is already set, then do nothing
  14. if (isLocaleLoaded()) return;
  15. const localeData = (await import(
  16. /* webpackMode: "lazy" */
  17. /* webpackChunkName: "locale/[request]" */
  18. /* webpackInclude: /\.json$/ */
  19. /* webpackPreload: true */
  20. `mastodon/locales/${locale}.json`
  21. )) as LocaleData['messages'];
  22. setLocale({ messages: localeData, locale });
  23. });
  24. }