@inglorious/i18n 1.0.0 → 1.1.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 CHANGED
@@ -12,20 +12,27 @@ pnpm add @inglorious/i18n
12
12
 
13
13
  ## Usage
14
14
 
15
+ Put one JSON catalogue per language in a folder, named after it (`en.json`, `it.json`, …), and hand the folder to `createI18n`:
16
+
15
17
  ```javascript
16
18
  // src/i18n.js
17
19
  import { createI18n } from "@inglorious/i18n"
18
20
 
19
- import en from "./locales/en.json"
20
- import it from "./locales/it.json"
21
-
22
- export const { I18n, t } = createI18n({
23
- resources: { en: { translation: en }, it: { translation: it } },
21
+ export const { I18n, t, trans, ready } = createI18n({
22
+ catalogues: import.meta.glob("./locales/*.json"),
24
23
  defaultLocale: "en",
25
24
  storageKey: "my-app-locale",
26
25
  })
27
26
  ```
28
27
 
28
+ Each catalogue is its own chunk, loaded when it is needed. Mount once `ready` resolves: by then the user's language and the fallback are loaded, so the first render is already translated.
29
+
30
+ ```javascript
31
+ ready.then(() => mount(store, renderApp, document.getElementById("root")))
32
+ ```
33
+
34
+ Adding a language is adding its file.
35
+
29
36
  Register the type and an entity for it:
30
37
 
31
38
  ```javascript
@@ -60,26 +67,68 @@ Switch language from anywhere:
60
67
  api.notify("#i18n:localeChange", "it")
61
68
  ```
62
69
 
70
+ Switching to a locale that is not loaded yet loads it first: `entity.loadingLocale` names it until it arrives, then the switch happens as usual. Only the latest choice switches, each locale is loaded once, and a failed load leaves the current language in place and is tried again on the next change.
71
+
72
+ ## A language picker
73
+
74
+ `entity.languages` lists the supported locales as picker options, each named in itself so whoever needs it finds it whatever language is showing: `[{ value: "en", label: "English" }, { value: "it", label: "Italiano" }, …]`. The names come from `Intl.DisplayNames`. `localeChange` takes a picker's `{ value }` as well as a plain locale, so a select can notify it directly.
75
+
76
+ ## The user's language
77
+
78
+ The choice is remembered on the device with `storageKey`. To keep it with the user's account instead, so it follows them to every device, pass `saveUserLocale` and tell the entity who signed in:
79
+
80
+ ```javascript
81
+ createI18n({
82
+ catalogues: import.meta.glob("./locales/*.json"),
83
+ saveUserLocale: (locale, api) => api.notify("#profile:localeSave", locale),
84
+ })
85
+
86
+ // When the user's data arrives:
87
+ api.notify("#i18n:userLocaleLoad", { userId: user.id, locale: user.locale })
88
+ // When they sign out:
89
+ api.notify("#i18n:userLocaleClear")
90
+ ```
91
+
92
+ - A change while signed in is saved at once.
93
+ - A change made before signing in, such as on the login screen, is saved when the user arrives: it is the more recent choice.
94
+ - Otherwise the user's saved locale is applied, or the current one is saved if they have none.
95
+ - It happens once per user, so reloading their data does not undo a change still being saved.
96
+
97
+ ## Labels in data
98
+
99
+ Options defined in data would freeze in the language of the moment they were created. `labelled(key, fields)` gives an item whose `label` is translated every time it is read, and which keeps `labelKey` when it is copied into store state; `translatedLabel(option)` reads either kind:
100
+
101
+ ```javascript
102
+ const periods = [labelled("periods.week", { value: "week" })]
103
+
104
+ translatedLabel(periods[0]) // "This week", or "Questa settimana"
105
+ translatedLabel({ label: "Lombardy" }) // data, not copy: as is
106
+ ```
107
+
63
108
  ## API
64
109
 
65
110
  ### `createI18n(options)`
66
111
 
67
- Returns `{ I18n, t, trans, i18next }`.
112
+ Returns `{ I18n, ready, languages, t, trans, currentLocale, labelled, translatedLabel, i18next }`.
68
113
 
