@sixbell-telco/sdk 1.4.0 → 1.5.0

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 (63) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +410 -472
  3. package/fesm2022/sixbell-telco-sdk-utils-logger.mjs +578 -0
  4. package/fesm2022/sixbell-telco-sdk-utils-logger.mjs.map +1 -0
  5. package/fesm2022/sixbell-telco-sdk-utils-resource-loader.mjs +1222 -0
  6. package/fesm2022/sixbell-telco-sdk-utils-resource-loader.mjs.map +1 -0
  7. package/fesm2022/sixbell-telco-sdk-utils-theme.mjs +1434 -180
  8. package/fesm2022/sixbell-telco-sdk-utils-theme.mjs.map +1 -1
  9. package/fesm2022/sixbell-telco-sdk-utils-translation.mjs +734 -182
  10. package/fesm2022/sixbell-telco-sdk-utils-translation.mjs.map +1 -1
  11. package/package.json +64 -56
  12. package/utils/logger/README.md +539 -0
  13. package/utils/logger/index.d.ts +5 -0
  14. package/utils/logger/public-api.d.ts +3 -0
  15. package/utils/logger/src/constants.d.ts +15 -0
  16. package/utils/logger/src/logger.service.d.ts +123 -0
  17. package/utils/logger/src/models/logger.d.ts +25 -0
  18. package/utils/logger/src/providers/logger.provider.d.ts +3 -0
  19. package/utils/resource-loader/README.md +460 -0
  20. package/utils/resource-loader/index.d.ts +5 -0
  21. package/utils/resource-loader/public-api.d.ts +1 -0
  22. package/utils/resource-loader/src/cache/index.d.ts +2 -0
  23. package/utils/resource-loader/src/cache/layers/factory.d.ts +38 -0
  24. package/utils/resource-loader/src/cache/layers/index.d.ts +3 -0
  25. package/utils/resource-loader/src/cache/layers/indexed-db-cache.d.ts +118 -0
  26. package/utils/resource-loader/src/cache/layers/local-storage-cache.d.ts +86 -0
  27. package/utils/resource-loader/src/cache/layers/memory-cache.d.ts +76 -0
  28. package/utils/resource-loader/src/cache/types.d.ts +107 -0
  29. package/utils/resource-loader/src/config/index.d.ts +1 -0
  30. package/utils/resource-loader/src/config/load-config.d.ts +32 -0
  31. package/utils/resource-loader/src/constants.d.ts +38 -0
  32. package/utils/resource-loader/src/http/index.d.ts +1 -0
  33. package/utils/resource-loader/src/http/retryable-client.d.ts +43 -0
  34. package/utils/resource-loader/src/index.d.ts +1 -0
  35. package/utils/resource-loader/src/resource-loader.d.ts +67 -0
  36. package/utils/resource-loader/src/types.d.ts +152 -0
  37. package/utils/resource-loader/src/utils/cache-validator.d.ts +72 -0
  38. package/utils/resource-loader/src/utils/helpers.d.ts +15 -0
  39. package/utils/resource-loader/src/utils/index.d.ts +2 -0
  40. package/utils/theme/README.md +1054 -109
  41. package/utils/theme/public-api.d.ts +9 -1
  42. package/utils/theme/src/constants.d.ts +74 -0
  43. package/utils/theme/src/models/theme.d.ts +288 -0
  44. package/utils/theme/src/providers/constants.d.ts +7 -0
  45. package/utils/theme/src/providers/theme.provider.d.ts +13 -0
  46. package/utils/theme/src/providers/theme.provider.types.d.ts +29 -0
  47. package/utils/theme/src/theme-assets/theme-assets.service.d.ts +214 -0
  48. package/utils/theme/src/theme-assets/theme-assets.types.d.ts +10 -0
  49. package/utils/theme/src/theme-dom/theme-dom.service.d.ts +87 -0
  50. package/utils/theme/src/theme-scheme/theme-scheme.service.d.ts +44 -0
  51. package/utils/theme/src/theme-storage/theme-storage.service.d.ts +47 -0
  52. package/utils/theme/src/theme.service.d.ts +40 -186
  53. package/utils/theme/src/utils/utils.d.ts +86 -0
  54. package/utils/translation/README.md +1414 -176
  55. package/utils/translation/public-api.d.ts +6 -0
  56. package/utils/translation/src/constants.d.ts +52 -0
  57. package/utils/translation/src/models/translation.d.ts +59 -0
  58. package/utils/translation/src/providers/constants.d.ts +11 -0
  59. package/utils/translation/src/providers/translation.provider.d.ts +73 -0
  60. package/utils/translation/src/providers/translation.provider.types.d.ts +26 -0
  61. package/utils/translation/src/translation-dom/translation-dom.service.d.ts +26 -0
  62. package/utils/translation/src/translation-storage/translation-storage.service.d.ts +34 -0
  63. package/utils/translation/src/translation.service.d.ts +19 -166
