@sixbell-telco/sdk 1.6.0 → 2.0.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.
Files changed (116) hide show
  1. package/CHANGELOG.md +196 -711
  2. package/README.md +307 -282
  3. package/_index.css +3 -3
  4. package/components/audio-player/audio-timeline/audio-timeline.component.d.ts +1 -1
  5. package/components/audio-player/services/audio.service.d.ts +14 -14
  6. package/components/countdown/src/countdown.component.d.ts +1 -1
  7. package/components/dropdown-menu/src/dropdown-menu-content/dropdown-menu-content.component.d.ts +2 -3
  8. package/components/dual-list/src/dual-list.component.d.ts +2 -1
  9. package/components/file-upload/file-dropzone/file-dropzone.component.d.ts +7 -7
  10. package/components/file-upload/file-uploader/file-uploader.component.d.ts +7 -7
  11. package/components/forms/input/src/input.component.d.ts +11 -1
  12. package/components/forms/textarea/src/textarea.component.d.ts +10 -10
  13. package/components/link/src/link.component.d.ts +0 -3
  14. package/components/tab/directives/tab-content/tab-content.directive.d.ts +3 -3
  15. package/components/tab/directives/tab-header/tab-header.directive.d.ts +2 -2
  16. package/components/wizard/services/wizard.service.d.ts +5 -5
  17. package/directives/auto-focus/public-api.d.ts +1 -1
  18. package/directives/auto-focus/src/{autofocus.directive.d.ts → auto-focus.directive.d.ts} +5 -7
  19. package/directives/only-numbers/public-api.d.ts +6 -1
  20. package/directives/only-numbers/src/only-numbers.directive.d.ts +37 -0
  21. package/fesm2022/sixbell-telco-sdk-components-audio-player.mjs +7 -5
  22. package/fesm2022/sixbell-telco-sdk-components-audio-player.mjs.map +1 -1
  23. package/fesm2022/sixbell-telco-sdk-components-avatar.mjs +1 -1
  24. package/fesm2022/sixbell-telco-sdk-components-avatar.mjs.map +1 -1
  25. package/fesm2022/sixbell-telco-sdk-components-badge.mjs +2 -2
  26. package/fesm2022/sixbell-telco-sdk-components-badge.mjs.map +1 -1
  27. package/fesm2022/sixbell-telco-sdk-components-countdown.mjs.map +1 -1
  28. package/fesm2022/sixbell-telco-sdk-components-data-table.mjs +2 -2
  29. package/fesm2022/sixbell-telco-sdk-components-data-table.mjs.map +1 -1
  30. package/fesm2022/sixbell-telco-sdk-components-dropdown-menu.mjs +0 -4
  31. package/fesm2022/sixbell-telco-sdk-components-dropdown-menu.mjs.map +1 -1
  32. package/fesm2022/sixbell-telco-sdk-components-dual-list.mjs +8 -7
  33. package/fesm2022/sixbell-telco-sdk-components-dual-list.mjs.map +1 -1
  34. package/fesm2022/sixbell-telco-sdk-components-file-upload.mjs +6 -4
  35. package/fesm2022/sixbell-telco-sdk-components-file-upload.mjs.map +1 -1
  36. package/fesm2022/sixbell-telco-sdk-components-forms-date-picker.mjs +2 -0
  37. package/fesm2022/sixbell-telco-sdk-components-forms-date-picker.mjs.map +1 -1
  38. package/fesm2022/sixbell-telco-sdk-components-forms-input.mjs +15 -5
  39. package/fesm2022/sixbell-telco-sdk-components-forms-input.mjs.map +1 -1
  40. package/fesm2022/sixbell-telco-sdk-components-forms-select.mjs +2 -2
  41. package/fesm2022/sixbell-telco-sdk-components-forms-select.mjs.map +1 -1
  42. package/fesm2022/sixbell-telco-sdk-components-forms-textarea.mjs +19 -8
  43. package/fesm2022/sixbell-telco-sdk-components-forms-textarea.mjs.map +1 -1
  44. package/fesm2022/sixbell-telco-sdk-components-link.mjs +2 -7
  45. package/fesm2022/sixbell-telco-sdk-components-link.mjs.map +1 -1
  46. package/fesm2022/sixbell-telco-sdk-components-overlay.mjs +2 -2
  47. package/fesm2022/sixbell-telco-sdk-components-overlay.mjs.map +1 -1
  48. package/fesm2022/sixbell-telco-sdk-components-tab.mjs.map +1 -1
  49. package/fesm2022/sixbell-telco-sdk-components-wizard.mjs.map +1 -1
  50. package/fesm2022/sixbell-telco-sdk-directives-auto-focus.mjs +14 -31
  51. package/fesm2022/sixbell-telco-sdk-directives-auto-focus.mjs.map +1 -1
  52. package/fesm2022/sixbell-telco-sdk-directives-only-numbers.mjs +42 -8
  53. package/fesm2022/sixbell-telco-sdk-directives-only-numbers.mjs.map +1 -1
  54. package/fesm2022/sixbell-telco-sdk-utils-date.mjs +1 -1
  55. package/fesm2022/sixbell-telco-sdk-utils-date.mjs.map +1 -1
  56. package/fesm2022/sixbell-telco-sdk-utils-pipes-to-bytes-extesion.mjs +1 -1
  57. package/fesm2022/sixbell-telco-sdk-utils-pipes-to-bytes-extesion.mjs.map +1 -1
  58. package/fesm2022/sixbell-telco-sdk-utils-runtime-config.mjs +339 -0
  59. package/fesm2022/sixbell-telco-sdk-utils-runtime-config.mjs.map +1 -0
  60. package/fesm2022/sixbell-telco-sdk-utils-sync.mjs +1 -1
  61. package/fesm2022/sixbell-telco-sdk-utils-sync.mjs.map +1 -1
  62. package/fesm2022/sixbell-telco-sdk-utils-theme.mjs +1053 -716
  63. package/fesm2022/sixbell-telco-sdk-utils-theme.mjs.map +1 -1
  64. package/fesm2022/sixbell-telco-sdk-utils-translation.mjs +345 -257
  65. package/fesm2022/sixbell-telco-sdk-utils-translation.mjs.map +1 -1
  66. package/package.json +67 -66
  67. package/utils/runtime-config/README.md +235 -0
  68. package/utils/{resource-loader → runtime-config}/index.d.ts +1 -1
  69. package/utils/runtime-config/public-api.d.ts +5 -0
  70. package/utils/runtime-config/src/http-client.d.ts +11 -0
  71. package/utils/runtime-config/src/runtime-config-loader.d.ts +23 -0
  72. package/utils/runtime-config/src/runtime-config-store.d.ts +11 -0
  73. package/utils/runtime-config/src/runtime-update-adapter.d.ts +15 -0
  74. package/utils/runtime-config/src/types.d.ts +66 -0
  75. package/utils/theme/README.md +324 -986
  76. package/utils/theme/public-api.d.ts +4 -4
  77. package/utils/theme/src/constants.d.ts +6 -12
  78. package/utils/theme/src/models/theme.d.ts +46 -173
  79. package/utils/theme/src/providers/theme.provider.d.ts +0 -10
  80. package/utils/theme/src/providers/theme.provider.types.d.ts +16 -15
  81. package/utils/theme/src/theme-assets/theme-assets.service.d.ts +16 -12
  82. package/utils/theme/src/theme-dom/theme-dom.service.d.ts +8 -0
  83. package/utils/theme/src/theme.service.d.ts +24 -27
  84. package/utils/theme/src/utils/utils.d.ts +2 -10
  85. package/utils/translation/README.md +170 -1390
  86. package/utils/translation/public-api.d.ts +3 -3
  87. package/utils/translation/src/constants.d.ts +7 -9
  88. package/utils/translation/src/models/translation.d.ts +9 -10
  89. package/utils/translation/src/providers/translation.provider.d.ts +17 -28
  90. package/utils/translation/src/providers/translation.provider.types.d.ts +13 -6
  91. package/utils/translation/src/translation.service.d.ts +37 -9
  92. package/directives/only-numbers/src/just-numbers.directive.d.ts +0 -9
  93. package/fesm2022/sixbell-telco-sdk-utils-resource-loader.mjs +0 -1222
  94. package/fesm2022/sixbell-telco-sdk-utils-resource-loader.mjs.map +0 -1
  95. package/utils/resource-loader/README.md +0 -460
  96. package/utils/resource-loader/public-api.d.ts +0 -1
  97. package/utils/resource-loader/src/cache/index.d.ts +0 -2
  98. package/utils/resource-loader/src/cache/layers/factory.d.ts +0 -38
  99. package/utils/resource-loader/src/cache/layers/index.d.ts +0 -3
  100. package/utils/resource-loader/src/cache/layers/indexed-db-cache.d.ts +0 -118
  101. package/utils/resource-loader/src/cache/layers/local-storage-cache.d.ts +0 -86
  102. package/utils/resource-loader/src/cache/layers/memory-cache.d.ts +0 -76
  103. package/utils/resource-loader/src/cache/types.d.ts +0 -107
  104. package/utils/resource-loader/src/config/index.d.ts +0 -1
  105. package/utils/resource-loader/src/config/load-config.d.ts +0 -32
  106. package/utils/resource-loader/src/constants.d.ts +0 -38
  107. package/utils/resource-loader/src/http/index.d.ts +0 -1
  108. package/utils/resource-loader/src/http/retryable-client.d.ts +0 -43
  109. package/utils/resource-loader/src/index.d.ts +0 -1
  110. package/utils/resource-loader/src/resource-loader.d.ts +0 -67
  111. package/utils/resource-loader/src/types.d.ts +0 -152
  112. package/utils/resource-loader/src/utils/cache-validator.d.ts +0 -72
  113. package/utils/resource-loader/src/utils/helpers.d.ts +0 -15
  114. package/utils/resource-loader/src/utils/index.d.ts +0 -2
  115. package/utils/theme/src/providers/constants.d.ts +0 -7
  116. package/utils/translation/src/providers/constants.d.ts +0 -11
