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

95 lines
2.0 KiB
TypeScript
Raw Normal View History

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