@@ -1,274 +1,1512 @@
1
- # Translation Service
1
+ # Translation Utility
2
2
 
3
- A modern Angular service for internationalization using ngx-translate with TypeScript IntelliSense support.
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.
4
4
 
5
- ## What it does
5
+ ## Quick Start
6
6
 
7
- The Translation Service provides:
7
+ ### Basic Setup
8
8
 
9
- - **Internationalization** with ngx-translate integration
10
- - **TypeScript IntelliSense** for language codes and translation keys
11
- - **Reactive translation** using Angular signals
12
- - **Flexible configuration** for additional languages and exclusions
13
- - **Provider-based setup** for Angular applications
9
+ ```typescript
10
+ import { provideRuntimeTranslation } from '@sixbell-telco/sdk/utils/translation';
11
+
12
+ bootstrapApplication(AppComponent, {
13
+ providers: [provideRuntimeTranslation('/assets/config/translation-config.json')],
14
+ });
15
+ ```
16
+
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
260
+
261
+ ```typescript
262
+ import { Component, ChangeDetectionStrategy, inject } from '@angular/core';
263
+ 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
+
272
+ @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',
322
+ standalone: true,
323
+ imports: [TranslatePipe],
324
+ 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
+ `,
332
+ })
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 {
387
+ 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
+ }
394
+ ```
395
+
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);
455
+
456
+ tenants = ['sixbell_telco', 'wom', 'custom'];
457
+
458
+ async onTenantChange(tenant: string): Promise<void> {
459
+ const configPath = `/api/v1/tenants/${tenant}/languages/config.json`;
460
+
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
+ ```
471
+
472
+ ## Real-World Examples
473
+
474
+ ### Example 1: Complete App Setup with Runtime Config
475
+
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';
481
+
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));
498
+ ```
499
+
500
+ ### Example 2: Navigation with Language Persistence
501
+
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';
513
+
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
+ }
570
+ }
571
+ ```
572
+
573
+ ### Example 3: Dynamic Content with Language-Specific URLs
574
+
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);
589
+
590
+ getLocalizedImageUrl(): string {
591
+ const lang = this.translationService.currentLanguage();
592
+ return `/assets/images/${lang}/hero.webp`;
593
+ }
594
+ }
595
+ ```
596
+
597
+ ### Example 4: Form Validation Messages with Translations
598
+
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';
604
+
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
+ }
619
+
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);
629
+
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
+ }
640
+ ```
641
+
642
+ ## Troubleshooting
643
+
644
+ ### Problem: Translation Keys Not Displaying
645
+
646
+ **Symptom**: `{{ 'sdk.common.welcome' | translate }}` shows as empty or missing key
647
+
648
+ **Diagnosis**:
649
+
650
+ 1. Check if translations are loaded:
651
+
652
+ ```typescript
653
+ const service = inject(TranslationService);
654
+ console.log('Ready:', service.isReady());
655
+ console.log('Current Language:', service.currentLanguage());
656
+ ```
657
+
658
+ 2. Check browser console for 404 errors on translation files:
659
+
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
+ ```
669
+
670
+ **Solutions**:
671
+
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
676
+
677
+ ### Problem: Language Not Persisting After Refresh
678
+
679
+ **Symptom**: Language resets to default after page refresh
680
+
681
+ **Diagnosis**:
682
+
683
+ 1. Check IndexedDB storage:
684
+
685
+ ```typescript
686
+ // In browser console
687
+ const db = await indexedDB.databases();
688
+ console.log(db); // Should show 'translations' store
689
+
690
+ // Or inspect via DevTools: Application > IndexedDB
691
+ ```
692
+
693
+ 2. Check if IndexedDB is available:
694
+
695
+ ```typescript
696
+ const service = inject(TranslationService);
697
+ console.log('Storage Available:', service.isStorageAvailable());
698
+ ```
14
699
 
15
- ## How to use
700
+ **Solutions**:
16
701
 
17
- ### Basic setup
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:
18
714
 
19
715
  ```typescript