69
- - `resources`: the catalogues, `{ [locale]: { translation: { … } } }`.
70
- - `locales`: the supported locales. Defaults to the keys of `resources`.
114
+ - `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
+ - `resources`: catalogues bundled with the app, `{ [locale]: { translation: { … } } }`. The lower-level alternative to `catalogues`.
116
+ - `loadLocale`: loads a locale that is not in `resources`, resolving to `{ translation: { … } }`. The lower-level alternative to a lazy glob.
117
+ - `locales`: the supported locales, in picker order. Defaults to those in `catalogues` and `resources`.
118
+ - `saveUserLocale`: saves the locale for the signed-in user. See [The user's language](#the-users-language).
71
119
  - `defaultLocale`: the fallback, and the locale when nothing else matches. Defaults to the first locale.
72
120
  - `storageKey`: where to remember the user's choice in `localStorage`. Omit it to not remember the choice.
73
121
  - `i18nextOptions`: any further i18next options.
74
122
 
75
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`.
76
124
 
77
- With the catalogues passed in `resources`, i18next initialises and switches synchronously, so there is no loading state to handle.
125
+ `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.
78
126
 
79
127
  ### The `I18n` type
80
128
 
81
- - `create(entity)`: sets `entity.locale` and `entity.locales`, and `<html lang>`.
82
- - `localeChange(entity, locale)`: switches i18next, updates `entity.locale`, remembers the choice and sets `<html lang>`. Unsupported locales are ignored.
129
+ - `create(entity)`: sets `entity.locale`, `entity.locales` and `entity.languages`, and `<html lang>`.
130
+ - `localeChange(entity, locale)`: switches i18next, updates `entity.locale`, remembers the choice and sets `<html lang>`. Takes a locale or a picker's `{ value }`; unsupported locales are ignored. A locale not loaded yet is loaded first (`entity.loadingLocale`), and the switch follows in `localeLoadSuccess`.
131
+ - `userLocaleLoad(entity, { userId, locale })` and `userLocaleClear(entity)`: the signed-in user's locale. See [The user's language](#the-users-language).
83
132
 
84
133
  ### `t(key, options)`
85
134
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/i18n",
3
- "version": "1.0.0",
3
+ "version": "1.1.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",
package/src/index.js CHANGED
@@ -12,27 +12,60 @@ import { parseTrans } from "./trans.js"
12
12
  *
13
13
  * The locale lives in a store entity, so changing language is an ordinary
14
14
  * event: the handler switches i18next and updates the entity, and the render
15
- * that follows reads every string in the new language. With the catalogues
16
- * passed in `resources`, i18next initialises and switches synchronously, so
17
- * nothing has to wait for a promise.
15
+ * that follows reads every string in the new language.
16
+ *
17
+ * Catalogues come in `catalogues`, typically straight from Vite:
18
+ * `import.meta.glob("./locales/*.json")`. Each file is a locale named after
19
+ * it, loaded only when needed; the starting locale and the fallback are loaded
20
+ * before `ready` resolves, so mount after it and the first render is already
21
+ * translated. A change to a locale not loaded yet loads it first and switches
22
+ * when it arrives; `entity.loadingLocale` names it meanwhile. `resources` and
23
+ * `loadLocale` are the lower-level way to the same, and catalogues passed in
24
+ * `resources` are bundled and switch synchronously.
25
+ *
26
+ * With `saveUserLocale`, the language also follows the signed-in user: see
27
+ * `userLocaleLoad` below.
18
28
  *
19
29
  * @param {I18nOptions} options
20
30
  * @returns {I18n}
21
31
  */
22
32
  export function createI18n({
23
- resources,
24
- locales = Object.keys(resources ?? {}),
33
+ catalogues,
34
+ resources: givenResources = {},
35
+ loadLocale: givenLoadLocale,
36
+ locales: givenLocales,
25
37
  defaultLocale,
26
38
  storageKey,
39
+ saveUserLocale,
27
40
  i18nextOptions = {},
28
41
  }) {
42
+ const { resources, loadLocale, cataloguedLocales } = fromCatalogues(
43
+ catalogues,
44
+ givenResources,
45
+ givenLoadLocale,
46
+ )
47
+ const locales = givenLocales ?? [
48
+ ...new Set([...Object.keys(resources), ...cataloguedLocales]),
49
+ ]
29
50
  const [firstLocale = "en"] = locales
30
51
  const fallbackLocale = defaultLocale ?? firstLocale
52
+ const startLocale = detectLocale({
53
+ locales,
54
+ defaultLocale: fallbackLocale,
55
+ storageKey,
56
+ })
57
+ const languages = locales.map((locale) => ({
58
+ value: locale,
59
+ label: languageName(locale),
60
+ }))
61
+
31
62
  const instance = i18next.createInstance()
32
63
  instance.init({
33
64
  ...i18nextOptions,
34
65
  resources,
35
- lng: detectLocale({ locales, defaultLocale: fallbackLocale, storageKey }),
66
+ // Until a loaded catalogue arrives, keys fall back rather than wait.
67
+ partialBundledLanguages: true,
68
+ lng: startLocale,
36
69
  fallbackLng: fallbackLocale,
37
70
  supportedLngs: locales,
38
71
  // lit-html escapes every text binding already; escaping here too would
@@ -41,20 +74,108 @@ export function createI18n({
41
74
  initAsync: false,
42
75
  })
43
76
 
77
+ const loader = createLoader(instance, resources, loadLocale)
78
+
79
+ // The fallback too: it fills in whatever the starting locale is missing.
80
+ const ready = Promise.all(
81
+ [...new Set([startLocale, fallbackLocale])].map((locale) =>
82
+ loader.load(locale).catch((error) => {
83
+ // The app still starts, with whatever did load.
84
+ console.warn(`[i18n] could not load "${locale}":`, error)
85
+ }),
86
+ ),
87
+ ).then(() => {})
88
+
44
89
  const I18n = {
45
90
  create(entity) {
46
91
  entity.locale = instance.language
47
92
  entity.locales = locales
93
+ entity.languages = languages
94
+ entity.loadingLocale = null
95
+ entity.userId = null
96
+ entity.isUnsaved = false
48
97
  applyDocumentLanguage(entity.locale)
49
98
  },
50
99
 
51
- localeChange(entity, locale) {
52
- if (!locales.includes(locale) || locale === entity.locale) return
53
- instance.changeLanguage(locale)
54
- entity.locale = locale
55
- saveLocale(storageKey, locale)
56
- applyDocumentLanguage(locale)
100
+ // The user's choice: a locale, or a picker's `{ value }`. With
101
+ // `saveUserLocale` it is saved for the signed-in user at once, and kept
102
+ // for whoever signs in next otherwise.
103
+ localeChange(entity, payload, api) {
104
+ const locale = payload?.value ?? payload
105
+ if (!requestLocale(entity, locale, api)) return
106
+ if (!saveUserLocale) return
107
+
108
+ if (entity.userId) saveUserLocale(locale, api)
109
+ else entity.isUnsaved = true
110
+ },
111
+
112
+ // Only the latest request switches: a slower load for a locale the user
113
+ // has since moved away from is kept for later, but not applied.
114
+ localeLoadSuccess(entity, locale) {
115
+ if (entity.loadingLocale !== locale) return
116
+ entity.loadingLocale = null
117
+ switchLocale(entity, locale)
118
+ },
119
+
120
+ localeLoadError(entity, { locale, error }) {
121
+ if (entity.loadingLocale !== locale) return
122
+ entity.loadingLocale = null
123
+ console.warn(`[i18n] could not load "${locale}":`, error)
124
+ },
125
+
126
+ // The signed-in user and the locale saved for them, or none yet. A choice
127
+ // made before they signed in is the more recent, so it is saved instead
128
+ // of applying theirs; with nothing saved, the current one is. Once per
129
+ // user, so reloading their data does not undo a change still being saved.
130
+ userLocaleLoad(entity, { userId, locale }, api) {
131
+ if (entity.userId === userId) return
132
+ entity.userId = userId
133
+
134
+ if (entity.isUnsaved || !locale) {
135
+ entity.isUnsaved = false
136
+ saveUserLocale?.(entity.loadingLocale ?? entity.locale, api)
137
+ return
138
+ }
139
+
140
+ requestLocale(entity, locale, api)
57
141
  },
142
+
143
+ // Signed out: later choices wait for the next user.
144
+ userLocaleClear(entity) {
145
+ entity.userId = null
146
+ entity.isUnsaved = false
147
+ },
148
+ }
149
+
150
+ // Switches to `locale`, loading it first if needed. Whether it is a change.
151
+ function requestLocale(entity, locale, api) {
152
+ if (!locales.includes(locale)) return false
153
+ const isChange = locale !== entity.locale
154
+ // Choosing the current locale again also cancels a pending change.
155
+ entity.loadingLocale = null
156
+ if (!isChange) return false
157
+
158
+ if (loader.isLoaded(locale)) {
159
+ switchLocale(entity, locale)
160
+ return true
161
+ }
162
+
163
+ // The id is taken now: the promise settles after this batch, when the
164
+ // entity here is no longer the live one.
165
+ const id = entity.id
166
+ entity.loadingLocale = locale
167
+ loader.load(locale).then(
168
+ () => api.notify(`#${id}:localeLoadSuccess`, locale),
169
+ (error) => api.notify(`#${id}:localeLoadError`, { locale, error }),
170
+ )
171
+ return true
172
+ }
173
+
174
+ function switchLocale(entity, locale) {
175
+ instance.changeLanguage(locale)
176
+ entity.locale = locale
177
+ saveLocale(storageKey, locale)
178
+ applyDocumentLanguage(locale)
58
179
  }