@@ -1,1512 +1,292 @@
1
1
  # Translation Utility
2
2
 
3
- A comprehensive, signal-based internationalization (i18n) system for Angular 19 applications with multi-language support, runtime configuration loading, persistent storage, and seamless ngx-translate integration.
3
+ Runtime i18n system for Angular 19 with ngx-translate integration, runtime config loading, and resilient caching.
4
4
 
5
- ## Quick Start
5
+ This doc covers:
6
6
 
7
- ### Basic Setup
7
+ - Translation config schema
8
+ - Loading flow and cache behavior
9
+ - Language switching and prefetch
10
+ - Examples for initialization and usage
11
+ - Runtime update handling
12
+
13
+ ---
14
+
15
+ ## Quick Start
8
16
 
9
17
  ```typescript
10
18
  import { provideRuntimeTranslation } from '@sixbell-telco/sdk/utils/translation';
11
19
 
12
20
  bootstrapApplication(AppComponent, {
13
- providers: [provideRuntimeTranslation('/assets/config/translation-config.json')],
21
+ providers: [provideRuntimeTranslation('/assets/translation/translation.json')],
14
22
  });
15
23
  ```
16
24
 
17
- ### Using the Translation Service
18
-
19
- ```typescript
20
- import { Component, ChangeDetectionStrategy, inject } from '@angular/core';
21
- import { TranslationService, TranslatePipe } from '@sixbell-telco/sdk/utils/translation';
22
- import {
23
- DropdownComponent,
24
- DropdownTriggerComponent,
25
- DropdownContentComponent,
26
- DropdownItemRadioComponent,
27
- } from '@sixbell-telco/sdk/components/dropdown';
28
- import { ButtonComponent } from '@sixbell-telco/sdk/components/button';
29
-
30
- @Component({
31
- selector: 'app-language-switcher',
32
- standalone: true,
33
- imports: [TranslatePipe, ButtonComponent, DropdownComponent, DropdownTriggerComponent, DropdownContentComponent, DropdownItemRadioComponent],
34
- changeDetection: ChangeDetectionStrategy.OnPush,
35
- template: `
36
- <div class="language-switcher">
37
- <st-dropdown>
38
- <st-dropdown-trigger>
39
- <st-button>
40
- {{ translationService.getLanguageName(translationService.currentLanguage()) }}
41
- </st-button>
42
- </st-dropdown-trigger>
43
- <st-dropdown-content>
44
- @for (lang of translationService.getAvailableLanguages(); track lang.code) {
45
- <st-dropdown-item-radio
46
- [value]="lang.code"
47
- [checked]="translationService.currentLanguage() === lang.code"
48
- (checkedChanged)="translationService.setLanguage($event)"
49
- >
50
- {{ lang.name }}
51
- </st-dropdown-item-radio>
52
- }
53
- </st-dropdown-content>
54
- </st-dropdown>
55
- </div>
56
- `,
57
- })
58
- export class LanguageSwitcherComponent {
59
- protected translationService = inject(TranslationService);
60
- }
61
- ```
62
-
63
- ## Features
64
-
65
- ### 🌐 Multi-Language Support
66
-
67
- - **Base Languages**: English, Spanish, Portuguese (out of the box)
68
- - **Extensible**: Add custom languages easily
69
- - **Language Filtering**: Exclude specific languages when needed
70
- - **Language Metadata**: Display names and language codes
71
-
72
- ### 💾 Persistence
73
-
74
- - **localStorage Integration**: Automatic saving/loading of user language preferences
75
- - **Error Handling**: Graceful fallback when storage is unavailable (SSR, private browsing)
76
- - **Multi-Key Storage**: Namespace isolation to prevent collisions
77
-
78
- ### 🚀 Runtime Configuration
79
-
80
- - **Dynamic Config Loading**: Load language configuration from remote URLs
81
- - **Smart Caching**: IndexedDB for long-term persistence + in-memory for current session
82
- - **Fallback Strategies**: Stale-while-revalidate, use-stale-on-error for resilience
83
- - **Multi-Path Loading**: Support for multiple translation file sources
84
-
85
- ### 🔄 ngx-translate Integration
86
-
87
- - **Seamless Integration**: Full compatibility with ngx-translate/core
88
- - **TranslatePipe**: Ready-to-use pipe for template translation
89
- - **Instant Translation**: Programmatic translation with `instant()` method
90
- - **Async Translation**: Observable-based translation with `get()` method
91
-
92
- ### 📱 Signals-Based Reactivity
93
-
94
- - **Current Language Signal**: Reactive language selection
95
- - **Ready State**: Know when translations are loaded
96
- - **Language Change Events**: React to language changes with observables
97
- - **DOM Integration**: Automatic `lang` attribute updates on document element
98
-
99
- ### 🏢 Multi-Tenant Support
100
-
101
- - **Runtime Language Configuration**: Load language settings from remote source
102
- - **Dynamic Paths**: Specify custom translation file locations
103
- - **Custom Loader Options**: Fine-tune caching and loading behavior
104
-
105
- ## Installation
106
-
107
- The translation utility is built into `@sixbell-telco/sdk`:
108
-
109
- ```bash
110
- npm install @sixbell-telco/sdk
111
- ```
112
-
113
- Import from the specific entry point:
114
-
115
- ```typescript
116
- import { TranslationService, provideRuntimeTranslation } from '@sixbell-telco/sdk/utils/translation';
117
- import { TranslatePipe } from '@sixbell-telco/sdk/utils/translation';
118
- ```
119
-
120
- ## API Reference
121
-
122
- ### TranslationService
123
-
124
- Main service for managing language state and translation operations.
125
-
126
- #### Signals (Reactive)
127
-
128
- ```typescript
129
- // Currently selected language code (e.g., 'en', 'es', 'pt')
130
- currentLanguage: Signal<string>;
131
-
132
- // Ready state - true when translations are fully loaded
133
- ready: Signal<boolean>;
134
-
135
- // Language change notification signal (useful for triggering effects)
136
- onLanguageChange: Signal<number>;
137
- ```
138
-
139
- #### Observables
140
-
141
- ```typescript
142
- // Observable that fires when language changes
143
- onLanguageChange$: Observable<LangChangeEvent>;
144
- ```
145
-
146
- #### Methods
147
-
148
- ```typescript
149
- // Change the active language
150
- setLanguage(lang: string): void;
151
-
152
- // Get all available languages with metadata
153
- getAvailableLanguages(): LanguageDefinition[];
154
-
155
- // Get default language code
156
- getDefaultLanguage(): string;
157
-
158
- // Get localized name for a language
159
- getLanguageName(langCode: string): string;
160
-
161
- // Translate a key instantly (synchronous)
162
- instant(key: string, params?: Record<string, unknown>): string;
163
-
164
- // Translate a key asynchronously (returns Observable)
165
- get(key: string, params?: Record<string, unknown>): Observable<string>;
166
-
167
- // Stream translations (useful for subscriptions)
168
- stream(key: string, params?: Record<string, unknown>): Observable<string>;
169
-
170
- // Configure static translation settings
171
- configure(config?: TranslationConfig): void;
172
-
173
- // Set runtime configuration from external source
174
- async setRuntimeConfig(config: TranslationConfig): Promise<void>;
175
-
176
- // Initialize translation service
177
- init(): void;
178
-
179
- // Check if service is ready
180
- isReady(): boolean;
181
-
182
- // Wait for translations to load (with timeout)
183
- async waitForTranslations(timeoutMs?: number): Promise<void>;
184
-
185
- // Load saved language preference from storage
186
- loadSavedPreferences(): void;
187
-
188
- // Check if a specific language is available
189
- isLanguageAvailable(lang: string): boolean;
190
- ```
191
-
192
- ### TranslationStorageService
193
-
194
- Handles persistent storage of language preferences.
195
-
196
- ```typescript
197
- // Save current language to localStorage
198
- saveLanguage(language: string): void;
199
-
200
- // Retrieve saved language
201
- getSavedLanguage(): string | null;
202
-
203
- // Clear all saved preferences
204
- clear(): void;
205
- ```
206
-
207
- ### TranslationDomService
208
-
209
- Handles DOM manipulation related to language/localization.
210
-
211
- ```typescript
212
- // Set the lang attribute on document element
213
- setDocumentLanguage(language: string): void;
214
-
215
- // Get current language from document element
216
- getDocumentLanguage(): string;
217
- ```
218
-
219
- ### Providers
220
-
221
- #### provideRuntimeTranslation(configPath, options?)
222
-
223
- Load translation configuration from a remote URL and set up ngx-translate.
224
-
225
- ```typescript
226
- providers: [
227
- provideRuntimeTranslation('/api/v1/languages/config.json', {
228
- loaderOptions: {
229
- cacheName: 'translation-config',
230
- cacheTTL: 1000 * 60 * 60 * 12, // 12 hours
231
- freshOnNavigation: true,
232
- staleWhileRevalidate: true,
233
- useStaleOnError: true,
234
- retries: 3,
235
- },
236
- }),
237
- ];
238
- ```
239
-
240
- #### provideTranslation(config?)
241
-
242
- Configure static translation settings (deprecated - use `provideRuntimeTranslation` instead).
243
-
244
- ```typescript
245
- providers: [
246
- provideTranslation({
247
- defaultLang: 'en',
248
- additionalLanguages: [
249
- { code: 'de', name: 'Deutsch' },
250
- { code: 'fr', name: 'Français' },
251
- ],
252
- excludeLanguages: ['pt'],
253
- }),
254
- ];
255
- ```
256
-
257
- ## Common Scenarios
258
-
259
- ### Scenario 1: Basic Language Switching
25
+ In a component:
260
26
 