20
- // app.config.ts
21
- import { provideTranslation } from '@sixbell-telco/sdk/utils/translation';
716
+ @Component({
717
+ changeDetection: ChangeDetectionStrategy.OnPush, // ✅ Required
718
+ })
719
+ ```
22
720
 
23
- export const appConfig: ApplicationConfig = {
24
- providers: [
25
- provideTranslation({
26
- defaultLang: 'es', // IntelliSense: 'en' | 'es' | 'pt'
27
- excludeLanguages: ['pt'], // IntelliSense: 'en' | 'es' | 'pt'
28
- }),
29
- ],
30
- };
721
+ 2. Verify component accesses signals directly:
722
+
723
+ ```typescript
724
+ // ✅ Good: Accesses signal
725
+ template: `{{ translationService.currentLanguage() }}`;
726
+
727
+ // ❌ Bad: No signal access
728
+ template: `{{ label }}`;
729
+ ```
730
+
731
+ 3. Check console for errors:
732
+
733
+ ```typescript
734
+ translationService.onLanguageChange.subscribe((lang) => {
735
+ console.log('Language changed to:', lang);
736
+ });
737
+ ```
738
+
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);
791
+
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);
806
+ });
807
+ ```
808
+
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
+ ```
873
+
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;
907
+ }
31
908
  ```
32
909
 
33
- ### With additional languages
910
+ ## How It Works
911
+
912
+ ### 1. Initialization
913
+
914
+ The translation system initializes with runtime-configurable language settings:
34
915
 
35
916
  ```typescript
36
917
  // app.config.ts
37
- import { provideTranslation } from '@sixbell-telco/sdk/utils/translation';
918
+ import { ApplicationConfig } from '@angular/core';
919
+ import { provideTranslationService } from '@sixbell-telco/sdk/utils/translation';
38
920
 
39
921
  export const appConfig: ApplicationConfig = {
40
922
  providers: [
41
- provideTranslation({
42
- additionalLanguages: [
43
- { code: 'de', name: 'Deutsch' },
44
- { code: 'fr', name: 'Français' },
45
- { code: 'it', name: 'Italiano' },
46
- ],
47
- defaultLang: 'de', // IntelliSense: 'en' | 'es' | 'pt' | 'de' | 'fr' | 'it'
48
- excludeLanguages: ['pt', 'it'], // IntelliSense: all available languages
49
- translationPaths: ['/assets/i18n/', '/assets/i18n/sdk/'],
923
+ provideTranslationService({
924
+ defaultLanguage: 'en',
925
+ supportedLanguages: ['en', 'es', 'pt'],
926
+ translationPath: 'assets/i18n',
50
927
  }),
51
928
  ],
52
929
  };
53
930
  ```
54
931
 
55
- ### Using in components
932
+ ### 2. Language Access in Components
933
+
934
+ Use modern Angular 19+ patterns with signals and standalone components:
56
935
 
57
936
  ```typescript
58
- // component.ts
937
+ import { Component, ChangeDetectionStrategy, inject } from '@angular/core';
59
938
  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';
60
946
 
61
947
  @Component({
948
+ selector: 'app-language-selector',
949
+ standalone: true,
950
+ imports: [DropdownComponent, DropdownTriggerComponent, DropdownContentComponent, DropdownItemRadioComponent, ButtonComponent],
951
+ changeDetection: ChangeDetectionStrategy.OnPush,
62
952
  template: `
