react-localization 1.0.19 → 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 +84 -43
- package/dist/react-localization.es.js +216 -0
- package/dist/react-localization.umd.js +1 -0
- package/package.json +35 -20
- package/lib/LocalizedStrings.d.ts +0 -72
- package/lib/LocalizedStrings.js +0 -89
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).
|
@@ -0,0 +1,216 @@
|
|
1
|
+
import f from "react";
|
2
|
+
function h() {
|
3
|
+
const i = "en-US";
|
4
|
+
if (typeof navigator > "u")
|
5
|
+
return i;
|
6
|
+
const e = navigator;
|
7
|
+
if (e) {
|
8
|
+
if (e.language)
|
9
|
+
return e.language;
|
10
|
+
if (e.languages && e.languages[0])
|
11
|
+
return e.languages[0];
|
12
|
+
if (e.userLanguage)
|
13
|
+
return e.userLanguage;
|
14
|
+
if (e.browserLanguage)
|
15
|
+
return e.browserLanguage;
|
16
|
+
}
|
17
|
+
return i;
|
18
|
+
}
|
19
|
+
function d(i, e) {
|
20
|
+
if (e[i]) return i;
|
21
|
+
const t = i.indexOf("-"), a = t >= 0 ? i.substring(0, t) : i;
|
22
|
+
return e[a] ? a : Object.keys(e)[0];
|
23
|
+
}
|
24
|
+
function _(i) {
|
25
|
+
const e = ["_interfaceLanguage", "_language", "_defaultLanguage", "_defaultLanguageFirstLevelKeys", "_props"];
|
26
|
+
i.forEach((t) => {
|
27
|
+
if (e.indexOf(t) !== -1)
|
28
|
+
throw new Error(`${t} cannot be used as a key. It is a reserved word.`);
|
29
|
+
});
|
30
|
+
}
|
31
|
+
function p(i) {
|
32
|
+
let e = "";
|
33
|
+
const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
34
|
+
for (let a = 0; a < i; a += 1) e += t.charAt(Math.floor(Math.random() * t.length));
|
35
|
+
return e;
|
36
|
+
}
|
37
|
+
const g = /(\{[\d|\w]+\})/, o = /(\$ref\{[\w|.]+\})/;
|
38
|
+
class L {
|
39
|
+
/**
|
40
|
+
* Constructor used to provide the strings objects in various language and the optional callback to get
|
41
|
+
* the interface language
|
42
|
+
* @param {*} props - the strings object
|
43
|
+
* @param {Function} options.customLanguageInterface - the optional method to use to get the InterfaceLanguage
|
44
|
+
* @param {Boolean} options.pseudo - convert all strings to pseudo, helpful when implementing
|
45
|
+
* @param {Boolean} options.pseudoMultipleLanguages - add 40% to pseudo, helps with translations in the future
|
46
|
+
* @param {Boolean} options.logsEnabled - Enable/Disable console.log outputs (default=true)
|
47
|
+
*/
|
48
|
+
constructor(e, t) {
|
49
|
+
typeof t == "function" && (t = {
|
50
|
+
customLanguageInterface: t
|
51
|
+
}), this._opts = Object.assign({}, {
|
52
|
+
customLanguageInterface: h,
|
53
|
+
pseudo: !1,
|
54
|
+
pseudoMultipleLanguages: !1,
|
55
|
+
logsEnabled: !0
|
56
|
+
}, t), this._interfaceLanguage = this._opts.customLanguageInterface(), this._language = this._interfaceLanguage, this.setContent(e);
|
57
|
+
}
|
58
|
+
/**
|
59
|
+
* Set the strings objects based on the parameter passed in the constructor
|
60
|
+
* @param {*} props
|
61
|
+
*/
|
62
|
+
setContent(e) {
|
63
|
+
const [t] = Object.keys(e);
|
64
|
+
this._defaultLanguage = t, this._defaultLanguageFirstLevelKeys = [], this._props = e, _(Object.keys(e[this._defaultLanguage])), Object.keys(this._props[this._defaultLanguage]).forEach((a) => {
|
65
|
+
typeof this._props[this._defaultLanguage][a] == "string" && this._defaultLanguageFirstLevelKeys.push(a);
|
66
|
+
}), this.setLanguage(this._interfaceLanguage), this._opts.pseudo && this._pseudoAllValues(this._props);
|
67
|
+
}
|
68
|
+
/**
|
69
|
+
* Replace all strings to pseudo value
|
70
|
+
* @param {Object} obj - Loopable object
|
71
|
+
*/
|
72
|
+
_pseudoAllValues(e) {
|
73
|
+
Object.keys(e).forEach((t) => {
|
74
|
+
if (typeof e[t] == "object")
|
75
|
+
this._pseudoAllValues(e[t]);
|
76
|
+
else if (typeof e[t] == "string") {
|
77
|
+
if (e[t].indexOf("[") === 0 && e[t].lastIndexOf("]") === e[t].length - 1)
|
78
|
+
return;
|
79
|
+
const a = e[t].split(" ");
|
80
|
+
for (let s = 0; s < a.length; s += 1)
|
81
|
+
if (!a[s].match(g)) {
|
82
|
+
if (!a[s].match(o)) {
|
83
|
+
let n = a[s].length;
|
84
|
+
this._opts.pseudoMultipleLanguages && (n = parseInt(n * 1.4, 10)), a[s] = p(n);
|
85
|
+
}
|
86
|
+
}
|
87
|
+
e[t] = `[${a.join(" ")}]`;
|
88
|
+
}
|
89
|
+
});
|
90
|
+
}
|
91
|
+
/**
|
92
|
+
* Can be used from ouside the class to force a particular language
|
93
|
+
* indipendently from the interface one
|
94
|
+
* @param {*} language
|
95
|
+
*/
|
96
|
+
setLanguage(e) {
|
97
|
+
const t = d(e, this._props), a = Object.keys(this._props)[0];
|
98
|
+
if (this._language = t, this._props[t]) {
|
99
|
+
for (let n = 0; n < this._defaultLanguageFirstLevelKeys.length; n += 1)
|
100
|
+
delete this[this._defaultLanguageFirstLevelKeys[n]];
|
101
|
+
let s = Object.assign({}, this._props[this._language]);
|
102
|
+
Object.keys(s).forEach((n) => {
|
103
|
+
this[n] = s[n];
|
104
|
+
}), a !== this._language && (s = this._props[a], this._fallbackValues(s, this));
|
105
|
+
}
|
106
|
+
}
|
107
|
+
/**
|
108
|
+
* Load fallback values for missing translations
|
109
|
+
* @param {*} defaultStrings
|
110
|
+
* @param {*} strings
|
111
|
+
*/
|
112
|
+
_fallbackValues(e, t) {
|
113
|
+
Object.keys(e).forEach((a) => {
|
114
|
+
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]);
|
115
|
+
});
|
116
|
+
}
|
117
|
+
/**
|
118
|
+
* The current language displayed (could differ from the interface language
|
119
|
+
* if it has been forced manually and a matching translation has been found)
|
120
|
+
*/
|
121
|
+
getLanguage() {
|
122
|
+
return this._language;
|
123
|
+
}
|
124
|
+
/**
|
125
|
+
* The current interface language (could differ from the language displayed)
|
126
|
+
*/
|
127
|
+
getInterfaceLanguage() {
|
128
|
+
return this._interfaceLanguage;
|
129
|
+
}
|
130
|
+
/**
|
131
|
+
* Return an array containing the available languages passed as props in the constructor
|
132
|
+
*/
|
133
|
+
getAvailableLanguages() {
|
134
|
+
return this._availableLanguages || (this._availableLanguages = [], Object.keys(this._props).forEach((e) => {
|
135
|
+
this._availableLanguages.push(e);
|
136
|
+
})), this._availableLanguages;
|
137
|
+
}
|
138
|
+
// Format the passed string replacing the numbered or tokenized placeholders
|
139
|
+
// eg. 1: I'd like some {0} and {1}, or just {0}
|
140
|
+
// eg. 2: I'd like some {bread} and {butter}, or just {bread}
|
141
|
+
// eg. 3: I'd like some $ref{bread} and $ref{butter}, or just $ref{bread}
|
142
|
+
// Use example:
|
143
|
+
// eg. 1: strings.formatString(strings.question, strings.bread, strings.butter)
|
144
|
+
// eg. 2: strings.formatString(strings.question, { bread: strings.bread, butter: strings.butter })
|
145
|
+
// eg. 3: strings.formatString(strings.question)
|
146
|
+
formatString(e, ...t) {
|
147
|
+
let a = e || "";
|
148
|
+
return typeof a == "string" && (a = this.getString(e, null, !0) || a), a.split(o).filter((n) => !!n).map((n) => {
|
149
|
+
if (n.match(o)) {
|
150
|
+
const l = n.slice(5, -1), r = this.getString(l);
|
151
|
+
return r || (this._opts.logsEnabled && console.log(`No Localization ref found for '${n}' in string '${e}'`), `$ref(id:${l})`);
|
152
|
+
}
|
153
|
+
return n;
|
154
|
+
}).join("").split(g).filter((n) => !!n).map((n) => {
|
155
|
+
if (n.match(g)) {
|
156
|
+
const l = n.slice(1, -1);
|
157
|
+
let r = t[l];
|
158
|
+
if (r === void 0) {
|
159
|
+
const u = t[0][l];
|
160
|
+
if (u !== void 0)
|
161
|
+
r = u;
|
162
|
+
else
|
163
|
+
return r;
|
164
|
+
}
|
165
|
+
return r;
|
166
|
+
}
|
167
|
+
return n;
|
168
|
+
}).join("");
|
169
|
+
}
|
170
|
+
// Return a string with the passed key in a different language or defalt if not set
|
171
|
+
// We allow deep . notation for finding strings
|
172
|
+
getString(e, t, a = !1) {
|
173
|
+
try {
|
174
|
+
let s = this._props[t || this._language];
|
175
|
+
const n = e.split(".");
|
176
|
+
for (let l = 0; l < n.length; l += 1) {
|
177
|
+
if (s[n[l]] === void 0)
|
178
|
+
throw Error(n[l]);
|
179
|
+
s = s[n[l]];
|
180
|
+
}
|
181
|
+
return s;
|
182
|
+
} catch (s) {
|
183
|
+
!a && this._opts.logsEnabled && console.log(`No localization found for key '${e}' and language '${t}', failed on ${s.message}`);
|
184
|
+
}
|
185
|
+
return null;
|
186
|
+
}
|
187
|
+
/**
|
188
|
+
* The current props (locale object)
|
189
|
+
*/
|
190
|
+
getContent() {
|
191
|
+
return this._props;
|
192
|
+
}
|
193
|
+
}
|
194
|
+
const c = /(\{[\d|\w]+\})/;
|
195
|
+
L.prototype.formatString = (i, ...e) => {
|
196
|
+
let t = !1;
|
197
|
+
const a = (i || "").split(c).filter((s) => !!s).map((s, n) => {
|
198
|
+
if (s.match(c)) {
|
199
|
+
const l = s.slice(1, -1);
|
200
|
+
let r = e[l];
|
201
|
+
if (r == null) {
|
202
|
+
const u = e[0] ? e[0][l] : void 0;
|
203
|
+
if (u !== void 0)
|
204
|
+
r = u;
|
205
|
+
else
|
206
|
+
return r;
|
207
|
+
}
|
208
|
+
return f.isValidElement(r) ? (t = !0, f.Children.toArray(r).map((u) => ({ ...u, key: n.toString() }))) : r;
|
209
|
+
}
|
210
|
+
return s;
|
211
|
+
});
|
212
|
+
return t ? a : a.join("");
|
213
|
+
};
|
214
|
+
export {
|
215
|
+
L as default
|
216
|
+
};
|
@@ -0,0 +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("-"),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,11 +1,24 @@
|
|
1
1
|
{
|
2
2
|
"name": "react-localization",
|
3
|
-
"version": "
|
4
|
-
"description": "Simple module to localize the React interface using the same syntax used in the ReactNativeLocalization module
|
3
|
+
"version": "2.0.2",
|
4
|
+
"description": "Simple module to localize the React interface using the same syntax used in the ReactNativeLocalization module",
|
5
|
+
"type": "module",
|
6
|
+
"main": "./dist/react-localization.umd.js",
|
7
|
+
"module": "./dist/react-localization.es.js",
|
8
|
+
"types": "./dist/LocalizedStrings.d.ts",
|
9
|
+
"exports": {
|
10
|
+
".": {
|
11
|
+
"import": "./dist/react-localization.es.js"
|
12
|
+
}
|
13
|
+
},
|
14
|
+
"files": [
|
15
|
+
"dist"
|
16
|
+
],
|
5
17
|
"scripts": {
|
6
|
-
"
|
7
|
-
"
|
8
|
-
"
|
18
|
+
"dev": "vite",
|
19
|
+
"build": "tsc && vite build",
|
20
|
+
"test": "vitest",
|
21
|
+
"prepare": "npm run build"
|
9
22
|
},
|
10
23
|
"repository": {
|
11
24
|
"type": "git",
|
@@ -17,30 +30,32 @@
|
|
17
30
|
"localization",
|
18
31
|
"internationalization",
|
19
32
|
"javascript",
|
20
|
-
"typescript"
|
21
|
-
"react",
|
22
|
-
"react-component"
|
33
|
+
"typescript"
|
23
34
|
],
|
24
|
-
"main": "./lib/LocalizedStrings.js",
|
25
|
-
"types": "./lib/LocalizedStrings.d.ts",
|
26
35
|
"author": "Stefano Falda <stefano.falda@gmail.com> (http://www.babisoft.com)",
|
27
36
|
"license": "MIT",
|
28
37
|
"bugs": {
|
29
38
|
"url": "https://github.com/stefalda/react-localization/issues"
|
30
39
|
},
|
31
40
|
"homepage": "https://github.com/stefalda/react-localization#readme",
|
41
|
+
"peerDependencies": {
|
42
|
+
"react": "^19.0.0",
|
43
|
+
"react-dom": "^19.0.0"
|
44
|
+
},
|
32
45
|
"devDependencies": {
|
33
|
-
"
|
34
|
-
"
|
35
|
-
"
|
36
|
-
"
|
37
|
-
"
|
38
|
-
"react": "^
|
46
|
+
"@testing-library/react": "^16.1.0",
|
47
|
+
"@types/node": "^22.10.5",
|
48
|
+
"@types/react": "^19.0.4",
|
49
|
+
"@types/react-dom": "^19.0.2",
|
50
|
+
"@vitejs/plugin-react": "^4.3.4",
|
51
|
+
"react": "^19.0.0",
|
52
|
+
"react-dom": "^19.0.0",
|
53
|
+
"typescript": "^5.7.3",
|
54
|
+
"vite": "^6.0.7",
|
55
|
+
"vitest": "^2.1.8",
|
56
|
+
"jsdom": "^26.0.0"
|
39
57
|
},
|
40
58
|
"dependencies": {
|
41
|
-
"localized-strings": "^0.
|
42
|
-
},
|
43
|
-
"peerDependencies": {
|
44
|
-
"react": "^18.0.0 || ^17.0.0 || ^16.0.0 || ^15.6.0"
|
59
|
+
"localized-strings": "^1.0.0"
|
45
60
|
}
|
46
61
|
}
|
@@ -1,72 +0,0 @@
|
|
1
|
-
declare module 'react-localization' {
|
2
|
-
type Formatted = number | string | JSX.Element;
|
3
|
-
type FormatObject<U extends Formatted> = { [key: string]: U };
|
4
|
-
|
5
|
-
export interface GlobalStrings<T> {
|
6
|
-
[language: string]: T;
|
7
|
-
}
|
8
|
-
|
9
|
-
export interface LocalizedStringsMethods {
|
10
|
-
/**
|
11
|
-
* Can be used from ouside the class to force a particular language
|
12
|
-
* independently from the interface one
|
13
|
-
* @param language
|
14
|
-
*/
|
15
|
-
setLanguage(language: string): void;
|
16
|
-
|
17
|
-
/**
|
18
|
-
* The current language displayed (could differ from the interface language
|
19
|
-
* if it has been forced manually and a matching translation has been found)
|
20
|
-
*/
|
21
|
-
getLanguage(): string;
|
22
|
-
|
23
|
-
/**
|
24
|
-
* The current interface language (could differ from the language displayed)
|
25
|
-
*/
|
26
|
-
getInterfaceLanguage(): string;
|
27
|
-
|
28
|
-
/**
|
29
|
-
* Format the passed string replacing the numbered placeholders
|
30
|
-
* i.e. I'd like some {0} and {1}, or just {0}
|
31
|
-
* Use example:
|
32
|
-
* strings.formatString(strings.question, strings.bread, strings.butter)
|
33
|
-
*/
|
34
|
-
formatString<T extends Formatted>(str: string, ...values: Array<T | FormatObject<T>>): Array<string | T> | string;
|
35
|
-
|
36
|
-
/**
|
37
|
-
* Return an array containing the available languages passed as props in the constructor
|
38
|
-
*/
|
39
|
-
getAvailableLanguages(): string[];
|
40
|
-
|
41
|
-
/**
|
42
|
-
* Return a string with the passed key in a different language
|
43
|
-
* @param key
|
44
|
-
* @param language
|
45
|
-
*/
|
46
|
-
getString(key: string, language?: string, omitWarning?: boolean): string;
|
47
|
-
|
48
|
-
/**
|
49
|
-
* Replace the NamedLocalization object without reinstantiating the object
|
50
|
-
* @param props
|
51
|
-
*/
|
52
|
-
setContent(props: any): void;
|
53
|
-
}
|
54
|
-
|
55
|
-
export type LocalizedStrings<T> = LocalizedStringsMethods & T;
|
56
|
-
|
57
|
-
type GetInterfaceLanguageCallback = () => string;
|
58
|
-
|
59
|
-
interface Options {
|
60
|
-
customLanguageInterface?: GetInterfaceLanguageCallback;
|
61
|
-
logsEnabled?: boolean;
|
62
|
-
pseudo?: boolean;
|
63
|
-
pseudoMultipleLanguages?: boolean;
|
64
|
-
}
|
65
|
-
|
66
|
-
interface LocalizedStringsFactory {
|
67
|
-
new <T>(props: GlobalStrings<T>, options?: Options): LocalizedStrings<T>;
|
68
|
-
}
|
69
|
-
|
70
|
-
var LocalizedStrings: LocalizedStringsFactory;
|
71
|
-
export default LocalizedStrings;
|
72
|
-
}
|
package/lib/LocalizedStrings.js
DELETED
@@ -1,89 +0,0 @@
|
|
1
|
-
'use strict';
|
2
|
-
/**
|
3
|
-
* Simple module to localize the React interface using the same syntax
|
4
|
-
* used in the ReactNativeLocalization module
|
5
|
-
* (https://github.com/stefalda/ReactNativeLocalization)
|
6
|
-
*
|
7
|
-
* Originally developed by Stefano Falda (stefano.falda@gmail.com)
|
8
|
-
*
|
9
|
-
* It uses a call to the Navigator/Browser object to get the current interface language,
|
10
|
-
* then display the correct language strings or the default language (the first
|
11
|
-
* one if a match is not found).
|
12
|
-
*
|
13
|
-
* This library has been refactored to use the newly created localized-strings package so to
|
14
|
-
* unify the code and make it easier to mantain
|
15
|
-
*
|
16
|
-
* How to use:
|
17
|
-
* Check the instructions at:
|
18
|
-
* https://github.com/stefalda/react-localization
|
19
|
-
*/
|
20
|
-
|
21
|
-
Object.defineProperty(exports, "__esModule", {
|
22
|
-
value: true
|
23
|
-
});
|
24
|
-
|
25
|
-
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
|
26
|
-
|
27
|
-
var _react = require('react');
|
28
|
-
|
29
|
-
var _react2 = _interopRequireDefault(_react);
|
30
|
-
|
31
|
-
var _localizedStrings = require('localized-strings');
|
32
|
-
|
33
|
-
var _localizedStrings2 = _interopRequireDefault(_localizedStrings);
|
34
|
-
|
35
|
-
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
36
|
-
|
37
|
-
var placeholderRegex = /(\{[\d|\w]+\})/;
|
38
|
-
|
39
|
-
/**
|
40
|
-
* Format the passed string replacing the numbered or tokenized placeholders
|
41
|
-
* eg. 1: I'd like some {0} and {1}, or just {0}
|
42
|
-
* eg. 2: I'd like some {bread} and {butter}, or just {bread}
|
43
|
-
* Use example:
|
44
|
-
* eg. 1: strings.formatString(strings.question, strings.bread, strings.butter)
|
45
|
-
* eg. 2: strings.formatString(strings.question, { bread: strings.bread, butter: strings.butter }
|
46
|
-
*
|
47
|
-
* THIS METHOD OVERRIDE the one of the parent class by adding support for JSX code
|
48
|
-
*/
|
49
|
-
_localizedStrings2.default.prototype.formatString = function (str) {
|
50
|
-
for (var _len = arguments.length, valuesForPlaceholders = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
|
51
|
-
valuesForPlaceholders[_key - 1] = arguments[_key];
|
52
|
-
}
|
53
|
-
|
54
|
-
var hasObject = false;
|
55
|
-
var res = (str || '').split(placeholderRegex).filter(function (textPart) {
|
56
|
-
return !!textPart;
|
57
|
-
}).map(function (textPart, index) {
|
58
|
-
if (textPart.match(placeholderRegex)) {
|
59
|
-
var matchedKey = textPart.slice(1, -1);
|
60
|
-
var valueForPlaceholder = valuesForPlaceholders[matchedKey];
|
61
|
-
|
62
|
-
// If no value found, check if working with an object instead
|
63
|
-
if (valueForPlaceholder == undefined) {
|
64
|
-
var valueFromObjectPlaceholder = valuesForPlaceholders[0][matchedKey];
|
65
|
-
if (valueFromObjectPlaceholder !== undefined) {
|
66
|
-
valueForPlaceholder = valueFromObjectPlaceholder;
|
67
|
-
} else {
|
68
|
-
// If value still isn't found, then it must have been undefined/null
|
69
|
-
return valueForPlaceholder;
|
70
|
-
}
|
71
|
-
}
|
72
|
-
|
73
|
-
if (_react2.default.isValidElement(valueForPlaceholder)) {
|
74
|
-
hasObject = true;
|
75
|
-
return _react2.default.Children.toArray(valueForPlaceholder).map(function (component) {
|
76
|
-
return _extends({}, component, { key: index.toString() });
|
77
|
-
});
|
78
|
-
}
|
79
|
-
|
80
|
-
return valueForPlaceholder;
|
81
|
-
}
|
82
|
-
return textPart;
|
83
|
-
});
|
84
|
-
// If the results contains a object return an array otherwise return a string
|
85
|
-
if (hasObject) return res;
|
86
|
-
return res.join('');
|
87
|
-
};
|
88
|
-
|
89
|
-
exports.default = _localizedStrings2.default;
|