@inglorious/i18n 1.2.2 → 1.3.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
@@ -116,11 +116,12 @@ Returns `{ I18n, ready, languages, t, trans, currentLocale, labelled, translated
116
116
  - `loadLocale`: loads a locale that is not in `resources`, resolving to `{ translation: { … } }`. The lower-level alternative to a lazy glob.
117
117
  - `locales`: the supported locales, in picker order. Defaults to those in `catalogues` and `resources`.
118
118
  - `saveUserLocale`: saves the locale for the signed-in user. See [The user's language](#the-users-language).
119
+ - `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
120
  - `defaultLocale`: the fallback, and the locale when nothing else matches. Defaults to the first locale.
120
121
  - `storageKey`: where to remember the user's choice in `localStorage`. Omit it to not remember the choice.
121
122
  - `i18nextOptions`: any further i18next options.
122
123
 
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`.
124
+ The starting locale is that of `<html lang>` on a server-rendered page, when supported, else the saved choice, else the first of the device's languages that is supported (`it-CH` picks `it`), else `defaultLocale`.
124
125
 
125
126
  `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
127
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/i18n",
3
- "version": "1.2.2",
3
+ "version": "1.3.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",
@@ -37,8 +37,8 @@
37
37
  "i18next": "^26.5.2"
38
38
  },
39
39
  "devDependencies": {
40
- "@inglorious/eslint-config": "1.1.4",
41
- "@inglorious/store": "11.1.0",
40
+ "@inglorious/eslint-config": "1.2.0",
41
+ "@inglorious/store": "12.1.0",
42
42
  "prettier": "^3.9.6",
43
43
  "vitest": "^5.0.0"
44
44
  },
