@sixbell-telco/sdk 1.5.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 (131) hide show
  1. package/CHANGELOG.md +223 -710
  2. package/README.md +307 -282
  3. package/_index.css +29 -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/dropdown-chevron/dropdown-chevron.component.d.ts +6 -1
  8. package/components/dropdown/dropdown-content/dropdown-content.component.d.ts +1 -1
  9. package/components/dropdown/dropdown-item/dropdown-item.component.d.ts +6 -1
  10. package/components/dropdown/dropdown-item-checkbox/dropdown-item-checkbox.component.d.ts +7 -1
  11. package/components/dropdown/dropdown-item-radio/dropdown-item-radio.component.d.ts +7 -1
  12. package/components/dropdown/dropdown-trigger/dropdown-trigger.component.d.ts +30 -0
  13. package/components/dropdown/public-api.d.ts +0 -1
  14. package/components/dropdown/src/dropdown.component.d.ts +31 -7
  15. package/components/dropdown-menu/src/dropdown-menu-content/dropdown-menu-content.component.d.ts +2 -3
  16. package/components/dual-list/src/dual-list.component.d.ts +2 -1
  17. package/components/file-upload/file-dropzone/file-dropzone.component.d.ts +7 -7
  18. package/components/file-upload/file-uploader/file-uploader.component.d.ts +7 -7
  19. package/components/forms/combobox/src/combobox.component.d.ts +24 -0
  20. package/components/forms/input/src/input.component.d.ts +11 -1
  21. package/components/forms/select/src/select.component.d.ts +24 -0
  22. package/components/forms/textarea/src/textarea.component.d.ts +10 -10
  23. package/components/link/src/link.component.d.ts +0 -3
  24. package/components/tab/directives/tab-content/tab-content.directive.d.ts +3 -3
  25. package/components/tab/directives/tab-header/tab-header.directive.d.ts +2 -2
  26. package/components/wizard/services/wizard.service.d.ts +5 -5
  27. package/directives/auto-focus/public-api.d.ts +1 -1
  28. package/directives/auto-focus/src/{autofocus.directive.d.ts → auto-focus.directive.d.ts} +5 -7
  29. package/directives/only-numbers/public-api.d.ts +6 -1
  30. package/directives/only-numbers/src/only-numbers.directive.d.ts +37 -0
  31. package/fesm2022/sixbell-telco-sdk-components-audio-player.mjs +7 -5
  32. package/fesm2022/sixbell-telco-sdk-components-audio-player.mjs.map +1 -1
  33. package/fesm2022/sixbell-telco-sdk-components-avatar.mjs +1 -1
  34. package/fesm2022/sixbell-telco-sdk-components-avatar.mjs.map +1 -1
  35. package/fesm2022/sixbell-telco-sdk-components-badge.mjs +2 -2
  36. package/fesm2022/sixbell-telco-sdk-components-badge.mjs.map +1 -1
  37. package/fesm2022/sixbell-telco-sdk-components-countdown.mjs.map +1 -1
  38. package/fesm2022/sixbell-telco-sdk-components-data-table.mjs +2 -2
  39. package/fesm2022/sixbell-telco-sdk-components-data-table.mjs.map +1 -1
  40. package/fesm2022/sixbell-telco-sdk-components-dropdown-menu.mjs +0 -4
  41. package/fesm2022/sixbell-telco-sdk-components-dropdown-menu.mjs.map +1 -1
  42. package/fesm2022/sixbell-telco-sdk-components-dropdown.mjs +472 -341
  43. package/fesm2022/sixbell-telco-sdk-components-dropdown.mjs.map +1 -1
  44. package/fesm2022/sixbell-telco-sdk-components-dual-list.mjs +8 -7
  45. package/fesm2022/sixbell-telco-sdk-components-dual-list.mjs.map +1 -1
  46. package/fesm2022/sixbell-telco-sdk-components-file-upload.mjs +6 -4
  47. package/fesm2022/sixbell-telco-sdk-components-file-upload.mjs.map +1 -1
  48. package/fesm2022/sixbell-telco-sdk-components-forms-combobox.mjs +58 -2
  49. package/fesm2022/sixbell-telco-sdk-components-forms-combobox.mjs.map +1 -1
  50. package/fesm2022/sixbell-telco-sdk-components-forms-date-picker.mjs +2 -0
  51. package/fesm2022/sixbell-telco-sdk-components-forms-date-picker.mjs.map +1 -1
  52. package/fesm2022/sixbell-telco-sdk-components-forms-input.mjs +15 -5
  53. package/fesm2022/sixbell-telco-sdk-components-forms-input.mjs.map +1 -1
  54. package/fesm2022/sixbell-telco-sdk-components-forms-select.mjs +54 -4
  55. package/fesm2022/sixbell-telco-sdk-components-forms-select.mjs.map +1 -1
  56. package/fesm2022/sixbell-telco-sdk-components-forms-textarea.mjs +19 -8
  57. package/fesm2022/sixbell-telco-sdk-components-forms-textarea.mjs.map +1 -1
  58. package/fesm2022/sixbell-telco-sdk-components-link.mjs +2 -7
  59. package/fesm2022/sixbell-telco-sdk-components-link.mjs.map +1 -1
  60. package/fesm2022/sixbell-telco-sdk-components-overlay.mjs +2 -2
  61. package/fesm2022/sixbell-telco-sdk-components-overlay.mjs.map +1 -1
  62. package/fesm2022/sixbell-telco-sdk-components-tab.mjs.map +1 -1
  63. package/fesm2022/sixbell-telco-sdk-components-wizard.mjs.map +1 -1
  64. package/fesm2022/sixbell-telco-sdk-directives-auto-focus.mjs +14 -31
  65. package/fesm2022/sixbell-telco-sdk-directives-auto-focus.mjs.map +1 -1
  66. package/fesm2022/sixbell-telco-sdk-directives-only-numbers.mjs +42 -8
  67. package/fesm2022/sixbell-telco-sdk-directives-only-numbers.mjs.map +1 -1
  68. package/fesm2022/sixbell-telco-sdk-utils-date.mjs +1 -1
  69. package/fesm2022/sixbell-telco-sdk-utils-date.mjs.map +1 -1
  70. package/fesm2022/sixbell-telco-sdk-utils-pipes-to-bytes-extesion.mjs +1 -1
  71. package/fesm2022/sixbell-telco-sdk-utils-pipes-to-bytes-extesion.mjs.map +1 -1
  72. package/fesm2022/sixbell-telco-sdk-utils-runtime-config.mjs +339 -0
  73. package/fesm2022/sixbell-telco-sdk-utils-runtime-config.mjs.map +1 -0
  74. package/fesm2022/sixbell-telco-sdk-utils-sync.mjs +1 -1
  75. package/fesm2022/sixbell-telco-sdk-utils-sync.mjs.map +1 -1
  76. package/fesm2022/sixbell-telco-sdk-utils-theme.mjs +1053 -716
  77. package/fesm2022/sixbell-telco-sdk-utils-theme.mjs.map +1 -1
  78. package/fesm2022/sixbell-telco-sdk-utils-translation.mjs +345 -257
  79. package/fesm2022/sixbell-telco-sdk-utils-translation.mjs.map +1 -1
  80. package/package.json +73 -72
  81. package/utils/runtime-config/README.md +235 -0
  82. package/utils/{resource-loader → runtime-config}/index.d.ts +1 -1
  83. package/utils/runtime-config/public-api.d.ts +5 -0
  84. package/utils/runtime-config/src/http-client.d.ts +11 -0
  85. package/utils/runtime-config/src/runtime-config-loader.d.ts +23 -0
  86. package/utils/runtime-config/src/runtime-config-store.d.ts +11 -0
  87. package/utils/runtime-config/src/runtime-update-adapter.d.ts +15 -0
  88. package/utils/runtime-config/src/types.d.ts +66 -0
  89. package/utils/theme/README.md +324 -986
  90. package/utils/theme/public-api.d.ts +4 -4
  91. package/utils/theme/src/constants.d.ts +6 -12
  92. package/utils/theme/src/models/theme.d.ts +46 -173
  93. package/utils/theme/src/providers/theme.provider.d.ts +0 -10
  94. package/utils/theme/src/providers/theme.provider.types.d.ts +16 -15
  95. package/utils/theme/src/theme-assets/theme-assets.service.d.ts +16 -12
  96. package/utils/theme/src/theme-dom/theme-dom.service.d.ts +8 -0
  97. package/utils/theme/src/theme.service.d.ts +24 -27
  98. package/utils/theme/src/utils/utils.d.ts +2 -10
  99. package/utils/translation/README.md +170 -1390
  100. package/utils/translation/public-api.d.ts +3 -3
  101. package/utils/translation/src/constants.d.ts +7 -9
  102. package/utils/translation/src/models/translation.d.ts +9 -10
  103. package/utils/translation/src/providers/translation.provider.d.ts +17 -28
  104. package/utils/translation/src/providers/translation.provider.types.d.ts +13 -6
  105. package/utils/translation/src/translation.service.d.ts +37 -9
  106. package/components/dropdown/src/services/dropdown.service.d.ts +0 -22
  107. package/directives/only-numbers/src/just-numbers.directive.d.ts +0 -9
  108. package/fesm2022/sixbell-telco-sdk-utils-resource-loader.mjs +0 -1222
  109. package/fesm2022/sixbell-telco-sdk-utils-resource-loader.mjs.map +0 -1
  110. package/utils/resource-loader/README.md +0 -460
  111. package/utils/resource-loader/public-api.d.ts +0 -1
  112. package/utils/resource-loader/src/cache/index.d.ts +0 -2
  113. package/utils/resource-loader/src/cache/layers/factory.d.ts +0 -38
  114. package/utils/resource-loader/src/cache/layers/index.d.ts +0 -3
  115. package/utils/resource-loader/src/cache/layers/indexed-db-cache.d.ts +0 -118
  116. package/utils/resource-loader/src/cache/layers/local-storage-cache.d.ts +0 -86
  117. package/utils/resource-loader/src/cache/layers/memory-cache.d.ts +0 -76
  118. package/utils/resource-loader/src/cache/types.d.ts +0 -107
  119. package/utils/resource-loader/src/config/index.d.ts +0 -1
  120. package/utils/resource-loader/src/config/load-config.d.ts +0 -32
  121. package/utils/resource-loader/src/constants.d.ts +0 -38
  122. package/utils/resource-loader/src/http/index.d.ts +0 -1
  123. package/utils/resource-loader/src/http/retryable-client.d.ts +0 -43
  124. package/utils/resource-loader/src/index.d.ts +0 -1
  125. package/utils/resource-loader/src/resource-loader.d.ts +0 -67
  126. package/utils/resource-loader/src/types.d.ts +0 -152
  127. package/utils/resource-loader/src/utils/cache-validator.d.ts +0 -72
  128. package/utils/resource-loader/src/utils/helpers.d.ts +0 -15
  129. package/utils/resource-loader/src/utils/index.d.ts +0 -2
  130. package/utils/theme/src/providers/constants.d.ts +0 -7
  131. package/utils/translation/src/providers/constants.d.ts +0 -11
