@rivinia/i18n 0.3.3 → 0.4.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 +374 -153
- package/cli/rivinia-i18n-keys.mjs +165 -0
- package/fesm2022/{rivinia-i18n-http-loader.impl-DVlKmSDL.mjs → rivinia-i18n-http-loader.impl--BRii7w1.mjs} +5 -3
- package/fesm2022/rivinia-i18n-http-loader.impl--BRii7w1.mjs.map +1 -0
- package/fesm2022/{rivinia-i18n-json-loader.impl-VXwAmyWL.mjs → rivinia-i18n-json-loader.impl-Bq-W-UW9.mjs} +5 -3
- package/fesm2022/rivinia-i18n-json-loader.impl-Bq-W-UW9.mjs.map +1 -0
- package/fesm2022/rivinia-i18n-loader-url-B9SlR1XB.mjs +11 -0
- package/fesm2022/rivinia-i18n-loader-url-B9SlR1XB.mjs.map +1 -0
- package/fesm2022/{rivinia-i18n-remote-loader.impl-XKqdLHoJ.mjs → rivinia-i18n-remote-loader.impl-CqKS6JWN.mjs} +4 -3
- package/fesm2022/rivinia-i18n-remote-loader.impl-CqKS6JWN.mjs.map +1 -0
- package/fesm2022/rivinia-i18n.mjs +397 -62
- package/fesm2022/rivinia-i18n.mjs.map +1 -1
- package/package.json +5 -2
- package/types/rivinia-i18n.d.ts +204 -50
- package/fesm2022/rivinia-i18n-http-loader.impl-DVlKmSDL.mjs.map +0 -1
- package/fesm2022/rivinia-i18n-json-loader.impl-VXwAmyWL.mjs.map +0 -1
- package/fesm2022/rivinia-i18n-remote-loader.impl-XKqdLHoJ.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -3,218 +3,439 @@
|
|
|
3
3
|
[](https://www.npmjs.com/package/@rivinia/i18n)
|
|
4
4
|
[](https://www.npmjs.com/package/@rivinia/i18n)
|
|
5
5
|
|
|
6
|
-
A headless Angular language manager built on signals.
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
A headless Angular language manager built on signals. Key-based JSON
|
|
7
|
+
dictionaries, inline translations, RTL/LTR document attributes, lazy loaders,
|
|
8
|
+
ICU plural/select messages, browser-language detection, and `Intl` number/date
|
|
9
|
+
formatting — with SSR that actually works and no runtime dependency beyond
|
|
10
|
+
Angular.
|
|
11
|
+
|
|
12
|
+
- Package version: **0.4.0**
|
|
13
|
+
- Peer dependency: **`@angular/core` `^22.0.0`** (plus `@angular-devkit/schematics` for `ng add`)
|
|
14
|
+
- Entry point: **`@rivinia/i18n`** (single public entry point)
|
|
15
|
+
- `sideEffects: false`; no runtime import beyond `@angular/core`; loaders are lazy chunks
|
|
16
|
+
- No `HttpClient` peer — the built-in loaders use `fetch`
|
|
17
|
+
|
|
18
|
+
## Quick features
|
|
19
|
+
|
|
20
|
+
- **Signal-first state.** `currentLanguage`, `dir`, `loadingState`, `missingKeys` and
|
|
21
|
+
`locale` are readonly signals; changes only via methods.
|
|
22
|
+
- **Zero-config dictionaries.** `jsonLoader()` reads `i18n/{language}.json` — the
|
|
23
|
+
`public/i18n/` layout Angular serves at the site root.
|
|
24
|
+
- **SSR-correct URLs.** On the server the loader builds an absolute URL from
|
|
25
|
+
`REQUEST` + `<base href>`; the browser uses `document.baseURI`.
|
|
26
|
+
- **TransferState hydration.** Dictionaries rendered on the server are not fetched again
|
|
27
|
+
by the client (measured in the e2e app).
|
|
28
|
+
- **Fallback language.** Current dictionary → fallback dictionary → `defaultValue` → key.
|
|
29
|
+
Fallback text keeps the fallback locale's plural rules.
|
|
30
|
+
- **Missing-key reporting.** `onMissingKey`, a `missingKeys` signal, and a dev-mode
|
|
31
|
+
warning — once per key per session, never a false positive during loading.
|
|
32
|
+
- **`reload()`.** Stale-while-revalidate: the visible dictionary stays on screen until
|
|
33
|
+
the fresh one arrives.
|
|
34
|
+
- **ICU subset with the six Arabic plural forms.** `plural`, `selectordinal`, `offset:`,
|
|
35
|
+
`select`, `number`/`date` styles, nesting, and `#`.
|
|
36
|
+
- **`t()` returns a `Signal<string>`**, so a field re-renders on a language switch or on a
|
|
37
|
+
signal read by its params function.
|
|
38
|
+
- **Typed keys.** A generated `.d.ts` turns a typo into a compile error; without it every
|
|
39
|
+
string key stays legal.
|
|
40
|
+
- **Persistence + detection.** local/session/cookie storage, `navigator.languages` match,
|
|
41
|
+
`<html lang>` and `<html dir>` kept in sync.
|
|
42
|
+
|
|
43
|
+
## Install
|
|
10
44
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
45
|
+
```bash
|
|
46
|
+
npm install @rivinia/i18n
|
|
47
|
+
pnpm add @rivinia/i18n
|
|
48
|
+
yarn add @rivinia/i18n
|
|
49
|
+
bun add @rivinia/i18n
|
|
50
|
+
```
|
|
14
51
|
|
|
15
|
-
|
|
52
|
+
With the CLI schematic (wires a starter provider into `app.config.ts`):
|
|
16
53
|
|
|
17
54
|
```bash
|
|
18
|
-
npm install @rivinia/i18n
|
|
19
55
|
ng add @rivinia/i18n
|
|
20
56
|
```
|
|
21
57
|
|
|
22
|
-
`ng add`
|
|
23
|
-
|
|
24
|
-
|
|
58
|
+
`ng add` asks for the language ids (comma-separated; the first is the default) and
|
|
59
|
+
whether to detect the browser language. It only inserts an import and a
|
|
60
|
+
`provideRiviniaI18n({…})` call, is idempotent, and skips with a warning — never an
|
|
61
|
+
error — when it does not recognize the workspace.
|
|
62
|
+
|
|
63
|
+
## Imports
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
import {
|
|
67
|
+
provideRiviniaI18n,
|
|
68
|
+
defineRiviniaI18n,
|
|
69
|
+
injectRiviniaI18n,
|
|
70
|
+
RiviniaI18n,
|
|
71
|
+
RTranslatePipe,
|
|
72
|
+
jsonLoader,
|
|
73
|
+
httpLoader,
|
|
74
|
+
remoteLoader,
|
|
75
|
+
customLoader,
|
|
76
|
+
formatIcu,
|
|
77
|
+
} from '@rivinia/i18n';
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Quick start
|
|
25
81
|
|
|
26
82
|
```ts
|
|
27
83
|
// src/app/i18n.config.ts
|
|
28
|
-
import { defineRiviniaI18n
|
|
84
|
+
import { defineRiviniaI18n } from '@rivinia/i18n';
|
|
29
85
|
|
|
30
|
-
export const
|
|
31
|
-
defaultLanguage: '
|
|
86
|
+
export const i18n = defineRiviniaI18n({
|
|
87
|
+
defaultLanguage: 'ar',
|
|
32
88
|
languages: [
|
|
33
|
-
{ id: 'en', nativeName: 'English', dir: 'ltr', locale: 'en-US' },
|
|
34
89
|
{ id: 'ar', nativeName: 'العربية', dir: 'rtl', locale: 'ar-EG' },
|
|
90
|
+
{ id: 'en', nativeName: 'English', dir: 'ltr', locale: 'en-GB' },
|
|
35
91
|
],
|
|
36
|
-
|
|
37
|
-
switchStrategy: 'preload-first',
|
|
38
|
-
loader: jsonLoader(),
|
|
92
|
+
fallbackLanguage: 'en',
|
|
39
93
|
});
|
|
40
94
|
```
|
|
41
95
|
|
|
42
96
|
```ts
|
|
43
97
|
// src/app/app.config.ts
|
|
44
98
|
import type { ApplicationConfig } from '@angular/core';
|
|
45
|
-
import {
|
|
99
|
+
import { i18n } from './i18n.config';
|
|
46
100
|
|
|
47
101
|
export const appConfig: ApplicationConfig = {
|
|
48
|
-
providers: [
|
|
102
|
+
providers: [i18n.provide()],
|
|
49
103
|
};
|
|
50
104
|
```
|
|
51
105
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
Defaults: `preload: true`, `detectBrowser: false`, local-storage persistence,
|
|
58
|
-
and automatic `<html lang>`/`<html dir>` updates. A stored supported language
|
|
59
|
-
always wins over browser detection. Use `storageStrategy: 'none'` to disable
|
|
60
|
-
persistence; `'session'` and `'cookie'` are also supported.
|
|
61
|
-
|
|
62
|
-
## Dictionaries
|
|
63
|
-
|
|
64
|
-
By default, `jsonLoader()` fetches `i18n/{language}.json` from the site root.
|
|
65
|
-
For Angular apps using the standard `public/` static-file directory, put
|
|
66
|
-
dictionaries at `public/i18n/en.json`, `public/i18n/ar.json`, and so on. Make
|
|
67
|
-
sure your host serves those files at `/i18n/{language}.json`.
|
|
106
|
+
```ts
|
|
107
|
+
// src/app/header.ts
|
|
108
|
+
import { Component } from '@angular/core';
|
|
109
|
+
import { RTranslatePipe } from '@rivinia/i18n';
|
|
110
|
+
import { i18n } from './i18n.config';
|
|
68
111
|
|
|
69
|
-
|
|
70
|
-
|
|
112
|
+
@Component({
|
|
113
|
+
selector: 'app-header',
|
|
114
|
+
imports: [RTranslatePipe],
|
|
115
|
+
template: `
|
|
116
|
+
<h1>{{ title() }}</h1>
|
|
117
|
+
<p>{{ 'booking.seats' | rTranslate: { count: seats } }}</p>
|
|
118
|
+
<button type="button" (click)="use('en')">English</button>
|
|
119
|
+
`,
|
|
120
|
+
})
|
|
121
|
+
export class Header {
|
|
122
|
+
private readonly service = i18n.inject();
|
|
123
|
+
readonly title = this.service.t('app.title');
|
|
124
|
+
readonly seats = 3;
|
|
71
125
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
{
|
|
75
|
-
"booking": {
|
|
76
|
-
"seats": "{count, plural, =0 {No seats} one {# seat} other {# seats}}"
|
|
126
|
+
use(id: 'ar' | 'en'): void {
|
|
127
|
+
this.service.setLanguage(id);
|
|
77
128
|
}
|
|
78
129
|
}
|
|
79
130
|
```
|
|
80
131
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
132
|
+
`defineRiviniaI18n()` keeps the `'ar' | 'en'` union through `provide()` and `inject()`.
|
|
133
|
+
`provideRiviniaI18n(config)` + `injectRiviniaI18n<'ar' | 'en'>()` do the same without the
|
|
134
|
+
wrapper.
|
|
135
|
+
|
|
136
|
+
`provideRiviniaI18n()` registers an app initializer that loads the initial language
|
|
137
|
+
before first paint (SSR waits through `PendingTasks`). `ready()` becomes true when the
|
|
138
|
+
first content is available or initial loading has settled.
|
|
139
|
+
|
|
140
|
+
## Configuration
|
|
141
|
+
|
|
142
|
+
| Option | Type | Default | Meaning |
|
|
143
|
+
| -------------------- | ------------------------------------------- | ---------------------------------- | --------------------------------------------------------------------------- |
|
|
144
|
+
| `languages` | `readonly Language<T>[]` | — | Supported languages (`id`, `nativeName`, `dir`, optional `locale`). |
|
|
145
|
+
| `defaultLanguage` | `T` | — | Must be one of `languages`; validated at construction. |
|
|
146
|
+
| `fallbackLanguage` | `T` | none | Second lookup dictionary; must be one of `languages`. |
|
|
147
|
+
| `loader` | `LoaderDescriptor<T>` | `jsonLoader()` | Dictionary source. |
|
|
148
|
+
| `translations` | `Partial<Record<T, Record<string, unknown>>>` | none | Inline seeds, painted before any network load; a loader response still wins. |
|
|
149
|
+
| `preload` | `boolean` | `true` | Load the initial language during provider setup. |
|
|
150
|
+
| `detectBrowser` | `boolean` | `false` | Match `navigator.languages` on first visit (a stored choice wins). |
|
|
151
|
+
| `storageStrategy` | `'local' \| 'session' \| 'cookie' \| 'none'` | `'local'` | Persistence; `'cookie'` also works on the server through `REQUEST`. |
|
|
152
|
+
| `storageKey` | `string` | `'rivinia.i18n.language'` | Storage key. |
|
|
153
|
+
| `switchStrategy` | `'instant' \| 'preload-first'` | `'instant'` | `'preload-first'` waits for the dictionary; a failure keeps the old language. |
|
|
154
|
+
| `autoApplyDirection` | `boolean` | `true` | Write `<html lang>` and `<html dir>`. |
|
|
155
|
+
| `onLoadError` | `(language, error) => void` | none | Dictionary load failure. Initialization never rejects because of it. |
|
|
156
|
+
| `onMissingKey` | `(event) => void` | none | Unresolved key; suppresses the default warning. |
|
|
157
|
+
| `warnOnMissingKey` | `boolean` | `isDevMode() && !onMissingKey` | `console.warn` once per key. |
|
|
158
|
+
| `viewTransition` | `ViewTransitionConfig` | none | Document view transition on language change. |
|
|
89
159
|
|
|
90
|
-
|
|
91
|
-
|
|
160
|
+
## Dictionaries
|
|
161
|
+
|
|
162
|
+
The default loader fetches `i18n/{language}.json`. For a standard Angular app that
|
|
163
|
+
means `public/i18n/en.json` served as `/i18n/en.json`. An existing
|
|
164
|
+
`assets/i18n/` layout is one option away:
|
|
92
165
|
|
|
93
166
|
```ts
|
|
94
167
|
import { httpLoader, jsonLoader, remoteLoader } from '@rivinia/i18n';
|
|
95
168
|
|
|
96
|
-
jsonLoader(
|
|
97
|
-
|
|
169
|
+
jsonLoader(); // /i18n/{language}.json
|
|
170
|
+
jsonLoader({ path: 'assets/i18n' }); // /assets/i18n/{language}.json
|
|
171
|
+
httpLoader({ endpoint: 'https://api.example.com/i18n' }); // …/{language}
|
|
98
172
|
remoteLoader({
|
|
99
173
|
url: (language) => `https://api.example.com/v2/${language}`,
|
|
100
174
|
headers: { Authorization: 'Bearer …' },
|
|
101
175
|
});
|
|
102
176
|
```
|
|
103
177
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
data source:
|
|
178
|
+
Loader implementations are resolved lazily: `jsonLoader`, `httpLoader` and
|
|
179
|
+
`remoteLoader` are separate chunks until first use. A loader can also be in-memory:
|
|
107
180
|
|
|
108
181
|
```ts
|
|
109
182
|
import { customLoader } from '@rivinia/i18n';
|
|
110
183
|
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
};
|
|
116
|
-
return dictionaries[language];
|
|
117
|
-
});
|
|
184
|
+
const inMemory = customLoader(async (language: 'ar' | 'en') => ({
|
|
185
|
+
ar: { greeting: 'مرحبًا' },
|
|
186
|
+
en: { greeting: 'Hello' },
|
|
187
|
+
})[language]);
|
|
118
188
|
```
|
|
119
189
|
|
|
120
|
-
|
|
190
|
+
A custom `TranslationLoader` receives the platform context:
|
|
121
191
|
|
|
122
|
-
|
|
192
|
+
```ts
|
|
193
|
+
import type { LoaderDescriptor, LoaderContext, TranslationLoader } from '@rivinia/i18n';
|
|
194
|
+
|
|
195
|
+
const filesystem: LoaderDescriptor<'ar' | 'en'> = {
|
|
196
|
+
resolve: async (context?: LoaderContext): Promise<TranslationLoader<'ar' | 'en'>> => ({
|
|
197
|
+
load: async (language) =>
|
|
198
|
+
context?.isServer
|
|
199
|
+
? JSON.parse(await readFile(`i18n/${language}.json`, 'utf8'))
|
|
200
|
+
: (await fetch(new URL(`i18n/${language}.json`, context?.baseUrl)).then((r) => r.json())),
|
|
201
|
+
}),
|
|
202
|
+
};
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
`LoaderContext.baseUrl` is an absolute, directory-like base (`document.baseURI` in the
|
|
206
|
+
browser; `<base href>` resolved against the request on the server). `isServer` means
|
|
207
|
+
"there is a server request context", which is what makes relative URLs fetchable.
|
|
208
|
+
|
|
209
|
+
## Translation API
|
|
210
|
+
|
|
211
|
+
### Signals
|
|
212
|
+
|
|
213
|
+
| Signal | Type | Meaning |
|
|
214
|
+
| ----------------------- | ----------------------------------- | -------------------------------------------------------------- |
|
|
215
|
+
| `currentLanguage` | `Signal<L>` | Active language id. |
|
|
216
|
+
| `currentLanguageObject` | `Signal<Language<L>>` | The active language entry. |
|
|
217
|
+
| `languageChanged` | `Signal<L>` | Alias of `currentLanguage` for effects. |
|
|
218
|
+
| `languages` | `Signal<readonly Language<L>[]>` | Supported languages. |
|
|
219
|
+
| `dir` / `isRtl` | `Signal<Direction>` / `Signal<boolean>` | Document direction. |
|
|
220
|
+
| `locale` | `Signal<string>` | BCP-47 locale driving `Intl` and plural rules. |
|
|
221
|
+
| `loadingState` | `Signal<'idle' \| 'loading' \| 'error'>` | Current dictionary status. |
|
|
222
|
+
| `loadingError` | `Signal<unknown>` | Last load failure. |
|
|
223
|
+
| `isLoading` | `Signal<boolean>` | `loadingState() === 'loading'`. |
|
|
224
|
+
| `ready` | `Signal<boolean>` | Initial content settled — the one to gate skeletons on. |
|
|
225
|
+
| `loadedTranslations` | `Signal<Record<string, unknown>>` | The active dictionary. |
|
|
226
|
+
| `missingKeys` | `Signal<readonly string[]>` | Unresolved keys, insertion order, deduplicated. |
|
|
227
|
+
|
|
228
|
+
### Methods
|
|
229
|
+
|
|
230
|
+
| Method | Result | Notes |
|
|
231
|
+
| --------------------------------------------- | --------------------- | --------------------------------------------------------------------- |
|
|
232
|
+
| `translate(key, params?)` | `string` | Key lookup + ICU rendering. |
|
|
233
|
+
| `translate(key, defaultValue, params?)` | `string` | A supplied `defaultValue` is not reported as missing. |
|
|
234
|
+
| `translate({ en: 'Hi', ar: 'أهلاً' })` | `string` | Inline map: current → fallback → first value. |
|
|
235
|
+
| `t(key, params?)` | `Signal<string>` | Same chain as a `computed`; params may be a function of signals. |
|
|
236
|
+
| `setLanguage(id)` / `setLanguageAsync(id)` | `void` / `Promise<void>` | Follows `switchStrategy`. |
|
|
237
|
+
| `toggle()` / `next()` / `previous()` | `void` | Cycle through `languages`. |
|
|
238
|
+
| `loadTranslations(id, { silent? })` | `Promise<Record<…>>` | Preload without switching. |
|
|
239
|
+
| `reload(language?)` | `Promise<boolean>` | Invalidate + refetch; never rejects. |
|
|
240
|
+
| `formatNumber(value, options?)` | `string` | `Intl.NumberFormat` bound to `locale`. |
|
|
241
|
+
| `formatDate(value, options?)` | `string` | `Intl.DateTimeFormat` bound to `locale`. |
|
|
242
|
+
| `getLanguage(id)` | `Language<L> \| undefined` | Lookup. |
|
|
243
|
+
| `initialize()` | `Promise<void>` | Called by the provider; idempotent. |
|
|
244
|
+
| `clearMissingKeys()` | `void` | Reset the missing-key report. |
|
|
245
|
+
|
|
246
|
+
`RTranslatePipe` (`rTranslate`) delegates to `translate()`. It is impure by necessity —
|
|
247
|
+
the service reads signals on every call — so prefer `t()` or component code for long
|
|
248
|
+
lists.
|
|
249
|
+
|
|
250
|
+
## ICU messages
|
|
251
|
+
|
|
252
|
+
Supported subset (MF1): `{name}` interpolation, `{n, plural, …}` (with `offset:`),
|
|
253
|
+
`{n, selectordinal, …}`, `{x, select, …}`, `#`, `{n, number[, style]}`,
|
|
254
|
+
`{d, date[, style]}`, and nesting.
|
|
255
|
+
|
|
256
|
+
```json
|
|
257
|
+
{
|
|
258
|
+
"items": "{count, plural, =0 {No items} one {# item} other {# items}}",
|
|
259
|
+
"guests": "{n, plural, offset:1 =0 {Nobody} =1 {Only you} one {You and # other} other {You and # others}}",
|
|
260
|
+
"place": "{rank, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}",
|
|
261
|
+
"amount": "{value, number, ::currency/USD}",
|
|
262
|
+
"ratio": "{value, number, percent}",
|
|
263
|
+
"day": "{value, date, long}"
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
- Categories come from `Intl.PluralRules(locale)`, so Arabic gets all six forms
|
|
268
|
+
(`zero`, `one`, `two`, `few`, `many`, `other`) with no dependency.
|
|
269
|
+
- `offset:` follows ICU: `=N` matches the **raw** value, the category is selected with
|
|
270
|
+
`value - offset`, and `#` renders `value - offset` in the locale's digits.
|
|
271
|
+
- `number` styles: `percent`, `integer`, `::currency/XXX`. `date` styles:
|
|
272
|
+
`short`/`medium`/`long`/`full`. Anything else is unsupported.
|
|
273
|
+
- Unsupported or malformed constructs never throw: the raw `{…}` segment is returned
|
|
274
|
+
as-is and parsing continues.
|
|
275
|
+
- `{name}` interpolation is `String(value)`; use `{n, number}` when formatting matters.
|
|
123
276
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
277
|
+
## Missing keys
|
|
278
|
+
|
|
279
|
+
A key is missing only when it is absent from the current dictionary, absent from the
|
|
280
|
+
fallback dictionary, and no `defaultValue` was supplied. It is reported **once per key
|
|
281
|
+
per session**, and only once the current language actually has a dictionary — so a slow
|
|
282
|
+
load never produces false positives.
|
|
128
283
|
|
|
129
284
|
```ts
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
285
|
+
provideRiviniaI18n({
|
|
286
|
+
defaultLanguage: 'ar',
|
|
287
|
+
languages: […],
|
|
288
|
+
fallbackLanguage: 'en',
|
|
289
|
+
onMissingKey: ({ key, language, fallbackLanguage }) =>
|
|
290
|
+
report(key, { language, fallbackLanguage }),
|
|
291
|
+
});
|
|
292
|
+
```
|
|
134
293
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
templateUrl: './header.component.html',
|
|
139
|
-
})
|
|
140
|
-
export class HeaderComponent {
|
|
141
|
-
readonly i18n = i18nConfig.inject();
|
|
142
|
-
readonly seatCount = 3;
|
|
143
|
-
readonly price = 12.5;
|
|
294
|
+
```html
|
|
295
|
+
@if (i18n.missingKeys().length) {
|
|
296
|
+
<p role="status">{{ i18n.missingKeys().length }} untranslated keys</p>
|
|
144
297
|
}
|
|
145
298
|
```
|
|
146
299
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
300
|
+
Without `onMissingKey`, a `console.warn` is logged once per key in dev mode. Set
|
|
301
|
+
`warnOnMissingKey: false` to silence it, or `true` to keep it in production.
|
|
302
|
+
|
|
303
|
+
## Fallback language
|
|
304
|
+
|
|
305
|
+
Lookup order for `translate(key)`:
|
|
306
|
+
|
|
307
|
+
1. current dictionary — rendered with the **current** locale;
|
|
308
|
+
2. fallback dictionary — rendered with the **fallback** locale;
|
|
309
|
+
3. `defaultValue` — current locale;
|
|
310
|
+
4. the key itself.
|
|
311
|
+
|
|
312
|
+
Rule 2's locale is deliberate: an English plural template borrowed by an Arabic UI must
|
|
313
|
+
use English plural rules (2 categories), not Arabic (6).
|
|
314
|
+
|
|
315
|
+
The fallback dictionary loads in parallel with the initial language and **silently** — a
|
|
316
|
+
fallback failure reaches `onLoadError` but never sets `loadingState` to `'error'`, because
|
|
317
|
+
the current dictionary is what the UI needs. It is transferred with the rest of the state,
|
|
318
|
+
so hydration does not fetch it again. With `preload: false`, the fallback works from
|
|
319
|
+
cache/inline dictionaries only.
|
|
320
|
+
|
|
321
|
+
## Reloading a dictionary
|
|
322
|
+
|
|
323
|
+
```ts
|
|
324
|
+
await i18n.reload(); // current + fallback; drops every other cached language
|
|
325
|
+
await i18n.reload('en'); // one language; applied only if it is the current one
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
`reload()` is stale-while-revalidate: the visible dictionary stays on screen until the
|
|
329
|
+
fresh one arrives, so a reload never flashes raw keys. Each language carries a generation
|
|
330
|
+
counter, so a response that was in flight when `reload()` ran is discarded instead of
|
|
331
|
+
overwriting the new one. It never rejects — failures land on `loadingState`,
|
|
332
|
+
`loadingError` and `onLoadError`.
|
|
333
|
+
|
|
334
|
+
A typical deploy hook:
|
|
335
|
+
|
|
336
|
+
```ts
|
|
337
|
+
window.addEventListener('focus', () => void i18n.reload());
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
## `t()` signals
|
|
341
|
+
|
|
342
|
+
```ts
|
|
343
|
+
readonly title = this.i18n.t('app.title');
|
|
344
|
+
readonly items = this.i18n.t('cart.items', () => ({ count: this.count() }));
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
A function `params` is invoked inside the computation, so the signals it reads are
|
|
348
|
+
tracked: changing `count` re-renders the text without touching the language. `t()` is a
|
|
349
|
+
`computed` over the same resolution chain as `translate()`, and missing keys are recorded
|
|
350
|
+
in a microtask because Angular forbids signal writes inside a `computed`.
|
|
351
|
+
|
|
352
|
+
Use it for component fields. For a template expression that runs on every change
|
|
353
|
+
detection, `translate()` or the pipe is cheaper.
|
|
354
|
+
|
|
355
|
+
## Typed keys
|
|
356
|
+
|
|
357
|
+
The registry is empty by default, so `RegisteredI18nKey` resolves to `string` and nothing
|
|
358
|
+
breaks. Generate the declaration from a dictionary to make a typo a compile error:
|
|
359
|
+
|
|
360
|
+
```bash
|
|
361
|
+
npx rivinia-i18n-keys
|
|
362
|
+
# → src/i18n-keys.d.ts
|
|
363
|
+
npx rivinia-i18n-keys --source public/i18n/en.json --out src/i18n-keys.d.ts
|
|
364
|
+
npx rivinia-i18n-keys --check # exit 1 when the file is stale (CI)
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
```ts
|
|
368
|
+
// src/i18n-keys.d.ts — generated, do not edit
|
|
369
|
+
import '@rivinia/i18n';
|
|
370
|
+
|
|
371
|
+
declare module '@rivinia/i18n' {
|
|
372
|
+
interface RiviniaI18nKeyRegistry {
|
|
373
|
+
readonly keys: 'app.title' | 'app.save' | 'booking.seats';
|
|
374
|
+
}
|
|
157
375
|
}
|
|
158
376
|
```
|
|
159
377
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
378
|
+
With that file in the program:
|
|
379
|
+
|
|
380
|
+
```ts
|
|
381
|
+
i18n.translate('app.title'); // ok
|
|
382
|
+
i18n.t('app.titel'); // TS error: not assignable to 'app.title' | …
|
|
383
|
+
i18n.translate(`status.${code}` as RegisteredI18nKey); // dynamic key, explicit
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
The CLI flattens nested objects to dot paths, keeps string leaves only, warns about
|
|
387
|
+
non-string leaves, sorts keys for stable diffs, and escapes quotes. It has no
|
|
388
|
+
dependencies and ships with the package (`rivinia-i18n-keys`).
|
|
389
|
+
|
|
390
|
+
## SSR
|
|
391
|
+
|
|
392
|
+
The default loader works on the server: `REQUEST` plus `<base href>` produce an absolute
|
|
393
|
+
URL, so Node's `fetch` never sees a relative path. The rendered dictionaries go into the
|
|
394
|
+
`TransferState`, and the browser reads them instead of fetching again.
|
|
395
|
+
|
|
396
|
+
- **A custom SSR host must provide `REQUEST`.** `renderApplication` does not add it;
|
|
397
|
+
`@angular/ssr` does. Without it the service cannot build an absolute URL on the server
|
|
398
|
+
and the default loader fails there — the same as any other library that needs the
|
|
399
|
+
request origin.
|
|
400
|
+
- **Provide the serializer in the app injector.** `renderApplication` serializes the
|
|
401
|
+
*platform* `TransferState`, while `bootstrapApplication` gives the app its own root
|
|
402
|
+
injector, so dictionaries loaded by the service land in a different instance. Register
|
|
403
|
+
a `BEFORE_APP_SERIALIZED` callback (or `provideServerRendering()`) in the app providers.
|
|
404
|
+
- **Serve the CSR shell as the template.** With `outputMode: 'server'` the builder
|
|
405
|
+
prerenders `browser/index.html`, so that file already contains a rendered app and its
|
|
406
|
+
own `ng-state` script. Use `browser/index.csr.html` as the render template; otherwise
|
|
407
|
+
the response carries two scripts with the same id and the client reads the empty one.
|
|
408
|
+
- `storageStrategy: 'cookie'` reads the request cookie on the server and writes it in the
|
|
409
|
+
browser, so the first paint matches the user's choice. Local/session storage fall back
|
|
410
|
+
to the default language or browser detection on the server.
|
|
411
|
+
- `provideClientHydration(withEventReplay())` is the standard client side; the clean CSR
|
|
412
|
+
shell carries no event-dispatch contract script, so an event fired before hydration
|
|
413
|
+
completes is not replayed.
|
|
414
|
+
|
|
415
|
+
A complete, runnable host lives in `projects/i18n-e2e` (`node:http` +
|
|
416
|
+
`renderApplication`, no Express), with `e2e/ssr-smoke.mjs` asserting the raw HTML, the
|
|
417
|
+
server log, the transfer payload, the absence of a client refetch, and hydration.
|
|
418
|
+
|
|
419
|
+
## Migration: 0.3.3 → 0.4.0
|
|
420
|
+
|
|
421
|
+
Everything below is additive; no export was removed and no import path changed. Two
|
|
422
|
+
behaviour changes are worth reading:
|
|
423
|
+
|
|
424
|
+
1. **`#` in a plural now uses the locale's digits.** It is formatted with
|
|
425
|
+
`Intl.NumberFormat(locale)` instead of the raw number, so a locale whose default
|
|
426
|
+
numbering system is not Latin (for example `ar-EG`) renders `٣` where it used to
|
|
427
|
+
render `3`. `en` and `ar` are unchanged.
|
|
428
|
+
2. **Missing keys warn in dev mode.** A key that resolves to nothing now logs
|
|
429
|
+
`[rivinia/i18n] missing key "…"` once per session when `isDevMode()` is true. Set
|
|
430
|
+
`warnOnMissingKey: false`, or pass `onMissingKey`, to control it.
|
|
431
|
+
|
|
432
|
+
New in 0.4.0: `fallbackLanguage`, `onMissingKey`, `warnOnMissingKey`, `missingKeys`,
|
|
433
|
+
`clearMissingKeys()`, `reload()`, `t()`, the typed-key registry and the
|
|
434
|
+
`rivinia-i18n-keys` CLI, ICU `selectordinal`/`offset:`/`{n, number}`/`{d, date}`, and
|
|
435
|
+
`Date` in `TranslateParams`. The default loader is unchanged (`i18n/{language}.json`);
|
|
436
|
+
`jsonLoader({ path: 'assets/i18n' })` keeps the old layout. The internal source layout
|
|
437
|
+
moved (models/services/utils/providers/pipes) but nothing under `src/` was ever
|
|
438
|
+
exported.
|
|
218
439
|
|
|
219
440
|
## License
|
|
220
441
|
|