@rivinia/i18n 0.3.0 → 0.3.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.
Files changed (2) hide show
  1. package/README.md +180 -93
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -3,132 +3,219 @@
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
- Headless language manager for Angular 22+. Signals, RTL/LTR, lazy loaders,
7
- ICU plurals (all six Arabic forms), browser detection, Intl formatting —
8
- zero DOM opinions beyond `<html dir/lang>`, zero styling.
6
+ A headless Angular language manager built on signals. It supports key-based
7
+ JSON dictionaries, inline translations, RTL/LTR document attributes, lazy
8
+ loaders, ICU plural/select messages, browser-language detection, and
9
+ ECMAScript internationalization number/date formatting.
9
10
 
10
- - Version: **0.3.0**
11
- - Requires: **Angular `^22.0.0`**, `tslib`
11
+ - Package version: **0.3.2**
12
+ - Peer dependency: **`@angular/core` `^22.0.0`**
13
+ - No `tslib` or `HttpClient` peer dependency. Built-in loaders use `fetch`.
12
14
 
13
- ## Install
15
+ ## Install and configure
14
16
 
15
17
  ```bash
16
18
  npm install @rivinia/i18n
17
- ng add @rivinia/i18n # asks default language + browser detection, wires an ar/en starter
19
+ ng add @rivinia/i18n
18
20
  ```
19
21
 
20
- ## Dictionaries by convention (no config needed)
22
+ `ng add` prompts for language IDs and whether to enable browser detection; the
23
+ first language becomes the default. It wires a starter provider into a
24
+ standalone app's `app.config.ts`. You can configure it yourself instead:
21
25
 
22
- Key-based `translate('booking.seats')` works out of the box with the conventional
23
- layout — the default loader fetches `i18n/{language}.json`
24
- (`public/i18n/ar.json`, `public/i18n/en.json`, … served from the site root;
25
- modern Angular templates map `public/` via `{ "glob": "**/*", "input": "public" }`).
26
- Override only when you differ:
27
-
28
- ```json
29
- // public/i18n/ar.json
30
- { "booking": { "seats": "{count, plural, zero {لا مقاعد} one {مقعد واحد} other {# مقاعد}}" } }
26
+ ```ts
27
+ // src/app/i18n.config.ts
28
+ import { defineRiviniaI18n, jsonLoader } from '@rivinia/i18n';
29
+
30
+ export const i18nConfig = defineRiviniaI18n({
31
+ defaultLanguage: 'en',
32
+ languages: [
33
+ { id: 'en', nativeName: 'English', dir: 'ltr', locale: 'en-US' },
34
+ { id: 'ar', nativeName: 'العربية', dir: 'rtl', locale: 'ar-EG' },
35
+ ],
36
+ detectBrowser: true,
37
+ switchStrategy: 'preload-first',
38
+ loader: jsonLoader(),
39
+ });
31
40
  ```
32
41
 
33
42
  ```ts
