@inglorious/i18n 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +9 -0
- package/README.md +140 -2
- package/package.json +51 -3
- package/src/index.js +140 -0
- package/src/index.test.js +125 -0
- package/src/trans.js +57 -0
- package/src/trans.test.js +146 -0
- package/types/index.d.ts +61 -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,141 @@
|
|
|
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
|
+
```javascript
|
|
16
|
+
// src/i18n.js
|
|
17
|
+
import { createI18n } from "@inglorious/i18n"
|
|
18
|
+
|
|
19
|
+
import en from "./locales/en.json"
|
|
20
|
+
import it from "./locales/it.json"
|
|
21
|
+
|
|
22
|
+
export const { I18n, t } = createI18n({
|
|
23
|
+
resources: { en: { translation: en }, it: { translation: it } },
|
|
24
|
+
defaultLocale: "en",
|
|
25
|
+
storageKey: "my-app-locale",
|
|
26
|
+
})
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Register the type and an entity for it:
|
|
30
|
+
|
|
31
|
+
```javascript
|
|
32
|
+
import { createStore } from "@inglorious/store"
|
|
33
|
+
|
|
34
|
+
import { I18n } from "./i18n.js"
|
|
35
|
+
|
|
36
|
+
export const store = createStore({
|
|
37
|
+
types: { I18n /* , … */ },
|
|
38
|
+
entities: { i18n: { type: "I18n" } /* , … */ },
|
|
39
|
+
})
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Translate in any template:
|
|
43
|
+
|
|
44
|
+
```javascript
|
|
45
|
+
import { html } from "@inglorious/web"
|
|
46
|
+
|
|
47
|
+
import { t } from "../i18n.js"
|
|
48
|
+
|
|
49
|
+
export const Events = {
|
|
50
|
+
render(entity) {
|
|
51
|
+
return html`<h1>${t("events.title")}</h1>
|
|
52
|
+
<p>${t("events.count", { count: entity.events.length })}</p>`
|
|
53
|
+
},
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Switch language from anywhere:
|
|
58
|
+
|
|
59
|
+
```javascript
|
|
60
|
+
api.notify("#i18n:localeChange", "it")
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## API
|
|
64
|
+
|
|
65
|
+
### `createI18n(options)`
|
|
66
|
+
|
|
67
|
+
Returns `{ I18n, t, trans, i18next }`.
|
|
68
|
+
|
|
69
|
+
- `resources`: the catalogues, `{ [locale]: { translation: { … } } }`.
|
|
70
|
+
- `locales`: the supported locales. Defaults to the keys of `resources`.
|
|
71
|
+
- `defaultLocale`: the fallback, and the locale when nothing else matches. Defaults to the first locale.
|
|
72
|
+
- `storageKey`: where to remember the user's choice in `localStorage`. Omit it to not remember the choice.
|
|
73
|
+
- `i18nextOptions`: any further i18next options.
|
|
74
|
+
|
|
75
|
+
The starting locale is the saved choice, else the first of the device's languages that is supported (`it-CH` picks `it`), else `defaultLocale`.
|
|
76
|
+
|
|
77
|
+
With the catalogues passed in `resources`, i18next initialises and switches synchronously, so there is no loading state to handle.
|
|
78
|
+
|
|
79
|
+
### The `I18n` type
|
|
80
|
+
|
|
81
|
+
- `create(entity)`: sets `entity.locale` and `entity.locales`, and `<html lang>`.
|
|
82
|
+
- `localeChange(entity, locale)`: switches i18next, updates `entity.locale`, remembers the choice and sets `<html lang>`. Unsupported locales are ignored.
|
|
83
|
+
|
|
84
|
+
### `t(key, options)`
|
|
85
|
+
|
|
86
|
+
i18next's `t`, bound to this instance. Everything i18next supports works:
|
|
87
|
+
|
|
88
|
+
```json
|
|
89
|
+
{
|
|
90
|
+
"greet": "Hello, {{name}}",
|
|
91
|
+
"event_one": "{{count}} event",
|
|
92
|
+
"event_other": "{{count}} events",
|
|
93
|
+
"deadline": "Closes on {{date, datetime}}"
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
```javascript
|
|
98
|
+
t("greet", { name: "Ada" })
|
|
99
|
+
t("event", { count: 3 })
|
|
100
|
+
t("deadline", {
|
|
101
|
+
date: new Date(),
|
|
102
|
+
formatParams: { date: { day: "numeric", month: "short" } },
|
|
103
|
+
})
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Interpolated values are not HTML-escaped: lit-html escapes every text binding already.
|
|
107
|
+
|
|
108
|
+
### `trans(key, { values, components })`
|
|
109
|
+
|
|
110
|
+
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.
|
|
111
|
+
|
|
112
|
+
```json
|
|
113
|
+
{
|
|
114
|
+
"loggedInAs": "Logging in as <strong>{{email}}</strong>.",
|
|
115
|
+
"terms": "Read the <link>terms of service</link>",
|
|
116
|
+
"twoLines": "First line<br/>Second line"
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
```javascript
|
|
121
|
+
import { html } from "@inglorious/web"
|
|
122
|
+
|
|
123
|
+
html`<p>
|
|
124
|
+
${trans("loggedInAs", {
|
|
125
|
+
values: { email },
|
|
126
|
+
components: { strong: (children) => html`<strong>${children}</strong>` },
|
|
127
|
+
})}
|
|
128
|
+
</p>`
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
It returns an array of parts (strings and what the components return), which lit renders like any other array.
|
|
132
|
+
|
|
133
|
+
It is safe with user data:
|
|
134
|
+
|
|
135
|
+
- Values are interpolated after the tags are parsed, as text: an email such as `<img src=x onerror=…>` shows as typed.
|
|
136
|
+
- A tag without a component (`<script>`, a typo, a stray `</b>`) shows as written instead of becoming markup.
|
|
137
|
+
- Plurals and formatters work as in `t`: `trans("events", { values: { count } })`.
|
|
138
|
+
|
|
139
|
+
### `detectLocale({ locales, defaultLocale, storageKey })`
|
|
140
|
+
|
|
141
|
+
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.0.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,140 @@
|
|
|
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. With the catalogues
|
|
16
|
+
* passed in `resources`, i18next initialises and switches synchronously, so
|
|
17
|
+
* nothing has to wait for a promise.
|
|
18
|
+
*
|
|
19
|
+
* @param {I18nOptions} options
|
|
20
|
+
* @returns {I18n}
|
|
21
|
+
*/
|
|
22
|
+
export function createI18n({
|
|
23
|
+
resources,
|
|
24
|
+
locales = Object.keys(resources ?? {}),
|
|
25
|
+
defaultLocale,
|
|
26
|
+
storageKey,
|
|
27
|
+
i18nextOptions = {},
|
|
28
|
+
}) {
|
|
29
|
+
const [firstLocale = "en"] = locales
|
|
30
|
+
const fallbackLocale = defaultLocale ?? firstLocale
|
|
31
|
+
const instance = i18next.createInstance()
|
|
32
|
+
instance.init({
|
|
33
|
+
...i18nextOptions,
|
|
34
|
+
resources,
|
|
35
|
+
lng: detectLocale({ locales, defaultLocale: fallbackLocale, storageKey }),
|
|
36
|
+
fallbackLng: fallbackLocale,
|
|
37
|
+
supportedLngs: locales,
|
|
38
|
+
// lit-html escapes every text binding already; escaping here too would
|
|
39
|
+
// print entities such as & on screen.
|
|
40
|
+
interpolation: { escapeValue: false, ...i18nextOptions.interpolation },
|
|
41
|
+
initAsync: false,
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
const I18n = {
|
|
45
|
+
create(entity) {
|
|
46
|
+
entity.locale = instance.language
|
|
47
|
+
entity.locales = locales
|
|
48
|
+
applyDocumentLanguage(entity.locale)
|
|
49
|
+
},
|
|
50
|
+
|
|
51
|
+
localeChange(entity, locale) {
|
|
52
|
+
if (!locales.includes(locale) || locale === entity.locale) return
|
|
53
|
+
instance.changeLanguage(locale)
|
|
54
|
+
entity.locale = locale
|
|
55
|
+
saveLocale(storageKey, locale)
|
|
56
|
+
applyDocumentLanguage(locale)
|
|
57
|
+
},
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Translates `key` into template parts, with the tags the translation
|
|
62
|
+
* contains rendered by `components`: `"Logging in as <strong>{{email}}</strong>."`
|
|
63
|
+
* with `{ strong: (children) => html`<strong>${children}</strong>` }`.
|
|
64
|
+
* Values fill the text between tags and stay text, so they cannot inject
|
|
65
|
+
* markup; tags without a component show as written.
|
|
66
|
+
*/
|
|
67
|
+
function trans(key, { values = {}, components = {} } = {}) {
|
|
68
|
+
const raw = instance.t(key, { ...values, skipInterpolation: true })
|
|
69
|
+
const interpolationOptions = {
|
|
70
|
+
interpolation: { ...instance.options.interpolation, escapeValue: false },
|
|
71
|
+
}
|
|
72
|
+
return parseTrans(raw, components, (text) =>
|
|
73
|
+
instance.services.interpolator.interpolate(
|
|
74
|
+
text,
|
|
75
|
+
values,
|
|
76
|
+
instance.language,
|
|
77
|
+
interpolationOptions,
|
|
78
|
+
),
|
|
79
|
+
)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
I18n,
|
|
84
|
+
t: (key, options) => instance.t(key, options),
|
|
85
|
+
trans,
|
|
86
|
+
i18next: instance,
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The locale to start with: the one saved by a previous choice, else the
|
|
92
|
+
* first of the device's languages that is supported (exactly, or by its base
|
|
93
|
+
* language, so `it-CH` picks `it`), else the default.
|
|
94
|
+
*
|
|
95
|
+
* @param {{ locales: string[], defaultLocale: string, storageKey?: string }} options
|
|
96
|
+
* @returns {string}
|
|
97
|
+
*/
|
|
98
|
+
export function detectLocale({ locales, defaultLocale, storageKey }) {
|
|
99
|
+
const saved = readLocale(storageKey)
|
|
100
|
+
if (saved && locales.includes(saved)) return saved
|
|
101
|
+
|
|
102
|
+
const preferred =
|
|
103
|
+
typeof navigator === "undefined"
|
|
104
|
+
? []
|
|
105
|
+
: (navigator.languages ?? [navigator.language])
|
|
106
|
+
for (const language of preferred.filter(Boolean)) {
|
|
107
|
+
if (locales.includes(language)) return language
|
|
108
|
+
const [base] = language.split("-")
|
|
109
|
+
if (locales.includes(base)) return base
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return defaultLocale
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function readLocale(storageKey) {
|
|
116
|
+
if (!storageKey) return null
|
|
117
|
+
try {
|
|
118
|
+
return globalThis.localStorage?.getItem(storageKey) ?? null
|
|
119
|
+
} catch {
|
|
120
|
+
// Storage can be unavailable (private mode, server rendering): fall back
|
|
121
|
+
// to detection rather than failing.
|
|
122
|
+
return null
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function saveLocale(storageKey, locale) {
|
|
127
|
+
if (!storageKey) return
|
|
128
|
+
try {
|
|
129
|
+
globalThis.localStorage?.setItem(storageKey, locale)
|
|
130
|
+
} catch {
|
|
131
|
+
// Not persisting the choice is better than breaking the switch.
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Screen readers, hyphenation and the browser's own spell checking read the
|
|
136
|
+
// document language, so it follows the app's.
|
|
137
|
+
function applyDocumentLanguage(locale) {
|
|
138
|
+
if (typeof document === "undefined") return
|
|
139
|
+
document.documentElement.lang = locale
|
|
140
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
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
|
+
})
|
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,61 @@
|
|
|
1
|
+
import type { i18n, InitOptions, Resource, TOptions } from "i18next"
|
|
2
|
+
|
|
3
|
+
export interface I18nOptions {
|
|
4
|
+
/** The catalogues, by locale: `{ en: { translation: { … } }, it: … }`. */
|
|
5
|
+
resources: Resource
|
|
6
|
+
/** The supported locales. Defaults to the keys of `resources`. */
|
|
7
|
+
locales?: string[]
|
|
8
|
+
/** The fallback, and the locale when nothing else matches. Defaults to the first locale. */
|
|
9
|
+
defaultLocale?: string
|
|
10
|
+
/** Where to remember the user's choice in localStorage. Omit to not remember it. */
|
|
11
|
+
storageKey?: string
|
|
12
|
+
/** Any further i18next options. `resources`, `lng`, `fallbackLng`, `supportedLngs` and `initAsync` are set by `createI18n`. */
|
|
13
|
+
i18nextOptions?: InitOptions
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface I18nEntity {
|
|
17
|
+
id: string
|
|
18
|
+
type: string
|
|
19
|
+
/** The active locale. */
|
|
20
|
+
locale?: string
|
|
21
|
+
/** The supported locales, for a language picker. */
|
|
22
|
+
locales?: string[]
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface I18nType {
|
|
26
|
+
create(entity: I18nEntity): void
|
|
27
|
+
/** Switches to `locale`, remembers it and sets `<html lang>`. Unsupported locales are ignored. */
|
|
28
|
+
localeChange(entity: I18nEntity, locale: string): void
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface TransOptions<Part = unknown> {
|
|
32
|
+
/** Values for the `{{placeholders}}`. They are inserted as text, never as markup. */
|
|
33
|
+
values?: TOptions
|
|
34
|
+
/** One renderer per tag name the translation uses; it receives the tag's contents. */
|
|
35
|
+
components?: Record<string, (children: Array<string | Part>) => Part>
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface I18n {
|
|
39
|
+
/** The type to register in the store, e.g. `types: { I18n }` with an `i18n` entity. */
|
|
40
|
+
I18n: I18nType
|
|
41
|
+
/** Translates `key` in the active locale. Same signature as i18next's `t`. */
|
|
42
|
+
t: (key: string | string[], options?: TOptions) => string
|
|
43
|
+
/**
|
|
44
|
+
* Translates `key` into template parts, rendering the tags in the translation
|
|
45
|
+
* through `components`. Tags without a component show as written.
|
|
46
|
+
*/
|
|
47
|
+
trans: <Part = unknown>(
|
|
48
|
+
key: string | string[],
|
|
49
|
+
options?: TransOptions<Part>,
|
|
50
|
+
) => Array<string | Part>
|
|
51
|
+
/** The underlying i18next instance, for anything the adapter does not cover. */
|
|
52
|
+
i18next: i18n
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function createI18n(options: I18nOptions): I18n
|
|
56
|
+
|
|
57
|
+
export function detectLocale(options: {
|
|
58
|
+
locales: string[]
|
|
59
|
+
defaultLocale: string
|
|
60
|
+
storageKey?: string
|
|
61
|
+
}): string
|