From d977ddc7f4a059ca5194a741cdd62dbe1d23b8e4 Mon Sep 17 00:00:00 2001 From: Lewis Crichton Date: Fri, 22 Dec 2023 16:29:20 +0000 Subject: [PATCH] perf: use global caches so we only have one subscription --- src/utils/translation.ts | 39 +++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/src/utils/translation.ts b/src/utils/translation.ts index e9d9fb3bd..e8523b382 100644 --- a/src/utils/translation.ts +++ b/src/utils/translation.ts @@ -16,6 +16,11 @@ import { Logger } from "./Logger"; // same color as pontoon's logo const logger = new Logger("Translations", "#7bc876"); +let subscribed = false; + +let bundleCache: Record = {}; +let messageCache: Record> = {}; + /** * Gets a function that translates strings. * @param context The context to use for translation (e.g., `vencord`). @@ -24,20 +29,22 @@ const logger = new Logger("Translations", "#7bc876"); export function getTranslations(context: string) { if (!translations[context]) throw new Error(`No translations for ${context}`); - let localeCache: FluentBundle[] = []; - let messageCache: Record = {}; + if (!subscribed) { + let lastLocale = i18n.getLocale(); - let lastLocale = i18n.getLocale(); - FluxDispatcher.subscribe("USER_SETTINGS_PROTO_UPDATE", ({ settings }) => { - if (settings.proto.localization.locale.value !== lastLocale) { - // locale was updated, clear our caches + FluxDispatcher.subscribe("USER_SETTINGS_PROTO_UPDATE", ({ settings }) => { + if (settings.proto.localization.locale.value !== lastLocale) { + // locale was updated, clear our caches - lastLocale = settings.proto.localization.locale.value; + lastLocale = settings.proto.localization.locale.value; - localeCache = []; - messageCache = {}; - } - }); + bundleCache = {}; + messageCache = {}; + } + }); + + subscribed = true; + } /** * Translates a key. Soft-fails and returns a fallback error string if the key could not be loaded. @@ -46,12 +53,16 @@ export function getTranslations(context: string) { * @returns A translated string. */ return function t(key: string, variables?: Record): string { + const msgCache = messageCache[context] ??= {}; + // adding the caching here speeds up retrieving translations for this key later - if (messageCache[key]) { - const bundle = messageCache[key]; + if (msgCache[key]) { + const bundle = msgCache[key]; return bundle.formatPattern(bundle.getMessage(key)!.value!, variables); } + const localeCache = bundleCache[context] ??= []; + // we've never loaded this context's translations if (localeCache.length === 0) { const availableLocales = Object.keys(translations[context]); @@ -85,7 +96,7 @@ export function getTranslations(context: string) { const message = bundle.getMessage(key); if (message?.value) { - messageCache[key] = bundle; + msgCache[key] = bundle; return bundle.formatPattern(message.value, variables); }