261
27
  ```typescript
262
28
  import { Component, ChangeDetectionStrategy, inject } from '@angular/core';
29
+ import { TranslatePipe } from '@ngx-translate/core';
263
30
  import { TranslationService } from '@sixbell-telco/sdk/utils/translation';
264
- import { ButtonComponent } from '@sixbell-telco/sdk/components/button';
265
- import {
266
- DropdownComponent,
267
- DropdownTriggerComponent,
268
- DropdownContentComponent,
269
- DropdownItemRadioComponent,
270
- } from '@sixbell-telco/sdk/components/dropdown';
271
31
 
272
32
  @Component({
273
- selector: 'app-language-selector',
274
- standalone: true,
275
- imports: [ButtonComponent, DropdownComponent, DropdownTriggerComponent, DropdownContentComponent, DropdownItemRadioComponent],
276
- changeDetection: ChangeDetectionStrategy.OnPush,
277
- template: `
278
- <div class="language-selector">
279
- <label>Select Language:</label>
280
- <st-dropdown>
281
- <st-dropdown-trigger>
282
- <st-button>{{ getCurrentLanguageName() }}</st-button>
283
- </st-dropdown-trigger>
284
- <st-dropdown-content>
285
- @for (lang of languages; track lang.code) {
286
- <st-dropdown-item-radio
287
- [value]="lang.code"
288
- [checked]="translationService.currentLanguage() === lang.code"
289
- (checkedChanged)="onLanguageChange($event)"
290
- >
291
- {{ lang.name }}
292
- </st-dropdown-item-radio>
293
- }
294
- </st-dropdown-content>
295
- </st-dropdown>
296
- <p>Current: {{ translationService.currentLanguage() }}</p>
297
- </div>
298
- `,
299
- })
300
- export class LanguageSelectorComponent {
301
- protected readonly translationService = inject(TranslationService);
302
- languages = this.translationService.getAvailableLanguages();
303
-
304
- getCurrentLanguageName(): string {
305
- return this.translationService.getLanguageName(this.translationService.currentLanguage());
306
- }
307
-
308
- onLanguageChange(langCode: string): void {
309
- this.translationService.setLanguage(langCode);
310
- }
311
- }
312
- ```
313
-
314
- ### Scenario 2: Template Translation with Pipe
315
-
316
- ```typescript
317
- import { Component, ChangeDetectionStrategy } from '@angular/core';
318
- import { TranslatePipe } from '@sixbell-telco/sdk/utils/translation';
319
-
320
- @Component({
321
- selector: 'app-content',
33
+ selector: 'app-language-status',
322
34
  standalone: true,
323
35
  imports: [TranslatePipe],
324
36
  changeDetection: ChangeDetectionStrategy.OnPush,
325
- template: `
326
- <div>
327
- <h1>{{ 'sdk.headers.title' | translate }}</h1>
328
- <p>{{ 'sdk.content.description' | translate }}</p>
329
- <button>{{ 'sdk.buttons.submit' | translate }}</button>
330
- </div>
331
- `,
37
+ template: `{{ 'sdk.title' | translate }} ({{ translationService.currentLanguage() }})`,
332
38
  })
333
- export class ContentComponent {}
334
- ```
335
-
336
- ### Scenario 3: Programmatic Translation
337
-
338
- ```typescript
339
- import { Component, ChangeDetectionStrategy, computed, inject } from '@angular/core';
340
- import { AsyncPipe } from '@angular/common';
341
- import { TranslationService } from '@sixbell-telco/sdk/utils/translation';
342
-
343
- @Component({
344
- selector: 'app-greeting',
345
- standalone: true,
346
- imports: [AsyncPipe],
347
- changeDetection: ChangeDetectionStrategy.OnPush,
348
- template: `
349
- <p>{{ greeting() }}</p>
350
- <p *ngIf="dynamicText$ | async as text">{{ text }}</p>
351
- `,
352
- })
353
- export class GreetingComponent {
354
- private readonly translationService = inject(TranslationService);
355
-
356
- // Synchronous translation (instant)
357
- greeting = computed(() => {
358
- return this.translationService.instant('sdk.common.hello', {
359
- name: 'John',
360
- });
361
- });
362
-
363
- // Asynchronous translation (observable)
364
- dynamicText$ = this.translationService.get('sdk.common.welcome');
365
- }
366
- ```
367
-
368
- ### Scenario 4: Wait for Translations Before Rendering
369
-
370
- ```typescript
371
- import { Component, ChangeDetectionStrategy, inject } from '@angular/core';
372
- import { TranslationService } from '@sixbell-telco/sdk/utils/translation';
373
-
374
- @Component({
375
- selector: 'app-root',
376
- standalone: true,
377
- changeDetection: ChangeDetectionStrategy.OnPush,
378
- template: `
379
- @if (translationService.ready()) {
380
- <app-main-content></app-main-content>
381
- } @else {
382
- <p>Loading translations...</p>
383
- }
384
- `,
385
- })
386
- export class AppComponent {
39
+ export class LanguageStatusComponent {
387
40
  protected readonly translationService = inject(TranslationService);
388
-
389
- constructor() {
390
- // Wait for translations to load before rendering
391
- this.translationService.waitForTranslations(5000).catch(() => console.error('Translations failed to load'));
392
- }
393
41
  }
394
42
  ```
395
43
 
