@rivinia/i18n 0.6.0 → 0.7.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
@@ -3,19 +3,28 @@
3
3
  [![npm version](https://img.shields.io/npm/v/@rivinia/i18n.svg)](https://www.npmjs.com/package/@rivinia/i18n)
4
4
  [![license](https://img.shields.io/npm/l/@rivinia/i18n.svg)](https://www.npmjs.com/package/@rivinia/i18n)
5
5
 
6
+ <p align="center">
7
+ <img src="https://raw.githubusercontent.com/abdelfattahqandil21-oss/Revinia/main/assets/rivinia-abstract-mark-light.svg" alt="Rivinia" width="140" />
8
+ </p>
9
+
6
10
  A headless Angular language manager built on signals. Key-based JSON
7
11
  dictionaries, inline translations, RTL/LTR document attributes, lazy loaders,
8
12
  ICU plural/select messages, browser-language detection, and `Intl` number/date
9
13
  formatting — with SSR that actually works and no runtime dependency beyond
10
14
  Angular.
11
15
 
12
- - Package version: **0.4.0**
16
+ Concretely: the text lives in JSON files, components ask for a key, and the whole
17
+ app — text, direction, dates, numbers — follows the language the user picked.
18
+ Arabic is a first-class target, not an afterthought of an English layout.
19
+
20
+ - Package version: **0.7.2**
13
21
  - Peer dependency: **`@angular/core` `^22.0.0`** (plus `@angular-devkit/schematics` for `ng add`)
14
- - Entry point: **`@rivinia/i18n`** (single public entry point)
22
+ - Entry points: **`@rivinia/i18n`** (headless core) and **`@rivinia/i18n/ui`**
23
+ (the standalone language toggle)
15
24
  - `sideEffects: false`; no runtime import beyond `@angular/core`; loaders are lazy chunks
16
25
  - No `HttpClient` peer — the built-in loaders use `fetch`
17
26
 
18
- ## Quick features
27
+ ## What you get
19
28
 
20
29
  - **Signal-first state.** `currentLanguage`, `dir`, `loadingState`, `missingKeys` and
21
30
  `locale` are readonly signals; changes only via methods.
@@ -40,7 +49,21 @@ Angular.
40
49
  - **Persistence + detection.** local/session/cookie storage, `navigator.languages` match,
41
50
  `<html lang>` and `<html dir>` kept in sync.
42
51
 
43
- ## Install
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
44
67
 
45
68
  ```bash
46
69
  npm install @rivinia/i18n
@@ -60,49 +83,76 @@ whether to detect the browser language. It only inserts an import and a
60
83
  `provideRiviniaI18n({…})` call, is idempotent, and skips with a warning — never an
61
84
  error — when it does not recognize the workspace.
62
85
 
63
- ## Imports
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
64
103
 
65
104
  ```ts
66
- import {
67
- provideRiviniaI18n,
68
- defineRiviniaI18n,
69
- injectRiviniaI18n,
70
- RiviniaI18n,
71
- RvTranslatePipe,
72
- jsonLoader,
73
- httpLoader,
74
- remoteLoader,
75
- customLoader,
76
- formatIcu,
77
- } from '@rivinia/i18n';
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
+ };
78
112
  ```
79
113
 
80
- ## API stability
114
+ #### 3. Translate
81
115
 
82
- Every export is classified so the 1.0 freeze is predictable. **Internal** symbols
83
- exist only so the package's own tests can import them; they may move to an
84
- `@rivinia/i18n/internal` entry point (or disappear) before 1.0.
116
+ ```ts
117
+ // src/app/header.ts
118
+ import { Component } from '@angular/core';
119
+ import { RvTranslatePipe } from '@rivinia/i18n';
120
+ import { injectI18n } from './i18n/languages';
121
+
122
+ @Component({
123
+ selector: 'app-header',
124
+ imports: [RvTranslatePipe],
125
+ template: `
126
+ <h1>{{ title() }}</h1>
127
+ <p>{{ 'booking.seats' | rvTranslate }}</p>
128
+ <button type="button" (click)="i18n.setLanguage('en')">English</button>
129
+ `,
130
+ })
131
+ export class Header {
132
+ readonly i18n = injectI18n();
133
+ readonly title = this.i18n.t('app.title');
134
+ }
135
+ ```
85
136
 
86
- | Export | Kind | Tier |
87
- | ------------------------------------------------------------------------------------- | ---------------- | ------------ |
88
- | `RiviniaI18n` | service | Stable |
89
- | `provideRiviniaI18n`, `defineRiviniaI18n`, `injectRiviniaI18n` | providers | Stable |
90
- | `RvTranslatePipe` (`rvTranslate`) | pipe | Stable |
91
- | `RiviniaI18nConfig` | type | Stable |
92
- | `Language`, `Direction`, `Translation`, `TranslateParams`, `StorageStrategy`, `SwitchStrategy` | types | Stable |
93
- | `RiviniaLoadError` | class | Stable |
94
- | `MissingKeyEvent`, `MissingParamEvent` | types | Stable |
95
- | `TranslationLoader`, `LoaderDescriptor`, `LoaderContext` | types | Stable |
96
- | `jsonLoader`, `httpLoader`, `remoteLoader`, `customLoader` | loader factories | Stable |
97
- | `HttpLoaderOptions`, `RemoteLoaderOptions` | types | Stable |
98
- | `formatIcu`, `IcuFormatOptions` | ICU API | Stable |
99
- | `RegisteredI18nKey`, `RiviniaI18nKeyRegistry` | typed-keys types | Stable |
100
- | `ViewTransitionConfig`, `ViewTransitionInfo` | types | Experimental |
101
- | `ViewTransitionService` | service | Internal |
102
- | `parseCookie`, `serializeCookie` | cookie helpers | Internal |
103
- | `browserLanguages`, `detectBrowserLanguage` | helpers | Internal |
104
-
105
- ## Quick start
137
+ Then the two dictionaries, same keys in both:
138
+
139
+ ```jsonc
140
+ // public/i18n/ar.json
141
+ { "app": { "title": "الحجوزات" }, "booking": { "seats": "المقاعد" } }
142
+ ```
143
+
144
+ ```jsonc
145
+ // public/i18n/en.json
146
+ { "app": { "title": "Bookings" }, "booking": { "seats": "Seats" } }
147
+ ```
148
+
149
+ Both `title()` and the pipe update on the click, and the direction of the page flips
150
+ with the language — nothing else is wired by hand.
151
+
152
+ #### Without the terminal
153
+
154
+ The same setup, written by hand: `provideRiviniaI18n(config)` and
155
+ `injectRiviniaI18n<'ar' | 'en'>()` are the primitives the generated module wraps.
106
156
 
107
157
  ```ts
108
158
  // src/app/i18n.config.ts
@@ -162,30 +212,159 @@ wrapper.
162
212
  before first paint (SSR waits through `PendingTasks`). `ready()` becomes true when the
163
213
  first content is available or initial loading has settled.
164
214
 
165
- ## Configuration
166
-
167
- | Option | Type | Default | Meaning |
168
- | -------------------- | ------------------------------------------- | ---------------------------------- | --------------------------------------------------------------------------- |
169
- | `languages` | `readonly Language<T>[]` | — | Supported languages (`id`, `nativeName`, `dir`, optional `locale`). |
170
- | `defaultLanguage` | `T` | — | Must be one of `languages`; validated at construction. |
171
- | `fallbackLanguage` | `T` | none | Second lookup dictionary; must be one of `languages`. |
172
- | `loader` | `LoaderDescriptor<T>` | `jsonLoader()` | Dictionary source. |
173
- | `translations` | `Partial<Record<T, Record<string, unknown>>>` | none | Inline seeds, painted before any network load; a loader response still wins. |
174
- | `preload` | `boolean` | `true` | Load the initial language during provider setup. |
175
- | `detectBrowser` | `boolean` | `false` | Match `navigator.languages` on first visit (a stored choice wins). |
176
- | `storageStrategy` | `'local' \| 'session' \| 'cookie' \| 'none'` | `'local'` | Persistence; `'cookie'` also works on the server through `REQUEST`. |
177
- | `storageKey` | `string` | `'rivinia.i18n.language'` | Storage key. |
178
- | `switchStrategy` | `'instant' \| 'preload-first'` | `'instant'` | `'preload-first'` waits for the dictionary; a failure keeps the old language. |
179
- | `autoApplyDirection` | `boolean` | `true` | Write `<html lang>` and `<html dir>`. |
180
- | `onLoadError` | `(language, error) => void` | none | Dictionary load failure. Initialization never rejects because of it. |
181
- | `onMissingKey` | `(event) => void` | none | Unresolved key; suppresses the default warning. |
182
- | `warnOnMissingKey` | `boolean` | `isDevMode() && !onMissingKey` | `console.warn` once per key. |
183
- | `onMissingParam` | `(event) => void` | none | Missing message argument; suppresses the default warning. |
184
- | `warnOnMissingParam` | `boolean` | `isDevMode() && !onMissingParam` | `console.warn` once per (key, param). |
185
- | `persist` | `boolean` | `true` | Persist the language after an explicit switch. First load writes nothing. |
186
- | `viewTransition` | `ViewTransitionConfig` | none | Document view transition on language change. |
187
-
188
- ## Dictionaries
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
189
368
 
190
369
  The default loader fetches `i18n/{language}.json`. For a standard Angular app that
191
370
  means `public/i18n/en.json` served as `/i18n/en.json`. An existing
@@ -212,10 +391,13 @@ also be in-memory:
212
391
  ```ts
213
392
  import { customLoader } from '@rivinia/i18n';
214
393
 
215
- const inMemory = customLoader(async (language: 'ar' | 'en') => ({
216
- ar: { greeting: 'مرحبًا' },
217
- en: { greeting: 'Hello' },
218
- })[language]);
394
+ const inMemory = customLoader(
395
+ async (language: 'ar' | 'en') =>
396
+ ({
397
+ ar: { greeting: 'مرحبًا' },
398
+ en: { greeting: 'Hello' },
399
+ })[language],
400
+ );
219
401
  ```
220
402
 
221
403
  A custom `TranslationLoader` receives the platform context:
@@ -228,7 +410,7 @@ const filesystem: LoaderDescriptor<'ar' | 'en'> = {
228
410
  load: async (language) =>
229
411
  context?.isServer
230
412
  ? JSON.parse(await readFile(`i18n/${language}.json`, 'utf8'))
231
- : (await fetch(new URL(`i18n/${language}.json`, context?.baseUrl)).then((r) => r.json())),
413
+ : await fetch(new URL(`i18n/${language}.json`, context?.baseUrl)).then((r) => r.json()),
232
414
  }),
233
415
  };
234
416
  ```
@@ -237,48 +419,211 @@ const filesystem: LoaderDescriptor<'ar' | 'en'> = {
237
419
  browser; `<base href>` resolved against the request on the server). `isServer` means
238
420
  "there is a server request context", which is what makes relative URLs fetchable.
239
421
 
240
- ## Translation API
241
-
242
- ### Signals
243
-
244
- | Signal | Type | Meaning |
245
- | ----------------------- | ----------------------------------- | -------------------------------------------------------------- |
246
- | `currentLanguage` | `Signal<L>` | Active language id. |
247
- | `currentLanguageObject` | `Signal<Language<L>>` | The active language entry. |
248
- | `languages` | `Signal<readonly Language<L>[]>` | Supported languages. |
249
- | `dir` / `isRtl` | `Signal<Direction>` / `Signal<boolean>` | Document direction. |
250
- | `locale` | `Signal<string>` | BCP-47 locale driving `Intl` and plural rules. |
251
- | `loadingState` | `Signal<'idle' \| 'loading' \| 'error'>` | Current dictionary status. |
252
- | `loadingError` | `Signal<unknown>` | Last load failure. |
253
- | `isLoading` | `Signal<boolean>` | `loadingState() === 'loading'`. |
254
- | `ready` | `Signal<boolean>` | Initial content settled — the one to gate skeletons on. |
255
- | `loadedTranslations` | `Signal<Record<string, unknown>>` | The active dictionary. |
256
- | `missingKeys` | `Signal<readonly string[]>` | Unresolved keys, insertion order, deduplicated. |
257
-
258
- ### Methods
259
-
260
- | Method | Result | Notes |
261
- | --------------------------------------------- | --------------------- | --------------------------------------------------------------------- |
262
- | `translate(key, params?)` | `string` | Key lookup + ICU rendering. |
263
- | `translate(key, defaultValue, params?)` | `string` | A supplied `defaultValue` is not reported as missing. |
264
- | `translate({ en: 'Hi', ar: 'أهلاً' })` | `string` | Inline map: current → fallback → first value. |
265
- | `t(key, params?)` | `Signal<string>` | Same chain as a `computed`; params may be a function of signals. |
266
- | `setLanguage(id)` / `setLanguageAsync(id)` | `void` / `Promise<void>` | Follows `switchStrategy`. |
267
- | `toggle()` / `next()` / `previous()` | `void` | `toggle()` flips the first two languages (dev warning with more); `next()`/`previous()` cycle. |
268
- | `loadTranslations(id)` | `Promise<Record<…>>` | Preload without switching. |
269
- | `reload(language?)` | `Promise<boolean>` | Invalidate + refetch; never rejects. |
270
- | `formatNumber(value, options?)` | `string` | `Intl.NumberFormat` bound to `locale`. |
271
- | `formatDate(value, options?)` | `string` | `Intl.DateTimeFormat` bound to `locale`. |
272
- | `getLanguage(id)` | `Language<L> \| undefined` | Lookup. |
273
- | `initialize()` | `Promise<void>` | Called by the provider; idempotent. |
274
- | `clearMissingKeys()` | `void` | Reset the missing-key report. |
275
- | `clearMissingParams()` | `void` | Reset the missing-parameter dedupe. |
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:
491
+
492
+ ```bash
493
+ npx rivinia-i18n-keys # public/i18n/en.json → src/i18n-keys.d.ts
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" />
506
+ ```
507
+
508
+ The button shows the language it switches **to**, carries `lang` and `dir` on its own
509
+ button, and works with the service (`[manager]`) or without it (`[languages]` +
510
+ `[current]` + `(languageChange)`). **Experimental in 0.7.1** — custom icons, trigger
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
523
+
524
+ The complete surface. Ordered by API, not by learning path.
525
+
526
+ ### Configuration
527
+
528
+ Every option, its default and what it does.
529
+
530
+ #### The options that change behaviour
531
+
532
+ - **`loader`** — where dictionaries come from. The default `jsonLoader()` reads
533
+ `/i18n/{language}.json`. Use a path for an `assets/` layout, `httpLoader` for an API,
534
+ `customLoader` for in-memory data. `httpLoader`/`remoteLoader` are lazy chunks; the
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. |
276
621
 
277
622
  `RvTranslatePipe` (`rvTranslate`) delegates to `translate()`. It is impure by necessity —
278
623
  the service reads signals on every call — so prefer `t()` or component code for long
279
624
  lists.
280
625
 
281
- ## ICU messages
626
+ ### ICU messages
282
627
 
283
628
  Supported subset (MF1): `{name}` interpolation, `{n, plural, …}` (with `offset:`),
284
629
  `{n, selectordinal, …}`, `{x, select, …}`, `#`, `{n, number[, style]}`,
@@ -313,7 +658,7 @@ Supported subset (MF1): `{name}` interpolation, `{n, plural, …}` (with `offset
313
658
  - Templates are compiled once into a cached AST, so a message rendered on every
314
659
  change-detection pass is not re-parsed.
315
660
 
316
- ## Missing keys
661
+ ### Missing keys
317
662
 
318
663
  A key is missing only when it is absent from the current dictionary, absent from the
319
664
  fallback dictionary, and no `defaultValue` was supplied. It is reported **once per key
@@ -339,7 +684,7 @@ provideRiviniaI18n({
339
684
  Without `onMissingKey`, a `console.warn` is logged once per key in dev mode. Set
340
685
  `warnOnMissingKey: false` to silence it, or `true` to keep it in production.
341
686
 
342
- ## Missing parameters
687
+ ### Missing parameters
343
688
 
344
689
  A message that needs `{name}` but receives no `name` keeps the placeholder — it is
345
690
  never replaced with `undefined`. Report it the same way as missing keys:
@@ -355,7 +700,7 @@ Without `onMissingParam`, dev mode logs one warning per (key, param) pair. Set
355
700
  `warnOnMissingParam: false` to silence it. The hook is delivered from a microtask,
356
701
  so it may write signals, and `i18n.clearMissingParams()` resets the dedupe.
357
702
 
358
- ## Fallback language
703
+ ### Fallback language
359
704
 
360
705
  Lookup order for `translate(key)`:
361
706
 
@@ -373,7 +718,27 @@ the current dictionary is what the UI needs. It is transferred with the rest of
373
718
  so hydration does not fetch it again. With `preload: false`, the fallback works from
374
719
  cache/inline dictionaries only.
375
720
 
376
- ## Reloading a dictionary
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
377
742
 
378
743
  ```ts
379
744
  await i18n.reload(); // current + fallback; drops every other cached language
@@ -392,7 +757,7 @@ A typical deploy hook:
392
757
  window.addEventListener('focus', () => void i18n.reload());
393
758
  ```
394
759
 
395
- ## `t()` signals
760
+ ### `t()` signals
396
761
 
397
762
  ```ts
398
763
  readonly title = this.i18n.t('app.title');
@@ -407,7 +772,7 @@ in a microtask because Angular forbids signal writes inside a `computed`.
407
772
  Use it for component fields. For a template expression that runs on every change
408
773
  detection, `translate()` or the pipe is cheaper.
409
774
 
410
- ## Typed keys
775
+ ### Typed keys reference
411
776
 
412
777
  The registry is empty by default, so `RegisteredI18nKey` resolves to `string` and nothing
413
778
  breaks. Generate the declaration from a dictionary to make a typo a compile error:
@@ -450,7 +815,309 @@ the base string but absent from the translation. Placeholders inside plural/sele
450
815
  branches are compared too; branch text itself is never read as a parameter. Any
451
816
  mismatch exits 1, so CI fails on the common "added to `en.json`, forgot `ar.json`" bug.
452
817
 
453
- ## SSR
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
454
1121
 
455
1122
  The default loader works on the server: `REQUEST` plus `<base href>` produce an absolute
456
1123
  URL, so Node's `fetch` never sees a relative path. The rendered dictionaries go into the
@@ -461,7 +1128,7 @@ URL, so Node's `fetch` never sees a relative path. The rendered dictionaries go
461
1128
  and the default loader fails there — the same as any other library that needs the
462
1129
  request origin.
463
1130
  - **Provide the serializer in the app injector.** `renderApplication` serializes the
464
- *platform* `TransferState`, while `bootstrapApplication` gives the app its own root
1131
+ _platform_ `TransferState`, while `bootstrapApplication` gives the app its own root
465
1132
  injector, so dictionaries loaded by the service land in a different instance. Register
466
1133
  a `BEFORE_APP_SERIALIZED` callback (or `provideServerRendering()`) in the app providers.
467
1134
  - **Serve the CSR shell as the template.** With `outputMode: 'server'` the builder
@@ -479,7 +1146,51 @@ A complete, runnable host lives in `projects/i18n-e2e` (`node:http` +
479
1146
  `renderApplication`, no Express), with `e2e/ssr-smoke.mjs` asserting the raw HTML, the
480
1147
  server log, the transfer payload, the absence of a client refetch, and hydration.
481
1148
 
482
- ## Migration: 0.5.0 → 0.6.0
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
483
1194
 
484
1195
  0.6.0 is a breaking minor (the pre-1.0 policy allows it). The core split (RIV-18) is
485
1196
  internal — no signature changed — but three compatibility names are gone:
@@ -499,7 +1210,7 @@ internal — no signature changed — but three compatibility names are gone:
499
1210
  3. **`loadTranslations(id, { silent })` is now `loadTranslations(id)`.** `silent` never
500
1211
  did anything — background loads are an internal concern.
501
1212
 
502
- ## Migration: 0.3.3 → 0.4.0
1213
+ ### Migration 0.3.3 to 0.4.0
503
1214
 
504
1215
  Everything below is additive; no export was removed and no import path changed. Two
505
1216
  behaviour changes are worth reading:
@@ -520,6 +1231,6 @@ New in 0.4.0: `fallbackLanguage`, `onMissingKey`, `warnOnMissingKey`, `missingKe
520
1231
  moved (models/services/utils/providers/pipes) but nothing under `src/` was ever
521
1232
  exported.
522
1233
 
523
- ## License
1234
+ ### License
524
1235
 
525
1236
  MIT.