59
180
 
60
181
  /**
@@ -79,10 +200,31 @@ export function createI18n({
79
200
  )
80
201
  }
81
202
 
203
+ function t(key, options) {
204
+ return instance.t(key, options)
205
+ }
206
+
82
207
  return {
83
208
  I18n,
84
- t: (key, options) => instance.t(key, options),
209
+ ready,
210
+ languages,
211
+ t,
85
212
  trans,
213
+ // The active locale, for `Intl` formatters.
214
+ currentLocale: () => instance.language,
215
+ // A data item whose label follows the language: `label` reads through `t`
216
+ // every time, and `labelKey` survives being copied into store state,
217
+ // where the getter would freeze into the text of the moment.
218
+ labelled: (labelKey, fields = {}) => ({
219
+ ...fields,
220
+ labelKey,
221
+ get label() {
222
+ return t(labelKey)
223
+ },
224
+ }),
225
+ // An option's label: translated when it carries a key, as is otherwise.
226
+ translatedLabel: (option) =>
227
+ option.labelKey ? t(option.labelKey) : option.label,
86
228
  i18next: instance,
87
229
  }
88
230
  }
@@ -112,6 +254,92 @@ export function detectLocale({ locales, defaultLocale, storageKey }) {
112
254
  return defaultLocale
113
255
  }
114
256
 
257
+ /**
258
+ * Turns `catalogues`, a map from file path to catalogue such as
259
+ * `import.meta.glob` returns, into the resources and loader i18next needs.
260
+ * Each file is a locale named after it: `./locales/it.json` is `it`. A lazy
261
+ * glob gives functions, loaded on demand; an eager one gives the modules,
262
+ * bundled. Either way the file is the `translation` namespace.
263
+ */
264
+ function fromCatalogues(catalogues, resources, loadLocale) {
265
+ if (!catalogues) return { resources, loadLocale, cataloguedLocales: [] }
266
+
267
+ const eager = { ...resources }
268
+ const lazy = {}
269
+ for (const [path, entry] of Object.entries(catalogues)) {
270
+ const locale = localeOfPath(path)
271
+ if (typeof entry === "function") lazy[locale] = entry
272
+ else eager[locale] = { translation: entry.default ?? entry }
273
+ }
274
+
275
+ return {
276
+ resources: eager,
277
+ loadLocale: async (locale) => {
278
+ if (!lazy[locale]) return loadLocale?.(locale)
279
+ const module = await lazy[locale]()
280
+ return { translation: module.default ?? module }
281
+ },
282
+ cataloguedLocales: Object.keys(catalogues).map(localeOfPath),
283
+ }
284
+ }
285
+
286
+ function localeOfPath(path) {
287
+ return path
288
+ .split("/")
289
+ .pop()
290
+ .replace(/\.[^.]+$/, "")
291
+ }
292
+
293
+ /**
294
+ * Loads each locale's catalogues once, through `loadLocale`. Locales in
295
+ * `resources` are loaded already, and without `loadLocale` every locale counts
296
+ * as loaded. A failed load is forgotten, so the next request tries again.
297
+ */
298
+ function createLoader(instance, resources, loadLocale) {
299
+ const loaded = new Set(Object.keys(resources))
300
+ const pending = new Map()
301
+
302
+ function isLoaded(locale) {
303
+ return !loadLocale || loaded.has(locale)
304
+ }
305
+
306
+ function load(locale) {
307
+ if (isLoaded(locale)) return Promise.resolve()
308
+ if (pending.has(locale)) return pending.get(locale)
309
+
310
+ // Called right away; a loader that throws rejects like one that fails.
311
+ const promise = new Promise((resolve) => resolve(loadLocale(locale)))
312
+ .then((bundles) => {
313
+ for (const [namespace, catalogue] of Object.entries(bundles ?? {})) {
314
+ instance.addResourceBundle(locale, namespace, catalogue, true, true)
315
+ }
316
+ loaded.add(locale)
317
+ })
318
+ .finally(() => pending.delete(locale))
319
+ pending.set(locale, promise)
320
+ return promise
321
+ }
322
+
323
+ return { isLoaded, load }
324
+ }
325
+
326
+ /**
327
+ * A language by its own name, as whoever speaks it looks for it in a picker:
328
+ * "Italiano", "Français". Falls back to the code where `Intl` cannot name it.
329
+ */
330
+ function languageName(locale) {
331
+ try {
332
+ const name = new Intl.DisplayNames([locale], { type: "language" }).of(
333
+ locale,
334
+ )
335
+ return name.replace(/^\p{Ll}/u, (letter) =>
336
+ letter.toLocaleUpperCase(locale),
337
+ )
338
+ } catch {
339
+ return locale
340
+ }
341
+ }
342
+
115
343
  function readLocale(storageKey) {
116
344
  if (!storageKey) return null
117
345
  try {
package/src/index.test.js CHANGED
@@ -123,3 +123,290 @@ describe("createI18n", () => {
123
123
  expect(t("hello")).toBe("Ciao")
124
124
  })
125
125
  })
