@owja/i18n
Version:
lightweight internationalization library for javascript
3 lines (2 loc) • 2.73 kB
JavaScript
function t(t){let i="string"==typeof t?new Intl.Locale(t):t;const s=!!i.script;return i=i.maximize(),i=new Intl.Locale(t.toString(),{script:s?i.script:void 0,region:i.region,language:i.language}),i.region&&i.language||console.warn(`[/i18n] locale "${i.toString()}" incomplete and can result in unexpected errors`),i}function i(t,s){let n={};for(const h of Object.keys(t||{})){const e=t[h];if("string"!=typeof e&&"object"!=typeof e)continue;const o=`${s}.${h}`;if("string"==typeof e){if(/[^a-zA-Z0-9_\-]/.test(h))throw`only a-Z, 0-9, minus sign and underscore allowed: "${h}"`;n[o]=e}else{if(/[^a-zA-Z0-9\-]/.test(h))throw`only a-Z, minus sign and 0-9 allowed: "${h}"`;n={...n,...i(e,o)}}}return n}function s(t){return new Intl.Locale(t).toString()}class n{constructor(i={}){this.i={default:"en-US",fallback:"en"},this.h=[],this.o={},this.l={},this.u=void 0,this.$=void 0,this.g=void 0,this.i={...this.i,...i},this.u=t(this.i.default),this.$=new Intl.PluralRules(this.long()),this.g=new Intl.PluralRules(this.i.fallback),this.t=this.t.bind(this)}t(t,i={}){void 0===i.replace&&(i.replace={}),"number"==typeof i.count&&(i.replace.count=i.count.toString());let s="",n=!1;const h=this.p(t,i,!1);if([this.long(),this.short()].some(t=>h.some(i=>!!(s=this.o[`${t}.${i}`])))||(n=this.p(t,i,!0).some(t=>!!(s=this.o[`${this.i.fallback}.${t}`]))),!s)return t;for(const t in i.replace)s=s.replace(new RegExp("{{"+t+"}}".replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&"),"g"),i.replace[t].toString());return(this.l[this.long()]||[]).concat(this.l[this.short()]||[]).concat(this.l.global||[]).forEach(t=>{s=t(s,i,n?this.i.fallback:this.long(),this)||s}),s}language(i){return i&&this.u.language!==i&&(this.u=t(i),this.$=new Intl.PluralRules(this.long()),this.g=new Intl.PluralRules(this.i.fallback),this.I()),this.short()}locale(i){const s=this.long();this.u=t(i),this.$=new Intl.PluralRules(this.long()),this.g=new Intl.PluralRules(this.i.fallback),s!==this.long()&&this.I()}short(){return`${this.u.language}${this.script()?`-${this.script()}`:""}`}region(){return this.u.region}script(){return this.u.script}long(){return`${this.short()}${this.region()?`-${this.region()}`:""}`}addResource(t,n){t=s(t),this.o={...this.o,...i(n,t)},this.I()}addPlugin(t,i="global"){"global"!==i&&(i=s(i)),void 0===this.l[i]&&(this.l[i]=[]),this.l[i].push(t),this.I()}listen(t){return-1!==this.h.indexOf(t)||this.h.push(t),()=>{const i=this.h.indexOf(t);-1!==i&&this.h.splice(i,1)}}I(){this.h.forEach(t=>t())}p(t,i,s){const n=[t];return i.context&&n.unshift(t=`${t}_${i.context}`),"number"==typeof i.count&&(n.unshift(`${t}_${(s?this.g:this.$).select(i.count).toString()}`),n.unshift(`${t}_${i.count}`)),n}}export{n as Translator};
//# sourceMappingURL=index.module.js.map