@inglorious/i18n 1.3.0 → 2.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
@@ -96,20 +96,45 @@ 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. `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:
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 = [labelled("periods.week", { value: "week" })]
102
+ const periods = [{ value: "week", label: "periods.week" }]
103
103
 
104
- translatedLabel(periods[0]) // "This week", or "Questa settimana"
105
- translatedLabel({ label: "Lombardy" }) // data, not copy: as is
104
+ periods.map((period) => ({ ...period, label: t(period.label) }))
105
+ t("Lombardy") // data, not copy: as is
106
+ ```
107
+
108
+ ## Content with its own translations
109
+
110
+ Records that come from a database or a CMS can't have keys in the catalogues: they may not exist yet when the app ships. Each brings its own translations instead, and `localized` picks the one in the active locale, else the default locale's:
111
+
112
+ ```javascript
113
+ const genre = {
114
+ value: "jazz",
115
+ labels: { en: "Jazz", it: "Jazz", ja: "ジャズ" },
116
+ }
117
+
118
+ localized(genre.labels) // "ジャズ" in Japanese, "Jazz" in French
119
+ ```
120
+
121
+ Keep the record as it is in state and call `localized` where it is rendered, so it follows a switch.
122
+
123
+ ## Messages in state
124
+
125
+ 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.
126
+
127
+ ```javascript
128
+ entity.error = { key: "errors.tooLong", values: { max: 80 } }
129
+
130
+ html`<p>${t(entity.error)}</p>`
106
131
  ```
107
132
 
108
133
  ## API
109
134
 
110
135
  ### `createI18n(options)`
111
136
 
112
- Returns `{ I18n, ready, languages, t, trans, currentLocale, labelled, translatedLabel, i18next }`.
137
+ Returns `{ I18n, ready, languages, t, trans, localized, currentLocale, i18next }`.
113
138
 