@@ -1,25 +1,28 @@
1
1
  # Theme Utility
2
2
 
3
- A comprehensive, signal-based theme management system for Angular 19 applications with multi-tenant support, color scheme detection, runtime configuration loading, and persistent storage.
3
+ Runtime theme system for Angular 19 with config-driven loading, JSON configs, assets, and signal-based state.
4
4
 
5
- ## Quick Start
5
+ This doc covers:
6
+
7
+ - Runtime theme config + JSON schema
8
+ - Loading flow and caching behavior
9
+ - Theme/asset switching behavior
10
+ - How to add or extend themes safely
11
+ - Tailwind `@theme` registration for new variables
6
12
 
7
- ### Basic Setup
13
+ ---
14
+
15
+ ## Quick Start
8
16
 
9
17
  ```typescript
10
- import { provideTheme } from '@sixbell-telco/sdk/utils/theme';
18
+ import { provideRuntimeTheme } from '@sixbell-telco/sdk/utils/theme';
11
19
 
12
20
  bootstrapApplication(AppComponent, {
13
- providers: [
14
- provideTheme({
15
- defaultTheme: 'sixbell_telco',
16
- defaultScheme: 'system',
17
- }),
18
- ],
21
+ providers: [provideRuntimeTheme('/assets/themes/themes.json')],
19
22
  });
20
23
  ```
21
24
 
22
- ### Using the Theme Service
25
+ Switch theme or scheme:
23
26
 
24
27
  ```typescript
25
28
  import { Component, inject } from '@angular/core';
@@ -29,9 +32,9 @@ import { ThemeService } from '@sixbell-telco/sdk/utils/theme';
29
32
  selector: 'app-theme-switcher',
30
33
  template: `
31
34
  <select (change)="onThemeChange($event)">
32
- <option *ngFor="let theme of themeService.getAvailableThemes()">
33
- {{ theme }}
34
- </option>
35
+ @for (theme of themeService.getAvailableThemes(); track theme) {
36
+ <option [value]="theme">{{ theme }}</option>
37
+ }
35
38
  </select>
36
39
  <button (click)="toggleScheme()">Current: {{ themeService.resolvedScheme() }}</button>
37
40
  `,
@@ -52,1079 +55,414 @@ export class ThemeSwitcherComponent {
52
55
  }
53
56
  ```
54
57
 
