react-text
Version:
React translation library with plain objects as dictionaries
2 lines (1 loc) • 1.57 kB
JavaScript
import e,{createContext as t}from"react";var r=(...e)=>{const t=Object.assign({},...e);let r;return Object.keys(t).reduce((e,n)=>{const o=Object.keys(t[n]);if(r||(r=o),JSON.stringify(r.sort())!==JSON.stringify(o.sort()))throw new Error(`Wrong amount of languages, expected '${r}' but got '${o}'`);return{...e,[n]:r.reduce((e,r)=>{const o=t[n][r];if(o&&o.normalized)return{...e,[r]:o};if("function"==typeof o){const t=(e={})=>o(e);return t.normalized=!0,{...e,[r]:t}}if("string"==typeof o){const t=()=>o;return t.normalized=!0,{...e,[r]:t}}throw new Error(`Value cannot be of type "${typeof o}"`)},{})}},{})},n=({id:e,dictionary:t,language:r,...n})=>{if(!e){const t=Object.entries(n).filter(([e,t])=>"boolean"==typeof t).map(([e])=>e);if(!t.length)throw new Error("Please make sure to pass an id");if(t.length>1)throw new Error(`Please only pass a single id/boolean, detected '${t}'`);e=t[0]}const o=Object.keys(t);if(!o.includes(e))throw new Error(`Couldn't find '${e}' in the dictionary. Available ids: ${o}`);if(void 0===t[e][r])throw new Error(`The language '${r}' is not available (attempted with id '${e}')`);return t[e][r](n)};const{Provider:o,Consumer:i}=t({});let a=({children:e})=>e;if("undefined"!=typeof require)try{a=require("react-native").Text}catch(e){}export default({language:t,dictionary:l={},children:c,render:s,component:u,...d})=>e.createElement(i,null,i=>c?(t=t||i.language,l={...i.dictionary,...r(l)},e.createElement(o,{value:{language:t,dictionary:l}},c)):u?!0===d[i.language]?u:null:s?s(n({...i,...d})):e.createElement(a,null,n({...i,...d})));