126
+
127
+ describe("loadLocale", () => {
128
+ const { en, it: italian } = resources
129
+
130
+ // A loader whose loads resolve or fail when the test says so.
131
+ function controlledLoader() {
132
+ const loads = {}
133
+ const loadLocale = vi.fn(
134
+ (locale) =>
135
+ new Promise((resolve, reject) => {
136
+ loads[locale] = { resolve, reject }
137
+ }),
138
+ )
139
+ return { loads, loadLocale }
140
+ }
141
+
142
+ function createI18nStore(options) {
143
+ const i18n = createI18n({
144
+ resources: { en },
145
+ locales: ["en", "it", "fr"],
146
+ ...options,
147
+ })
148
+ const store = createStore({
149
+ types: { I18n: i18n.I18n },
150
+ entities: { i18n: { type: "I18n" } },
151
+ })
152
+ store.notify("init")
153
+ return { ...i18n, store }
154
+ }
155
+
156
+ const settle = () => new Promise((resolve) => setTimeout(resolve))
157
+
158
+ it("loads the starting locale before ready resolves", async () => {
159
+ stubBrowser({ languages: ["it-IT"] })
160
+ const { ready, t } = createI18n({
161
+ resources: { en },
162
+ locales: ["en", "it"],
163
+ loadLocale: async () => italian,
164
+ })
165
+
166
+ await ready
167
+
168
+ expect(t("hello")).toBe("Ciao")
169
+ })
170
+
171
+ it("is ready at once when the starting locale is bundled", async () => {
172
+ stubBrowser({ languages: ["en"] })
173
+ const loadLocale = vi.fn()
174
+ const { ready } = createI18n({ resources: { en }, loadLocale })
175
+
176
+ await ready
177
+
178
+ expect(loadLocale).not.toHaveBeenCalled()
179
+ })
180
+
181
+ it("loads a locale before switching to it", async () => {
182
+ stubBrowser({ languages: ["en"] })
183
+ const { loads, loadLocale } = controlledLoader()
184
+ const { store, t } = createI18nStore({ loadLocale })
185
+
186
+ store.notify("#i18n:localeChange", "it")
187
+
188
+ expect(store.getState().i18n.locale).toBe("en")
189
+ expect(store.getState().i18n.loadingLocale).toBe("it")
190
+ expect(t("hello")).toBe("Hello")
191
+
192
+ loads.it.resolve(italian)
193
+ await settle()
194
+
195
+ expect(store.getState().i18n.locale).toBe("it")
196
+ expect(store.getState().i18n.loadingLocale).toBe(null)
197
+ expect(t("hello")).toBe("Ciao")
198
+ })
199
+
200
+ it("switches only to the latest choice", async () => {
201
+ stubBrowser({ languages: ["en"] })
202
+ const { loads, loadLocale } = controlledLoader()
203
+ const { store } = createI18nStore({ loadLocale })
204
+
205
+ store.notify("#i18n:localeChange", "it")
206
+ store.notify("#i18n:localeChange", "fr")
207
+ loads.fr.resolve({ translation: { hello: "Bonjour" } })
208
+ await settle()
209
+ loads.it.resolve(italian)
210
+ await settle()
211
+
212
+ expect(store.getState().i18n.locale).toBe("fr")
213
+ })
214
+
215
+ it("loads each locale once", async () => {
216
+ stubBrowser({ languages: ["en"] })
217
+ const loadLocale = vi.fn(async () => italian)
218
+ const { store } = createI18nStore({ loadLocale })
219
+
220
+ store.notify("#i18n:localeChange", "it")
221
+ await settle()
222
+ store.notify("#i18n:localeChange", "en")
223
+ store.notify("#i18n:localeChange", "it")
224
+
225
+ expect(store.getState().i18n.locale).toBe("it")
226
+ expect(loadLocale).toHaveBeenCalledTimes(1)
227
+ })
228
+
229
+ it("keeps the current locale when a load fails, and tries again later", async () => {
230
+ stubBrowser({ languages: ["en"] })
231
+ vi.spyOn(console, "warn").mockImplementation(() => {})
232
+ const { loads, loadLocale } = controlledLoader()
233
+ const { store } = createI18nStore({ loadLocale })
234
+
235
+ store.notify("#i18n:localeChange", "it")
236
+ loads.it.reject(new Error("offline"))
237
+ await settle()
238
+
239
+ expect(store.getState().i18n.locale).toBe("en")
240
+ expect(store.getState().i18n.loadingLocale).toBe(null)
241
+
242
+ store.notify("#i18n:localeChange", "it")
243
+ loads.it.resolve(italian)
244
+ await settle()
245
+
246
+ expect(store.getState().i18n.locale).toBe("it")
247
+ expect(loadLocale).toHaveBeenCalledTimes(2)
248
+ })
249
+ })
250
+
251
+ describe("catalogues", () => {
252
+ const { en, it: italian } = resources
253
+
254
+ it("takes a lazy glob: a locale per file, loaded when needed", async () => {
255
+ stubBrowser({ languages: ["it-IT"] })
256
+ const load = {
257
+ en: vi.fn(async () => ({ default: en.translation })),
258
+ it: vi.fn(async () => ({ default: italian.translation })),
259
+ fr: vi.fn(),
260
+ }
261
+ const { I18n, ready, t } = createI18n({
262
+ catalogues: {
263
+ "./locales/en.json": load.en,
264
+ "./locales/fr.json": load.fr,
265
+ "./locales/it.json": load.it,
266
+ },
267
+ defaultLocale: "en",
268
+ })
269
+ const entity = {}
270
+ I18n.create(entity)
271
+
272
+ expect(entity.locales).toEqual(["en", "fr", "it"])
273
+
274
+ await ready
275
+
276
+ expect(t("hello")).toBe("Ciao")
277
+ expect(load.en).toHaveBeenCalled()
278
+ expect(load.fr).not.toHaveBeenCalled()
279
+ })
280
+
281
+ it("takes an eager glob: every catalogue bundled", () => {
282
+ stubBrowser({ languages: ["en"] })
283
+ const { I18n, t } = createI18n({
284
+ catalogues: {
285
+ "./locales/en.json": { default: en.translation },
286
+ "./locales/it.json": { default: italian.translation },
287
+ },
288
+ })
289
+ const entity = {}
290
+ I18n.create(entity)
291
+
292
+ I18n.localeChange(entity, "it")
293
+
294
+ expect(t("hello")).toBe("Ciao")
295
+ })
296
+ })
297
+
298
+ describe("languages", () => {
299
+ it("names each language in itself, for a picker", () => {
300
+ stubBrowser({ languages: ["en"] })
301
+ const { languages } = createI18n({ resources, locales: ["en", "it", "fr"] })
302
+
303
+ expect(languages).toEqual([
304
+ { value: "en", label: "English" },
305
+ { value: "it", label: "Italiano" },
306
+ { value: "fr", label: "Français" },
307
+ ])
308
+ })
309
+
310
+ it("takes a picker's { value } as the locale", () => {
311
+ stubBrowser({ languages: ["en"] })
312
+ const { I18n } = createI18n({ resources })
313
+ const entity = {}
314
+ I18n.create(entity)
315
+
316
+ I18n.localeChange(entity, { value: "it" })
317
+
318
+ expect(entity.locale).toBe("it")
319
+ })
320
+ })
321
+
322
+ describe("saveUserLocale", () => {
323
+ function setup() {
324
+ stubBrowser({ languages: ["en"] })
325
+ const saveUserLocale = vi.fn()
326
+ const { I18n } = createI18n({ resources, saveUserLocale })
327
+ const api = { notify: vi.fn() }
328
+ const entity = { id: "i18n" }
329
+ I18n.create(entity)
330
+ return { I18n, entity, api, saveUserLocale }
331
+ }
332
+
333
+ it("saves a change at once for a signed-in user", () => {
334
+ const { I18n, entity, api, saveUserLocale } = setup()
335
+ I18n.userLocaleLoad(entity, { userId: "u1", locale: "en" }, api)
336
+
337
+ I18n.localeChange(entity, "it", api)
338
+
339
+ expect(saveUserLocale).toHaveBeenCalledWith("it", api)
340
+ })
341
+
342
+ it("applies the user's saved locale", () => {
343
+ const { I18n, entity, api, saveUserLocale } = setup()
344
+
345
+ I18n.userLocaleLoad(entity, { userId: "u1", locale: "it" }, api)
346
+
347
+ expect(entity.locale).toBe("it")
348
+ expect(saveUserLocale).not.toHaveBeenCalled()
349
+ })
350
+
351
+ it("saves a choice made before signing in instead", () => {
352
+ const { I18n, entity, api, saveUserLocale } = setup()
353
+ I18n.localeChange(entity, "it", api)
354
+
355
+ expect(saveUserLocale).not.toHaveBeenCalled()
356
+
357
+ I18n.userLocaleLoad(entity, { userId: "u1", locale: "en" }, api)
358
+
359
+ expect(entity.locale).toBe("it")
360
+ expect(saveUserLocale).toHaveBeenCalledWith("it", api)
361
+ })
362
+
363
+ it("saves the current locale for a user with none", () => {
364
+ const { I18n, entity, api, saveUserLocale } = setup()
365
+
366
+ I18n.userLocaleLoad(entity, { userId: "u1", locale: null }, api)
367
+
368
+ expect(saveUserLocale).toHaveBeenCalledWith("en", api)
369
+ })
370
+
371
+ it("applies once per user", () => {
372
+ const { I18n, entity, api } = setup()
373
+ I18n.userLocaleLoad(entity, { userId: "u1", locale: "it" }, api)
374
+ I18n.localeChange(entity, "en", api)
375
+
376
+ I18n.userLocaleLoad(entity, { userId: "u1", locale: "it" }, api)
377
+
378
+ expect(entity.locale).toBe("en")
379
+ })
380
+
381
+ it("keeps choices made after signing out for the next user", () => {
382
+ const { I18n, entity, api, saveUserLocale } = setup()
383
+ I18n.userLocaleLoad(entity, { userId: "u1", locale: "en" }, api)
384
+ I18n.userLocaleClear(entity)
385
+
386
+ I18n.localeChange(entity, "it", api)
387
+
388
+ expect(saveUserLocale).not.toHaveBeenCalled()
389
+ expect(entity.isUnsaved).toBe(true)
390
+ })
391
+ })
392
+
393
+ describe("helpers", () => {
394
+ it("labels data in the active language, and keeps the key", () => {
395
+ stubBrowser({ languages: ["en"] })
396
+ const { I18n, labelled, translatedLabel, currentLocale } = createI18n({
397
+ resources,
398
+ })
399
+ const entity = {}
400
+ I18n.create(entity)
401
+ const option = labelled("hello", { value: "greeting" })
402
+
403
+ expect(option.label).toBe("Hello")
404
+
405
+ I18n.localeChange(entity, "it")
406
+
407
+ expect(option.label).toBe("Ciao")
408
+ expect(currentLocale()).toBe("it")
409
+ expect(translatedLabel({ ...option })).toBe("Ciao")
410
+ expect(translatedLabel({ label: "Lombardy" })).toBe("Lombardy")
411
+ })
412
+ })
package/types/index.d.ts CHANGED
@@ -1,14 +1,36 @@
1
1
  import type { i18n, InitOptions, Resource, TOptions } from "i18next"
