Anki/ts/lib/i18n/bundles.ts
Henrik Giesel 8a839a844e Move lib/i18n/translate to lib/translate
* This restores tree shaking
2021-10-04 02:34:03 +02:00

46 lines
1.2 KiB
TypeScript

// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import { FluentNumber } from "@fluent/bundle";
import type { FluentBundle, FluentVariable } from "@fluent/bundle";
let bundles: FluentBundle[] = [];
export function setBundles(...newBundles: FluentBundle[]): void {
bundles.splice(0, bundles.length, ...newBundles);
}
export function firstLanguage(): string {
return bundles[0].locales[0];
}
function toFluentNumber(num: number): FluentNumber {
return new FluentNumber(num, {
maximumFractionDigits: 2,
});
}
function formatArgs(
args: Record<string, FluentVariable>
): Record<string, FluentVariable> {
return Object.fromEntries(
Object.entries(args).map(([key, value]) => [
key,
typeof value === "number" ? toFluentNumber(value) : value,
])
);
}
export function getMessage(
key: string,
args: Record<string, FluentVariable> = {}
): string | null {
for (const bundle of bundles) {
const msg = bundle.getMessage(key);
if (msg && msg.value) {
return bundle.formatPattern(msg.value, formatArgs(args));
}
}
return null;
}