55
- ## Features
56
-
57
- ### 🎨 Theme Management
58
-
59
- - **Multiple Themes**: Support for base theme + additional themes
60
- - **Color Schemes**: Light, Dark, and System (automatic detection)
61
- - **Signals-Based**: Reactive theme and scheme selection
62
- - **Computed Properties**: Derived values like `isDarkTheme()` and `resolvedScheme()`
63
-
64
- ### 💾 Persistence
65
-
66
- - **localStorage Integration**: Automatic saving/loading of user preferences
67
- - **Error Handling**: Graceful fallback when storage is unavailable (SSR, private browsing)
68
- - **Multi-Key Storage**: Separate keys for theme and scheme with namespace isolation
69
-
70
- ### 🚀 Runtime Configuration
71
-
72
- - **Dynamic Theme Loading**: Load theme configs from remote URLs
73
- - **Smart Caching**: IndexedDB for long-term persistence + in-memory for current session
74
- - **Fallback Strategies**: Stale-while-revalidate, use-stale-on-error for resilience
75
- - **Asset Management**: Dynamic logo/banner/illustration loading based on theme and scheme
76
-
77
- ### 🌐 System Integration
78
-
79
- - **OS Preference Detection**: Automatically detect system dark mode preference
80
- - **Live Updates**: Listen to OS theme preference changes
81
- - **DOM Injection**: Automatic CSS variable and font-face injection
82
-
83
- ### 🏢 Multi-Tenant Support
84
-
85
- - **Theme Variants**: Define light/dark variants for each theme
86
- - **Dynamic Assets**: Map brand-specific assets to themes
87
- - **Global Variables**: Set theme-specific CSS variables
88
- - **Font Management**: Load theme-specific fonts and styles
89
-
90
- ## Installation
91
-
92
- The theme utility is built into `@sixbell-telco/sdk`:
93
-
94
- ```bash
95
- npm install @sixbell-telco/sdk
96
- ```
97
-
98
- Import from the specific entry point:
99
-
100
- ```typescript
101
- import { ThemeService, provideTheme } from '@sixbell-telco/sdk/utils/theme';
102
- ```
103
-
104
- ## API Reference
105
-
106
- ### ThemeService
107
-
108
- Main service for managing theme state and operations.
109
-
110
- #### Signals (Reactive)
111
-
112
- ```typescript
113
- // Current selected theme (e.g., 'sixbell_telco')
114
- selectedTheme: Signal<string>;
115
-
116
- // Current selected scheme ('system', 'light', or 'dark')
117
- selectedScheme: Signal<ThemeScheme>;
118
-
119
- // Resolved scheme (always 'light' or 'dark', never 'system')
120
- resolvedScheme: Computed<ResolvedThemeScheme>;
121
-
122
- // Whether current scheme is dark
123
- isDarkTheme: Computed<boolean>;
124
-
125
- // Final computed theme identifier (e.g., 'sixbell_telco__dark')
126
- finalTheme: Computed<string>;
58
+ ---
59
+
60
+ ## Runtime Model Overview
61
+
62
+ The theme system is config-based:
63
+
64
+ 1. App loads a config (`themes.json`) containing a list of theme paths.
65
+ 2. The selected theme file is loaded blocking (fonts + assets are ready before paint).
66
+ 3. Remaining themes are prefetched non-blocking so switching is instant later.
67
+
68
+ ### Mermaid: Boot Flow
69
+
70
+ ```mermaid
71
+ sequenceDiagram
72
+ participant App
73
+ participant Provider as provideRuntimeTheme
74
+ participant Loader as RuntimeConfigLoader
75
+ participant Dexie as RuntimeConfigStore
76
+ participant ThemeSvc as ThemeService
77
+
78
+ App->>Provider: bootstrap
79
+ Provider->>Loader: loadLatest(theme-config)
80
+ Loader->>Dexie: get(cacheKey)
81
+ alt cached & schema ok
82
+ Dexie-->>Loader: cached
83
+ Loader-->>Provider: theme-config (source=cache)
84
+ else cache miss / schema mismatch
85
+ Loader->>Provider: fetch(theme-config)
86
+ Provider->>Loader: parse + store
87
+ Loader->>Dexie: set(cacheKey)
88
+ end
89
+
90
+ Provider->>ThemeSvc: applyRuntimeConfig()
91
+ Provider->>Provider: resolve selectedTheme
92
+ Provider->>Loader: loadLatest(theme file)
93
+ Provider->>ThemeSvc: configureRuntime(theme, blocking=true)
94
+ Provider->>Loader: prefetch remaining theme files (non-blocking)
95
+ Provider->>ThemeSvc: configureRuntime(theme, blocking=false)
96
+ ```
97
+
98
+ ---
99
+
100
+ ## Files and Schemas
101
+
102
+ ### 1) Theme Config (`themes.json`)
103
+
104
+ ```json
105
+ {
106
+ "meta": {
107
+ "name": "themes",
108
+ "updatedAt": "2026-02-02T00:00:00Z",
109
+ "hash": "showcase-themes-v2",
110
+ "schemaVersion": "2"
111
+ },
112
+ "themes": ["/assets/themes/catalog/sixbell_telco.json", "/assets/themes/catalog/wom.json"],
113
+ "defaultTheme": "sixbell_telco",
114
+ "defaultScheme": "system",
115
+ "excludeThemes": []
116
+ }
127
117
  ```
128
118
 
129
- #### Methods
130
-
131
- ```typescript
132
- // Configure static theme settings
133
- configure(config?: ThemeConfig): void;
134
-
135
- // Load and configure runtime theme from remote source
136
- configureRuntime(config: RuntimeThemeConfig): void;
137
-
138
- // Change the active theme
139
- setTheme(theme: string): void;
140
-
141
- // Change the color scheme
142
- setScheme(scheme: ThemeScheme): void;
143
-
144
- // Get all available themes
145
- getAvailableThemes(): string[];
146
-
147
- // Get available schemes
148
- getAvailableSchemes(): ThemeScheme[];
149
-
150
- // Get default theme
151
- getDefaultTheme(): string;
152
-
153
- // Get default scheme
154
- getDefaultScheme(): ThemeScheme;
155
-
156
- // Get localized theme name (respects translation service)
157
- getLocalizedThemeName(theme: string): string;
158
-
159
- // Get localized scheme name (respects translation service)
160
- getLocalizedSchemeName(scheme: string): string;
161
-
162
- // Get current theme identifier
163
- getCurrentThemeIdentifier(): string;
164
-
165
- // Load theme from saved preferences
166
- loadSavedPreferences(): void;
167
-
168
- // Set custom resource loader for runtime configs
169
- setRuntimeLoader(
170
- configPath: string,
171
- loader: ResourceLoader,
172
- loaderOptions?: ResourceLoaderRequestOptions<RuntimeThemeConfig>
173
- ): void;
119
+ Config rules:
120
+
121
+ - `themes` is required.
122
+ - Each item is a theme JSON path.
123
+ - Theme name comes from `meta.name` inside the theme file.
124
+ - `excludeThemes` hides themes at runtime without deleting files.
125
+ - `meta.schemaVersion` is required and used to invalidate old cache entries.
126
+ - `meta.hash` is required and used for update detection.
127
+
128
+ ### 2) Per-Theme Runtime Config (`<theme>.json`)
129
+
130
+ ```json
131
+ {
132
+ "meta": {
133
+ "name": "sixbell_telco",
134
+ "updatedAt": "2026-02-02T00:00:00Z",
135
+ "hash": "showcase-theme-sixbell-telco-v1",
136
+ "schemaVersion": "2"
137
+ },
138
+ "fonts": [
139
+ {
140
+ "family": "Poppins",
141
+ "faces": [{ "weight": 400, "style": "normal", "src": "./assets/fonts/Poppins-Regular.ttf" }]
142
+ }
143
+ ],
144
+ "themes": {
145
+ "light": {
146
+ "variables": {
147
+ "colors": {
148
+ "--color-primary": "oklch(65.64% 0.1155 219.3)"
149
+ },
150
+ "radius": {},
151
+ "sizes": {},
152
+ "effects": {},
153
+ "others": {
154
+ "--font-body": "Poppins, sans-serif"
155
+ }
156
+ }
157
+ },
158
+ "dark": {
159
+ "variables": {
160
+ "colors": {
161
+ "--color-primary": "oklch(65.64% 0.1155 219.3)"
162
+ },
163
+ "radius": {},
164
+ "sizes": {},
165
+ "effects": {},
166
+ "others": {
167
+ "--font-body": "Poppins, sans-serif"
168
+ }
169
+ }
170
+ }
171
+ },
172
+ "assets": [
173
+ {
174
+ "name": "logo",
175
+ "light": "/assets/logos/sixbell-logo-light-mode.svg",
176
+ "dark": "/assets/logos/sixbell-logo-dark-mode.svg"
177
+ }
178
+ ]
179
+ }
174
180
  ```
175
181
 
176
- ### ThemeStorageService
177
-
178
- Handles persistent storage of theme preferences.
179
-
180
- ```typescript
181
- // Save current theme to localStorage
182
- saveTheme(theme: string): void;
182
+ Theme file rules:
183
183
 
184
- // Retrieve saved theme
185
- getSavedTheme(): string | null;
184
+ - File should contain `themes.light` and `themes.dark`.
185
+ - Both `light` and `dark` variants are required.
186
+ - `meta.name`, `meta.hash`, `meta.schemaVersion`, and `meta.updatedAt` are required.
187
+ - `variables` are grouped by category and injected as CSS custom properties with a `data-theme` selector.
188
+ - `others` is required and intended for app-specific tokens not provided by the SDK.
189
+ - `assets` are optional but should have both light and dark variants for each asset.
186
190
 
187
- // Save current scheme to localStorage
188
- saveScheme(scheme: ThemeScheme): void;
191
+ ---
189
192
 
190
- // Retrieve saved scheme
191
- getSavedScheme(): ThemeScheme | null;
193
+ ## ThemeService API (Runtime)
192
194
 
193
- // Clear all saved preferences
194
- clear(): void;
195
- ```
195
+ ### Signals
196
196
 
197
- ### ThemeSchemeService
197
+ - `selectedTheme()` - current theme key
198
+ - `selectedScheme()` - `system | light | dark`
199
+ - `resolvedScheme()` - resolved to `light | dark`
200
+ - `isDarkTheme()` - boolean
201
+ - `finalTheme()` - string like `sixbell_telco__dark`
198
202
 
199
- Handles color scheme detection and resolution.
203
+ ### Common methods
200
204
 
201
205
  ```typescript
202
- // Resolve 'system' scheme to actual 'light' or 'dark'
203
- resolveScheme(scheme: ThemeScheme): ResolvedThemeScheme;
204
-
205
- // Detect system preferred color scheme
206
- detectSystemScheme(): ResolvedThemeScheme;
207
-
208
- // Listen to system scheme changes
209
- listenToSystemSchemeChanges(
210
- listener: (scheme: ResolvedThemeScheme) => void
211
- ): () => void;
206
+ themeService.setTheme('wom');
207
+ themeService.setScheme('dark');
208
+ themeService.getAvailableThemes();
209
+ themeService.getDefaultTheme();
212
210
  ```
