UNPKG

@logistically/i18n-react-core

Version:

React integration for @logistically/i18n with state management agnostic design

3 lines (2 loc) 1.73 kB
import{TranslationService as t}from"@logistically/i18n";class e{constructor(e){this.config=e;const a={...e,debug:"boolean"==typeof e.debug?e.debug:e.debug?.enabled||!1};this.translationService=new t(a)}async getTranslation(t){try{this.translationService.reloadTranslations();const e=this.translationService.getKeys(t),a={};return e.forEach(e=>{a[e]=this.translationService.translate(e,t)}),a}catch(t){return{}}}async preloadTranslations(t){const e=t.map(t=>this.getTranslation(t));await Promise.all(e)}async createSSRContext(t){return{locale:t,translations:await this.getTranslation(t),preloadedLocales:this.config.ssr?.preloadLocales||[]}}serializeContext(t){return JSON.stringify(t)}deserializeContext(t){try{return JSON.parse(t)}catch(t){return{locale:"en",translations:{},preloadedLocales:[]}}}createSSRUtils(t){return{locale:t.locale,translations:t.translations,t:(e,a)=>{const n=t.translations[e]||e;return a?Object.keys(a).reduce((t,e)=>t.replace(`{${e}}`,a[e]),n):n}}}destroy(){}}const a=async(t,a)=>new e(a).getTranslation(t),n=async(t,a)=>{const n=new e(a);await n.preloadTranslations(t)},r=async(t,a)=>new e(a).createSSRContext(t),s=t=>new e({}).serializeContext(t),o=t=>new e({}).deserializeContext(t),i=async(t,a)=>{const n=new e(a),r=await n.createSSRContext(t);return{props:{ssrContext:n.serializeContext(r)}}},l=async(t,a)=>{const n=new e(a);return{t:(e,a)=>{try{return n.translationService.translate(e,t,a)}catch{return e}},translations:await n.getTranslation(t),locale:t}};export{e as SSRTranslationUtils,r as createSSRContext,o as deserializeContext,i as getServerSideTranslations,l as getServerTranslation,a as getTranslation,n as preloadTranslations,s as serializeContext}; //# sourceMappingURL=ssr.esm.js.map