feat: plurality

This commit is contained in:
Lewis Crichton 2024-06-03 17:39:17 +01:00
parent c0111169b8
commit 9c9a02f9bf
No known key found for this signature in database
2 changed files with 26 additions and 7 deletions

View file

@ -80,8 +80,10 @@ function getByPath(key: string, object: any) {
} }
} }
type Translation = string | ({ [rule in Intl.LDMLPluralRule]?: string } & { other: string; });
// translation retrieval function // translation retrieval function
function _t(key: string, bundle: any): string { function _t(key: string, bundle: any): Translation {
const translation = getByPath(key, bundle); const translation = getByPath(key, bundle);
if (!translation) { 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. * Translates a key. Soft-fails and returns the key if it is not valid.
* @param key The key to translate. * @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. * @returns A translated string.
*/ */
export function $t(key: string, variables?: Record<string, any>): string { export function $t(key: string, variables?: Record<string, any>): string {
const translation = _t(key, loadedLocale); const translation = _t(key, loadedLocale);
if (!variables) return translation; if (typeof translation !== "string") {
return format(translation, variables); 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);
}

View file

@ -1,3 +1,7 @@
{ {
"hello": "Hello {name}!" "hello": "Hello {name}!",
"plural": {
"one": "One thing.",
"other": "{count} things."
}
} }