@rivinia/i18n 0.6.0 → 0.7.1

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