2
0
mirror of https://github.com/frappe/books.git synced 2024-09-20 03:29:00 +00:00
books/frappe/utils/translation.js

87 lines
1.6 KiB
JavaScript
Raw Normal View History

2022-02-16 14:10:08 +00:00
import {
getIndexFormat,
getIndexList,
getSnippets,
getWhitespaceSanitized,
} from '../../scripts/helpers';
import { ValueError } from './errors';
class TranslationString {
constructor(...args) {
this.args = args;
}
get s() {
return this.toString();
}
ctx(context) {
this.context = context;
return this;
}
#formatArg(arg) {
2022-02-07 08:41:10 +00:00
return arg ?? '';
}
2022-02-16 14:10:08 +00:00
#translate() {
let indexFormat = getIndexFormat(this.args[0]);
indexFormat = getWhitespaceSanitized(indexFormat);
const translatedIndexFormat =
this.languageMap[indexFormat]?.translation ?? indexFormat;
this.argList = getIndexList(translatedIndexFormat).map(
(i) => this.argList[i]
);
this.strList = getSnippets(translatedIndexFormat);
}
#stitch() {
if (!(this.args[0] instanceof Array)) {
throw new ValueError(
`invalid args passed to TranslationString ${
this.args
} of type ${typeof this.args[0]}`
);
}
2022-02-16 14:10:08 +00:00
this.strList = this.args[0];
this.argList = this.args.slice(1);
if (this.languageMap) {
this.#translate();
}
return this.strList
.map((s, i) => s + this.#formatArg(this.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;
}
2022-02-16 14:10:08 +00:00
export function setLanguageMapOnTranslationString(languageMap) {
TranslationString.prototype.languageMap = languageMap;
}