@inglorious/i18n 1.2.3 → 2.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/README.md +19 -7
- package/package.json +3 -3
- package/src/index.js +58 -59
- package/src/index.test.js +95 -10
- package/src/trans.js +0 -4
- package/src/trans.test.js +0 -1
- package/types/index.d.ts +22 -11
package/README.md
CHANGED
|
@@ -96,31 +96,43 @@ api.notify("#i18n:userLocaleClear")
|
|
|
96
96
|
|
|
97
97
|
## Labels in data
|
|
98
98
|
|
|
99
|
-
Options defined in data would freeze in the language of the moment they were created.
|
|
99
|
+
Options defined in data would freeze in the language of the moment they were created. Keep the key as the label, and translate it where it is rendered. A label that is not a key, such as a place name, comes back as it is:
|
|
100
100
|
|
|
101
101
|
```javascript
|
|
102
|
-
const periods = [
|
|
102
|
+
const periods = [{ value: "week", label: "periods.week" }]
|
|
103
103
|
|
|
104
|
-
|
|
105
|
-
|
|
104
|
+
periods.map((period) => ({ ...period, label: t(period.label) }))
|
|
105
|
+
t("Lombardy") // data, not copy: as is
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Messages in state
|
|
109
|
+
|
|
110
|
+
For the same reason, state holds a message's key rather than its text: an error saved in Italian would stay Italian after a switch to English. `t` takes the message as it is kept: a key, `{ key, values }` for one that interpolates, or text that is not a key, such as an error from a server, which comes back as it is.
|
|
111
|
+
|
|
112
|
+
```javascript
|
|
113
|
+
entity.error = { key: "errors.tooLong", values: { max: 80 } }
|
|
114
|
+
|
|
115
|
+
html`<p>${t(entity.error)}</p>`
|
|
106
116
|
```
|
|
107
117
|
|
|
108
118
|
## API
|
|
109
119
|
|
|
110
120
|
### `createI18n(options)`
|
|
111
121
|
|
|
112
|
-
Returns `{ I18n, ready, languages, t, trans, currentLocale,
|
|
122
|
+
Returns `{ I18n, ready, languages, t, trans, currentLocale, i18next }`.
|
|
113
123
|
|
|
114
124
|
- `catalogues`: the catalogues by file path, as `import.meta.glob("./locales/*.json")` returns them. A lazy glob loads each on demand; an eager one (`{ eager: true }`) bundles them all.
|
|
115
125
|
- `resources`: catalogues bundled with the app, `{ [locale]: { translation: { … } } }`. The lower-level alternative to `catalogues`.
|
|
116
126
|
- `loadLocale`: loads a locale that is not in `resources`, resolving to `{ translation: { … } }`. The lower-level alternative to a lazy glob.
|
|
117
127
|
- `locales`: the supported locales, in picker order. Defaults to those in `catalogues` and `resources`.
|
|
118
128
|
- `saveUserLocale`: saves the locale for the signed-in user. See [The user's language](#the-users-language).
|
|
129
|
+
- `isServerRendered`: whether the page comes rendered from a server, as with SSX. It then starts in the language of `<html lang>`, the one the server rendered, so hydration keeps it and only its catalogue loads. Leave it off for a page served as is, whose `<html lang>` says nothing about the visitor.
|
|
119
130
|
- `defaultLocale`: the fallback, and the locale when nothing else matches. Defaults to the first locale.
|
|
120
131
|
- `storageKey`: where to remember the user's choice in `localStorage`. Omit it to not remember the choice.
|
|
132
|
+
- `queryParam`: the query parameter a link names the language with, such as `"lang"` for `?lang=it`, so a page linking to the app can open it in the page's language. That locale is remembered, as a choice would be.
|
|
121
133
|
- `i18nextOptions`: any further i18next options.
|
|
122
134
|
|
|
123
|
-
The starting locale is the saved choice, else the first of the device's languages that is supported (`it-CH` picks `it`), else `defaultLocale`.
|
|
135
|
+
The starting locale is that of `<html lang>` on a server-rendered page, when supported, else the one in `queryParam`, else the saved choice, else the first of the device's languages that is supported (`it-CH` picks `it`), else `defaultLocale`.
|
|
124
136
|
|
|
125
137
|
`ready` resolves once the starting locale and the fallback are loaded: at once when they are bundled. With every catalogue bundled, i18next also switches synchronously, so there is no loading state to handle.
|
|
126
138
|
|
|
@@ -185,6 +197,6 @@ It is safe with user data:
|
|
|
185
197
|
- A tag without a component (`<script>`, a typo, a stray `</b>`) shows as written instead of becoming markup.
|
|
186
198
|
- Plurals and formatters work as in `t`: `trans("events", { values: { count } })`.
|
|
187
199
|
|
|
188
|
-
### `detectLocale({ locales, defaultLocale, storageKey })`
|
|
200
|
+
### `detectLocale({ locales, defaultLocale, storageKey, queryParam })`
|
|
189
201
|
|
|
190
202
|
The detection `createI18n` uses, exported for apps that need it elsewhere.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inglorious/i18n",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Internationalization for Inglorious Web: an i18next instance driven by a store entity.",
|
|
5
5
|
"author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
|
|
6
6
|
"license": "MIT",
|
|
@@ -38,12 +38,12 @@
|
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
40
|
"@inglorious/eslint-config": "1.2.0",
|
|
41
|
-
"@inglorious/store": "12.1.
|
|
41
|
+
"@inglorious/store": "12.1.1",
|
|
42
42
|
"prettier": "^3.9.6",
|
|
43
43
|
"vitest": "^5.0.0"
|
|
44
44
|
},
|
|
45
45
|
"engines": {
|
|
46
|
-
"node": ">=
|
|
46
|
+
"node": ">= 26"
|
|
47
47
|
},
|
|
48
48
|
"scripts": {
|
|
49
49
|
"format": "prettier --write .",
|
package/src/index.js
CHANGED
|
@@ -34,8 +34,10 @@ export function createI18n({
|
|
|
34
34
|
resources: givenResources = {},
|
|
35
35
|
loadLocale: givenLoadLocale,
|
|
36
36
|
locales: givenLocales,
|
|
37
|
+
isServerRendered = false,
|
|
37
38
|
defaultLocale,
|
|
38
39
|
storageKey,
|
|
40
|
+
queryParam,
|
|
39
41
|
saveUserLocale,
|
|
40
42
|
i18nextOptions = {},
|
|
41
43
|
}) {
|
|
@@ -49,11 +51,20 @@ export function createI18n({
|
|
|
49
51
|
]
|
|
50
52
|
const [firstLocale = "en"] = locales
|
|
51
53
|
const fallbackLocale = defaultLocale ?? firstLocale
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
54
|
+
// A server-rendered page is already in a language, which hydration must keep.
|
|
55
|
+
// In a page served as is, `<html lang>` is whatever the file says, so it is
|
|
56
|
+
// detected instead.
|
|
57
|
+
const startLocale =
|
|
58
|
+
(isServerRendered && matchLocale(getDocumentLanguage(), locales)) ||
|
|
59
|
+
detectLocale({
|
|
60
|
+
locales,
|
|
61
|
+
defaultLocale: fallbackLocale,
|
|
62
|
+
storageKey,
|
|
63
|
+
queryParam,
|
|
64
|
+
})
|
|
65
|
+
if (startLocale === queryLocale(queryParam, locales)) {
|
|
66
|
+
saveLocale(storageKey, startLocale)
|
|
67
|
+
}
|
|
57
68
|
const languages = locales.map((locale) => ({
|
|
58
69
|
value: locale,
|
|
59
70
|
label: languageName(locale),
|
|
@@ -63,24 +74,19 @@ export function createI18n({
|
|
|
63
74
|
instance.init({
|
|
64
75
|
...i18nextOptions,
|
|
65
76
|
resources,
|
|
66
|
-
// Until a loaded catalogue arrives, keys fall back rather than wait.
|
|
67
77
|
partialBundledLanguages: true,
|
|
68
78
|
lng: startLocale,
|
|
69
79
|
fallbackLng: fallbackLocale,
|
|
70
80
|
supportedLngs: locales,
|
|
71
|
-
// lit-html escapes every text binding already; escaping here too would
|
|
72
|
-
// print entities such as & on screen.
|
|
73
81
|
interpolation: { escapeValue: false, ...i18nextOptions.interpolation },
|
|
74
82
|
initAsync: false,
|
|
75
83
|
})
|
|
76
84
|
|
|
77
85
|
const loader = createLoader(instance, resources, loadLocale)
|
|
78
86
|
|
|
79
|
-
// The fallback too: it fills in whatever the starting locale is missing.
|
|
80
87
|
const ready = Promise.all(
|
|
81
88
|
[...new Set([startLocale, fallbackLocale])].map((locale) =>
|
|
82
89
|
loader.load(locale).catch((error) => {
|
|
83
|
-
// The app still starts, with whatever did load.
|
|
84
90
|
console.warn(`[i18n] could not load "${locale}":`, error)
|
|
85
91
|
}),
|
|
86
92
|
),
|
|
@@ -98,9 +104,6 @@ export function createI18n({
|
|
|
98
104
|
applyDocumentLanguage(entity.locale, entity.dir)
|
|
99
105
|
},
|
|
100
106
|
|
|
101
|
-
// The user's choice: a locale, or a picker's `{ value }`. With
|
|
102
|
-
// `saveUserLocale` it is saved for the signed-in user at once, and kept
|
|
103
|
-
// for whoever signs in next otherwise.
|
|
104
107
|
localeChange(entity, payload, api) {
|
|
105
108
|
const locale = payload?.value ?? payload
|
|
106
109
|
if (!requestLocale(entity, locale, api)) return
|
|
@@ -110,8 +113,6 @@ export function createI18n({
|
|
|
110
113
|
else entity.isUnsaved = true
|
|
111
114
|
},
|
|
112
115
|
|
|
113
|
-
// Only the latest request switches: a slower load for a locale the user
|
|
114
|
-
// has since moved away from is kept for later, but not applied.
|
|
115
116
|
localeLoadSuccess(entity, locale) {
|
|
116
117
|
if (entity.loadingLocale !== locale) return
|
|
117
118
|
entity.loadingLocale = null
|
|
@@ -124,10 +125,6 @@ export function createI18n({
|
|
|
124
125
|
console.warn(`[i18n] could not load "${locale}":`, error)
|
|
125
126
|
},
|
|
126
127
|
|
|
127
|
-
// The signed-in user and the locale saved for them, or none yet. A choice
|
|
128
|
-
// made before they signed in is the more recent, so it is saved instead
|
|
129
|
-
// of applying theirs; with nothing saved, the current one is. Once per
|
|
130
|
-
// user, so reloading their data does not undo a change still being saved.
|
|
131
128
|
userLocaleLoad(entity, { userId, locale }, api) {
|
|
132
129
|
if (entity.userId === userId) return
|
|
133
130
|
entity.userId = userId
|
|
@@ -141,32 +138,22 @@ export function createI18n({
|
|
|
141
138
|
requestLocale(entity, locale, api)
|
|
142
139
|
},
|
|
143
140
|
|
|
144
|
-
// Signed out: later choices wait for the next user.
|
|
145
141
|
userLocaleClear(entity) {
|
|
146
142
|
entity.userId = null
|
|
147
143
|
entity.isUnsaved = false
|
|
148
144
|
},
|
|
149
145
|
}
|
|
150
146
|
|
|
151
|
-
// Switches to `locale`, loading it first if needed, so `loadingLocale` names
|
|
152
|
-
// it until its catalogue is in: what a server render or a hydration waits for.
|
|
153
|
-
// Whether it is a change.
|
|
154
147
|
function requestLocale(entity, locale, api) {
|
|
155
148
|
if (!locales.includes(locale)) return false
|
|
156
149
|
const isChange = locale !== entity.locale
|
|
157
|
-
// Choosing the current locale again also cancels a pending change.
|
|
158
150
|
entity.loadingLocale = null
|
|
159
151
|
|
|
160
152
|
if (loader.isLoaded(locale)) {
|
|
161
|
-
// The i18next instance is shared by every store, as on a server rendering
|
|
162
|
-
// pages in different languages, so it can be elsewhere when the entity is not.
|
|
163
153
|
if (isChange || locale !== instance.language) switchLocale(entity, locale)
|
|
164
154
|
return isChange
|
|
165
155
|
}
|
|
166
156
|
|
|
167
|
-
// Also the current locale, while the catalogue it started with is loading.
|
|
168
|
-
// The id is taken now: the promise settles after this batch, when the
|
|
169
|
-
// entity here is no longer the live one.
|
|
170
157
|
const id = entity.id
|
|
171
158
|
entity.loadingLocale = locale
|
|
172
159
|
loader.load(locale).then(
|
|
@@ -206,7 +193,14 @@ export function createI18n({
|
|
|
206
193
|
)
|
|
207
194
|
}
|
|
208
195
|
|
|
196
|
+
/**
|
|
197
|
+
* Translates a key, or a message kept in state as `{ key, values }`. Text
|
|
198
|
+
* that is not a key, such as an error from a server, comes back as it is.
|
|
199
|
+
*/
|
|
209
200
|
function t(key, options) {
|
|
201
|
+
if (key && typeof key === "object" && !Array.isArray(key)) {
|
|
202
|
+
return instance.t(key.key, { ...key.values, ...options })
|
|
203
|
+
}
|
|
210
204
|
return instance.t(key, options)
|
|
211
205
|
}
|
|
212
206
|
|
|
@@ -216,34 +210,29 @@ export function createI18n({
|
|
|
216
210
|
languages,
|
|
217
211
|
t,
|
|
218
212
|
trans,
|
|
219
|
-
// The active locale, for `Intl` formatters.
|
|
220
213
|
currentLocale: () => instance.language,
|
|
221
|
-
// A data item whose label follows the language: `label` reads through `t`
|
|
222
|
-
// every time, and `labelKey` survives being copied into store state,
|
|
223
|
-
// where the getter would freeze into the text of the moment.
|
|
224
|
-
labelled: (labelKey, fields = {}) => ({
|
|
225
|
-
...fields,
|
|
226
|
-
labelKey,
|
|
227
|
-
get label() {
|
|
228
|
-
return t(labelKey)
|
|
229
|
-
},
|
|
230
|
-
}),
|
|
231
|
-
// An option's label: translated when it carries a key, as is otherwise.
|
|
232
|
-
translatedLabel: (option) =>
|
|
233
|
-
option.labelKey ? t(option.labelKey) : option.label,
|
|
234
214
|
i18next: instance,
|
|
235
215
|
}
|
|
236
216
|
}
|
|
237
217
|
|
|
238
218
|
/**
|
|
239
|
-
* The locale to start with: the one
|
|
240
|
-
* first of the device's languages that is
|
|
241
|
-
* language, so `it-CH` picks `it`), else the
|
|
219
|
+
* The locale to start with: the one a link names in `queryParam`, else the one
|
|
220
|
+
* saved by a previous choice, else the first of the device's languages that is
|
|
221
|
+
* supported (exactly, or by its base language, so `it-CH` picks `it`), else the
|
|
222
|
+
* default.
|
|
242
223
|
*
|
|
243
|
-
* @param {{ locales: string[], defaultLocale: string, storageKey?: string }} options
|
|
224
|
+
* @param {{ locales: string[], defaultLocale: string, storageKey?: string, queryParam?: string }} options
|
|
244
225
|
* @returns {string}
|
|
245
226
|
*/
|
|
246
|
-
export function detectLocale({
|
|
227
|
+
export function detectLocale({
|
|
228
|
+
locales,
|
|
229
|
+
defaultLocale,
|
|
230
|
+
storageKey,
|
|
231
|
+
queryParam,
|
|
232
|
+
}) {
|
|
233
|
+
const linked = queryLocale(queryParam, locales)
|
|
234
|
+
if (linked) return linked
|
|
235
|
+
|
|
247
236
|
const saved = readLocale(storageKey)
|
|
248
237
|
if (saved && locales.includes(saved)) return saved
|
|
249
238
|
|
|
@@ -251,15 +240,28 @@ export function detectLocale({ locales, defaultLocale, storageKey }) {
|
|
|
251
240
|
typeof navigator === "undefined"
|
|
252
241
|
? []
|
|
253
242
|
: (navigator.languages ?? [navigator.language])
|
|
254
|
-
for (const language of preferred
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
if (locales.includes(base)) return base
|
|
243
|
+
for (const language of preferred) {
|
|
244
|
+
const locale = matchLocale(language, locales)
|
|
245
|
+
if (locale) return locale
|
|
258
246
|
}
|
|
259
247
|
|
|
260
248
|
return defaultLocale
|
|
261
249
|
}
|
|
262
250
|
|
|
251
|
+
function queryLocale(queryParam, locales) {
|
|
252
|
+
if (!queryParam) return null
|
|
253
|
+
const search = globalThis.location?.search ?? ""
|
|
254
|
+
const locale = new URLSearchParams(search).get(queryParam)
|
|
255
|
+
return locales.includes(locale) ? locale : null
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function matchLocale(language, locales) {
|
|
259
|
+
if (!language) return null
|
|
260
|
+
if (locales.includes(language)) return language
|
|
261
|
+
const [base] = language.split("-")
|
|
262
|
+
return locales.includes(base) ? base : null
|
|
263
|
+
}
|
|
264
|
+
|
|
263
265
|
/**
|
|
264
266
|
* Turns `catalogues`, a map from file path to catalogue such as
|
|
265
267
|
* `import.meta.glob` returns, into the resources and loader i18next needs.
|
|
@@ -313,7 +315,6 @@ function createLoader(instance, resources, loadLocale) {
|
|
|
313
315
|
if (isLoaded(locale)) return Promise.resolve()
|
|
314
316
|
if (pending.has(locale)) return pending.get(locale)
|
|
315
317
|
|
|
316
|
-
// Called right away; a loader that throws rejects like one that fails.
|
|
317
318
|
const promise = new Promise((resolve) => resolve(loadLocale(locale)))
|
|
318
319
|
.then((bundles) => {
|
|
319
320
|
for (const [namespace, catalogue] of Object.entries(bundles ?? {})) {
|
|
@@ -351,8 +352,6 @@ function readLocale(storageKey) {
|
|
|
351
352
|
try {
|
|
352
353
|
return globalThis.localStorage?.getItem(storageKey) ?? null
|
|
353
354
|
} catch {
|
|
354
|
-
// Storage can be unavailable (private mode, server rendering): fall back
|
|
355
|
-
// to detection rather than failing.
|
|
356
355
|
return null
|
|
357
356
|
}
|
|
358
357
|
}
|
|
@@ -366,10 +365,10 @@ function saveLocale(storageKey, locale) {
|
|
|
366
365
|
}
|
|
367
366
|
}
|
|
368
367
|
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
368
|
+
function getDocumentLanguage() {
|
|
369
|
+
return globalThis.document?.documentElement.lang
|
|
370
|
+
}
|
|
371
|
+
|
|
373
372
|
function applyDocumentLanguage(locale, dir) {
|
|
374
373
|
if (typeof document === "undefined") return
|
|
375
374
|
document.documentElement.lang = locale
|
package/src/index.test.js
CHANGED
|
@@ -22,8 +22,9 @@ const resources = {
|
|
|
22
22
|
},
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
function stubBrowser({ languages = [], saved = {} } = {}) {
|
|
25
|
+
function stubBrowser({ languages = [], saved = {}, search = "" } = {}) {
|
|
26
26
|
const store = { ...saved }
|
|
27
|
+
vi.stubGlobal("location", { search })
|
|
27
28
|
vi.stubGlobal("navigator", { languages, language: languages[0] })
|
|
28
29
|
vi.stubGlobal("localStorage", {
|
|
29
30
|
getItem: (key) => store[key] ?? null,
|
|
@@ -61,6 +62,16 @@ describe("detectLocale", () => {
|
|
|
61
62
|
expect(detectLocale(options)).toBe("en")
|
|
62
63
|
})
|
|
63
64
|
|
|
65
|
+
it("prefers the locale a link names", () => {
|
|
66
|
+
stubBrowser({ saved: { lang: "en" }, search: "?lang=it" })
|
|
67
|
+
expect(detectLocale({ ...options, queryParam: "lang" })).toBe("it")
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
it("ignores a linked locale that is not supported", () => {
|
|
71
|
+
stubBrowser({ saved: { lang: "it" }, search: "?lang=de" })
|
|
72
|
+
expect(detectLocale({ ...options, queryParam: "lang" })).toBe("it")
|
|
73
|
+
})
|
|
74
|
+
|
|
64
75
|
it("ignores a saved locale that is no longer supported", () => {
|
|
65
76
|
stubBrowser({ languages: ["en"], saved: { lang: "de" } })
|
|
66
77
|
expect(detectLocale(options)).toBe("en")
|
|
@@ -89,6 +100,45 @@ describe("createI18n", () => {
|
|
|
89
100
|
expect(document.documentElement.lang).toBe("it")
|
|
90
101
|
})
|
|
91
102
|
|
|
103
|
+
it("starts a server-rendered page in its language, ahead of the saved choice and the device", () => {
|
|
104
|
+
stubBrowser({ languages: ["en"], saved: { lang: "en" } })
|
|
105
|
+
document.documentElement.lang = "it-IT"
|
|
106
|
+
const { I18n, t } = createI18n({
|
|
107
|
+
resources,
|
|
108
|
+
isServerRendered: true,
|
|
109
|
+
storageKey: "lang",
|
|
110
|
+
})
|
|
111
|
+
const entity = {}
|
|
112
|
+
|
|
113
|
+
I18n.create(entity)
|
|
114
|
+
|
|
115
|
+
expect(entity.locale).toBe("it")
|
|
116
|
+
expect(document.documentElement.lang).toBe("it")
|
|
117
|
+
expect(t("hello")).toBe("Ciao")
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
it("detects the locale when the page's language is unsupported", () => {
|
|
121
|
+
stubBrowser({ languages: ["it"] })
|
|
122
|
+
document.documentElement.lang = "de"
|
|
123
|
+
const { I18n } = createI18n({ resources, isServerRendered: true })
|
|
124
|
+
const entity = {}
|
|
125
|
+
|
|
126
|
+
I18n.create(entity)
|
|
127
|
+
|
|
128
|
+
expect(entity.locale).toBe("it")
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
it("ignores the language of a page that is not server-rendered", () => {
|
|
132
|
+
stubBrowser({ languages: ["it"] })
|
|
133
|
+
document.documentElement.lang = "en"
|
|
134
|
+
const { I18n } = createI18n({ resources })
|
|
135
|
+
const entity = {}
|
|
136
|
+
|
|
137
|
+
I18n.create(entity)
|
|
138
|
+
|
|
139
|
+
expect(entity.locale).toBe("it")
|
|
140
|
+
})
|
|
141
|
+
|
|
92
142
|
it("switches language, remembers it and ignores unsupported ones", () => {
|
|
93
143
|
const saved = stubBrowser({ languages: ["en"] })
|
|
94
144
|
const { I18n, t } = createI18n({ resources, storageKey: "lang" })
|
|
@@ -127,7 +177,6 @@ describe("createI18n", () => {
|
|
|
127
177
|
describe("loadLocale", () => {
|
|
128
178
|
const { en, it: italian } = resources
|
|
129
179
|
|
|
130
|
-
// A loader whose loads resolve or fail when the test says so.
|
|
131
180
|
function controlledLoader() {
|
|
132
181
|
const loads = {}
|
|
133
182
|
const loadLocale = vi.fn(
|
|
@@ -168,6 +217,24 @@ describe("loadLocale", () => {
|
|
|
168
217
|
expect(t("hello")).toBe("Ciao")
|
|
169
218
|
})
|
|
170
219
|
|
|
220
|
+
it("loads only the server-rendered page's locale, not the device's", async () => {
|
|
221
|
+
stubBrowser({ languages: ["fr-FR"] })
|
|
222
|
+
document.documentElement.lang = "it"
|
|
223
|
+
const loadLocale = vi.fn(async () => italian)
|
|
224
|
+
const { ready, t } = createI18n({
|
|
225
|
+
resources: { en },
|
|
226
|
+
locales: ["en", "it", "fr"],
|
|
227
|
+
isServerRendered: true,
|
|
228
|
+
loadLocale,
|
|
229
|
+
})
|
|
230
|
+
|
|
231
|
+
await ready
|
|
232
|
+
|
|
233
|
+
expect(loadLocale).toHaveBeenCalledTimes(1)
|
|
234
|
+
expect(loadLocale).toHaveBeenCalledWith("it")
|
|
235
|
+
expect(t("hello")).toBe("Ciao")
|
|
236
|
+
})
|
|
237
|
+
|
|
171
238
|
it("is ready at once when the starting locale is bundled", async () => {
|
|
172
239
|
stubBrowser({ languages: ["en"] })
|
|
173
240
|
const loadLocale = vi.fn()
|
|
@@ -444,22 +511,40 @@ describe("direction", () => {
|
|
|
444
511
|
})
|
|
445
512
|
|
|
446
513
|
describe("helpers", () => {
|
|
447
|
-
it("
|
|
448
|
-
stubBrowser({ languages: ["en"] })
|
|
449
|
-
const {
|
|
514
|
+
it("remembers the locale a link names", () => {
|
|
515
|
+
const saved = stubBrowser({ languages: ["en"], search: "?lang=it" })
|
|
516
|
+
const { t } = createI18n({
|
|
450
517
|
resources,
|
|
518
|
+
storageKey: "lang",
|
|
519
|
+
queryParam: "lang",
|
|
451
520
|
})
|
|
521
|
+
|
|
522
|
+
expect(t("hello")).toBe("Ciao")
|
|
523
|
+
expect(saved.lang).toBe("it")
|
|
524
|
+
})
|
|
525
|
+
|
|
526
|
+
it("translates messages kept in state, and leaves other text as it is", () => {
|
|
527
|
+
stubBrowser({ languages: ["en"] })
|
|
528
|
+
const { t } = createI18n({ resources })
|
|
529
|
+
|
|
530
|
+
expect(t("hello")).toBe("Hello")
|
|
531
|
+
expect(t({ key: "greet", values: { name: "Ada" } })).toBe("Hello, Ada")
|
|
532
|
+
expect(t("Network down: retry later.")).toBe("Network down: retry later.")
|
|
533
|
+
})
|
|
534
|
+
|
|
535
|
+
it("translates a label kept as a key in the active language", () => {
|
|
536
|
+
stubBrowser({ languages: ["en"] })
|
|
537
|
+
const { I18n, t, currentLocale } = createI18n({ resources })
|
|
452
538
|
const entity = {}
|
|
453
539
|
I18n.create(entity)
|
|
454
|
-
const option =
|
|
540
|
+
const option = { value: "greeting", label: "hello" }
|
|
455
541
|
|
|
456
|
-
expect(option.label).toBe("Hello")
|
|
542
|
+
expect(t(option.label)).toBe("Hello")
|
|
457
543
|
|
|
458
544
|
I18n.localeChange(entity, "it")
|
|
459
545
|
|
|
460
|
-
expect(option.label).toBe("Ciao")
|
|
546
|
+
expect(t(option.label)).toBe("Ciao")
|
|
461
547
|
expect(currentLocale()).toBe("it")
|
|
462
|
-
expect(
|
|
463
|
-
expect(translatedLabel({ label: "Lombardy" })).toBe("Lombardy")
|
|
548
|
+
expect(t("Lombardy")).toBe("Lombardy")
|
|
464
549
|
})
|
|
465
550
|
})
|
package/src/trans.js
CHANGED
|
@@ -28,7 +28,6 @@ export function parseTrans(raw, components, interpolate) {
|
|
|
28
28
|
|
|
29
29
|
const component = components[name]
|
|
30
30
|
if (!component) {
|
|
31
|
-
// Not one of the caller's tags: show it as it was written.
|
|
32
31
|
current.children.push(source)
|
|
33
32
|
} else if (selfClosing) {
|
|
34
33
|
current.children.push(component([]))
|
|
@@ -39,14 +38,11 @@ export function parseTrans(raw, components, interpolate) {
|
|
|
39
38
|
current = node.parent
|
|
40
39
|
current.children.push(component(node.children))
|
|
41
40
|
} else {
|
|
42
|
-
// A closing tag with nothing of its name open.
|
|
43
41
|
current.children.push(source)
|
|
44
42
|
}
|
|
45
43
|
}
|
|
46
44
|
addText(raw.slice(last))
|
|
47
45
|
|
|
48
|
-
// Tags left open were never components: put them back as text, contents
|
|
49
|
-
// and all.
|
|
50
46
|
while (current !== root) {
|
|
51
47
|
const node = current
|
|
52
48
|
current = node.parent
|
package/src/trans.test.js
CHANGED
package/types/index.d.ts
CHANGED
|
@@ -24,10 +24,22 @@ export interface I18nOptions {
|
|
|
24
24
|
* catalogue is its own chunk.
|
|
25
25
|
*/
|
|
26
26
|
loadLocale?: (locale: string) => Promise<Resource[string]>
|
|
27
|
+
/**
|
|
28
|
+
* Whether the page comes rendered from a server, as with SSX: it then starts in the
|
|
29
|
+
* language of `<html lang>`, the one the server rendered it in, instead of detecting
|
|
30
|
+
* one. Defaults to `false`.
|
|
31
|
+
*/
|
|
32
|
+
isServerRendered?: boolean
|
|
27
33
|
/** The fallback, and the locale when nothing else matches. Defaults to the first locale. */
|
|
28
34
|
defaultLocale?: string
|
|
29
35
|
/** Where to remember the user's choice in localStorage. Omit to not remember it. */
|
|
30
36
|
storageKey?: string
|
|
37
|
+
/**
|
|
38
|
+
* The query parameter a link names the language with, as in `?lang=it`. A
|
|
39
|
+
* supported locale there wins over the saved choice and the device, and is
|
|
40
|
+
* remembered with `storageKey`.
|
|
41
|
+
*/
|
|
42
|
+
queryParam?: string
|
|
31
43
|
/**
|
|
32
44
|
* Saves the user's locale wherever the app keeps their preferences, e.g.
|
|
33
45
|
* `(locale, api) => api.notify("#profile:localeSave", locale)`. Called for a
|
|
@@ -57,8 +69,6 @@ export interface I18nEntity {
|
|
|
57
69
|
isUnsaved?: boolean
|
|
58
70
|
}
|
|
59
71
|
|
|
60
|
-
// A type alias rather than an interface, so it fits option types that allow
|
|
61
|
-
// extra fields, such as Inglorious UI's `SelectOption`.
|
|
62
72
|
export type LanguageOption = {
|
|
63
73
|
value: string
|
|
64
74
|
/** The language in itself: "Italiano", "Français". */
|
|
@@ -96,6 +106,9 @@ export type I18nType = {
|
|
|
96
106
|
userLocaleClear(entity: I18nEntity): void
|
|
97
107
|
}
|
|
98
108
|
|
|
109
|
+
/** A message kept in state: a key, a key with values, or text shown as it is. */
|
|
110
|
+
export type Message = string | { key: string; values?: TOptions }
|
|
111
|
+
|
|
99
112
|
export interface TransOptions<Part = unknown> {
|
|
100
113
|
/** Values for the `{{placeholders}}`. They are inserted as text, never as markup. */
|
|
101
114
|
values?: TOptions
|
|
@@ -112,15 +125,12 @@ export interface I18n {
|
|
|
112
125
|
languages: LanguageOption[]
|
|
113
126
|
/** The active locale, for `Intl` formatters. */
|
|
114
127
|
currentLocale: () => string
|
|
115
|
-
/**
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
translatedLabel: (option: { labelKey?: string; label?: string }) => string
|
|
122
|
-
/** Translates `key` in the active locale. Same signature as i18next's `t`. */
|
|
123
|
-
t: (key: string | string[], options?: TOptions) => string
|
|
128
|
+
/**
|
|
129
|
+
* Translates `key` in the active locale, as i18next's `t`. It also takes a
|
|
130
|
+
* message kept in state as `{ key, values }`; text that is not a key comes
|
|
131
|
+
* back as it is.
|
|
132
|
+
*/
|
|
133
|
+
t: (key: string | string[] | Message, options?: TOptions) => string
|
|
124
134
|
/**
|
|
125
135
|
* Translates `key` into template parts, rendering the tags in the translation
|
|
126
136
|
* through `components`. Tags without a component show as written.
|
|
@@ -139,4 +149,5 @@ export function detectLocale(options: {
|
|
|
139
149
|
locales: string[]
|
|
140
150
|
defaultLocale: string
|
|
141
151
|
storageKey?: string
|
|
152
|
+
queryParam?: string
|
|
142
153
|
}): string
|