package/src/index.js CHANGED
@@ -34,6 +34,7 @@ export function createI18n({
34
34
  resources: givenResources = {},
35
35
  loadLocale: givenLoadLocale,
36
36
  locales: givenLocales,
37
+ isServerRendered = false,
37
38
  defaultLocale,
38
39
  storageKey,
39
40
  saveUserLocale,
@@ -49,11 +50,12 @@ export function createI18n({
49
50
  ]
50
51
  const [firstLocale = "en"] = locales
51
52
  const fallbackLocale = defaultLocale ?? firstLocale
52
- const startLocale = detectLocale({
53
- locales,
54
- defaultLocale: fallbackLocale,
55
- storageKey,
56
- })
53
+ // A server-rendered page is already in a language, which hydration must keep.
54
+ // In a page served as is, `<html lang>` is whatever the file says, so it is
55
+ // detected instead.
56
+ const startLocale =
57
+ (isServerRendered && matchLocale(getDocumentLanguage(), locales)) ||
58
+ detectLocale({ locales, defaultLocale: fallbackLocale, storageKey })
57
59
  const languages = locales.map((locale) => ({
58
60
  value: locale,
59
61
  label: languageName(locale),
@@ -148,19 +150,23 @@ export function createI18n({
148
150
  },
149
151
  }
150
152
 
151
- // Switches to `locale`, loading it first if needed. Whether it is a change.
153
+ // Switches to `locale`, loading it first if needed, so `loadingLocale` names
154
+ // it until its catalogue is in: what a server render or a hydration waits for.
155
+ // Whether it is a change.
152
156
  function requestLocale(entity, locale, api) {
153
157
  if (!locales.includes(locale)) return false
154
158
  const isChange = locale !== entity.locale
155
159
  // Choosing the current locale again also cancels a pending change.
156
160
  entity.loadingLocale = null
157
- if (!isChange) return false
158
161
 
159
162
  if (loader.isLoaded(locale)) {
160
- switchLocale(entity, locale)
161
- return true
163
+ // The i18next instance is shared by every store, as on a server rendering
164
+ // pages in different languages, so it can be elsewhere when the entity is not.
165
+ if (isChange || locale !== instance.language) switchLocale(entity, locale)
166
+ return isChange
162
167
  }
163
168
 
169
+ // Also the current locale, while the catalogue it started with is loading.
164
170
  // The id is taken now: the promise settles after this batch, when the
165
171
  // entity here is no longer the live one.
166
172
  const id = entity.id
@@ -169,7 +175,7 @@ export function createI18n({
169
175
  () => api.notify(`#${id}:localeLoadSuccess`, locale),
170
176
  (error) => api.notify(`#${id}:localeLoadError`, { locale, error }),
171
177
  )
172
- return true
178
+ return isChange
173
179
  }
174
180
 
175
181
  function switchLocale(entity, locale) {
@@ -247,15 +253,23 @@ export function detectLocale({ locales, defaultLocale, storageKey }) {
247
253
  typeof navigator === "undefined"
248
254
  ? []
249
255
  : (navigator.languages ?? [navigator.language])
250
- for (const language of preferred.filter(Boolean)) {
251
- if (locales.includes(language)) return language
252
- const [base] = language.split("-")
253
- if (locales.includes(base)) return base
256
+ for (const language of preferred) {
257
+ const locale = matchLocale(language, locales)
258
+ if (locale) return locale
254
259
  }
255
260
 
256
261
  return defaultLocale
257
262
  }
258
263
 
264
+ // The supported locale for a language, exactly or by its base language, so
265
+ // `it-CH` picks `it`; null when there is none.
266
+ function matchLocale(language, locales) {
267
+ if (!language) return null
268
+ if (locales.includes(language)) return language
269
+ const [base] = language.split("-")
270
+ return locales.includes(base) ? base : null
271
+ }
272
+
259
273
  /**
260
274
  * Turns `catalogues`, a map from file path to catalogue such as
261
275
  * `import.meta.glob` returns, into the resources and loader i18next needs.
@@ -362,6 +376,10 @@ function saveLocale(storageKey, locale) {
362
376
  }
363
377
  }
364
378
 
379
+ function getDocumentLanguage() {
380
+ return globalThis.document?.documentElement.lang
381
+ }
382
+
365
383
  // Screen readers, hyphenation and the browser's own spell checking read the
366
384
  // document language, so it follows the app's. So does the direction: in
367
385
  // Arabic, Hebrew or Persian the whole page reads right to left, and CSS that
package/src/index.test.js CHANGED
@@ -89,6 +89,45 @@ describe("createI18n", () => {
89
89
  expect(document.documentElement.lang).toBe("it")
90
90
  })
91
91
 
92
+ it("starts a server-rendered page in its language, ahead of the saved choice and the device", () => {
93
+ stubBrowser({ languages: ["en"], saved: { lang: "en" } })
94
+ document.documentElement.lang = "it-IT"
95
+ const { I18n, t } = createI18n({
96
+ resources,
97
+ isServerRendered: true,
98
+ storageKey: "lang",
99
+ })
100
+ const entity = {}
101
+
102
+ I18n.create(entity)
103
+
104
+ expect(entity.locale).toBe("it")
105
+ expect(document.documentElement.lang).toBe("it")
106
+ expect(t("hello")).toBe("Ciao")
107
+ })
108
+
109
+ it("detects the locale when the page's language is unsupported", () => {
110
+ stubBrowser({ languages: ["it"] })
111
+ document.documentElement.lang = "de"
112
+ const { I18n } = createI18n({ resources, isServerRendered: true })
113
+ const entity = {}
114
+
115
+ I18n.create(entity)
116
+
117
+ expect(entity.locale).toBe("it")
118
+ })
119
+
120
+ it("ignores the language of a page that is not server-rendered", () => {
121
+ stubBrowser({ languages: ["it"] })
122
+ document.documentElement.lang = "en"
123
+ const { I18n } = createI18n({ resources })
124
+ const entity = {}
125
+
126
+ I18n.create(entity)
127
+
128
+ expect(entity.locale).toBe("it")
129
+ })
130
+
92
131
  it("switches language, remembers it and ignores unsupported ones", () => {
93
132
  const saved = stubBrowser({ languages: ["en"] })
94
133
  const { I18n, t } = createI18n({ resources, storageKey: "lang" })
@@ -168,6 +207,24 @@ describe("loadLocale", () => {
168
207
  expect(t("hello")).toBe("Ciao")
169
208
  })
170
209
 
210
+ it("loads only the server-rendered page's locale, not the device's", async () => {
211
+ stubBrowser({ languages: ["fr-FR"] })
212
+ document.documentElement.lang = "it"
213
+ const loadLocale = vi.fn(async () => italian)
214
+ const { ready, t } = createI18n({
215
+ resources: { en },
216
+ locales: ["en", "it", "fr"],
217
+ isServerRendered: true,
218
+ loadLocale,
219
+ })
220
+
221
+ await ready
222
+
223
+ expect(loadLocale).toHaveBeenCalledTimes(1)
224
+ expect(loadLocale).toHaveBeenCalledWith("it")
225
+ expect(t("hello")).toBe("Ciao")
226
+ })
227
+
171
228
  it("is ready at once when the starting locale is bundled", async () => {
172
229
  stubBrowser({ languages: ["en"] })
173
230
  const loadLocale = vi.fn()
@@ -226,6 +283,40 @@ describe("loadLocale", () => {
226
283
  expect(loadLocale).toHaveBeenCalledTimes(1)
227
284
  })
228
285
 
286
+ it("waits for the starting locale when asked for it while it loads", async () => {
287
+ stubBrowser({ languages: ["it-IT"] })
288
+ const { loads, loadLocale } = controlledLoader()
289
+ const { store, t } = createI18nStore({ loadLocale })
290
+
291
+ store.notify("#i18n:localeChange", "it")
292
+
293
+ expect(store.getState().i18n.loadingLocale).toBe("it")
294
+
295
+ loads.it.resolve(italian)
296
+ await settle()
297
+
298
+ expect(store.getState().i18n.loadingLocale).toBe(null)
299
+ expect(t("hello")).toBe("Ciao")
300
+ })
301
+
302
+ it("switches the shared instance back for a store already in the locale", () => {
303
+ stubBrowser({ languages: ["en"] })
304
+ const { I18n, t } = createI18n({ resources })
305
+ const createI18nStoreOf = () =>
306
+ createStore({
307
+ types: { I18n },
308
+ entities: { i18n: { type: "I18n" } },
309
+ })
310
+ const english = createI18nStoreOf()
311
+ const italianStore = createI18nStoreOf()
312
+
313
+ italianStore.notify("#i18n:localeChange", "it")
314
+ expect(t("hello")).toBe("Ciao")
315
+
316
+ english.notify("#i18n:localeChange", "en")
317
+ expect(t("hello")).toBe("Hello")
318
+ })
319
+
229
320
  it("keeps the current locale when a load fails, and tries again later", async () => {
230
321
  stubBrowser({ languages: ["en"] })
231
322
  vi.spyOn(console, "warn").mockImplementation(() => {})
package/types/index.d.ts CHANGED
@@ -24,6 +24,12 @@ 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. */