34
- // custom path / HTTP endpoint / in-memory (first truth wins):
35
- provideRiviniaI18n({ loader: jsonLoader({ path: '/my-i18n' }), ... });
36
- provideRiviniaI18n({ loader: httpLoader({ endpoint: 'https://api.example.com/i18n' }), ... });
37
- // inline-only apps (zero network): loader: customLoader(async () => ({}))
43
+ // src/app/app.config.ts
44
+ import type { ApplicationConfig } from '@angular/core';
45
+ import { i18nConfig } from './i18n.config';
46
+
47
+ export const appConfig: ApplicationConfig = {
48
+ providers: [i18nConfig.provide()],
49
+ };
38
50
  ```
39
51
 
40
- Loaders code-split: fetch implementations load on first use only.
52
+ `defineRiviniaI18n()` binds the config to typed accessors, so
53
+ `i18nConfig.inject()` retains the `'en' | 'ar'` language type. Alternatively,
54
+ use `provideRiviniaI18n(config)` in the providers array and
55
+ `injectRiviniaI18n<'en' | 'ar'>()` in an injection context.
41
56
 
42
- > **Migration (0.3.0 — breaking default):** the default
43
- > loader path changed from `assets/i18n` to `i18n`. Move
44
- > `src/assets/i18n/*.json` → `public/i18n/*.json` (served from the site root),
45
- > or keep the old layout explicitly with
46
- > `jsonLoader({ path: 'assets/i18n' })`.
57
+ Defaults: `preload: true`, `detectBrowser: false`, local-storage persistence,
58
+ and automatic `<html lang>`/`<html dir>` updates. A stored supported language
59
+ always wins over browser detection. Use `storageStrategy: 'none'` to disable
60
+ persistence; `'session'` and `'cookie'` are also supported.
47
61
 
48
- ## Startup loading (no raw keys on first paint)
62
+ ## Dictionaries
49
63
 
50
- `provideRiviniaI18n()` registers an app initializer that loads the initial
51
- language before first paint (SSR waits via `PendingTasks`):
64
+ By default, `jsonLoader()` fetches `i18n/{language}.json` from the site root.
65
+ For Angular apps using the standard `public/` static-file directory, put
66
+ dictionaries at `public/i18n/en.json`, `public/i18n/ar.json`, and so on. Make
67
+ sure your host serves those files at `/i18n/{language}.json`.
52
68
 
53
- ```ts
54
- provideRiviniaI18n({
55
- // ...
56
- preload: false, // opt out: load manually instead
57
- translations: { ar: { hello: 'مرحبا' } }, // inline seed: instant, zero network,
58
- }); // a successful loader response still wins
59
- ```
69
+ If an existing app still serves dictionaries from `assets/i18n/`, keep that
70
+ layout with `jsonLoader({ path: 'assets/i18n' })` instead.
60
71
 
61
- Gate skeletons on the `ready` signal (true once initial content is available),
62
- not on `isLoading`. Load failures never reject setup — they land on
63
- `loadingError`/`onLoadError` with safe fallbacks preserved.
72
+ ```json
73
+ // public/i18n/en.json
74
+ {
75
+ "booking": {
76
+ "seats": "{count, plural, =0 {No seats} one {# seat} other {# seats}}"
77
+ }
78
+ }
79
+ ```
64
80
 
65
- ## Persistence and SSR
81
+ ```json
82
+ // public/i18n/ar.json
83
+ {
84
+ "booking": {
85
+ "seats": "{count, plural, zero {لا مقاعد} one {مقعد واحد} two {مقعدان} few {# مقاعد} many {# مقعدًا} other {# مقعد}}"
86
+ }
87
+ }
88
+ ```
66
89
 
67
- - `storageStrategy: 'cookie'` syncs SSR and browser through one cookie:
68
- the server reads the request cookie (correct first paint, no hydration
69
- mismatch), the browser writes it. `local`/`session` fall back to the
70
- default language on the server.
71
- - Dictionaries loaded on the server travel to the browser via `TransferState`
72
- (no double fetch). The `<html dir/lang>` effect uses injected `DOCUMENT`,
73
- so it renders on the server too.
90
+ The default loader does not use `HttpClient`. To use a different JSON path or
91
+ an endpoint, pass a loader descriptor:
74
92
 
75
93
  ```ts
76
- // app.config.ts
77
- import { provideRiviniaI18n } from '@rivinia/i18n';
78
-
79
- providers: [
80
- provideRiviniaI18n({
81
- defaultLanguage: 'ar',
82
- languages: [
83
- { id: 'ar', nativeName: 'العربية', dir: 'rtl' },
84
- { id: 'en', nativeName: 'English', dir: 'ltr' },
85
- ],
86
- }),
87
- ];
94
+ import { httpLoader, jsonLoader, remoteLoader } from '@rivinia/i18n';
95
+
96
+ jsonLoader({ path: '/my-i18n' }); // fetches /my-i18n/{language}.json
97
+ httpLoader({ endpoint: 'https://api.example.com/i18n' }); // appends /{language}
98
+ remoteLoader({
99
+ url: (language) => `https://api.example.com/v2/${language}`,
100
+ headers: { Authorization: 'Bearer …' },
101
+ });
88
102
  ```
89
103
 
90
- ## Quick start
104
+ All loaders are resolved lazily; their fetch implementations are loaded only
105
+ when needed. A custom loader can also use an in-memory dictionary or another
106
+ data source:
91
107
 
92
108
  ```ts
93
- export class Header {
94
- i18n = injectRiviniaI18n();
95
- save = () => this.i18n.translate({ ar: 'حفظ', en: 'Save' });
96
- seats = (n: number) => this.i18n.translate('booking.seats', { count: n });
97
- }
109
+ import { customLoader } from '@rivinia/i18n';
110
+
111
+ const inMemoryLoader = customLoader(async (language: 'en' | 'ar') => {
112
+ const dictionaries = {
113
+ en: { greeting: 'Hello' },
114
+ ar: { greeting: 'مرحبًا' },
115
+ };
116
+ return dictionaries[language];
117
+ });
98
118
  ```
99
119
 
100
- ```json
101
- // public/i18n/en.json
102
- { "booking": { "seats": "{count, plural, one {# seat} other {# seats}}" } }
120
+ Pass that descriptor as `loader: inMemoryLoader` in the provider config.
121
+
122
+ ## Use in a standalone component
123
+
124
+ `provideRiviniaI18n()` registers an app initializer that loads the initial
125
+ language before first paint. The `ready` signal becomes true when initial
126
+ content is available or initial loading has settled; it is more useful for
127
+ initial skeletons than `isLoading`.
128
+
129
+ ```ts
130
+ // src/app/header.component.ts
131
+ import { Component } from '@angular/core';
132
+ import { RTranslatePipe } from '@rivinia/i18n';
133
+ import { i18nConfig } from './i18n.config';
134
+
135
+ @Component({
136
+ selector: 'app-header',
137
+ standalone: true,
138
+ imports: [RTranslatePipe],
139
+ templateUrl: './header.component.html',
140
+ })
141
+ export class HeaderComponent {
142
+ readonly i18n = i18nConfig.inject();
143
+ readonly seatCount = 3;
144
+ readonly price = 12.5;
145
+ }
103
146
  ```
104
147
 
105
148
  ```html
106
- <p>{{ i18n.translate({ ar: 'مرحبا', en: 'Hello' }) }}</p>
107
- <p>{{ 'booking.seats' | rTranslate:{ count: seats() } }}</p>
149
+ <!-- src/app/header.component.html -->
150
+ @if (i18n.ready()) {
151
+ <p>{{ i18n.translate({ en: 'Welcome', ar: 'أهلاً' }) }}</p>
152
+ <p>{{ 'booking.seats' | rTranslate: { count: seatCount } }}</p>
153
+ <p>{{ i18n.formatNumber(price, { style: 'currency', currency: 'USD' }) }}</p>
154
+ <button type="button" (click)="i18n.setLanguage('ar')">العربية</button>
155
+ <button type="button" (click)="i18n.setLanguage('en')">English</button>
156
+ } @else {
157
+ <p>Loading…</p>
158
+ }
108
159
  ```
109
160
 
110
- ## API
111
-
112
- | Export | Kind | Purpose |
113
- | ------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
114
- | `provideRiviniaI18n(config)` | provider | languages, default, storage (+`cookie`), loader, `detectBrowser?` (off), `switchStrategy?`, `preload?`, `translations?` (inline seed) |
115
- | `RiviniaI18n` | `@Service()` | signals (`locale`, `ready`) + `translate/setLanguage(toggle/next/previous)/loadTranslations/formatNumber/formatDate` |
116
- | `injectRiviniaI18n()` | function | shorthand, preserves the language union; `defineRiviniaI18n(config)` binds config + accessors with inference |
117
- | `jsonLoader/httpLoader/remoteLoader/customLoader` | loaders | lazy code-split dictionaries (fetch, no HttpClient) |
118
- | `formatIcu(template, params, locale)` | util | ICU subset: plural/select/`#`/nesting via native `Intl.PluralRules` |
119
- | `detectBrowserLanguage(ids, langs)` | util | in-order priority + base-tag fallback (`ar-EG` → `ar`), pure/testable |
120
- | `parseCookie/serializeCookie` | utils | cookie strategy primitives (server header / browser cookie) |
121
- | `RTranslatePipe` | pipe | `rTranslate` (impure by necessity — prefer `translate()` in code for lists) |
122
- | types | types | `RiviniaI18nConfig`, `Language` (+`locale?`), `Translation`, `LoaderDescriptor`, … |
123
-
124
- Dictionaries commit to visible signals only for the currently intended
125
- language — out-of-order responses stay cached. `setLanguageAsync` aborts on
126
- load failure (language, direction and dictionary untouched). ICU subset is
127
- deliberately small (`plural`/`select` only) — full ICU belongs to
128
- FormatJS, not to a 10 kB core. Malformed templates render raw, never throw.
129
- Stored preference always beats browser detection; detection runs only when
130
- nothing is stored. `switchStrategy: 'preload-first'` (or `setLanguageAsync`)
131
- avoids raw-key flashes on route switches.
161
+ For key lookup, `translate('booking.seats', { count: 3 })` is also available.
162
+ Missing keys return the key itself, or the supplied fallback:
163
+ `translate('missing.key', 'Not available')`. Inline language maps fall back to
164
+ their first value if the active language is absent. `RTranslatePipe` is
165
+ impure so it reevaluates when the language changes; for long lists, prefer
166
+ calling `translate()` in component code.
167
+
168
+ ## Loading, switching, and SSR
169
+
170
+ - Initial language loading is enabled by default. Set `preload: false` to skip
171
+ the initial request; the service then marks `ready()` true immediately.
172
+ - `translations` can seed inline dictionaries before the initial request. A
173
+ successful loader response replaces the seed; if loading fails, the seed
174
+ remains visible. For an app with no network, pair inline translations with
175
+ a `customLoader` or disable preloading as appropriate.
176
+ - Load failures do not reject provider initialization. Inspect
177
+ `loadingState()`/`loadingError()` or handle them with `onLoadError`; lookups
178
+ still fall back to the key or supplied fallback.
179
+ - `switchStrategy: 'instant'` changes language immediately and loads in the
180
+ background. `'preload-first'` waits for the new dictionary; a failed load
181
+ leaves the current language and direction unchanged. You can also call and
182
+ await `setLanguageAsync(id)` explicitly.
183
+ - `loadTranslations(id)` preloads a dictionary without switching. Dictionaries
184
+ are cached by language; out-of-order responses do not replace the currently
185
+ displayed language.
186
+ - For SSR, dictionaries are transferred to the browser to avoid a second
187
+ fetch. `storageStrategy: 'cookie'` reads the request cookie on the server
188
+ and writes it in the browser, keeping the initial language consistent.
189
+ Local/session storage are unavailable on the server and fall back to the
190
+ configured default or browser detection.
191
+
192
+ ## ICU messages and formatting
193
+
194
+ The supported ICU subset is plain `{name}` interpolation, `{count, plural,
195
+ ...}`, `{gender, select, ...}`, nested messages, exact numeric selectors such
196
+ as `=0`, and `#` inside a plural. Selection follows the platform's plural
197
+ rules for the configured locale; dictionaries can provide all six Arabic
198
+ categories. This is not full ICU MessageFormat; date/time and number
199
+ formatting are separate `formatDate()` and `formatNumber()` methods. Malformed
200
+ or unsupported messages render as raw text rather than throwing.
201
+
202
+ Set `locale` on a language entry when the language ID alone is not the desired
203
+ formatting locale. For example, the Arabic-Egypt locale can request its
204
+ appropriate digit conventions.
205
+
206
+ ## Public API
207
+
208
+ | Export | Kind | Purpose |
209
+ | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | -------------------------------------------------------------------------- |
210
+ | `provideRiviniaI18n(config)` | Provider | Configure languages, loader, persistence, startup loading, and switching. |
211
+ | `defineRiviniaI18n(config)` | Helper | Bind config and preserve the configured language union in `inject()`. |
212
+ | `RiviniaI18n`, `injectRiviniaI18n()` | Service / function | Language, direction, loading, translation, switching, and formatting APIs. |
213
+ | `RTranslatePipe` | Pipe | Template pipe named `rTranslate`. |
214
+ | `jsonLoader`, `httpLoader`, `remoteLoader`, `customLoader` | Loaders | Lazy descriptors for fetch-based or custom dictionary loading. |
215
+ | `formatIcu`, `detectBrowserLanguage`, `browserLanguages` | Utilities | Format the supported ICU subset; inspect browser language matches. |
216
+ | `parseCookie`, `serializeCookie` | Utilities | Cookie strategy helpers. |
217
+ | `ViewTransitionService` | Service | View-transition integration used by the optional config. |
218
+ | `Language`, `Translation`, `TranslateParams`, `RiviniaI18nConfig`, `StorageStrategy`, `SwitchStrategy`, `LoaderDescriptor`, `TranslationLoader` | Types | Configuration, dictionary, and loader types. |
132
219
 
133
220
  ## License
134
221
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rivinia/i18n",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Headless language manager for Angular: signals, RTL, loaders, ICU plurals, browser detection, Intl formatting.",
5
5
  "keywords": [
6
6
  "angular",