63
- <div>
64
- <p>{{ 'common.welcome' | translate }}</p>
65
- <p>Current language: {{ translation.getCurrentLanguage() }}</p>
66
-
67
- <select (change)="changeLanguage($event.target.value)">
68
- @for (lang of translation.getAvailableLanguagesConfig(); track lang.code) {
69
- <option [value]="lang.code">{{ lang.name }}</option>
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>
70
968
  }
71
- </select>
72
- </div>
969
+ </st-dropdown-content>
970
+ </st-dropdown>
73
971
  `,
74
972
  })
75
- export class MyComponent {
76
- translation = inject(TranslationService);
973
+ export class LanguageSelectorComponent {
974
+ protected translationService = inject(TranslationService);
975
+ }
976
+ ```
77
977
 
78
- changeLanguage(langCode: string) {
79
- this.translation.setLanguage(langCode);
80
- }
978
+ ### 3. Signal-Based Reactivity
81
979
 
82
- translateMessage(key: string, params?: any) {
83
- return this.translation.instant(key, params);
84
- }
85
- }
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!
86
989
  ```
87
990
 
88
- ### Reactive translations in templates
991
+ ### 4. Storage Architecture
89
992
 
90
- ```html
91
- <!-- Direct translation with ngx-translate pipe -->
92
- <p>{{ 'common.welcome' | translate }}</p>
993
+ The translation system uses a two-layer approach for reliability:
93
994
 
94
- <!-- Translation with parameters -->
95
- <p>{{ 'common.greeting' | translate: { name: userName } }}</p>
995
+ ```
996
+ ┌─────────────────────────────────────┐
997
+ │ Application (Signal Updates) │
998
+ ├─────────────────────────────────────┤
999
+ │ In-Memory Cache (Runtime Session) │ ← Fast access
1000
+ ├─────────────────────────────────────┤
1001
+ │ IndexedDB (Persistent Recovery) │ ← Fallback
1002
+ └─────────────────────────────────────┘
1003
+ ```
96
1004
 
97
- <!-- Async translation -->
98
- <p>{{ translation.get('common.message') | async }}</p>
1005
+ **In-Memory Layer:**
99
1006
 
100
- <!-- Conditional content based on language -->
101
- @if (translation.getCurrentLanguage() === 'es') {
102
- <p>Contenido en español</p>
103
- } @else {
104
- <p>Content in other language</p>
105
- }
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
+ └────────────────────────────────────────────┘
106
1129
  ```
107
1130
 
108
- ## Key features
1131
+ **Flow:**
109
1132
 
110
- - **Signal-based reactivity** - Modern Angular reactive patterns
111
- - **IntelliSense support** - Full TypeScript autocomplete for language codes
112
- - **Flexible configuration** - Add languages, exclude unwanted ones
113
- - **Provider pattern** - Clean Angular dependency injection setup
114
- - **Automatic persistence** - Saves user preferences to localStorage
115
- - **ngx-translate integration** - Full compatibility with existing translation workflows
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
116
1141
 
117
- ## Default languages
1142
+ **Key Features:**
118
1143
 
119
- - `en` (English) - Always available unless excluded
120
- - `es` (Spanish) - Always available unless excluded
121
- - `pt` (Portuguese) - Always available unless excluded
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
122
1148
 
123
- You can add more languages using `additionalLanguages` or exclude default ones using `excludeLanguages`.
1149
+ ### Signal Flow Diagram
124
1150
 
125
- ## Translation methods
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
+ ```
126
1186
 
127
- The service provides convenient methods for translations:
1187
+ ## Performance Tips
128
1188
 