396
- ### Scenario 5: React to Language Changes
397
-
398
- ```typescript
399
- import { Component, ChangeDetectionStrategy, computed, inject } from '@angular/core';
400
- import { TranslationService } from '@sixbell-telco/sdk/utils/translation';
401
-
402
- @Component({
403
- selector: 'app-header',
404
- standalone: true,
405
- changeDetection: ChangeDetectionStrategy.OnPush,
406
- template: `
407
- <header [attr.lang]="translationService.currentLanguage()">
408
- <h1>{{ title() }}</h1>
409
- </header>
410
- `,
411
- })
412
- export class HeaderComponent {
413
- private readonly translationService = inject(TranslationService);
414
-
415
- title = computed(() => {
416
- // React whenever language changes
417
- this.translationService.currentLanguage();
418
- return this.translationService.instant('sdk.headers.appTitle');
419
- });
420
- }
421
- ```
422
-
423
- ### Scenario 6: Multi-Tenant Language Configuration
424
-
425
- ```typescript
426
- import { Component, ChangeDetectionStrategy, inject } from '@angular/core';
427
- import { TranslationService } from '@sixbell-telco/sdk/utils/translation';
428
- import { ButtonComponent } from '@sixbell-telco/sdk/components/button';
429
- import { DropdownComponent, DropdownTriggerComponent, DropdownContentComponent, DropdownItemComponent } from '@sixbell-telco/sdk/components/dropdown';
430
-
431
- @Component({
432
- selector: 'app-tenant-switcher',
433
- standalone: true,
434
- imports: [ButtonComponent, DropdownComponent, DropdownTriggerComponent, DropdownContentComponent, DropdownItemComponent],
435
- changeDetection: ChangeDetectionStrategy.OnPush,
436
- template: `
437
- <div>
438
- <st-dropdown>
439
- <st-dropdown-trigger>
440
- <st-button>Select Tenant</st-button>
441
- </st-dropdown-trigger>
442
- <st-dropdown-content>
443
- @for (tenant of tenants; track tenant) {
444
- <st-dropdown-item (click)="onTenantChange(tenant)">
445
- {{ tenant }}
446
- </st-dropdown-item>
447
- }
448
- </st-dropdown-content>
449
- </st-dropdown>
450
- </div>
451
- `,
452
- })
453
- export class TenantSwitcherComponent {
454
- private readonly translationService = inject(TranslationService);
44
+ ---
455
45
 
456
- tenants = ['sixbell_telco', 'wom', 'custom'];
46
+ ## Runtime Model Overview
457
47
 
458
- async onTenantChange(tenant: string): Promise<void> {
459
- const configPath = `/api/v1/tenants/${tenant}/languages/config.json`;
48
+ Translation config is a **single JSON** file that lists available languages and file paths. The loader:
460
49
 
461
- try {
462
- // Load tenant-specific translation config
463
- const config = await fetch(configPath).then((res) => res.json());
464
- await this.translationService.setRuntimeConfig(config);
465
- } catch (error) {
466
- console.error('Failed to load tenant config:', error);
467
- }
468
- }
469
- }
470
- ```
50
+ - Loads the config at boot.
51
+ - Applies selected language and updates ngx-translate.
52
+ - Prefetches other languages in background (default on).
471
53
 
472
- ## Real-World Examples
54
+ ### Mermaid: Boot Flow
473
55
 
474
- ### Example 1: Complete App Setup with Runtime Config
56
+ ```mermaid
57
+ sequenceDiagram
58
+ participant App
59
+ participant Provider as provideRuntimeTranslation
60
+ participant Loader as RuntimeConfigLoader
61
+ participant Dexie as RuntimeConfigStore
62
+ participant Service as TranslationService
475
63
 
476
- ```typescript
477
- import { bootstrapApplication } from '@angular/platform-browser';
478
- import { provideHttpClient } from '@angular/common/http';
479
- import { provideRuntimeTranslation, TranslationService } from '@sixbell-telco/sdk/utils/translation';
480
- import { AppComponent } from './app.component';
64
+ App->>Provider: bootstrap
65
+ Provider->>Loader: loadLatest(config)
66
+ Loader->>Dexie: get(cacheKey)
67
+ alt cached & schema ok
68
+ Dexie-->>Loader: cached
69
+ Loader-->>Provider: config (source=cache)
70
+ else cache miss / schema mismatch
71
+ Loader->>Provider: fetch(config)
72
+ Provider->>Loader: parse + store
73
+ Loader->>Dexie: set(cacheKey)
74
+ end
481
75
 
482
- bootstrapApplication(AppComponent, {
483
- providers: [
484
- provideHttpClient(),
485
- provideRuntimeTranslation('/api/v1/languages/config.json', {
486
- loaderOptions: {
487
- cacheName: 'translation-runtime-config',
488
- cacheTTL: 1000 * 60 * 60 * 12,
489
- freshOnNavigation: true,
490
- staleWhileRevalidate: true,
491
- useStaleOnError: true,
492
- retries: 3,
493
- retryDelayMs: 400,
494
- },
495
- }),
496
- ],
497
- }).catch((err) => console.error(err));
76
+ Provider->>Service: applyRuntimeConfig()
77
+ Service->>Service: setRuntimeConfig() + applyLanguage()
78
+ Service->>Service: loadSelectedLanguage()
79
+ Service-->>Service: prefetchRemainingLanguages()
498
80
  ```
499
81
 
500
- ### Example 2: Navigation with Language Persistence
82
+ ---
501
83
 
502
- ```typescript
503
- import { Component, ChangeDetectionStrategy, computed, inject } from '@angular/core';
504
- import { RouterLink, RouterLinkActive } from '@angular/router';
505
- import { TranslationService, TranslatePipe } from '@sixbell-telco/sdk/utils/translation';
506
- import {
507
- DropdownComponent,
508
- DropdownTriggerComponent,
509
- DropdownContentComponent,
510
- DropdownItemRadioComponent,
511
- } from '@sixbell-telco/sdk/components/dropdown';
512
- import { ButtonComponent } from '@sixbell-telco/sdk/components/button';
84
+ ## Translation Config Schema
513
85
 
