UNPKG

@logistically/i18n-react-core

Version:

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

3 lines (2 loc) 1.74 kB
"use strict";var t=require("@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.TranslationService(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(){}}exports.SSRTranslationUtils=e,exports.createSSRContext=async(t,a)=>new e(a).createSSRContext(t),exports.deserializeContext=t=>new e({}).deserializeContext(t),exports.getServerSideTranslations=async(t,a)=>{const n=new e(a),r=await n.createSSRContext(t);return{props:{ssrContext:n.serializeContext(r)}}},exports.getServerTranslation=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}},exports.getTranslation=async(t,a)=>new e(a).getTranslation(t),exports.preloadTranslations=async(t,a)=>{const n=new e(a);await n.preloadTranslations(t)},exports.serializeContext=t=>new e({}).serializeContext(t); //# sourceMappingURL=ssr.js.map