UNPKG

@logistically/i18n-react-core

Version:

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

12 lines (11 loc) 10.7 kB
"use strict";var e=require("@logistically/i18n"),t=require("react"),r=require("react-native");class a{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.TranslationService(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 n,s={exports:{}},i={};var o,l={}; /** * @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?s.exports=function(){if(n)return i;n=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 s in a={},r)"key"!==s&&(a[s]=r[s]);else a=r;return r=a.ref,{$$typeof:e,type:t,key:n,ref:void 0!==r?r:null,props:a}}return i.Fragment=t,i.jsx=r,i.jsxs=r,i}():s.exports=(o||(o=1,"production"!==process.env.NODE_ENV&&function(){function e(t){if(null==t)return null;if("function"==typeof t)return t.$$typeof===w?null:t.displayName||t.name||null;if("string"==typeof t)return t;switch(t){case y:return"Fragment";case p:return"Profiler";case b:return"StrictMode";case v:return"Suspense";case T:return"SuspenseList";case j:return"Activity"}if("object"==typeof t)switch(t.tag,t.$$typeof){case h:return"Portal";case m:return(t.displayName||"Context")+".Provider";case g: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 x:return null!==(r=t.displayName||null)?r:e(t.type)||"Memo";case L: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===L)return"<...>";try{var r=e(t);return r?"<"+r+">":"<...>"}catch(e){return"<...>"}}function s(){return Error("react-stack-top-frame")}function i(){var t=e(this.type);return P[t]||(P[t]=!0),void 0!==(t=this.props.ref)?t:null}function o(t,r,n,s,o,l,f,h){var y,b=r.children;if(void 0!==b)if(s){if(O(b)){for(s=0;s<b.length;s++)c(b[s]);Object.freeze&&Object.freeze(b)}}else c(b);if(k.call(r,"key")){b=e(t);var p=Object.keys(r).filter(function(e){return"key"!==e});s=0<p.length?"{key: someKey, "+p.join(": ..., ")+": ...}":"{key: someKey}",R[b+s]||(p=0<p.length?"{"+p.join(": ..., ")+": ...}":"{}",R[b+s]=!0)}if(b=null,void 0!==n&&(a(n),b=""+n),function(e){if(k.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 g in n={},r)"key"!==g&&(n[g]=r[g]);else n=r;return b&&function(e){function t(){u||(u=!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,s,o,l){return r=s.ref,e={$$typeof:d,type:e,key:t,props:s,_owner:n},null!==(void 0!==r?r:null)?Object.defineProperty(e,"ref",{enumerable:!1,get:i}):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,l,0,null===(y=_.A)?null:y.getOwner(),n,f,h)}function c(e){"object"==typeof e&&null!==e&&e.$$typeof===d&&e._store&&(e._store.validated=1)}var u,f=t,d=Symbol.for("react.transitional.element"),h=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),p=Symbol.for("react.profiler"),g=Symbol.for("react.consumer"),m=Symbol.for("react.context"),S=Symbol.for("react.forward_ref"),v=Symbol.for("react.suspense"),T=Symbol.for("react.suspense_list"),x=Symbol.for("react.memo"),L=Symbol.for("react.lazy"),j=Symbol.for("react.activity"),w=Symbol.for("react.client.reference"),_=f.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,k=Object.prototype.hasOwnProperty,O=Array.isArray,N=console.createTask?console.createTask:function(){return null},P={},C=(f={react_stack_bottom_frame:function(e){return e()}}).react_stack_bottom_frame.bind(f,s)(),z=N(n(s)),R={};l.Fragment=y,l.jsx=function(e,t,r,a,s){var i=1e4>_.recentlyCreatedOwnerStacks++;return o(e,t,r,!1,0,s,i?Error("react-stack-top-frame"):C,i?N(n(e)):z)},l.jsxs=function(e,t,r,a,s){var i=1e4>_.recentlyCreatedOwnerStacks++;return o(e,t,r,!0,0,s,i?Error("react-stack-top-frame"):C,i?N(n(e)):z)}}()),l);var c=s.exports;const u=t.createContext(null);class f{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 d=()=>{const e=t.useContext(u);if(!e)throw new Error("useTranslationStore must be used within a TranslationProvider");return e},h=()=>{const e=d();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}},y=({translationKey:e,params:t,locale:a,fallback:n,component:s=r.Text,style:i,children:o,debug:l=!1,...u})=>{const{t:f,translate:d,isLoading:y,error:b,locale:p}=h();if(y)return c.jsx(s,{style:i,...u,children:n||e});if(b)return c.jsx(s,{style:i,...u,children:n||e});let g;try{g=d(e,t),g===e&&n&&(g=n)}catch(b){g=n||e}const m=g===e&&n?n:g;return c.jsx(s,{style:i,...u,children:o||m})};exports.ContextAdapter=f,exports.TranslatedBody=e=>c.jsx(y,{component:r.Text,style:[{fontSize:16},e.style],...e}),exports.TranslatedCaption=e=>c.jsx(y,{component:r.Text,style:[{fontSize:14,color:"#666"},e.style],...e}),exports.TranslatedHeading=e=>c.jsx(y,{component:r.Text,style:[{fontSize:24,fontWeight:"bold"},e.style],...e}),exports.TranslatedSubheading=e=>c.jsx(y,{component:r.Text,style:[{fontSize:18,fontWeight:"600"},e.style],...e}),exports.TranslatedText=e=>c.jsx(y,{component:r.Text,...e}),exports.TranslatedTextRN=y,exports.TranslatedView=e=>c.jsx(y,{component:r.View,...e}),exports.TranslationCore=a,exports.TranslationProvider=({children:e,config:r,initialLocale:n})=>{const[s,i]=t.useState(null),[o,l]=t.useState(!1);return t.useEffect(()=>{const e=new a(r),t=new f(e),s={...t.getState(),...t.getActions()};i(s);const o=t.subscribe(e=>{const r=t.getActions();i({...e,...r})});return(async()=>{try{await e.initialize(n);const r=t.getState(),a=t.getActions();i({...r,...a}),l(!0)}catch(e){i({...t.getState(),...t.getActions()}),l(!0)}})(),()=>{o(),t.destroy()}},[r,n]),s?c.jsx(u.Provider,{value:s,children:e}):c.jsx(u.Provider,{value:null,children:c.jsx("div",{children:"Loading..."})})},exports.createContextAdapter=e=>new f(e),exports.useLocale=()=>{const e=d();return{locale:e.locale,setLocale:e.setLocale,supportedLocales:["en","fr","es"],isRTL:e.isRTLLocale(e.locale),direction:e.getTextDirection(""),isRTLLocale:e.isRTLLocale}},exports.useTranslation=h,exports.useTranslationStore=d; //# sourceMappingURL=react-native.js.map