2021-10-07 15:31:49 +02:00
|
|
|
// Copyright: Ankitects Pty Ltd and contributors
|
|
|
|
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|
|
|
|
|
|
|
import type { FluentBundle, FluentVariable } from "@fluent/bundle";
|
2022-02-04 09:36:34 +01:00
|
|
|
import { FluentNumber } from "@fluent/bundle";
|
2021-10-07 15:31:49 +02:00
|
|
|
|
|
|
|
let bundles: FluentBundle[] = [];
|
|
|
|
|
|
|
|
export function setBundles(newBundles: FluentBundle[]): void {
|
|
|
|
bundles = newBundles;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function firstLanguage(): string {
|
|
|
|
return bundles[0].locales[0];
|
|
|
|
}
|
|
|
|
|
|
|
|
function toFluentNumber(num: number): FluentNumber {
|
|
|
|
return new FluentNumber(num, {
|
|
|
|
maximumFractionDigits: 2,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
function formatArgs(
|
2021-10-19 01:06:00 +02:00
|
|
|
args: Record<string, FluentVariable>,
|
2021-10-07 15:31:49 +02:00
|
|
|
): Record<string, FluentVariable> {
|
2021-11-02 03:54:06 +01:00
|
|
|
const entries: [string, FluentVariable][] = Object.entries(args).map(
|
|
|
|
([key, value]) => [
|
2021-10-07 15:31:49 +02:00
|
|
|
key,
|
|
|
|
typeof value === "number" ? toFluentNumber(value) : value,
|
2021-11-02 03:54:06 +01:00
|
|
|
],
|
2021-10-07 15:31:49 +02:00
|
|
|
);
|
2021-11-02 03:54:06 +01:00
|
|
|
const out: Record<string, FluentVariable> = {};
|
|
|
|
for (const [key, value] of entries) {
|
|
|
|
out[key] = value;
|
|
|
|
}
|
|
|
|
return out;
|
2021-10-07 15:31:49 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export function getMessage(
|
|
|
|
key: string,
|
2021-10-19 01:06:00 +02:00
|
|
|
args: Record<string, FluentVariable> = {},
|
2021-10-07 15:31:49 +02:00
|
|
|
): 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;
|
|
|
|
}
|