213
211
 
214
- ### ThemeDomService
215
-
216
- Handles DOM manipulation and CSS injection.
217
-
218
- ```typescript
219
- // Inject font-face declarations
220
- injectFonts(fonts: FontDefinition[]): void;
212
+ ---
221
213
 
222
- // Inject global CSS variables
223
- injectGlobalVariables(variables: Record<string, string>): void;
214
+ ## How the Flow Works (Detailed)
224
215
 
225
- // Inject theme-specific CSS variables
226
- injectThemeStyles(themes: Record<string, ThemeVariants>): void;
216
+ ### Mermaid: Runtime Theme Selection
227
217
 
228
- // Set active theme on document body
229
- setActiveTheme(themeIdentifier: string): void;
218
+ ```mermaid
219
+ flowchart TD
220
+ A[User sets theme/scheme] --> B[ThemeService updates signals]
221
+ B --> C[Resolved scheme computed]
222
+ C --> D[finalTheme computed]
223
+ D --> E[ThemeDomService sets data-theme]
224
+ E --> F[ThemeStorageService persists preferences]
225
+ D --> G[ThemeDomService injects CSS vars]
230
226
  ```
231
227
 
232
- ### ThemeAssetsService
233
-
234
- Manages dynamic asset loading based on theme and scheme.
228
+ ### Config + Theme Loading (Boot)
235
229
 
236
- ```typescript
237
- // Get asset URL for current theme and scheme
238
- getAssetUrl(assetKey: string, theme?: string): string | null;
230
+ 1. `provideRuntimeTheme()` runs at app init.
231
+ 2. It loads the config via `RuntimeConfigLoader`.
232
+ 3. Available themes are computed with `excludeThemes`.
233
+ 4. The saved theme is restored (if still available).
234
+ 5. Selected theme config is loaded blocking (fonts + assets).
235
+ 6. Remaining themes are loaded non-blocking.
239
236
 
240
- // Get full asset object with light/dark variants
241
- getAsset(assetKey: string, theme?: string): ThemeAsset | null;
237
+ ### Asset Resolution
242
238
 
243
- // Check if asset exists
244
- hasAsset(assetKey: string, theme?: string): boolean;
245
-
246
- // Get all assets for specific theme
247
- getThemeAssets(theme?: string): ThemeAssets | null;
248
-
249
- // Clear asset cache
250
- clearCache(): void;
251
- ```
252
-
253
- ### Providers
254
-
255
- #### provideTheme(config?)
256
-
257
- Configure static theme settings.
239
+ - Assets are resolved by theme name + asset key + scheme.
240
+ - If an asset is missing in the current config, the last working config is used.
241
+ - Asset cache is in-memory by theme.
258
242
 
259
243
  ```typescript
260
- providers: [
261
- provideTheme({
262
- additionalThemes: ['custom', 'premium'],
263
- defaultTheme: 'sixbell_telco',
264
- defaultScheme: 'system',
265
- excludeThemes: ['draft'],
266
- }),
267
- ];
244
+ const url = assetsService.getAssetUrl(themeService.selectedTheme(), 'logo', themeService.resolvedScheme());
268
245
  ```
269
246
 
270
- #### provideRuntimeTheme(configPath, options?)
247
+ ---
271
248
 
272
- Load theme configuration from a remote URL.
249
+ ## Cache and Schema Versioning
273
250
 
274
- ```typescript
275
- providers: [
276
- provideRuntimeTheme('/assets/themes/config.json', {
277
- freshOnNavigation: false,
278
- cacheTTL: 1000 * 60 * 60 * 24, // 24 hours
279
- useStaleOnError: true,
280
- }),
281
- ];
282
- ```
251
+ Runtime configs are cached in IndexedDB (Dexie) as last-known-good.
283
252
 
284
- ## Common Scenarios
253
+ When JSON schema changes, bump `THEME_SCHEMA_VERSION` and update `meta.schemaVersion` in JSON.
254
+ Old cached entries will be discarded automatically.
285
255
 
286
- ### Scenario 1: Dynamic Theme Switching
256
+ Hash requirements:
287
257
 
288
- ```typescript
289
- import { Component, ChangeDetectionStrategy, inject } from '@angular/core';
290
- import { CommonModule } from '@angular/common';
291
- import { ThemeService } from '@sixbell-telco/sdk/utils/theme';
292
- import { ButtonComponent } from '@sixbell-telco/sdk/components/button';
293
- import {
294
- DropdownComponent,
295
- DropdownTriggerComponent,
296
- DropdownContentComponent,
297
- DropdownItemRadioComponent,
298
- } from '@sixbell-telco/sdk/components/dropdown';
258
+ - `meta.hash` is required for the config and each theme file.
259
+ - Config hash drives update detection.
299
260
 
300
- @Component({
301
- selector: 'app-theme-switcher',
302
- standalone: true,
303
- imports: [CommonModule, ButtonComponent, DropdownComponent, DropdownTriggerComponent, DropdownContentComponent, DropdownItemRadioComponent],
304
- changeDetection: ChangeDetectionStrategy.OnPush,
305
- template: `
306
- <div [attr.data-theme]="themeService.finalTheme()">
307
- <st-dropdown>
308
- <st-dropdown-trigger>
309
- <st-button>
310
- {{ themeService.getLocalizedThemeName(themeService.selectedTheme()) }}
311
- </st-button>
312
- </st-dropdown-trigger>
313
- <st-dropdown-content>
314
- @for (theme of themeService.getAvailableThemes(); track theme) {
315
- <st-dropdown-item-radio
316
- [value]="theme"
317
- [checked]="themeService.selectedTheme() === theme"
318
- (checkedChanged)="themeService.setTheme($event)"
319
- >
320
- {{ themeService.getLocalizedThemeName(theme) }}
321
- </st-dropdown-item-radio>
322
- }
323
- </st-dropdown-content>
324
- </st-dropdown>
325
- </div>
326
- `,
327
- })
328
- export class ThemeSwitcherComponent {
329
- protected readonly themeService = inject(ThemeService);
330
- }
261
+ ```ts
262
+ // projects/sdk/utils/theme/src/constants.ts
263
+ export const THEME_SCHEMA_VERSION = '2' as const;
331
264
  ```
332
265
 
333
- ### Scenario 2: System Preference with Override
334
-
335
- ```typescript
336
- import { Component, ChangeDetectionStrategy, computed, inject } from '@angular/core';
337
- import { CommonModule } from '@angular/common';
338
- import { ThemeService, ThemeScheme } from '@sixbell-telco/sdk/utils/theme';
339
- import { ButtonComponent } from '@sixbell-telco/sdk/components/button';
340
-
341
- @Component({
342
- selector: 'app-scheme-controller',
343
- standalone: true,
344
- imports: [CommonModule, ButtonComponent],
345
- changeDetection: ChangeDetectionStrategy.OnPush,
346
- template: `
347
- <div class="controls">
348
- <label>
349
- <input type="radio" value="system" [checked]="themeService.selectedScheme() === 'system'" (change)="themeService.setScheme('system')" />
350
- System Preference
351
- </label>
352
- <label>
353
- <input type="radio" value="light" [checked]="themeService.selectedScheme() === 'light'" (change)="themeService.setScheme('light')" />
354
- Light Mode
355
- </label>
356
- <label>
357
- <input type="radio" value="dark" [checked]="themeService.selectedScheme() === 'dark'" (change)="themeService.setScheme('dark')" />
358
- Dark Mode
359
- </label>
360
- </div>
361
- <div>Active: {{ themeService.resolvedScheme() }}</div>
362
- `,
363
- })
364
- export class SchemeControllerComponent {
365
- protected readonly themeService = inject(ThemeService);
366
- }
266
+ ```ts
267
+ // note: THEME_SCHEMA_VERSION is exported from the theme public API
268
+ // import from @sixbell-telco/sdk/utils/theme
367
269
  ```
368
270
 
369
- ### Scenario 3: Multi-Tenant Asset Loading
271
+ ---
370
272
 
371
- ```typescript
372
- import { Component, ChangeDetectionStrategy, computed, inject } from '@angular/core';
373
- import { ThemeAssetsService } from '@sixbell-telco/sdk/utils/theme';
374
- import { ThemeService } from '@sixbell-telco/sdk/utils/theme';
273
+ ## Tailwind Token Registration (Required for New Variables)
375
274
 