114
139
  - `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
140
  - `resources`: catalogues bundled with the app, `{ [locale]: { translation: { … } } }`. The lower-level alternative to `catalogues`.
@@ -119,9 +144,10 @@ Returns `{ I18n, ready, languages, t, trans, currentLocale, labelled, translated
119
144
  - `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.
120
145
  - `defaultLocale`: the fallback, and the locale when nothing else matches. Defaults to the first locale.
121
146
  - `storageKey`: where to remember the user's choice in `localStorage`. Omit it to not remember the choice.
147
+ - `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.
122
148
  - `i18nextOptions`: any further i18next options.
123
149
 
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`.
150
+ 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`.
125
151
 
126
152
  `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.
127
153
 
@@ -186,6 +212,6 @@ It is safe with user data:
186
212
  - A tag without a component (`<script>`, a typo, a stray `</b>`) shows as written instead of becoming markup.
187
213
  - Plurals and formatters work as in `t`: `trans("events", { values: { count } })`.
188
214
 
189
- ### `detectLocale({ locales, defaultLocale, storageKey })`
215
+ ### `detectLocale({ locales, defaultLocale, storageKey, queryParam })`
190
216
 
191
217
  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": "1.3.0",
3
+ "version": "2.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",
@@ -34,16 +34,16 @@
34
34
  "access": "public"
35
35
  },
36
36
  "dependencies": {
37
- "i18next": "^26.5.2"
37
+ "i18next": "^27.0.0"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@inglorious/eslint-config": "1.2.0",
41
- "@inglorious/store": "12.1.0",
42
- "prettier": "^3.9.6",
43
- "vitest": "^5.0.0"
41
+ "@inglorious/store": "12.3.0",
42
+ "prettier": "^3.9.10",
43
+ "vitest": "^5.1.0"
44
44
  },
45
45
  "engines": {
46
- "node": ">= 22"
46
+ "node": ">= 26"
47
47
  },
48
48
  "scripts": {
49
49
  "format": "prettier --write .",
package/src/index.js CHANGED
@@ -37,6 +37,7 @@ export function createI18n({
37
37
  isServerRendered = false,
38
38
  defaultLocale,
39
39
  storageKey,
40
+ queryParam,
40
41
  saveUserLocale,
41
42
  i18nextOptions = {},
42
43
  }) {
@@ -55,7 +56,15 @@ export function createI18n({
55
56
  // detected instead.
56
57
  const startLocale =
57
58
  (isServerRendered && matchLocale(getDocumentLanguage(), locales)) ||
58
- detectLocale({ locales, defaultLocale: fallbackLocale, storageKey })
59
+ detectLocale({
60
+ locales,
61
+ defaultLocale: fallbackLocale,
62
+ storageKey,
63
+ queryParam,
64
+ })
65
+ if (startLocale === queryLocale(queryParam, locales)) {
66
+ saveLocale(storageKey, startLocale)
67
+ }
59
68
  const languages = locales.map((locale) => ({
60
69
  value: locale,
61
70
  label: languageName(locale),
@@ -65,24 +74,19 @@ export function createI18n({
65
74
  instance.init({
66
75
  ...i18nextOptions,
67
76
  resources,
68
- // Until a loaded catalogue arrives, keys fall back rather than wait.
69
77
  partialBundledLanguages: true,
70
78
  lng: startLocale,
71
79
  fallbackLng: fallbackLocale,
72
80
  supportedLngs: locales,
73
- // lit-html escapes every text binding already; escaping here too would
74
- // print entities such as &amp; on screen.
75
81
  interpolation: { escapeValue: false, ...i18nextOptions.interpolation },
76
82
  initAsync: false,
77
83
  })
78
84
 
79
85
  const loader = createLoader(instance, resources, loadLocale)
80
86
 
81
- // The fallback too: it fills in whatever the starting locale is missing.
82
87
  const ready = Promise.all(
83
88
  [...new Set([startLocale, fallbackLocale])].map((locale) =>
84
89
  loader.load(locale).catch((error) => {
85
- // The app still starts, with whatever did load.
86
90
  console.warn(`[i18n] could not load "${locale}":`, error)
87
91
  }),
88
92
  ),
@@ -100,9 +104,6 @@ export function createI18n({
100
104
  applyDocumentLanguage(entity.locale, entity.dir)
101
105
  },
102
106
 
103
- // The user's choice: a locale, or a picker's `{ value }`. With
104
- // `saveUserLocale` it is saved for the signed-in user at once, and kept
105
- // for whoever signs in next otherwise.
106
107
  localeChange(entity, payload, api) {
107
108
  const locale = payload?.value ?? payload
108
109
  if (!requestLocale(entity, locale, api)) return
@@ -112,8 +113,6 @@ export function createI18n({
112
113
  else entity.isUnsaved = true
113
114
  },
114
115
 
115
- // Only the latest request switches: a slower load for a locale the user
116
- // has since moved away from is kept for later, but not applied.
117
116
  localeLoadSuccess(entity, locale) {
118
117
  if (entity.loadingLocale !== locale) return
119
118
  entity.loadingLocale = null
@@ -126,10 +125,6 @@ export function createI18n({
126
125
  console.warn(`[i18n] could not load "${locale}":`, error)
127
126
  },
128
127
 
129
- // The signed-in user and the locale saved for them, or none yet. A choice
130
- // made before they signed in is the more recent, so it is saved instead
131
- // of applying theirs; with nothing saved, the current one is. Once per
132
- // user, so reloading their data does not undo a change still being saved.
133
128
  userLocaleLoad(entity, { userId, locale }, api) {
134
129
  if (entity.userId === userId) return
135
130
  entity.userId = userId
@@ -143,32 +138,22 @@ export function createI18n({
143
138
  requestLocale(entity, locale, api)
144
139
  },
145
140
 
146
- // Signed out: later choices wait for the next user.
147
141
  userLocaleClear(entity) {
148
142
  entity.userId = null
149
143
  entity.isUnsaved = false
150
144
  },
151
145
  }
152
146
 
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.
156
147
  function requestLocale(entity, locale, api) {
157
148
  if (!locales.includes(locale)) return false
158
149
  const isChange = locale !== entity.locale
159
- // Choosing the current locale again also cancels a pending change.
160
150
  entity.loadingLocale = null
161
151
 
162
152
  if (loader.isLoaded(locale)) {
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
153
  if (isChange || locale !== instance.language) switchLocale(entity, locale)
166
154
  return isChange
167
155
  }
168
156
 
169
- // Also the current locale, while the catalogue it started with is loading.
170
- // The id is taken now: the promise settles after this batch, when the
171
- // entity here is no longer the live one.
172
157
  const id = entity.id
173
158
  entity.loadingLocale = locale
174
159
  loader.load(locale).then(
@@ -208,44 +193,55 @@ export function createI18n({
208
193
  )
209
194
  }
210
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
+ */
211
200
  function t(key, options) {
201
+ if (key && typeof key === "object" && !Array.isArray(key)) {
202
+ return instance.t(key.key, { ...key.values, ...options })
203
+ }
212
204
  return instance.t(key, options)
213
205
  }
214
206
 
207
+ /**
208
+ * Content's own translation, such as a record's `{ en: "Jazz", it: "Jazz" }`
209
+ * from a database or a CMS: the active locale's, else the default locale's.
210
+ */
211
+ function localized(translations) {
212
+ return translations?.[instance.language] ?? translations?.[fallbackLocale]
213
+ }
214
+
215
215
  return {
216
216
  I18n,
217
217
  ready,
218
218
  languages,
219
219
  t,
220
220
  trans,
221
- // The active locale, for `Intl` formatters.
221
+ localized,
222
222
  currentLocale: () => instance.language,
223
- // A data item whose label follows the language: `label` reads through `t`
224
- // every time, and `labelKey` survives being copied into store state,
225
- // where the getter would freeze into the text of the moment.
226
- labelled: (labelKey, fields = {}) => ({
227
- ...fields,
228
- labelKey,
229
- get label() {
230
- return t(labelKey)
231
- },
232
- }),
233
- // An option's label: translated when it carries a key, as is otherwise.
234
- translatedLabel: (option) =>
235
- option.labelKey ? t(option.labelKey) : option.label,
236
223
  i18next: instance,
237
224
  }
238
225
  }
239
226
 
240
227
  /**
241
- * The locale to start with: the one saved by a previous choice, else the
242
- * first of the device's languages that is supported (exactly, or by its base
243
- * language, so `it-CH` picks `it`), else the default.
228
+ * The locale to start with: the one a link names in `queryParam`, else the one
229
+ * saved by a previous choice, else the first of the device's languages that is
230
+ * supported (exactly, or by its base language, so `it-CH` picks `it`), else the
231
+ * default.
244
232
  *
245
- * @param {{ locales: string[], defaultLocale: string, storageKey?: string }} options
233
+ * @param {{ locales: string[], defaultLocale: string, storageKey?: string, queryParam?: string }} options
246
234
  * @returns {string}
247
235
  */
248
- export function detectLocale({ locales, defaultLocale, storageKey }) {
236
+ export function detectLocale({
237
+ locales,
238
+ defaultLocale,
239
+ storageKey,
240
+ queryParam,
241
+ }) {
242
+ const linked = queryLocale(queryParam, locales)
243
+ if (linked) return linked
244
+
249
245
  const saved = readLocale(storageKey)
250
246
  if (saved && locales.includes(saved)) return saved
251
247
 
@@ -261,8 +257,13 @@ export function detectLocale({ locales, defaultLocale, storageKey }) {
261
257
  return defaultLocale
262
258
  }
263
259
 
264
- // The supported locale for a language, exactly or by its base language, so
265
- // `it-CH` picks `it`; null when there is none.
260
+ function queryLocale(queryParam, locales) {
261
+ if (!queryParam) return null
262
+ const search = globalThis.location?.search ?? ""
263
+ const locale = new URLSearchParams(search).get(queryParam)
264
+ return locales.includes(locale) ? locale : null
265
+ }
266
+
266
267
  function matchLocale(language, locales) {
267
268
  if (!language) return null
268
269
  if (locales.includes(language)) return language
@@ -323,7 +324,6 @@ function createLoader(instance, resources, loadLocale) {
323
324
  if (isLoaded(locale)) return Promise.resolve()
324
325
  if (pending.has(locale)) return pending.get(locale)
325
326
 
326
- // Called right away; a loader that throws rejects like one that fails.
327
327
  const promise = new Promise((resolve) => resolve(loadLocale(locale)))
328
328
  .then((bundles) => {
329
329
  for (const [namespace, catalogue] of Object.entries(bundles ?? {})) {
@@ -361,8 +361,6 @@ function readLocale(storageKey) {
361
361
  try {
362
362
  return globalThis.localStorage?.getItem(storageKey) ?? null
363
363
  } catch {
364
- // Storage can be unavailable (private mode, server rendering): fall back
365
- // to detection rather than failing.
366
364
  return null
367
365
  }
368
366
  }
@@ -380,10 +378,6 @@ function getDocumentLanguage() {
380
378
  return globalThis.document?.documentElement.lang
381
379
  }
382
380
 
383
- // Screen readers, hyphenation and the browser's own spell checking read the
384
- // document language, so it follows the app's. So does the direction: in
385
- // Arabic, Hebrew or Persian the whole page reads right to left, and CSS that
386
- // uses logical properties (`margin-inline-start`, `text-align: start`) follows.
387
381
  function applyDocumentLanguage(locale, dir) {
388
382
  if (typeof document === "undefined") return
389
383
  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")
@@ -166,7 +177,6 @@ describe("createI18n", () => {
166
177
  describe("loadLocale", () => {
167
178
  const { en, it: italian } = resources
168
179
 
169
- // A loader whose loads resolve or fail when the test says so.
170
180
  function controlledLoader() {
171
181
  const loads = {}
172
182
  const loadLocale = vi.fn(
@@ -386,6 +396,37 @@ describe("catalogues", () => {
386
396
  })
387
397
  })
388
398
 
399
+ describe("localized", () => {
400
+ const jazz = { en: "Jazz", it: "Musica jazz" }
401
+
402
+ it("picks content's translation in the active locale", () => {
403
+ stubBrowser({ languages: ["it"] })
404
+ const { localized } = createI18n({ resources })
405
+
406
+ expect(localized(jazz)).toBe("Musica jazz")
407
+ })
408
+
409
+ it("falls back to the default locale, and to nothing", () => {
410
+ stubBrowser({ languages: ["it"] })
411
+ const { localized } = createI18n({ resources, defaultLocale: "en" })
412
+
413
+ expect(localized({ en: "Jazz" })).toBe("Jazz")
414
+ expect(localized({ fr: "Jazz" })).toBeUndefined()
415
+ expect(localized(undefined)).toBeUndefined()
416
+ })
417
+
418
+ it("follows a switch", () => {
419
+ stubBrowser({ languages: ["en"] })
420
+ const { I18n, localized } = createI18n({ resources })
421
+ const entity = {}
422
+ I18n.create(entity)
423
+
424
+ I18n.localeChange(entity, "it")
425
+
426
+ expect(localized(jazz)).toBe("Musica jazz")
427
+ })
428
+ })
429
+
389
430
  describe("languages", () => {
390
431
  it("names each language in itself, for a picker", () => {
391
432
  stubBrowser({ languages: ["en"] })
@@ -501,22 +542,40 @@ describe("direction", () => {
501
542
  })
502
543
 
503
544
  describe("helpers", () => {
504
- it("labels data in the active language, and keeps the key", () => {
505
- stubBrowser({ languages: ["en"] })
506
- const { I18n, labelled, translatedLabel, currentLocale } = createI18n({
545
+ it("remembers the locale a link names", () => {
546
+ const saved = stubBrowser({ languages: ["en"], search: "?lang=it" })
547
+ const { t } = createI18n({
507
548
  resources,
549
+ storageKey: "lang",
550
+ queryParam: "lang",
508
551
  })
552
+
553
+ expect(t("hello")).toBe("Ciao")
554
+ expect(saved.lang).toBe("it")
555
+ })
556
+
557
+ it("translates messages kept in state, and leaves other text as it is", () => {
558
+ stubBrowser({ languages: ["en"] })
559
+ const { t } = createI18n({ resources })
560
+
561
+ expect(t("hello")).toBe("Hello")
562
+ expect(t({ key: "greet", values: { name: "Ada" } })).toBe("Hello, Ada")
563
+ expect(t("Network down: retry later.")).toBe("Network down: retry later.")
564
+ })
565
+
566
+ it("translates a label kept as a key in the active language", () => {
567
+ stubBrowser({ languages: ["en"] })
568
+ const { I18n, t, currentLocale } = createI18n({ resources })
509
569
  const entity = {}
510
570
  I18n.create(entity)
511
- const option = labelled("hello", { value: "greeting" })
571
+ const option = { value: "greeting", label: "hello" }
512
572
 
513
- expect(option.label).toBe("Hello")
573
+ expect(t(option.label)).toBe("Hello")
514
574
 
515
575
  I18n.localeChange(entity, "it")
516
576
 
517
- expect(option.label).toBe("Ciao")
577
+ expect(t(option.label)).toBe("Ciao")
518
578
  expect(currentLocale()).toBe("it")
519
- expect(translatedLabel({ ...option })).toBe("Ciao")
520
- expect(translatedLabel({ label: "Lombardy" })).toBe("Lombardy")
579
+ expect(t("Lombardy")).toBe("Lombardy")
521
580
  })
522
581
  })
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
@@ -22,7 +22,6 @@ const resources = {
22
22
  },
23
23
  }
24
24
 
25
- // Components return plain objects, so the tests can see what was built.
26
25
  const tag = (name) => (children) => ({ tag: name, children })
27
26
  const components = {
28
27
  strong: tag("strong"),
package/types/index.d.ts CHANGED
@@ -34,6 +34,12 @@ export interface I18nOptions {
34
34
  defaultLocale?: string
35
35
  /** Where to remember the user's choice in localStorage. Omit to not remember it. */
36
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
37
43
  /**
38
44
  * Saves the user's locale wherever the app keeps their preferences, e.g.
39
45
  * `(locale, api) => api.notify("#profile:localeSave", locale)`. Called for a
@@ -63,8 +69,6 @@ export interface I18nEntity {
63
69
  isUnsaved?: boolean
64
70
  }
65
71
 
66
- // A type alias rather than an interface, so it fits option types that allow
67
- // extra fields, such as Inglorious UI's `SelectOption`.
68
72
  export type LanguageOption = {
69
73
  value: string
70
74
  /** The language in itself: "Italiano", "Français". */
@@ -102,6 +106,9 @@ export type I18nType = {
102
106
  userLocaleClear(entity: I18nEntity): void
103
107
  }
104
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
+
105
112
  export interface TransOptions<Part = unknown> {
106
113
  /** Values for the `{{placeholders}}`. They are inserted as text, never as markup. */
107
114
  values?: TOptions
@@ -118,15 +125,12 @@ export interface I18n {
118
125
  languages: LanguageOption[]
119
126
  /** The active locale, for `Intl` formatters. */
120
127
  currentLocale: () => string
121
- /** A data item whose `label` is `t(labelKey)` whenever it is read. */
122
- labelled: <Fields extends object>(
123
- labelKey: string,
124
- fields?: Fields,
125
- ) => Fields & { labelKey: string; readonly label: string }
126
- /** An option's label: `t(labelKey)` when it has one, `label` otherwise. */
127
- translatedLabel: (option: { labelKey?: string; label?: string }) => string
128
- /** Translates `key` in the active locale. Same signature as i18next's `t`. */
129
- 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
130
134
  /**
131
135
  * Translates `key` into template parts, rendering the tags in the translation
132
136
  * through `components`. Tags without a component show as written.
@@ -135,6 +139,13 @@ export interface I18n {
135
139
  key: string | string[],
136
140
  options?: TransOptions<Part>,
137
141
  ) => Array<string | Part>
142
+ /**
143
+ * Content's own translation, such as a record's `{ en: "Jazz", it: "Jazz" }`
144
+ * from a database or a CMS: the active locale's, else the default locale's.
145
+ */
146
+ localized: <Value = string>(
147
+ translations: Partial<Record<string, Value>> | null | undefined,
148
+ ) => Value | undefined
138
149
  /** The underlying i18next instance, for anything the adapter does not cover. */
139
150
  i18next: i18n
140
151
  }
@@ -145,4 +156,5 @@ export function detectLocale(options: {
145
156
  locales: string[]
146
157
  defaultLocale: string
147
158
  storageKey?: string
159
+ queryParam?: string
148
160
  }): string