2022-01-20 09:03:41 +00:00
|
|
|
import { ValueError } from '../common/errors';
|
|
|
|
|
2022-01-19 08:24:54 +00:00
|
|
|
function stringReplace(str, args) {
|
|
|
|
if (!Array.isArray(args)) {
|
|
|
|
args = [args];
|
|
|
|
}
|
|
|
|
|
|
|
|
if (str == undefined) return str;
|
|
|
|
|
|
|
|
let unkeyed_index = 0;
|
|
|
|
return str.replace(/\{(\w*)\}/g, (match, key) => {
|
|
|
|
if (key === '') {
|
|
|
|
key = unkeyed_index;
|
|
|
|
unkeyed_index++;
|
|
|
|
}
|
|
|
|
if (key == +key) {
|
|
|
|
return args[key] !== undefined ? args[key] : match;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
class TranslationString {
|
|
|
|
constructor(...args) {
|
|
|
|
this.args = args;
|
|
|
|
}
|
|
|
|
|
|
|
|
get s() {
|
|
|
|
return this.toString();
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx(context) {
|
|
|
|
this.context = context;
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
#translate(segment) {
|
2022-01-24 09:25:52 +00:00
|
|
|
segment = segment.replace(/\s+/g, ' ').trim();
|
2022-01-20 09:03:41 +00:00
|
|
|
// TODO: implement translation backend
|
2022-01-19 08:24:54 +00:00
|
|
|
return segment;
|
|
|
|
}
|
|
|
|
|
2022-01-24 09:25:52 +00:00
|
|
|
#formatArg(arg) {
|
|
|
|
if (typeof arg === 'undefined') {
|
|
|
|
return ' ';
|
|
|
|
}
|
|
|
|
|
|
|
|
return ` ${arg} `;
|
|
|
|
}
|
|
|
|
|
2022-01-19 08:24:54 +00:00
|
|
|
#stitch() {
|
2022-01-20 09:03:41 +00:00
|
|
|
if (typeof this.args[0] === 'string') {
|
|
|
|
return stringReplace(this.args[0], this.args.slice(1));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!(this.args[0] instanceof Array)) {
|
|
|
|
throw new ValueError(
|
|
|
|
`invalid args passed to TranslationString ${
|
|
|
|
this.args
|
|
|
|
} of type ${typeof this.args[0]}`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-01-19 08:24:54 +00:00
|
|
|
const strList = this.args[0];
|
|
|
|
const argList = this.args.slice(1);
|
|
|
|
return strList
|
2022-01-24 09:25:52 +00:00
|
|
|
.map((s, i) => this.#translate(s) + this.#formatArg(argList[i]))
|
|
|
|
.join('')
|
|
|
|
.trim();
|
2022-01-19 08:24:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
toString() {
|
|
|
|
return this.#stitch();
|
|
|
|
}
|
|
|
|
|
|
|
|
toJSON() {
|
|
|
|
return this.#stitch();
|
|
|
|
}
|
|
|
|
|
|
|
|
valueOf() {
|
|
|
|
return this.#stitch();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-20 08:18:12 +00:00
|
|
|
export function T(...args) {
|
2022-01-19 08:24:54 +00:00
|
|
|
return new TranslationString(...args);
|
|
|
|
}
|
2022-01-20 09:03:41 +00:00
|
|
|
|
|
|
|
export function t(...args) {
|
|
|
|
return new TranslationString(...args).s;
|
|
|
|
}
|