2
2
 
3
+ /** A catalogue file as a glob gives it: the module, or a function loading it. */
4
+ export type CatalogueEntry =
5
+ Record<string, unknown> | (() => Promise<Record<string, unknown>>)
6
+
3
7
  export interface I18nOptions {
4
- /** The catalogues, by locale: `{ en: { translation: { … } }, it: … }`. */
5
- resources: Resource
6
- /** The supported locales. Defaults to the keys of `resources`. */
8
+ /**
9
+ * The catalogues by file path, as `import.meta.glob("./locales/*.json")`
10
+ * returns them. Each file is a locale named after it; a lazy glob loads them
11
+ * on demand, an eager one bundles them.
12
+ */
13
+ catalogues?: Record<string, CatalogueEntry>
14
+ /** The catalogues bundled with the app, by locale: `{ en: { translation: { … } }, it: … }`. */
15
+ resources?: Resource
16
+ /** The supported locales, in picker order. Defaults to those in `resources` and `catalogues`; list them all when some are loaded with `loadLocale`. */
7
17
  locales?: string[]
18
+ /**
19
+ * Loads a locale that is not in `resources`, resolving to its catalogues by
20
+ * namespace: `{ translation: { … } }`. Typically a dynamic import, so each
21
+ * catalogue is its own chunk.
22
+ */
23
+ loadLocale?: (locale: string) => Promise<Resource[string]>
8
24
  /** The fallback, and the locale when nothing else matches. Defaults to the first locale. */
9
25
  defaultLocale?: string
10
26
  /** Where to remember the user's choice in localStorage. Omit to not remember it. */
11
27
  storageKey?: string
28
+ /**
29
+ * Saves the user's locale wherever the app keeps their preferences, e.g.
30
+ * `(locale, api) => api.notify("#profile:localeSave", locale)`. Called for a
31
+ * change while a user is signed in, and when one signs in after choosing.
32
+ */
33
+ saveUserLocale?: (locale: string, api: unknown) => void
12
34
  /** Any further i18next options. `resources`, `lng`, `fallbackLng`, `supportedLngs` and `initAsync` are set by `createI18n`. */
13
35
  i18nextOptions?: InitOptions
14
36
  }