514
- @Component({
515
- selector: 'app-navigation',
516
- standalone: true,
517
- imports: [
518
- RouterLink,
519
- RouterLinkActive,
520
- TranslatePipe,
521
- DropdownComponent,
522
- DropdownTriggerComponent,
523
- DropdownContentComponent,
524
- DropdownItemRadioComponent,
525
- ButtonComponent,
526
- ],
527
- changeDetection: ChangeDetectionStrategy.OnPush,
528
- template: `
529
- <nav [attr.lang]="translationService.currentLanguage()">
530
- <a routerLink="/" routerLinkActive="active">
531
- {{ 'sdk.nav.home' | translate }}
532
- </a>
533
- <a routerLink="/about" routerLinkActive="active">
534
- {{ 'sdk.nav.about' | translate }}
535
- </a>
536
-
537
- <div class="language-switcher">
538
- <st-dropdown>
539
- <st-dropdown-trigger>
540
- <st-button>{{ getCurrentLanguageName() }}</st-button>
541
- </st-dropdown-trigger>
542
- <st-dropdown-content>
543
- @for (lang of languages; track lang.code) {
544
- <st-dropdown-item-radio
545
- [value]="lang.code"
546
- [checked]="translationService.currentLanguage() === lang.code"
547
- (checkedChanged)="switchLanguage($event)"
548
- >
549
- {{ lang.name }}
550
- </st-dropdown-item-radio>
551
- }
552
- </st-dropdown-content>
553
- </st-dropdown>
554
- </div>
555
- </nav>
556
- `,
557
- })
558
- export class NavigationComponent {
559
- protected readonly translationService = inject(TranslationService);
560
-
561
- languages = this.translationService.getAvailableLanguages();
562
-
563
- getCurrentLanguageName = computed(() => this.translationService.getLanguageName(this.translationService.currentLanguage()));
564
-
565
- switchLanguage(langCode: string): void {
566
- // Change language and stay on current route
567
- this.translationService.setLanguage(langCode);
568
- // Language is automatically saved to IndexedDB
569
- }
86
+ ```json
87
+ {
88
+ "meta": {
89
+ "version": "2026-02-02T00:00:00Z",
90
+ "updatedAt": "2026-02-02T00:00:00Z",
91
+ "hash": "showcase-translations-v1",
92
+ "schemaVersion": "2"
93
+ },
94
+ "additionalLanguages": [{ "code": "de", "name": "Deutsch" }],
95
+ "defaultLang": "es",
96
+ "excludeLanguages": ["pt"],
97
+ "translationPaths": ["/assets/i18n/", "/assets/i18n/sdk/", "/assets/themes/i18n/"]
570
98
  }
571
99
  ```
572
100
 
573
- ### Example 3: Dynamic Content with Language-Specific URLs
101
+ **Rules**
574
102
 
575
- ```typescript
576
- @Component({
577
- selector: 'app-page',
578
- standalone: true,
579
- imports: [TranslatePipe],
580
- template: `
581
- <div [attr.lang]="translationService.currentLanguage()">
582
- <h1>{{ 'sdk.pages.title' | translate }}</h1>
583
- <img [src]="getLocalizedImageUrl()" alt="{{ 'sdk.pages.image' | translate }}" />
584
- </div>
585
- `,
586
- })
587
- export class PageComponent {
588
- private readonly translationService = inject(TranslationService);
103
+ - `translationPaths` should contain directories; each path loads `{lang}.json`.
104
+ - `defaultLang` must exist in available languages (base + additional - excluded).
105
+ - `meta.schemaVersion` is required and invalidates cached configs when bumped.
106
+ - `meta.hash` is required and drives update detection.
107
+ - Runtime admin tooling should bump `meta.hash` when translation files change.
589
108
 
590
- getLocalizedImageUrl(): string {
591
- const lang = this.translationService.currentLanguage();
592
- return `/assets/images/${lang}/hero.webp`;
593
- }
594
- }
595
- ```
109
+ ---
596
110
 
597
- ### Example 4: Form Validation Messages with Translations
111
+ ## Signals and Key APIs
598
112
 
599
- ```typescript
600
- import { Component, ChangeDetectionStrategy, inject } from '@angular/core';
601
- import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
602
- import { TranslationService, TranslatePipe } from '@sixbell-telco/sdk/utils/translation';
603
- import { ButtonComponent } from '@sixbell-telco/sdk/components/button';
113
+ ### Signals
604
114
 
605
- @Component({
606
- selector: 'app-form',
607
- standalone: true,
608
- imports: [ReactiveFormsModule, TranslatePipe, ButtonComponent],
609
- changeDetection: ChangeDetectionStrategy.OnPush,
610
- template: `
611
- <form [formGroup]="form" (ngSubmit)="onSubmit()">
612
- <input formControlName="email" type="email" />
613
- @if (form.get('email')?.hasError('required')) {
614
- <span>{{ 'sdk.errors.emailRequired' | translate }}</span>
615
- }
616
- @if (form.get('email')?.hasError('email')) {
617
- <span>{{ 'sdk.errors.emailInvalid' | translate }}</span>
618
- }
115
+ - `currentLanguage()` - active language code
116
+ - `ready()` - true when current language files are loaded
117
+ - `updateAvailable()` - set by optional update checks
619
118
 
620
- <st-button type="submit" [disabled]="!form.valid">
621
- {{ 'sdk.buttons.submit' | translate }}
622
- </st-button>
623
- </form>
624
- `,
625
- })
626
- export class FormComponent {
627
- private readonly fb = inject(FormBuilder);
628
- protected readonly translationService = inject(TranslationService);
119
+ ### Key Methods
629
120
 
630
- form = this.fb.group({
631
- email: ['', [Validators.required, Validators.email]],
632
- });
633
-
634
- onSubmit(): void {
635
- if (this.form.valid) {
636
- console.log(this.translationService.instant('sdk.messages.formSubmitted'));
637
- }
638
- }
639
- }
121
+ ```ts
122
+ translationService.setLanguage('es');
123
+ translationService.getAvailableLanguages();
124
+ translationService.getDefaultLanguage();
125
+ translationService.withTranslationsReady(() => doWork());
640
126
  ```
641
127
 
642
- ## Troubleshooting
643
-
644
- ### Problem: Translation Keys Not Displaying
128
+ ---
645
129
 
646
- **Symptom**: `{{ 'sdk.common.welcome' | translate }}` shows as empty or missing key
130
+ ## Loading and Merge Behavior
647
131
 
648
- **Diagnosis**:
132
+ - The loader fetches all `translationPaths` for a language.
133
+ - JSON files are merged **deeply** from left to right.
134
+ - Last file wins on conflicts.
649
135
 
650
- 1. Check if translations are loaded:
136
+ ### Mermaid: Merge Flow
651
137
 
652
- ```typescript
653
- const service = inject(TranslationService);
654
- console.log('Ready:', service.isReady());
655
- console.log('Current Language:', service.currentLanguage());
138
+ ```mermaid
139
+ flowchart TD
140
+ A[translationPaths] --> B[Fetch lang.json for each path]
141
+ B --> C[Deep merge results]
142
+ C --> D[ngx-translate cache]
143
+ D --> E["ready() set true"]
656
144
  ```
657
145
 
658
- 2. Check browser console for 404 errors on translation files:
146
+ ---
659
147
 
660
- ```
661
- GET /assets/i18n/en.json 404
662
- ```
663
-
664
- 3. Verify key exists in translation JSON:
665
-
666
- ```bash
667
- cat src/assets/i18n/en.json | grep "common.welcome"
668
- ```
148
+ ## Cache and Schema Versioning
669
149
 
670
- **Solutions**:
150
+ Translation config is cached in IndexedDB as last-known-good. When schema changes:
671
151
 
672
- - Ensure translation files are in `src/assets/i18n/` (or configured path)
673
- - Use exact key path: `sdk.common.welcome` (nested dot notation)
674
- - Wait for translations to load: `await service.waitForTranslations(5000)`
675
- - Check `translationPath` in provider configuration
152
+ - Bump `TRANSLATION_SCHEMA_VERSION`.
153
+ - Update `meta.schemaVersion` in JSON.
154
+ - Old cached config is discarded automatically.
676
155
 
677
- ### Problem: Language Not Persisting After Refresh
156
+ Hash requirements:
678
157
 
679
- **Symptom**: Language resets to default after page refresh
158
+ - `meta.hash` is required and drives update detection.
680
159
 
681
- **Diagnosis**:
160
+ Default mode bootstrap validation:
682
161
 
683
- 1. Check IndexedDB storage:
162
+ - Cached configs are validated on boot against the latest `meta.hash`.
163
+ - If the hash changed, the current language reloads before render, and other languages refresh in the background.
164
+ - If the network check fails, the cached config is used to keep the app available.
684
165
 
685
- ```typescript
686
- // In browser console
687
- const db = await indexedDB.databases();
688
- console.log(db); // Should show 'translations' store
166
+ When editing translation files manually, always update the runtime config `meta.hash` so clients detect the change.
689
167
 
690
- // Or inspect via DevTools: Application > IndexedDB
168
+ ```ts
169
+ // projects/sdk/utils/translation/src/constants.ts
170
+ export const TRANSLATION_SCHEMA_VERSION = '2' as const;
691
171
  ```
692
172
 
693
- 2. Check if IndexedDB is available:
694
-
695
- ```typescript
696
- const service = inject(TranslationService);
697
- console.log('Storage Available:', service.isStorageAvailable());
698
- ```
699
-
700
- **Solutions**:
701
-
702
- - Check if IndexedDB is disabled in browser settings
703
- - In private/incognito mode, use fallback: `service.loadSavedPreferences()`
704
- - Verify browser permissions allow IndexedDB
705
- - Check browser console for storage quota errors
706
-
707
- ### Problem: Language Change Not Triggering UI Update
708
-
709
- **Symptom**: Component doesn't update when language changes
710
-
711
- **Diagnosis**:
712
-
713
- 1. Check if component uses OnPush detection:
714
-
715
- ```typescript
716
- @Component({
717
- changeDetection: ChangeDetectionStrategy.OnPush, // ✅ Required
718
- })
173
+ ```ts
174
+ // note: TRANSLATION_SCHEMA_VERSION is exported from the translation public API
175
+ // import from @sixbell-telco/sdk/utils/translation
719
176
  ```
720
177
 
721
- 2. Verify component accesses signals directly:
178
+ ---
722
179
 
723
- ```typescript
724
- // ✅ Good: Accesses signal
725
- template: `{{ translationService.currentLanguage() }}`;
726
-
727
- // ❌ Bad: No signal access
728
- template: `{{ label }}`;
729
- ```
180
+ ## Examples
730
181
 
731
- 3. Check console for errors:
182
+ ### Basic Setup
732
183
 
733
- ```typescript
734
- translationService.onLanguageChange.subscribe((lang) => {
735
- console.log('Language changed to:', lang);
184
+ ```ts
185
+ bootstrapApplication(AppComponent, {
186
+ providers: [provideRuntimeTranslation('/assets/translation/translation.json')],
736
187
  });
737
188
  ```
738
189
 
739
- **Solutions**:
740
-
741
- - Always use `ChangeDetectionStrategy.OnPush` in components
742
- - Access signal in template: `{{ translationService.currentLanguage() }}`
743
- - Access signal in component class: `this.translationService.currentLanguage()`
744
- - Avoid storing language in component properties - use service signals
745
-
746
- ### Problem: Missing Translations in Logs
747
-
748
- **Symptom**: Logging translations returns undefined
749
-
750
- **Diagnosis**:
751
-
752
- ```typescript
753
- // Check if translation is loaded
754
- const translation = service.instant('sdk.missing.key');
755
- console.log('Result:', translation); // May be key itself if missing
756
- ```
757
-
758
- **Solutions**:
759
-
760
- - Use `instant()` only for UI display, not console logging
761
- - For dynamic keys, verify they exist in translation files
762
- - Use `stream()` for observables that auto-update
763
-
764
- ### Problem: RTL Language Not Displaying Correctly
765
-
766
- **Symptom**: Arabic/Hebrew text displays LTR instead of RTL
767
-
768
- **Diagnosis**:
769
-
770
- Check if `lang` attribute is set on HTML element:
771
-
772
- ```html
773
- <html lang="ar">
774
- <!-- Should be set -->
775
- </html>
776
- ```
777
-
778
- **Solutions**:
779
-
780
- - Language change automatically updates `lang` attribute
781
- - For RTL, ensure Tailwind/CSS respects `:dir(rtl)` selector
782
- - Test with `document.documentElement.getAttribute('lang')`
783
-
784
- ### Console Debugging Tips
785
-
786
- **Enable detailed logging:**
787
-
788
- ```typescript
789
- // In component
790
- const service = inject(TranslationService);
190
+ ### SSE Updates
791
191
 
792
- // Monitor language changes
793
- effect(() => {
794
- console.log('🌍 Language:', service.currentLanguage());
795
- });
796
-
797
- // Monitor translation loading
798
- effect(() => {
799
- console.log('📦 Ready:', service.isReady());
800
- });
801
-
802
- // Monitor storage state
803
- effect(() => {
804
- const saved = service.getSavedLanguage();
805
- console.log('💾 Saved Language:', saved);
192
+ ```ts
193
+ bootstrapApplication(AppComponent, {
194
+ providers: [
195
+ provideRuntimeTranslation('/assets/translation/translation.json', {
196
+ appId: 'host-app',
197
+ sse: { url: 'http://localhost:4000/api/runtime/updates?resource=translation', eventType: 'message' },
198
+ }),
199
+ ],
806
200
  });
807
201
  ```
808
202
 
809
- **Check storage state:**
810
-
811
- ```typescript
812
- // Browser DevTools Console
813
- indexedDB.databases().then((dbs) => console.table(dbs.map((db) => ({ name: db.name }))));
814
-
815
- // Check localStorage (user prefs only)
816
- localStorage.getItem('translation-preference');
817
-
818
- // Check IndexedDB content
819
- (async () => {
820
- const dbs = await indexedDB.databases();
821
- console.log(
822
- 'IndexedDB Stores:',
823
- dbs.map((db) => db.name),
824
- );
825
- })();
826
- ```
827
-
828
- ## Configuration Guide
829
-
830
- ### Static Translation Configuration
831
-
832
- ```typescript
833
- interface TranslationConfig {
834
- // Additional languages beyond English, Spanish, Portuguese
835
- additionalLanguages?: readonly LanguageDefinition[];
836
-
837
- // Languages to exclude from available options
838
- excludeLanguages?: readonly string[];
839
-
840
- // Default language on first load
841
- defaultLang?: string;
842
-
843
- // Translation file paths (where .json files are located)
844
- translationPaths?: string[];
845
-
846
- // Resource loader configuration for remote config
847
- resourceLoader?: TranslationResourceLoaderConfig;
848
- }
849
-
850
- interface LanguageDefinition {
851
- code: string; // Language code (e.g., 'en', 'es', 'pt')
852
- name: string; // Display name (e.g., 'English', 'Español')
853
- }
854
- ```
855
-
856
- ### Runtime Translation Configuration
857
-
858
- ```typescript
859
- interface RuntimeTranslationConfig {
860
- // Available languages
861
- languages: LanguageDefinition[];
862
-
863
- // Default language
864
- defaultLanguage: string;
865
-
866
- // Translation file paths
867
- translationPaths?: string[];
868
-
869
- // Custom loader options
870
- loaderOptions?: ResourceLoaderRequestOptions<Record<string, unknown>>;
871
- }
872
- ```
203
+ Translation update events must include `lang` so clients refresh only the changed locale:
873
204
 
874
- ### Loader Options
875
-
876
- ```typescript
877
- interface ResourceLoaderRequestOptions {
878
- // Cache name for IndexedDB
879
- cacheName?: string;
880
-
881
- // Storage order: IndexedDB → localStorage → memory
882
- storageOrder?: ('indexedDB' | 'localStorage' | 'memory')[];
883
-
884
- // Cache TTL in milliseconds
885
- cacheTTL?: number;
886
-
887
- // Refresh cache on navigation
888
- freshOnNavigation?: boolean;
889
-
890
- // Serve stale cache while revalidating in background
891
- staleWhileRevalidate?: boolean;
892
-
893
- // Use stale cache if fetch fails
894
- useStaleOnError?: boolean;
895
-
896
- // Number of retry attempts
897
- retries?: number;
898
-
899
- // Delay between retries in milliseconds
900
- retryDelayMs?: number;
901
-
902
- // Request timeout in milliseconds
903
- timeoutMs?: number;
904
-
905
- // Log errors to console/logger
906
- logErrors?: boolean;
205
+ ```json
206
+ {
207
+ "resource": "translation",
208
+ "version": "translation-update",
209
+ "hash": "translations-1700000000000",
210
+ "url": "/api/runtime/translation/config",
211
+ "lang": "es"
907
212
  }
908
213
  ```
909
214
 
910
- ## How It Works
911
-
912
- ### 1. Initialization
913
-
914
- The translation system initializes with runtime-configurable language settings:
215
+ ### Disable Prefetch
915
216
 
916
- ```typescript
917
- // app.config.ts
918
- import { ApplicationConfig } from '@angular/core';
919
- import { provideTranslationService } from '@sixbell-telco/sdk/utils/translation';
920
-
921
- export const appConfig: ApplicationConfig = {
922
- providers: [
923
- provideTranslationService({
924
- defaultLanguage: 'en',
925
- supportedLanguages: ['en', 'es', 'pt'],
926
- translationPath: 'assets/i18n',
927
- }),
928
- ],
929
- };
217
+ ```ts
218
+ const translationService = inject(TranslationService);
219
+ translationService.enablePrefetch(false);
930
220
  ```
931
221
 
932
- ### 2. Language Access in Components
933
-
934
- Use modern Angular 19+ patterns with signals and standalone components:
222
+ ### Switch Language with UI
935
223
 
936
- ```typescript
224
+ ```ts
937
225
  import { Component, ChangeDetectionStrategy, inject } from '@angular/core';
938
226
  import { TranslationService } from '@sixbell-telco/sdk/utils/translation';
939
- import {
940
- DropdownComponent,
941
- DropdownTriggerComponent,
942
- DropdownContentComponent,
943
- DropdownItemRadioComponent,
944
- ButtonComponent,
945
- } from '@sixbell-telco/sdk/components/dropdown';
946
227
 
947
228
  @Component({
948
- selector: 'app-language-selector',
949
- standalone: true,
950
- imports: [DropdownComponent, DropdownTriggerComponent, DropdownContentComponent, DropdownItemRadioComponent, ButtonComponent],
229
+ selector: 'app-lang-switcher',
951
230
  changeDetection: ChangeDetectionStrategy.OnPush,
952
231
  template: `
953
- <st-dropdown>
954
- <st-dropdown-trigger>
955
- <st-button [variant]="'outline'">
956
- {{ translationService.currentLanguage() | uppercase }}
957
- </st-button>
958
- </st-dropdown-trigger>
959
- <st-dropdown-content>
960
- @for (lang of translationService.getAvailableLanguages(); track lang) {
961
- <st-dropdown-item-radio
962
- [value]="lang"
963
- [checked]="translationService.currentLanguage() === lang"
964
- (checkedChanged)="translationService.setLanguage($event)"
965
- >
966
- {{ lang | uppercase }}
967
- </st-dropdown-item-radio>
968
- }
969
- </st-dropdown-content>
970
- </st-dropdown>
232
+ <select (change)="setLanguage($event)">
233
+ @for (lang of translationService.getAvailableLanguagesConfig(); track lang.code) {
234
+ <option [value]="lang.code">{{ lang.name }}</option>
235
+ }
236
+ </select>
971
237
  `,
972
238
  })
973
- export class LanguageSelectorComponent {
974
- protected translationService = inject(TranslationService);
975
- }
976
- ```
977
-
978
- ### 3. Signal-Based Reactivity
979
-
980
- All translation state flows through signals for automatic reactivity:
981
-
982
- ```typescript
983
- // Access the current language as a signal
984
- const currentLang = translationService.currentLanguage(); // Signal<string>
985
-
986
- // Language changes automatically propagate
987
- translationService.setLanguage('es');
988
- // currentLang now signals 'es' - all dependents auto-update!
989
- ```
990
-
991
- ### 4. Storage Architecture
992
-
993
- The translation system uses a two-layer approach for reliability:
994
-
995
- ```
996
- ┌─────────────────────────────────────┐
997
- │ Application (Signal Updates) │
998
- ├─────────────────────────────────────┤
999
- │ In-Memory Cache (Runtime Session) │ ← Fast access
1000
- ├─────────────────────────────────────┤
1001
- │ IndexedDB (Persistent Recovery) │ ← Fallback
1002
- └─────────────────────────────────────┘
1003
- ```
1004
-
1005
- **In-Memory Layer:**
1006
-
1007
- - Lightning-fast language lookups
1008
- - Current session language state
1009
- - ngx-translate cache for translations
1010
- - Signal updates and computed values
1011
- - Cleared on page unload
1012
-
1013
- **IndexedDB Layer:**
1014
-
1015
- - User language preference persists across sessions
1016
- - Survives page refresh
1017
- - Automatic recovery on startup
1018
- - No localStorage conflicts
1019
- - Graceful degradation if unavailable
1020
-
1021
- ### 5. Language Selection Flow
1022
-
1023
- ```
1024
- User selects language
1025
- ↓
1026
- TranslationService.setLanguage()
1027
- ↓
1028
- currentLanguage signal updated
1029
- ↓
1030
- ngx-translate switches translations
1031
- ↓
1032
- Language persisted to IndexedDB (async)
1033
- ↓
1034
- DOM lang attribute updated
1035
- ↓
1036
- onLanguageChange observable fired
1037
- ↓
1038
- Components detect change via signal/observable
1039
- ```
1040
-
1041
- ### 6. Signal Reactivity
1042
-
1043
- All language changes flow through signals:
1044
-
1045
- ```
1046
- currentLanguage signal
1047
- ↓
1048
- ngx-translate notified
1049
- ↓
1050
- onLanguageChange signal updated
1051
- ↓
1052
- Effect: Components detect → Templates re-evaluate
1053
- ↓
1054
- Subscribers notified automatically
1055
- ```
1056
-
1057
- ## Architecture Deep Dive
1058
-
1059
- ### Service Breakdown
1060
-
1061
- The translation system uses three focused services for single-responsibility design:
1062
-
1063
- #### TranslationService
1064
-
1065
- The main orchestration service providing the public API:
1066
-
1067
- - **currentLanguage signal**: Current active language
1068
- - **onLanguageChange signal**: Fires when language changes
1069
- - **getAvailableLanguages()**: Returns array of supported languages
1070
- - **setLanguage()**: Changes active language with full sync (storage, DOM, signals)
1071
- - **instant()**: Synchronous translation lookup
1072
- - **get()**: Observable translation lookup
1073
- - **stream()**: Continuous translation stream
1074
-
1075
- **Key Design:**
1076
-
1077
- - Uses ngx-translate internally for translation resolution
1078
- - Exposes only signals (never raw Observables) for reactive consistency
1079
- - Handles language persistence automatically
1080
- - Syncs DOM lang attribute without manual intervention
1081
-
1082
- #### TranslationStorageService
1083
-
1084
- Handles user language preference persistence:
1085
-
1086
- - **saveLanguage()**: Write preference to IndexedDB + in-memory cache
1087
- - **getSavedLanguage()**: Read preference from storage (in-memory first)
1088
- - **clear()**: Reset all storage layers
1089
-
1090
- **Key Design:**
1091
-
1092
- - Uses IndexedDB for long-term persistence
1093
- - Falls back to in-memory if IndexedDB unavailable (private browsing)
1094
- - No localStorage pollution
1095
- - Automatic recovery on app startup
1096
-
1097
- #### TranslationDomService
1098
-
1099
- Manages DOM synchronization for locale features:
1100
-
1101
- - **setDocumentLanguage()**: Update `<html lang="...">` attribute
1102
- - **getDocumentLanguage()**: Read current lang attribute
1103
- - **setTextDirection()**: Set RTL/LTR for Arabic, Hebrew, etc.
1104
-
1105
- **Key Design:**
1106
-
1107
- - Ensures semantic HTML with proper lang attribute
1108
- - Required for accessibility (screen readers, search engines)
1109
- - Enables browser spell-check and font selection
1110
-
1111
- ### Storage Strategy
1112
-
1113
- ```
1114
- ┌────────────────────────────────────────────┐
1115
- │ TranslationService (Public API) │
1116
- └────────────────────────────────────────────┘
1117
- ↓
1118
- ┌────────────────────────────────────────────┐
1119
- │ ngx-translate (ngx Module) │
1120
- │ ├─ In-Memory Translation Cache │
1121
- │ └─ Language Loading Pipeline │
1122
- └────────────────────────────────────────────┘
1123
- ↓
1124
- ┌────────────────────────────────────────────┐
1125
- │ TranslationStorageService │
1126
- │ ├─ IndexedDB (Persistent) │
1127
- │ └─ In-Memory (Session) │
1128
- └────────────────────────────────────────────┘
1129
- ```
1130
-
1131
- **Flow:**
1132
-
1133
- 1. Component injects `TranslationService`
1134
- 2. Calls `translationService.setLanguage('es')`
1135
- 3. Service updates internal signal
1136
- 4. Service notifies ngx-translate to load Spanish translations
1137
- 5. Service writes preference to IndexedDB via `TranslationStorageService`
1138
- 6. Service updates DOM lang attribute via `TranslationDomService`
1139
- 7. Component signal updates trigger OnPush re-evaluation
1140
- 8. Templates re-evaluate with new translations
1141
-
1142
- **Key Features:**
1143
-
1144
- - **No Manual Subscriptions**: Signals auto-propagate changes
1145
- - **Resilient Persistence**: IndexedDB + in-memory fallback
1146
- - **Instant Resolution**: In-memory cache + signal memoization
1147
- - **Clean Separation**: Each service handles one responsibility
1148
-
1149
- ### Signal Flow Diagram
1150
-
1151
- ```
1152
- setLanguage('es') called
1153
- ↓
1154
- currentLanguage signal emits 'es'
1155
- ↓
1156
- computed() re-evaluates
1157
- ↓
1158
- effect() triggered (OnPush detection)
1159
- ↓
1160
- Component template re-evaluates
1161
- ↓
1162
- All instant() calls resolve to Spanish
1163
- ↓
1164
- Pipe + {{ }} bindings show Spanish
1165
- ```
1166
-
1167
- ### Initialization Sequence
1168
-
1169
- ```
1170
- 1. provideTranslationService() called
1171
- ↓
1172
- 2. Create: TranslationService, StorageService, DomService
1173
- ↓
1174
- 3. Load saved language from storage (IndexedDB)
1175
- ↓
1176
- 4. If not found, use defaultLanguage
1177
- ↓
1178
- 5. Set ngx-translate language
1179
- ↓
1180
- 6. Update DOM lang attribute
1181
- ↓
1182
- 7. Services ready for injection
1183
- ↓
1184
- 8. Components can access translationService.currentLanguage()
1185
- ```
1186
-
1187
- ## Performance Tips
1188
-
1189
- ### 1. Use Async Translation Sparingly
1190
-
1191
- ```typescript
1192
- // ✅ Good: Instant translation in computed (no subscriptions)
1193
- title = computed(() => {
1194
- return this.translationService.instant('sdk.titles.main');
1195
- });
1196
-
1197
- // ❌ Avoid: Observable subscription for static content
1198
- title$ = this.translationService.get('sdk.titles.main');
1199
- ```
1200
-
1201
- ### 2. Cache Translation Keys
1202
-
1203
- ```typescript
1204
- // ✅ Good: Cache computed values
1205
- welcomeMessage = computed(() =>
1206
- this.translationService.instant('sdk.common.welcome', { name: this.userName() })
1207
- );
1208
-
1209
- // ❌ Avoid: Computing translation on every change
1210
- welcomeMessage(): string {
1211
- return this.translationService.instant('sdk.common.welcome', {
1212
- name: this.userName(),
1213
- });
1214
- }
1215
- ```
1216
-
1217
- ### 3. Batch Language Changes
1218
-
1219
- ```typescript
1220
- // ✅ Good: Change language once
1221
- this.translationService.setLanguage('es');
1222
-
1223
- // ❌ Avoid: Changing language multiple times
1224
- this.translationService.setLanguage('en');
1225
- this.translationService.setLanguage('es');
1226
- this.translationService.setLanguage('pt');
1227
- ```
1228
-
1229
- ### 4. Lazy Load Translation Files
1230
-
1231
- The translation system automatically lazy-loads translation files on demand via ResourceLoader caching.
1232
-
1233
- ### 5. Use OnPush Change Detection
1234
-
1235
- ```typescript
1236
- @Component({
1237
- changeDetection: ChangeDetectionStrategy.OnPush,
1238
- })
1239
- export class MyComponent {
1240
- // Signals and observables are always detected efficiently
1241
- }
1242
- ```
1243
-
1244
- ## Translation File Format
1245
-
1246
- Translation files should be JSON format with nested keys:
1247
-
1248
- ```json
1249
- {
1250
- "sdk": {
1251
- "common": {
1252
- "welcome": "Welcome",
1253
- "hello": "Hello {{name}}",
1254
- "goodbye": "Goodbye"
1255
- },
1256
- "buttons": {
1257
- "submit": "Submit",
1258
- "cancel": "Cancel",
1259
- "save": "Save"
1260
- },
1261
- "headers": {
1262
- "title": "Application Title",
1263
- "subtitle": "Subtitle"
1264
- },
1265
- "errors": {
1266
- "emailRequired": "Email is required",
1267
- "emailInvalid": "Email is invalid"
1268
- },
1269
- "messages": {
1270
- "formSubmitted": "Form submitted successfully"
1271
- }
1272
- }
1273
- }
1274
- ```
1275
-
1276
- ### File Organization
1277
-
1278
- ```
1279
- /assets/i18n/
1280
- ├── en.json
1281
- ├── es.json
1282
- └── pt.json
1283
- ```
1284
-
1285
- ### Parameterized Translations
1286
-
1287
- ```json
1288
- {
1289
- "sdk": {
1290
- "messages": {
1291
- "greeting": "Hello {{name}}, welcome to {{app}}"
1292
- }
1293
- }
1294
- }
1295
- ```
1296
-
1297
- Usage:
1298
-
1299
- ```typescript
1300
- this.translationService.instant('sdk.messages.greeting', {
1301
- name: 'John',
1302
- app: 'MyApp',
1303
- });
1304
- ```
1305
-
1306
- ## Error Handling
1307
-
1308
- ### Storage Errors
1309
-
1310
- Storage errors are logged but don't break the app:
239
+ export class LangSwitcherComponent {
240
+ protected readonly translationService = inject(TranslationService);
1311
241
 
1312
- ```typescript
1313
- // Graceful fallback if localStorage unavailable
1314
- getSavedLanguage(): string | null {
1315
- try {
1316
- const key = `translation:selectedLanguage`;
1317
- return localStorage.getItem(key);
1318
- } catch (error) {
1319
- logger.error('Failed to read language from storage', error, {
1320
- component: 'TranslationStorageService',
1321
- action: 'getSavedLanguage',
1322
- });
1323
- return null; // Fallback to default
242
+ setLanguage(event: Event): void {
243
+ const lang = (event.target as HTMLSelectElement).value;
244
+ this.translationService.setLanguage(lang);
1324
245
  }
1325
246
  }
1326
247
  ```
1327
248
 
1328
- ### Translation Loading Errors
1329
-
1330
- If translation files fail to load, the system falls back to cached translations:
1331
-
1332
- ```typescript
1333
- provideRuntimeTranslation('/api/v1/languages/config.json', {
1334
- loaderOptions: {
1335
- useStaleOnError: true, // Use cached translations if fetch fails
1336
- retries: 3, // Retry 3 times
1337
- retryDelayMs: 400, // Wait 400ms between retries
1338
- fallbackData: {
1339
- languages: [{ code: 'en', name: 'English' }],
1340
- defaultLanguage: 'en',
1341
- }, // Fallback data if everything fails
1342
- },
1343
- });
1344
- ```
1345
-
1346
- ## Troubleshooting
1347
-
1348
- ### Language Not Persisting
1349
-
1350
- **Problem**: Language selection is lost on page refresh.
249
+ ### Wait Until Ready
1351
250
 
1352
- **Solution**: Ensure `TranslationStorageService` is provided and localStorage is available:
1353
-
1354
- ```typescript
1355
- // Check if localStorage is accessible
1356
- const hasStorage = () => {
1357
- try {
1358
- localStorage.setItem('test', 'test');
1359
- localStorage.removeItem('test');
1360
- return true;
1361
- } catch (e) {
1362
- return false;
1363
- }
1364
- };
251
+ ```ts
252
+ await translationService.waitForTranslations(10000);
1365
253
  ```
1366
254
 
1367
- ### Translations Not Loading
1368
-
1369
- **Problem**: Translation keys show as untranslated (e.g., `[MISSING TRANSLATION]`).
1370
-
1371
- **Solution**: Check translation file paths and file structure:
1372
-
1373
- ```typescript
1374
- // Verify translation file exists
1375
- fetch('/assets/i18n/en.json')
1376
- .then((res) => res.json())
1377
- .then((data) => console.log('Translation structure:', Object.keys(data)));
1378
-
1379
- // Verify translation keys are correct
1380
- console.log('Translated:', translationService.instant('sdk.common.welcome'));
1381
- ```
1382
-
1383
- ### Runtime Config Not Loading
1384
-
1385
- **Problem**: Remote language configuration not loading.
1386
-
1387
- **Solution**: Check endpoint and network:
1388
-
1389
- ```typescript
1390
- // Verify config endpoint is accessible
1391
- const configUrl = '/api/v1/languages/config.json';
1392
- const response = await fetch(configUrl);
1393
- console.log(response.ok, response.status);
1394
-
1395
- // Check cache settings
1396
- provideRuntimeTranslation(configUrl, {
1397
- loaderOptions: {
1398
- freshOnNavigation: false,
1399
- cacheTTL: 1000 * 60 * 60, // 1 hour
1400
- },
1401
- });
1402
- ```
1403
-
1404
- ### Service Not Ready
1405
-
1406
- **Problem**: `ready()` signal never becomes true.
255
+ ### Using the local runtime API server
1407
256
 
1408
- **Solution**: Wait with timeout and handle error:
1409
-
1410
- ```typescript
1411
- try {
1412
- await this.translationService.waitForTranslations(5000);
1413
- console.log('Translations loaded');
1414
- } catch (error) {
1415
- console.error('Translations failed to load:', error);
1416
- // Use default language
1417
- }
1418
- ```
1419
-
1420
- ## Best Practices
1421
-
1422
- ### 1. Define Languages at Bootstrap
1423
-
1424
- ```typescript
1425
- // ✅ Good: Define all languages during app init
257
+ ```ts
1426
258
  bootstrapApplication(AppComponent, {
1427
259
  providers: [
1428
- provideRuntimeTranslation('/api/v1/languages/config.json', {
1429
- loaderOptions: {
1430
- cacheTTL: 1000 * 60 * 60 * 12, // 12 hours
1431
- },
260
+ provideRuntimeTranslation('http://localhost:4000/api/runtime/translation/config', {
261
+ sse: { url: 'http://localhost:4000/api/runtime/updates?resource=translation' },
1432
262
  }),
1433
263
  ],
1434
264
  });
1435
265
  ```
1436
266
 
1437
- ### 2. Use Type-Safe Language Codes
267
+ ## Hash and SchemaVersion Ownership
1438
268
 
1439
- ```typescript
1440
- // ✅ Good: Enum for language codes
1441
- enum Language {
1442
- ENGLISH = 'en',
1443
- SPANISH = 'es',
1444
- PORTUGUESE = 'pt',
1445
- }
269
+ In production, the backend or build pipeline that publishes runtime JSON should always set:
1446
270
 
1447
- translationService.setLanguage(Language.SPANISH);
1448
- ```
271
+ - `meta.hash`: update this on any content change (language lists, paths, or values).
272
+ - `meta.schemaVersion`: update only when the JSON structure changes.
1449
273
 
1450
- ### 3. Namespace Translation Keys
274
+ ---
1451
275
 
1452
- ```typescript
1453
- // ✅ Good: Use namespaces to organize keys
1454
- 'sdk.common.welcome';
1455
- 'sdk.buttons.submit';
1456
- 'sdk.errors.validation';
1457
-
1458
- // ❌ Avoid: Flat key structure
1459
- 'welcome';
1460
- 'submit';
1461
- 'validation_error';
1462
- ```
1463
-
1464
- ### 4. Load Runtime Config Early
276
+ ## Troubleshooting
1465
277
 
1466
- ```typescript
1467
- // ✅ Good: Load config as early as possible during bootstrap
1468
- bootstrapApplication(AppComponent, {
1469
- providers: [
1470
- provideRuntimeTranslation('/api/v1/languages/config.json', {
1471
- loaderOptions: {
1472
- freshOnNavigation: false,
1473
- retries: 3,
1474
- },
1475
- }),
1476
- ],
1477
- });
1478
- ```
278
+ ### Translations not updating
1479
279
 
1480
- ### 5. Test Language Changes
280
+ - Verify `translationPaths` are correct and end with `/` or are normalized.
281
+ - Verify files are named `{lang}.json`.
1481
282
 
1482
- ```typescript
1483
- // ✅ Good: Verify language switching works
1484
- it('should persist language selection', () => {
1485
- translationService.setLanguage('es');
1486
- translationService.loadSavedPreferences();
1487
- expect(translationService.currentLanguage()).toBe('es');
1488
- });
1489
- ```
283
+ ### Old config stuck in cache
1490
284
 
1491
- ### 6. Provide Missing Translation Handler
285
+ - Bump `TRANSLATION_SCHEMA_VERSION` and `meta.schemaVersion`.
1492
286
 
1493
- ```typescript
1494
- // ✅ Good: Handle missing translations gracefully
1495
- const missingTranslationHandler: MissingTranslationHandler = {
1496
- handle(params: MissingTranslationHandlerParams): string {
1497
- return `[Missing: ${params.key}]`;
1498
- },
1499
- };
1500
- ```
287
+ ---
1501
288
 
1502
289
  ## Related Utilities
1503
290
 
1504
- - **[Theme Service](../theme/)**: Multi-theme support with language awareness
1505
- - **[ResourceLoader](../resource-loader/)**: Runtime config loading with caching
1506
- - **[cn Utility](../cn/)**: Conditional CSS class merging
1507
- - **[ngx-translate](https://github.com/ngx-translate/core)**: Core translation library
1508
- - **[ngx-translate-multi-http-loader](https://github.com/ngx-translate-multi-http-loader)**: Multi-path translation file loading
1509
-
1510
- ## License
1511
-
1512
- MIT - See LICENSE file in the root of the project.
291
+ - `@sixbell-telco/sdk/utils/runtime-config` - Loader + cache
292
+ - `@sixbell-telco/sdk/utils/theme` - Runtime theme system