@rivinia/i18n 0.7.2 → 1.0.0-rc.1
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/CHANGELOG.md +130 -1
- package/README.md +121 -1191
- package/fesm2022/rivinia-i18n-select.mjs +391 -0
- package/fesm2022/rivinia-i18n-select.mjs.map +1 -0
- package/fesm2022/rivinia-i18n-ui.mjs +2 -2
- package/fesm2022/rivinia-i18n-ui.mjs.map +1 -1
- package/package.json +10 -2
- package/types/rivinia-i18n-select.d.ts +149 -0
package/README.md
CHANGED
|
@@ -7,115 +7,19 @@
|
|
|
7
7
|
<img src="https://raw.githubusercontent.com/abdelfattahqandil21-oss/Revinia/main/assets/rivinia-abstract-mark-light.svg" alt="Rivinia" width="140" />
|
|
8
8
|
</p>
|
|
9
9
|
|
|
10
|
-
A headless Angular language manager built on signals
|
|
11
|
-
dictionaries, inline translations, RTL/LTR document attributes, lazy loaders,
|
|
12
|
-
|
|
10
|
+
A headless Angular language manager built on signals: key-based JSON
|
|
11
|
+
dictionaries, inline translations, RTL/LTR document attributes, lazy loaders, ICU
|
|
12
|
+
plural/select messages, browser-language detection, and `Intl` number/date
|
|
13
13
|
formatting — with SSR that actually works and no runtime dependency beyond
|
|
14
|
-
Angular.
|
|
14
|
+
Angular. Package version: **1.0.0-rc.1**.
|
|
15
15
|
|
|
16
16
|
Concretely: the text lives in JSON files, components ask for a key, and the whole
|
|
17
17
|
app — text, direction, dates, numbers — follows the language the user picked.
|
|
18
18
|
Arabic is a first-class target, not an afterthought of an English layout.
|
|
19
19
|
|
|
20
|
-
- Package version: **0.7.2**
|
|
21
|
-
- Peer dependency: **`@angular/core` `^22.0.0`** (plus `@angular-devkit/schematics` for `ng add`)
|
|
22
|
-
- Entry points: **`@rivinia/i18n`** (headless core) and **`@rivinia/i18n/ui`**
|
|
23
|
-
(the standalone language toggle)
|
|
24
|
-
- `sideEffects: false`; no runtime import beyond `@angular/core`; loaders are lazy chunks
|
|
25
|
-
- No `HttpClient` peer — the built-in loaders use `fetch`
|
|
26
|
-
|
|
27
|
-
## What you get
|
|
28
|
-
|
|
29
|
-
- **Signal-first state.** `currentLanguage`, `dir`, `loadingState`, `missingKeys` and
|
|
30
|
-
`locale` are readonly signals; changes only via methods.
|
|
31
|
-
- **Zero-config dictionaries.** `jsonLoader()` reads `i18n/{language}.json` — the
|
|
32
|
-
`public/i18n/` layout Angular serves at the site root.
|
|
33
|
-
- **SSR-correct URLs.** On the server the loader builds an absolute URL from
|
|
34
|
-
`REQUEST` + `<base href>`; the browser uses `document.baseURI`.
|
|
35
|
-
- **TransferState hydration.** Dictionaries rendered on the server are not fetched again
|
|
36
|
-
by the client (measured in the e2e app).
|
|
37
|
-
- **Fallback language.** Current dictionary → fallback dictionary → `defaultValue` → key.
|
|
38
|
-
Fallback text keeps the fallback locale's plural rules.
|
|
39
|
-
- **Missing-key reporting.** `onMissingKey`, a `missingKeys` signal, and a dev-mode
|
|
40
|
-
warning — once per key per session, never a false positive during loading.
|
|
41
|
-
- **`reload()`.** Stale-while-revalidate: the visible dictionary stays on screen until
|
|
42
|
-
the fresh one arrives.
|
|
43
|
-
- **ICU subset with the six Arabic plural forms.** `plural`, `selectordinal`, `offset:`,
|
|
44
|
-
`select`, `number`/`date` styles, nesting, and `#`.
|
|
45
|
-
- **`t()` returns a `Signal<string>`**, so a field re-renders on a language switch or on a
|
|
46
|
-
signal read by its params function.
|
|
47
|
-
- **Typed keys.** A generated `.d.ts` turns a typo into a compile error; without it every
|
|
48
|
-
string key stays legal.
|
|
49
|
-
- **Persistence + detection.** local/session/cookie storage, `navigator.languages` match,
|
|
50
|
-
`<html lang>` and `<html dir>` kept in sync.
|
|
51
|
-
|
|
52
|
-
## Contents
|
|
53
|
-
|
|
54
|
-
Three levels. Stop at the one that answers your question.
|
|
55
|
-
|
|
56
|
-
| Tier | What it covers | Start at |
|
|
57
|
-
| ---------------------- | ------------------------------------------------------------------- | ------------------------------------- |
|
|
58
|
-
| **Start here** (5 min) | install, generate the language list, render a first translation | [Quick start](#quick-start) |
|
|
59
|
-
| **Everyday use** | translating, plurals, switching, dictionaries, the toggle, SSR | [Translating text](#translating-text) |
|
|
60
|
-
| **Reference** | every option, loader, ICU rule, UI input, export tier and migration | [Configuration](#configuration) |
|
|
61
|
-
|
|
62
|
-
## Start here
|
|
63
|
-
|
|
64
|
-
These three sections are everything needed to run an app. The rest can wait.
|
|
65
|
-
|
|
66
|
-
### Install
|
|
67
|
-
|
|
68
|
-
```bash
|
|
69
|
-
npm install @rivinia/i18n
|
|
70
|
-
pnpm add @rivinia/i18n
|
|
71
|
-
yarn add @rivinia/i18n
|
|
72
|
-
bun add @rivinia/i18n
|
|
73
|
-
```
|
|
74
|
-
|
|
75
|
-
With the CLI schematic (wires a starter provider into `app.config.ts`):
|
|
76
|
-
|
|
77
|
-
```bash
|
|
78
|
-
ng add @rivinia/i18n
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
`ng add` asks for the language ids (comma-separated; the first is the default) and
|
|
82
|
-
whether to detect the browser language. It only inserts an import and a
|
|
83
|
-
`provideRiviniaI18n({…})` call, is idempotent, and skips with a warning — never an
|
|
84
|
-
error — when it does not recognize the workspace.
|
|
85
|
-
|
|
86
|
-
### Quick start
|
|
87
|
-
|
|
88
|
-
#### 1. Generate the language list
|
|
89
|
-
|
|
90
|
-
```bash
|
|
91
|
-
npx rivinia-i18n-keys init
|
|
92
|
-
```
|
|
93
|
-
|
|
94
|
-
It asks for each language (id, native name, direction) and the default one, then
|
|
95
|
-
writes `src/app/i18n/languages.ts` plus one empty dictionary per language under
|
|
96
|
-
`public/i18n/`. Without a terminal:
|
|
97
|
-
|
|
98
|
-
```bash
|
|
99
|
-
npx rivinia-i18n-keys init --languages ar:العربية:rtl,en:English:ltr --default en
|
|
100
|
-
```
|
|
101
|
-
|
|
102
|
-
#### 2. Register it once, at bootstrap
|
|
103
|
-
|
|
104
|
-
```ts
|
|
105
|
-
// src/app/app.config.ts
|
|
106
|
-
import type { ApplicationConfig } from '@angular/core';
|
|
107
|
-
import { i18n } from './i18n/languages';
|
|
108
|
-
|
|
109
|
-
export const appConfig: ApplicationConfig = {
|
|
110
|
-
providers: [i18n.provide()],
|
|
111
|
-
};
|
|
112
|
-
```
|
|
113
|
-
|
|
114
|
-
#### 3. Translate
|
|
115
|
-
|
|
116
20
|
```ts
|
|
117
21
|
// src/app/header.ts
|
|
118
|
-
import { Component } from '@angular/core';
|
|
22
|
+
import { Component, signal } from '@angular/core';
|
|
119
23
|
import { RvTranslatePipe } from '@rivinia/i18n';
|
|
120
24
|
import { injectI18n } from './i18n/languages';
|
|
121
25
|
|
|
@@ -124,1113 +28,139 @@ import { injectI18n } from './i18n/languages';
|
|
|
124
28
|
imports: [RvTranslatePipe],
|
|
125
29
|
template: `
|
|
126
30
|
<h1>{{ title() }}</h1>
|
|
127
|
-
<p>{{ 'booking.seats' | rvTranslate }}</p>
|
|
31
|
+
<p>{{ 'booking.seats' | rvTranslate: { count: seats() } }}</p>
|
|
128
32
|
<button type="button" (click)="i18n.setLanguage('en')">English</button>
|
|
129
33
|
`,
|
|
130
34
|
})
|
|
131
35
|
export class Header {
|
|
132
36
|
readonly i18n = injectI18n();
|
|
133
37
|
readonly title = this.i18n.t('app.title');
|
|
38
|
+
readonly seats = signal(3);
|
|
134
39
|
}
|
|
135
40
|
```
|
|
136
41
|
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
fallbackLanguage: 'en',
|
|
168
|
-
});
|
|
169
|
-
```
|
|
170
|
-
|
|
171
|
-
```ts
|
|
172
|
-
// src/app/app.config.ts
|
|
173
|
-
import type { ApplicationConfig } from '@angular/core';
|
|
174
|
-
import { i18n } from './i18n.config';
|
|
175
|
-
|
|
176
|
-
export const appConfig: ApplicationConfig = {
|
|
177
|
-
providers: [i18n.provide()],
|
|
178
|
-
};
|
|
179
|
-
```
|
|
180
|
-
|
|
181
|
-
```ts
|
|
182
|
-
// src/app/header.ts
|
|
183
|
-
import { Component } from '@angular/core';
|
|
184
|
-
import { RvTranslatePipe } from '@rivinia/i18n';
|
|
185
|
-
import { i18n } from './i18n.config';
|
|
186
|
-
|
|
187
|
-
@Component({
|
|
188
|
-
selector: 'app-header',
|
|
189
|
-
imports: [RvTranslatePipe],
|
|
190
|
-
template: `
|
|
191
|
-
<h1>{{ title() }}</h1>
|
|
192
|
-
<p>{{ 'booking.seats' | rvTranslate: { count: seats } }}</p>
|
|
193
|
-
<button type="button" (click)="use('en')">English</button>
|
|
194
|
-
`,
|
|
195
|
-
})
|
|
196
|
-
export class Header {
|
|
197
|
-
private readonly service = i18n.inject();
|
|
198
|
-
readonly title = this.service.t('app.title');
|
|
199
|
-
readonly seats = 3;
|
|
200
|
-
|
|
201
|
-
use(id: 'ar' | 'en'): void {
|
|
202
|
-
this.service.setLanguage(id);
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
```
|
|
206
|
-
|
|
207
|
-
`defineRiviniaI18n()` keeps the `'ar' | 'en'` union through `provide()` and `inject()`.
|
|
208
|
-
`provideRiviniaI18n(config)` + `injectRiviniaI18n<'ar' | 'en'>()` do the same without the
|
|
209
|
-
wrapper.
|
|
210
|
-
|
|
211
|
-
`provideRiviniaI18n()` registers an app initializer that loads the initial language
|
|
212
|
-
before first paint (SSR waits through `PendingTasks`). `ready()` becomes true when the
|
|
213
|
-
first content is available or initial loading has settled.
|
|
214
|
-
|
|
215
|
-
### What you just configured
|
|
216
|
-
|
|
217
|
-
Each entry of `languages` answers four questions:
|
|
218
|
-
|
|
219
|
-
| Field | Answers | Required |
|
|
220
|
-
| ------------ | -------------------------------------------------------------------------------------------------------------------- | -------- |
|
|
221
|
-
| `id` | The key everything else uses: JSON filename, stored preference, `currentLanguage()`, `setLanguage('…')`. | yes |
|
|
222
|
-
| `nativeName` | How the language calls itself in a switcher (`العربية`, not "Arabic"). Falls back to `Intl.DisplayNames`, then `id`. | no |
|
|
223
|
-
| `dir` | The document direction while this language is active. Explicit, not guessed — `he` and `ur` exist. | yes |
|
|
224
|
-
| `locale` | BCP-47 locale for `Intl` and plural rules. Defaults to `id`. | no |
|
|
225
|
-
|
|
226
|
-
`locale` is the one that surprises people: a bare `ar` formats Latin digits (`3`),
|
|
227
|
-
while `ar-EG` formats Arabic-Indic ones (`٣`). When the dictionary is read by Arabic
|
|
228
|
-
readers, pass `ar-EG`.
|
|
229
|
-
|
|
230
|
-
The generated module keeps the union literal, so the type of `id` is `'ar' | 'en'` and
|
|
231
|
-
`setLanguage('fr')` does not compile. Registering the provider also installs an app
|
|
232
|
-
initializer that loads the first dictionary before the first paint — `ready()` turns
|
|
233
|
-
true when that initial load has settled, which is the signal to gate skeletons on.
|
|
234
|
-
|
|
235
|
-
## Everyday use
|
|
236
|
-
|
|
237
|
-
The patterns a real app needs, with the smallest correct example for each.
|
|
238
|
-
|
|
239
|
-
### Translating text
|
|
240
|
-
|
|
241
|
-
Keys are dot paths into the JSON file: `{"booking": {"seats": "Seats"}}` becomes
|
|
242
|
-
`booking.seats`. Three ways to read one:
|
|
243
|
-
|
|
244
|
-
```html
|
|
245
|
-
<!-- template: the pipe -->
|
|
246
|
-
<p>{{ 'booking.seats' | rvTranslate: { count: seats } }}</p>
|
|
247
|
-
```
|
|
248
|
-
|
|
249
|
-
```ts
|
|
250
|
-
// component field: a signal that re-renders on a language switch
|
|
251
|
-
readonly title = this.i18n.t('app.title');
|
|
252
|
-
// params may be a function of signals — the text follows both language and count
|
|
253
|
-
readonly seats = this.i18n.t('booking.seats', () => ({ count: this.count() }));
|
|
254
|
-
```
|
|
255
|
-
|
|
256
|
-
```ts
|
|
257
|
-
// plain TypeScript
|
|
258
|
-
this.i18n.translate('app.save');
|
|
259
|
-
this.i18n.translate('app.title', 'Untitled'); // defaultValue: never reported as missing
|
|
260
|
-
this.i18n.translate({ en: 'Hello', ar: 'أهلاً' }); // inline map
|
|
261
|
-
```
|
|
262
|
-
|
|
263
|
-
`t()` is a `computed`, so it is the right tool for component fields. The pipe is impure
|
|
264
|
-
by necessity and re-runs on every change-detection pass: fine for a page, wasteful for
|
|
265
|
-
a thousand rows. A key that resolves nowhere renders as the key itself and is reported
|
|
266
|
-
— see [Missing keys](#missing-keys).
|
|
267
|
-
|
|
268
|
-
### Plurals that survive translation
|
|
269
|
-
|
|
270
|
-
"1 item / 2 items" looks like a single `if`:
|
|
271
|
-
|
|
272
|
-
```ts
|
|
273
|
-
const label = count === 1 ? `${count} item` : `${count} items`;
|
|
274
|
-
```
|
|
275
|
-
|
|
276
|
-
That line is already wrong in Arabic. English has two plural forms; Arabic has six, and
|
|
277
|
-
which one applies is decided by the number in a way English never trained you for:
|
|
278
|
-
|
|
279
|
-
| count | English category | Arabic category | Arabic text |
|
|
280
|
-
| ----- | ---------------- | --------------- | -------------- |
|
|
281
|
-
| 0 | `other` | `zero` | سلتك فارغة |
|
|
282
|
-
| 1 | `one` | `one` | لديك عنصر واحد |
|
|
283
|
-
| 2 | `other` | `two` | لديك عنصران |
|
|
284
|
-
| 3 | `other` | `few` | لديك 3 عناصر |
|
|
285
|
-
| 11 | `other` | `many` | لديك 11 عنصرًا |
|
|
286
|
-
| 100 | `other` | `other` | لديك 100 عنصر |
|
|
287
|
-
|
|
288
|
-
The words around the number also change — gender, case, the shape of the noun — so
|
|
289
|
-
gluing `count + ' items'` together cannot produce a correct Arabic sentence.
|
|
290
|
-
|
|
291
|
-
ICU MessageFormat puts the decision inside the message:
|
|
292
|
-
|
|
293
|
-
```text
|
|
294
|
-
{count, plural,
|
|
295
|
-
=0 {Your cart is empty}
|
|
296
|
-
one {You have one item in your cart}
|
|
297
|
-
other {You have # items in your cart}
|
|
298
|
-
}
|
|
299
|
-
```
|
|
300
|
-
|
|
301
|
-
- `count` is the parameter you pass: `translate('cart.items', { count: 3 })`.
|
|
302
|
-
- `plural` picks a branch from that number.
|
|
303
|
-
- `=0` matches the value **exactly**, in every language.
|
|
304
|
-
- `one` and `other` are plural **categories**, selected by `Intl.PluralRules(locale)`.
|
|
305
|
-
English only ever selects `one` and `other`.
|
|
306
|
-
- `#` is the number, formatted for the locale — `٣` under `ar-EG`, `3` under `ar`.
|
|
307
|
-
|
|
308
|
-
The same message in Arabic names the categories Arabic actually has:
|
|
309
|
-
|
|
310
|
-
```text
|
|
311
|
-
{count, plural,
|
|
312
|
-
=0 {سلتك فارغة}
|
|
313
|
-
one {لديك عنصر واحد}
|
|
314
|
-
two {لديك عنصران}
|
|
315
|
-
few {لديك # عناصر}
|
|
316
|
-
many {لديك # عنصرًا}
|
|
317
|
-
other {لديك # عنصر}
|
|
318
|
-
}
|
|
319
|
-
```
|
|
320
|
-
|
|
321
|
-
`zero`, `one`, `two`, `few`, `many` and `other` are the six CLDR categories for Arabic.
|
|
322
|
-
They are not `if` branches you can reorder: the category is computed from the number and
|
|
323
|
-
the locale, so one message yields six Arabic forms and two English ones with no code
|
|
324
|
-
change. In Arabic, 3–10 select `few`, 11–99 select `many`, and 100 selects `other`.
|
|
325
|
-
|
|
326
|
-
Note the difference between `=0` and `zero`. `=0` is an exact-value rule that works
|
|
327
|
-
everywhere; `zero` is a category only some languages select — an English message with a
|
|
328
|
-
`zero {…}` branch never shows it, because English at 0 resolves to `other`. For an empty
|
|
329
|
-
state, use `=0`.
|
|
330
|
-
|
|
331
|
-
`select`, `selectordinal`, `offset:` and the number/date styles are in the
|
|
332
|
-
[ICU reference](#icu-messages).
|
|
333
|
-
|
|
334
|
-
### Switching the language
|
|
335
|
-
|
|
336
|
-
```ts
|
|
337
|
-
this.i18n.setLanguage('ar'); // flips now; the dictionary follows (default strategy)
|
|
338
|
-
await this.i18n.setLanguageAsync('ar'); // resolves once the dictionary is in place
|
|
339
|
-
this.i18n.toggle(); // flips the first two configured languages
|
|
340
|
-
```
|
|
341
|
-
|
|
342
|
-
`setLanguage()` is synchronous and obeys `switchStrategy`; `setLanguageAsync()` always
|
|
343
|
-
waits for the dictionary, which is why the toggle uses it — a failed load leaves the
|
|
344
|
-
previous language in place instead of an empty page.
|
|
345
|
-
|
|
346
|
-
Everything visual is a signal, so nothing needs wiring:
|
|
347
|
-
|
|
348
|
-
```ts
|
|
349
|
-
readonly language = this.i18n.currentLanguage; // Signal<'ar' | 'en'>
|
|
350
|
-
readonly direction = this.i18n.dir; // Signal<'rtl' | 'ltr'> — also written on <html dir>
|
|
351
|
-
readonly locale = this.i18n.locale; // Signal<string>
|
|
352
|
-
readonly ready = this.i18n.ready; // gate skeletons on this
|
|
353
|
-
```
|
|
354
|
-
|
|
355
|
-
Numbers and dates follow the same locale:
|
|
356
|
-
|
|
357
|
-
```ts
|
|
358
|
-
this.i18n.formatNumber(1234.5); // ar-EG → ١٬٢٣٤٫٥
|
|
359
|
-
this.i18n.formatDate(Date.now(), { dateStyle: 'long' });
|
|
360
|
-
```
|
|
361
|
-
|
|
362
|
-
The choice survives a reload in `localStorage` under `rivinia.i18n.language`, and is only
|
|
363
|
-
written after the user actually switches (`persist`). On a first visit,
|
|
364
|
-
`detectBrowser: true` matches `navigator.languages` (`ar-EG` → `ar`); a stored choice
|
|
365
|
-
always wins. All of it is configurable — [Configuration](#configuration).
|
|
366
|
-
|
|
367
|
-
### Where translations live
|
|
368
|
-
|
|
369
|
-
The default loader fetches `i18n/{language}.json`. For a standard Angular app that
|
|
370
|
-
means `public/i18n/en.json` served as `/i18n/en.json`. An existing
|
|
371
|
-
`assets/i18n/` layout is one option away:
|
|
372
|
-
|
|
373
|
-
```ts
|
|
374
|
-
import { httpLoader, jsonLoader, remoteLoader } from '@rivinia/i18n';
|
|
375
|
-
|
|
376
|
-
jsonLoader(); // /i18n/{language}.json
|
|
377
|
-
jsonLoader({ path: 'assets/i18n' }); // /assets/i18n/{language}.json
|
|
378
|
-
httpLoader({ endpoint: 'https://api.example.com/i18n' }); // …/{language}
|
|
379
|
-
remoteLoader({
|
|
380
|
-
url: (language) => `https://api.example.com/v2/${language}`,
|
|
381
|
-
headers: { Authorization: 'Bearer …' },
|
|
382
|
-
});
|
|
383
|
-
```
|
|
384
|
-
|
|
385
|
-
Loader implementations are resolved lazily: `httpLoader` and `remoteLoader` are
|
|
386
|
-
separate chunks until first use. The default `jsonLoader` is part of the main
|
|
387
|
-
bundle — it runs in the app initializer, where a lazy chunk would put two extra
|
|
388
|
-
script requests between the main bundle and the dictionary fetch. A loader can
|
|
389
|
-
also be in-memory:
|
|
390
|
-
|
|
391
|
-
```ts
|
|
392
|
-
import { customLoader } from '@rivinia/i18n';
|
|
393
|
-
|
|
394
|
-
const inMemory = customLoader(
|
|
395
|
-
async (language: 'ar' | 'en') =>
|
|
396
|
-
({
|
|
397
|
-
ar: { greeting: 'مرحبًا' },
|
|
398
|
-
en: { greeting: 'Hello' },
|
|
399
|
-
})[language],
|
|
400
|
-
);
|
|
401
|
-
```
|
|
402
|
-
|
|
403
|
-
A custom `TranslationLoader` receives the platform context:
|
|
404
|
-
|
|
405
|
-
```ts
|
|
406
|
-
import type { LoaderDescriptor, LoaderContext, TranslationLoader } from '@rivinia/i18n';
|
|
407
|
-
|
|
408
|
-
const filesystem: LoaderDescriptor<'ar' | 'en'> = {
|
|
409
|
-
resolve: async (context?: LoaderContext): Promise<TranslationLoader<'ar' | 'en'>> => ({
|
|
410
|
-
load: async (language) =>
|
|
411
|
-
context?.isServer
|
|
412
|
-
? JSON.parse(await readFile(`i18n/${language}.json`, 'utf8'))
|
|
413
|
-
: await fetch(new URL(`i18n/${language}.json`, context?.baseUrl)).then((r) => r.json()),
|
|
414
|
-
}),
|
|
415
|
-
};
|
|
416
|
-
```
|
|
417
|
-
|
|
418
|
-
`LoaderContext.baseUrl` is an absolute, directory-like base (`document.baseURI` in the
|
|
419
|
-
browser; `<base href>` resolved against the request on the server). `isServer` means
|
|
420
|
-
"there is a server request context", which is what makes relative URLs fetchable.
|
|
421
|
-
|
|
422
|
-
### Generating the language module
|
|
423
|
-
|
|
424
|
-
Writing the language list by hand is the one boilerplate this package still asked for.
|
|
425
|
-
`init` collects it once and writes the module plus one empty dictionary per language:
|
|
426
|
-
|
|
427
|
-
```bash
|
|
428
|
-
npx rivinia-i18n-keys init
|
|
429
|
-
# [rivinia/i18n] Language id (ar, en, ar-EG …): ar
|
|
430
|
-
# Native name [العربية]:
|
|
431
|
-
# Direction (ltr/rtl) [rtl]:
|
|
432
|
-
# Another language? (Y/n): y
|
|
433
|
-
# [rivinia/i18n] Language id (ar, en, ar-EG …): en
|
|
434
|
-
# Native name [English]:
|
|
435
|
-
# Direction (ltr/rtl) [ltr]:
|
|
436
|
-
# Another language? (y/N): n
|
|
437
|
-
# [rivinia/i18n] Default language — (1) ar (2) en [1]:
|
|
438
|
-
```
|
|
439
|
-
|
|
440
|
-
That writes `src/app/i18n/languages.ts`:
|
|
441
|
-
|
|
442
|
-
```ts
|
|
443
|
-
// Generated by `npx rivinia-i18n-keys init`. Re-run the command to regenerate.
|
|
444
|
-
import { defineRiviniaI18n } from '@rivinia/i18n';
|
|
445
|
-
|
|
446
|
-
export const i18n = defineRiviniaI18n({
|
|
447
|
-
defaultLanguage: 'ar',
|
|
448
|
-
languages: [
|
|
449
|
-
{ id: 'ar', nativeName: 'العربية', dir: 'rtl' },
|
|
450
|
-
{ id: 'en', nativeName: 'English', dir: 'ltr' },
|
|
451
|
-
],
|
|
452
|
-
});
|
|
453
|
-
|
|
454
|
-
/** The typed language manager — call inside an injection context. */
|
|
455
|
-
export const injectI18n = i18n.inject;
|
|
456
|
-
```
|
|
457
|
-
|
|
458
|
-
and `public/i18n/ar.json` / `public/i18n/en.json` (each `{}`; an existing dictionary is
|
|
459
|
-
kept untouched). The module keeps the `'ar' | 'en'` union, so the components stay short:
|
|
460
|
-
|
|
461
|
-
```ts
|
|
462
|
-
// src/app/app.config.ts
|
|
463
|
-
import type { ApplicationConfig } from '@angular/core';
|
|
464
|
-
import { i18n } from './i18n/languages';
|
|
465
|
-
|
|
466
|
-
export const appConfig: ApplicationConfig = {
|
|
467
|
-
providers: [i18n.provide()],
|
|
468
|
-
};
|
|
469
|
-
```
|
|
470
|
-
|
|
471
|
-
```ts
|
|
472
|
-
// any component — field initializer or constructor body
|
|
473
|
-
import { injectI18n } from './i18n/languages';
|
|
474
|
-
|
|
475
|
-
private readonly i18n = injectI18n();
|
|
476
|
-
```
|
|
477
|
-
|
|
478
|
-
`i18n.config` is the same object, so `i18n.config.languages` stays `'ar' | 'en'` wherever
|
|
479
|
-
it is imported.
|
|
480
|
-
|
|
481
|
-
`dir` is explicit rather than derived at runtime, so an Urdu or Hebrew dictionary cannot
|
|
482
|
-
silently render left-to-right. Ids, directions and duplicates are validated before
|
|
483
|
-
anything is written; `--languages ar:العربية:rtl,en:English:ltr` skips the questions for
|
|
484
|
-
CI, `--dry-run` prints the files, and a `languages.ts` that was not written by this
|
|
485
|
-
command is only replaced with `--force`.
|
|
486
|
-
|
|
487
|
-
### Typed keys
|
|
488
|
-
|
|
489
|
-
Every key is a plain `string` until you generate the declaration. One command turns the
|
|
490
|
-
dictionary into a union type, so a typo fails the build instead of reaching the screen:
|
|
42
|
+
`title()` and the pipe update on the click and the page's direction flips with the
|
|
43
|
+
language — nothing else is wired by hand. The same app under
|
|
44
|
+
[`projects/i18n-e2e/src/app`](https://github.com/abdelfattahqandil21-oss/Revinia/tree/main/projects/i18n-e2e/src/app)
|
|
45
|
+
is what the Playwright suites drive: `npx ng build i18n-e2e` runs it locally.
|
|
46
|
+
|
|
47
|
+
## Why `@rivinia/i18n`
|
|
48
|
+
|
|
49
|
+
- **Signal-first state.** `currentLanguage`, `dir`, `locale`, `loadingState` and
|
|
50
|
+
`missingKeys` are readonly signals; writes go through methods only.
|
|
51
|
+
- **Plurals that survive translation.** The ICU subset covers `plural`, `select`,
|
|
52
|
+
`selectordinal`, `offset:`, `#` and the number/date styles — with all six Arabic
|
|
53
|
+
categories from `Intl.PluralRules`, so one message yields six Arabic forms and
|
|
54
|
+
two English ones with no code change.
|
|
55
|
+
- **Typed keys are opt-in.** Every key is a plain `string` until you generate the
|
|
56
|
+
declaration; then a typo fails the build instead of reaching the screen.
|
|
57
|
+
- **SSR-correct URLs and hydration.** The default loader builds an absolute URL
|
|
58
|
+
from `REQUEST` + `<base href>`, and dictionaries rendered on the server travel in
|
|
59
|
+
`TransferState` so the client never refetches them.
|
|
60
|
+
- **Failure reporting you can see.** `fallbackLanguage`, `onMissingKey`,
|
|
61
|
+
`onMissingParam` and `onLoadError`, each deduplicated once per key (or language)
|
|
62
|
+
per session — and a load failure never rejects, it lands on `loadingState`.
|
|
63
|
+
- **Persistence and detection without wiring.** local/session/cookie storage, a
|
|
64
|
+
`navigator.languages` match on first visit, `<html lang>` and `<html dir>` kept
|
|
65
|
+
in sync.
|
|
66
|
+
- **Two ready-made controls, when you want them.** `@rivinia/i18n/ui` ships a
|
|
67
|
+
two-language toggle; `@rivinia/i18n/select` composes `@rivinia/select` into a
|
|
68
|
+
picker for three or more. Both entry points are optional, and the picker's peer
|
|
69
|
+
is optional too.
|
|
70
|
+
|
|
71
|
+
## Install
|
|
491
72
|
|
|
492
73
|
```bash
|
|
493
|
-
|
|
494
|
-
```
|
|
495
|
-
|
|
496
|
-
Re-run it when keys change, or let CI run `--check`. The flags, the flattening rules and
|
|
497
|
-
`--parity` are in the [typed-keys reference](#typed-keys-reference).
|
|
498
|
-
|
|
499
|
-
### The language toggle
|
|
500
|
-
|
|
501
|
-
The second entry point ships a two-language switch:
|
|
502
|
-
|
|
503
|
-
```ts
|
|
504
|
-
import { RiviniaLanguageToggle } from '@rivinia/i18n/ui';
|
|
505
|
-
// <rv-language-toggle [manager]="i18n" label="Switch language" />
|
|
74
|
+
npm install @rivinia/i18n # or pnpm add / yarn add / bun add
|
|
506
75
|
```
|
|
507
76
|
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
`
|
|
511
|
-
templates, presentational mode, styling hooks and the accessibility contract are in the
|
|
512
|
-
[toggle reference](#toggle-reference).
|
|
513
|
-
|
|
514
|
-
### Server-side rendering
|
|
515
|
-
|
|
516
|
-
The default loader works on the server: `REQUEST` plus `<base href>` produce an absolute
|
|
517
|
-
URL, and the rendered dictionaries travel in `TransferState`, so the client does not
|
|
518
|
-
fetch them twice. A custom host has to provide `REQUEST`, serialize the app-level
|
|
519
|
-
`TransferState` and use the CSR shell as the template — all three, with the reasons, are
|
|
520
|
-
in the [SSR reference](#ssr-reference).
|
|
521
|
-
|
|
522
|
-
## Reference
|
|
77
|
+
Optional, for `ng add`: `@angular-devkit/schematics` (declared as an optional peer,
|
|
78
|
+
so an app that never runs `ng add` does not install it). Optional, for the picker:
|
|
79
|
+
`npm install @rivinia/select`.
|
|
523
80
|
|
|
524
|
-
|
|
81
|
+
- Requires **Angular `^22.0.0`** (`@angular/core` is a peer, not a dependency).
|
|
82
|
+
- Node: **same as Angular 22** (`^22.22.3 || ^24.15.0 || >=26.0.0`).
|
|
83
|
+
- `sideEffects: false`; no runtime import beyond `@angular/core`; the network
|
|
84
|
+
loaders are lazy chunks. No `HttpClient` peer — the built-in loaders use `fetch`.
|
|
525
85
|
|
|
526
|
-
|
|
86
|
+
## Quick start
|
|
527
87
|
|
|
528
|
-
|
|
88
|
+
1. **Generate the language list.** `npx rivinia-i18n-keys init` asks for each
|
|
89
|
+
language (id, native name, direction) and the default one, then writes
|
|
90
|
+
`src/app/i18n/languages.ts` plus one empty dictionary per language under
|
|
91
|
+
`public/i18n/`. `--languages ar:العربية:rtl,en:English:ltr --default en` skips
|
|
92
|
+
the questions for CI.
|
|
93
|
+
2. **Register it once, at bootstrap.**
|
|
529
94
|
|
|
530
|
-
|
|
95
|
+
```ts
|
|
96
|
+
// src/app/app.config.ts
|
|
97
|
+
import type { ApplicationConfig } from '@angular/core';
|
|
98
|
+
import { i18n } from './i18n/languages';
|
|
531
99
|
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
default stays in the main bundle because it runs before first paint.
|
|
536
|
-
- **`switchStrategy`** — `'instant'` (default) flips the id immediately and the
|
|
537
|
-
dictionary follows; `'preload-first'` waits for the dictionary and keeps the old
|
|
538
|
-
language when loading fails. Choose `'preload-first'` when a flash of raw keys is worse
|
|
539
|
-
than a slower switch.
|
|
540
|
-
- **`preload`** — `true` (default) loads the initial language during provider setup, and
|
|
541
|
-
SSR waits for it. `false` for apps that ship inline dictionaries or load by hand with
|
|
542
|
-
`loadTranslations()`.
|
|
543
|
-
- **`fallbackLanguage`** — the second dictionary for keys missing from the current one.
|
|
544
|
-
It loads silently and its text is rendered with its own locale.
|
|
545
|
-
- **`detectBrowser`** — `true` matches `navigator.languages` on the first visit; a stored
|
|
546
|
-
preference always wins.
|
|
547
|
-
- **`persist` / `storageStrategy`** — whether and where an explicit switch is remembered.
|
|
548
|
-
`'cookie'` also works on the server, so the first paint matches the user's choice.
|
|
549
|
-
- **`translations`** — inline seeds painted before any network load; a loader response
|
|
550
|
-
still wins.
|
|
551
|
-
|
|
552
|
-
| Option | Type | Default | Meaning |
|
|
553
|
-
| -------------------- | --------------------------------------------- | -------------------------------- | ----------------------------------------------------------------------------- |
|
|
554
|
-
| `languages` | `readonly Language<T>[]` | — | Supported languages (`id`, `nativeName`, `dir`, optional `locale`). |
|
|
555
|
-
| `defaultLanguage` | `T` | first of `languages` | Initial language on a first visit; must be a non-empty configured id. |
|
|
556
|
-
| `fallbackLanguage` | `T` | none | Second lookup dictionary; must be one of `languages`. |
|
|
557
|
-
| `loader` | `LoaderDescriptor<T>` | `jsonLoader()` | Dictionary source. |
|
|
558
|
-
| `translations` | `Partial<Record<T, Record<string, unknown>>>` | none | Inline seeds, painted before any network load; a loader response still wins. |
|
|
559
|
-
| `preload` | `boolean` | `true` | Load the initial language during provider setup. |
|
|
560
|
-
| `detectBrowser` | `boolean` | `false` | Match `navigator.languages` on first visit (a stored choice wins). |
|
|
561
|
-
| `storageStrategy` | `'local' \| 'session' \| 'cookie' \| 'none'` | `'local'` | Persistence; `'cookie'` also works on the server through `REQUEST`. |
|
|
562
|
-
| `storageKey` | `string` | `'rivinia.i18n.language'` | Storage key. |
|
|
563
|
-
| `switchStrategy` | `'instant' \| 'preload-first'` | `'instant'` | `'preload-first'` waits for the dictionary; a failure keeps the old language. |
|
|
564
|
-
| `autoApplyDirection` | `boolean` | `true` | Write `<html lang>` and `<html dir>`. |
|
|
565
|
-
| `onLoadError` | `(language, error) => void` | none | Dictionary load failure. Initialization never rejects because of it. |
|
|
566
|
-
| `warnOnLoadError` | `boolean` | `isDevMode() && !onLoadError` | `console.error` once per language when a dictionary fails to load. |
|
|
567
|
-
| `onMissingKey` | `(event) => void` | none | Unresolved key; suppresses the default warning. |
|
|
568
|
-
| `warnOnMissingKey` | `boolean` | `isDevMode() && !onMissingKey` | `console.warn` once per key. |
|
|
569
|
-
| `onMissingParam` | `(event) => void` | none | Missing message argument; suppresses the default warning. |
|
|
570
|
-
| `warnOnMissingParam` | `boolean` | `isDevMode() && !onMissingParam` | `console.warn` once per (key, param). |
|
|
571
|
-
| `persist` | `boolean` | `true` | Persist the language after an explicit switch. First load writes nothing. |
|
|
572
|
-
| `viewTransition` | `ViewTransitionConfig` | none | Document view transition on language change. |
|
|
573
|
-
|
|
574
|
-
The config is validated once at construction: `languages` must be a non-empty array with a
|
|
575
|
-
non-empty, **unique** `id` per entry, and `defaultLanguage` / `fallbackLanguage` (when
|
|
576
|
-
provided) must name one of those ids. Anything else throws a `[rivinia/i18n] …` error at
|
|
577
|
-
bootstrap instead of degrading into an undefined current language.
|
|
578
|
-
|
|
579
|
-
A repeated id written inline (`languages: [AR, EN, AR]`) is also a **compile error**:
|
|
580
|
-
`provideRiviniaI18n` and `defineRiviniaI18n` require the property `duplicateLanguageId`,
|
|
581
|
-
which only the type checker sees. The check reads the array literal, so it does not fire
|
|
582
|
-
when the union is supplied explicitly (`provideRiviniaI18n<'ar' | 'en'>(…)`) or the list is
|
|
583
|
-
hoisted into a variable — both forms still throw the runtime error above.
|
|
584
|
-
|
|
585
|
-
### Translation API
|
|
586
|
-
|
|
587
|
-
#### Signals
|
|
588
|
-
|
|
589
|
-
| Signal | Type | Meaning |
|
|
590
|
-
| ----------------------- | ---------------------------------------- | ------------------------------------------------------- |
|
|
591
|
-
| `currentLanguage` | `Signal<L>` | Active language id. |
|
|
592
|
-
| `currentLanguageObject` | `Signal<Language<L>>` | The active language entry. |
|
|
593
|
-
| `languages` | `Signal<readonly Language<L>[]>` | Supported languages. |
|
|
594
|
-
| `dir` / `isRtl` | `Signal<Direction>` / `Signal<boolean>` | Document direction. |
|
|
595
|
-
| `locale` | `Signal<string>` | BCP-47 locale driving `Intl` and plural rules. |
|
|
596
|
-
| `loadingState` | `Signal<'idle' \| 'loading' \| 'error'>` | Current dictionary status. |
|
|
597
|
-
| `loadingError` | `Signal<unknown>` | Last load failure. |
|
|
598
|
-
| `isLoading` | `Signal<boolean>` | `loadingState() === 'loading'`. |
|
|
599
|
-
| `ready` | `Signal<boolean>` | Initial content settled — the one to gate skeletons on. |
|
|
600
|
-
| `loadedTranslations` | `Signal<Record<string, unknown>>` | The active dictionary. |
|
|
601
|
-
| `missingKeys` | `Signal<readonly string[]>` | Unresolved keys, insertion order, deduplicated. |
|
|
602
|
-
|
|
603
|
-
#### Methods
|
|
604
|
-
|
|
605
|
-
| Method | Result | Notes |
|
|
606
|
-
| ------------------------------------------ | -------------------------- | ---------------------------------------------------------------------------------------------- |
|
|
607
|
-
| `translate(key, params?)` | `string` | Key lookup + ICU rendering. |
|
|
608
|
-
| `translate(key, defaultValue, params?)` | `string` | A supplied `defaultValue` is not reported as missing. |
|
|
609
|
-
| `translate({ en: 'Hi', ar: 'أهلاً' })` | `string` | Inline map: current → fallback → first value → `''`. |
|
|
610
|
-
| `t(key, params?)` | `Signal<string>` | Same chain as a `computed`; params may be a function of signals. |
|
|
611
|
-
| `setLanguage(id)` / `setLanguageAsync(id)` | `void` / `Promise<void>` | Follows `switchStrategy`. |
|
|
612
|
-
| `toggle()` / `next()` / `previous()` | `void` | `toggle()` flips the first two languages (dev warning with more); `next()`/`previous()` cycle. |
|
|
613
|
-
| `loadTranslations(id)` | `Promise<Record<…>>` | Preload without switching. |
|
|
614
|
-
| `reload(language?)` | `Promise<boolean>` | Invalidate + refetch; never rejects. |
|
|
615
|
-
| `formatNumber(value, options?)` | `string` | `Intl.NumberFormat` bound to `locale`. |
|
|
616
|
-
| `formatDate(value, options?)` | `string` | `Intl.DateTimeFormat` bound to `locale`. |
|
|
617
|
-
| `getLanguage(id)` | `Language<L> \| undefined` | Lookup. |
|
|
618
|
-
| `initialize()` | `Promise<void>` | Called by the provider; idempotent. |
|
|
619
|
-
| `clearMissingKeys()` | `void` | Reset the missing-key report. |
|
|
620
|
-
| `clearMissingParams()` | `void` | Reset the missing-parameter dedupe. |
|
|
621
|
-
|
|
622
|
-
`RvTranslatePipe` (`rvTranslate`) delegates to `translate()`. It is impure by necessity —
|
|
623
|
-
the service reads signals on every call — so prefer `t()` or component code for long
|
|
624
|
-
lists.
|
|
625
|
-
|
|
626
|
-
### ICU messages
|
|
627
|
-
|
|
628
|
-
Supported subset (MF1): `{name}` interpolation, `{n, plural, …}` (with `offset:`),
|
|
629
|
-
`{n, selectordinal, …}`, `{x, select, …}`, `#`, `{n, number[, style]}`,
|
|
630
|
-
`{d, date[, style]}`, and nesting.
|
|
631
|
-
|
|
632
|
-
```json
|
|
633
|
-
{
|
|
634
|
-
"items": "{count, plural, =0 {No items} one {# item} other {# items}}",
|
|
635
|
-
"guests": "{n, plural, offset:1 =0 {Nobody} =1 {Only you} one {You and # other} other {You and # others}}",
|
|
636
|
-
"place": "{rank, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}",
|
|
637
|
-
"amount": "{value, number, ::currency/USD}",
|
|
638
|
-
"ratio": "{value, number, percent}",
|
|
639
|
-
"day": "{value, date, long}"
|
|
640
|
-
}
|
|
641
|
-
```
|
|
642
|
-
|
|
643
|
-
- Categories come from `Intl.PluralRules(locale)`, so Arabic gets all six forms
|
|
644
|
-
(`zero`, `one`, `two`, `few`, `many`, `other`) with no dependency.
|
|
645
|
-
- `offset:` follows ICU: `=N` matches the **raw** value, the category is selected with
|
|
646
|
-
`value - offset`, and `#` renders `value - offset` in the locale's digits.
|
|
647
|
-
- `number` styles: `percent`, `integer`, `::currency/XXX`. `date` styles:
|
|
648
|
-
`short`/`medium`/`long`/`full`. Anything else is unsupported.
|
|
649
|
-
- Unsupported or malformed constructs never throw: the raw `{…}` segment is returned
|
|
650
|
-
as-is and parsing continues.
|
|
651
|
-
- `{name}` interpolation is `String(value)`; use `{n, number}` when formatting matters.
|
|
652
|
-
- `''` renders one apostrophe. A single apostrophe immediately before `{` or `}` (and
|
|
653
|
-
`#` inside a plural) starts a quoted literal that ends at the next apostrophe:
|
|
654
|
-
`It''s '{'x'}'` → `It's {x}`. A lone apostrophe elsewhere (`Don't`) is unchanged.
|
|
655
|
-
- `date` accepts a `Date`, epoch milliseconds, or a strict ISO-8601 string
|
|
656
|
-
(`2026-10-28`, `2026-10-28T12:00:00Z`). Invalid input keeps the raw segment. Plain
|
|
657
|
-
`{d}` on a `Date` uses `String()` — use `{d, date, …}` for localized output.
|
|
658
|
-
- Templates are compiled once into a cached AST, so a message rendered on every
|
|
659
|
-
change-detection pass is not re-parsed.
|
|
660
|
-
|
|
661
|
-
### Missing keys
|
|
662
|
-
|
|
663
|
-
A key is missing only when it is absent from the current dictionary, absent from the
|
|
664
|
-
fallback dictionary, and no `defaultValue` was supplied. It is reported **once per key
|
|
665
|
-
per session**, and only once the current language actually has a dictionary — so a slow
|
|
666
|
-
load never produces false positives.
|
|
667
|
-
|
|
668
|
-
```ts
|
|
669
|
-
provideRiviniaI18n({
|
|
670
|
-
defaultLanguage: 'ar',
|
|
671
|
-
languages: […],
|
|
672
|
-
fallbackLanguage: 'en',
|
|
673
|
-
onMissingKey: ({ key, language, fallbackLanguage }) =>
|
|
674
|
-
report(key, { language, fallbackLanguage }),
|
|
675
|
-
});
|
|
676
|
-
```
|
|
677
|
-
|
|
678
|
-
```html
|
|
679
|
-
@if (i18n.missingKeys().length) {
|
|
680
|
-
<p role="status">{{ i18n.missingKeys().length }} untranslated keys</p>
|
|
681
|
-
}
|
|
682
|
-
```
|
|
683
|
-
|
|
684
|
-
Without `onMissingKey`, a `console.warn` is logged once per key in dev mode. Set
|
|
685
|
-
`warnOnMissingKey: false` to silence it, or `true` to keep it in production.
|
|
686
|
-
|
|
687
|
-
### Missing parameters
|
|
688
|
-
|
|
689
|
-
A message that needs `{name}` but receives no `name` keeps the placeholder — it is
|
|
690
|
-
never replaced with `undefined`. Report it the same way as missing keys:
|
|
691
|
-
|
|
692
|
-
```ts
|
|
693
|
-
provideRiviniaI18n({
|
|
694
|
-
// …
|
|
695
|
-
onMissingParam: ({ key, param, language }) => report(param, { key, language }),
|
|
696
|
-
});
|
|
697
|
-
```
|
|
698
|
-
|
|
699
|
-
Without `onMissingParam`, dev mode logs one warning per (key, param) pair. Set
|
|
700
|
-
`warnOnMissingParam: false` to silence it. The hook is delivered from a microtask,
|
|
701
|
-
so it may write signals, and `i18n.clearMissingParams()` resets the dedupe.
|
|
702
|
-
|
|
703
|
-
### Fallback language
|
|
704
|
-
|
|
705
|
-
Lookup order for `translate(key)`:
|
|
706
|
-
|
|
707
|
-
1. current dictionary — rendered with the **current** locale;
|
|
708
|
-
2. fallback dictionary — rendered with the **fallback** locale;
|
|
709
|
-
3. `defaultValue` — current locale;
|
|
710
|
-
4. the key itself.
|
|
711
|
-
|
|
712
|
-
Rule 2's locale is deliberate: an English plural template borrowed by an Arabic UI must
|
|
713
|
-
use English plural rules (2 categories), not Arabic (6).
|
|
714
|
-
|
|
715
|
-
The fallback dictionary loads in parallel with the initial language and **silently** — a
|
|
716
|
-
fallback failure reaches `onLoadError` but never sets `loadingState` to `'error'`, because
|
|
717
|
-
the current dictionary is what the UI needs. It is transferred with the rest of the state,
|
|
718
|
-
so hydration does not fetch it again. With `preload: false`, the fallback works from
|
|
719
|
-
cache/inline dictionaries only.
|
|
720
|
-
|
|
721
|
-
### Load failures
|
|
722
|
-
|
|
723
|
-
A dictionary that fails to load leaves **every** key unresolved, so the page renders raw
|
|
724
|
-
key names. Initialization never rejects: the failure lands on `loadingState` and
|
|
725
|
-
`loadingError`, and with the default `switchStrategy: 'instant'` the language has already
|
|
726
|
-
flipped — use `'preload-first'` if you want a failed load to abort the switch instead.
|
|
727
|
-
|
|
728
|
-
```ts
|
|
729
|
-
provideRiviniaI18n({
|
|
730
|
-
defaultLanguage: 'ar',
|
|
731
|
-
languages: […],
|
|
732
|
-
onLoadError: (language, error) => report(error, { language }),
|
|
733
|
-
});
|
|
734
|
-
```
|
|
735
|
-
|
|
736
|
-
Without `onLoadError`, a `console.error` is logged **once per language per session** in
|
|
737
|
-
dev mode, so a retry loop cannot flood the console. Set `warnOnLoadError: false` to
|
|
738
|
-
silence it, or `true` to keep it in production. A failing fallback dictionary is reported
|
|
739
|
-
the same way but never flips `loadingState` (see [Fallback language](#fallback-language)).
|
|
740
|
-
|
|
741
|
-
### Reloading a dictionary
|
|
742
|
-
|
|
743
|
-
```ts
|
|
744
|
-
await i18n.reload(); // current + fallback; drops every other cached language
|
|
745
|
-
await i18n.reload('en'); // one language; applied only if it is the current one
|
|
746
|
-
```
|
|
747
|
-
|
|
748
|
-
`reload()` is stale-while-revalidate: the visible dictionary stays on screen until the
|
|
749
|
-
fresh one arrives, so a reload never flashes raw keys. Each language carries a generation
|
|
750
|
-
counter, so a response that was in flight when `reload()` ran is discarded instead of
|
|
751
|
-
overwriting the new one. It never rejects — failures land on `loadingState`,
|
|
752
|
-
`loadingError` and `onLoadError`.
|
|
753
|
-
|
|
754
|
-
A typical deploy hook:
|
|
755
|
-
|
|
756
|
-
```ts
|
|
757
|
-
window.addEventListener('focus', () => void i18n.reload());
|
|
758
|
-
```
|
|
759
|
-
|
|
760
|
-
### `t()` signals
|
|
761
|
-
|
|
762
|
-
```ts
|
|
763
|
-
readonly title = this.i18n.t('app.title');
|
|
764
|
-
readonly items = this.i18n.t('cart.items', () => ({ count: this.count() }));
|
|
765
|
-
```
|
|
766
|
-
|
|
767
|
-
A function `params` is invoked inside the computation, so the signals it reads are
|
|
768
|
-
tracked: changing `count` re-renders the text without touching the language. `t()` is a
|
|
769
|
-
`computed` over the same resolution chain as `translate()`, and missing keys are recorded
|
|
770
|
-
in a microtask because Angular forbids signal writes inside a `computed`.
|
|
771
|
-
|
|
772
|
-
Use it for component fields. For a template expression that runs on every change
|
|
773
|
-
detection, `translate()` or the pipe is cheaper.
|
|
774
|
-
|
|
775
|
-
### Typed keys reference
|
|
776
|
-
|
|
777
|
-
The registry is empty by default, so `RegisteredI18nKey` resolves to `string` and nothing
|
|
778
|
-
breaks. Generate the declaration from a dictionary to make a typo a compile error:
|
|
779
|
-
|
|
780
|
-
```bash
|
|
781
|
-
npx rivinia-i18n-keys
|
|
782
|
-
# → src/i18n-keys.d.ts
|
|
783
|
-
npx rivinia-i18n-keys --source public/i18n/en.json --out src/i18n-keys.d.ts
|
|
784
|
-
npx rivinia-i18n-keys --check # exit 1 when the file is stale (CI)
|
|
785
|
-
npx rivinia-i18n-keys --parity --dir public/i18n --base en
|
|
786
|
-
```
|
|
787
|
-
|
|
788
|
-
```ts
|
|
789
|
-
// src/i18n-keys.d.ts — generated, do not edit
|
|
790
|
-
import '@rivinia/i18n';
|
|
791
|
-
|
|
792
|
-
declare module '@rivinia/i18n' {
|
|
793
|
-
interface RiviniaI18nKeyRegistry {
|
|
794
|
-
readonly keys: 'app.title' | 'app.save' | 'booking.seats';
|
|
795
|
-
}
|
|
796
|
-
}
|
|
797
|
-
```
|
|
798
|
-
|
|
799
|
-
With that file in the program:
|
|
800
|
-
|
|
801
|
-
```ts
|
|
802
|
-
i18n.translate('app.title'); // ok
|
|
803
|
-
i18n.t('app.titel'); // TS error: not assignable to 'app.title' | …
|
|
804
|
-
i18n.translate(`status.${code}` as RegisteredI18nKey); // dynamic key, explicit
|
|
805
|
-
```
|
|
806
|
-
|
|
807
|
-
The CLI flattens nested objects to dot paths, keeps literal dotted keys as-is, keeps
|
|
808
|
-
string leaves only, warns about non-string leaves and key collisions (the flat key
|
|
809
|
-
wins), sorts keys for stable diffs, and escapes quotes. It has no dependencies and
|
|
810
|
-
ships with the package (`rivinia-i18n-keys`).
|
|
811
|
-
|
|
812
|
-
`--parity` compares every `<language>.json` in `--dir` against `--base` and reports,
|
|
813
|
-
sorted: keys missing from a language, keys extra to it, and ICU placeholders used by
|
|
814
|
-
the base string but absent from the translation. Placeholders inside plural/select
|
|
815
|
-
branches are compared too; branch text itself is never read as a parameter. Any
|
|
816
|
-
mismatch exits 1, so CI fails on the common "added to `en.json`, forgot `ar.json`" bug.
|
|
817
|
-
|
|
818
|
-
### Toggle reference
|
|
819
|
-
|
|
820
|
-
The `@rivinia/i18n/ui` entry point ships a two-language toggle and the template that
|
|
821
|
-
replaces its default label:
|
|
822
|
-
|
|
823
|
-
```ts
|
|
824
|
-
import { RiviniaLanguageToggle, RiviniaLanguageTrigger } from '@rivinia/i18n/ui';
|
|
825
|
-
```
|
|
826
|
-
|
|
827
|
-
**Every export of this entry point is Experimental in 0.7.1** (D68):
|
|
828
|
-
`RiviniaLanguageToggle`, `RiviniaLanguageTrigger`, `RiviniaLanguageTriggerContext`,
|
|
829
|
-
`RiviniaLanguageManager` and `LanguageLike`. The five symbols may change — or lose
|
|
830
|
-
members — without a deprecation cycle until the entry point is promoted to Stable, which
|
|
831
|
-
needs the browser matrix and one release of consumer use first. The core entry point
|
|
832
|
-
keeps its own tiers; this one moves none of them.
|
|
833
|
-
|
|
834
|
-
The control flips between exactly two languages. The button shows the language it
|
|
835
|
-
switches **to** — the label is the destination — and the inner `<button>` owns the
|
|
836
|
-
accessible name, `lang` and `dir`, so the name is pronounced and laid out in its own
|
|
837
|
-
language even when the page runs the other direction. The host element is the API: write
|
|
838
|
-
`<rv-language-toggle>`, style through the hooks below, and never reach for the button.
|
|
839
|
-
|
|
840
|
-
#### Managed, with `RiviniaI18n`
|
|
841
|
-
|
|
842
|
-
`RiviniaI18n` satisfies `RiviniaLanguageManager` structurally, so pass the service
|
|
843
|
-
directly. Managed state wins: `[languages]`, `[current]` and `[busy]` are ignored while
|
|
844
|
-
`manager` is set.
|
|
845
|
-
|
|
846
|
-
```ts
|
|
847
|
-
import { Component, inject } from '@angular/core';
|
|
848
|
-
import { RiviniaI18n } from '@rivinia/i18n';
|
|
849
|
-
import { RiviniaLanguageToggle } from '@rivinia/i18n/ui';
|
|
850
|
-
|
|
851
|
-
@Component({
|
|
852
|
-
selector: 'app-header',
|
|
853
|
-
imports: [RiviniaLanguageToggle],
|
|
854
|
-
template: `<rv-language-toggle [manager]="i18n" [label]="switchLabel()" />`,
|
|
855
|
-
})
|
|
856
|
-
export class Header {
|
|
857
|
-
readonly i18n = inject(RiviniaI18n<'ar' | 'en'>);
|
|
858
|
-
readonly switchLabel = this.i18n.t('common.switchLanguage');
|
|
859
|
-
}
|
|
860
|
-
```
|
|
861
|
-
|
|
862
|
-
`label` is the _action_ fragment, appended after the language name. The button above is
|
|
863
|
-
rendered as:
|
|
864
|
-
|
|
865
|
-
```html
|
|
866
|
-
<button
|
|
867
|
-
type="button"
|
|
868
|
-
class="rv-language-toggle__button"
|
|
869
|
-
lang="ar"
|
|
870
|
-
dir="rtl"
|
|
871
|
-
aria-label="العربية, Switch language"
|
|
872
|
-
>
|
|
873
|
-
<span class="rv-language-toggle__icon">
|
|
874
|
-
<svg viewBox="0 0 64 64" aria-hidden="true" focusable="false"><!-- globe --></svg>
|
|
875
|
-
</span>
|
|
876
|
-
<span class="rv-language-toggle__name">العربية</span>
|
|
877
|
-
</button>
|
|
878
|
-
```
|
|
879
|
-
|
|
880
|
-
`label` is never translated for you — the UI entry point imports core types only, so the
|
|
881
|
-
app passes an already translated string (a `t()` signal re-renders on a language switch).
|
|
882
|
-
|
|
883
|
-
#### Presentational, without a manager
|
|
884
|
-
|
|
885
|
-
```html
|
|
886
|
-
<rv-language-toggle
|
|
887
|
-
[languages]="languages"
|
|
888
|
-
[current]="language()"
|
|
889
|
-
[busy]="switching()"
|
|
890
|
-
label="Switch language"
|
|
891
|
-
(languageChange)="language.set($event)"
|
|
892
|
-
/>
|
|
893
|
-
```
|
|
894
|
-
|
|
895
|
-
With no manager, `languages` + `current` describe the state, `busy` supplies the loading
|
|
896
|
-
state, and `languageChange` is the only side effect. Presentational mode is synchronous:
|
|
897
|
-
there is nothing to await, so the event fires on activation.
|
|
898
|
-
|
|
899
|
-
#### The icon
|
|
900
|
-
|
|
901
|
-
The button leads with a mark: a globe drawn in `currentColor`, so it inherits the
|
|
902
|
-
button's colour, hover, active and disabled states without extra styling. It is
|
|
903
|
-
`aria-hidden` and `focusable="false"`, and it contributes nothing to the accessible
|
|
904
|
-
name — `aria-label` on the button supplies that (D57).
|
|
905
|
-
|
|
906
|
-
`[icon]` replaces it with a template. The template is rendered as-is inside a
|
|
907
|
-
`1.5em` square box that stretches it on both axes, so an `<svg>` needs no `width` or
|
|
908
|
-
`height` of its own:
|
|
909
|
-
|
|
910
|
-
```ts
|
|
911
|
-
@Component({
|
|
912
|
-
imports: [RiviniaLanguageToggle],
|
|
913
|
-
template: `
|
|
914
|
-
<ng-template #swapIcon>
|
|
915
|
-
<svg viewBox="0 0 64 64" fill="none" stroke="currentColor" aria-hidden="true">
|
|
916
|
-
<path d="M10 24h36M38 16l8 8-8 8M54 40H18M26 32l-8 8 8 8" />
|
|
917
|
-
</svg>
|
|
918
|
-
</ng-template>
|
|
919
|
-
<rv-language-toggle [manager]="i18n" [icon]="swapIcon" [label]="switchLabel()" />
|
|
920
|
-
`,
|
|
921
|
-
})
|
|
922
|
-
export class Header {
|
|
923
|
-
readonly i18n = inject(RiviniaI18n<'ar' | 'en'>);
|
|
924
|
-
readonly switchLabel = this.i18n.t('common.switchLanguage');
|
|
925
|
-
}
|
|
926
|
-
```
|
|
927
|
-
|
|
928
|
-
Two constraints come from that box:
|
|
929
|
-
|
|
930
|
-
- **Draw in `currentColor`.** A hard-coded fill ignores the hover and disabled states.
|
|
931
|
-
- **Design at the painted size.** The default is `1.5em` — 21px at the shipped
|
|
932
|
-
`0.875rem` type — and the mark is drawn at `stroke-width="4.4"` on a 64-unit viewBox
|
|
933
|
-
so it lands at ~1.4px. Artwork authored for a 16px or 24px grid is usually too dense
|
|
934
|
-
here: fine latitudes and extra meridians fill in below roughly 22px. Resize with
|
|
935
|
-
`--rv-i18n-toggle-icon-size` rather than by hand, and a consumer icon follows the same
|
|
936
|
-
token.
|
|
937
|
-
|
|
938
|
-
A consumer icon drawn inside `rvLanguageTrigger` instead of `[icon]` sits after the
|
|
939
|
-
button's own mark, so pass `[icon]` when replacing it.
|
|
940
|
-
|
|
941
|
-
#### With a trigger template
|
|
942
|
-
|
|
943
|
-
`rvLanguageTrigger` replaces the default name span inside the button. The template
|
|
944
|
-
receives the target entry as `$implicit` and `busy`, and inherits the button's `lang` and
|
|
945
|
-
`dir`:
|
|
946
|
-
|
|
947
|
-
```html
|
|
948
|
-
<rv-language-toggle [manager]="i18n" label="Switch language">
|
|
949
|
-
<ng-template rvLanguageTrigger let-language let-busy="busy">
|
|
950
|
-
<svg aria-hidden="true" focusable="false"><!-- consumer-provided icon --></svg>
|
|
951
|
-
<span [lang]="language.id">{{ language.nativeName }}</span>
|
|
952
|
-
@if (busy) {
|
|
953
|
-
<span class="spinner" aria-hidden="true"></span>
|
|
954
|
-
}
|
|
955
|
-
</ng-template>
|
|
956
|
-
</rv-language-toggle>
|
|
957
|
-
```
|
|
958
|
-
|
|
959
|
-
Set `lang` explicitly on any text inside the template that is **not** in the target
|
|
960
|
-
language — a "current language" hint, an English action word, a flag's alt text — because
|
|
961
|
-
it would otherwise inherit the target's `lang` and be pronounced and laid out as that
|
|
962
|
-
language.
|
|
963
|
-
|
|
964
|
-
> **WARNING — the template's visible text must be a prefix of the accessible name.**
|
|
965
|
-
> The name is computed from the target language, not read from the template's DOM, so
|
|
966
|
-
> the library cannot see what the template renders. Whatever text the template shows the
|
|
967
|
-
> user must remain a prefix of that name (WCAG 2.5.3 / D57). `label` is appended after
|
|
968
|
-
> the language name, so it cannot repair a template whose visible text comes first: such
|
|
969
|
-
> a template must be changed, not the name. A template that renders العربية under an
|
|
970
|
-
> accessible name of English, Switch language is a voice-control failure — the user says
|
|
971
|
-
> what they see and nothing matches. Icon-only triggers are safe: no visible text, no
|
|
972
|
-
> prefix to violate, and the name is still non-empty. `label` is required with a custom
|
|
973
|
-
> template; a dev-mode warning fires without it.
|
|
974
|
-
|
|
975
|
-
A text suffix is bidi-fragile, so it belongs to the name's run. When the template adds
|
|
976
|
-
words after the name — ", Switch language", a count, a code — put the punctuation inside
|
|
977
|
-
the element that holds the name and keep the whole label in one element. As the first
|
|
978
|
-
character of an LTR fragment a comma is pushed to the far edge of an RTL button, far from
|
|
979
|
-
the name it closes, and the button's `gap` then separates it from that name in both
|
|
980
|
-
directions. The proof page under `projects/i18n-e2e` renders exactly this case.
|
|
981
|
-
|
|
982
|
-
#### Inputs and output
|
|
983
|
-
|
|
984
|
-
| Input | Type | Default | Meaning |
|
|
985
|
-
| ----------- | ------------------------- | ------- | --------------------------------------------------------------------------- |
|
|
986
|
-
| `manager` | `RiviniaLanguageManager` | none | Managed mode: the source of truth for languages, current and busy. |
|
|
987
|
-
| `languages` | `readonly LanguageLike[]` | `[]` | Presentational languages; the button shows the entry that is not `current`. |
|
|
988
|
-
| `current` | `string` | none | Presentational current language id. |
|
|
989
|
-
| `label` | `string` | none | Action fragment appended to the name; required with a template. |
|
|
990
|
-
| `busy` | `boolean` | `false` | Presentational loading state; ignored with a manager. |
|
|
991
|
-
| `disabled` | `boolean` | `false` | The app's own switch: sets the native `disabled` attribute. |
|
|
992
|
-
| `icon` | `TemplateRef \| null` | `null` | Replaces the default globe; the template fills the icon box. |
|
|
993
|
-
|
|
994
|
-
`languageChange` emits the id that is now current — see the contract below.
|
|
995
|
-
|
|
996
|
-
`LanguageLike` is `{ id, nativeName?, dir?, locale? }`: `dir` absent renders `dir="auto"`,
|
|
997
|
-
and `locale` is what Intl.DisplayNames uses when `nativeName` is missing.
|
|
998
|
-
|
|
999
|
-
#### Two languages exactly
|
|
1000
|
-
|
|
1001
|
-
| `languages().length` | Renders |
|
|
1002
|
-
| -------------------- | ---------------------------------------------------------------- |
|
|
1003
|
-
| 0 or 1 | nothing: an empty host with no `data-*` attribute |
|
|
1004
|
-
| 2 | the toggle |
|
|
1005
|
-
| 3 or more | one button with `aria-disabled="true"` plus one dev-mode warning |
|
|
1006
|
-
|
|
1007
|
-
Three or more never cycles through the first two. The button keeps its name and stays in
|
|
1008
|
-
the tab order (`aria-disabled`, not the native attribute) so a keyboard or screen-reader
|
|
1009
|
-
user can reach it and learn that the shape is wrong for the data; the count guard also
|
|
1010
|
-
wins over a transient busy state, so the verdict does not alternate. Use a select, a menu,
|
|
1011
|
-
or your own control for three or more languages.
|
|
1012
|
-
|
|
1013
|
-
#### Busy, failure and the emission contract
|
|
1014
|
-
|
|
1015
|
-
- **Busy is announced, not asserted away.** While the manager reports
|
|
1016
|
-
`loadingState() === 'loading'` (or `[busy]` is true, presentational) the button carries
|
|
1017
|
-
`aria-busy="true"` and nothing else, its cursor turns to `progress`, and activation is
|
|
1018
|
-
ignored in the handler rather than queued. The label, the fill and the colours do not
|
|
1019
|
-
move: a switch is a plain wait, and the spinner belongs to the product's template.
|
|
1020
|
-
Focus stays where it is; the component never moves it.
|
|
1021
|
-
- **`languageChange` confirms, it does not intend.** In managed mode the event fires only
|
|
1022
|
-
after `setLanguageAsync(target)` resolves **and** `currentLanguage() === target`.
|
|
1023
|
-
Activating the current language emits nothing. An overlapping switch that loses the
|
|
1024
|
-
core's last-resolved-wins race is silent, because the check runs after the await.
|
|
1025
|
-
- **A failure emits nothing and shows nothing.** `setLanguageAsync` aborts on a failed
|
|
1026
|
-
load, so the visible language, the direction and the label stay as they were.
|
|
1027
|
-
`RiviniaLanguageManager` is four members and includes neither `loadingError` nor
|
|
1028
|
-
`onLoadError`: read `RiviniaI18n.loadingError` or pass `onLoadError` in the config, and
|
|
1029
|
-
render your own message next to the toggle.
|
|
1030
|
-
- **`switchStrategy` caveat.** The toggle always calls `setLanguageAsync()`, which waits
|
|
1031
|
-
for the dictionary and then applies, regardless of `switchStrategy`. An app configured
|
|
1032
|
-
with `'instant'` still gets the preload-first path through this control — that is what
|
|
1033
|
-
makes the confirmation above meaningful.
|
|
1034
|
-
|
|
1035
|
-
#### SSR and the language name
|
|
1036
|
-
|
|
1037
|
-
The component renders the same markup on the server and touches no browser global. The
|
|
1038
|
-
name resolves as `nativeName` → Intl.DisplayNames → the raw id, cached per
|
|
1039
|
-
(locale, id). Supply `nativeName` when the server's CLDR data might differ from the
|
|
1040
|
-
browser's: it short-circuits the lookup, so the server HTML and the first client render
|
|
1041
|
-
cannot disagree.
|
|
1042
|
-
|
|
1043
|
-
#### Styling
|
|
1044
|
-
|
|
1045
|
-
Sizes are `rem`, properties are logical, and every token falls back to a `--rv-*`
|
|
1046
|
-
semantic value. Override the custom property, not the declaration:
|
|
1047
|
-
|
|
1048
|
-
| Token | Falls back to | Default |
|
|
1049
|
-
| ----------------------------------- | ------------- | --------------------------------------------------- |
|
|
1050
|
-
| `--rv-i18n-toggle-bg` | `--rv-bg` | `transparent` |
|
|
1051
|
-
| `--rv-i18n-toggle-fg` | `--rv-fg` | `currentColor` |
|
|
1052
|
-
| `--rv-i18n-toggle-border` | `--rv-border` | `currentColor` |
|
|
1053
|
-
| `--rv-i18n-toggle-radius` | `--rv-radius` | `0.5rem` |
|
|
1054
|
-
| `--rv-i18n-toggle-shadow` | `--rv-shadow` | `none` |
|
|
1055
|
-
| `--rv-i18n-toggle-font` | `--rv-font` | `inherit` |
|
|
1056
|
-
| `--rv-i18n-toggle-padding` | — | `0.5rem 0.75rem` |
|
|
1057
|
-
| `--rv-i18n-toggle-gap` | — | `0.5rem` |
|
|
1058
|
-
| `--rv-i18n-toggle-size` | — | `0.875rem` |
|
|
1059
|
-
| `--rv-i18n-toggle-icon-size` | — | `1.5em` |
|
|
1060
|
-
| `--rv-i18n-toggle-hover-bg` | — | `color-mix(in srgb, currentColor 8%, transparent)` |
|
|
1061
|
-
| `--rv-i18n-toggle-active-bg` | — | `color-mix(in srgb, currentColor 16%, transparent)` |
|
|
1062
|
-
| `--rv-i18n-toggle-focus-ring` | — | `2px solid currentColor` |
|
|
1063
|
-
| `--rv-i18n-toggle-focus-offset` | — | `0.125rem` |
|
|
1064
|
-
| `--rv-i18n-toggle-disabled-opacity` | — | `0.45` |
|
|
1065
|
-
|
|
1066
|
-
The border and font tokens are a **colour** and a **font family**, not shorthands: the
|
|
1067
|
-
declaration supplies `1px solid` and `font-family`, so `--rv-border` and `--rv-font` from
|
|
1068
|
-
`@rivinia/theme` flow through unchanged instead of producing an invalid shorthand.
|
|
1069
|
-
|
|
1070
|
-
Hover and active default to 8% and 16% of `currentColor` mixed **over** the button's own
|
|
1071
|
-
background, so a dark `--rv-bg` keeps its fill instead of turning see-through. A value
|
|
1072
|
-
you set for `--rv-i18n-toggle-hover-bg` or `--rv-i18n-toggle-active-bg` replaces the whole
|
|
1073
|
-
fill, not just the tint.
|
|
1074
|
-
|
|
1075
|
-
The hooks that are safe to depend on:
|
|
1076
|
-
|
|
1077
|
-
- the host `rv-language-toggle` — with `[data-busy]`, `[data-disabled]` and
|
|
1078
|
-
`[data-languages="2" | "many"]`; `data-disabled` mirrors the `[disabled]` input only,
|
|
1079
|
-
so a stylesheet can tell "the app disabled this" apart from "this shape is wrong for
|
|
1080
|
-
the data" (which is `data-languages="many"` plus `aria-disabled="true"`);
|
|
1081
|
-
- `rv-language-toggle__button`, `rv-language-toggle__icon` and
|
|
1082
|
-
`rv-language-toggle__name` on the inner elements.
|
|
1083
|
-
|
|
1084
|
-
With 0 or 1 languages the host is empty and carries no `data-*` attribute at all, so a
|
|
1085
|
-
`[data-languages]` selector has nothing to match by design. There is no error state to
|
|
1086
|
-
style.
|
|
1087
|
-
|
|
1088
|
-
#### Recipes: inside a menu or beside a select (Experimental, untested)
|
|
1089
|
-
|
|
1090
|
-
Neither recipe is covered by this release's test matrix; the select in particular is the
|
|
1091
|
-
supported shape for three or more languages, not something the toggle turns into.
|
|
1092
|
-
|
|
1093
|
-
- **Inside a menu.** The toggle is a plain `<button>` in normal flow, so it can sit in a
|
|
1094
|
-
panel that already exists — `@rivinia/menu/ui` ships the menu primitives. The menu's
|
|
1095
|
-
focus trap and keyboard model with this control inside it have **not** been tested.
|
|
1096
|
-
- **Beside a native `<select>`.** For three or more languages, bind the select to the
|
|
1097
|
-
service and leave the toggle out:
|
|
1098
|
-
|
|
1099
|
-
```html
|
|
1100
|
-
<select (change)="i18n.setLanguage($any($event.target).value)">
|
|
1101
|
-
@for (lang of i18n.languages(); track lang.id) {
|
|
1102
|
-
<option [value]="lang.id" [selected]="lang.id === i18n.currentLanguage()" [lang]="lang.id">
|
|
1103
|
-
{{ lang.nativeName }}
|
|
1104
|
-
</option>
|
|
1105
|
-
}
|
|
1106
|
-
</select>
|
|
1107
|
-
```
|
|
1108
|
-
|
|
1109
|
-
`@rivinia/select/ui` ships a richer popup if the native control is not enough; using it
|
|
1110
|
-
with this service is **untested**.
|
|
1111
|
-
|
|
1112
|
-
#### No flags
|
|
1113
|
-
|
|
1114
|
-
The library ships one neutral mark — a globe — and no flag imagery. Flag icons for
|
|
1115
|
-
languages are politically ambiguous and the W3C i18n guidance recommends against them.
|
|
1116
|
-
A globe does not name a language it cannot represent, and it says "switch language"
|
|
1117
|
-
without saying which. An app that wants its own mark passes `[icon]`, or draws one
|
|
1118
|
-
inside `rvLanguageTrigger`; either way the accessible name is unaffected.
|
|
1119
|
-
|
|
1120
|
-
### SSR reference
|
|
1121
|
-
|
|
1122
|
-
The default loader works on the server: `REQUEST` plus `<base href>` produce an absolute
|
|
1123
|
-
URL, so Node's `fetch` never sees a relative path. The rendered dictionaries go into the
|
|
1124
|
-
`TransferState`, and the browser reads them instead of fetching again.
|
|
1125
|
-
|
|
1126
|
-
- **A custom SSR host must provide `REQUEST`.** `renderApplication` does not add it;
|
|
1127
|
-
`@angular/ssr` does. Without it the service cannot build an absolute URL on the server
|
|
1128
|
-
and the default loader fails there — the same as any other library that needs the
|
|
1129
|
-
request origin.
|
|
1130
|
-
- **Provide the serializer in the app injector.** `renderApplication` serializes the
|
|
1131
|
-
_platform_ `TransferState`, while `bootstrapApplication` gives the app its own root
|
|
1132
|
-
injector, so dictionaries loaded by the service land in a different instance. Register
|
|
1133
|
-
a `BEFORE_APP_SERIALIZED` callback (or `provideServerRendering()`) in the app providers.
|
|
1134
|
-
- **Serve the CSR shell as the template.** With `outputMode: 'server'` the builder
|
|
1135
|
-
prerenders `browser/index.html`, so that file already contains a rendered app and its
|
|
1136
|
-
own `ng-state` script. Use `browser/index.csr.html` as the render template; otherwise
|
|
1137
|
-
the response carries two scripts with the same id and the client reads the empty one.
|
|
1138
|
-
- `storageStrategy: 'cookie'` reads the request cookie on the server and writes it in the
|
|
1139
|
-
browser, so the first paint matches the user's choice. Local/session storage fall back
|
|
1140
|
-
to the default language or browser detection on the server.
|
|
1141
|
-
- `provideClientHydration(withEventReplay())` is the standard client side; the clean CSR
|
|
1142
|
-
shell carries no event-dispatch contract script, so an event fired before hydration
|
|
1143
|
-
completes is not replayed.
|
|
1144
|
-
|
|
1145
|
-
A complete, runnable host lives in `projects/i18n-e2e` (`node:http` +
|
|
1146
|
-
`renderApplication`, no Express), with `e2e/ssr-smoke.mjs` asserting the raw HTML, the
|
|
1147
|
-
server log, the transfer payload, the absence of a client refetch, and hydration.
|
|
1148
|
-
|
|
1149
|
-
### Imports
|
|
1150
|
-
|
|
1151
|
-
```ts
|
|
1152
|
-
import {
|
|
1153
|
-
provideRiviniaI18n,
|
|
1154
|
-
defineRiviniaI18n,
|
|
1155
|
-
injectRiviniaI18n,
|
|
1156
|
-
RiviniaI18n,
|
|
1157
|
-
RvTranslatePipe,
|
|
1158
|
-
jsonLoader,
|
|
1159
|
-
httpLoader,
|
|
1160
|
-
remoteLoader,
|
|
1161
|
-
customLoader,
|
|
1162
|
-
formatIcu,
|
|
1163
|
-
} from '@rivinia/i18n';
|
|
1164
|
-
```
|
|
1165
|
-
|
|
1166
|
-
### API stability
|
|
1167
|
-
|
|
1168
|
-
Every export is classified so the 1.0 freeze is predictable. **Internal** symbols
|
|
1169
|
-
exist only so the package's own tests can import them; they may move to an
|
|
1170
|
-
`@rivinia/i18n/internal` entry point (or disappear) before 1.0.
|
|
1171
|
-
|
|
1172
|
-
| Export | Kind | Tier |
|
|
1173
|
-
| ---------------------------------------------------------------------------------------------- | ---------------- | ------------ |
|
|
1174
|
-
| `RiviniaI18n` | service | Stable |
|
|
1175
|
-
| `provideRiviniaI18n`, `defineRiviniaI18n`, `injectRiviniaI18n` | providers | Stable |
|
|
1176
|
-
| `RvTranslatePipe` (`rvTranslate`) | pipe | Stable |
|
|
1177
|
-
| `RiviniaI18nConfig` | type | Stable |
|
|
1178
|
-
| `Language`, `Direction`, `Translation`, `TranslateParams`, `StorageStrategy`, `SwitchStrategy` | types | Stable |
|
|
1179
|
-
| `RiviniaLoadError` | class | Stable |
|
|
1180
|
-
| `MissingKeyEvent`, `MissingParamEvent` | types | Stable |
|
|
1181
|
-
| `TranslationLoader`, `LoaderDescriptor`, `LoaderContext` | types | Stable |
|
|
1182
|
-
| `jsonLoader`, `httpLoader`, `remoteLoader`, `customLoader` | loader factories | Stable |
|
|
1183
|
-
| `HttpLoaderOptions`, `RemoteLoaderOptions` | types | Stable |
|
|
1184
|
-
| `formatIcu`, `IcuFormatOptions` | ICU API | Stable |
|
|
1185
|
-
| `RegisteredI18nKey`, `RiviniaI18nKeyRegistry` | typed-keys types | Stable |
|
|
1186
|
-
| `ViewTransitionConfig`, `ViewTransitionInfo` | types | Experimental |
|
|
1187
|
-
| `ViewTransitionService` | service | Internal |
|
|
1188
|
-
| `parseCookie`, `serializeCookie` | cookie helpers | Internal |
|
|
1189
|
-
| `browserLanguages`, `detectBrowserLanguage` | helpers | Internal |
|
|
1190
|
-
| `RiviniaLanguageToggle` (`rv-language-toggle`), `RiviniaLanguageTrigger` (`rvLanguageTrigger`) | `/ui` components | Experimental |
|
|
1191
|
-
| `RiviniaLanguageManager`, `LanguageLike`, `RiviniaLanguageTriggerContext` | `/ui` types | Experimental |
|
|
1192
|
-
|
|
1193
|
-
### Migration 0.5.0 to 0.6.0
|
|
1194
|
-
|
|
1195
|
-
0.6.0 is a breaking minor (the pre-1.0 policy allows it). The core split (RIV-18) is
|
|
1196
|
-
internal — no signature changed — but three compatibility names are gone:
|
|
1197
|
-
|
|
1198
|
-
1. **The pipe is `rvTranslate`.** `RTranslatePipe` (`rTranslate`) was removed; the
|
|
1199
|
-
package prefix is `rv`, and there is no alias to keep:
|
|
1200
|
-
|
|
1201
|
-
```html
|
|
1202
|
-
<!-- before -->
|
|
1203
|
-
{{ 'booking.seats' | rTranslate: { count: seats } }}
|
|
1204
|
-
<!-- after -->
|
|
1205
|
-
{{ 'booking.seats' | rvTranslate: { count: seats } }}
|
|
100
|
+
export const appConfig: ApplicationConfig = {
|
|
101
|
+
providers: [i18n.provide()],
|
|
102
|
+
};
|
|
1206
103
|
```
|
|
1207
104
|
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
`
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
105
|
+
The provider loads the initial language before first paint (SSR waits through
|
|
106
|
+
`PendingTasks`); `ready()` is the signal to gate skeletons on.
|
|
107
|
+
|
|
108
|
+
3. **Translate.** `{{ 'booking.seats' | rvTranslate }}` in a template,
|
|
109
|
+
`i18n.t('app.title')` for a component field, `i18n.translate(…)` in plain code —
|
|
110
|
+
the component at the top of this file is all three, and the JSON files hold the
|
|
111
|
+
text. Each language entry answers four questions: `id`, `nativeName`, `dir`,
|
|
112
|
+
`locale`. `locale` is the one that surprises people — a bare `ar` formats Latin
|
|
113
|
+
digits (`3`), `ar-EG` formats Arabic-Indic ones (`٣`).
|
|
114
|
+
|
|
115
|
+
4. **Add the switch.** Two languages: `<rv-language-toggle [manager]="i18n" />` from
|
|
116
|
+
`@rivinia/i18n/ui`. Three or more: install `@rivinia/select` and use
|
|
117
|
+
`<rv-language-select [manager]="i18n" label="Language" />` from
|
|
118
|
+
`@rivinia/i18n/select`. Preferring no terminal at all, `defineRiviniaI18n({…})` is
|
|
119
|
+
the object the generated module wraps.
|
|
120
|
+
|
|
121
|
+
## Two ways to use it
|
|
122
|
+
|
|
123
|
+
| Way | Entry | You get |
|
|
124
|
+
| ------------- | ---------------------------------- | -------------------------------------------------------------------------------------- |
|
|
125
|
+
| Headless core | `@rivinia/i18n` | the service, the loaders, ICU formatting, the `rvTranslate` pipe, typed keys |
|
|
126
|
+
| Ready-made UI | `@rivinia/i18n/ui`, `/i18n/select` | `rv-language-toggle` and `rv-language-select`, with their ARIA and their styling hooks |
|
|
127
|
+
|
|
128
|
+
The two are independent: the UI entry points import core **types** only, and the core
|
|
129
|
+
never imports them. Every UI export is Experimental; the tiers are in the
|
|
130
|
+
[API reference](https://github.com/abdelfattahqandil21-oss/Revinia/blob/main/docs/i18n/api.md#api-stability).
|
|
131
|
+
|
|
132
|
+
## Compatibility
|
|
133
|
+
|
|
134
|
+
| | Chrome / Edge | Firefox | Safari macOS | Safari iOS |
|
|
135
|
+
| -------------------------- | ------------- | ------- | ------------ | ---------- |
|
|
136
|
+
| **Supported** (test floor) | 114 | 125 | 17 | 18.3 |
|
|
137
|
+
| **Enhanced** (popup) | 131 | never | 26.2 | 26.2 |
|
|
138
|
+
|
|
139
|
+
`@rivinia/i18n` itself needs no browser feature that Angular 22 does not already
|
|
140
|
+
need: `Intl.PluralRules`, `Intl.DisplayNames` and `fetch` all sit below the floors
|
|
141
|
+
above. The **Enhanced** row belongs to the picker's popup, which is
|
|
142
|
+
`@rivinia/select`'s; the toggle is a plain button and is unaffected.
|
|
143
|
+
`document.startViewTransition` is used only if you opt into `viewTransition` — the
|
|
144
|
+
service feature-detects it and applies the change without a transition where it is
|
|
145
|
+
absent. Peers: `@angular/core` `^22.0.0`, plus `@rivinia/select` `^1.0.0-rc.1` for
|
|
146
|
+
the `/select` entry only — optional, so an app that never imports
|
|
147
|
+
`@rivinia/i18n/select` does not install it. The caret admits every select 1.x
|
|
148
|
+
release, the rc and the final alike, and excludes a 2.0. The floor dates, the
|
|
149
|
+
`@supports` gate and what has never been run (including real Safari) are in
|
|
150
|
+
[browser support](https://github.com/abdelfattahqandil21-oss/Revinia/blob/main/docs/browser-support.md).
|
|
151
|
+
|
|
152
|
+
## Go further
|
|
153
|
+
|
|
154
|
+
Three levels, kept as they were: everyday patterns first, then the complete
|
|
155
|
+
surface ordered by API.
|
|
156
|
+
|
|
157
|
+
| Tier | Read |
|
|
158
|
+
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
159
|
+
| Everyday use | [translating text](https://github.com/abdelfattahqandil21-oss/Revinia/blob/main/docs/i18n/translating.md) · [switching the language](https://github.com/abdelfattahqandil21-oss/Revinia/blob/main/docs/i18n/switching.md) · [dictionaries and SSR](https://github.com/abdelfattahqandil21-oss/Revinia/blob/main/docs/i18n/dictionaries.md) |
|
|
160
|
+
| Reference — behaviour | [ICU messages](https://github.com/abdelfattahqandil21-oss/Revinia/blob/main/docs/i18n/icu.md) · [missing keys, fallback and failures](https://github.com/abdelfattahqandil21-oss/Revinia/blob/main/docs/i18n/resilience.md) · [the CLI](https://github.com/abdelfattahqandil21-oss/Revinia/blob/main/docs/i18n/cli.md) |
|
|
161
|
+
| Reference — the surface | [the API](https://github.com/abdelfattahqandil21-oss/Revinia/blob/main/docs/i18n/api.md) · [the language toggle](https://github.com/abdelfattahqandil21-oss/Revinia/blob/main/docs/i18n/toggle.md) · [the language picker](https://github.com/abdelfattahqandil21-oss/Revinia/blob/main/docs/i18n/select.md) |
|
|
162
|
+
| Theming | [Rivinia theming](https://github.com/abdelfattahqandil21-oss/Revinia/blob/main/docs/theming.md) |
|
|
163
|
+
|
|
164
|
+
Migration notes for each version live in
|
|
165
|
+
[CHANGELOG.md](https://github.com/abdelfattahqandil21-oss/Revinia/blob/main/projects/i18n/CHANGELOG.md).
|
|
166
|
+
MIT licensed.
|