@@ -20,12 +42,51 @@ export interface I18nEntity {
20
42
  locale?: string
21
43
  /** The supported locales, for a language picker. */
22
44
  locales?: string[]
45
+ /** The supported locales named in themselves, as options for a picker. */
46
+ languages?: LanguageOption[]
47
+ /** The locale being loaded before a change, if any. */
48
+ loadingLocale?: string | null
49
+ /** The signed-in user, once `userLocaleLoad` has named them. */
50
+ userId?: string | null
51
+ /** A choice made before signing in, to save for the next user. */
52
+ isUnsaved?: boolean
53
+ }
54
+
55
+ export interface LanguageOption {
56
+ value: string
57
+ /** The language in itself: "Italiano", "Français". */
58
+ label: string
23
59
  }
24
60
 
25
61
  export interface I18nType {
26
62
  create(entity: I18nEntity): void
27
- /** Switches to `locale`, remembers it and sets `<html lang>`. Unsupported locales are ignored. */
28
- localeChange(entity: I18nEntity, locale: string): void
63
+ /**
64
+ * Switches to `locale`, remembers it and sets `<html lang>`. Unsupported
65
+ * locales are ignored. A locale not loaded yet is loaded first, and the
66
+ * switch follows in `localeLoadSuccess`.
67
+ */
68
+ localeChange(
69
+ entity: I18nEntity,
70
+ locale: string | { value: string },
71
+ api?: unknown,
72
+ ): void
73
+ localeLoadSuccess(entity: I18nEntity, locale: string): void
74
+ localeLoadError(
75
+ entity: I18nEntity,
76
+ payload: { locale: string; error: unknown },
77
+ ): void
78
+ /**
79
+ * The signed-in user and their saved locale (`null` for none). Applies it,
80
+ * or saves the current one if it was chosen before signing in or nothing
81
+ * was saved. Once per user.
82
+ */
83
+ userLocaleLoad(
84
+ entity: I18nEntity,
85
+ payload: { userId: string; locale: string | null },
86
+ api: unknown,
87
+ ): void
88
+ /** Signed out: later choices wait for the next user. */
89
+ userLocaleClear(entity: I18nEntity): void
29
90
  }
30
91
 
31
92
  export interface TransOptions<Part = unknown> {
@@ -38,6 +99,19 @@ export interface TransOptions<Part = unknown> {
38
99
  export interface I18n {
39
100
  /** The type to register in the store, e.g. `types: { I18n }` with an `i18n` entity. */
40
101
  I18n: I18nType
102
+ /** Resolves once the starting locale and the fallback are loaded. Mount after it. */
103
+ ready: Promise<void>
104
+ /** The supported locales named in themselves, as options for a picker. */
105
+ languages: LanguageOption[]
106
+ /** The active locale, for `Intl` formatters. */
107
+ currentLocale: () => string
108
+ /** A data item whose `label` is `t(labelKey)` whenever it is read. */
109
+ labelled: <Fields extends object>(
110
+ labelKey: string,
111
+ fields?: Fields,
112
+ ) => Fields & { labelKey: string; readonly label: string }
113
+ /** An option's label: `t(labelKey)` when it has one, `label` otherwise. */
114
+ translatedLabel: (option: { labelKey?: string; label?: string }) => string
41
115
  /** Translates `key` in the active locale. Same signature as i18next's `t`. */
42
116
  t: (key: string | string[], options?: TOptions) => string
43
117
  /**