ldc-gen-game-web/resources/ts/modules/trans.ts

50 lines
1.6 KiB
TypeScript

export default {
data() {
return {
locale: window.__SYSTEM._locale,
};
},
methods: {
/**
* Translate the given key.
*/
__(key: string, replace: Record<PropertyKey, string> = {}): string {
let translation: string,
translationNotFound = true;
try {
translation = key
.split(".")
.reduce<unknown>(
(t, i) => (t as Record<string, unknown>)[i] ?? null,
window.__SYSTEM._translations.php
) as string;
if (translation) {
translationNotFound = false;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (_e) {
translation = key;
}
if (translationNotFound) {
translation = ((window.__SYSTEM._translations.json as Record<string, unknown>)[key] ??
key) as string;
}
const vars = translation.match(/:[0-9A-Za-z_]+/g);
if (vars) {
for (const match of vars) {
try {
translation = translation.replace(
new RegExp(match, "g"),
replace[match.substring(1)]
);
} catch (e) {
console.error("String replace failed ", e);
}
}
}
return translation;
},
},
};