react-localization 2.0.1 → 2.0.3
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 +84 -43
- package/dist/react-localization.es.js +1 -1
- package/dist/react-localization.umd.js +1 -1
- package/package.json +11 -3
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
|
-
|
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
|
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
|
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
|
-
|
41
|
+
```js
|
25
42
|
// ES6 module syntax
|
26
|
-
import LocalizedStrings from
|
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
|
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
|
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
|
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
|
-
|
74
|
-
|
75
|
-
|
76
|
-
|
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
|
-
|
112
|
-
|
113
|
-
|
114
|
-
|
115
|
-
|
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
|
-
|
120
|
-
|
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
|
-
|
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
|
-
|
136
|
-
|
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
|
-
|
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).
|
@@ -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("-"),
|
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.
|
3
|
+
"version": "2.0.3",
|
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",
|
@@ -39,8 +39,8 @@
|
|
39
39
|
},
|
40
40
|
"homepage": "https://github.com/stefalda/react-localization#readme",
|
41
41
|
"peerDependencies": {
|
42
|
-
"react": "
|
43
|
-
"react-dom": "
|
42
|
+
"react": ">=19.0.0",
|
43
|
+
"react-dom": ">=19.0.0"
|
44
44
|
},
|
45
45
|
"devDependencies": {
|
46
46
|
"@testing-library/react": "^16.1.0",
|
@@ -57,5 +57,13 @@
|
|
57
57
|
},
|
58
58
|
"dependencies": {
|
59
59
|
"localized-strings": "^1.0.0"
|
60
|
+
},
|
61
|
+
"peerDependenciesMeta": {
|
62
|
+
"react": {
|
63
|
+
"optional": true
|
64
|
+
},
|
65
|
+
"react-dom": {
|
66
|
+
"optional": true
|
67
|
+
}
|
60
68
|
}
|
61
69
|
}
|