wuchale
Version:
Protobuf-like i18n from normal code
44 lines • 1.27 kB
JavaScript
export const catalogVarName = 'c';
export const defaultPluralsRule = n => n === 1 ? 0 : 1;
export class Runtime {
_ = { c: [], p: defaultPluralsRule };
constructor(module) {
if (!module) { // for fallback
return;
}
this._ = module;
}
/** get composite context */
cx = (id) => {
const ctx = this._.c[id];
if (typeof ctx === 'string') {
return [ctx];
}
if (Array.isArray(ctx)) {
return ctx;
}
if (ctx == null) {
return [`[i18n-404:${id}]`];
}
return [`[i18n-400:${id}(${ctx})]`];
};
/** get translation using composite context */
tx = (ctx, args = [], start = 1) => {
let txt = '';
for (let i = start; i < ctx.length; i++) {
const fragment = ctx[i];
if (typeof fragment === 'string') {
txt += fragment;
}
else { // index of non-text children
txt += args[fragment];
}
}
return txt;
};
/** get translation for plural */
tp = (id) => this._.c[id] ?? [];
/** get translation */
t = (id, args = []) => this.tx(this.cx(id), args, 0);
}
//# sourceMappingURL=runtime.js.map