@rivinia/i18n 0.8.0 → 1.0.0-rc.2

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