376
- @Component({
377
- selector: 'app-brand-header',
378
- standalone: true,
379
- changeDetection: ChangeDetectionStrategy.OnPush,
380
- template: `
381
- <div class="brand-header">
382
- <img [src]="logoUrl()" alt="Logo" [style.height.px]="logoHeight()" />
383
- </div>
384
- `,
385
- })
386
- export class BrandHeaderComponent {
387
- private readonly assetsService = inject(ThemeAssetsService);
388
- private readonly themeService = inject(ThemeService);
275
+ Runtime variables are injected at runtime, but Tailwind utility classes are compiled at build time. If you add new variables and want Tailwind classes for them, you must register the tokens in your global CSS:
389
276
 
390
- logoUrl = computed(() => {
391
- return this.assetsService.getAssetUrl('logo') || '/fallback-logo.svg';
392
- });
277
+ ```css
278
+ @import 'tailwindcss';
393
279
 
394
- logoHeight = computed(() => {
395
- return this.themeService.isDarkTheme() ? 48 : 40;
396
- });
280
+ @theme {
281
+ --color-counters-input: oklch(65.5% 0.0126 255.51);
282
+ --color-counters-done: oklch(69.5% 0.2115 142.5);
283
+ --color-counters-busy: oklch(75.89% 0.181 99.99);
397
284
  }
398
285
  ```
399
286
 
400
- ### Scenario 4: Theme-Aware Styling
401
-
402
- ```typescript
403
- import { Component, ChangeDetectionStrategy, computed, inject } from '@angular/core';
404
- import { cn } from '@sixbell-telco/sdk/utils/cn';
405
- import { ThemeService } from '@sixbell-telco/sdk/utils/theme';
287
+ When you add custom tokens under `variables.others`, register those tokens in your app `@theme` block so Tailwind utilities can use them.
406
288
 
407
- @Component({
408
- selector: 'app-adaptive',
409
- standalone: true,
410
- changeDetection: ChangeDetectionStrategy.OnPush,
411
- template: ` <div [class]="containerClass()">Content adapts to theme</div> `,
412
- })
413
- export class AdaptiveComponent {
414
- private readonly themeService = inject(ThemeService);
289
+ ---
415
290
 
416
- containerClass = computed(() =>
417
- cn('p-4 rounded-lg transition-colors', this.themeService.isDarkTheme() ? 'bg-slate-900 text-white' : 'bg-white text-slate-900'),
418
- );
419
- }
420
- ```
291
+ ## Extending Themes (Add New Theme)
421
292
 
422
- ## Real-World Examples
293
+ ### Step 1: Add a theme JSON
423
294
 
424
- ### Example 1: Complete App Setup with Runtime Config
295
+ Create `/assets/themes/catalog/acme.json`:
425
296
 
426
- ```typescript
427
- import { bootstrapApplication } from '@angular/platform-browser';
428
- import { provideHttpClient } from '@angular/common/http';
429
- import { provideTheme, provideRuntimeTheme } from '@sixbell-telco/sdk/utils/theme';
430
- import { ResourceLoader } from '@sixbell-telco/sdk/utils/resource-loader';
431
- import { AppComponent } from './app.component';
432
-
433
- bootstrapApplication(AppComponent, {
434
- providers: [
435
- provideHttpClient(),
436
- provideTheme({
437
- defaultTheme: 'sixbell_telco',
438
- defaultScheme: 'system',
439
- additionalThemes: ['wom', 'custom'],
440
- }),
441
- provideRuntimeTheme('/api/v1/themes/config', {
442
- freshOnNavigation: false,
443
- cacheTTL: 1000 * 60 * 60 * 24,
444
- staleWhileRevalidate: true,
445
- useStaleOnError: true,
446
- }),
297
+ ```json
298
+ {
299
+ "meta": {
300
+ "name": "acme",
301
+ "updatedAt": "2026-02-02T00:00:00Z",
302
+ "hash": "acme-theme-v1",
303
+ "schemaVersion": "2"
304
+ },
305
+ "fonts": [
306
+ {
307
+ "family": "Acme Sans",
308
+ "faces": [{ "weight": 400, "style": "normal", "src": "/assets/fonts/AcmeSans-Regular.woff2" }]
309
+ }
447
310
  ],
448
- });
449
- ```
450
-
451
- ### Example 2: Theme Service in Layout Component
452
-
453
- ```typescript
454
- import { Component, ChangeDetectionStrategy, computed, inject } from '@angular/core';
455
- import { CommonModule } from '@angular/common';
456
- import { ThemeService, ThemeScheme } from '@sixbell-telco/sdk/utils/theme';
457
- import { ButtonComponent } from '@sixbell-telco/sdk/components/button';
458
- import {
459
- DropdownComponent,
460
- DropdownTriggerComponent,
461
- DropdownContentComponent,
462
- DropdownItemRadioComponent,
463
- } from '@sixbell-telco/sdk/components/dropdown';
464
-
465
- @Component({
466
- selector: 'app-layout',
467
- standalone: true,
468
- imports: [CommonModule, ButtonComponent, DropdownComponent, DropdownTriggerComponent, DropdownContentComponent, DropdownItemRadioComponent],
469
- changeDetection: ChangeDetectionStrategy.OnPush,
470
- template: `
471
- <header [attr.data-theme]="themeService.finalTheme()">
472
- <div class="theme-switcher">
473
- <!-- Theme Selector -->
474
- <st-dropdown>
475
- <st-dropdown-trigger>
476
- <st-button>Select Theme</st-button>
477
- </st-dropdown-trigger>
478
- <st-dropdown-content>
479
- @for (theme of themeService.getAvailableThemes(); track theme) {
480
- <st-dropdown-item-radio
481
- [value]="theme"
482
- [checked]="themeService.selectedTheme() === theme"
483
- (checkedChanged)="themeService.setTheme($event)"
484
- >
485
- {{ themeService.getLocalizedThemeName(theme) }}
486
- </st-dropdown-item-radio>
487
- }
488
- </st-dropdown-content>
489
- </st-dropdown>
490
-
491
- <!-- Scheme Selector -->
492
- <st-dropdown>
493
- <st-dropdown-trigger>
494
- <st-button>Select Scheme</st-button>
495
- </st-dropdown-trigger>
496
- <st-dropdown-content>
497
- @for (scheme of themeService.getAvailableSchemes(); track scheme) {
498
- <st-dropdown-item-radio
499
- [value]="scheme"
500
- [checked]="themeService.selectedScheme() === scheme"
501
- (checkedChanged)="themeService.setScheme($event)"
502
- >
503
- {{ themeService.getLocalizedSchemeName(scheme) }}
504
- </st-dropdown-item-radio>
505
- }
506
- </st-dropdown-content>
507
- </st-dropdown>
508
-
509
- <div class="status">Current: {{ themeService.selectedTheme() }} - {{ themeService.resolvedScheme() }}</div>
510
- </div>
511
- </header>
512
-
513
- <main>
514
- <ng-content></ng-content>
515
- </main>
516
- `,
517
- })
518
- export class LayoutComponent {
519
- protected readonly themeService = inject(ThemeService);
520
- }
521
- ```
522
-
523
- ### Example 3: Multi-Tenant Brand Switcher
524
-
525
- ````typescript
526
- import { Component, ChangeDetectionStrategy, inject } from '@angular/core';
527
- import { CommonModule } from '@angular/common';
528
- import { ThemeService } from '@sixbell-telco/sdk/utils/theme';
529
- import { ThemeAssetsService } from '@sixbell-telco/sdk/utils/theme';
530
- import { ButtonComponent } from '@sixbell-telco/sdk/components/button';
531
-
532
- @Component({
533
- selector: 'app-brand-switcher',
534
- standalone: true,
535
- imports: [CommonModule, ButtonComponent],
536
- changeDetection: ChangeDetectionStrategy.OnPush,
537
- template: `
538
- <div class="brand-grid">
539
- @for (brand of brands; track brand) {
540
- <st-button
541
- [variant]="currentBrand() === brand ? 'primary' : 'base'"
542
- [style.background-image]="'url(' + logoFor(brand) + ')'"
543
- (click)="switchBrand(brand)"
544
- >
545
- {{ brand }}
546
- </st-button>
311
+ "themes": {
312
+ "light": {
313
+ "variables": {
314
+ "colors": {
315
+ "--color-primary": "oklch(70% 0.1 220)"
316
+ },
317
+ "radius": {},
318
+ "sizes": {},
319
+ "effects": {},
320
+ "others": {
321
+ "--font-body": "Acme Sans, sans-serif"
322
+ }
547
323
  }
548
- </div>
549
- `,
550
- })
551
- export class BrandSwitcherComponent {
552
- private readonly themeService = inject(ThemeService);
553
- private readonly assetsService = inject(ThemeAssetsService);
554
-
555
- brands = this.themeService.getAvailableThemes();
556
- currentBrand = this.themeService.selectedTheme;
557
-
558
- logoFor(brand: string): string {
559
- return this.assetsService.getAssetUrl('logo', brand) || '/default-logo.svg';
560
- }
561
-
562
- switchBrand(brand: string): void {
563
- this.themeService.setTheme(brand);
564
- }
565
- }
566
- ```## Configuration Guide
567
-
568
- ### Static Theme Configuration
569
-
570
- ```typescript
571
- interface ThemeConfig {
572
- // Additional themes beyond 'sixbell_telco'
573
- additionalThemes?: readonly string[];
574
-
575
- // Themes to exclude from available options
576
- excludeThemes?: readonly string[];
577
-
578
- // Default theme on first load
579
- defaultTheme?: string;
580
-
581
- // Default color scheme on first load
582
- defaultScheme?: ThemeScheme; // 'system' | 'light' | 'dark'
583
- }
584
- ````
585
-
586
- ### Runtime Theme Configuration
587
-
588
- ```typescript
589
- interface RuntimeThemeConfig {
590
- // Map of theme name to light/dark variants
591
- themes: {
592
- [themeName: string]: {
593
- light: ThemeVariant;
594
- dark: ThemeVariant;
595
- };
596
- };
597
-
598
- // Assets mapped to themes (logos, banners, illustrations)
599
- assets?: {
600
- [themeName: string]: {
601
- [assetKey: string]: ThemeAsset | NestedAssets;
602
- };
603
- };
604
-
605
- // Global CSS variables for all themes
606
- globalVariables?: Record<string, string>;
607
-
608
- // Font definitions to inject
609
- fonts?: FontDefinition[];
610
- }
611
-
612
- interface ThemeVariant {
613
- daisyuiName: string; // DaisyUI theme name
614
- prefersDark: boolean; // Whether this is dark variant
615
- variables?: Record<string, string>; // Theme-specific CSS variables
616
- }
617
-
618
- interface ThemeAsset {
619
- light: string; // URL for light scheme
620
- dark?: string; // URL for dark scheme (optional)
621
- }
622
- ```
623
-
624
- ### How It Works
625
-
626
- #### Theme Resolution Flow
627
-
628
- ```
629
- User selects theme/scheme
630
- ↓
631
- ThemeService.setTheme() / setScheme()
632
- ↓
633
- Signals updated (selectedTheme, selectedScheme)
634
- ↓
635
- Computed values recalculated (resolvedScheme, isDarkTheme, finalTheme)
636
- ↓
637
- Effect listeners triggered (DOM updates)
638
- ↓
639
- Theme persisted to localStorage (async)
640
- ↓
641
- CSS variables injected (ThemeDomService)
642
- ↓
643
- data-theme attribute set on document body
644
- ```
645
-
646
- #### Storage & Caching Strategy
647
-
648
- The theme system uses a simplified two-layer storage strategy for maximum reliability:
649
-
650
- **Layer 1: In-Memory (Runtime Cache)**
651
-
652
- - Current active theme and scheme
653
- - Last working configuration
654
- - Asset cache with light/dark variants
655
- - Session-scoped, cleared on page refresh
656
- - Provides instant reactivity and computed values
657
-
658
- **Layer 2: IndexedDB (Persistent Cache)**
659
-
660
- - Runtime theme configurations loaded from remote
661
- - Long-term theme asset URLs and metadata
662
- - Multi-day retention with automatic cleanup
663
- - Survives page refreshes and sessions
664
- - Used as fallback when remote config unavailable
665
-
666
- **Why This Design:**
667
-
668
- - **Simplified**: No localStorage race conditions or privacy mode issues
669
- - **Fast**: In-memory layer provides instant access to current state
670
- - **Persistent**: IndexedDB stores heavy runtime configs for recovery
671
- - **Resilient**: Falls back to last working config automatically
672
- - **Safe**: No sensitive data stored, graceful degradation in private browsing
673
-
674
- **When Each Layer Is Used:**
675
-
676
- - **Runtime Flow**: In-memory signals + computed values (no I/O)
677
- - **Config Loading**: Fetch remote → IndexedDB → In-memory → fallback
678
- - **Asset Resolution**: In-memory cache (with scheme variants)
679
- - **Session Persistence**: localStorage (user preferences only, not config)
680
- - **Config Recovery**: Last working IndexedDB entry if remote fails
681
-
682
- ### Signal Reactivity
683
-
684
- All theme changes flow through signals for maximum performance:
685
-
686
- ```
687
- selectedTheme/Scheme signals (user input)
688
- ↓
689
- Effects trigger (auto-persist to localStorage)
690
- ↓
691
- Computed values update (resolvedScheme, isDarkTheme, finalTheme)
692
- ↓
693
- Components subscribed via signals detect change
694
- ↓
695
- OnPush change detection → Template update (instant!)
696
- ↓
697
- DOM updates apply via ThemeDomService
698
- ```
699
-
700
- **Why Signals?**
701
-
702
- - No manual unsubscribes needed (no memory leaks)
703
- - Automatic fine-grained reactivity
704
- - Computed values only recalculate when dependencies change
705
- - Optimal change detection with OnPush strategy
706
- - Better performance than RxJS Observables for this use case
707
-
708
- ## Performance Tips
709
-
710
- ### 1. Use Computed Values Carefully
711
-
712
- ```typescript
713
- // ✅ Good: Single computed value
714
- isDarkTheme = this.themeService.isDarkTheme;
715
-
716
- // ❌ Avoid: Complex computation in template
717
- isDarkTheme() ? 'dark' : 'light';
718
- ```
719
-
720
- ### 2. Cache Theme-Specific Data
721
-
722
- ```typescript
723
- // ✅ Cache loaded theme config
724
- private runtimeConfig = signal<RuntimeThemeConfig | null>(null);
725
-
726
- // ❌ Avoid: Reloading on every change
727
- this.themeService.configureRuntime(config);
728
- ```
729
-
730
- ### 3. Use OnPush Change Detection
731
-
732
- ```typescript
733
- @Component({
734
- changeDetection: ChangeDetectionStrategy.OnPush,
735
- })
736
- export class MyComponent {
737
- // Signals are always detected efficiently
324
+ },
325
+ "dark": {
326
+ "variables": {
327
+ "colors": {
328
+ "--color-primary": "oklch(65% 0.1 220)"
329
+ },
330
+ "radius": {},
331
+ "sizes": {},
332
+ "effects": {},
333
+ "others": {
334
+ "--font-body": "Acme Sans, sans-serif"
335
+ }
336
+ }
337
+ }
338
+ },
339
+ "assets": [
340
+ {
341
+ "name": "logo",
342
+ "light": "/assets/logos/acme_light.svg",
343
+ "dark": "/assets/logos/acme_dark.svg"
344
+ }
345
+ ]
738
346
  }
739
347
  ```
740
348
 
741
- ### 4. Lazy Load Heavy Assets
742
-
743
- ```typescript
744
- // ✅ Load logos only when needed
745
- logoUrl = computed(() => {
746
- if (!this.isVisible()) return null;
747
- return this.assetsService.getAssetUrl('logo');
748
- });
749
- ```
750
-
751
- ## Architecture Deep Dive
752
-
753
- ### ThemeService Core
754
-
755
- The main service orchestrates all theme operations through signals:
756
-
757
- ```typescript
758
- // Signal-based reactive state (auto-persisted)
759
- selectedTheme: Signal<string>; // Currently active theme
760
- selectedScheme: Signal<ThemeScheme>; // Currently active scheme ('system'|'light'|'dark')
761
-
762
- // Computed derived values (auto-memoized, no extra I/O)
763
- resolvedScheme: Computed<ResolvedThemeScheme>; // Always 'light' or 'dark'
764
- isDarkTheme: Computed<boolean>; // Quick dark mode check
765
- finalTheme: Computed<string>; // Complete identifier like 'sixbell_telco__dark'
766
- ```
767
-
768
- ### Multi-Service Architecture
769
-
770
- The theme system is composed of focused, single-responsibility services:
771
-
772
- **ThemeService** (Orchestrator)
773
-
774
- - Manages signals and main theme state
775
- - Coordinates configuration loading
776
- - Exposes high-level API for components
777
-
778
- **ThemeStorageService** (Preferences)
779
-
780
- - Persists user choices (theme, scheme) to localStorage
781
- - Reads saved preferences on app startup
782
- - Includes error handling for private browsing mode
783
-
784
- **ThemeSchemeService** (OS Integration)
785
-
786
- - Detects system dark mode preference via matchMedia
787
- - Resolves 'system' scheme to actual 'light'/'dark' value
788
- - Listens to OS theme changes for live updates
789
-
790
- **ThemeDomService** (DOM Manipulation)
791
-
792
- - Injects CSS variables into document head
793
- - Manages font-face declarations
794
- - Sets data-theme attribute on document body
795
-
796
- **ThemeAssetsService** (Dynamic Assets)
797
-
798
- - Retrieves logos/banners/illustrations for current theme
799
- - Provides automatic light/dark scheme variants
800
- - In-memory cache prevents repeated lookups
801
-
802
- ### Runtime Config Loading Flow
803
-
804
- ```
805
- Remote Config File (JSON)
806
- ↓
807
- ResourceLoader fetches with smart defaults
808
- ↓
809
- IndexedDB Layer stores for recovery
810
- ↓
811
- In-Memory Cache provides instant access
812
- ↓
813
- ThemeService signals updated
814
- ↓
815
- Components automatically re-render via signals
816
- ↓
817
- Assets resolve from nested config by theme/scheme
818
- ```
819
-
820
- **Resilience Features:**
821
-
822
- - Automatic retry with exponential backoff
823
- - Stale-while-revalidate (always try fresh first)
824
- - Use-stale-on-error (use cached if fresh fails)
825
- - Last-working-config fallback
826
- - Per-theme asset resolution
349
+ ### Step 2: Register it in the config
827
350
 
828
- ### In-Memory vs IndexedDB Usage
829
-
830
- **In-Memory Layer (Runtime Cache):**
831
-
832
- - ✅ Instant access (no await)
833
- - ✅ Current active theme/scheme
834
- - ✅ Asset URL lookups
835
- - ✅ Computed values
836
- - ❌ Lost on page refresh
837
- - ❌ Session-scoped only
838
-
839
- **IndexedDB Layer (Persistent Cache):**
840
-
841
- - ✅ Survives page refresh
842
- - ✅ Stores heavy theme configs
843
- - ✅ Recovery when remote unavailable
844
- - ✅ Multi-day retention
845
- - ❌ Async (requires await)
846
- - ❌ Larger storage overhead
847
-
848
- ## Error Handling
849
-
850
- ### Storage Errors
851
-
852
- Storage errors are logged but don't break the app - graceful fallback ensures functionality:
853
-
854
- ```typescript
855
- // Graceful fallback if localStorage unavailable
856
- getSavedTheme(): string | null {
857
- try {
858
- return localStorage.getItem('theme:selectedTheme');
859
- } catch (error) {
860
- logger.error('Failed to read theme from storage', error, {
861
- component: 'ThemeStorageService',
862
- action: 'getSavedTheme'
863
- });
864
- return null; // Falls back to default theme
865
- }
351
+ ```json
352
+ {
353
+ "themes": ["/assets/themes/catalog/sixbell_telco.json", "/assets/themes/catalog/wom.json", "/assets/themes/catalog/acme.json"]
866
354
  }
867
355
  ```
868
356
 
869
- **Scenarios Handled:**
870
-
871
- - Private/Incognito browsing (no localStorage)
872
- - Storage quota exceeded
873
- - Cross-origin restrictions
874
- - Server-side rendering (no localStorage)
875
-
876
- ### Runtime Config Loading Errors
357
+ ### Step 3: Register tokens in `@theme` (if new variables)
877
358
 
878
- If runtime config loading fails, the system automatically uses the last working configuration:
359
+ Add to `projects/sdk/src/_index.css` (or your app CSS):
879
360
 
880
- ```typescript
881
- // Failed fetch? Use cached config
882
- configureRuntime(config: RuntimeThemeConfig): void {
883
- if (!validateThemeConfig(config)) {
884
- logger.error('Invalid runtime theme config', {
885
- component: 'ThemeService',
886
- action: 'configureRuntime'
887
- });
888
- // Automatically falls back to previous working config
889
- return;
890
- }
891
- // Apply new config
361
+ ```css
362
+ @theme {
363
+ --color-acme-highlight: oklch(72% 0.12 30);
364
+ --color-acme-surface: oklch(98% 0.02 95);
892
365
  }
893
366
  ```
894
367
 
895
- **Resilience Strategies:**
896
-
897
- - Network retry with exponential backoff
898
- - Stale-while-revalidate (always try fresh, use stale if fresh fails)
899
- - IndexedDB recovery (last known good config)
900
- - Fallback to in-memory (current session config)
901
-
902
- ## Troubleshooting
903
-
904
- ### Theme Not Persisting
905
-
906
- **Problem**: Theme changes are lost on page refresh.
907
-
908
- **Solution**: Ensure `ThemeStorageService` is provided and localStorage is available:
909
-
910
- ```typescript
911
- // Check localStorage is accessible
912
- const hasStorage = () => {
913
- try {
914
- localStorage.setItem('test', 'test');
915
- localStorage.removeItem('test');
916
- return true;
917
- } catch (e) {
918
- return false; // Private browsing, quota exceeded, etc.
919
- }
920
- };
921
-
922
- // In your component, verify theme is being saved
923
- this.themeService.setTheme('custom');
924
- const saved = localStorage.getItem('theme:selectedTheme');
925
- console.log('Saved theme:', saved); // Should be 'custom'
926
- ```
927
-
928
- ### System Scheme Not Detecting
929
-
930
- **Problem**: OS dark mode preference not being detected.
931
-
932
- **Solution**: Verify matchMedia support and check system preference:
368
+ ### Step 4: Use it
933
369
 
934
370
  ```typescript
935
- // Check if system supports media queries
936
- const supportsMediaQuery = () => {
937
- return window.matchMedia != null;
938
- };
939
-
940
- // Check current system preference
941
- const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
942
- console.log('System prefers dark:', isDarkMode);
943
-
944
- // Verify theme service is using system setting
945
- console.log('Selected scheme:', this.themeService.selectedScheme()); // Should be 'system'
946
- console.log('Resolved scheme:', this.themeService.resolvedScheme()); // Should be 'light' or 'dark'
371
+ themeService.setTheme('acme');
372
+ themeService.setScheme('dark');
947
373
  ```
948
374
 
949
- ### Runtime Config Not Loading
375
+ ---
950
376
 
951
- **Problem**: Remote theme config not loading or showing stale data.
377
+ ## Examples
952
378
 
953
- **Solution**: Check ResourceLoader configuration and network:
379
+ ### Minimal Bootstrap
954
380
 
955
- ```typescript
956
- // Verify config endpoint is accessible
957
- const configUrl = '/api/v1/themes/config';
958
- const response = await fetch(configUrl);
959
- console.log('Config fetch:', response.ok, response.status);
960
-
961
- // Check cache settings
962
- provideRuntimeTheme(configUrl, {
963
- freshOnNavigation: false, // Try fresh first, fall back to cache
964
- cacheTTL: 1000 * 60 * 60 * 24, // 24 hour validity
965
- retries: 3, // Retry failed requests
966
- });
967
-
968
- // Clear IndexedDB cache to force fresh fetch
969
- await indexedDB.databases().forEach((db) => {
970
- indexedDB.deleteDatabase(db.name);
381
+ ```ts
382
+ bootstrapApplication(AppComponent, {
383
+ providers: [provideRuntimeTheme('/assets/themes/themes.json')],
971
384
  });
972
385
  ```
973
386
 
974
- ### Assets Not Loading
975
-
976
- **Problem**: Theme-specific logos/banners not displaying.
977
-
978
- **Solution**: Verify asset configuration and URLs:
979
-
980
- ```typescript
981
- // Check asset exists in config
982
- const hasLogo = this.assetsService.hasAsset('logo');
983
- console.log('Has logo asset:', hasLogo);
984
-
985
- // Get asset URL and verify it's correct
986
- const url = this.assetsService.getAssetUrl('logo');
987
- console.log('Logo URL:', url);
988
-
989
- // Verify for specific theme
990
- const womLogo = this.assetsService.getAssetUrl('logo', 'wom');
991
- console.log('WOM logo URL:', womLogo);
387
+ ### App with SSE Update Support
992
388
 
993
- // Check RuntimeThemeConfig has assets defined
994
- console.log('Runtime config:', this.themeService.runtimeConfig);
389
+ ```ts
390
+ bootstrapApplication(AppComponent, {
391
+ providers: [
392
+ provideRuntimeTheme('/assets/themes/themes.json', {
393
+ appId: 'host-app',
394
+ sse: { url: 'http://localhost:4000/api/runtime/updates?resource=theme', eventType: 'message' },
395
+ }),
396
+ ],
397
+ });
995
398
  ```
996
399
 
997
- ### CSS Variables Not Applying
400
+ ### React to Update Availability
998
401
 
999
- **Problem**: Theme CSS variables not updating when theme changes.
402
+ ```ts
403
+ const themeService = inject(ThemeService);
1000
404
 
1001
- **Solution**: Verify DOM injection and CSS variable names:
1002
-
1003
- ```typescript
1004
- // Check data-theme attribute is set correctly
1005
- const themeAttr = document.body.getAttribute('data-theme');
1006
- console.log('Current data-theme:', themeAttr); // Should be like 'sixbell_telco__light'
1007
-
1008
- // Check CSS variables exist
1009
- const vars = getComputedStyle(document.documentElement);
1010
- console.log('CSS variables:', vars.getPropertyValue('--primary-color'));
1011
-
1012
- // Verify theme styles were injected
1013
- const styleSheets = Array.from(document.styleSheets);
1014
- const themeSheet = styleSheets.find((sheet) => {
1015
- try {
1016
- return sheet.cssRules?.toString().includes('data-theme');
1017
- } catch (e) {
1018
- return false;
405
+ effect(() => {
406
+ if (themeService.updateAvailable()) {
407
+ // prompt user and call refreshTheme()
1019
408
  }
1020
409
  });
1021
- console.log('Theme stylesheet found:', !!themeSheet);
1022
410
  ```
1023
411
 
1024
- ### Performance Issues
1025
-
1026
- **Problem**: App feels sluggish when switching themes.
412
+ ### Manual Refresh
1027
413
 
1028
- **Solution**: Optimize with OnPush change detection and signal usage:
1029
-
1030
- ```typescript
1031
- // ✅ Good: OnPush with signals
1032
- @Component({
1033
- changeDetection: ChangeDetectionStrategy.OnPush,
1034
- })
1035
- export class ThemeAwareComponent {
1036
- isDark = this.themeService.isDarkTheme; // Memoized!
1037
- }
1038
-
1039
- // ❌ Avoid: Default change detection with method calls
1040
- @Component({
1041
- changeDetection: ChangeDetectionStrategy.Default,
1042
- })
1043
- export class SlowComponent {
1044
- isDark() {
1045
- // Called on every digest!
1046
- return this.themeService.isDarkTheme();
1047
- }
1048
- }
1049
-
1050
- // Monitor theme loading performance
1051
- console.time('theme-load');
1052
- await this.themeService.configureRuntime(config);
1053
- console.timeEnd('theme-load');
414
+ ```ts
415
+ await themeService.refreshTheme();
1054
416
  ```
1055
417
 
1056
- ## Best Practices
1057
-
1058
- ### 1. Define Themes at Bootstrap
418
+ ### Using the local runtime API server
1059
419
 
1060
- ```typescript
1061
- // ✅ Good: Define all themes during app init
420
+ ```ts
1062
421
  bootstrapApplication(AppComponent, {
1063
422
  providers: [
1064
- provideTheme({
1065
- additionalThemes: ['wom', 'custom'],
1066
- defaultTheme: 'sixbell_telco',
423
+ provideRuntimeTheme('http://localhost:4000/api/runtime/theme/config', {
424
+ sse: { url: 'http://localhost:4000/api/runtime/updates?resource=theme' },
1067
425
  }),
1068
426
  ],
1069
427
  });
1070
428
  ```
1071
429
 
1072
- ### 2. Use Type-Safe Theme Names
430
+ ## Hash and SchemaVersion Ownership
1073
431
 
1074
- ```typescript
1075
- // ✅ Good: Enum for theme names
1076
- enum BrandTheme {
1077
- SIXBELL = 'sixbell_telco',
1078
- WOM = 'wom',
1079
- CUSTOM = 'custom',
1080
- }
432
+ In production, the backend or build pipeline that publishes runtime JSON should always set:
1081
433
 
1082
- themeService.setTheme(BrandTheme.WOM);
1083
- ```
434
+ - `meta.hash`: update this on any content change (colors, assets, fonts, paths).
435
+ - `meta.schemaVersion`: update only when the JSON structure changes.
1084
436
 
1085
- ### 3. Handle System Preference Changes
437
+ Default mode bootstrap validation:
1086
438
 
1087
- ```typescript
1088
- // ✅ Good: Listen to OS theme changes
1089
- effect(() => {
1090
- if (this.selectedScheme() === 'system') {
1091
- // App will automatically update via computed resolvedScheme
1092
- }
1093
- });
1094
- ```
439
+ - Cached configs are validated on boot against the latest `meta.hash`.
440
+ - If the hash changed, the selected theme reloads before render.
441
+ - If the network check fails, the cached config is used to keep the app available.
1095
442
 
1096
- ### 4. Preload Runtime Config Early
443
+ When editing theme files manually, update the file `meta.hash` and the top-level `meta.hash` so clients detect the change.
1097
444
 
1098
- ```typescript
1099
- // ✅ Good: Load config as early as possible
1100
- bootstrapApplication(AppComponent, {
1101
- providers: [
1102
- provideRuntimeTheme('/api/v1/themes/config', {
1103
- freshOnNavigation: false,
1104
- retries: 3,
1105
- }),
1106
- ],
1107
- });
1108
- ```
445
+ ---
1109
446
 
1110
- ### 5. Test Theme Persistence
447
+ ## Troubleshooting
1111
448
 
1112
- ```typescript
1113
- // ✅ Good: Verify saved preferences work
1114
- it('should persist theme selection', () => {
1115
- themeService.setTheme('custom');
1116
- themeService.loadSavedPreferences();
1117
- expect(themeService.selectedTheme()).toBe('custom');
1118
- });
1119
- ```
449
+ ### Theme not applied on load
1120
450
 
1121
- ## Related Utilities
451
+ - Check the config path is correct.
452
+ - Check the theme JSON has both `light` and `dark` variants.
453
+ - Check that `meta.name` matches the config `name`.
454
+
455
+ ### New variables not usable in Tailwind utilities
1122
456
 
1123
- - **[ThemeAssetsService](./theme-assets/)**: Dynamic asset loading based on theme
1124
- - **[cn Utility](../cn/)**: Conditional CSS class merging
1125
- - **[ResourceLoader](../resource-loader/)**: Runtime config loading with caching
1126
- - **[TranslationService](../translation/)**: Localized theme and scheme names
457
+ - Add the token to `@theme` in global CSS.
1127
458
 
1128
- ## License
459
+ ### Old config stuck in cache
460
+
461
+ - Bump `THEME_SCHEMA_VERSION` and add `meta.schemaVersion` in JSON.
462
+
463
+ ---
464
+
465
+ ## Related Utilities
1129
466
 
1130
- MIT - See LICENSE file in the root of the project.
467
+ - `@sixbell-telco/sdk/utils/runtime-config` - Loader + cache
468
+ - `@sixbell-telco/sdk/utils/translation` - i18n runtime config