Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

runtime.ts

71 lines2.4 KB

1import { getTranslationsSnapshot } from "gt-react";
2​
3import { getClientSettings, subscribeClientSettings } from "../hooks/useSettings";
4import { initializeI18n } from "./initializeI18n";
5import { DEFAULT_LOCALE, resolveWebLocaleSelection } from "./locales";
6import { setActiveLocale } from "./messages";
7​
8export interface I18nSnapshot {
9 readonly locale: string;
10 readonly formattingLocale: string | undefined;
12​
13const listeners = new Set<() => void>();
14let snapshot: I18nSnapshot = { locale: DEFAULT_LOCALE, formattingLocale: undefined };
15let requestedLocale: ReturnType<typeof resolveWebLocaleSelection> = {
16 catalogLocale: DEFAULT_LOCALE,
17 formattingLocale: undefined,
18};
19​
20function activateLocale(locale: string): void {
21 if (requestedLocale.catalogLocale !== locale) return;
22 const { formattingLocale } = requestedLocale;
23 if (snapshot.locale === locale && snapshot.formattingLocale === formattingLocale) return;
24 snapshot = { locale, formattingLocale };
25 setActiveLocale(locale);
26 for (const listener of listeners) listener();
28​
29function applyLanguageSetting(): void {
30 // Not desktopBridge.getSystemLocale(): that is the regional/time locale, not the UI language.
31 requestedLocale = resolveWebLocaleSelection(
32 getClientSettings().language,
33 navigator.languages,
34 window.desktopBridge?.getPreferredSystemLanguages(),
35 );
36 void whenLocaleReady();
38​
39export function startI18n(): void {
40 initializeI18n();
41 subscribeClientSettings(applyLanguageSetting);
42 window.addEventListener("languagechange", applyLanguageSetting);
43 applyLanguageSetting();
45​
46/**
47 * Resolves once the requested locale's catalog is in GT's cache; immediate for English. GT's
48 * provider then renders that locale without a fallback first, so the splash screen is replaced
49 * by the app and the language, dates and call-time formatting switch together. A catalog that
50 * fails to load still activates: GT renders English and warns.
51 */
52export function whenLocaleReady(): Promise<void> {
53 const locale = requestedLocale.catalogLocale;
54 const activate = () => activateLocale(locale);
55 return getTranslationsSnapshot(locale).then(activate, activate);
57​
58export function subscribeI18n(listener: () => void): () => void {
59 listeners.add(listener);
60 return () => {
61 listeners.delete(listener);
62 };
64​
65export function getI18nSnapshot(): I18nSnapshot {
66 return snapshot;
68​
69export function getFormattingLocale(): string | undefined {
70 return snapshot.formattingLocale;