2
0
mirror of https://github.com/frappe/books.git synced 2024-11-10 07:40:55 +00:00
books/frappe/utils/translation.js

68 lines
1.3 KiB
JavaScript
Raw Normal View History

import { ValueError } from '../common/errors';
class TranslationString {
constructor(...args) {
this.args = args;
}
get s() {
return this.toString();
}
ctx(context) {
this.context = context;
return this;
}
#translate(segment) {
2022-02-07 08:41:10 +00:00
const startSpace = segment.match(/^\s+/)?.[0] ?? '';
const endSpace = segment.match(/\s+$/)?.[0] ?? '';
segment = segment.replace(/\s+/g, ' ').trim();
// TODO: implement translation backend
2022-02-07 08:41:10 +00:00
// segment = translate(segment)
return startSpace + segment + endSpace;
}
#formatArg(arg) {
2022-02-07 08:41:10 +00:00
return arg ?? '';
}
#stitch() {
if (!(this.args[0] instanceof Array)) {
throw new ValueError(
`invalid args passed to TranslationString ${
this.args
} of type ${typeof this.args[0]}`
);
}
const strList = this.args[0];
const argList = this.args.slice(1);
return strList
.map((s, i) => this.#translate(s) + this.#formatArg(argList[i]))
.join('')
.replace(/\s+/g, ' ')
.trim();
}
toString() {
return this.#stitch();
}
toJSON() {
return this.#stitch();
}
valueOf() {
return this.#stitch();
}
}
export function T(...args) {
return new TranslationString(...args);
}
export function t(...args) {
return new TranslationString(...args).s;
}