react-native-i18njs 0.0.2 → 1.0.0

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/dist/index.mjs CHANGED
@@ -1,497 +1 @@
1
- import { I18n } from 'i18n-js';
2
- import * as RNLocalize from 'react-native-localize';
3
- import { I18nManager, AppState, Text } from 'react-native';
4
- import React, { createContext, useState, useEffect, useMemo, useContext, isValidElement, Fragment, cloneElement } from 'react';
5
-
6
- var __defProp = Object.defineProperty;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
9
- var RTL_SCRIPTS = /* @__PURE__ */ new Set(["Arab", "Hebr", "Thaa", "Syrc", "Nkoo", "Adlm"]);
10
- var RTL_LANGUAGE_CODES = /* @__PURE__ */ new Set([
11
- "ar",
12
- // Arabic
13
- "fa",
14
- // Persian
15
- "he",
16
- // Hebrew
17
- "iw",
18
- // Hebrew (legacy)
19
- "ur",
20
- // Urdu
21
- "ps",
22
- // Pashto
23
- "dv",
24
- // Divehi
25
- "ku",
26
- // Kurdish
27
- "ug",
28
- // Uyghur
29
- "yi",
30
- // Yiddish
31
- "sd"
32
- // Sindhi
33
- ]);
34
- var DefaultI18nEngine = class {
35
- constructor() {
36
- __publicField(this, "i18n");
37
- __publicField(this, "listeners");
38
- __publicField(this, "onLocaleChange");
39
- __publicField(this, "fallbackLocales");
40
- __publicField(this, "missingBehavior");
41
- __publicField(this, "onMissingKey");
42
- __publicField(this, "enableFallback");
43
- __publicField(this, "followSystem");
44
- __publicField(this, "localeSource");
45
- __publicField(this, "initialized");
46
- __publicField(this, "version");
47
- __publicField(this, "readyPromise");
48
- __publicField(this, "resolveReady");
49
- this.i18n = new I18n();
50
- this.listeners = /* @__PURE__ */ new Set();
51
- this.i18n.enableFallback = false;
52
- this.missingBehavior = "key";
53
- this.enableFallback = true;
54
- this.followSystem = true;
55
- this.localeSource = "system";
56
- this.initialized = false;
57
- this.version = 0;
58
- this.readyPromise = new Promise((resolve) => {
59
- this.resolveReady = resolve;
60
- });
61
- }
62
- init(translations, options = {}) {
63
- var _a;
64
- const {
65
- defaultLocale = "en",
66
- enableFallback = true,
67
- onLocaleChange,
68
- fallbackLocales,
69
- followSystem = true,
70
- missingBehavior = "key",
71
- onMissingKey
72
- } = options;
73
- this.i18n.store(this.normalizeTranslations(translations));
74
- this.i18n.defaultLocale = this.normalizeLocaleTag(defaultLocale);
75
- this.i18n.locale = this.normalizeLocaleTag(defaultLocale);
76
- this.enableFallback = enableFallback;
77
- this.onLocaleChange = onLocaleChange;
78
- this.fallbackLocales = fallbackLocales;
79
- this.followSystem = followSystem;
80
- this.localeSource = "system";
81
- this.missingBehavior = missingBehavior;
82
- this.onMissingKey = onMissingKey;
83
- if (this.followSystem) this.updateLocale();
84
- this.version += 1;
85
- this.notifyListeners({ type: "translations", version: this.version });
86
- if (!this.initialized) {
87
- this.initialized = true;
88
- (_a = this.resolveReady) == null ? void 0 : _a.call(this);
89
- this.resolveReady = void 0;
90
- }
91
- }
92
- loadTranslations(translations) {
93
- this.i18n.store(this.normalizeTranslations(translations));
94
- this.version += 1;
95
- this.notifyListeners({ type: "translations", version: this.version });
96
- }
97
- updateLocale() {
98
- if (!this.followSystem) return;
99
- if (this.localeSource === "user") return;
100
- let locales = [];
101
- try {
102
- locales = RNLocalize.getLocales();
103
- } catch {
104
- return;
105
- }
106
- if (!locales || locales.length === 0) return;
107
- const systemLocale = this.normalizeLocaleTag(locales[0].languageTag);
108
- if (!systemLocale) return;
109
- this.setLocaleFromSystem(systemLocale);
110
- }
111
- setLocale(locale) {
112
- this.localeSource = "user";
113
- this.applyLocale(locale);
114
- }
115
- getLocale() {
116
- return this.i18n.locale;
117
- }
118
- t(scope, options) {
119
- var _a, _b, _c;
120
- if (typeof scope !== "string") {
121
- return (_a = this.normalizeTranslateResult(this.i18n.t(scope, options))) != null ? _a : "";
122
- }
123
- const key = scope;
124
- const currentLocale = this.i18n.locale;
125
- const chain = this.enableFallback ? this.getLocaleChain(currentLocale) : [currentLocale];
126
- for (const locale of chain) {
127
- if (this.hasTranslation(locale, key)) {
128
- const translated = this.normalizeTranslateResult(
129
- this.translateAtLocale(locale, scope, options)
130
- );
131
- if (translated !== void 0) return translated;
132
- }
133
- }
134
- (_b = this.onMissingKey) == null ? void 0 : _b.call(this, key, currentLocale);
135
- if (options && Object.prototype.hasOwnProperty.call(options, "defaultValue")) {
136
- return (_c = this.normalizeTranslateResult(
137
- this.translateAtLocale(currentLocale, scope, options)
138
- )) != null ? _c : "";
139
- }
140
- if (this.missingBehavior === "empty") return "";
141
- if (this.missingBehavior === "throw") {
142
- throw new Error(`Missing translation: ${currentLocale}.${key}`);
143
- }
144
- return key;
145
- }
146
- formatNumber(n, options) {
147
- if (typeof Intl === "undefined" || typeof Intl.NumberFormat !== "function") {
148
- return String(n);
149
- }
150
- try {
151
- return new Intl.NumberFormat(this.i18n.locale, options).format(n);
152
- } catch {
153
- return String(n);
154
- }
155
- }
156
- formatCurrency(n, currency, options) {
157
- if (typeof Intl === "undefined" || typeof Intl.NumberFormat !== "function") {
158
- return `${n} ${currency}`;
159
- }
160
- try {
161
- return new Intl.NumberFormat(this.i18n.locale, {
162
- ...options,
163
- style: "currency",
164
- currency
165
- }).format(n);
166
- } catch {
167
- return `${n} ${currency}`;
168
- }
169
- }
170
- formatDate(date, options) {
171
- const d = typeof date === "number" ? new Date(date) : date;
172
- if (Number.isNaN(d.getTime())) return "";
173
- if (typeof Intl === "undefined" || typeof Intl.DateTimeFormat !== "function") {
174
- return d.toISOString();
175
- }
176
- try {
177
- return new Intl.DateTimeFormat(this.i18n.locale, options).format(d);
178
- } catch {
179
- return d.toISOString();
180
- }
181
- }
182
- subscribe(listener) {
183
- this.listeners.add(listener);
184
- return () => {
185
- this.listeners.delete(listener);
186
- };
187
- }
188
- isRTL() {
189
- return I18nManager.isRTL;
190
- }
191
- ready() {
192
- if (this.initialized) return Promise.resolve();
193
- return this.readyPromise;
194
- }
195
- isReady() {
196
- return this.initialized;
197
- }
198
- handleRTL(locale) {
199
- var _a, _b;
200
- const isRTL = this.isRTLLocale(locale);
201
- if (typeof ((_a = I18nManager) == null ? void 0 : _a.allowRTL) !== "function" || typeof ((_b = I18nManager) == null ? void 0 : _b.forceRTL) !== "function") {
202
- return;
203
- }
204
- if (I18nManager.isRTL !== isRTL) {
205
- I18nManager.allowRTL(isRTL);
206
- I18nManager.forceRTL(isRTL);
207
- }
208
- }
209
- notifyListeners(change) {
210
- this.listeners.forEach((listener) => listener(this.i18n.locale, change));
211
- }
212
- setLocaleFromSystem(locale) {
213
- this.localeSource = "system";
214
- this.applyLocale(locale);
215
- }
216
- applyLocale(locale) {
217
- var _a;
218
- const normalizedLocale = this.normalizeLocaleTag(locale);
219
- if (this.i18n.locale !== normalizedLocale) {
220
- this.i18n.locale = normalizedLocale;
221
- this.handleRTL(normalizedLocale);
222
- this.version += 1;
223
- this.notifyListeners({ type: "locale", version: this.version });
224
- (_a = this.onLocaleChange) == null ? void 0 : _a.call(this, normalizedLocale);
225
- }
226
- }
227
- translateAtLocale(locale, scope, options) {
228
- const prevLocale = this.i18n.locale;
229
- this.i18n.locale = locale;
230
- try {
231
- return this.i18n.t(scope, options);
232
- } finally {
233
- this.i18n.locale = prevLocale;
234
- }
235
- }
236
- getLocaleChain(locale) {
237
- const chain = [];
238
- const normalizedLocale = this.normalizeLocaleTag(locale);
239
- chain.push(normalizedLocale);
240
- const parts = normalizedLocale.split("-").filter(Boolean);
241
- for (let i = parts.length - 1; i >= 1; i -= 1) {
242
- chain.push(parts.slice(0, i).join("-"));
243
- }
244
- const extra = this.fallbackLocales ? typeof this.fallbackLocales === "function" ? this.fallbackLocales(normalizedLocale) : this.fallbackLocales : [];
245
- for (const l of extra) {
246
- const normalizedFallback = this.normalizeLocaleTag(l);
247
- chain.push(normalizedFallback);
248
- const fallbackParts = normalizedFallback.split("-").filter(Boolean);
249
- for (let i = fallbackParts.length - 1; i >= 1; i -= 1) {
250
- chain.push(fallbackParts.slice(0, i).join("-"));
251
- }
252
- }
253
- if (this.i18n.defaultLocale) {
254
- const normalizedDefault = this.normalizeLocaleTag(this.i18n.defaultLocale);
255
- chain.push(normalizedDefault);
256
- const defaultParts = normalizedDefault.split("-").filter(Boolean);
257
- for (let i = defaultParts.length - 1; i >= 1; i -= 1) {
258
- chain.push(defaultParts.slice(0, i).join("-"));
259
- }
260
- }
261
- const seen = /* @__PURE__ */ new Set();
262
- return chain.filter((l) => {
263
- if (!l) return false;
264
- const normalized = l;
265
- if (seen.has(normalized)) return false;
266
- seen.add(normalized);
267
- return true;
268
- });
269
- }
270
- hasTranslation(locale, key) {
271
- var _a;
272
- const table = (_a = this.i18n.translations) == null ? void 0 : _a[locale];
273
- if (!table || typeof table !== "object") return false;
274
- if (!key.includes(".") && Object.prototype.hasOwnProperty.call(table, key)) {
275
- const direct = table[key];
276
- return direct !== null && direct !== void 0;
277
- }
278
- const parts = key.split(".").filter(Boolean);
279
- let node = table;
280
- for (const part of parts) {
281
- if (!node || typeof node !== "object" || !(part in node)) return false;
282
- node = node[part];
283
- }
284
- return node !== null && node !== void 0;
285
- }
286
- normalizeTranslateResult(value) {
287
- if (typeof value === "string") return value;
288
- if (typeof value === "number") return String(value);
289
- return void 0;
290
- }
291
- normalizeLocaleTag(tag) {
292
- return tag.replace(/_/g, "-");
293
- }
294
- normalizeTranslations(translations) {
295
- const normalized = {};
296
- for (const key of Object.keys(translations)) {
297
- normalized[this.normalizeLocaleTag(key)] = translations[key];
298
- }
299
- return normalized;
300
- }
301
- isRTLLocale(locale) {
302
- var _a;
303
- const normalized = locale.replace(/_/g, "-");
304
- const parts = normalized.split("-").filter(Boolean);
305
- const languageCode = (_a = parts[0]) == null ? void 0 : _a.toLowerCase();
306
- if (!languageCode) return false;
307
- const scriptSubtag = parts.find((part) => /^[A-Za-z]{4}$/.test(part));
308
- if (scriptSubtag) {
309
- const script = scriptSubtag[0].toUpperCase() + scriptSubtag.slice(1).toLowerCase();
310
- return RTL_SCRIPTS.has(script);
311
- }
312
- return RTL_LANGUAGE_CODES.has(languageCode);
313
- }
314
- };
315
- var i18nService = new DefaultI18nEngine();
316
- var DEFAULT_I18N_CONTEXT = {
317
- locale: i18nService.getLocale(),
318
- setLocale: (locale) => i18nService.setLocale(locale),
319
- t: (scope, options) => i18nService.t(scope, options),
320
- formatNumber: (n, o) => i18nService.formatNumber(n, o),
321
- formatCurrency: (n, c, o) => i18nService.formatCurrency(n, c, o),
322
- formatDate: (d, o) => i18nService.formatDate(d, o)
323
- };
324
- var I18nContext = createContext(DEFAULT_I18N_CONTEXT);
325
- var I18nProvider = ({ children, readyGate, fallback }) => {
326
- const [locale, setLocaleState] = useState(i18nService.getLocale());
327
- const [version, setVersion] = useState(0);
328
- const [ready, setReady] = useState(i18nService.isReady());
329
- useEffect(() => {
330
- const unsubscribe = i18nService.subscribe((newLocale, change) => {
331
- setLocaleState(newLocale);
332
- setVersion((prev) => {
333
- var _a;
334
- return (_a = change == null ? void 0 : change.version) != null ? _a : prev + 1;
335
- });
336
- });
337
- return () => unsubscribe();
338
- }, []);
339
- useEffect(() => {
340
- var _a, _b;
341
- const handler = (state) => {
342
- if (state === "active") {
343
- i18nService.updateLocale();
344
- }
345
- };
346
- const subscription = (_b = (_a = AppState) == null ? void 0 : _a.addEventListener) == null ? void 0 : _b.call(_a, "change", handler);
347
- return () => {
348
- var _a2, _b2;
349
- if (typeof (subscription == null ? void 0 : subscription.remove) === "function") {
350
- subscription.remove();
351
- return;
352
- }
353
- (_b2 = (_a2 = AppState) == null ? void 0 : _a2.removeEventListener) == null ? void 0 : _b2.call(_a2, "change", handler);
354
- };
355
- }, []);
356
- useEffect(() => {
357
- if (!readyGate) return;
358
- let cancelled = false;
359
- i18nService.ready().then(() => {
360
- if (!cancelled) setReady(true);
361
- });
362
- return () => {
363
- cancelled = true;
364
- };
365
- }, [readyGate]);
366
- const value = useMemo(() => ({
367
- locale,
368
- setLocale: (l) => i18nService.setLocale(l),
369
- t: (scope, options) => i18nService.t(scope, options),
370
- formatNumber: (n, o) => i18nService.formatNumber(n, o),
371
- formatCurrency: (n, c, o) => i18nService.formatCurrency(n, c, o),
372
- formatDate: (d, o) => i18nService.formatDate(d, o)
373
- }), [locale, version]);
374
- if (readyGate && !ready) return /* @__PURE__ */ React.createElement(React.Fragment, null, fallback != null ? fallback : null);
375
- return /* @__PURE__ */ React.createElement(I18nContext.Provider, { value }, children);
376
- };
377
- function withI18n(Component) {
378
- return function WithI18n(props) {
379
- return /* @__PURE__ */ React.createElement(I18nContext.Consumer, null, (context) => {
380
- if (context === DEFAULT_I18N_CONTEXT) {
381
- throw new Error("withI18n must be used within an I18nProvider");
382
- }
383
- return /* @__PURE__ */ React.createElement(Component, { ...props, ...context });
384
- });
385
- };
386
- }
387
- function useI18n() {
388
- const context = useContext(I18nContext);
389
- if (context === DEFAULT_I18N_CONTEXT) {
390
- throw new Error("useI18n must be used within an I18nProvider");
391
- }
392
- return useMemo(() => {
393
- const t2 = (scope, options) => {
394
- return context.t(scope, options);
395
- };
396
- return {
397
- ...context,
398
- t: t2
399
- };
400
- }, [context]);
401
- }
402
- var escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
403
- var parseString = (input) => {
404
- var _a;
405
- const root = { type: "tag", name: "root", children: [] };
406
- const stack = [root];
407
- const tagRegex = /<(\/?)([A-Za-z][\w-]*)(?:\s[^>]*?)?(\/?)>/g;
408
- let lastIndex = 0;
409
- for (const match of input.matchAll(tagRegex)) {
410
- const fullMatch = match[0];
411
- const isClosing = match[1] === "/";
412
- const tagName = match[2];
413
- const isSelfClosing = match[3] === "/" || fullMatch.endsWith("/>");
414
- const index = (_a = match.index) != null ? _a : 0;
415
- if (index > lastIndex) {
416
- const text = input.slice(lastIndex, index);
417
- if (text) stack[stack.length - 1].children.push({ type: "text", content: text });
418
- }
419
- if (isClosing) {
420
- if (stack.length > 1 && stack[stack.length - 1].name === tagName) {
421
- stack.pop();
422
- } else {
423
- stack[stack.length - 1].children.push({ type: "text", content: fullMatch });
424
- }
425
- } else if (isSelfClosing) {
426
- stack[stack.length - 1].children.push({ type: "tag", name: tagName, children: [] });
427
- } else {
428
- const node = { type: "tag", name: tagName, children: [] };
429
- stack[stack.length - 1].children.push(node);
430
- stack.push(node);
431
- }
432
- lastIndex = index + fullMatch.length;
433
- }
434
- if (lastIndex < input.length) {
435
- stack[stack.length - 1].children.push({ type: "text", content: input.slice(lastIndex) });
436
- }
437
- return root.children;
438
- };
439
- var Trans = ({ i18nKey, values, components, ...props }) => {
440
- const { t: t2 } = useI18n();
441
- const stringValues = {};
442
- const placeholderToElement = {};
443
- if (values) {
444
- Object.keys(values).forEach((key) => {
445
- const value = values[key];
446
- if (isValidElement(value)) {
447
- const placeholder = `__ELEMENT_${key}__`;
448
- placeholderToElement[placeholder] = value;
449
- stringValues[key] = placeholder;
450
- } else {
451
- stringValues[key] = value == null ? "" : String(value);
452
- }
453
- });
454
- }
455
- const translatedText = t2(i18nKey, stringValues);
456
- const ast = parseString(translatedText);
457
- const renderAST = (nodes, keyPrefix) => {
458
- return nodes.map((node, index) => {
459
- const key = `${keyPrefix}-${index}`;
460
- if (node.type === "text") {
461
- const placeholders = Object.keys(placeholderToElement);
462
- if (placeholders.length === 0) return node.content;
463
- const pattern = new RegExp(`(${placeholders.map(escapeRegExp).join("|")})`, "g");
464
- const parts = node.content.split(pattern);
465
- if (parts.length === 1) return node.content;
466
- return /* @__PURE__ */ React.createElement(Fragment, { key }, parts.map((part, i) => {
467
- if (placeholderToElement[part]) {
468
- return cloneElement(placeholderToElement[part], { key: `${key}-${i}` });
469
- }
470
- return part;
471
- }));
472
- } else if (node.type === "tag") {
473
- const Component = components == null ? void 0 : components[node.name];
474
- const children2 = renderAST(node.children, key);
475
- if (isValidElement(Component)) {
476
- return cloneElement(Component, { key }, children2.length > 0 ? children2 : void 0);
477
- }
478
- return /* @__PURE__ */ React.createElement(Fragment, { key }, children2);
479
- }
480
- return null;
481
- });
482
- };
483
- const children = renderAST(ast, "trans");
484
- return /* @__PURE__ */ React.createElement(Text, { ...props }, children);
485
- };
486
-
487
- // src/index.ts
488
- var initI18n = (translations, options) => i18nService.init(translations, options);
489
- var loadTranslations = (translations) => i18nService.loadTranslations(translations);
490
- var setLocale = (locale) => i18nService.setLocale(locale);
491
- var getLocale = () => i18nService.getLocale();
492
- var t = (scope, options) => i18nService.t(scope, options);
493
- var readyI18n = () => i18nService.ready();
494
- var isI18nReady = () => i18nService.isReady();
495
- var index_default = i18nService;
496
-
497
- export { I18nContext, I18nProvider, Trans, index_default as default, getLocale, initI18n, isI18nReady, loadTranslations, readyI18n, setLocale, t, useI18n, withI18n };
1
+ import {I18n}from'i18n-js';import*as R from'react-native-localize';import {I18nManager,AppState,Text}from'react-native';import T,{createContext,useState,useEffect,useMemo,useContext,isValidElement,Fragment,cloneElement}from'react';var E=Object.defineProperty;var M=(n,t,e)=>t in n?E(n,t,{enumerable:true,configurable:true,writable:true,value:e}):n[t]=e;var h=(n,t,e)=>M(n,typeof t!="symbol"?t+"":t,e);var K=new Set(["ar","fa","he","iw","ur","ps","dv","ku","ug","yi","sd"]),_=new Set(["Arab","Hebr","Thaa","Syrc","Nkoo","Adlm"]),d=n=>n.replace(/_/g,"-"),x=class{constructor(){h(this,"i",new I18n);h(this,"ls",new Set);h(this,"cb");h(this,"fb");h(this,"mb","key");h(this,"mk");h(this,"ef",true);h(this,"fs",true);h(this,"sr","system");h(this,"ok",false);h(this,"v",0);h(this,"rp");h(this,"rr");h(this,"nc",new Map);h(this,"dc",new Map);h(this,"lc",new Map);this.i.enableFallback=false,this.rp=new Promise(t=>{this.rr=t;});}init(t,e={}){var a;let{defaultLocale:r="en",enableFallback:s=true,onLocaleChange:l,fallbackLocales:o,followSystem:p=true,missingBehavior:f="key",onMissingKey:m}=e;this.i.store(this.nt(t)),this.i.defaultLocale=this.i.locale=d(r),this.ef=s,this.cb=l,this.fb=o,this.fs=p,this.sr="system",this.mb=f,this.mk=m,this.cl(),p&&this.updateLocale(),this.em("translations"),this.ok||(this.ok=true,(a=this.rr)==null||a.call(this),this.rr=void 0);}loadTranslations(t){this.i.store(this.nt(t)),this.em("translations");}updateLocale(){var t,e;if(!(!this.fs||this.sr==="user"))try{let r=(e=(t=R.getLocales())==null?void 0:t[0])==null?void 0:e.languageTag;r&&(this.sr="system",this.ap(r));}catch{}}setLocale(t){this.sr="user",this.ap(t);}getLocale(){return this.i.locale}resetToSystem(){this.sr="system",this.updateLocale();}t(t,e){var l,o,p;if(typeof t!="string")return (l=this.nr(this.i.t(t,e)))!=null?l:"";let r=this.i.locale,s=this.ef?this.gc(r):[r];for(let f of s)if(this.ht(f,t)){let m=this.nr(this.ta(f,t,e));if(m!==void 0)return m}if((o=this.mk)==null||o.call(this,t,r),e&&Object.prototype.hasOwnProperty.call(e,"defaultValue"))return (p=this.nr(this.ta(r,t,e)))!=null?p:"";if(this.mb==="empty")return "";if(this.mb==="throw")throw new Error(`Missing translation: ${r}.${t}`);return t}formatNumber(t,e){if(typeof Intl=="undefined"||!Intl.NumberFormat)return String(t);try{return this.gn(this.i.locale,e).format(t)}catch{return String(t)}}formatCurrency(t,e,r){if(typeof Intl=="undefined"||!Intl.NumberFormat)return `${t} ${e}`;try{return this.gn(this.i.locale,{...r,style:"currency",currency:e}).format(t)}catch{return `${t} ${e}`}}formatDate(t,e){let r=typeof t=="number"?new Date(t):t;if(Number.isNaN(r.getTime()))return "";if(typeof Intl=="undefined"||!Intl.DateTimeFormat)return r.toISOString();try{return this.gd(this.i.locale,e).format(r)}catch{return r.toISOString()}}subscribe(t){return this.ls.add(t),()=>{this.ls.delete(t);}}isRTL(){return I18nManager.isRTL}ready(){return this.ok?Promise.resolve():this.rp}isReady(){return this.ok}cl(){this.nc.clear(),this.dc.clear(),this.lc.clear();}gn(t,e){let r=t+(e?JSON.stringify(e):""),s=this.nc.get(r);return s||(s=new Intl.NumberFormat(t,e),this.nc.set(r,s)),s}gd(t,e){let r=t+(e?JSON.stringify(e):""),s=this.dc.get(r);return s||(s=new Intl.DateTimeFormat(t,e),this.dc.set(r,s)),s}em(t){this.v++,this.ls.forEach(e=>e(this.i.locale,{type:t,version:this.v}));}ap(t){var r;let e=d(t);this.i.locale!==e&&(this.i.locale=e,this.cl(),this.hr(e),this.em("locale"),(r=this.cb)==null||r.call(this,e));}hr(t){var p;let e=d(t).split("-").filter(Boolean),r=(p=e[0])==null?void 0:p.toLowerCase();if(!r)return;let s=e.find(f=>/^[A-Za-z]{4}$/.test(f)),l=s?_.has(s[0].toUpperCase()+s.slice(1).toLowerCase()):K.has(r),o=I18nManager;typeof(o==null?void 0:o.allowRTL)=="function"&&typeof(o==null?void 0:o.forceRTL)=="function"&&I18nManager.isRTL!==l&&(o.allowRTL(l),o.forceRTL(l));}ta(t,e,r){let s=this.i.locale;this.i.locale=t;try{return this.i.t(e,r)}finally{this.i.locale=s;}}dg(t,e){let r=d(e);t.push(r);let s=r.split("-").filter(Boolean);for(let l=s.length-1;l>=1;l--)t.push(s.slice(0,l).join("-"));}gc(t){let e=this.lc.get(t);if(e)return e;let r=[];this.dg(r,t);let s=this.fb?typeof this.fb=="function"?this.fb(d(t)):this.fb:[];for(let p of s)this.dg(r,p);this.i.defaultLocale&&this.dg(r,this.i.defaultLocale);let l=new Set,o=r.filter(p=>p&&!l.has(p)&&(l.add(p),true));return this.lc.set(t,o),o}ht(t,e){var l;let r=(l=this.i.translations)==null?void 0:l[t];if(!r||typeof r!="object")return false;if(!e.includes(".")&&Object.prototype.hasOwnProperty.call(r,e))return r[e]!=null;let s=r;for(let o of e.split(".").filter(Boolean)){if(!s||typeof s!="object"||!(o in s))return false;s=s[o];}return s!=null}nr(t){return typeof t=="string"?t:typeof t=="number"?String(t):void 0}nt(t){let e={};for(let r of Object.keys(t))e[d(r)]=t[r];return e}},i=new x;var N={locale:i.getLocale(),setLocale:n=>i.setLocale(n),t:(n,t)=>i.t(n,t),formatNumber:(n,t)=>i.formatNumber(n,t),formatCurrency:(n,t,e)=>i.formatCurrency(n,t,e),formatDate:(n,t)=>i.formatDate(n,t)},b=createContext(N),V=({children:n,readyGate:t,fallback:e})=>{let[r,s]=useState(i.getLocale()),[l,o]=useState(0),[p,f]=useState(i.isReady());useEffect(()=>i.subscribe((a,c)=>{s(a),o(u=>{var g;return (g=c==null?void 0:c.version)!=null?g:u+1});}),[]),useEffect(()=>{var u,g;let a=y=>{y==="active"&&i.updateLocale();},c=(g=(u=AppState)==null?void 0:u.addEventListener)==null?void 0:g.call(u,"change",a);return ()=>{var y,C;typeof(c==null?void 0:c.remove)=="function"?c.remove():(C=(y=AppState)==null?void 0:y.removeEventListener)==null||C.call(y,"change",a);}},[]),useEffect(()=>{if(!t)return;let a=false;return i.ready().then(()=>{a||f(true);}),()=>{a=true;}},[t]);let m=useMemo(()=>({locale:r,setLocale:a=>i.setLocale(a),t:(a,c)=>i.t(a,c),formatNumber:(a,c)=>i.formatNumber(a,c),formatCurrency:(a,c,u)=>i.formatCurrency(a,c,u),formatDate:(a,c)=>i.formatDate(a,c)}),[r,l]);return t&&!p?T.createElement(T.Fragment,null,e!=null?e:null):T.createElement(b.Provider,{value:m},n)};function w(){let n=useContext(b);if(n===N)throw new Error("useI18n must be used within an I18nProvider");return useMemo(()=>({...n,t:((t,e)=>n.t(t,e))}),[n])}function J(n){return t=>T.createElement(b.Consumer,null,e=>{if(e===N)throw new Error("withI18n must be used within an I18nProvider");return T.createElement(n,{...t,...e})})}var H=/<(\/?)([A-Za-z][\w-]*)(?:\s[^>]*?)?(\/?)>/g,U=n=>n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),W=n=>{var s;let t={t:"g",n:"",ch:[]},e=[t],r=0;for(let l of n.matchAll(H)){let[o,p,f,m]=l,a=(s=l.index)!=null?s:0;if(a>r){let c=n.slice(r,a);c&&e[e.length-1].ch.push({t:"x",c});}if(p==="/")e.length>1&&e[e.length-1].n===f?e.pop():e[e.length-1].ch.push({t:"x",c:o});else if(m==="/"||o.endsWith("/>"))e[e.length-1].ch.push({t:"g",n:f,ch:[]});else {let c={t:"g",n:f,ch:[]};e[e.length-1].ch.push(c),e.push(c);}r=a+o.length;}return r<n.length&&e[e.length-1].ch.push({t:"x",c:n.slice(r)}),t.ch},j=(n,t,e,r={})=>n.map((s,l)=>{let o=`${t}-${l}`;if(s.t==="x"){let m=Object.keys(r);if(!m.length)return s.c;let a=s.c.split(new RegExp(`(${m.map(U).join("|")})`,"g"));return a.length===1?s.c:T.createElement(Fragment,{key:o},a.map((c,u)=>r[c]?cloneElement(r[c],{key:`${o}-${u}`}):c))}let p=e==null?void 0:e[s.n],f=j(s.ch,o,e,r);return isValidElement(p)?cloneElement(p,{key:o},f.length?f:void 0):T.createElement(Fragment,{key:o},f)}),q=({i18nKey:n,values:t,components:e,...r})=>{let{t:s}=w(),{sv:l,pe:o}=useMemo(()=>{let a={},c={};if(t)for(let u of Object.keys(t)){let g=t[u];if(isValidElement(g)){let y=`__E_${u}__`;c[y]=g,a[u]=y;}else a[u]=g==null?"":String(g);}return {sv:a,pe:c}},[t]),p=s(n,l),f=useMemo(()=>W(p),[p]),m=useMemo(()=>j(f,"tr",e,o),[f,e,o]);return T.createElement(Text,{...r},m)};var bt=(n,t)=>i.init(n,t),vt=n=>i.loadTranslations(n),xt=n=>i.setLocale(n),It=()=>i.getLocale(),Lt=(n,t)=>i.t(n,t),Nt=(n,t)=>i.formatNumber(n,t),wt=(n,t,e)=>i.formatCurrency(n,t,e),Ot=(n,t)=>i.formatDate(n,t),kt=n=>i.subscribe(n),Ct=()=>i.isRTL(),Rt=()=>i.resetToSystem(),St=()=>i.ready(),Ft=()=>i.isReady(),Pt=i;export{b as I18nContext,V as I18nProvider,q as Trans,Pt as default,wt as formatCurrency,Ot as formatDate,Nt as formatNumber,It as getLocale,bt as initI18n,Ft as isI18nReady,Ct as isRTL,vt as loadTranslations,St as readyI18n,Rt as resetToSystem,xt as setLocale,kt as subscribe,Lt as t,w as useI18n,J as withI18n};
package/package.json CHANGED
@@ -1,13 +1,24 @@
1
1
  {
2
2
  "name": "react-native-i18njs",
3
- "version": "0.0.2",
3
+ "version": "1.0.0",
4
4
  "description": "一个轻量级、类型安全、零心智负担的 React Native 国际化解决方案。",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://gitee.com/ws18250840411/react-native-i18njs.git"
8
8
  },
9
9
  "license": "ISC",
10
- "author": "wangws",
10
+ "author": "wangwenshan",
11
+ "keywords": [
12
+ "react-native",
13
+ "i18n",
14
+ "internationalization",
15
+ "localization",
16
+ "l10n",
17
+ "translation",
18
+ "locale",
19
+ "react",
20
+ "typescript"
21
+ ],
11
22
  "sideEffects": false,
12
23
  "main": "dist/index.js",
13
24
  "module": "dist/index.mjs",