70 lines
1.6 KiB
TypeScript
70 lines
1.6 KiB
TypeScript
function locale() {
|
|
return {locale: globalThis.__SYSTEM._locale,};
|
|
}
|
|
/**
|
|
* Translate the given key.
|
|
*/
|
|
function __(key: string, replace: Record<PropertyKey, string | number> = {}): string {
|
|
let translation: string,
|
|
translationNotFound = true;
|
|
|
|
try {
|
|
translation = key
|
|
.split(".")
|
|
.reduce(
|
|
(t, i) => t[i as never] ?? null,
|
|
globalThis.__SYSTEM._translations.php
|
|
) as string;
|
|
if (translation) {
|
|
translationNotFound = false;
|
|
}
|
|
} catch {
|
|
translation = key;
|
|
}
|
|
|
|
if (translationNotFound) {
|
|
translation = (globalThis.__SYSTEM._translations.json[key as never] ?? key) as string;
|
|
}
|
|
const vars = translation.match(/:\w+/g);
|
|
if (vars) {
|
|
for (const match of vars) {
|
|
try {
|
|
translation = translation.replaceAll(
|
|
match,
|
|
String(replace[match.substring(1)] ?? match)
|
|
);
|
|
} catch (e) {
|
|
console.error("String replace failed ", e);
|
|
}
|
|
}
|
|
}
|
|
return translation;
|
|
}
|
|
|
|
function trans(key: string, replace: Record<PropertyKey, string | number> = {}): string{
|
|
return __(key, replace);
|
|
}
|
|
|
|
/**
|
|
* Translate a pluralized key based on count.
|
|
*/
|
|
function trans_choice(key: string, count: number, replace: Record<PropertyKey, string | number> = {}): string {
|
|
const translation = __(key, { ...replace, count, });
|
|
const segments = translation.split("|");
|
|
|
|
if (segments.length <= 1) {
|
|
return translation;
|
|
}
|
|
|
|
if (count <= 1) {
|
|
return __(segments[0], { ...replace, count, });
|
|
}
|
|
|
|
return __(segments.at(-1) ?? translation, { ...replace, count, });
|
|
}
|
|
|
|
|
|
export {
|
|
__, locale, trans,
|
|
trans_choice
|
|
};
|