~cytrogen/masto-fe

ref: 86c9c5afa045b9e2cfa41c15db63ad97d58954c1 masto-fe/app/javascript/mastodon/locales/load_locale.ts -rw-r--r-- 1.1 KiB
86c9c5af — Claire Merge commit '40ba6e119b7457161fd43b449875d0fb9d473c1a' into glitch-soc/merge-upstream 2 years 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
import { Semaphore } from 'async-mutex';

import type { LocaleData } from './global_locale';
import { isLocaleLoaded, setLocale } from './global_locale';

const localeLoadingSemaphore = new Semaphore(1);

export async function loadLocale() {
  // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- we want to match empty strings
  const locale = document.querySelector<HTMLElement>('html')?.lang || 'en';

  // We use a Semaphore here so only one thing can try to load the locales at
  // the same time. If one tries to do it while its in progress, it will wait
  // for the initial load to finish before it is resumed (and will see that locale
  // data is already loaded)
  await localeLoadingSemaphore.runExclusive(async () => {
    // if the locale is already set, then do nothing
    if (isLocaleLoaded()) return;

    const localeData = (await import(
      /* webpackMode: "lazy" */
      /* webpackChunkName: "locales/vanilla/[request]" */
      /* webpackInclude: /\.json$/ */
      /* webpackPreload: true */
      `mastodon/locales/${locale}.json`
    )) as LocaleData['messages'];

    setLocale({ messages: localeData, locale });
  });
}