129
- - `instant(key: string, params?: any)` - Get immediate translation
130
- - `get(key: string, params?: any)` - Get translation as Observable
131
- - `stream(key: string, params?: any)` - Get translation stream that updates on language changes
132
- - `setLanguage(langCode: string)` - Change current language
133
- - `getCurrentLanguage()` - Get current language code
134
- - `getDefaultLanguage()` - Get default language code
135
- - `getAvailableLanguagesConfig()` - Get all available language definitions
136
- - `getAvailableLanguageCodes()` - Get array of available language codes
137
- - `getLanguageByCode(code: string)` - Get language definition by code
138
- - `getLanguageDisplayName(code: string)` - Get display name for language code
1189
+ ### 1. Use Async Translation Sparingly
139
1190
 
140
- ## Configuration options
1191
+ ```typescript
1192
+ // ✅ Good: Instant translation in computed (no subscriptions)
1193
+ title = computed(() => {
1194
+ return this.translationService.instant('sdk.titles.main');
1195
+ });
141
1196
 
142
- | Property | Type | Description |
143
- | --------------------- | ------------------------------- | ------------------------------------------------------------------- |
144
- | `additionalLanguages` | `readonly LanguageDefinition[]` | Additional languages beyond the defaults |
145
- | `defaultLang` | `string` | Default language to use (with IntelliSense for available languages) |
146
- | `excludeLanguages` | `readonly string[]` | Languages to exclude from available languages |
147
- | `translationPaths` | `string[]` | Custom paths for translation files (default: `['/assets/i18n/']`) |
1197
+ // ❌ Avoid: Observable subscription for static content
1198
+ title$ = this.translationService.get('sdk.titles.main');
1199
+ ```
148
1200
 
149
- ## Language definition interface
1201
+ ### 2. Cache Translation Keys
150
1202
 
151
1203
  ```typescript
152
- interface LanguageDefinition {
153
- code: string; // Language code (e.g., 'en', 'es', 'de')
154
- name: string; // Display name (e.g., 'English', 'Español', 'Deutsch')
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
+ });
155
1214
  }
156
1215
  ```
157
1216
 
158
- ## Translation file structure
1217
+ ### 3. Batch Language Changes
159
1218
 
160
- Place your translation files in `/assets/i18n/` with the following structure:
1219
+ ```typescript
1220
+ // ✅ Good: Change language once
1221
+ this.translationService.setLanguage('es');
161
1222
 
1223
+ // ❌ Avoid: Changing language multiple times
1224
+ this.translationService.setLanguage('en');
1225
+ this.translationService.setLanguage('es');
1226
+ this.translationService.setLanguage('pt');
162
1227
  ```
163
- src/
164
- assets/
165
- i18n/
166
- en.json
167
- es.json
168
- pt.json
169
- de.json // if using additional languages
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
+ }
170
1242
  ```
171
1243
 
172
- Example translation file (`en.json`):
1244
+ ## Translation File Format
1245
+
1246
+ Translation files should be JSON format with nested keys:
173
1247
 
174
1248
  ```json
175
1249
  {
176
- "common": {
177
- "welcome": "Welcome",
178
- "greeting": "Hello {{name}}!",
179
- "message": "This is a message"
180
- },
181
- "navigation": {
182
- "home": "Home",
183
- "about": "About",
184
- "contact": "Contact"
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
+ }
185
1272
  }
186
1273
  }
187
1274
  ```
188
1275
 
189
- ## Advanced usage
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
+ ```
190
1296
 
191
- ### Custom translation paths
1297
+ Usage:
192
1298
 
193
1299
  ```typescript
194
- provideTranslation({
195
- translationPaths: [
196
- '/assets/i18n/', // Main translations
197
- '/assets/i18n/modules/', // Module-specific translations
198
- '/assets/i18n/sdk/', // SDK translations
199
- ],
1300
+ this.translationService.instant('sdk.messages.greeting', {
1301
+ name: 'John',
1302
+ app: 'MyApp',
200
1303
  });
201
1304
  ```
202
1305
 
203
- ### Programmatic language detection
1306
+ ## Error Handling
204
1307
 
