lexisync-react 0.1.1
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 +63 -0
- package/dist/index.cjs +201 -0
- package/dist/index.d.cts +56 -0
- package/dist/index.d.ts +56 -0
- package/dist/index.js +167 -0
- package/package.json +50 -0
- package/src/createI18n.test.ts +116 -0
- package/src/createI18n.ts +56 -0
- package/src/index.test.ts +13 -0
- package/src/index.ts +4 -0
- package/src/lexisync.d.ts +19 -0
- package/src/provider.test.tsx +184 -0
- package/src/provider.tsx +136 -0
- package/src/test/setup.ts +5 -0
- package/src/types.ts +34 -0
package/README.md
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# lexisync-react
|
|
2
|
+
|
|
3
|
+
React bindings for [LexiSync](https://lexisync.app) — Locize-style workflow:
|
|
4
|
+
|
|
5
|
+
1. Create org + API keys in the dashboard
|
|
6
|
+
2. Load **working copy** (`version: "latest"`) with optional `saveMissing`
|
|
7
|
+
3. Translate in the dashboard
|
|
8
|
+
4. **Publish** a version (`production`, `1.0.0`, …)
|
|
9
|
+
5. Pin the app to that version (CDN) or keep `latest` in dev
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install lexisync-react lexisync i18next react-i18next
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
```tsx
|
|
20
|
+
import { LexiSyncProvider, useLexiSync, useT } from 'lexisync-react';
|
|
21
|
+
|
|
22
|
+
function Copy() {
|
|
23
|
+
const t = useT();
|
|
24
|
+
const { changeLanguage, status } = useLexiSync();
|
|
25
|
+
return (
|
|
26
|
+
<>
|
|
27
|
+
<h1>{t('title')}</h1>
|
|
28
|
+
<button type="button" onClick={() => void changeLanguage('nl')}>NL</button>
|
|
29
|
+
<p>{status}</p>
|
|
30
|
+
</>
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function App() {
|
|
35
|
+
return (
|
|
36
|
+
<LexiSyncProvider
|
|
37
|
+
projectId={import.meta.env.VITE_LEXISYNC_PROJECT_ID}
|
|
38
|
+
apiKey={import.meta.env.VITE_LEXISYNC_API_KEY}
|
|
39
|
+
apiUrl="https://lexisync.app" // optional default
|
|
40
|
+
// cdnUrl="https://cdn.lexisync.app" // optional — auto for lexisync.app
|
|
41
|
+
version="latest" // or "production" after publish
|
|
42
|
+
lng="en"
|
|
43
|
+
ns="common"
|
|
44
|
+
saveMissing
|
|
45
|
+
>
|
|
46
|
+
<Copy />
|
|
47
|
+
</LexiSyncProvider>
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
CDN URL shape after publish:
|
|
53
|
+
|
|
54
|
+
```
|
|
55
|
+
https://cdn.lexisync.app/{projectId}/{version}/{lng}/{namespace}.json
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Tests
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
npm test
|
|
62
|
+
# 100% statements / branches / functions / lines on createI18n + provider
|
|
63
|
+
```
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
LexiSyncContext: () => LexiSyncContext,
|
|
34
|
+
LexiSyncProvider: () => LexiSyncProvider,
|
|
35
|
+
createLexiSyncI18n: () => createLexiSyncI18n,
|
|
36
|
+
resolveConfig: () => resolveConfig,
|
|
37
|
+
useLexiSync: () => useLexiSync,
|
|
38
|
+
useT: () => useT
|
|
39
|
+
});
|
|
40
|
+
module.exports = __toCommonJS(index_exports);
|
|
41
|
+
|
|
42
|
+
// src/createI18n.ts
|
|
43
|
+
var import_i18next = __toESM(require("i18next"), 1);
|
|
44
|
+
var import_lexisync = __toESM(require("lexisync"), 1);
|
|
45
|
+
var DEFAULT_API_URL = "https://lexisync.app";
|
|
46
|
+
function resolveConfig(config) {
|
|
47
|
+
if (!config.projectId || !String(config.projectId).trim()) {
|
|
48
|
+
throw new Error("LexiSync: projectId is required");
|
|
49
|
+
}
|
|
50
|
+
const version = config.version || "latest";
|
|
51
|
+
const ns = config.ns ?? "common";
|
|
52
|
+
const defaultNS = config.defaultNS || (Array.isArray(ns) ? ns[0] : ns) || "common";
|
|
53
|
+
return {
|
|
54
|
+
...config,
|
|
55
|
+
projectId: config.projectId,
|
|
56
|
+
apiUrl: (config.apiUrl || DEFAULT_API_URL).replace(/\/$/, ""),
|
|
57
|
+
version,
|
|
58
|
+
lng: config.lng || "en",
|
|
59
|
+
fallbackLng: config.fallbackLng ?? "en",
|
|
60
|
+
ns,
|
|
61
|
+
defaultNS,
|
|
62
|
+
saveMissing: Boolean(config.saveMissing && config.apiKey && version === "latest")
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
async function createLexiSyncI18n(config) {
|
|
66
|
+
const cfg = resolveConfig(config);
|
|
67
|
+
const instance = import_i18next.default.createInstance();
|
|
68
|
+
const nsList = Array.isArray(cfg.ns) ? cfg.ns : [cfg.ns];
|
|
69
|
+
await instance.use(import_lexisync.default).init({
|
|
70
|
+
lng: cfg.lng,
|
|
71
|
+
fallbackLng: cfg.fallbackLng,
|
|
72
|
+
ns: nsList,
|
|
73
|
+
defaultNS: cfg.defaultNS,
|
|
74
|
+
interpolation: { escapeValue: false },
|
|
75
|
+
backend: {
|
|
76
|
+
projectId: cfg.projectId,
|
|
77
|
+
apiKey: cfg.apiKey,
|
|
78
|
+
apiUrl: cfg.apiUrl,
|
|
79
|
+
cdnUrl: cfg.cdnUrl,
|
|
80
|
+
version: cfg.version
|
|
81
|
+
},
|
|
82
|
+
saveMissing: cfg.saveMissing,
|
|
83
|
+
saveMissingTo: "current",
|
|
84
|
+
react: {
|
|
85
|
+
useSuspense: false
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
return instance;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// src/provider.tsx
|
|
92
|
+
var import_react = require("react");
|
|
93
|
+
var LexiSyncContext = (0, import_react.createContext)(null);
|
|
94
|
+
function toError(e) {
|
|
95
|
+
return e instanceof Error ? e : new Error(String(e));
|
|
96
|
+
}
|
|
97
|
+
function LexiSyncProvider(props) {
|
|
98
|
+
const { children, i18n: externalI18n, ...rawConfig } = props;
|
|
99
|
+
const config = (0, import_react.useMemo)(
|
|
100
|
+
() => resolveConfig(rawConfig),
|
|
101
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps -- stable by field
|
|
102
|
+
[
|
|
103
|
+
rawConfig.projectId,
|
|
104
|
+
rawConfig.apiKey,
|
|
105
|
+
rawConfig.apiUrl,
|
|
106
|
+
rawConfig.cdnUrl,
|
|
107
|
+
rawConfig.version,
|
|
108
|
+
rawConfig.lng,
|
|
109
|
+
rawConfig.fallbackLng,
|
|
110
|
+
rawConfig.ns,
|
|
111
|
+
rawConfig.defaultNS,
|
|
112
|
+
rawConfig.saveMissing
|
|
113
|
+
]
|
|
114
|
+
);
|
|
115
|
+
const [instance, setInstance] = (0, import_react.useState)(() => externalI18n ?? null);
|
|
116
|
+
const [status, setStatus] = (0, import_react.useState)(() => externalI18n ? "ready" : "loading");
|
|
117
|
+
const [error, setError] = (0, import_react.useState)(null);
|
|
118
|
+
const [tick, setTick] = (0, import_react.useState)(0);
|
|
119
|
+
const bootstrap = (0, import_react.useCallback)(async () => {
|
|
120
|
+
if (externalI18n) {
|
|
121
|
+
setInstance(externalI18n);
|
|
122
|
+
setStatus("ready");
|
|
123
|
+
setError(null);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
setStatus("loading");
|
|
127
|
+
setError(null);
|
|
128
|
+
try {
|
|
129
|
+
const i18n = await createLexiSyncI18n(config);
|
|
130
|
+
setInstance(i18n);
|
|
131
|
+
setStatus("ready");
|
|
132
|
+
} catch (e) {
|
|
133
|
+
setError(toError(e));
|
|
134
|
+
setStatus("error");
|
|
135
|
+
}
|
|
136
|
+
}, [config, externalI18n]);
|
|
137
|
+
(0, import_react.useEffect)(() => {
|
|
138
|
+
void bootstrap();
|
|
139
|
+
}, [bootstrap]);
|
|
140
|
+
const changeLanguage = (0, import_react.useCallback)(async (lng) => {
|
|
141
|
+
setInstance((current) => {
|
|
142
|
+
if (current) {
|
|
143
|
+
void current.changeLanguage(lng).then(() => setTick((t2) => t2 + 1));
|
|
144
|
+
}
|
|
145
|
+
return current;
|
|
146
|
+
});
|
|
147
|
+
}, []);
|
|
148
|
+
const reload = (0, import_react.useCallback)(async () => {
|
|
149
|
+
if (externalI18n) {
|
|
150
|
+
await externalI18n.reloadResources();
|
|
151
|
+
setTick((t2) => t2 + 1);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
await bootstrap();
|
|
155
|
+
setTick((t2) => t2 + 1);
|
|
156
|
+
}, [bootstrap, externalI18n]);
|
|
157
|
+
const t = (0, import_react.useCallback)(
|
|
158
|
+
(key, options) => {
|
|
159
|
+
void tick;
|
|
160
|
+
return instance ? instance.t(key, options) : key;
|
|
161
|
+
},
|
|
162
|
+
[instance, tick]
|
|
163
|
+
);
|
|
164
|
+
const value = (0, import_react.useMemo)(() => {
|
|
165
|
+
if (!instance && status !== "error") {
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
return {
|
|
169
|
+
config,
|
|
170
|
+
status,
|
|
171
|
+
error,
|
|
172
|
+
i18n: instance ?? null,
|
|
173
|
+
t,
|
|
174
|
+
changeLanguage,
|
|
175
|
+
reload
|
|
176
|
+
};
|
|
177
|
+
}, [instance, status, error, config, t, changeLanguage, reload]);
|
|
178
|
+
if (!value) {
|
|
179
|
+
return (0, import_react.createElement)("div", { "data-lexisync-status": status, role: "status" }, "Loading translations\u2026");
|
|
180
|
+
}
|
|
181
|
+
return (0, import_react.createElement)(LexiSyncContext.Provider, { value }, children);
|
|
182
|
+
}
|
|
183
|
+
function useLexiSync() {
|
|
184
|
+
const ctx = (0, import_react.useContext)(LexiSyncContext);
|
|
185
|
+
if (!ctx) {
|
|
186
|
+
throw new Error("useLexiSync must be used within <LexiSyncProvider>");
|
|
187
|
+
}
|
|
188
|
+
return ctx;
|
|
189
|
+
}
|
|
190
|
+
function useT() {
|
|
191
|
+
return useLexiSync().t;
|
|
192
|
+
}
|
|
193
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
194
|
+
0 && (module.exports = {
|
|
195
|
+
LexiSyncContext,
|
|
196
|
+
LexiSyncProvider,
|
|
197
|
+
createLexiSyncI18n,
|
|
198
|
+
resolveConfig,
|
|
199
|
+
useLexiSync,
|
|
200
|
+
useT
|
|
201
|
+
});
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import * as i18next from 'i18next';
|
|
2
|
+
import { i18n } from 'i18next';
|
|
3
|
+
import * as react from 'react';
|
|
4
|
+
import { ReactNode } from 'react';
|
|
5
|
+
|
|
6
|
+
type LexiSyncConfig = {
|
|
7
|
+
/** LexiSync project id from the dashboard */
|
|
8
|
+
projectId: string;
|
|
9
|
+
/** Secret key (sk_…) — required for saveMissing / write */
|
|
10
|
+
apiKey?: string;
|
|
11
|
+
/** Platform origin, default https://lexisync.app */
|
|
12
|
+
apiUrl?: string;
|
|
13
|
+
/** CDN origin, default https://cdn.lexisync.app when apiUrl is lexisync.app */
|
|
14
|
+
cdnUrl?: string;
|
|
15
|
+
/**
|
|
16
|
+
* Catalog version:
|
|
17
|
+
* - `latest` — working copy (dev, saveMissing)
|
|
18
|
+
* - `production` / `1.0.0` / … — published CDN snapshot
|
|
19
|
+
*/
|
|
20
|
+
version?: string;
|
|
21
|
+
lng?: string;
|
|
22
|
+
fallbackLng?: string | string[];
|
|
23
|
+
ns?: string | string[];
|
|
24
|
+
defaultNS?: string;
|
|
25
|
+
/** Auto-push missing keys to working copy (needs apiKey, version latest) */
|
|
26
|
+
saveMissing?: boolean;
|
|
27
|
+
};
|
|
28
|
+
type LexiSyncStatus = 'idle' | 'loading' | 'ready' | 'error';
|
|
29
|
+
type LexiSyncContextValue = {
|
|
30
|
+
config: Required<Pick<LexiSyncConfig, 'projectId' | 'apiUrl' | 'version'>> & LexiSyncConfig;
|
|
31
|
+
status: LexiSyncStatus;
|
|
32
|
+
error: Error | null;
|
|
33
|
+
i18n: i18next.i18n;
|
|
34
|
+
t: (key: string, options?: Record<string, unknown>) => string;
|
|
35
|
+
changeLanguage: (lng: string) => Promise<void>;
|
|
36
|
+
reload: () => Promise<void>;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
declare function resolveConfig(config: LexiSyncConfig): Required<Pick<LexiSyncConfig, 'projectId' | 'apiUrl' | 'version' | 'lng' | 'defaultNS' | 'saveMissing' | 'ns'>> & LexiSyncConfig;
|
|
40
|
+
declare function createLexiSyncI18n(config: LexiSyncConfig): Promise<i18n>;
|
|
41
|
+
|
|
42
|
+
declare const LexiSyncContext: react.Context<LexiSyncContextValue | null>;
|
|
43
|
+
type LexiSyncProviderProps = LexiSyncConfig & {
|
|
44
|
+
children: ReactNode;
|
|
45
|
+
/** Optional pre-built i18n instance (tests / advanced). */
|
|
46
|
+
i18n?: i18n;
|
|
47
|
+
};
|
|
48
|
+
declare function LexiSyncProvider(props: LexiSyncProviderProps): react.DetailedReactHTMLElement<{
|
|
49
|
+
'data-lexisync-status': LexiSyncStatus;
|
|
50
|
+
role: "status";
|
|
51
|
+
}, HTMLElement> | react.FunctionComponentElement<react.ProviderProps<LexiSyncContextValue | null>>;
|
|
52
|
+
declare function useLexiSync(): LexiSyncContextValue;
|
|
53
|
+
/** Shortcut: translation function bound to the provider instance. */
|
|
54
|
+
declare function useT(): (key: string, options?: Record<string, unknown>) => string;
|
|
55
|
+
|
|
56
|
+
export { type LexiSyncConfig, LexiSyncContext, type LexiSyncContextValue, LexiSyncProvider, type LexiSyncProviderProps, type LexiSyncStatus, createLexiSyncI18n, resolveConfig, useLexiSync, useT };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import * as i18next from 'i18next';
|
|
2
|
+
import { i18n } from 'i18next';
|
|
3
|
+
import * as react from 'react';
|
|
4
|
+
import { ReactNode } from 'react';
|
|
5
|
+
|
|
6
|
+
type LexiSyncConfig = {
|
|
7
|
+
/** LexiSync project id from the dashboard */
|
|
8
|
+
projectId: string;
|
|
9
|
+
/** Secret key (sk_…) — required for saveMissing / write */
|
|
10
|
+
apiKey?: string;
|
|
11
|
+
/** Platform origin, default https://lexisync.app */
|
|
12
|
+
apiUrl?: string;
|
|
13
|
+
/** CDN origin, default https://cdn.lexisync.app when apiUrl is lexisync.app */
|
|
14
|
+
cdnUrl?: string;
|
|
15
|
+
/**
|
|
16
|
+
* Catalog version:
|
|
17
|
+
* - `latest` — working copy (dev, saveMissing)
|
|
18
|
+
* - `production` / `1.0.0` / … — published CDN snapshot
|
|
19
|
+
*/
|
|
20
|
+
version?: string;
|
|
21
|
+
lng?: string;
|
|
22
|
+
fallbackLng?: string | string[];
|
|
23
|
+
ns?: string | string[];
|
|
24
|
+
defaultNS?: string;
|
|
25
|
+
/** Auto-push missing keys to working copy (needs apiKey, version latest) */
|
|
26
|
+
saveMissing?: boolean;
|
|
27
|
+
};
|
|
28
|
+
type LexiSyncStatus = 'idle' | 'loading' | 'ready' | 'error';
|
|
29
|
+
type LexiSyncContextValue = {
|
|
30
|
+
config: Required<Pick<LexiSyncConfig, 'projectId' | 'apiUrl' | 'version'>> & LexiSyncConfig;
|
|
31
|
+
status: LexiSyncStatus;
|
|
32
|
+
error: Error | null;
|
|
33
|
+
i18n: i18next.i18n;
|
|
34
|
+
t: (key: string, options?: Record<string, unknown>) => string;
|
|
35
|
+
changeLanguage: (lng: string) => Promise<void>;
|
|
36
|
+
reload: () => Promise<void>;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
declare function resolveConfig(config: LexiSyncConfig): Required<Pick<LexiSyncConfig, 'projectId' | 'apiUrl' | 'version' | 'lng' | 'defaultNS' | 'saveMissing' | 'ns'>> & LexiSyncConfig;
|
|
40
|
+
declare function createLexiSyncI18n(config: LexiSyncConfig): Promise<i18n>;
|
|
41
|
+
|
|
42
|
+
declare const LexiSyncContext: react.Context<LexiSyncContextValue | null>;
|
|
43
|
+
type LexiSyncProviderProps = LexiSyncConfig & {
|
|
44
|
+
children: ReactNode;
|
|
45
|
+
/** Optional pre-built i18n instance (tests / advanced). */
|
|
46
|
+
i18n?: i18n;
|
|
47
|
+
};
|
|
48
|
+
declare function LexiSyncProvider(props: LexiSyncProviderProps): react.DetailedReactHTMLElement<{
|
|
49
|
+
'data-lexisync-status': LexiSyncStatus;
|
|
50
|
+
role: "status";
|
|
51
|
+
}, HTMLElement> | react.FunctionComponentElement<react.ProviderProps<LexiSyncContextValue | null>>;
|
|
52
|
+
declare function useLexiSync(): LexiSyncContextValue;
|
|
53
|
+
/** Shortcut: translation function bound to the provider instance. */
|
|
54
|
+
declare function useT(): (key: string, options?: Record<string, unknown>) => string;
|
|
55
|
+
|
|
56
|
+
export { type LexiSyncConfig, LexiSyncContext, type LexiSyncContextValue, LexiSyncProvider, type LexiSyncProviderProps, type LexiSyncStatus, createLexiSyncI18n, resolveConfig, useLexiSync, useT };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// src/createI18n.ts
|
|
2
|
+
import i18next from "i18next";
|
|
3
|
+
import LexiSyncBackend from "lexisync";
|
|
4
|
+
var DEFAULT_API_URL = "https://lexisync.app";
|
|
5
|
+
function resolveConfig(config) {
|
|
6
|
+
if (!config.projectId || !String(config.projectId).trim()) {
|
|
7
|
+
throw new Error("LexiSync: projectId is required");
|
|
8
|
+
}
|
|
9
|
+
const version = config.version || "latest";
|
|
10
|
+
const ns = config.ns ?? "common";
|
|
11
|
+
const defaultNS = config.defaultNS || (Array.isArray(ns) ? ns[0] : ns) || "common";
|
|
12
|
+
return {
|
|
13
|
+
...config,
|
|
14
|
+
projectId: config.projectId,
|
|
15
|
+
apiUrl: (config.apiUrl || DEFAULT_API_URL).replace(/\/$/, ""),
|
|
16
|
+
version,
|
|
17
|
+
lng: config.lng || "en",
|
|
18
|
+
fallbackLng: config.fallbackLng ?? "en",
|
|
19
|
+
ns,
|
|
20
|
+
defaultNS,
|
|
21
|
+
saveMissing: Boolean(config.saveMissing && config.apiKey && version === "latest")
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
async function createLexiSyncI18n(config) {
|
|
25
|
+
const cfg = resolveConfig(config);
|
|
26
|
+
const instance = i18next.createInstance();
|
|
27
|
+
const nsList = Array.isArray(cfg.ns) ? cfg.ns : [cfg.ns];
|
|
28
|
+
await instance.use(LexiSyncBackend).init({
|
|
29
|
+
lng: cfg.lng,
|
|
30
|
+
fallbackLng: cfg.fallbackLng,
|
|
31
|
+
ns: nsList,
|
|
32
|
+
defaultNS: cfg.defaultNS,
|
|
33
|
+
interpolation: { escapeValue: false },
|
|
34
|
+
backend: {
|
|
35
|
+
projectId: cfg.projectId,
|
|
36
|
+
apiKey: cfg.apiKey,
|
|
37
|
+
apiUrl: cfg.apiUrl,
|
|
38
|
+
cdnUrl: cfg.cdnUrl,
|
|
39
|
+
version: cfg.version
|
|
40
|
+
},
|
|
41
|
+
saveMissing: cfg.saveMissing,
|
|
42
|
+
saveMissingTo: "current",
|
|
43
|
+
react: {
|
|
44
|
+
useSuspense: false
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
return instance;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// src/provider.tsx
|
|
51
|
+
import {
|
|
52
|
+
createContext,
|
|
53
|
+
createElement,
|
|
54
|
+
useCallback,
|
|
55
|
+
useContext,
|
|
56
|
+
useEffect,
|
|
57
|
+
useMemo,
|
|
58
|
+
useState
|
|
59
|
+
} from "react";
|
|
60
|
+
var LexiSyncContext = createContext(null);
|
|
61
|
+
function toError(e) {
|
|
62
|
+
return e instanceof Error ? e : new Error(String(e));
|
|
63
|
+
}
|
|
64
|
+
function LexiSyncProvider(props) {
|
|
65
|
+
const { children, i18n: externalI18n, ...rawConfig } = props;
|
|
66
|
+
const config = useMemo(
|
|
67
|
+
() => resolveConfig(rawConfig),
|
|
68
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps -- stable by field
|
|
69
|
+
[
|
|
70
|
+
rawConfig.projectId,
|
|
71
|
+
rawConfig.apiKey,
|
|
72
|
+
rawConfig.apiUrl,
|
|
73
|
+
rawConfig.cdnUrl,
|
|
74
|
+
rawConfig.version,
|
|
75
|
+
rawConfig.lng,
|
|
76
|
+
rawConfig.fallbackLng,
|
|
77
|
+
rawConfig.ns,
|
|
78
|
+
rawConfig.defaultNS,
|
|
79
|
+
rawConfig.saveMissing
|
|
80
|
+
]
|
|
81
|
+
);
|
|
82
|
+
const [instance, setInstance] = useState(() => externalI18n ?? null);
|
|
83
|
+
const [status, setStatus] = useState(() => externalI18n ? "ready" : "loading");
|
|
84
|
+
const [error, setError] = useState(null);
|
|
85
|
+
const [tick, setTick] = useState(0);
|
|
86
|
+
const bootstrap = useCallback(async () => {
|
|
87
|
+
if (externalI18n) {
|
|
88
|
+
setInstance(externalI18n);
|
|
89
|
+
setStatus("ready");
|
|
90
|
+
setError(null);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
setStatus("loading");
|
|
94
|
+
setError(null);
|
|
95
|
+
try {
|
|
96
|
+
const i18n = await createLexiSyncI18n(config);
|
|
97
|
+
setInstance(i18n);
|
|
98
|
+
setStatus("ready");
|
|
99
|
+
} catch (e) {
|
|
100
|
+
setError(toError(e));
|
|
101
|
+
setStatus("error");
|
|
102
|
+
}
|
|
103
|
+
}, [config, externalI18n]);
|
|
104
|
+
useEffect(() => {
|
|
105
|
+
void bootstrap();
|
|
106
|
+
}, [bootstrap]);
|
|
107
|
+
const changeLanguage = useCallback(async (lng) => {
|
|
108
|
+
setInstance((current) => {
|
|
109
|
+
if (current) {
|
|
110
|
+
void current.changeLanguage(lng).then(() => setTick((t2) => t2 + 1));
|
|
111
|
+
}
|
|
112
|
+
return current;
|
|
113
|
+
});
|
|
114
|
+
}, []);
|
|
115
|
+
const reload = useCallback(async () => {
|
|
116
|
+
if (externalI18n) {
|
|
117
|
+
await externalI18n.reloadResources();
|
|
118
|
+
setTick((t2) => t2 + 1);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
await bootstrap();
|
|
122
|
+
setTick((t2) => t2 + 1);
|
|
123
|
+
}, [bootstrap, externalI18n]);
|
|
124
|
+
const t = useCallback(
|
|
125
|
+
(key, options) => {
|
|
126
|
+
void tick;
|
|
127
|
+
return instance ? instance.t(key, options) : key;
|
|
128
|
+
},
|
|
129
|
+
[instance, tick]
|
|
130
|
+
);
|
|
131
|
+
const value = useMemo(() => {
|
|
132
|
+
if (!instance && status !== "error") {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
return {
|
|
136
|
+
config,
|
|
137
|
+
status,
|
|
138
|
+
error,
|
|
139
|
+
i18n: instance ?? null,
|
|
140
|
+
t,
|
|
141
|
+
changeLanguage,
|
|
142
|
+
reload
|
|
143
|
+
};
|
|
144
|
+
}, [instance, status, error, config, t, changeLanguage, reload]);
|
|
145
|
+
if (!value) {
|
|
146
|
+
return createElement("div", { "data-lexisync-status": status, role: "status" }, "Loading translations\u2026");
|
|
147
|
+
}
|
|
148
|
+
return createElement(LexiSyncContext.Provider, { value }, children);
|
|
149
|
+
}
|
|
150
|
+
function useLexiSync() {
|
|
151
|
+
const ctx = useContext(LexiSyncContext);
|
|
152
|
+
if (!ctx) {
|
|
153
|
+
throw new Error("useLexiSync must be used within <LexiSyncProvider>");
|
|
154
|
+
}
|
|
155
|
+
return ctx;
|
|
156
|
+
}
|
|
157
|
+
function useT() {
|
|
158
|
+
return useLexiSync().t;
|
|
159
|
+
}
|
|
160
|
+
export {
|
|
161
|
+
LexiSyncContext,
|
|
162
|
+
LexiSyncProvider,
|
|
163
|
+
createLexiSyncI18n,
|
|
164
|
+
resolveConfig,
|
|
165
|
+
useLexiSync,
|
|
166
|
+
useT
|
|
167
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "lexisync-react",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "React bindings for LexiSync — Provider, hooks, saveMissing, versioned CDN catalogs",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.cjs",
|
|
8
|
+
"module": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"import": "./dist/index.js",
|
|
14
|
+
"require": "./dist/index.cjs"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist",
|
|
19
|
+
"src"
|
|
20
|
+
],
|
|
21
|
+
"sideEffects": false,
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build": "tsup src/index.ts --format cjs,esm --dts --clean",
|
|
24
|
+
"test": "vitest run --coverage",
|
|
25
|
+
"test:watch": "vitest",
|
|
26
|
+
"prepublishOnly": "npm run test && npm run build"
|
|
27
|
+
},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"i18next": ">=23.0.0",
|
|
30
|
+
"react": ">=18.0.0",
|
|
31
|
+
"react-i18next": ">=14.0.0"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"lexisync": "*"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@testing-library/react": "^16.2.0",
|
|
38
|
+
"@types/react": "^19.0.0",
|
|
39
|
+
"@types/react-dom": "^19.0.0",
|
|
40
|
+
"@vitest/coverage-v8": "^3.0.5",
|
|
41
|
+
"i18next": "^24.2.2",
|
|
42
|
+
"jsdom": "^26.0.0",
|
|
43
|
+
"react": "^19.0.0",
|
|
44
|
+
"react-dom": "^19.0.0",
|
|
45
|
+
"react-i18next": "^15.4.1",
|
|
46
|
+
"tsup": "^8.3.6",
|
|
47
|
+
"typescript": "^5.7.2",
|
|
48
|
+
"vitest": "^3.0.5"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
2
|
+
import { resolveConfig, createLexiSyncI18n } from './createI18n';
|
|
3
|
+
|
|
4
|
+
const readMock = vi.fn();
|
|
5
|
+
const createMock = vi.fn();
|
|
6
|
+
|
|
7
|
+
vi.mock('lexisync', () => {
|
|
8
|
+
class MockBackend {
|
|
9
|
+
static type = 'backend';
|
|
10
|
+
type = 'backend';
|
|
11
|
+
options: Record<string, unknown> = {};
|
|
12
|
+
constructor(_s: unknown, opts: Record<string, unknown> = {}) {
|
|
13
|
+
this.options = opts;
|
|
14
|
+
}
|
|
15
|
+
init(_s: unknown, opts: Record<string, unknown> = {}) {
|
|
16
|
+
this.options = { ...this.options, ...opts };
|
|
17
|
+
}
|
|
18
|
+
read(lng: string, ns: string, cb: (err: Error | null, data: Record<string, string> | null) => void) {
|
|
19
|
+
readMock(lng, ns);
|
|
20
|
+
cb(null, { greeting: `hi-${lng}`, title: 'Title' });
|
|
21
|
+
}
|
|
22
|
+
create(languages: string | string[], namespace: string, key: string, fallbackValue: string) {
|
|
23
|
+
createMock(languages, namespace, key, fallbackValue);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return { default: MockBackend, __esModule: true };
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
describe('resolveConfig', () => {
|
|
30
|
+
it('throws without projectId', () => {
|
|
31
|
+
expect(() => resolveConfig({ projectId: '' })).toThrow(/projectId/);
|
|
32
|
+
expect(() => resolveConfig({ projectId: ' ' })).toThrow(/projectId/);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('applies defaults', () => {
|
|
36
|
+
const c = resolveConfig({ projectId: 'p1' });
|
|
37
|
+
expect(c.apiUrl).toBe('https://lexisync.app');
|
|
38
|
+
expect(c.version).toBe('latest');
|
|
39
|
+
expect(c.lng).toBe('en');
|
|
40
|
+
expect(c.defaultNS).toBe('common');
|
|
41
|
+
expect(c.ns).toBe('common');
|
|
42
|
+
expect(c.saveMissing).toBe(false);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('strips trailing slash on apiUrl', () => {
|
|
46
|
+
const c = resolveConfig({ projectId: 'p1', apiUrl: 'https://x.test/' });
|
|
47
|
+
expect(c.apiUrl).toBe('https://x.test');
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('enables saveMissing only with apiKey + latest', () => {
|
|
51
|
+
expect(
|
|
52
|
+
resolveConfig({ projectId: 'p1', apiKey: 'sk', saveMissing: true, version: 'latest' }).saveMissing
|
|
53
|
+
).toBe(true);
|
|
54
|
+
expect(
|
|
55
|
+
resolveConfig({ projectId: 'p1', apiKey: 'sk', saveMissing: true, version: 'production' }).saveMissing
|
|
56
|
+
).toBe(false);
|
|
57
|
+
expect(resolveConfig({ projectId: 'p1', saveMissing: true, version: 'latest' }).saveMissing).toBe(false);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it('defaultNS from ns array first element', () => {
|
|
61
|
+
const c = resolveConfig({ projectId: 'p1', ns: ['auth', 'common'] });
|
|
62
|
+
expect(c.defaultNS).toBe('auth');
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('defaultNS falls back when ns array empty', () => {
|
|
66
|
+
const c = resolveConfig({ projectId: 'p1', ns: [] });
|
|
67
|
+
expect(c.defaultNS).toBe('common');
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it('respects explicit defaultNS', () => {
|
|
71
|
+
const c = resolveConfig({ projectId: 'p1', ns: ['a'], defaultNS: 'custom' });
|
|
72
|
+
expect(c.defaultNS).toBe('custom');
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
describe('createLexiSyncI18n', () => {
|
|
77
|
+
beforeEach(() => {
|
|
78
|
+
readMock.mockClear();
|
|
79
|
+
createMock.mockClear();
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('loads resources via backend (string ns)', async () => {
|
|
83
|
+
const i18n = await createLexiSyncI18n({
|
|
84
|
+
projectId: 'proj',
|
|
85
|
+
apiUrl: 'https://api.test',
|
|
86
|
+
lng: 'nl',
|
|
87
|
+
ns: 'common',
|
|
88
|
+
});
|
|
89
|
+
expect(readMock).toHaveBeenCalled();
|
|
90
|
+
expect(i18n.t('greeting')).toBe('hi-nl');
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('loads resources via backend (array ns)', async () => {
|
|
94
|
+
const i18n = await createLexiSyncI18n({
|
|
95
|
+
projectId: 'proj',
|
|
96
|
+
lng: 'en',
|
|
97
|
+
ns: ['common', 'auth'],
|
|
98
|
+
});
|
|
99
|
+
expect(i18n.isInitialized).toBe(true);
|
|
100
|
+
expect(i18n.t('greeting')).toBe('hi-en');
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it('wires saveMissing when enabled', async () => {
|
|
104
|
+
const i18n = await createLexiSyncI18n({
|
|
105
|
+
projectId: 'proj',
|
|
106
|
+
apiKey: 'sk_test',
|
|
107
|
+
saveMissing: true,
|
|
108
|
+
version: 'latest',
|
|
109
|
+
lng: 'en',
|
|
110
|
+
ns: ['common'],
|
|
111
|
+
});
|
|
112
|
+
i18n.t('another_missing', { defaultValue: 'fallback text' });
|
|
113
|
+
await Promise.resolve();
|
|
114
|
+
expect(i18n.isInitialized).toBe(true);
|
|
115
|
+
});
|
|
116
|
+
});
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import i18next, { type i18n as I18nInstance } from 'i18next';
|
|
2
|
+
import LexiSyncBackend from 'lexisync';
|
|
3
|
+
import type { LexiSyncConfig } from './types';
|
|
4
|
+
|
|
5
|
+
const DEFAULT_API_URL = 'https://lexisync.app';
|
|
6
|
+
|
|
7
|
+
export function resolveConfig(config: LexiSyncConfig): Required<
|
|
8
|
+
Pick<LexiSyncConfig, 'projectId' | 'apiUrl' | 'version' | 'lng' | 'defaultNS' | 'saveMissing' | 'ns'>
|
|
9
|
+
> &
|
|
10
|
+
LexiSyncConfig {
|
|
11
|
+
if (!config.projectId || !String(config.projectId).trim()) {
|
|
12
|
+
throw new Error('LexiSync: projectId is required');
|
|
13
|
+
}
|
|
14
|
+
const version = config.version || 'latest';
|
|
15
|
+
const ns = config.ns ?? 'common';
|
|
16
|
+
const defaultNS = config.defaultNS || (Array.isArray(ns) ? ns[0] : ns) || 'common';
|
|
17
|
+
return {
|
|
18
|
+
...config,
|
|
19
|
+
projectId: config.projectId,
|
|
20
|
+
apiUrl: (config.apiUrl || DEFAULT_API_URL).replace(/\/$/, ''),
|
|
21
|
+
version,
|
|
22
|
+
lng: config.lng || 'en',
|
|
23
|
+
fallbackLng: config.fallbackLng ?? 'en',
|
|
24
|
+
ns,
|
|
25
|
+
defaultNS,
|
|
26
|
+
saveMissing: Boolean(config.saveMissing && config.apiKey && version === 'latest'),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function createLexiSyncI18n(config: LexiSyncConfig): Promise<I18nInstance> {
|
|
31
|
+
const cfg = resolveConfig(config);
|
|
32
|
+
const instance = i18next.createInstance();
|
|
33
|
+
const nsList = Array.isArray(cfg.ns) ? cfg.ns : [cfg.ns];
|
|
34
|
+
|
|
35
|
+
await instance.use(LexiSyncBackend as never).init({
|
|
36
|
+
lng: cfg.lng,
|
|
37
|
+
fallbackLng: cfg.fallbackLng,
|
|
38
|
+
ns: nsList,
|
|
39
|
+
defaultNS: cfg.defaultNS,
|
|
40
|
+
interpolation: { escapeValue: false },
|
|
41
|
+
backend: {
|
|
42
|
+
projectId: cfg.projectId,
|
|
43
|
+
apiKey: cfg.apiKey,
|
|
44
|
+
apiUrl: cfg.apiUrl,
|
|
45
|
+
cdnUrl: cfg.cdnUrl,
|
|
46
|
+
version: cfg.version,
|
|
47
|
+
},
|
|
48
|
+
saveMissing: cfg.saveMissing,
|
|
49
|
+
saveMissingTo: 'current',
|
|
50
|
+
react: {
|
|
51
|
+
useSuspense: false,
|
|
52
|
+
} as never,
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
return instance;
|
|
56
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import * as pkg from './index';
|
|
3
|
+
|
|
4
|
+
describe('package exports', () => {
|
|
5
|
+
it('exposes public API', () => {
|
|
6
|
+
expect(typeof pkg.LexiSyncProvider).toBe('function');
|
|
7
|
+
expect(typeof pkg.useLexiSync).toBe('function');
|
|
8
|
+
expect(typeof pkg.useT).toBe('function');
|
|
9
|
+
expect(typeof pkg.createLexiSyncI18n).toBe('function');
|
|
10
|
+
expect(typeof pkg.resolveConfig).toBe('function');
|
|
11
|
+
expect(pkg.LexiSyncContext).toBeTruthy();
|
|
12
|
+
});
|
|
13
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export type { LexiSyncConfig, LexiSyncContextValue, LexiSyncStatus } from './types';
|
|
2
|
+
export { createLexiSyncI18n, resolveConfig } from './createI18n';
|
|
3
|
+
export { LexiSyncProvider, useLexiSync, useT, LexiSyncContext } from './provider';
|
|
4
|
+
export type { LexiSyncProviderProps } from './provider';
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
declare module 'lexisync' {
|
|
2
|
+
type Callback = (err: Error | null, data: Record<string, string> | null) => void;
|
|
3
|
+
|
|
4
|
+
class LexiSyncBackend {
|
|
5
|
+
static type: string;
|
|
6
|
+
type: string;
|
|
7
|
+
constructor(services?: unknown, options?: Record<string, unknown>, i18nOptions?: unknown);
|
|
8
|
+
init(services?: unknown, options?: Record<string, unknown>, i18nOptions?: unknown): void;
|
|
9
|
+
read(language: string, namespace: string, callback: Callback): void;
|
|
10
|
+
create(
|
|
11
|
+
languages: string | string[],
|
|
12
|
+
namespace: string,
|
|
13
|
+
key: string,
|
|
14
|
+
fallbackValue: string
|
|
15
|
+
): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export default LexiSyncBackend;
|
|
19
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
2
|
+
import { render, screen, waitFor, act } from '@testing-library/react';
|
|
3
|
+
import { createElement } from 'react';
|
|
4
|
+
import i18next from 'i18next';
|
|
5
|
+
import { LexiSyncProvider, useLexiSync, useT } from './provider';
|
|
6
|
+
|
|
7
|
+
vi.mock('./createI18n', async () => {
|
|
8
|
+
const actual = await vi.importActual<typeof import('./createI18n')>('./createI18n');
|
|
9
|
+
return {
|
|
10
|
+
...actual,
|
|
11
|
+
createLexiSyncI18n: vi.fn(async (cfg: { projectId: string; lng?: string }) => {
|
|
12
|
+
const instance = i18next.createInstance();
|
|
13
|
+
await instance.init({
|
|
14
|
+
lng: cfg.lng || 'en',
|
|
15
|
+
resources: {
|
|
16
|
+
en: { common: { hello: 'Hello', world: 'World' } },
|
|
17
|
+
nl: { common: { hello: 'Hallo', world: 'Wereld' } },
|
|
18
|
+
},
|
|
19
|
+
ns: ['common'],
|
|
20
|
+
defaultNS: 'common',
|
|
21
|
+
});
|
|
22
|
+
return instance;
|
|
23
|
+
}),
|
|
24
|
+
};
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
function Probe() {
|
|
28
|
+
const { t, status, changeLanguage, reload, config } = useLexiSync();
|
|
29
|
+
return createElement(
|
|
30
|
+
'div',
|
|
31
|
+
null,
|
|
32
|
+
createElement('span', { 'data-testid': 'status' }, status),
|
|
33
|
+
createElement('span', { 'data-testid': 'hello' }, t('hello')),
|
|
34
|
+
createElement('span', { 'data-testid': 'version' }, config.version),
|
|
35
|
+
createElement(
|
|
36
|
+
'button',
|
|
37
|
+
{
|
|
38
|
+
type: 'button',
|
|
39
|
+
onClick: () => {
|
|
40
|
+
void changeLanguage('nl');
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
'nl'
|
|
44
|
+
),
|
|
45
|
+
createElement(
|
|
46
|
+
'button',
|
|
47
|
+
{
|
|
48
|
+
type: 'button',
|
|
49
|
+
onClick: () => {
|
|
50
|
+
void reload();
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
'reload'
|
|
54
|
+
)
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function TOnly() {
|
|
59
|
+
const t = useT();
|
|
60
|
+
return createElement('span', { 'data-testid': 't-only' }, t('world'));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
describe('LexiSyncProvider', () => {
|
|
64
|
+
beforeEach(() => {
|
|
65
|
+
vi.clearAllMocks();
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('throws useLexiSync outside provider', () => {
|
|
69
|
+
expect(() => render(createElement(Probe))).toThrow(/useLexiSync must be used within/);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it('shows loading then ready with translations', async () => {
|
|
73
|
+
render(createElement(LexiSyncProvider, { projectId: 'p1', version: 'latest' }, createElement(Probe)));
|
|
74
|
+
await waitFor(() => expect(screen.getByTestId('status').textContent).toBe('ready'));
|
|
75
|
+
expect(screen.getByTestId('hello').textContent).toBe('Hello');
|
|
76
|
+
expect(screen.getByTestId('version').textContent).toBe('latest');
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('useT returns translations', async () => {
|
|
80
|
+
render(createElement(LexiSyncProvider, { projectId: 'p1' }, createElement(TOnly)));
|
|
81
|
+
await waitFor(() => expect(screen.getByTestId('t-only').textContent).toBe('World'));
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('changeLanguage updates strings', async () => {
|
|
85
|
+
render(createElement(LexiSyncProvider, { projectId: 'p1', lng: 'en' }, createElement(Probe)));
|
|
86
|
+
await waitFor(() => expect(screen.getByTestId('hello').textContent).toBe('Hello'));
|
|
87
|
+
await act(async () => {
|
|
88
|
+
screen.getByText('nl').click();
|
|
89
|
+
});
|
|
90
|
+
await waitFor(() => expect(screen.getByTestId('hello').textContent).toBe('Hallo'));
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('reload works', async () => {
|
|
94
|
+
render(createElement(LexiSyncProvider, { projectId: 'p1' }, createElement(Probe)));
|
|
95
|
+
await waitFor(() => expect(screen.getByTestId('status').textContent).toBe('ready'));
|
|
96
|
+
await act(async () => {
|
|
97
|
+
screen.getByText('reload').click();
|
|
98
|
+
});
|
|
99
|
+
await waitFor(() => expect(screen.getByTestId('status').textContent).toBe('ready'));
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it('accepts external i18n instance', async () => {
|
|
103
|
+
const external = i18next.createInstance();
|
|
104
|
+
await external.init({
|
|
105
|
+
lng: 'en',
|
|
106
|
+
resources: { en: { common: { hello: 'External' } } },
|
|
107
|
+
ns: ['common'],
|
|
108
|
+
defaultNS: 'common',
|
|
109
|
+
});
|
|
110
|
+
render(createElement(LexiSyncProvider, { projectId: 'p1', i18n: external }, createElement(Probe)));
|
|
111
|
+
await waitFor(() => expect(screen.getByTestId('hello').textContent).toBe('External'));
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it('reload with external i18n calls reloadResources', async () => {
|
|
115
|
+
const external = i18next.createInstance();
|
|
116
|
+
await external.init({
|
|
117
|
+
lng: 'en',
|
|
118
|
+
resources: { en: { common: { hello: 'Ext' } } },
|
|
119
|
+
ns: ['common'],
|
|
120
|
+
defaultNS: 'common',
|
|
121
|
+
});
|
|
122
|
+
const spy = vi.spyOn(external, 'reloadResources').mockResolvedValue(external as never);
|
|
123
|
+
render(createElement(LexiSyncProvider, { projectId: 'p1', i18n: external }, createElement(Probe)));
|
|
124
|
+
await waitFor(() => expect(screen.getByTestId('status').textContent).toBe('ready'));
|
|
125
|
+
await act(async () => {
|
|
126
|
+
screen.getByText('reload').click();
|
|
127
|
+
});
|
|
128
|
+
expect(spy).toHaveBeenCalled();
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it('surfaces error status when create fails with Error', async () => {
|
|
132
|
+
const { createLexiSyncI18n } = await import('./createI18n');
|
|
133
|
+
vi.mocked(createLexiSyncI18n).mockRejectedValueOnce(new Error('boom'));
|
|
134
|
+
|
|
135
|
+
function ErrProbe() {
|
|
136
|
+
const { status, error, t, changeLanguage } = useLexiSync();
|
|
137
|
+
return createElement(
|
|
138
|
+
'div',
|
|
139
|
+
null,
|
|
140
|
+
createElement('span', { 'data-testid': 'status' }, status),
|
|
141
|
+
createElement('span', { 'data-testid': 'err' }, error?.message || ''),
|
|
142
|
+
createElement('span', { 'data-testid': 't' }, t('x')),
|
|
143
|
+
createElement(
|
|
144
|
+
'button',
|
|
145
|
+
{
|
|
146
|
+
type: 'button',
|
|
147
|
+
onClick: () => {
|
|
148
|
+
void changeLanguage('de');
|
|
149
|
+
},
|
|
150
|
+
},
|
|
151
|
+
'de'
|
|
152
|
+
)
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
render(createElement(LexiSyncProvider, { projectId: 'p1' }, createElement(ErrProbe)));
|
|
157
|
+
await waitFor(() => expect(screen.getByTestId('status').textContent).toBe('error'));
|
|
158
|
+
expect(screen.getByTestId('err').textContent).toBe('boom');
|
|
159
|
+
expect(screen.getByTestId('t').textContent).toBe('x');
|
|
160
|
+
await act(async () => {
|
|
161
|
+
screen.getByText('de').click();
|
|
162
|
+
});
|
|
163
|
+
expect(screen.getByTestId('status').textContent).toBe('error');
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it('surfaces error when create fails with non-Error', async () => {
|
|
167
|
+
const { createLexiSyncI18n } = await import('./createI18n');
|
|
168
|
+
vi.mocked(createLexiSyncI18n).mockRejectedValueOnce('string-fail');
|
|
169
|
+
|
|
170
|
+
function ErrProbe() {
|
|
171
|
+
const { status, error } = useLexiSync();
|
|
172
|
+
return createElement(
|
|
173
|
+
'div',
|
|
174
|
+
null,
|
|
175
|
+
createElement('span', { 'data-testid': 'status' }, status),
|
|
176
|
+
createElement('span', { 'data-testid': 'err' }, error?.message || '')
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
render(createElement(LexiSyncProvider, { projectId: 'p1' }, createElement(ErrProbe)));
|
|
181
|
+
await waitFor(() => expect(screen.getByTestId('status').textContent).toBe('error'));
|
|
182
|
+
expect(screen.getByTestId('err').textContent).toBe('string-fail');
|
|
183
|
+
});
|
|
184
|
+
});
|
package/src/provider.tsx
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createContext,
|
|
3
|
+
createElement,
|
|
4
|
+
useCallback,
|
|
5
|
+
useContext,
|
|
6
|
+
useEffect,
|
|
7
|
+
useMemo,
|
|
8
|
+
useState,
|
|
9
|
+
type ReactNode,
|
|
10
|
+
} from 'react';
|
|
11
|
+
import type { i18n as I18nInstance } from 'i18next';
|
|
12
|
+
import { createLexiSyncI18n, resolveConfig } from './createI18n';
|
|
13
|
+
import type { LexiSyncConfig, LexiSyncContextValue, LexiSyncStatus } from './types';
|
|
14
|
+
|
|
15
|
+
const LexiSyncContext = createContext<LexiSyncContextValue | null>(null);
|
|
16
|
+
|
|
17
|
+
export type LexiSyncProviderProps = LexiSyncConfig & {
|
|
18
|
+
children: ReactNode;
|
|
19
|
+
/** Optional pre-built i18n instance (tests / advanced). */
|
|
20
|
+
i18n?: I18nInstance;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
function toError(e: unknown): Error {
|
|
24
|
+
return e instanceof Error ? e : new Error(String(e));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function LexiSyncProvider(props: LexiSyncProviderProps) {
|
|
28
|
+
const { children, i18n: externalI18n, ...rawConfig } = props;
|
|
29
|
+
const config = useMemo(
|
|
30
|
+
() => resolveConfig(rawConfig),
|
|
31
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps -- stable by field
|
|
32
|
+
[
|
|
33
|
+
rawConfig.projectId,
|
|
34
|
+
rawConfig.apiKey,
|
|
35
|
+
rawConfig.apiUrl,
|
|
36
|
+
rawConfig.cdnUrl,
|
|
37
|
+
rawConfig.version,
|
|
38
|
+
rawConfig.lng,
|
|
39
|
+
rawConfig.fallbackLng,
|
|
40
|
+
rawConfig.ns,
|
|
41
|
+
rawConfig.defaultNS,
|
|
42
|
+
rawConfig.saveMissing,
|
|
43
|
+
]
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
const [instance, setInstance] = useState<I18nInstance | null>(() => externalI18n ?? null);
|
|
47
|
+
const [status, setStatus] = useState<LexiSyncStatus>(() => (externalI18n ? 'ready' : 'loading'));
|
|
48
|
+
const [error, setError] = useState<Error | null>(null);
|
|
49
|
+
const [tick, setTick] = useState(0);
|
|
50
|
+
|
|
51
|
+
const bootstrap = useCallback(async () => {
|
|
52
|
+
if (externalI18n) {
|
|
53
|
+
setInstance(externalI18n);
|
|
54
|
+
setStatus('ready');
|
|
55
|
+
setError(null);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
setStatus('loading');
|
|
59
|
+
setError(null);
|
|
60
|
+
try {
|
|
61
|
+
const i18n = await createLexiSyncI18n(config);
|
|
62
|
+
setInstance(i18n);
|
|
63
|
+
setStatus('ready');
|
|
64
|
+
} catch (e) {
|
|
65
|
+
setError(toError(e));
|
|
66
|
+
setStatus('error');
|
|
67
|
+
}
|
|
68
|
+
}, [config, externalI18n]);
|
|
69
|
+
|
|
70
|
+
useEffect(() => {
|
|
71
|
+
void bootstrap();
|
|
72
|
+
}, [bootstrap]);
|
|
73
|
+
|
|
74
|
+
const changeLanguage = useCallback(async (lng: string) => {
|
|
75
|
+
setInstance((current) => {
|
|
76
|
+
if (current) {
|
|
77
|
+
void current.changeLanguage(lng).then(() => setTick((t) => t + 1));
|
|
78
|
+
}
|
|
79
|
+
return current;
|
|
80
|
+
});
|
|
81
|
+
}, []);
|
|
82
|
+
|
|
83
|
+
const reload = useCallback(async () => {
|
|
84
|
+
if (externalI18n) {
|
|
85
|
+
await externalI18n.reloadResources();
|
|
86
|
+
setTick((t) => t + 1);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
await bootstrap();
|
|
90
|
+
setTick((t) => t + 1);
|
|
91
|
+
}, [bootstrap, externalI18n]);
|
|
92
|
+
|
|
93
|
+
const t = useCallback(
|
|
94
|
+
(key: string, options?: Record<string, unknown>) => {
|
|
95
|
+
void tick;
|
|
96
|
+
return instance ? instance.t(key, options) : key;
|
|
97
|
+
},
|
|
98
|
+
[instance, tick]
|
|
99
|
+
);
|
|
100
|
+
|
|
101
|
+
const value = useMemo<LexiSyncContextValue | null>(() => {
|
|
102
|
+
if (!instance && status !== 'error') {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
config,
|
|
107
|
+
status,
|
|
108
|
+
error,
|
|
109
|
+
i18n: (instance ?? (null as unknown as I18nInstance)),
|
|
110
|
+
t,
|
|
111
|
+
changeLanguage,
|
|
112
|
+
reload,
|
|
113
|
+
};
|
|
114
|
+
}, [instance, status, error, config, t, changeLanguage, reload]);
|
|
115
|
+
|
|
116
|
+
if (!value) {
|
|
117
|
+
return createElement('div', { 'data-lexisync-status': status, role: 'status' }, 'Loading translations…');
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return createElement(LexiSyncContext.Provider, { value }, children);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function useLexiSync(): LexiSyncContextValue {
|
|
124
|
+
const ctx = useContext(LexiSyncContext);
|
|
125
|
+
if (!ctx) {
|
|
126
|
+
throw new Error('useLexiSync must be used within <LexiSyncProvider>');
|
|
127
|
+
}
|
|
128
|
+
return ctx;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Shortcut: translation function bound to the provider instance. */
|
|
132
|
+
export function useT() {
|
|
133
|
+
return useLexiSync().t;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export { LexiSyncContext };
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export type LexiSyncConfig = {
|
|
2
|
+
/** LexiSync project id from the dashboard */
|
|
3
|
+
projectId: string;
|
|
4
|
+
/** Secret key (sk_…) — required for saveMissing / write */
|
|
5
|
+
apiKey?: string;
|
|
6
|
+
/** Platform origin, default https://lexisync.app */
|
|
7
|
+
apiUrl?: string;
|
|
8
|
+
/** CDN origin, default https://cdn.lexisync.app when apiUrl is lexisync.app */
|
|
9
|
+
cdnUrl?: string;
|
|
10
|
+
/**
|
|
11
|
+
* Catalog version:
|
|
12
|
+
* - `latest` — working copy (dev, saveMissing)
|
|
13
|
+
* - `production` / `1.0.0` / … — published CDN snapshot
|
|
14
|
+
*/
|
|
15
|
+
version?: string;
|
|
16
|
+
lng?: string;
|
|
17
|
+
fallbackLng?: string | string[];
|
|
18
|
+
ns?: string | string[];
|
|
19
|
+
defaultNS?: string;
|
|
20
|
+
/** Auto-push missing keys to working copy (needs apiKey, version latest) */
|
|
21
|
+
saveMissing?: boolean;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type LexiSyncStatus = 'idle' | 'loading' | 'ready' | 'error';
|
|
25
|
+
|
|
26
|
+
export type LexiSyncContextValue = {
|
|
27
|
+
config: Required<Pick<LexiSyncConfig, 'projectId' | 'apiUrl' | 'version'>> & LexiSyncConfig;
|
|
28
|
+
status: LexiSyncStatus;
|
|
29
|
+
error: Error | null;
|
|
30
|
+
i18n: import('i18next').i18n;
|
|
31
|
+
t: (key: string, options?: Record<string, unknown>) => string;
|
|
32
|
+
changeLanguage: (lng: string) => Promise<void>;
|
|
33
|
+
reload: () => Promise<void>;
|
|
34
|
+
};
|