@inglorious/i18n 0.0.0-stage → 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/LICENSE +9 -0
- package/README.md +189 -2
- package/package.json +51 -3
- package/src/index.js +368 -0
- package/src/index.test.js +412 -0
- package/src/trans.js +57 -0
- package/src/trans.test.js +146 -0
- package/types/index.d.ts +135 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright © 2025 Inglorious Coderz Srl.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,190 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @inglorious/i18n
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Internationalization for `@inglorious/web`: an [i18next](https://www.i18next.com/) instance driven by a store entity.
|
|
4
|
+
|
|
5
|
+
i18next does the translating (interpolation, plurals, fallbacks, formatting through `Intl`). This package is the binding to the Inglorious store, the way `react-i18next` is the binding to React: the active locale lives in an entity, so changing language is an ordinary event, and the render that follows reads every string in the new language.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add @inglorious/i18n
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
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
|
+
|
|
17
|
+
```javascript
|
|
18
|
+
// src/i18n.js
|
|
19
|
+
import { createI18n } from "@inglorious/i18n"
|
|
20
|
+
|
|
21
|
+
export const { I18n, t, trans, ready } = createI18n({
|
|
22
|
+
catalogues: import.meta.glob("./locales/*.json"),
|
|
23
|
+
defaultLocale: "en",
|
|
24
|
+
storageKey: "my-app-locale",
|
|
25
|
+
})
|
|
26
|
+
```
|
|
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
|
+
|
|
36
|
+
Register the type and an entity for it:
|
|
37
|
+
|
|
38
|
+
```javascript
|
|
39
|
+
import { createStore } from "@inglorious/store"
|
|
40
|
+
|
|
41
|
+
import { I18n } from "./i18n.js"
|
|
42
|
+
|
|
43
|
+
export const store = createStore({
|
|
44
|
+
types: { I18n /* , … */ },
|
|
45
|
+
entities: { i18n: { type: "I18n" } /* , … */ },
|
|
46
|
+
})
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Translate in any template:
|
|
50
|
+
|
|
51
|
+
```javascript
|
|
52
|
+
import { html } from "@inglorious/web"
|
|
53
|
+
|
|
54
|
+
import { t } from "../i18n.js"
|
|
55
|
+
|
|
56
|
+
export const Events = {
|
|
57
|
+
render(entity) {
|
|
58
|
+
return html`<h1>${t("events.title")}</h1>
|
|
59
|
+
<p>${t("events.count", { count: entity.events.length })}</p>`
|
|
60
|
+
},
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Switch language from anywhere:
|
|
65
|
+
|
|
66
|
+
```javascript
|
|
67
|
+
api.notify("#i18n:localeChange", "it")
|
|
68
|
+
```
|
|
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
|
+
|
|
108
|
+
## API
|
|
109
|
+
|
|
110
|
+
### `createI18n(options)`
|
|
111
|
+
|
|
112
|
+
Returns `{ I18n, ready, languages, t, trans, currentLocale, labelled, translatedLabel, i18next }`.
|
|
113
|
+
|
|
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).
|
|
119
|
+
- `defaultLocale`: the fallback, and the locale when nothing else matches. Defaults to the first locale.
|
|
120
|
+
- `storageKey`: where to remember the user's choice in `localStorage`. Omit it to not remember the choice.
|
|
121
|
+
- `i18nextOptions`: any further i18next options.
|
|
122
|
+
|
|
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
|
+
|
|
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.
|
|
126
|
+
|
|
127
|
+
### The `I18n` type
|
|
128
|
+
|
|
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).
|
|
132
|
+
|
|
133
|
+
### `t(key, options)`
|
|
134
|
+
|
|
135
|
+
i18next's `t`, bound to this instance. Everything i18next supports works:
|
|
136
|
+
|
|
137
|
+
```json
|
|
138
|
+
{
|
|
139
|
+
"greet": "Hello, {{name}}",
|
|
140
|
+
"event_one": "{{count}} event",
|
|
141
|
+
"event_other": "{{count}} events",
|
|
142
|
+
"deadline": "Closes on {{date, datetime}}"
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
```javascript
|
|
147
|
+
t("greet", { name: "Ada" })
|
|
148
|
+
t("event", { count: 3 })
|
|
149
|
+
t("deadline", {
|
|
150
|
+
date: new Date(),
|
|
151
|
+
formatParams: { date: { day: "numeric", month: "short" } },
|
|
152
|
+
})
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Interpolated values are not HTML-escaped: lit-html escapes every text binding already.
|
|
156
|
+
|
|
157
|
+
### `trans(key, { values, components })`
|
|
158
|
+
|
|
159
|
+
For translations with markup in them. The tags are placeholders, not HTML: each one is rendered by the component of the same name, so the translator decides where the bold text or the link goes, and the word order can differ between languages.
|
|
160
|
+
|
|
161
|
+
```json
|
|
162
|
+
{
|
|
163
|
+
"loggedInAs": "Logging in as <strong>{{email}}</strong>.",
|
|
164
|
+
"terms": "Read the <link>terms of service</link>",
|
|
165
|
+
"twoLines": "First line<br/>Second line"
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
```javascript
|
|
170
|
+
import { html } from "@inglorious/web"
|
|
171
|
+
|
|
172
|
+
html`<p>
|
|
173
|
+
${trans("loggedInAs", {
|
|
174
|
+
values: { email },
|
|
175
|
+
components: { strong: (children) => html`<strong>${children}</strong>` },
|
|
176
|
+
})}
|
|
177
|
+
</p>`
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
It returns an array of parts (strings and what the components return), which lit renders like any other array.
|
|
181
|
+
|
|
182
|
+
It is safe with user data:
|
|
183
|
+
|
|
184
|
+
- Values are interpolated after the tags are parsed, as text: an email such as `<img src=x onerror=…>` shows as typed.
|
|
185
|
+
- A tag without a component (`<script>`, a typo, a stray `</b>`) shows as written instead of becoming markup.
|
|
186
|
+
- Plurals and formatters work as in `t`: `trans("events", { values: { count } })`.
|
|
187
|
+
|
|
188
|
+
### `detectLocale({ locales, defaultLocale, storageKey })`
|
|
189
|
+
|
|
190
|
+
The detection `createI18n` uses, exported for apps that need it elsewhere.
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inglorious/i18n",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Internationalization for Inglorious Web: an i18next instance driven by a store entity.",
|
|
5
|
+
"author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/IngloriousCoderz/inglorious-forge.git",
|
|
10
|
+
"directory": "packages/i18n"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/IngloriousCoderz/inglorious-forge/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"i18n",
|
|
17
|
+
"i18next",
|
|
18
|
+
"internationalization",
|
|
19
|
+
"localization",
|
|
20
|
+
"inglorious-web"
|
|
21
|
+
],
|
|
22
|
+
"type": "module",
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./types/index.d.ts",
|
|
26
|
+
"import": "./src/index.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"src",
|
|
31
|
+
"types"
|
|
32
|
+
],
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"i18next": "^26.5.2"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@inglorious/eslint-config": "1.1.2",
|
|
41
|
+
"@inglorious/store": "11.0.3",
|
|
42
|
+
"prettier": "^3.9.6",
|
|
43
|
+
"vitest": "^5.0.0"
|
|
44
|
+
},
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">= 22"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"format": "prettier --write .",
|
|
50
|
+
"lint": "eslint .",
|
|
51
|
+
"test:watch": "vitest",
|
|
52
|
+
"test": "vitest run"
|
|
53
|
+
}
|
|
6
54
|
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
import i18next from "i18next"
|
|
2
|
+
|
|
3
|
+
import { parseTrans } from "./trans.js"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @typedef {import('../types').I18nOptions} I18nOptions
|
|
7
|
+
* @typedef {import('../types').I18n} I18n
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Creates an i18next instance and the Inglorious type that drives it.
|
|
12
|
+
*
|
|
13
|
+
* The locale lives in a store entity, so changing language is an ordinary
|
|
14
|
+
* event: the handler switches i18next and updates the entity, and the render
|
|
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.
|
|
28
|
+
*
|
|
29
|
+
* @param {I18nOptions} options
|
|
30
|
+
* @returns {I18n}
|
|
31
|
+
*/
|
|
32
|
+
export function createI18n({
|
|
33
|
+
catalogues,
|
|
34
|
+
resources: givenResources = {},
|
|
35
|
+
loadLocale: givenLoadLocale,
|
|
36
|
+
locales: givenLocales,
|
|
37
|
+
defaultLocale,
|
|
38
|
+
storageKey,
|
|
39
|
+
saveUserLocale,
|
|
40
|
+
i18nextOptions = {},
|
|
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
|
+
]
|
|
50
|
+
const [firstLocale = "en"] = locales
|
|
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
|
+
|
|
62
|
+
const instance = i18next.createInstance()
|
|
63
|
+
instance.init({
|
|
64
|
+
...i18nextOptions,
|
|
65
|
+
resources,
|
|
66
|
+
// Until a loaded catalogue arrives, keys fall back rather than wait.
|
|
67
|
+
partialBundledLanguages: true,
|
|
68
|
+
lng: startLocale,
|
|
69
|
+
fallbackLng: fallbackLocale,
|
|
70
|
+
supportedLngs: locales,
|
|
71
|
+
// lit-html escapes every text binding already; escaping here too would
|
|
72
|
+
// print entities such as & on screen.
|
|
73
|
+
interpolation: { escapeValue: false, ...i18nextOptions.interpolation },
|
|
74
|
+
initAsync: false,
|
|
75
|
+
})
|
|
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
|
+
|
|
89
|
+
const I18n = {
|
|
90
|
+
create(entity) {
|
|
91
|
+
entity.locale = instance.language
|
|
92
|
+
entity.locales = locales
|
|
93
|
+
entity.languages = languages
|
|
94
|
+
entity.loadingLocale = null
|
|
95
|
+
entity.userId = null
|
|
96
|
+
entity.isUnsaved = false
|
|
97
|
+
applyDocumentLanguage(entity.locale)
|
|
98
|
+
},
|
|
99
|
+
|
|
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)
|
|
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)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Translates `key` into template parts, with the tags the translation
|
|
183
|
+
* contains rendered by `components`: `"Logging in as <strong>{{email}}</strong>."`
|
|
184
|
+
* with `{ strong: (children) => html`<strong>${children}</strong>` }`.
|
|
185
|
+
* Values fill the text between tags and stay text, so they cannot inject
|
|
186
|
+
* markup; tags without a component show as written.
|
|
187
|
+
*/
|
|
188
|
+
function trans(key, { values = {}, components = {} } = {}) {
|
|
189
|
+
const raw = instance.t(key, { ...values, skipInterpolation: true })
|
|
190
|
+
const interpolationOptions = {
|
|
191
|
+
interpolation: { ...instance.options.interpolation, escapeValue: false },
|
|
192
|
+
}
|
|
193
|
+
return parseTrans(raw, components, (text) =>
|
|
194
|
+
instance.services.interpolator.interpolate(
|
|
195
|
+
text,
|
|
196
|
+
values,
|
|
197
|
+
instance.language,
|
|
198
|
+
interpolationOptions,
|
|
199
|
+
),
|
|
200
|
+
)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function t(key, options) {
|
|
204
|
+
return instance.t(key, options)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
return {
|
|
208
|
+
I18n,
|
|
209
|
+
ready,
|
|
210
|
+
languages,
|
|
211
|
+
t,
|
|
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,
|
|
228
|
+
i18next: instance,
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* The locale to start with: the one saved by a previous choice, else the
|
|
234
|
+
* first of the device's languages that is supported (exactly, or by its base
|
|
235
|
+
* language, so `it-CH` picks `it`), else the default.
|
|
236
|
+
*
|
|
237
|
+
* @param {{ locales: string[], defaultLocale: string, storageKey?: string }} options
|
|
238
|
+
* @returns {string}
|
|
239
|
+
*/
|
|
240
|
+
export function detectLocale({ locales, defaultLocale, storageKey }) {
|
|
241
|
+
const saved = readLocale(storageKey)
|
|
242
|
+
if (saved && locales.includes(saved)) return saved
|
|
243
|
+
|
|
244
|
+
const preferred =
|
|
245
|
+
typeof navigator === "undefined"
|
|
246
|
+
? []
|
|
247
|
+
: (navigator.languages ?? [navigator.language])
|
|
248
|
+
for (const language of preferred.filter(Boolean)) {
|
|
249
|
+
if (locales.includes(language)) return language
|
|
250
|
+
const [base] = language.split("-")
|
|
251
|
+
if (locales.includes(base)) return base
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
return defaultLocale
|
|
255
|
+
}
|
|
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
|
+
|
|
343
|
+
function readLocale(storageKey) {
|
|
344
|
+
if (!storageKey) return null
|
|
345
|
+
try {
|
|
346
|
+
return globalThis.localStorage?.getItem(storageKey) ?? null
|
|
347
|
+
} catch {
|
|
348
|
+
// Storage can be unavailable (private mode, server rendering): fall back
|
|
349
|
+
// to detection rather than failing.
|
|
350
|
+
return null
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function saveLocale(storageKey, locale) {
|
|
355
|
+
if (!storageKey) return
|
|
356
|
+
try {
|
|
357
|
+
globalThis.localStorage?.setItem(storageKey, locale)
|
|
358
|
+
} catch {
|
|
359
|
+
// Not persisting the choice is better than breaking the switch.
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Screen readers, hyphenation and the browser's own spell checking read the
|
|
364
|
+
// document language, so it follows the app's.
|
|
365
|
+
function applyDocumentLanguage(locale) {
|
|
366
|
+
if (typeof document === "undefined") return
|
|
367
|
+
document.documentElement.lang = locale
|
|
368
|
+
}
|
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
import { createStore } from "@inglorious/store"
|
|
2
|
+
import { afterEach, describe, expect, it, vi } from "vitest"
|
|
3
|
+
|
|
4
|
+
import { createI18n, detectLocale } from "./index.js"
|
|
5
|
+
|
|
6
|
+
const resources = {
|
|
7
|
+
en: {
|
|
8
|
+
translation: {
|
|
9
|
+
hello: "Hello",
|
|
10
|
+
greet: "Hello, {{name}}",
|
|
11
|
+
event_one: "{{count}} event",
|
|
12
|
+
event_other: "{{count}} events",
|
|
13
|
+
},
|
|
14
|
+
},
|
|
15
|
+
it: {
|
|
16
|
+
translation: {
|
|
17
|
+
hello: "Ciao",
|
|
18
|
+
greet: "Ciao, {{name}}",
|
|
19
|
+
event_one: "{{count}} evento",
|
|
20
|
+
event_other: "{{count}} eventi",
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function stubBrowser({ languages = [], saved = {} } = {}) {
|
|
26
|
+
const store = { ...saved }
|
|
27
|
+
vi.stubGlobal("navigator", { languages, language: languages[0] })
|
|
28
|
+
vi.stubGlobal("localStorage", {
|
|
29
|
+
getItem: (key) => store[key] ?? null,
|
|
30
|
+
setItem: (key, value) => {
|
|
31
|
+
store[key] = value
|
|
32
|
+
},
|
|
33
|
+
})
|
|
34
|
+
vi.stubGlobal("document", { documentElement: { lang: "" } })
|
|
35
|
+
return store
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
afterEach(() => {
|
|
39
|
+
vi.unstubAllGlobals()
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
describe("detectLocale", () => {
|
|
43
|
+
const options = {
|
|
44
|
+
locales: ["en", "it"],
|
|
45
|
+
defaultLocale: "en",
|
|
46
|
+
storageKey: "lang",
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
it("prefers the locale the user chose before", () => {
|
|
50
|
+
stubBrowser({ languages: ["en-US"], saved: { lang: "it" } })
|
|
51
|
+
expect(detectLocale(options)).toBe("it")
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
it("matches a device language by its base language", () => {
|
|
55
|
+
stubBrowser({ languages: ["fr-FR", "it-CH"] })
|
|
56
|
+
expect(detectLocale(options)).toBe("it")
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
it("falls back to the default when nothing matches", () => {
|
|
60
|
+
stubBrowser({ languages: ["fr-FR"] })
|
|
61
|
+
expect(detectLocale(options)).toBe("en")
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
it("ignores a saved locale that is no longer supported", () => {
|
|
65
|
+
stubBrowser({ languages: ["en"], saved: { lang: "de" } })
|
|
66
|
+
expect(detectLocale(options)).toBe("en")
|
|
67
|
+
})
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
describe("createI18n", () => {
|
|
71
|
+
it("translates with interpolation and plurals", () => {
|
|
72
|
+
stubBrowser({ languages: ["en"] })
|
|
73
|
+
const { t } = createI18n({ resources })
|
|
74
|
+
|
|
75
|
+
expect(t("greet", { name: "Ada & Grace" })).toBe("Hello, Ada & Grace")
|
|
76
|
+
expect(t("event", { count: 1 })).toBe("1 event")
|
|
77
|
+
expect(t("event", { count: 3 })).toBe("3 events")
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
it("starts in the device language and sets the document language", () => {
|
|
81
|
+
stubBrowser({ languages: ["it-IT"] })
|
|
82
|
+
const { I18n } = createI18n({ resources })
|
|
83
|
+
const entity = {}
|
|
84
|
+
|
|
85
|
+
I18n.create(entity)
|
|
86
|
+
|
|
87
|
+
expect(entity.locale).toBe("it")
|
|
88
|
+
expect(entity.locales).toEqual(["en", "it"])
|
|
89
|
+
expect(document.documentElement.lang).toBe("it")
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
it("switches language, remembers it and ignores unsupported ones", () => {
|
|
93
|
+
const saved = stubBrowser({ languages: ["en"] })
|
|
94
|
+
const { I18n, t } = createI18n({ resources, storageKey: "lang" })
|
|
95
|
+
const entity = {}
|
|
96
|
+
I18n.create(entity)
|
|
97
|
+
|
|
98
|
+
I18n.localeChange(entity, "it")
|
|
99
|
+
expect(entity.locale).toBe("it")
|
|
100
|
+
expect(t("hello")).toBe("Ciao")
|
|
101
|
+
expect(saved.lang).toBe("it")
|
|
102
|
+
expect(document.documentElement.lang).toBe("it")
|
|
103
|
+
|
|
104
|
+
I18n.localeChange(entity, "de")
|
|
105
|
+
expect(entity.locale).toBe("it")
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
it("drives a store: an event switches every later translation", () => {
|
|
109
|
+
stubBrowser({ languages: ["en"] })
|
|
110
|
+
const { I18n, t } = createI18n({ resources })
|
|
111
|
+
const store = createStore({
|
|
112
|
+
types: { I18n },
|
|
113
|
+
entities: { i18n: { type: "I18n" } },
|
|
114
|
+
})
|
|
115
|
+
store.notify("init")
|
|
116
|
+
|
|
117
|
+
expect(store.getState().i18n.locale).toBe("en")
|
|
118
|
+
expect(t("hello")).toBe("Hello")
|
|
119
|
+
|
|
120
|
+
store.notify("#i18n:localeChange", "it")
|
|
121
|
+
|
|
122
|
+
expect(store.getState().i18n.locale).toBe("it")
|
|
123
|
+
expect(t("hello")).toBe("Ciao")
|
|
124
|
+
})
|
|
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/src/trans.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Tags in a translation are placeholders for components, not HTML: only the
|
|
2
|
+
// names the caller passes in `components` are replaced, and anything else
|
|
3
|
+
// stays visible text. Values are interpolated into the text between tags
|
|
4
|
+
// after parsing, so a value can never turn into markup.
|
|
5
|
+
const TAG = /<(\/?)([A-Za-z0-9_-]+)\s*(\/?)>/g
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Turns a translated string into parts for a template: strings, and what the
|
|
9
|
+
* components return for the tags they own.
|
|
10
|
+
*
|
|
11
|
+
* @param {string} raw - The translation, with `{{placeholders}}` still in it.
|
|
12
|
+
* @param {Record<string, (children: unknown[]) => unknown>} components
|
|
13
|
+
* @param {(text: string) => string} interpolate - Fills the placeholders of a text piece.
|
|
14
|
+
* @returns {unknown[]}
|
|
15
|
+
*/
|
|
16
|
+
export function parseTrans(raw, components, interpolate) {
|
|
17
|
+
const root = { children: [], parent: null }
|
|
18
|
+
let current = root
|
|
19
|
+
const addText = (text) => {
|
|
20
|
+
if (text) current.children.push(interpolate(text))
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
let last = 0
|
|
24
|
+
for (const match of raw.matchAll(TAG)) {
|
|
25
|
+
const [source, closing, name, selfClosing] = match
|
|
26
|
+
addText(raw.slice(last, match.index))
|
|
27
|
+
last = match.index + source.length
|
|
28
|
+
|
|
29
|
+
const component = components[name]
|
|
30
|
+
if (!component) {
|
|
31
|
+
// Not one of the caller's tags: show it as it was written.
|
|
32
|
+
current.children.push(source)
|
|
33
|
+
} else if (selfClosing) {
|
|
34
|
+
current.children.push(component([]))
|
|
35
|
+
} else if (!closing) {
|
|
36
|
+
current = { name, source, children: [], parent: current }
|
|
37
|
+
} else if (current.name === name) {
|
|
38
|
+
const node = current
|
|
39
|
+
current = node.parent
|
|
40
|
+
current.children.push(component(node.children))
|
|
41
|
+
} else {
|
|
42
|
+
// A closing tag with nothing of its name open.
|
|
43
|
+
current.children.push(source)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
addText(raw.slice(last))
|
|
47
|
+
|
|
48
|
+
// Tags left open were never components: put them back as text, contents
|
|
49
|
+
// and all.
|
|
50
|
+
while (current !== root) {
|
|
51
|
+
const node = current
|
|
52
|
+
current = node.parent
|
|
53
|
+
current.children.push(node.source, ...node.children)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return root.children
|
|
57
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from "vitest"
|
|
2
|
+
|
|
3
|
+
import { createI18n } from "./index.js"
|
|
4
|
+
|
|
5
|
+
const resources = {
|
|
6
|
+
en: {
|
|
7
|
+
translation: {
|
|
8
|
+
loggedInAs: "Logging in as <strong>{{email}}</strong>.",
|
|
9
|
+
terms: "Read the <link>terms of <em>service</em></link>",
|
|
10
|
+
lineBreak: "First<br/>Second",
|
|
11
|
+
unknown: "A <script>tag</script> stays text",
|
|
12
|
+
stray: "One </strong> and <strong>two",
|
|
13
|
+
events_one: "<b>{{count}}</b> event",
|
|
14
|
+
events_other: "<b>{{count}}</b> events",
|
|
15
|
+
due: "Due <em>{{date, datetime}}</em>",
|
|
16
|
+
},
|
|
17
|
+
},
|
|
18
|
+
it: {
|
|
19
|
+
translation: {
|
|
20
|
+
loggedInAs: "<strong>{{email}}</strong> sta accedendo.",
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Components return plain objects, so the tests can see what was built.
|
|
26
|
+
const tag = (name) => (children) => ({ tag: name, children })
|
|
27
|
+
const components = {
|
|
28
|
+
strong: tag("strong"),
|
|
29
|
+
em: tag("em"),
|
|
30
|
+
link: tag("link"),
|
|
31
|
+
br: tag("br"),
|
|
32
|
+
b: tag("b"),
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function setup() {
|
|
36
|
+
vi.stubGlobal("navigator", { languages: ["en"] })
|
|
37
|
+
return createI18n({ resources })
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
afterEach(() => {
|
|
41
|
+
vi.unstubAllGlobals()
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
describe("trans", () => {
|
|
45
|
+
it("renders tags through their components, with values as text", () => {
|
|
46
|
+
const { trans } = setup()
|
|
47
|
+
|
|
48
|
+
expect(
|
|
49
|
+
trans("loggedInAs", { values: { email: "ada@x.it" }, components }),
|
|
50
|
+
).toEqual([
|
|
51
|
+
"Logging in as ",
|
|
52
|
+
{ tag: "strong", children: ["ada@x.it"] },
|
|
53
|
+
".",
|
|
54
|
+
])
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it("keeps a value that looks like markup as text", () => {
|
|
58
|
+
const { trans } = setup()
|
|
59
|
+
|
|
60
|
+
expect(
|
|
61
|
+
trans("loggedInAs", {
|
|
62
|
+
values: { email: "<em>x</em><img src=x onerror=alert(1)>" },
|
|
63
|
+
components,
|
|
64
|
+
}),
|
|
65
|
+
).toEqual([
|
|
66
|
+
"Logging in as ",
|
|
67
|
+
{ tag: "strong", children: ["<em>x</em><img src=x onerror=alert(1)>"] },
|
|
68
|
+
".",
|
|
69
|
+
])
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
it("nests tags", () => {
|
|
73
|
+
const { trans } = setup()
|
|
74
|
+
|
|
75
|
+
expect(trans("terms", { components })).toEqual([
|
|
76
|
+
"Read the ",
|
|
77
|
+
{
|
|
78
|
+
tag: "link",
|
|
79
|
+
children: ["terms of ", { tag: "em", children: ["service"] }],
|
|
80
|
+
},
|
|
81
|
+
])
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
it("renders self-closing tags with no children", () => {
|
|
85
|
+
const { trans } = setup()
|
|
86
|
+
|
|
87
|
+
expect(trans("lineBreak", { components })).toEqual([
|
|
88
|
+
"First",
|
|
89
|
+
{ tag: "br", children: [] },
|
|
90
|
+
"Second",
|
|
91
|
+
])
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
it("shows tags without a component as written", () => {
|
|
95
|
+
const { trans } = setup()
|
|
96
|
+
|
|
97
|
+
expect(trans("unknown", { components })).toEqual([
|
|
98
|
+
"A ",
|
|
99
|
+
"<script>",
|
|
100
|
+
"tag",
|
|
101
|
+
"</script>",
|
|
102
|
+
" stays text",
|
|
103
|
+
])
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
it("shows stray and unclosed tags as written", () => {
|
|
107
|
+
const { trans } = setup()
|
|
108
|
+
|
|
109
|
+
expect(trans("stray", { components })).toEqual([
|
|
110
|
+
"One ",
|
|
111
|
+
"</strong>",
|
|
112
|
+
" and ",
|
|
113
|
+
"<strong>",
|
|
114
|
+
"two",
|
|
115
|
+
])
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
it("picks the plural form and formats values", () => {
|
|
119
|
+
const { trans } = setup()
|
|
120
|
+
|
|
121
|
+
expect(trans("events", { values: { count: 3 }, components })).toEqual([
|
|
122
|
+
{ tag: "b", children: ["3"] },
|
|
123
|
+
" events",
|
|
124
|
+
])
|
|
125
|
+
expect(
|
|
126
|
+
trans("due", {
|
|
127
|
+
values: {
|
|
128
|
+
date: new Date("2026-10-24T12:00:00Z"),
|
|
129
|
+
formatParams: { date: { day: "numeric", month: "short" } },
|
|
130
|
+
},
|
|
131
|
+
components,
|
|
132
|
+
}),
|
|
133
|
+
).toEqual(["Due ", { tag: "em", children: ["Oct 24"] }])
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
it("follows the active language, word order included", () => {
|
|
137
|
+
const { I18n, trans } = setup()
|
|
138
|
+
const entity = {}
|
|
139
|
+
I18n.create(entity)
|
|
140
|
+
I18n.localeChange(entity, "it")
|
|
141
|
+
|
|
142
|
+
expect(
|
|
143
|
+
trans("loggedInAs", { values: { email: "ada@x.it" }, components }),
|
|
144
|
+
).toEqual([{ tag: "strong", children: ["ada@x.it"] }, " sta accedendo."])
|
|
145
|
+
})
|
|
146
|
+
})
|
package/types/index.d.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import type { i18n, InitOptions, Resource, TOptions } from "i18next"
|
|
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
|
+
|
|
7
|
+
export interface I18nOptions {
|
|
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`. */
|
|
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]>
|
|
24
|
+
/** The fallback, and the locale when nothing else matches. Defaults to the first locale. */
|
|
25
|
+
defaultLocale?: string
|
|
26
|
+
/** Where to remember the user's choice in localStorage. Omit to not remember it. */
|
|
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
|
|
34
|
+
/** Any further i18next options. `resources`, `lng`, `fallbackLng`, `supportedLngs` and `initAsync` are set by `createI18n`. */
|
|
35
|
+
i18nextOptions?: InitOptions
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface I18nEntity {
|
|
39
|
+
id: string
|
|
40
|
+
type: string
|
|
41
|
+
/** The active locale. */
|
|
42
|
+
locale?: string
|
|
43
|
+
/** The supported locales, for a language picker. */
|
|
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
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface I18nType {
|
|
62
|
+
create(entity: I18nEntity): 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
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface TransOptions<Part = unknown> {
|
|
93
|
+
/** Values for the `{{placeholders}}`. They are inserted as text, never as markup. */
|
|
94
|
+
values?: TOptions
|
|
95
|
+
/** One renderer per tag name the translation uses; it receives the tag's contents. */
|
|
96
|
+
components?: Record<string, (children: Array<string | Part>) => Part>
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface I18n {
|
|
100
|
+
/** The type to register in the store, e.g. `types: { I18n }` with an `i18n` entity. */
|
|
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
|
|
115
|
+
/** Translates `key` in the active locale. Same signature as i18next's `t`. */
|
|
116
|
+
t: (key: string | string[], options?: TOptions) => string
|
|
117
|
+
/**
|
|
118
|
+
* Translates `key` into template parts, rendering the tags in the translation
|
|
119
|
+
* through `components`. Tags without a component show as written.
|
|
120
|
+
*/
|
|
121
|
+
trans: <Part = unknown>(
|
|
122
|
+
key: string | string[],
|
|
123
|
+
options?: TransOptions<Part>,
|
|
124
|
+
) => Array<string | Part>
|
|
125
|
+
/** The underlying i18next instance, for anything the adapter does not cover. */
|
|
126
|
+
i18next: i18n
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function createI18n(options: I18nOptions): I18n
|
|
130
|
+
|
|
131
|
+
export function detectLocale(options: {
|
|
132
|
+
locales: string[]
|
|
133
|
+
defaultLocale: string
|
|
134
|
+
storageKey?: string
|
|
135
|
+
}): string
|