205
- ```typescript
206
- @Component({...})
207
- export class LanguageDetectorComponent {
208
- translation = inject(TranslationService);
1308
+ ### Storage Errors
209
1309
 
210
- ngOnInit() {
211
- // Detect browser language
212
- const browserLang = navigator.language.split('-')[0];
213
- const availableCodes = this.translation.getAvailableLanguageCodes();
1310
+ Storage errors are logged but don't break the app:
214
1311
 
215
- if (availableCodes.includes(browserLang)) {
216
- this.translation.setLanguage(browserLang);
217
- }
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
218
1324
  }
219
1325
  }
220
1326
  ```
221
1327
 
222
- ### Reactive language switching
1328
+ ### Translation Loading Errors
1329
+
1330
+ If translation files fail to load, the system falls back to cached translations:
223
1331
 
224
1332
  ```typescript
225
- @Component({
226
- template: `
227
- <div class="language-switcher">
228
- @for (lang of availableLanguages; track lang.code) {
229
- <button [class.active]="lang.code === currentLanguage" (click)="switchLanguage(lang.code)">
230
- {{ lang.name }}
231
- </button>
232
- }
233
- </div>
234
- `,
235
- })
236
- export class LanguageSwitcherComponent {
237
- translation = inject(TranslationService);
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
238
1347
 
239
- availableLanguages = this.translation.getAvailableLanguagesConfig();
240
- currentLanguage = this.translation.getCurrentLanguage();
1348
+ ### Language Not Persisting
241
1349
 
242
- switchLanguage(langCode: string) {
243
- this.translation.setLanguage(langCode);
244
- this.currentLanguage = this.translation.getCurrentLanguage();
1350
+ **Problem**: Language selection is lost on page refresh.
1351
+
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;
245
1363
  }
1364
+ };
1365
+ ```
1366
+
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.
1407
+
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
1426
+ bootstrapApplication(AppComponent, {
1427
+ providers: [
1428
+ provideRuntimeTranslation('/api/v1/languages/config.json', {
1429
+ loaderOptions: {
1430
+ cacheTTL: 1000 * 60 * 60 * 12, // 12 hours
1431
+ },
1432
+ }),
1433
+ ],
1434
+ });
1435
+ ```
1436
+
1437
+ ### 2. Use Type-Safe Language Codes
1438
+
1439
+ ```typescript
1440
+ // ✅ Good: Enum for language codes
1441
+ enum Language {
1442
+ ENGLISH = 'en',
1443
+ SPANISH = 'es',
1444
+ PORTUGUESE = 'pt',
246
1445
  }
1446
+
1447
+ translationService.setLanguage(Language.SPANISH);
1448
+ ```
1449
+
1450
+ ### 3. Namespace Translation Keys
1451
+
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';
247
1462
  ```
248
1463
 
249
- ## What's included automatically
1464
+ ### 4. Load Runtime Config Early
250
1465
 
251
- The `provideTranslation()` provider automatically configures:
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
+ ```
252
1479
 
253
- - ✅ `TranslateService` from `@ngx-translate/core`
254
- - ✅ `TranslateHttpLoader` with configurable paths
255
- - ✅ All necessary ngx-translate providers
256
- - ✅ Automatic service initialization for MFE compatibility
257
- - ✅ Browser environment safety checks
1480
+ ### 5. Test Language Changes
258
1481
 
259
- ## Available components
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
+ ```
260
1490
 
261
- All useful ngx-translate components are automatically available for import:
1491
+ ### 6. Provide Missing Translation Handler
262
1492
 
263
1493
  ```typescript
264
- import {
265
- TranslatePipe,
266
- TranslateDirective,
267
- TranslateService,
268
- // ... all other ngx-translate exports
269
- } from '@sixbell-telco/sdk/utils/translation';
1494
+ // ✅ Good: Handle missing translations gracefully
1495
+ const missingTranslationHandler: MissingTranslationHandler = {
1496
+ handle(params: MissingTranslationHandlerParams): string {
1497
+ return `[Missing: ${params.key}]`;
1498
+ },
1499
+ };
270
1500
  ```
271
1501
 
272
- ## Language persistence
1502
+ ## Related Utilities
1503
+
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
273
1511
 
274
- User language preferences are automatically saved to localStorage and restored on app initialization. No additional setup required.
1512
+ MIT - See LICENSE file in the root of the project.