react-localization 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,15 +1,29 @@
1
1
  # react-localization
2
+
2
3
  Simple module to localize the React interface using the same syntax used in the
3
4
  [ReactNativeLocalization module](https://github.com/stefalda/ReactNativeLocalization/).
4
5
 
6
+ ## React 19 support
7
+
8
+ Version 2.0 has been recreated to support React 19, removing babel and adding vite tooling.
9
+
10
+ If you work with previous versions of react you can use version 1.x.
11
+
5
12
  ### Note about version 1.x
6
- This library has been refactored to use the newly created [localized-strings package](https://github.com/stefalda/localized-strings), now added as a dependency, so to unify the code and make it easier to mantain
7
13
 
8
- All the basic code is now in the localized-strings project but this React version add support for embedding JSX code in the formatted strings, by overriding the formatString method.
14
+ This library has been refactored to use the newly created
15
+ [localized-strings package](https://github.com/stefalda/localized-strings), now
16
+ added as a dependency, so to unify the code and make it easier to mantain
17
+
18
+ All the basic code is now in the localized-strings project but this React
19
+ version add support for embedding JSX code in the formatted strings, by
20
+ overriding the formatString method.
9
21
 
10
22
  ## How it works
11
23
 
12
- The library uses the current interface language, then it loads and displays the strings matching the current interface locale or the default language (the first one if a match is not found) if a specific localization can't be found.
24
+ The library uses the current interface language, then it loads and displays the
25
+ strings matching the current interface locale or the default language (the first
26
+ one if a match is not found) if a specific localization can't be found.
13
27
 
14
28
  It's possible to force a language different from the interface one.
15
29
 
@@ -19,61 +33,71 @@ It's possible to force a language different from the interface one.
19
33
 
20
34
  ## Usage
21
35
 
22
- In the React class that you want to localize, require the library and define the strings object passing to the constructor a simple object containing a language key (i.e. en, it, fr..) and then a list of key-value pairs with the needed localized strings.
36
+ In the React class that you want to localize, require the library and define the
37
+ strings object passing to the constructor a simple object containing a language
38
+ key (i.e. en, it, fr..) and then a list of key-value pairs with the needed
39
+ localized strings.
23
40
 
24
- ```js
41
+ ```js
25
42
  // ES6 module syntax
26
- import LocalizedStrings from 'react-localization';
43
+ import LocalizedStrings from "react-localization";
27
44
 
28
45
  let strings = new LocalizedStrings({
29
- en:{
30
- how:"How do you want your egg today?",
31
- boiledEgg:"Boiled egg",
32
- softBoiledEgg:"Soft-boiled egg",
33
- choice:"How to choose the egg"
46
+ en: {
47
+ how: "How do you want your egg today?",
48
+ boiledEgg: "Boiled egg",
49
+ softBoiledEgg: "Soft-boiled egg",
50
+ choice: "How to choose the egg",
34
51
  },
35
52
  it: {
36
- how:"Come vuoi il tuo uovo oggi?",
37
- boiledEgg:"Uovo sodo",
38
- softBoiledEgg:"Uovo alla coque",
39
- choice:"Come scegliere l'uovo"
40
- }
53
+ how: "Come vuoi il tuo uovo oggi?",
54
+ boiledEgg: "Uovo sodo",
55
+ softBoiledEgg: "Uovo alla coque",
56
+ choice: "Come scegliere l'uovo",
57
+ },
41
58
  });
42
59
  ```
43
60
 
44
- Then use the `strings` object literal directly in the render method accessing the key of the localized string.
61
+ Then use the `strings` object literal directly in the render method accessing
62
+ the key of the localized string.
45
63
 
46
64
  ```js
47
65
  <Text style={styles.title}>
48
66
  {strings.how}
49
- </Text>
67
+ </Text>;
50
68
  ```
51
69
 
52
- The first language is considered the default one, so if a translation is missing for the selected language, the default one is shown and a line is written to the log as a reminder.
70
+ The first language is considered the default one, so if a translation is missing
71
+ for the selected language, the default one is shown and a line is written to the
72
+ log as a reminder.
53
73
 
54
74
  #### Update / Overwrite Locale
55
75
 
56
- You might have default localized in the build but then download the latest localization strings from a server. Use setContent to overwrite the whole object.
76
+ You might have default localized in the build but then download the latest
77
+ localization strings from a server. Use setContent to overwrite the whole
78
+ object.
57
79
 
58
80
  **NOTE** that this will remove all other localizations if used.
59
81
 
60
82
  ```js
61
83
  strings.setContent({
62
- en:{
63
- how:"How do you want your egg todajsie?",
64
- boiledEgg:"Boiled eggsie",
65
- softBoiledEgg:"Soft-boiled egg",
66
- choice:"How to choose the egg"
67
- }
68
- })
84
+ en: {
85
+ how: "How do you want your egg todajsie?",
86
+ boiledEgg: "Boiled eggsie",
87
+ softBoiledEgg: "Soft-boiled egg",
88
+ choice: "How to choose the egg",
89
+ },
90
+ });
69
91
  ```
70
92
 
71
93
  ## API
72
94
 
73
- * setLanguage(languageCode) - to force manually a particular language
74
- * getLanguage() - to get the current displayed language
75
- * getInterfaceLanguage() - to get the current device interface language
76
- * formatString() - formats the input string and returns a new string, replacing its placeholders with the other arguments strings
95
+ - setLanguage(languageCode) - to force manually a particular language
96
+ - getLanguage() - to get the current displayed language
97
+ - getInterfaceLanguage() - to get the current device interface language
98
+ - formatString() - formats the input string and returns a new string, replacing
99
+ its placeholders with the other arguments strings
100
+
77
101
  ```js
78
102
  en:{
79
103
  bread:"bread",
@@ -108,18 +132,28 @@ Typical usage is to render it in a JSX with `formatString` calls inlined:
108
132
 
109
133
  ```jsx
110
134
  <div>
111
- <SomeComponent food={strings.formatString(strings.question, strings.bread, "jam")} />
112
- <p>Usage with an object parameter: {
113
- strings.formatString(strings.currentDate, { month: "February", day: 13, year: 2050 })
114
- }></p>
115
- </div>
135
+ <SomeComponent
136
+ food={strings.formatString(strings.question, strings.bread, "jam")}
137
+ />
138
+ <p>
139
+ Usage with an object parameter:{" "}
140
+ {strings.formatString(strings.currentDate, {
141
+ month: "February",
142
+ day: 13,
143
+ year: 2050,
144
+ })}>
145
+ </p>
146
+ </div>;
116
147
  ```
148
+
117
149
  **Beware: do not define a string key as formatString!**
118
150
 
119
- * setContent(props) - to dynamically load another set of strings
120
- * getAvailableLanguages() - to get an array of the languages passed in the constructor
151
+ - setContent(props) - to dynamically load another set of strings
152
+ - getAvailableLanguages() - to get an array of the languages passed in the
153
+ constructor
121
154
 
122
155
  ## Examples
156
+
123
157
  To force a particular language use something like this:
124
158
 
125
159
  ```js
@@ -128,12 +162,17 @@ _onSetLanguageToItalian() {
128
162
  this.setState({});
129
163
  }
130
164
  ```
165
+
131
166
  ## Typescript support
132
- Because of the dynamically generated class properties, it's a little tricky to have the autocomplete functionality working.
167
+
168
+ Because of the dynamically generated class properties, it's a little tricky to
169
+ have the autocomplete functionality working.
133
170
 
134
171
  Anyway it's possible to gain the desired results by:
135
- 1. defining an Interface that extends the LocalizedStringsMethods interface and has all the object string's keys
136
- 2. defining that the LocalizedStrings instance implements that interface
172
+
173
+ 1. defining an Interface that extends the LocalizedStringsMethods interface and
174
+ has all the object string's keys
175
+ 2. defining that the LocalizedStrings instance implements that interface
137
176
 
138
177
  This is the suggested solution to work with Typescript:
139
178
 
@@ -154,7 +193,9 @@ this.strings = new LocalizedStrings({
154
193
  time: "Time"
155
194
  }
156
195
  });
157
-
158
196
  ```
197
+
159
198
  ## Questions or suggestions?
160
- Feel free to contact me on [Twitter](https://twitter.com/talpaz) or [open an issue](https://github.com/stefalda/react-localization/issues/new).
199
+
200
+ Feel free to contact me on [Twitter](https://twitter.com/talpaz) or
201
+ [open an issue](https://github.com/stefalda/react-localization/issues/new).
@@ -199,7 +199,7 @@ L.prototype.formatString = (i, ...e) => {
199
199
  const l = s.slice(1, -1);
200
200
  let r = e[l];
201
201
  if (r == null) {
202
- const u = e[0][l];
202
+ const u = e[0] ? e[0][l] : void 0;
203
203
  if (u !== void 0)
204
204
  r = u;
205
205
  else
@@ -1 +1 @@
1
- (function(u,o){typeof exports=="object"&&typeof module<"u"?module.exports=o(require("react")):typeof define=="function"&&define.amd?define(["react"],o):(u=typeof globalThis<"u"?globalThis:u||self,u.ReactLocalization=o(u.React))})(this,function(u){"use strict";function o(){const i="en-US";if(typeof navigator>"u")return i;const e=navigator;if(e){if(e.language)return e.language;if(e.languages&&e.languages[0])return e.languages[0];if(e.userLanguage)return e.userLanguage;if(e.browserLanguage)return e.browserLanguage}return i}function p(i,e){if(e[i])return i;const t=i.indexOf("-"),a=t>=0?i.substring(0,t):i;return e[a]?a:Object.keys(e)[0]}function _(i){const e=["_interfaceLanguage","_language","_defaultLanguage","_defaultLanguageFirstLevelKeys","_props"];i.forEach(t=>{if(e.indexOf(t)!==-1)throw new Error(`${t} cannot be used as a key. It is a reserved word.`)})}function L(i){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let a=0;a<i;a+=1)e+=t.charAt(Math.floor(Math.random()*t.length));return e}const f=/(\{[\d|\w]+\})/,c=/(\$ref\{[\w|.]+\})/;class h{constructor(e,t){typeof t=="function"&&(t={customLanguageInterface:t}),this._opts=Object.assign({},{customLanguageInterface:o,pseudo:!1,pseudoMultipleLanguages:!1,logsEnabled:!0},t),this._interfaceLanguage=this._opts.customLanguageInterface(),this._language=this._interfaceLanguage,this.setContent(e)}setContent(e){const[t]=Object.keys(e);this._defaultLanguage=t,this._defaultLanguageFirstLevelKeys=[],this._props=e,_(Object.keys(e[this._defaultLanguage])),Object.keys(this._props[this._defaultLanguage]).forEach(a=>{typeof this._props[this._defaultLanguage][a]=="string"&&this._defaultLanguageFirstLevelKeys.push(a)}),this.setLanguage(this._interfaceLanguage),this._opts.pseudo&&this._pseudoAllValues(this._props)}_pseudoAllValues(e){Object.keys(e).forEach(t=>{if(typeof e[t]=="object")this._pseudoAllValues(e[t]);else if(typeof e[t]=="string"){if(e[t].indexOf("[")===0&&e[t].lastIndexOf("]")===e[t].length-1)return;const a=e[t].split(" ");for(let s=0;s<a.length;s+=1)if(!a[s].match(f)){if(!a[s].match(c)){let n=a[s].length;this._opts.pseudoMultipleLanguages&&(n=parseInt(n*1.4,10)),a[s]=L(n)}}e[t]=`[${a.join(" ")}]`}})}setLanguage(e){const t=p(e,this._props),a=Object.keys(this._props)[0];if(this._language=t,this._props[t]){for(let n=0;n<this._defaultLanguageFirstLevelKeys.length;n+=1)delete this[this._defaultLanguageFirstLevelKeys[n]];let s=Object.assign({},this._props[this._language]);Object.keys(s).forEach(n=>{this[n]=s[n]}),a!==this._language&&(s=this._props[a],this._fallbackValues(s,this))}}_fallbackValues(e,t){Object.keys(e).forEach(a=>{Object.prototype.hasOwnProperty.call(e,a)&&!t[a]&&t[a]!==""?(t[a]=e[a],this._opts.logsEnabled&&console.log(`🚧 👷 key '${a}' not found in localizedStrings for language ${this._language} 🚧`)):typeof t[a]!="string"&&this._fallbackValues(e[a],t[a])})}getLanguage(){return this._language}getInterfaceLanguage(){return this._interfaceLanguage}getAvailableLanguages(){return this._availableLanguages||(this._availableLanguages=[],Object.keys(this._props).forEach(e=>{this._availableLanguages.push(e)})),this._availableLanguages}formatString(e,...t){let a=e||"";return typeof a=="string"&&(a=this.getString(e,null,!0)||a),a.split(c).filter(n=>!!n).map(n=>{if(n.match(c)){const r=n.slice(5,-1),l=this.getString(r);return l||(this._opts.logsEnabled&&console.log(`No Localization ref found for '${n}' in string '${e}'`),`$ref(id:${r})`)}return n}).join("").split(f).filter(n=>!!n).map(n=>{if(n.match(f)){const r=n.slice(1,-1);let l=t[r];if(l===void 0){const g=t[0][r];if(g!==void 0)l=g;else return l}return l}return n}).join("")}getString(e,t,a=!1){try{let s=this._props[t||this._language];const n=e.split(".");for(let r=0;r<n.length;r+=1){if(s[n[r]]===void 0)throw Error(n[r]);s=s[n[r]]}return s}catch(s){!a&&this._opts.logsEnabled&&console.log(`No localization found for key '${e}' and language '${t}', failed on ${s.message}`)}return null}getContent(){return this._props}}const d=/(\{[\d|\w]+\})/;return h.prototype.formatString=(i,...e)=>{let t=!1;const a=(i||"").split(d).filter(s=>!!s).map((s,n)=>{if(s.match(d)){const r=s.slice(1,-1);let l=e[r];if(l==null){const g=e[0][r];if(g!==void 0)l=g;else return l}return u.isValidElement(l)?(t=!0,u.Children.toArray(l).map(g=>({...g,key:n.toString()}))):l}return s});return t?a:a.join("")},h});
1
+ (function(u,o){typeof exports=="object"&&typeof module<"u"?module.exports=o(require("react")):typeof define=="function"&&define.amd?define(["react"],o):(u=typeof globalThis<"u"?globalThis:u||self,u.ReactLocalization=o(u.React))})(this,function(u){"use strict";function o(){const i="en-US";if(typeof navigator>"u")return i;const e=navigator;if(e){if(e.language)return e.language;if(e.languages&&e.languages[0])return e.languages[0];if(e.userLanguage)return e.userLanguage;if(e.browserLanguage)return e.browserLanguage}return i}function p(i,e){if(e[i])return i;const t=i.indexOf("-"),n=t>=0?i.substring(0,t):i;return e[n]?n:Object.keys(e)[0]}function _(i){const e=["_interfaceLanguage","_language","_defaultLanguage","_defaultLanguageFirstLevelKeys","_props"];i.forEach(t=>{if(e.indexOf(t)!==-1)throw new Error(`${t} cannot be used as a key. It is a reserved word.`)})}function L(i){let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let n=0;n<i;n+=1)e+=t.charAt(Math.floor(Math.random()*t.length));return e}const f=/(\{[\d|\w]+\})/,c=/(\$ref\{[\w|.]+\})/;class h{constructor(e,t){typeof t=="function"&&(t={customLanguageInterface:t}),this._opts=Object.assign({},{customLanguageInterface:o,pseudo:!1,pseudoMultipleLanguages:!1,logsEnabled:!0},t),this._interfaceLanguage=this._opts.customLanguageInterface(),this._language=this._interfaceLanguage,this.setContent(e)}setContent(e){const[t]=Object.keys(e);this._defaultLanguage=t,this._defaultLanguageFirstLevelKeys=[],this._props=e,_(Object.keys(e[this._defaultLanguage])),Object.keys(this._props[this._defaultLanguage]).forEach(n=>{typeof this._props[this._defaultLanguage][n]=="string"&&this._defaultLanguageFirstLevelKeys.push(n)}),this.setLanguage(this._interfaceLanguage),this._opts.pseudo&&this._pseudoAllValues(this._props)}_pseudoAllValues(e){Object.keys(e).forEach(t=>{if(typeof e[t]=="object")this._pseudoAllValues(e[t]);else if(typeof e[t]=="string"){if(e[t].indexOf("[")===0&&e[t].lastIndexOf("]")===e[t].length-1)return;const n=e[t].split(" ");for(let s=0;s<n.length;s+=1)if(!n[s].match(f)){if(!n[s].match(c)){let a=n[s].length;this._opts.pseudoMultipleLanguages&&(a=parseInt(a*1.4,10)),n[s]=L(a)}}e[t]=`[${n.join(" ")}]`}})}setLanguage(e){const t=p(e,this._props),n=Object.keys(this._props)[0];if(this._language=t,this._props[t]){for(let a=0;a<this._defaultLanguageFirstLevelKeys.length;a+=1)delete this[this._defaultLanguageFirstLevelKeys[a]];let s=Object.assign({},this._props[this._language]);Object.keys(s).forEach(a=>{this[a]=s[a]}),n!==this._language&&(s=this._props[n],this._fallbackValues(s,this))}}_fallbackValues(e,t){Object.keys(e).forEach(n=>{Object.prototype.hasOwnProperty.call(e,n)&&!t[n]&&t[n]!==""?(t[n]=e[n],this._opts.logsEnabled&&console.log(`🚧 👷 key '${n}' not found in localizedStrings for language ${this._language} 🚧`)):typeof t[n]!="string"&&this._fallbackValues(e[n],t[n])})}getLanguage(){return this._language}getInterfaceLanguage(){return this._interfaceLanguage}getAvailableLanguages(){return this._availableLanguages||(this._availableLanguages=[],Object.keys(this._props).forEach(e=>{this._availableLanguages.push(e)})),this._availableLanguages}formatString(e,...t){let n=e||"";return typeof n=="string"&&(n=this.getString(e,null,!0)||n),n.split(c).filter(a=>!!a).map(a=>{if(a.match(c)){const r=a.slice(5,-1),l=this.getString(r);return l||(this._opts.logsEnabled&&console.log(`No Localization ref found for '${a}' in string '${e}'`),`$ref(id:${r})`)}return a}).join("").split(f).filter(a=>!!a).map(a=>{if(a.match(f)){const r=a.slice(1,-1);let l=t[r];if(l===void 0){const g=t[0][r];if(g!==void 0)l=g;else return l}return l}return a}).join("")}getString(e,t,n=!1){try{let s=this._props[t||this._language];const a=e.split(".");for(let r=0;r<a.length;r+=1){if(s[a[r]]===void 0)throw Error(a[r]);s=s[a[r]]}return s}catch(s){!n&&this._opts.logsEnabled&&console.log(`No localization found for key '${e}' and language '${t}', failed on ${s.message}`)}return null}getContent(){return this._props}}const d=/(\{[\d|\w]+\})/;return h.prototype.formatString=(i,...e)=>{let t=!1;const n=(i||"").split(d).filter(s=>!!s).map((s,a)=>{if(s.match(d)){const r=s.slice(1,-1);let l=e[r];if(l==null){const g=e[0]?e[0][r]:void 0;if(g!==void 0)l=g;else return l}return u.isValidElement(l)?(t=!0,u.Children.toArray(l).map(g=>({...g,key:a.toString()}))):l}return s});return t?n:n.join("")},h});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-localization",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "description": "Simple module to localize the React interface using the same syntax used in the ReactNativeLocalization module",
5
5
  "type": "module",
6
6
  "main": "./dist/react-localization.umd.js",