From 9c9a02f9bf38b5e0ddd8165b0f69e0215b506987 Mon Sep 17 00:00:00 2001 From: Lewis Crichton Date: Mon, 3 Jun 2024 17:39:17 +0100 Subject: [PATCH] feat: plurality --- src/utils/translation.ts | 27 +++++++++++++++++++++------ translations/en/vencord.json | 6 +++++- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/src/utils/translation.ts b/src/utils/translation.ts index 0fbd7314b..807ac1d8d 100644 --- a/src/utils/translation.ts +++ b/src/utils/translation.ts @@ -80,8 +80,10 @@ function getByPath(key: string, object: any) { } } +type Translation = string | ({ [rule in Intl.LDMLPluralRule]?: string } & { other: string; }); + // translation retrieval function -function _t(key: string, bundle: any): string { +function _t(key: string, bundle: any): Translation { const translation = getByPath(key, bundle); if (!translation) { @@ -98,14 +100,27 @@ function _t(key: string, bundle: any): string { /** * Translates a key. Soft-fails and returns the key if it is not valid. * @param key The key to translate. - * @param variables The variables to interpolate into the resultant string. + * @param variables The variables to interpolate into the resultant string. If dealing with plurals, `count` must be set. * @returns A translated string. */ export function $t(key: string, variables?: Record): string { const translation = _t(key, loadedLocale); - if (!variables) return translation; - return format(translation, variables); -} + if (typeof translation !== "string") { + if (!variables || !variables.count) throw new Error(`translation key ${key} is an object (requires plurality?)`); -$t("vencord.hello"); + if (variables.count) { + const pluralTag = new Intl.PluralRules(bestLocale).select(variables.count); + + if (translation[pluralTag]) { + return format(translation[pluralTag]!, variables); + } else { + return format(translation.other, variables); + } + } + } + + if (!variables) return translation as string; + + return format(translation as string, variables); +} diff --git a/translations/en/vencord.json b/translations/en/vencord.json index 0ebe93014..3ba54e915 100644 --- a/translations/en/vencord.json +++ b/translations/en/vencord.json @@ -1,3 +1,7 @@ { - "hello": "Hello {name}!" + "hello": "Hello {name}!", + "plural": { + "one": "One thing.", + "other": "{count} things." + } }