UNPKG

@logistically/i18n-react-core

Version:

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

12 lines (11 loc) 10.7 kB
import{TranslationService as e}from"@logistically/i18n";import t,{createContext as r,useState as a,useEffect as n,useContext as i}from"react";import{Text as s,View as o}from"react-native";class l{constructor(t){this.listeners=new Set,this.config=t;const r={...t,debug:"boolean"==typeof t.debug?t.debug:t.debug?.enabled||!1};this.translationService=new e(r),this.state={locale:t.defaultLocale||"en",translations:{},isLoading:!1,error:null,isInitialized:!1}}getState(){return{...this.state}}setState(e){this.state={...this.state,...e},this.notifyListeners()}notifyListeners(){this.listeners.forEach(e=>e(this.getState()))}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}getActions(){return{setLocale:this.setLocale.bind(this),loadTranslations:this.loadTranslations.bind(this),translate:this.translate.bind(this),translatePlural:this.translatePlural.bind(this),formatDate:this.formatDate.bind(this),formatNumber:this.formatNumber.bind(this),getTextDirection:this.getTextDirection.bind(this),isRTLLocale:this.isRTLLocale.bind(this),reloadTranslations:this.reloadTranslations.bind(this),clearCache:this.clearCache.bind(this)}}async setLocale(e){if(this.state.locale!==e){this.setState({locale:e,isLoading:!0,error:null});try{await this.loadTranslations(e),this.setState({isLoading:!1,isInitialized:!0})}catch(e){throw this.setState({isLoading:!1,error:e}),e}}}async loadTranslations(e){try{this.setState({isLoading:!0,error:null}),this.translationService.reloadTranslations();const t=this.translationService.getKeys(e),r={};t.forEach(t=>{r[t]=this.translationService.translate(t,e)}),this.setState({translations:r,isLoading:!1,isInitialized:!0})}catch(e){throw this.setState({isLoading:!1,error:e}),e}}translate(e,t){try{return this.translationService.translate(e,this.state.locale,t)}catch(t){return("object"==typeof this.config.debug?this.config.debug:{enabled:!1}).logMissingKeys,e}}translatePlural(e,t,r){try{return this.translationService.translatePlural(e,t,this.state.locale,r)}catch(t){return("object"==typeof this.config.debug?this.config.debug:{enabled:!1}).logMissingKeys,e}}formatDate(e,t){return this.translationService.formatDateForLocale(e,this.state.locale,t)}formatNumber(e,t){return this.translationService.formatNumberForLocale(e,this.state.locale)}getTextDirection(e){return this.translationService.getTextDirection(e)}isRTLLocale(e){return this.translationService.isRTLLocale(e)}async reloadTranslations(){await this.loadTranslations(this.state.locale)}clearCache(){this.translationService.clearCache()}setAdapter(e){this.adapter=e}getAdapter(){return this.adapter}async initialize(e){const t=e||this.config.defaultLocale||"en";try{this.setState({isLoading:!0,error:null}),this.setState({locale:t}),await this.loadTranslations(t),this.setState({isLoading:!1,isInitialized:!0})}catch(e){throw this.setState({isLoading:!1,error:e}),e}}destroy(){this.listeners.clear(),this.translationService.clearCache()}getTranslationService(){return this.translationService}getConfig(){return this.config}isInitialized(){return this.state.isInitialized}}var c,u={exports:{}},f={};var h,d={}; /** * @license React * react-jsx-runtime.development.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */"production"===process.env.NODE_ENV?u.exports=function(){if(c)return f;c=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function r(t,r,a){var n=null;if(void 0!==a&&(n=""+a),void 0!==r.key&&(n=""+r.key),"key"in r)for(var i in a={},r)"key"!==i&&(a[i]=r[i]);else a=r;return r=a.ref,{$$typeof:e,type:t,key:n,ref:void 0!==r?r:null,props:a}}return f.Fragment=t,f.jsx=r,f.jsxs=r,f}():u.exports=(h||(h=1,"production"!==process.env.NODE_ENV&&function(){function e(t){if(null==t)return null;if("function"==typeof t)return t.$$typeof===k?null:t.displayName||t.name||null;if("string"==typeof t)return t;switch(t){case y:return"Fragment";case g:return"Profiler";case b:return"StrictMode";case v:return"Suspense";case L:return"SuspenseList";case _:return"Activity"}if("object"==typeof t)switch(t.tag,t.$$typeof){case h:return"Portal";case p:return(t.displayName||"Context")+".Provider";case m:return(t._context.displayName||"Context")+".Consumer";case S:var r=t.render;return(t=t.displayName)||(t=""!==(t=r.displayName||r.name||"")?"ForwardRef("+t+")":"ForwardRef"),t;case T:return null!==(r=t.displayName||null)?r:e(t.type)||"Memo";case j:r=t._payload,t=t._init;try{return e(t(r))}catch(e){}}return null}function r(e){return""+e}function a(e){try{r(e);var t=!1}catch(e){t=!0}if(t){var a=(t=console).error,n="function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return a.call(t,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",n),r(e)}}function n(t){if(t===y)return"<>";if("object"==typeof t&&null!==t&&t.$$typeof===j)return"<...>";try{var r=e(t);return r?"<"+r+">":"<...>"}catch(e){return"<...>"}}function i(){return Error("react-stack-top-frame")}function s(){var t=e(this.type);return P[t]||(P[t]=!0),void 0!==(t=this.props.ref)?t:null}function o(t,r,n,i,o,u,h,d){var y,b=r.children;if(void 0!==b)if(i){if(O(b)){for(i=0;i<b.length;i++)l(b[i]);Object.freeze&&Object.freeze(b)}}else l(b);if(x.call(r,"key")){b=e(t);var g=Object.keys(r).filter(function(e){return"key"!==e});i=0<g.length?"{key: someKey, "+g.join(": ..., ")+": ...}":"{key: someKey}",D[b+i]||(g=0<g.length?"{"+g.join(": ..., ")+": ...}":"{}",D[b+i]=!0)}if(b=null,void 0!==n&&(a(n),b=""+n),function(e){if(x.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}(r)&&(a(r.key),b=""+r.key),"key"in r)for(var m in n={},r)"key"!==m&&(n[m]=r[m]);else n=r;return b&&function(e){function t(){c||(c=!0)}t.isReactWarning=!0,Object.defineProperty(e,"key",{get:t,configurable:!0})}(n,"function"==typeof t&&(t.displayName||t.name)),function(e,t,r,a,n,i,o,l){return r=i.ref,e={$$typeof:f,type:e,key:t,props:i,_owner:n},null!==(void 0!==r?r:null)?Object.defineProperty(e,"ref",{enumerable:!1,get:s}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:o}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:l}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}(t,b,u,0,null===(y=w.A)?null:y.getOwner(),n,h,d)}function l(e){"object"==typeof e&&null!==e&&e.$$typeof===f&&e._store&&(e._store.validated=1)}var c,u=t,f=Symbol.for("react.transitional.element"),h=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),g=Symbol.for("react.profiler"),m=Symbol.for("react.consumer"),p=Symbol.for("react.context"),S=Symbol.for("react.forward_ref"),v=Symbol.for("react.suspense"),L=Symbol.for("react.suspense_list"),T=Symbol.for("react.memo"),j=Symbol.for("react.lazy"),_=Symbol.for("react.activity"),k=Symbol.for("react.client.reference"),w=u.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,x=Object.prototype.hasOwnProperty,O=Array.isArray,N=console.createTask?console.createTask:function(){return null},P={},z=(u={react_stack_bottom_frame:function(e){return e()}}).react_stack_bottom_frame.bind(u,i)(),R=N(n(i)),D={};d.Fragment=y,d.jsx=function(e,t,r,a,i){var s=1e4>w.recentlyCreatedOwnerStacks++;return o(e,t,r,!1,0,i,s?Error("react-stack-top-frame"):z,s?N(n(e)):R)},d.jsxs=function(e,t,r,a,i){var s=1e4>w.recentlyCreatedOwnerStacks++;return o(e,t,r,!0,0,i,s?Error("react-stack-top-frame"):z,s?N(n(e)):R)}}()),d);var y=u.exports;const b=r(null);class g{constructor(e){this.listeners=new Set,this.core=e,this.state=e.getState(),this.core.subscribe(e=>{this.state=e,this.notifyListeners()})}getState(){return this.state}getActions(){return this.core.getActions()}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(){this.listeners.forEach(e=>e(this.state))}async initialize(){await this.core.initialize()}destroy(){this.listeners.clear(),this.core.destroy()}}const m=({children:e,config:t,initialLocale:r})=>{const[i,s]=a(null),[o,c]=a(!1);return n(()=>{const e=new l(t),a=new g(e),n={...a.getState(),...a.getActions()};s(n);const i=a.subscribe(e=>{const t=a.getActions();s({...e,...t})});return(async()=>{try{await e.initialize(r);const t=a.getState(),n=a.getActions();s({...t,...n}),c(!0)}catch(e){s({...a.getState(),...a.getActions()}),c(!0)}})(),()=>{i(),a.destroy()}},[t,r]),i?y.jsx(b.Provider,{value:i,children:e}):y.jsx(b.Provider,{value:null,children:y.jsx("div",{children:"Loading..."})})},p=()=>{const e=i(b);if(!e)throw new Error("useTranslationStore must be used within a TranslationProvider");return e},S=()=>{const e=p();return{t:(t,r)=>e.translate(t,r?.params),translate:e.translate,translatePlural:e.translatePlural,formatDate:e.formatDate,formatNumber:e.formatNumber,getTextDirection:e.getTextDirection,isLoading:e.isLoading,error:e.error,locale:e.locale,setLocale:e.setLocale,isRTLLocale:e.isRTLLocale,reloadTranslations:e.reloadTranslations,clearCache:e.clearCache}},v=()=>{const e=p();return{locale:e.locale,setLocale:e.setLocale,supportedLocales:["en","fr","es"],isRTL:e.isRTLLocale(e.locale),direction:e.getTextDirection(""),isRTLLocale:e.isRTLLocale}},L=e=>new g(e),T=({translationKey:e,params:t,locale:r,fallback:a,component:n=s,style:i,children:o,debug:l=!1,...c})=>{const{t:u,translate:f,isLoading:h,error:d,locale:b}=S();if(h)return y.jsx(n,{style:i,...c,children:a||e});if(d)return y.jsx(n,{style:i,...c,children:a||e});let g;try{g=f(e,t),g===e&&a&&(g=a)}catch(d){g=a||e}const m=g===e&&a?a:g;return y.jsx(n,{style:i,...c,children:o||m})},j=e=>y.jsx(T,{component:s,...e}),_=e=>y.jsx(T,{component:o,...e}),k=e=>y.jsx(T,{component:s,style:[{fontSize:24,fontWeight:"bold"},e.style],...e}),w=e=>y.jsx(T,{component:s,style:[{fontSize:18,fontWeight:"600"},e.style],...e}),x=e=>y.jsx(T,{component:s,style:[{fontSize:16},e.style],...e}),O=e=>y.jsx(T,{component:s,style:[{fontSize:14,color:"#666"},e.style],...e});export{g as ContextAdapter,x as TranslatedBody,O as TranslatedCaption,k as TranslatedHeading,w as TranslatedSubheading,j as TranslatedText,T as TranslatedTextRN,_ as TranslatedView,l as TranslationCore,m as TranslationProvider,L as createContextAdapter,v as useLocale,S as useTranslation,p as useTranslationStore}; //# sourceMappingURL=react-native.esm.js.map