@sixbell-telco/sdk 1.3.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 (97) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/README.md +437 -472
  3. package/_index.css +109 -11
  4. package/assets/styles/toast.css +8 -0
  5. package/components/forms/date-picker/constants/date-picker.constants.d.ts +13 -0
  6. package/components/forms/date-picker/index.d.ts +5 -0
  7. package/components/forms/date-picker/public-api.d.ts +3 -0
  8. package/components/forms/date-picker/src/date-picker.component.d.ts +323 -0
  9. package/components/forms/date-picker/types/date-picker.types.d.ts +39 -0
  10. package/components/{forms/datepicker → sonner}/index.d.ts +1 -1
  11. package/components/sonner/public-api.d.ts +2 -0
  12. package/components/sonner/src/sonner.component.d.ts +39 -0
  13. package/components/sonner/toaster/index.d.ts +5 -0
  14. package/components/sonner/toaster/public-api.d.ts +1 -0
  15. package/components/sonner/toaster/src/toaster.component.d.ts +89 -0
  16. package/components/toast/public-api.d.ts +9 -0
  17. package/components/toast/services/toast.service.d.ts +3 -0
  18. package/components/toast/toast-message/toast-message.component.d.ts +3 -0
  19. package/components/toast/toasts-container/toasts-container.component.d.ts +3 -0
  20. package/fesm2022/sixbell-telco-sdk-components-forms-date-picker.mjs +885 -0
  21. package/fesm2022/sixbell-telco-sdk-components-forms-date-picker.mjs.map +1 -0
  22. package/fesm2022/sixbell-telco-sdk-components-sonner-toaster.mjs +132 -0
  23. package/fesm2022/sixbell-telco-sdk-components-sonner-toaster.mjs.map +1 -0
  24. package/fesm2022/sixbell-telco-sdk-components-sonner.mjs +179 -0
  25. package/fesm2022/sixbell-telco-sdk-components-sonner.mjs.map +1 -0
  26. package/fesm2022/sixbell-telco-sdk-components-toast.mjs +14 -0
  27. package/fesm2022/sixbell-telco-sdk-components-toast.mjs.map +1 -1
  28. package/fesm2022/sixbell-telco-sdk-utils-date.mjs +90 -2
  29. package/fesm2022/sixbell-telco-sdk-utils-date.mjs.map +1 -1
  30. package/fesm2022/sixbell-telco-sdk-utils-logger.mjs +578 -0
  31. package/fesm2022/sixbell-telco-sdk-utils-logger.mjs.map +1 -0
  32. package/fesm2022/sixbell-telco-sdk-utils-resource-loader.mjs +1222 -0
  33. package/fesm2022/sixbell-telco-sdk-utils-resource-loader.mjs.map +1 -0
  34. package/fesm2022/sixbell-telco-sdk-utils-theme.mjs +1434 -180
  35. package/fesm2022/sixbell-telco-sdk-utils-theme.mjs.map +1 -1
  36. package/fesm2022/sixbell-telco-sdk-utils-translation.mjs +734 -182
  37. package/fesm2022/sixbell-telco-sdk-utils-translation.mjs.map +1 -1
  38. package/package.json +68 -51
  39. package/utils/date/src/date-utils.d.ts +44 -0
  40. package/utils/logger/README.md +539 -0
  41. package/utils/logger/index.d.ts +5 -0
  42. package/utils/logger/public-api.d.ts +3 -0
  43. package/utils/logger/src/constants.d.ts +15 -0
  44. package/utils/logger/src/logger.service.d.ts +123 -0
  45. package/utils/logger/src/models/logger.d.ts +25 -0
  46. package/utils/logger/src/providers/logger.provider.d.ts +3 -0
  47. package/utils/resource-loader/README.md +460 -0
  48. package/utils/resource-loader/index.d.ts +5 -0
  49. package/utils/resource-loader/public-api.d.ts +1 -0
  50. package/utils/resource-loader/src/cache/index.d.ts +2 -0
  51. package/utils/resource-loader/src/cache/layers/factory.d.ts +38 -0
  52. package/utils/resource-loader/src/cache/layers/index.d.ts +3 -0
  53. package/utils/resource-loader/src/cache/layers/indexed-db-cache.d.ts +118 -0
  54. package/utils/resource-loader/src/cache/layers/local-storage-cache.d.ts +86 -0
  55. package/utils/resource-loader/src/cache/layers/memory-cache.d.ts +76 -0
  56. package/utils/resource-loader/src/cache/types.d.ts +107 -0
  57. package/utils/resource-loader/src/config/index.d.ts +1 -0
  58. package/utils/resource-loader/src/config/load-config.d.ts +32 -0
  59. package/utils/resource-loader/src/constants.d.ts +38 -0
  60. package/utils/resource-loader/src/http/index.d.ts +1 -0
  61. package/utils/resource-loader/src/http/retryable-client.d.ts +43 -0
  62. package/utils/resource-loader/src/index.d.ts +1 -0
  63. package/utils/resource-loader/src/resource-loader.d.ts +67 -0
  64. package/utils/resource-loader/src/types.d.ts +152 -0
  65. package/utils/resource-loader/src/utils/cache-validator.d.ts +72 -0
  66. package/utils/resource-loader/src/utils/helpers.d.ts +15 -0
  67. package/utils/resource-loader/src/utils/index.d.ts +2 -0
  68. package/utils/theme/README.md +1054 -109
  69. package/utils/theme/public-api.d.ts +9 -1
  70. package/utils/theme/src/constants.d.ts +74 -0
  71. package/utils/theme/src/models/theme.d.ts +288 -0
  72. package/utils/theme/src/providers/constants.d.ts +7 -0
  73. package/utils/theme/src/providers/theme.provider.d.ts +13 -0
  74. package/utils/theme/src/providers/theme.provider.types.d.ts +29 -0
  75. package/utils/theme/src/theme-assets/theme-assets.service.d.ts +214 -0
  76. package/utils/theme/src/theme-assets/theme-assets.types.d.ts +10 -0
  77. package/utils/theme/src/theme-dom/theme-dom.service.d.ts +87 -0
  78. package/utils/theme/src/theme-scheme/theme-scheme.service.d.ts +44 -0
  79. package/utils/theme/src/theme-storage/theme-storage.service.d.ts +47 -0
  80. package/utils/theme/src/theme.service.d.ts +40 -186
  81. package/utils/theme/src/utils/utils.d.ts +86 -0
  82. package/utils/translation/README.md +1414 -176
  83. package/utils/translation/public-api.d.ts +6 -0
  84. package/utils/translation/src/constants.d.ts +52 -0
  85. package/utils/translation/src/models/translation.d.ts +59 -0
  86. package/utils/translation/src/providers/constants.d.ts +11 -0
  87. package/utils/translation/src/providers/translation.provider.d.ts +73 -0
  88. package/utils/translation/src/providers/translation.provider.types.d.ts +26 -0
  89. package/utils/translation/src/translation-dom/translation-dom.service.d.ts +26 -0
  90. package/utils/translation/src/translation-storage/translation-storage.service.d.ts +34 -0
  91. package/utils/translation/src/translation.service.d.ts +19 -166
  92. package/components/forms/datepicker/constants/datepicker.constants.d.ts +0 -5
  93. package/components/forms/datepicker/public-api.d.ts +0 -3
  94. package/components/forms/datepicker/src/datepicker.component.d.ts +0 -165
  95. package/components/forms/datepicker/types/datepicker.types.d.ts +0 -7
  96. package/fesm2022/sixbell-telco-sdk-components-forms-datepicker.mjs +0 -487
  97. package/fesm2022/sixbell-telco-sdk-components-forms-datepicker.mjs.map +0 -1
@@ -1,295 +1,1549 @@
1
- import { DOCUMENT } from '@angular/common';
2
1
  import * as i0 from '@angular/core';
3
- import { InjectionToken, inject, signal, computed, Inject, Optional, Injectable, provideAppInitializer } from '@angular/core';
2
+ import { InjectionToken, signal, inject, Injectable, Inject, computed, Optional, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';
3
+ import { LoggerService } from '@sixbell-telco/sdk/utils/logger';
4
+ import { ResourceLoader } from '@sixbell-telco/sdk/utils/resource-loader';
5
+ import { Router, NavigationEnd } from '@angular/router';
4
6
  import { TranslationService } from '@sixbell-telco/sdk/utils/translation';
7
+ import { filter } from 'rxjs/operators';
8
+ import { DOCUMENT } from '@angular/common';
5
9
 
6
- // Default base theme - always available unless excluded
10
+ /**
11
+ * Theme Constants and Injection Tokens
12
+ * Centralized configuration values and DI tokens following Single Responsibility Principle
13
+ */
14
+ /**
15
+ * Default base theme - always available unless explicitly excluded
16
+ * This is the foundational theme that comes with the SDK
17
+ */
7
18
  const DEFAULT_BASE_THEME = 'sixbell_telco';
19
+ /**
20
+ * List of default themes available out of the box
21
+ */
8
22
  const DEFAULT_THEMES = [DEFAULT_BASE_THEME];
23
+ /**
24
+ * Type-safe default theme codes for IDE IntelliSense
25
+ */
9
26
  const DEFAULT_THEME_CODES = [DEFAULT_BASE_THEME];
10
- // Injection tokens for dependency injection
27
+ /**
28
+ * LocalStorage key for persisting selected theme
29
+ */
30
+ const THEME_STORAGE_THEME_KEY = 'selectedTheme';
31
+ /**
32
+ * LocalStorage key for persisting selected scheme
33
+ */
34
+ const THEME_STORAGE_SCHEME_KEY = 'selectedScheme';
35
+ /**
36
+ * Namespace for storage keys to prevent collisions with other apps
37
+ */
38
+ const THEME_STORAGE_NAMESPACE = 'theme:';
39
+ /**
40
+ * HTML attribute name for setting the active theme on document body
41
+ */
42
+ const THEME_ATTRIBUTE_NAME = 'data-theme';
43
+ /**
44
+ * Separator used when combining theme name and scheme into a theme identifier
45
+ * @example "sixbell_telco__light" (theme__scheme format)
46
+ */
47
+ const THEME_SCHEME_SEPARATOR = '__';
48
+ /**
49
+ * Default theme scheme preference
50
+ */
51
+ const DEFAULT_SCHEME = 'system';
52
+ /**
53
+ * All valid scheme values
54
+ */
55
+ const VALID_SCHEMES = ['system', 'light', 'dark'];
56
+ /**
57
+ * Minimal runtime configuration used as a resilient fallback when remote loading fails
58
+ */
59
+ const FALLBACK_RUNTIME_THEME_CONFIG = {
60
+ themes: {
61
+ [DEFAULT_BASE_THEME]: {
62
+ light: {
63
+ daisyuiName: `${DEFAULT_BASE_THEME}__light`,
64
+ prefersDark: false,
65
+ variables: {
66
+ '--font-poppins': 'Poppins, sans-serif',
67
+ '--font-heading': 'Poppins, sans-serif',
68
+ '--font-body': 'Poppins, sans-serif',
69
+ '--color-base-100': 'oklch(96.65% 0.0045 258.32)',
70
+ '--color-base-200': 'oklch(100% 0 0)',
71
+ '--color-base-300': 'oklch(92.88% 0.0126 255.51)',
72
+ '--color-base-content': 'oklch(13.49% 0.0024 286.07)',
73
+ '--color-primary': 'oklch(65.64% 0.1155 219.3)',
74
+ '--color-primary-content': 'oklch(100% 0 0)',
75
+ '--color-secondary': 'oklch(86.57% 0.0064 255.48)',
76
+ '--color-secondary-content': 'oklch(13.49% 0.0024 286.07)',
77
+ '--color-accent': 'oklch(70.45% 0.1926 39.23)',
78
+ '--color-accent-content': 'oklch(13.49% 0.0024 286.07)',
79
+ '--color-neutral': 'oklch(92.08% 0.0063 255.48)',
80
+ '--color-neutral-content': 'oklch(13.49% 0.0024 286.07)',
81
+ '--color-info': 'oklch(55.86% 0.1907 256)',
82
+ '--color-info-content': 'oklch(100% 0 0)',
83
+ '--color-success': 'oklch(73.79% 0.2409 140.89)',
84
+ '--color-success-content': 'oklch(36.22% 0.1147 140.02)',
85
+ '--color-warning': 'oklch(85.44% 0.1839 108.37)',
86
+ '--color-warning-content': 'oklch(46.41% 0.0998 109)',
87
+ '--color-error': 'oklch(65.92% 0.2275 29.05)',
88
+ '--color-error-content': 'oklch(25.91% 0.0904 29.25)',
89
+ '--color-base-50': 'color-mix(in oklch, var(--color-base-200), #000 7%)',
90
+ '--color-primary-light': 'color-mix(in oklch, var(--color-primary) 75%, #fff)',
91
+ '--color-primary-gradient': 'color-mix(in oklch, var(--color-primary) 60%, #121212)',
92
+ '--color-primary-gradient-content': 'oklch(100% 0 0)',
93
+ '--color-secondary-gradient': 'color-mix(in oklch, var(--color-secondary) 60%, #121212)',
94
+ '--color-secondary-gradient-content': 'oklch(13.49% 0.0024 286.07)',
95
+ '--color-tertiary-gradient': 'color-mix(in oklch, var(--color-tertiary) 60%, #121212)',
96
+ '--color-tertiary-gradient-content': 'oklch(13.49% 0.0024 286.07)',
97
+ '--color-accent-gradient': 'color-mix(in oklch, var(--color-accent) 60%, #121212)',
98
+ '--color-accent-gradient-content': 'oklch(100% 0 0)',
99
+ '--color-tertiary': 'oklch(72.52% 0 0)',
100
+ '--color-tertiary-content': 'oklch(13.49% 0.0024 286.07)',
101
+ '--color-neutral-secondary': 'oklch(73.97% 0.0115 280.4)',
102
+ '--color-neutral-secondary-content': 'oklch(100% 0 0)',
103
+ '--color-neutral-tertiary': 'oklch(100% 0 0)',
104
+ '--color-neutral-tertiary-content': 'oklch(73.97% 0.0115 280.4)',
105
+ '--color-base-placeholder': 'oklch(51.6% 0.0073 255.51)',
106
+ '--color-backdrop': 'oklch(0% 0 0/ 0.4)',
107
+ '--color-shadow-primary': 'oklch(0.8975 0 0)',
108
+ '--color-shadow-backdrop': 'oklch(0% 0 0/ 0.25)',
109
+ '--color-metrics-increase': 'oklch(74.59% 0.1812 152.33)',
110
+ '--color-metrics-decrease': 'oklch(63.07% 0.194 29.44)',
111
+ '--color-metrics-neutral': 'oklch(62.99% 0.0152 202.37)',
112
+ '--color-metrics-intensity-highest': 'oklch(65.64% 0.1155 219.3)',
113
+ '--color-metrics-intensity-high': 'oklch(68.62% 0.0925 226.08)',
114
+ '--color-metrics-intensity-medium': 'oklch(68.62% 0.0925 226.08)',
115
+ '--color-metrics-intensity-low': 'oklch(76.18% 0.0656 213.66)',
116
+ '--color-metrics-intensity-lowest': 'oklch(78% 0.0473 211.88)',
117
+ '--color-scroll-thumb': 'oklch(75% 0 0)',
118
+ '--radius-selector': '0.5rem',
119
+ '--radius-field': '0.25rem',
120
+ '--radius-box': '0.5rem',
121
+ '--size-selector': '0.25rem',
122
+ '--size-field': '0.25rem',
123
+ '--border': '1px',
124
+ '--depth': '0',
125
+ '--noise': '0',
126
+ },
127
+ },
128
+ dark: {
129
+ daisyuiName: `${DEFAULT_BASE_THEME}__dark`,
130
+ prefersDark: true,
131
+ variables: {
132
+ '--font-poppins': 'Poppins, sans-serif',
133
+ '--font-heading': 'Poppins, sans-serif',
134
+ '--font-body': 'Poppins, sans-serif',
135
+ '--color-base-100': 'oklch(18.22% 0 0)',
136
+ '--color-base-200': 'oklch(23.5% 0 0)',
137
+ '--color-base-300': 'oklch(28.5% 0 0)',
138
+ '--color-base-content': 'oklch(100% 0 0)',
139
+ '--color-primary': 'oklch(65.64% 0.1155 219.3)',
140
+ '--color-primary-content': 'oklch(100% 0 0)',
141
+ '--color-secondary': 'oklch(48.72% 0.0161 276.78)',
142
+ '--color-secondary-content': 'oklch(100% 0 0)',
143
+ '--color-accent': 'oklch(70.45% 0.1926 39.23)',
144
+ '--color-accent-content': 'oklch(23.5% 0 0)',
145
+ '--color-neutral': 'oklch(49.26% 0 0)',
146
+ '--color-neutral-content': 'oklch(100% 0 0)',
147
+ '--color-info': 'oklch(55.86% 0.1907 256)',
148
+ '--color-info-content': 'oklch(100% 0 0)',
149
+ '--color-success': 'oklch(73.79% 0.2409 140.89)',
150
+ '--color-success-content': 'oklch(36.22% 0.1147 140.02)',
151
+ '--color-warning': 'oklch(85.44% 0.1839 108.37)',
152
+ '--color-warning-content': 'oklch(46.41% 0.0998 109)',
153
+ '--color-error': 'oklch(65.92% 0.2275 29.05)',
154
+ '--color-error-content': 'oklch(25.91% 0.0904 29.25)',
155
+ '--color-base-50': 'color-mix(in oklch, var(--color-base-200), #000 7%)',
156
+ '--color-primary-light': 'color-mix(in oklch, var(--color-primary) 75%, #000)',
157
+ '--color-primary-gradient': 'color-mix(in oklch, var(--color-primary) 60%, #121212)',
158
+ '--color-primary-gradient-content': 'oklch(100% 0 0)',
159
+ '--color-secondary-gradient': 'color-mix(in oklch, var(--color-secondary) 60%, #121212)',
160
+ '--color-secondary-gradient-content': 'oklch(100% 0 0)',
161
+ '--color-tertiary-gradient': 'color-mix(in oklch, var(--color-tertiary) 60%, #121212)',
162
+ '--color-tertiary-gradient-content': 'oklch(100% 0 0)',
163
+ '--color-accent-gradient': 'color-mix(in oklch, var(--color-accent) 60%, #121212)',
164
+ '--color-accent-gradient-content': 'oklch(100% 0 0)',
165
+ '--color-tertiary': 'oklch(72.52% 0 0)',
166
+ '--color-tertiary-content': 'oklch(13.49% 0.0024 286.07)',
167
+ '--color-neutral-secondary': 'oklch(73.97% 0.0115 280.4)',
168
+ '--color-neutral-secondary-content': 'oklch(100% 0 0)',
169
+ '--color-neutral-tertiary': 'oklch(100% 0 0)',
170
+ '--color-neutral-tertiary-content': 'oklch(73.97% 0.0115 280.4)',
171
+ '--color-base-placeholder': 'oklch(51.6% 0.0073 255.51)',
172
+ '--color-backdrop': 'oklch(0% 0 0/ 0.4)',
173
+ '--color-shadow-primary': 'oklch(0 0 0)',
174
+ '--color-shadow-backdrop': 'oklch(0% 0 0/ 0.25)',
175
+ '--color-metrics-increase': 'oklch(74.59% 0.1812 152.33)',
176
+ '--color-metrics-decrease': 'oklch(63.07% 0.194 29.44)',
177
+ '--color-metrics-neutral': 'oklch(62.99% 0.0152 202.37)',
178
+ '--color-metrics-intensity-highest': 'oklch(65.64% 0.1155 219.3)',
179
+ '--color-metrics-intensity-high': 'oklch(68.62% 0.0925 226.08)',
180
+ '--color-metrics-intensity-medium': 'oklch(68.62% 0.0925 226.08)',
181
+ '--color-metrics-intensity-low': 'oklch(76.18% 0.0656 213.66)',
182
+ '--color-metrics-intensity-lowest': 'oklch(78% 0.0473 211.88)',
183
+ '--color-scroll-thumb': 'oklch(35% 0 0)',
184
+ '--radius-selector': '0.5rem',
185
+ '--radius-field': '0.25rem',
186
+ '--radius-box': '0.5rem',
187
+ '--size-selector': '0.25rem',
188
+ '--size-field': '0.25rem',
189
+ '--border': '1px',
190
+ '--depth': '0',
191
+ '--noise': '0',
192
+ },
193
+ },
194
+ },
195
+ },
196
+ availableThemes: [DEFAULT_BASE_THEME],
197
+ defaultTheme: DEFAULT_BASE_THEME,
198
+ defaultScheme: DEFAULT_SCHEME,
199
+ };
200
+ /**
201
+ * CSS class name applied to document when dark theme is detected
202
+ */
203
+ const DARK_THEME_CLASS = 'dark';
204
+ /**
205
+ * Media query for detecting system dark mode preference
206
+ */
207
+ const DARK_MODE_MEDIA_QUERY = '(prefers-color-scheme: dark)';
208
+ /**
209
+ * Injection token for theme configuration
210
+ * Used to provide static theme configuration at bootstrap
211
+ */
11
212
  const THEME_CONFIG_TOKEN = new InjectionToken('Theme Configuration');
12
- // LocalStorage keys
13
- const THEME_SELECTED_THEME_KEY = 'selectedTheme';
14
- const THEME_SELECTED_SCHEME_KEY = 'selectedScheme';
15
- class ThemeService {
213
+ /**
214
+ * Injection token for runtime theme configuration
215
+ * Used to provide dynamic runtime theme configuration loaded from JSON file
216
+ */
217
+ const RUNTIME_THEME_CONFIG_TOKEN = new InjectionToken('Runtime Theme Configuration');
218
+
219
+ /**
220
+ * Theme Assets Service
221
+ * Manages dynamic asset loading and retrieval based on selected theme and color scheme
222
+ *
223
+ * Responsibilities:
224
+ * - Retrieve assets (images, logos, illustrations) for current theme
225
+ * - Provide scheme-aware asset variants (light/dark)
226
+ * - Cache asset references with config-based resilience strategy
227
+ * - Validate asset availability and provide graceful fallback through memory layers
228
+ *
229
+ * Multi-Layer Caching Strategy (Like Theme Config Persistence):
230
+ * - Layer 1: Current config assets (read from active RuntimeThemeConfig)
231
+ * - Layer 2: Last working asset config (in-memory, persists across config updates)
232
+ * - Falls back to last complete working config if current config breaks
233
+ *
234
+ * This matches the ResourceLoader and ThemeService pattern where:
235
+ * - User preferences/working configs are stored in memory layers
236
+ * - When new config fails, the last working config is used automatically
237
+ * - Handles asset removal, name changes, path changes, config resets
238
+ */
239
+ class ThemeAssetsService {
240
+ /**
241
+ * Signal holding current runtime configuration reference
242
+ * Used to look up asset definitions for the active theme
243
+ */
244
+ config = signal(null);
245
+ /**
246
+ * Layer 1: In-memory cache of resolved assets
247
+ * Maps "themeName:assetKey" to CachedAsset for fast retrieval
248
+ * Cleared when setConfig() is called to force re-resolution from new config
249
+ */
250
+ assetCache = new Map();
251
+ /**
252
+ * Layer 2: Last working config storage (memory-based)
253
+ * Stores the most recent RuntimeThemeConfig that successfully resolved assets
254
+ * Persists across config updates as a complete fallback mechanism
255
+ * Similar to ThemeService's multi-layer config persistence
256
+ *
257
+ * When current config fails to provide an asset:
258
+ * - Falls back to the last complete working config
259
+ * - Handles asset removal, name changes, path changes
260
+ * - Automatically restores working state on config resets
261
+ * - No individual URL tracking - entire config stored once per successful load
262
+ */
263
+ lastWorkingConfigLayer = null;
264
+ logger = inject(LoggerService);
265
+ constructor() { }
266
+ /**
267
+ * Initialize service with runtime configuration
268
+ * Called by ThemeService after loading configuration
269
+ *
270
+ * If new config successfully resolves assets, it becomes the new fallback layer.
271
+ * Otherwise, previous working config persists.
272
+ *
273
+ * Only updates Layer 2 if:
274
+ * - Config has no PARTIAL/BROKEN assets (missing variants)
275
+ * - Themes can be removed entirely (that's intentional)
276
+ * - But existing assets must be COMPLETE (both light and dark)
277
+ *
278
+ * This ensures that accidental removals of variants trigger fallback
279
+ * while intentional complete removals are allowed.
280
+ *
281
+ * @param config - Runtime configuration containing asset definitions
282
+ */
283
+ setConfig(config) {
284
+ this.config.set(config);
285
+ const hasPartialAssets = this.hasPartialAssets(config);
286
+ const hasValid = !hasPartialAssets;
287
+ this.logger.debug('setConfig called', {
288
+ component: 'ThemeAssetsService',
289
+ action: 'setConfig',
290
+ hasPartialAssets,
291
+ hasValidAssets: hasValid,
292
+ themes: config?.assets ? Object.keys(config.assets) : [],
293
+ hasLastWorking: !!this.lastWorkingConfigLayer,
294
+ });
295
+ // Only store as last working config if it has NO partial/broken assets
296
+ if (hasValid) {
297
+ this.logger.debug('Storing config as last working config', {
298
+ component: 'ThemeAssetsService',
299
+ action: 'setConfig',
300
+ });
301
+ this.lastWorkingConfigLayer = config;
302
+ }
303
+ else {
304
+ this.logger.debug('Config has partial/broken assets - keeping previous last working config', {
305
+ component: 'ThemeAssetsService',
306
+ action: 'setConfig',
307
+ });
308
+ }
309
+ this.clearCache();
310
+ }
311
+ /**
312
+ * Internal: Check if config has any PARTIAL/BROKEN assets
313
+ * Returns true if ANY asset is incomplete (missing light or dark variant)
314
+ *
315
+ * A partial asset is invalid:
316
+ * - logo: { light: "..." } ← missing dark
317
+ * - logo: { dark: "..." } ← missing light
318
+ * - logo: {} ← missing both
319
+ *
320
+ * Complete removals are OK:
321
+ * - {} ← no assets at all (intentional)
322
+ * - theme: {} ← theme removed (intentional)
323
+ *
324
+ * @private
325
+ * @param config - Config to check
326
+ * @returns True if config has partial/broken assets, false if all complete or intentionally removed
327
+ */
328
+ hasPartialAssets(config) {
329
+ if (!config?.assets)
330
+ return false;
331
+ // Check if ANY theme has ANY problematic assets
332
+ // Problematic = partial (missing variant) OR empty (intentionally removed)
333
+ for (const themeName in config.assets) {
334
+ const themeAssets = config.assets[themeName];
335
+ if (this.themeHasProblematicAssets(themeAssets)) {
336
+ return true; // Config has issues, don't update Layer 2
337
+ }
338
+ }
339
+ return false; // Config is clean, can update Layer 2
340
+ }
341
+ /**
342
+ * Internal: Check if a theme/asset object has ANY problematic assets
343
+ * Problematic assets are:
344
+ * - Partial assets: { light: "..." } or { dark: "..." } (missing variant)
345
+ * - Empty asset objects: { "logo": {} } (asset key exists but has no variants)
346
+ * - Broken nested assets at any level
347
+ *
348
+ * NOT problematic:
349
+ * - Completely empty themes: {} (all assets intentionally removed - OK to accept)
350
+ * - Missing themes (not in config at all)
351
+ *
352
+ * @private
353
+ * @param obj - Theme's asset object to check
354
+ * @returns True if object has problematic assets
355
+ */
356
+ themeHasProblematicAssets(obj) {
357
+ if (!obj || typeof obj !== 'object')
358
+ return false;
359
+ const record = obj;
360
+ const keys = Object.keys(record);
361
+ // Empty theme assets {} is OK - intentional complete removal
362
+ // No need to check further, this is a valid state
363
+ if (keys.length === 0) {
364
+ return false; // Empty theme is fine, accept config
365
+ }
366
+ // Theme has content - check all properties for problems
367
+ for (const key of keys) {
368
+ const value = record[key];
369
+ // Check if this value is a partial asset (has light OR dark but not both)
370
+ if (this.isPartialAsset(value)) {
371
+ return true; // Partial asset found - problematic
372
+ }
373
+ // Check if it's an empty object (asset key exists but has no content)
374
+ // Example: { "logo": {} } - the logo key exists but is empty
375
+ if (typeof value === 'object' && value !== null && Object.keys(value).length === 0) {
376
+ return true; // Empty asset found (key exists but broken) - problematic
377
+ }
378
+ // Recursively check for problematic nested assets
379
+ if (this.themeHasProblematicAssets(value)) {
380
+ return true;
381
+ }
382
+ }
383
+ return false; // No problematic assets found
384
+ }
385
+ /**
386
+ * Internal: Check if object is a PARTIAL asset (incomplete)
387
+ * Partial means it LOOKS LIKE an asset (has some scheme keys) but is missing variants
388
+ *
389
+ * @private
390
+ * @param obj - Object to check
391
+ * @returns True if object is a partial/incomplete asset
392
+ */
393
+ isPartialAsset(obj) {
394
+ if (typeof obj !== 'object' || obj === null)
395
+ return false;
396
+ const record = obj;
397
+ const hasLight = typeof record['light'] === 'string';
398
+ const hasDark = typeof record['dark'] === 'string';
399
+ // Partial if it has scheme keys but not both
400
+ const hasSchemeKeys = 'light' in record || 'dark' in record;
401
+ return hasSchemeKeys && (!hasLight || !hasDark);
402
+ }
403
+ /**
404
+ * Get asset URL for the specified scheme
405
+ * Retrieves a specific asset variant (light or dark) with config-based fallback
406
+ *
407
+ * Resolution Strategy (in order):
408
+ * 1. Try to get the requested scheme variant from current config
409
+ * 2. If not available, use last working config from memory layer
410
+ * 3. If no last working config, return null
411
+ *
412
+ * This ensures:
413
+ * - Graceful degradation when assets are removed from config
414
+ * - Support for asset name changes, path changes, config resets
415
+ * - Automatic restoration when config is fixed
416
+ * - No automatic scheme switching (stays on requested scheme)
417
+ * - Similar to ThemeService's config persistence pattern
418
+ *
419
+ * @param themeName - Name of the theme (e.g., 'sixbell_telco', 'wom')
420
+ * @param assetKey - Asset identifier path (e.g., 'logo', 'banners.hero', 'illustrations.empty')
421
+ * @param scheme - Color scheme ('light' or 'dark')
422
+ * @returns Asset URL for the specified scheme, or from last working config, or null if not found
423
+ *
424
+ * @example
425
+ * // Current config has dark - returns requested variant
426
+ * getAssetUrl('wom', 'logo', 'dark')
427
+ * // Returns: '/assets/logos/logo_wom_dark.svg'
428
+ *
429
+ * // Current config missing dark - returns from last working config
430
+ * getAssetUrl('wom', 'logo', 'dark')
431
+ * // Returns: '/assets/logos/logo_wom_dark.svg' (from last working config layer)
432
+ *
433
+ * // Never existed - no working config
434
+ * getAssetUrl('wom', 'nonexistent', 'dark')
435
+ * // Returns: null
436
+ */
437
+ getAssetUrl(themeName, assetKey, scheme) {
438
+ // Layer 1: Try to resolve from current config
439
+ const url = this.resolveAssetUrl(themeName, assetKey, scheme, this.config());
440
+ if (url) {
441
+ this.logger.debug('Asset resolved from current config', {
442
+ component: 'ThemeAssetsService',
443
+ action: 'getAssetUrl',
444
+ themeName,
445
+ assetKey,
446
+ scheme,
447
+ url,
448
+ });
449
+ return url;
450
+ }
451
+ // Layer 2: Try to resolve from last working config
452
+ if (this.lastWorkingConfigLayer) {
453
+ const lastWorkingUrl = this.resolveAssetUrl(themeName, assetKey, scheme, this.lastWorkingConfigLayer);
454
+ if (lastWorkingUrl) {
455
+ this.logger.debug('Asset resolved from last working config (fallback)', {
456
+ component: 'ThemeAssetsService',
457
+ action: 'getAssetUrl',
458
+ fallback: true,
459
+ themeName,
460
+ assetKey,
461
+ scheme,
462
+ url: lastWorkingUrl,
463
+ });
464
+ return lastWorkingUrl;
465
+ }
466
+ }
467
+ // Layer 3: No URL available
468
+ this.logger.debug('Asset not found in any layer', {
469
+ component: 'ThemeAssetsService',
470
+ action: 'getAssetUrl',
471
+ themeName,
472
+ assetKey,
473
+ scheme,
474
+ hasLastWorking: !!this.lastWorkingConfigLayer,
475
+ });
476
+ return null;
477
+ }
478
+ /**
479
+ * Internal: Resolve asset URL from a specific config
480
+ * Helper method to resolve URL from current or last working config
481
+ *
482
+ * Returns null if:
483
+ * - Asset not found
484
+ * - Asset is incomplete (missing either light or dark variant)
485
+ * - Requested scheme variant not available
486
+ *
487
+ * @private
488
+ * @param themeName - Theme name
489
+ * @param assetKey - Asset key path
490
+ * @param scheme - Scheme variant
491
+ * @param configToUse - Config to resolve from (current or lastWorking)
492
+ * @returns URL if found and complete, null otherwise
493
+ */
494
+ resolveAssetUrl(themeName, assetKey, scheme, configToUse) {
495
+ if (!configToUse?.assets?.[themeName])
496
+ return null;
497
+ const themeAssets = configToUse.assets[themeName];
498
+ const parts = assetKey.split('.');
499
+ // Navigate nested structure
500
+ let current = themeAssets;
501
+ for (const part of parts) {
502
+ if (!current || typeof current !== 'object')
503
+ return null;
504
+ current = current[part];
505
+ }
506
+ // Check if it's a valid asset with the requested scheme
507
+ if (!this.isThemeAsset(current))
508
+ return null;
509
+ // Asset must be complete (have both variants) - return requested variant
510
+ const asset = current;
511
+ const url = scheme === 'light' ? asset.light : asset.dark;
512
+ // Return null if variant is missing (indicates incomplete asset)
513
+ return url || null;
514
+ }
515
+ /**
516
+ * Get both light and dark variants of an asset
517
+ * Returns an object with both scheme variants for easy access
518
+ *
519
+ * @param themeName - Name of the theme
520
+ * @param assetKey - Asset identifier path
521
+ * @returns Object with light and dark URLs, or null if asset not found
522
+ *
523
+ * @example
524
+ * getAsset('wom', 'logo')
525
+ * // Returns: { light: '/assets/logos/logo_wom_light.svg', dark: '/assets/logos/logo_wom_dark.svg' }
526
+ */
527
+ getAsset(themeName, assetKey) {
528
+ // Try current config first
529
+ let light = this.resolveAssetUrl(themeName, assetKey, 'light', this.config());
530
+ let dark = this.resolveAssetUrl(themeName, assetKey, 'dark', this.config());
531
+ // If not available in current config, try last working config
532
+ if ((!light || !dark) && this.lastWorkingConfigLayer) {
533
+ if (!light)
534
+ light = this.resolveAssetUrl(themeName, assetKey, 'light', this.lastWorkingConfigLayer);
535
+ if (!dark)
536
+ dark = this.resolveAssetUrl(themeName, assetKey, 'dark', this.lastWorkingConfigLayer);
537
+ }
538
+ // Return asset if at least one variant found
539
+ if (light || dark) {
540
+ return { light: light || undefined, dark: dark || undefined };
541
+ }
542
+ return null;
543
+ }
544
+ /**
545
+ * Check if an asset exists in the specified theme
546
+ * Useful for conditional rendering or fallback handling
547
+ *
548
+ * @param themeName - Name of the theme
549
+ * @param assetKey - Asset identifier path
550
+ * @returns True if the asset exists, false otherwise
551
+ *
552
+ * @example
553
+ * hasAsset('wom', 'logo') // true
554
+ * hasAsset('wom', 'nonexistent') // false
555
+ */
556
+ hasAsset(themeName, assetKey) {
557
+ // Check if asset exists in current config
558
+ if (this.resolveAssetUrl(themeName, assetKey, 'light', this.config()) || this.resolveAssetUrl(themeName, assetKey, 'dark', this.config())) {
559
+ return true;
560
+ }
561
+ // Check if asset exists in last working config
562
+ if (this.lastWorkingConfigLayer) {
563
+ if (this.resolveAssetUrl(themeName, assetKey, 'light', this.lastWorkingConfigLayer) ||
564
+ this.resolveAssetUrl(themeName, assetKey, 'dark', this.lastWorkingConfigLayer)) {
565
+ return true;
566
+ }
567
+ }
568
+ return false;
569
+ }
570
+ /**
571
+ * Get all assets for a specific theme
572
+ * Returns the complete asset set for further processing
573
+ *
574
+ * @param themeName - Name of the theme
575
+ * @returns All assets for the theme, or null if theme has no assets
576
+ */
577
+ getThemeAssets(themeName) {
578
+ const cfg = this.config();
579
+ if (!cfg?.assets?.[themeName])
580
+ return null;
581
+ return cfg.assets[themeName];
582
+ }
583
+ /**
584
+ * Manually clear the asset cache
585
+ * Typically called automatically by setConfig(), but can be used for:
586
+ * - Testing and debugging
587
+ * - Force cache refresh in special scenarios
588
+ *
589
+ * Note: The last-working-config layer is NOT cleared - only the config cache
590
+ * This allows the fallback mechanism to persist across manual cache clears
591
+ *
592
+ * @example
593
+ * // In tests
594
+ * assetsService.clearCache();
595
+ *
596
+ * @example
597
+ * // Force refresh (if config doesn't change but images do)
598
+ * assetsService.clearCache();
599
+ * assetsService.setConfig(currentConfig);
600
+ */
601
+ clearCache() {
602
+ this.assetCache.clear();
603
+ }
604
+ /**
605
+ * Internal: Type guard to validate ThemeAsset structure
606
+ * Requires BOTH light and dark variants to be present
607
+ * Partial assets (missing either variant) are considered incomplete/broken
608
+ *
609
+ * Why both required:
610
+ * - Assets are designed to work with both light and dark themes
611
+ * - Missing variant indicates incomplete config (likely accidental removal)
612
+ * - Triggers fallback to last complete working config
613
+ * - Prevents partially broken configs from overwriting good state
614
+ *
615
+ * @private
616
+ * @param obj - Object to validate
617
+ * @returns True if object is a valid ThemeAsset (has BOTH light and dark)
618
+ */
619
+ isThemeAsset(obj) {
620
+ if (typeof obj !== 'object' || obj === null)
621
+ return false;
622
+ const record = obj;
623
+ const hasLight = typeof record['light'] === 'string';
624
+ const hasDark = typeof record['dark'] === 'string';
625
+ // Valid only if BOTH variants are present
626
+ return hasLight && hasDark;
627
+ }
628
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeAssetsService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
629
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeAssetsService, providedIn: 'root' });
630
+ }
631
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeAssetsService, decorators: [{
632
+ type: Injectable,
633
+ args: [{
634
+ providedIn: 'root',
635
+ }]
636
+ }], ctorParameters: () => [] });
637
+
638
+ /**
639
+ * DOM and CSS Injection Service
640
+ * Handles all DOM manipulation and CSS variable injection
641
+ */
642
+ /**
643
+ * Service responsible for all DOM manipulation and CSS injection
644
+ * Decouples DOM operations from business logic
645
+ */
646
+ class ThemeDomService {
16
647
  rendererFactory;
17
648
  document;
649
+ renderer;
650
+ constructor(rendererFactory, document) {
651
+ this.rendererFactory = rendererFactory;
652
+ this.document = document;
653
+ this.renderer = this.rendererFactory.createRenderer(null, null);
654
+ }
655
+ /**
656
+ * Injects font-face declarations into the document head
657
+ * Creates a single style tag containing all font face definitions
658
+ * @param fonts - Array of font definitions with faces
659
+ */
660
+ injectFonts(fonts) {
661
+ const styleContent = this.buildFontFaceStyles(fonts);
662
+ if (styleContent) {
663
+ this.appendStyleToHead(styleContent);
664
+ }
665
+ }
666
+ /**
667
+ * Injects global CSS variables as root-level custom properties
668
+ * Sets variables directly on the document element
669
+ * @param variables - Record of CSS variable names to values
670
+ */
671
+ injectGlobalVariables(variables) {
672
+ const root = this.document.documentElement || this.document.body;
673
+ Object.entries(variables).forEach(([key, value]) => {
674
+ this.renderer.setStyle(root, key, value);
675
+ });
676
+ }
677
+ /**
678
+ * Injects theme-specific CSS variables as data-theme selectors
679
+ * Creates styles for each theme variant (light/dark)
680
+ * @param themes - Theme definitions with variants
681
+ */
682
+ injectThemeStyles(themes) {
683
+ const styleContent = this.buildThemeStyles(themes);
684
+ if (styleContent) {
685
+ this.appendStyleToHead(styleContent);
686
+ }
687
+ }
688
+ /**
689
+ * Sets the active theme on the document body
690
+ * Uses data-theme attribute for CSS theme targeting
691
+ * @param themeIdentifier - Theme identifier (e.g., "sixbell_telco__light")
692
+ */
693
+ setActiveTheme(themeIdentifier) {
694
+ this.renderer.setAttribute(this.document.body, THEME_ATTRIBUTE_NAME, themeIdentifier);
695
+ }
696
+ /**
697
+ * Builds @font-face CSS rules from font definitions
698
+ * Private helper to construct font-face declarations
699
+ * @param fonts - Array of font definitions
700
+ * @returns CSS content string with @font-face rules
701
+ */
702
+ buildFontFaceStyles(fonts) {
703
+ return fonts
704
+ .map((font) => this.buildFontFaceForFamily(font))
705
+ .filter((content) => content.length > 0)
706
+ .join('\n');
707
+ }
708
+ /**
709
+ * Builds @font-face rules for a single font family
710
+ * @param font - Font definition with faces
711
+ * @returns CSS content string with all faces for this family
712
+ */
713
+ buildFontFaceForFamily(font) {
714
+ return font.faces.map((face) => this.buildFontFaceRule(font.family, face)).join('\n');
715
+ }
716
+ /**
717
+ * Builds a single @font-face rule
718
+ * @param fontFamily - Font family name
719
+ * @param face - Font face definition
720
+ * @returns @font-face CSS rule
721
+ */
722
+ buildFontFaceRule(fontFamily, face) {
723
+ return `@font-face {
724
+ font-family: '${fontFamily}';
725
+ font-weight: ${face.weight};
726
+ font-style: ${face.style};
727
+ src: url('${face.src}');
728
+ }`;
729
+ }
730
+ /**
731
+ * Builds theme style definitions as CSS custom properties
732
+ * Creates selectors for each theme variant
733
+ * @param themes - Theme definitions mapped by theme code
734
+ * @returns CSS content string with theme definitions
735
+ */
736
+ buildThemeStyles(themes) {
737
+ const styleBlocks = Object.entries(themes)
738
+ .flatMap(([themeName, variants]) => this.buildThemeVariantStyles(themeName, variants))
739
+ .filter((content) => content.length > 0);
740
+ return styleBlocks.join('\n\n');
741
+ }
742
+ /**
743
+ * Builds CSS rules for light and dark variants of a theme
744
+ * @param themeName - Name of the theme
745
+ * @param variants - Light and dark variants
746
+ * @returns Array of CSS rules for each variant
747
+ */
748
+ buildThemeVariantStyles(themeName, variants) {
749
+ const styles = [];
750
+ if (variants.light) {
751
+ styles.push(this.buildThemeVariantRule(themeName, 'light', variants.light.variables));
752
+ }
753
+ if (variants.dark) {
754
+ styles.push(this.buildThemeVariantRule(themeName, 'dark', variants.dark.variables));
755
+ }
756
+ return styles;
757
+ }
758
+ /**
759
+ * Builds a single theme variant CSS rule
760
+ * @param themeName - Name of the theme
761
+ * @param scheme - Scheme variant ('light' or 'dark')
762
+ * @param variables - CSS variables for this variant
763
+ * @returns CSS rule string
764
+ */
765
+ buildThemeVariantRule(themeName, scheme, variables) {
766
+ const selector = `[${THEME_ATTRIBUTE_NAME}="${themeName}${THEME_SCHEME_SEPARATOR}${scheme}"]`;
767
+ const declarations = Object.entries(variables)
768
+ .map(([key, value]) => `\t${key}: ${value};`)
769
+ .join('\n');
770
+ return `${selector} {
771
+ ${declarations}
772
+ }`;
773
+ }
774
+ /**
775
+ * Appends a style tag to the document head
776
+ * Helper to inject CSS into the document
777
+ * @param content - CSS content to inject
778
+ */
779
+ appendStyleToHead(content) {
780
+ const style = this.renderer.createElement('style');
781
+ style.textContent = content;
782
+ this.renderer.appendChild(this.document.head, style);
783
+ }
784
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeDomService, deps: [{ token: i0.RendererFactory2 }, { token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable });
785
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeDomService, providedIn: 'root' });
786
+ }
787
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeDomService, decorators: [{
788
+ type: Injectable,
789
+ args: [{ providedIn: 'root' }]
790
+ }], ctorParameters: () => [{ type: i0.RendererFactory2 }, { type: Document, decorators: [{
791
+ type: Inject,
792
+ args: [DOCUMENT]
793
+ }] }] });
794
+
795
+ /**
796
+ * Theme Utility Functions
797
+ * Pure, side-effect-free utilities for theme logic
798
+ */
799
+ /**
800
+ * Validates that a given value is a valid theme scheme
801
+ * @param value - The value to validate
802
+ * @returns True if the value is a valid scheme ('system', 'light', or 'dark')
803
+ */
804
+ function isValidScheme(value) {
805
+ return typeof value === 'string' && VALID_SCHEMES.includes(value);
806
+ }
807
+ /**
808
+ * Builds the final theme identifier by combining theme name and scheme
809
+ * @param themeName - The name of the theme
810
+ * @param scheme - The scheme variant (light or dark)
811
+ * @returns Combined identifier (e.g., "sixbell_telco__light")
812
+ */
813
+ function buildThemeIdentifier(themeName, scheme) {
814
+ return `${themeName}__${scheme}`;
815
+ }
816
+ /**
817
+ * Extracts theme name and scheme from a combined identifier
818
+ * @param identifier - The combined identifier (e.g., "sixbell_telco__light")
819
+ * @returns Object with extracted themeName and scheme
820
+ */
821
+ function parseThemeIdentifier(identifier) {
822
+ const [themeName, scheme] = identifier.split('__');
823
+ return { themeName, scheme };
824
+ }
825
+ /**
826
+ * Builds the list of available themes from configuration
827
+ * Starts with default base theme, adds additional themes, and filters exclusions
828
+ * Removes duplicates and returns sorted list
829
+ * @param additionalThemes - Additional themes to include
830
+ * @param excludeThemes - Themes to exclude
831
+ * @returns Deduplicated list of available themes
832
+ */
833
+ function buildAvailableThemes(additionalThemes, excludeThemes) {
834
+ // Start with base theme
835
+ let themes = [DEFAULT_BASE_THEME];
836
+ // Add additional themes
837
+ if (additionalThemes && additionalThemes.length > 0) {
838
+ themes = [DEFAULT_BASE_THEME, ...additionalThemes];
839
+ }
840
+ // Filter exclusions
841
+ if (excludeThemes && excludeThemes.length > 0) {
842
+ themes = themes.filter((theme) => !excludeThemes.includes(theme));
843
+ }
844
+ // Remove duplicates and maintain consistency
845
+ return [...new Set(themes)];
846
+ }
847
+ /**
848
+ * Determines the effective default theme from configuration
849
+ * Ensures the default theme is in the available themes list
850
+ * Falls back to first available theme if default is not available
851
+ * @param defaultTheme - Configured default theme
852
+ * @param availableThemes - List of available themes
853
+ * @returns The effective default theme to use
854
+ */
855
+ function resolveDefaultTheme(defaultTheme, availableThemes) {
856
+ // Use provided default if valid
857
+ if (defaultTheme && availableThemes.includes(defaultTheme)) {
858
+ return defaultTheme;
859
+ }
860
+ // Check if base theme is available
861
+ if (availableThemes.includes(DEFAULT_BASE_THEME)) {
862
+ return DEFAULT_BASE_THEME;
863
+ }
864
+ // Fallback to first available
865
+ return availableThemes[0] || DEFAULT_BASE_THEME;
866
+ }
867
+ /**
868
+ * Validates that a given theme exists in the available themes
869
+ * @param theme - Theme name to validate
870
+ * @param availableThemes - List of available themes
871
+ * @returns True if theme is available
872
+ */
873
+ function isThemeAvailable(theme, availableThemes) {
874
+ return availableThemes.includes(theme);
875
+ }
876
+ /**
877
+ * Validates the configuration and logs warnings for invalid states
878
+ * Returns true if configuration is valid for use
879
+ * @param config - Configuration to validate
880
+ * @param configName - Name of config for logging purposes
881
+ * @returns True if configuration is valid
882
+ */
883
+ function validateThemeConfig(config, configName = 'ThemeConfig') {
884
+ const errors = [];
885
+ if (!config.availableThemes || config.availableThemes.length === 0) {
886
+ errors.push('availableThemes must be a non-empty array');
887
+ }
888
+ if (!config.defaultTheme) {
889
+ errors.push('defaultTheme must be defined');
890
+ }
891
+ if (config.defaultTheme && !config.availableThemes.includes(config.defaultTheme)) {
892
+ errors.push(`defaultTheme '${config.defaultTheme}' not in availableThemes`);
893
+ }
894
+ if (errors.length > 0) {
895
+ console.error(`${configName} validation failed:`, errors.join(', '));
896
+ return false;
897
+ }
898
+ return true;
899
+ }
900
+ /**
901
+ * Formats a theme name for display to users
902
+ * Converts snake_case to Title Case
903
+ * @param theme - Theme name to format
904
+ * @returns Formatted theme name
905
+ */
906
+ function formatThemeName(theme) {
907
+ return theme.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase());
908
+ }
909
+ /**
910
+ * Formats a scheme name for display to users
911
+ * Capitalizes first letter
912
+ * @param scheme - Scheme name to format
913
+ * @returns Formatted scheme name
914
+ */
915
+ function formatSchemeName(scheme) {
916
+ return scheme.charAt(0).toUpperCase() + scheme.slice(1);
917
+ }
918
+ /**
919
+ * Checks if the browser supports the matchMedia API
920
+ * Safe to call in non-browser environments
921
+ * @returns True if matchMedia is available
922
+ */
923
+ function supportsMediaQuery() {
924
+ return typeof window !== 'undefined' && typeof window.matchMedia === 'function';
925
+ }
926
+ /**
927
+ * Checks if localStorage is available in the current environment
928
+ * Safe to call in non-browser environments
929
+ * @returns True if localStorage is accessible
930
+ */
931
+ function hasLocalStorage() {
932
+ try {
933
+ return typeof window !== 'undefined' && typeof localStorage !== 'undefined' && localStorage !== null;
934
+ }
935
+ catch {
936
+ return false;
937
+ }
938
+ }
939
+
940
+ /**
941
+ * Theme Scheme Resolver Service
942
+ * Handles scheme detection and resolution (system -> light/dark)
943
+ */
944
+ /**
945
+ * Service for resolving and detecting color schemes
946
+ * Handles system preference detection and scheme validation
947
+ * Separates scheme logic from the main service
948
+ */
949
+ class ThemeSchemeService {
950
+ /**
951
+ * Media query list for detecting dark mode preference
952
+ * Cached to avoid repeated queries
953
+ */
954
+ darkModeMediaQuery = null;
955
+ /**
956
+ * Resolves a theme scheme to its actual light/dark value
957
+ * If scheme is 'system', detects the OS preference
958
+ * If scheme is already 'light' or 'dark', returns it as-is
959
+ * @param scheme - The scheme to resolve
960
+ * @returns Resolved scheme ('light' or 'dark')
961
+ */
962
+ resolveScheme(scheme) {
963
+ if (scheme === 'system') {
964
+ return this.detectSystemScheme();
965
+ }
966
+ return scheme;
967
+ }
968
+ /**
969
+ * Detects the system's preferred color scheme
970
+ * Uses CSS media query (prefers-color-scheme: dark)
971
+ * Safely handles environments where matchMedia is not available
972
+ * @returns 'dark' if system prefers dark, 'light' otherwise
973
+ */
974
+ detectSystemScheme() {
975
+ if (!supportsMediaQuery()) {
976
+ // Fallback to light in non-browser environments
977
+ return 'light';
978
+ }
979
+ // Use cached media query list if available
980
+ if (!this.darkModeMediaQuery) {
981
+ this.darkModeMediaQuery = this.createMediaQuery();
982
+ }
983
+ return this.darkModeMediaQuery.matches ? 'dark' : 'light';
984
+ }
985
+ /**
986
+ * Listens for changes in system color scheme preference
987
+ * Allows components to react to OS theme changes
988
+ * @param listener - Callback function when scheme changes
989
+ * @returns Unsubscribe function to remove listener
990
+ */
991
+ listenToSystemSchemeChanges(listener) {
992
+ if (!supportsMediaQuery()) {
993
+ // Return no-op unsubscribe function if matchMedia not available
994
+ return () => { };
995
+ }
996
+ const mediaQuery = this.createMediaQuery();
997
+ const handleChange = (e) => {
998
+ listener(e.matches ? 'dark' : 'light');
999
+ };
1000
+ // Use addEventListener for modern browsers
1001
+ if (mediaQuery.addEventListener) {
1002
+ mediaQuery.addEventListener('change', handleChange);
1003
+ return () => mediaQuery.removeEventListener('change', handleChange);
1004
+ }
1005
+ // Fallback for older browsers using addListener (deprecated but supported)
1006
+ const legacyMediaQuery = mediaQuery;
1007
+ legacyMediaQuery.addListener?.(handleChange);
1008
+ return () => legacyMediaQuery.removeListener?.(handleChange);
1009
+ }
1010
+ /**
1011
+ * Creates a media query for detecting dark mode
1012
+ * Extracted method to make testing easier
1013
+ * @returns MediaQueryList for dark mode preference
1014
+ */
1015
+ createMediaQuery() {
1016
+ return window.matchMedia(DARK_MODE_MEDIA_QUERY);
1017
+ }
1018
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeSchemeService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1019
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeSchemeService, providedIn: 'root' });
1020
+ }
1021
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeSchemeService, decorators: [{
1022
+ type: Injectable,
1023
+ args: [{ providedIn: 'root' }]
1024
+ }] });
1025
+
1026
+ /**
1027
+ * Theme Storage Service
1028
+ * Handles persistent theme preferences using localStorage
1029
+ */
1030
+ /**
1031
+ * Service for managing theme preferences in local storage
1032
+ * Provides safe access to localStorage with error handling
1033
+ * Works gracefully in non-browser environments (SSR)
1034
+ */
1035
+ class ThemeStorageService {
1036
+ logger = inject(LoggerService);
1037
+ /**
1038
+ * Retrieves the saved theme preference from localStorage
1039
+ * Returns null if no saved preference or storage unavailable
1040
+ * @returns Saved theme name or null
1041
+ */
1042
+ getSavedTheme() {
1043
+ try {
1044
+ if (!hasLocalStorage()) {
1045
+ return null;
1046
+ }
1047
+ const key = this.getStorageKey(THEME_STORAGE_THEME_KEY);
1048
+ return localStorage.getItem(key);
1049
+ }
1050
+ catch (error) {
1051
+ this.logger.error('Failed to retrieve saved theme', error, {
1052
+ component: 'ThemeStorageService',
1053
+ action: 'getSavedTheme',
1054
+ });
1055
+ return null;
1056
+ }
1057
+ }
1058
+ /**
1059
+ * Saves the current theme preference to localStorage
1060
+ * Fails silently if storage is unavailable
1061
+ * @param theme - Theme name to save
1062
+ */
1063
+ saveTheme(theme) {
1064
+ try {
1065
+ if (!hasLocalStorage()) {
1066
+ return;
1067
+ }
1068
+ const key = this.getStorageKey(THEME_STORAGE_THEME_KEY);
1069
+ localStorage.setItem(key, theme);
1070
+ }
1071
+ catch (error) {
1072
+ this.logger.error('Failed to save theme', error, {
1073
+ component: 'ThemeStorageService',
1074
+ action: 'saveTheme',
1075
+ theme,
1076
+ });
1077
+ }
1078
+ }
1079
+ /**
1080
+ * Retrieves the saved scheme preference from localStorage
1081
+ * Returns null if no saved preference or storage unavailable
1082
+ * @returns Saved scheme ('system', 'light', 'dark') or null
1083
+ */
1084
+ getSavedScheme() {
1085
+ try {
1086
+ if (!hasLocalStorage()) {
1087
+ return null;
1088
+ }
1089
+ const key = this.getStorageKey(THEME_STORAGE_SCHEME_KEY);
1090
+ return localStorage.getItem(key);
1091
+ }
1092
+ catch (error) {
1093
+ this.logger.error('Failed to retrieve saved scheme', error, {
1094
+ component: 'ThemeStorageService',
1095
+ action: 'getSavedScheme',
1096
+ });
1097
+ return null;
1098
+ }
1099
+ }
1100
+ /**
1101
+ * Saves the current scheme preference to localStorage
1102
+ * Fails silently if storage is unavailable
1103
+ * @param scheme - Scheme to save
1104
+ */
1105
+ saveScheme(scheme) {
1106
+ try {
1107
+ if (!hasLocalStorage()) {
1108
+ return;
1109
+ }
1110
+ const key = this.getStorageKey(THEME_STORAGE_SCHEME_KEY);
1111
+ localStorage.setItem(key, scheme);
1112
+ }
1113
+ catch (error) {
1114
+ this.logger.error('Failed to save scheme', error, {
1115
+ component: 'ThemeStorageService',
1116
+ action: 'saveScheme',
1117
+ scheme,
1118
+ });
1119
+ }
1120
+ }
1121
+ /**
1122
+ * Clears all saved theme preferences from localStorage
1123
+ * Useful for resetting to defaults
1124
+ */
1125
+ clear() {
1126
+ try {
1127
+ if (!hasLocalStorage()) {
1128
+ return;
1129
+ }
1130
+ const themeKey = this.getStorageKey(THEME_STORAGE_THEME_KEY);
1131
+ const schemeKey = this.getStorageKey(THEME_STORAGE_SCHEME_KEY);
1132
+ localStorage.removeItem(themeKey);
1133
+ localStorage.removeItem(schemeKey);
1134
+ }
1135
+ catch (error) {
1136
+ this.logger.error('Failed to clear storage', error, {
1137
+ component: 'ThemeStorageService',
1138
+ action: 'clear',
1139
+ });
1140
+ }
1141
+ }
1142
+ /**
1143
+ * Constructs a namespaced storage key to avoid collisions
1144
+ * @param key - The base storage key
1145
+ * @returns Namespaced key (e.g., "theme:selectedTheme")
1146
+ */
1147
+ getStorageKey(key) {
1148
+ return `${THEME_STORAGE_NAMESPACE}${key}`;
1149
+ }
1150
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeStorageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1151
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeStorageService, providedIn: 'root' });
1152
+ }
1153
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeStorageService, decorators: [{
1154
+ type: Injectable,
1155
+ args: [{ providedIn: 'root' }]
1156
+ }] });
1157
+
1158
+ class ThemeService {
18
1159
  themeConfig;
1160
+ runtimeThemeConfig;
19
1161
  translationService = inject(TranslationService);
20
- renderer;
21
- initialized = false;
22
- // Default configuration - can be overridden by provider
1162
+ domService = inject(ThemeDomService);
1163
+ storageService = inject(ThemeStorageService);
1164
+ schemeResolver = inject(ThemeSchemeService);
1165
+ assetsService = inject(ThemeAssetsService);
1166
+ router = inject(Router);
1167
+ logger = inject(LoggerService);
1168
+ runtimeConfigPath;
1169
+ runtimeLoader;
1170
+ runtimeLoaderOptions;
1171
+ navigationSubscription;
1172
+ skipFirstNavigation = true;
1173
+ isUsingFallbackConfig = false;
23
1174
  config = {
24
1175
  availableThemes: [DEFAULT_BASE_THEME],
25
1176
  defaultTheme: DEFAULT_BASE_THEME,
26
- defaultScheme: 'system',
1177
+ defaultScheme: DEFAULT_SCHEME,
27
1178
  };
28
- // Reactive signals
29
1179
  selectedTheme = signal(this.config.defaultTheme);
30
1180
  selectedScheme = signal(this.config.defaultScheme);
31
- /**
32
- * Get the actual resolved scheme ('light' or 'dark') regardless of user selection.
33
- * This is useful for conditional rendering where you need to know the actual
34
- * light/dark state, even when the user has selected 'system' preference.
35
- */
36
1181
  resolvedScheme = computed(() => {
37
1182
  const scheme = this.selectedScheme();
38
- if (scheme === 'system') {
39
- // Resolve system preference to actual light/dark
40
- const prefersDark = typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
41
- return prefersDark ? 'dark' : 'light';
42
- }
43
- return scheme; // Return 'light' or 'dark' directly
1183
+ return this.schemeResolver.resolveScheme(scheme);
44
1184
  });
45
- /**
46
- * Convenient computed signal that returns true when the current resolved scheme is 'dark'.
47
- */
48
1185
  isDarkTheme = computed(() => this.resolvedScheme() === 'dark');
49
- // Computed final theme
50
1186
  finalTheme = computed(() => {
51
1187
  const theme = this.selectedTheme();
52
- const resolvedScheme = this.resolvedScheme();
53
- return `${theme}__${resolvedScheme}`;
1188
+ const scheme = this.resolvedScheme();
1189
+ return buildThemeIdentifier(theme, scheme);
54
1190
  });
55
- constructor(rendererFactory, document, themeConfig) {
56
- this.rendererFactory = rendererFactory;
57
- this.document = document;
1191
+ constructor(themeConfig, runtimeThemeConfig) {
58
1192
  this.themeConfig = themeConfig;
59
- this.renderer = this.rendererFactory.createRenderer(null, null);
60
- // Configure with provided config or defaults
1193
+ this.runtimeThemeConfig = runtimeThemeConfig;
61
1194
  if (themeConfig) {
62
1195
  this.configure(themeConfig);
63
1196
  }
64
1197
  else {
65
- // Initialize with defaults immediately
66
- this.initializeFromStorage();
67
- this.applyTheme();
68
- this.initialized = true;
1198
+ // Don't call initializeFromStorage here - the runtime config might not be loaded yet
1199
+ // If we restore from storage now and the theme isn't available, we'll save the wrong value back
1200
+ // The runtime provider will call configureRuntime() which will properly restore from storage
69
1201
  }
70
1202
  }
71
- /**
72
- * Configure and initialize the theme service (used by provider)
73
- */
74
1203
  configure(config = {}) {
75
- // Start with default base theme (sixbell_telco)
76
- let availableThemes = [DEFAULT_BASE_THEME];
77
- // Handle additional themes
78
- if (config.additionalThemes) {
79
- availableThemes = [DEFAULT_BASE_THEME, ...config.additionalThemes];
80
- }
81
- // Apply theme exclusions if specified
82
- if (config.excludeThemes) {
83
- const excludeThemeNames = config.excludeThemes;
84
- availableThemes = availableThemes.filter((theme) => !excludeThemeNames.includes(theme));
85
- }
86
- // Remove duplicates
87
- availableThemes = [...new Set(availableThemes)];
88
- // Determine default theme
89
- const defaultTheme = config.defaultTheme || (availableThemes.includes(DEFAULT_BASE_THEME) ? DEFAULT_BASE_THEME : availableThemes[0]);
90
- // Update configuration
1204
+ const availableThemes = buildAvailableThemes(config.additionalThemes, config.excludeThemes);
1205
+ const defaultTheme = resolveDefaultTheme(config.defaultTheme, availableThemes);
91
1206
  this.config = {
92
1207
  availableThemes,
93
1208
  defaultTheme,
94
- defaultScheme: config.defaultScheme || this.config.defaultScheme,
1209
+ defaultScheme: config.defaultScheme || DEFAULT_SCHEME,
95
1210
  };
96
- // Validate defaultTheme is in available themes
97
- if (!this.config.availableThemes.includes(this.config.defaultTheme)) {
98
- console.warn(`ThemeService: defaultTheme '${this.config.defaultTheme}' not in availableThemes, using '${this.config.availableThemes[0] || DEFAULT_BASE_THEME}'`);
99
- this.config.defaultTheme = this.config.availableThemes[0] || DEFAULT_BASE_THEME;
100
- }
101
- // Update signal defaults
1211
+ validateThemeConfig(this.config, 'ThemeService.configure');
102
1212
  this.selectedTheme.set(this.config.defaultTheme);
103
1213
  this.selectedScheme.set(this.config.defaultScheme);
104
- // Initialize from storage (will override defaults if values exist)
105
1214
  this.initializeFromStorage();
106
1215
  this.applyTheme();
107
- this.initialized = true;
108
1216
  }
109
- /**
110
- * Initialize theme from localStorage and apply it immediately
111
- */
112
- initializeFromStorage() {
113
- // Safety checks for browser environment
114
- if (typeof window === 'undefined' || typeof localStorage === 'undefined') {
115
- console.warn('ThemeService: Browser environment not available, using defaults');
116
- return;
1217
+ configureRuntime(config) {
1218
+ // Note: isUsingFallbackConfig is set via configureRuntimeWithSource() or left from previous call
1219
+ // This keeps configureRuntime compatible with existing code while allowing precise tracking
1220
+ if (config.fonts && config.fonts.length > 0) {
1221
+ this.domService.injectFonts(config.fonts);
117
1222
  }
118
- try {
119
- // Get saved theme or use default
120
- const savedTheme = localStorage.getItem(THEME_SELECTED_THEME_KEY);
121
- const currentTheme = savedTheme && this.config.availableThemes.includes(savedTheme) ? savedTheme : this.config.defaultTheme;
122
- // Get saved scheme or use default
123
- const savedScheme = localStorage.getItem(THEME_SELECTED_SCHEME_KEY);
124
- const currentScheme = savedScheme && ['system', 'light', 'dark'].includes(savedScheme) ? savedScheme : this.config.defaultScheme;
125
- // Update signals
126
- this.selectedTheme.set(currentTheme);
127
- this.selectedScheme.set(currentScheme);
1223
+ if (config.globalVariables) {
1224
+ this.domService.injectGlobalVariables(config.globalVariables);
128
1225
  }
129
- catch (error) {
130
- console.error('ThemeService: Failed to initialize from storage:', error);
1226
+ if (config.themes) {
1227
+ this.domService.injectThemeStyles(config.themes);
131
1228
  }
132
- }
133
- /**
134
- * Apply the current theme to the document
135
- */
136
- applyTheme() {
137
- const finalTheme = this.finalTheme();
138
- // Set the theme attribute on the body
139
- this.renderer.setAttribute(this.document.body, 'data-theme', finalTheme);
140
- // Persist to localStorage
141
- if (typeof localStorage !== 'undefined') {
142
- localStorage.setItem(THEME_SELECTED_THEME_KEY, this.selectedTheme());
143
- localStorage.setItem(THEME_SELECTED_SCHEME_KEY, this.selectedScheme());
1229
+ // Initialize assets service with configuration
1230
+ this.assetsService.setConfig(config);
1231
+ if (!config.themes || !Object.keys(config.themes).length) {
1232
+ this.logger.error('Invalid runtime config - no themes defined', undefined, {
1233
+ component: 'ThemeService',
1234
+ action: 'configureRuntime',
1235
+ });
1236
+ return;
1237
+ }
1238
+ // Auto-derive availableThemes from themes object keys, apply exclusions
1239
+ const themesFromConfig = Object.keys(config.themes);
1240
+ const availableThemes = buildAvailableThemes(themesFromConfig, config.excludeThemes);
1241
+ if (!availableThemes.length) {
1242
+ this.logger.error('No themes available after applying exclusions', undefined, {
1243
+ component: 'ThemeService',
1244
+ action: 'configureRuntime',
1245
+ });
1246
+ return;
1247
+ }
1248
+ // Use provided defaultTheme or fallback to first available theme
1249
+ const defaultTheme = config.defaultTheme ? resolveDefaultTheme(config.defaultTheme, availableThemes) : availableThemes[0];
1250
+ this.config = {
1251
+ availableThemes,
1252
+ defaultTheme,
1253
+ defaultScheme: config.defaultScheme || DEFAULT_SCHEME,
1254
+ };
1255
+ validateThemeConfig(this.config, 'ThemeService.configureRuntime');
1256
+ // Set defaults from config
1257
+ this.selectedTheme.set(this.config.defaultTheme);
1258
+ this.selectedScheme.set(this.config.defaultScheme);
1259
+ // Always restore user's saved settings (overrides defaults if they exist)
1260
+ this.initializeFromStorage();
1261
+ this.applyTheme();
1262
+ // Now that initialization is complete, set up the router subscription for fresh on navigation
1263
+ // This ensures the initial navigation event doesn't trigger a reload
1264
+ const freshOnNavigation = this.runtimeLoaderOptions?.freshOnNavigation ?? false;
1265
+ if (freshOnNavigation && !this.navigationSubscription) {
1266
+ this.navigationSubscription = this.router.events.pipe(filter((event) => event instanceof NavigationEnd)).subscribe(() => {
1267
+ // Skip the first navigation event (happens during app bootstrap)
1268
+ if (this.skipFirstNavigation) {
1269
+ this.skipFirstNavigation = false;
1270
+ return;
1271
+ }
1272
+ this.reloadRuntimeConfig().catch((error) => {
1273
+ if (this.runtimeLoaderOptions?.logErrors !== false) {
1274
+ this.logger.error('Error reloading runtime config on navigation', error, {
1275
+ component: 'ThemeService',
1276
+ action: 'configureRuntime.navigationSubscription',
1277
+ });
1278
+ }
1279
+ });
1280
+ });
144
1281
  }
145
1282
  }
146
- /**
147
- * Set the current theme
148
- */
149
1283
  setTheme(theme) {
150
- if (theme && this.config.availableThemes.includes(theme)) {
1284
+ if (isThemeAvailable(theme, this.config.availableThemes)) {
151
1285
  this.selectedTheme.set(theme);
152
1286
  this.applyTheme();
153
1287
  }
154
1288
  else {
155
- console.warn(`ThemeService: Theme '${theme}' not available, using default '${this.config.defaultTheme}'`);
1289
+ this.logger.warn(`Theme '${theme}' not available. Using default '${this.config.defaultTheme}'`, {
1290
+ component: 'ThemeService',
1291
+ action: 'setTheme',
1292
+ requestedTheme: theme,
1293
+ defaultTheme: this.config.defaultTheme,
1294
+ });
156
1295
  }
157
1296
  }
158
- /**
159
- * Set the current color scheme
160
- */
161
1297
  setScheme(scheme) {
162
- if (scheme && ['system', 'light', 'dark'].includes(scheme)) {
1298
+ if (isValidScheme(scheme) && VALID_SCHEMES.includes(scheme)) {
163
1299
  this.selectedScheme.set(scheme);
164
1300
  this.applyTheme();
165
1301
  }
166
1302
  else {
167
- console.warn(`ThemeService: Scheme '${scheme}' not valid, using default '${this.config.defaultScheme}'`);
1303
+ this.logger.warn(`Scheme '${scheme}' is invalid. Using default '${this.config.defaultScheme}'`, {
1304
+ component: 'ThemeService',
1305
+ action: 'setScheme',
1306
+ requestedScheme: scheme,
1307
+ defaultScheme: this.config.defaultScheme,
1308
+ });
168
1309
  }
169
1310
  }
170
- /**
171
- * Get available themes
172
- */
173
1311
  getAvailableThemes() {
174
1312
  return this.config.availableThemes;
175
1313
  }
176
- /**
177
- * Get available schemes
178
- */
179
1314
  getAvailableSchemes() {
180
1315
  return ['system', 'light', 'dark'];
181
1316
  }
182
- /**
183
- * Get default theme
184
- */
185
1317
  getDefaultTheme() {
186
1318
  return this.config.defaultTheme;
187
1319
  }
188
- /**
189
- * Get default scheme
190
- */
191
1320
  getDefaultScheme() {
192
1321
  return this.config.defaultScheme;
193
1322
  }
194
- /**
195
- * Get localized scheme name by code using translations
196
- * This automatically returns the localized name based on the current language
197
- */
198
1323
  getLocalizedSchemeName(scheme) {
199
1324
  const translationKey = `sdk.theme.schemes.${scheme}`;
200
1325
  const translatedName = this.translationService.instant(translationKey);
201
1326
  if (translatedName && translatedName !== translationKey) {
202
1327
  return translatedName;
203
1328
  }
204
- return scheme.charAt(0).toUpperCase() + scheme.slice(1);
1329
+ return formatSchemeName(scheme);
205
1330
  }
206
- /**
207
- * Get localized theme name by code using translations
208
- * This automatically returns the localized name based on the current language
209
- */
210
1331
  getLocalizedThemeName(theme) {
211
1332
  const translationKey = `sdk.theme.themes.${theme}`;
212
1333
  const translatedName = this.translationService.instant(translationKey);
213
1334
  if (translatedName && translatedName !== translationKey) {
214
1335
  return translatedName;
215
1336
  }
216
- return theme.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase());
1337
+ return formatThemeName(theme);
1338
+ }
1339
+ initializeFromStorage() {
1340
+ const savedTheme = this.storageService.getSavedTheme();
1341
+ this.logger.debug('initializeFromStorage - savedTheme', {
1342
+ component: 'ThemeService',
1343
+ action: 'initializeFromStorage',
1344
+ savedTheme,
1345
+ availableThemes: this.config.availableThemes,
1346
+ });
1347
+ if (savedTheme) {
1348
+ if (isThemeAvailable(savedTheme, this.config.availableThemes)) {
1349
+ // Saved theme is available in current config
1350
+ this.logger.debug('Restoring saved theme', {
1351
+ component: 'ThemeService',
1352
+ action: 'initializeFromStorage',
1353
+ savedTheme,
1354
+ });
1355
+ this.selectedTheme.set(savedTheme);
1356
+ }
1357
+ else if (this.isUsingFallbackConfig) {
1358
+ // Using fallback config (JSON failed): restore saved theme anyway
1359
+ // This preserves user preference when using cached data
1360
+ this.logger.debug('Using fallback config - restoring saved theme anyway', {
1361
+ component: 'ThemeService',
1362
+ action: 'initializeFromStorage',
1363
+ savedTheme,
1364
+ });
1365
+ this.selectedTheme.set(savedTheme);
1366
+ // Add saved theme to available list if missing
1367
+ if (!this.config.availableThemes.includes(savedTheme)) {
1368
+ this.config.availableThemes.push(savedTheme);
1369
+ }
1370
+ }
1371
+ else {
1372
+ // Using valid config but theme is missing: reset to defaultTheme
1373
+ // This handles the case where theme was removed/renamed in config
1374
+ this.logger.debug('Valid config but saved theme missing - using defaultTheme', {
1375
+ component: 'ThemeService',
1376
+ action: 'initializeFromStorage',
1377
+ savedTheme,
1378
+ defaultTheme: this.config.defaultTheme,
1379
+ });
1380
+ this.selectedTheme.set(this.config.defaultTheme);
1381
+ }
1382
+ }
1383
+ const savedScheme = this.storageService.getSavedScheme();
1384
+ this.logger.debug('initializeFromStorage - savedScheme', {
1385
+ component: 'ThemeService',
1386
+ action: 'initializeFromStorage',
1387
+ savedScheme,
1388
+ });
1389
+ if (savedScheme && isValidScheme(savedScheme)) {
1390
+ this.logger.debug('Restoring saved scheme', {
1391
+ component: 'ThemeService',
1392
+ action: 'initializeFromStorage',
1393
+ savedScheme,
1394
+ });
1395
+ this.selectedScheme.set(savedScheme);
1396
+ }
1397
+ }
1398
+ applyTheme() {
1399
+ const themeIdentifier = this.finalTheme();
1400
+ this.domService.setActiveTheme(themeIdentifier);
1401
+ this.storageService.saveTheme(this.selectedTheme());
1402
+ this.storageService.saveScheme(this.selectedScheme());
1403
+ }
1404
+ /**
1405
+ * Internal method to set runtime loader and enable navigation-based reloading.
1406
+ * Called by provideRuntimeTheme.
1407
+ * @internal
1408
+ */
1409
+ setRuntimeLoader(configPath, loader, loaderOptions) {
1410
+ this.runtimeConfigPath = configPath;
1411
+ this.runtimeLoader = loader;
1412
+ this.runtimeLoaderOptions = loaderOptions;
217
1413
  }
218
1414
  /**
219
- * Force initialization method for MFE environments
1415
+ * Internal method to configure runtime theme with config source information.
1416
+ * @internal
220
1417
  */
1418
+ configureRuntimeWithSource(config, source) {
1419
+ this.isUsingFallbackConfig = source === 'fallback';
1420
+ this.configureRuntime(config);
1421
+ }
1422
+ /**
1423
+ * Manually reload the runtime theme configuration from the configured path.
1424
+ * Useful for hot-reload scenarios or programmatic refresh.
1425
+ */
1426
+ async reloadRuntimeConfig() {
1427
+ if (!this.runtimeConfigPath || !this.runtimeLoader || !this.runtimeLoaderOptions) {
1428
+ return;
1429
+ }
1430
+ try {
1431
+ const result = await this.runtimeLoader.load(this.runtimeConfigPath, this.runtimeLoaderOptions);
1432
+ this.configureRuntime(result.data);
1433
+ }
1434
+ catch (error) {
1435
+ if (this.runtimeLoaderOptions.logErrors !== false) {
1436
+ this.logger.error(`Error reloading runtime config from ${this.runtimeConfigPath}`, error, {
1437
+ component: 'ThemeService',
1438
+ action: 'reloadRuntimeConfig',
1439
+ configPath: this.runtimeConfigPath,
1440
+ });
1441
+ }
1442
+ // Don't update config on reload error - keep existing config
1443
+ }
1444
+ }
221
1445
  init() {
222
- // This method just ensures the service is instantiated and initialized
223
- this.getAvailableThemes(); // Trigger any lazy initialization
1446
+ this.getAvailableThemes();
224
1447
  }
225
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeService, deps: [{ token: i0.RendererFactory2 }, { token: DOCUMENT }, { token: THEME_CONFIG_TOKEN, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
1448
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeService, deps: [{ token: THEME_CONFIG_TOKEN, optional: true }, { token: RUNTIME_THEME_CONFIG_TOKEN, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
226
1449
  static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeService, providedIn: 'root' });
227
1450
  }
228
1451
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.0", ngImport: i0, type: ThemeService, decorators: [{
229
1452
  type: Injectable,
230
- args: [{
231
- providedIn: 'root',
232
- }]
233
- }], ctorParameters: () => [{ type: i0.RendererFactory2 }, { type: Document, decorators: [{
1453
+ args: [{ providedIn: 'root' }]
1454
+ }], ctorParameters: () => [{ type: undefined, decorators: [{
234
1455
  type: Inject,
235
- args: [DOCUMENT]
1456
+ args: [THEME_CONFIG_TOKEN]
1457
+ }, {
1458
+ type: Optional
236
1459
  }] }, { type: undefined, decorators: [{
237
1460
  type: Inject,
238
- args: [THEME_CONFIG_TOKEN]
1461
+ args: [RUNTIME_THEME_CONFIG_TOKEN]
239
1462
  }, {
240
1463
  type: Optional
241
1464
  }] }] });
1465
+
242
1466
  /**
243
- * Provider function for theme configuration in Angular applications
244
- * This provides the theme configuration through dependency injection
245
- *
246
- * @param config Optional theme configuration
247
- * @returns Provider array that configures theme service
248
- *
249
- * @example
250
- * ```typescript
251
- * // app.config.ts
252
- * import { provideTheme } from '@sixbell-telco/sdk/utils/theme';
253
- *
254
- * export const appConfig: ApplicationConfig = {
255
- * providers: [
256
- * provideRouter(routes),
257
- *
258
- * // Basic usage - sixbell_telco always available
259
- * provideTheme({
260
- * defaultScheme: 'light',
261
- * defaultTheme: 'sixbell_telco' // IntelliSense: 'sixbell_telco'
262
- * }),
263
- *
264
- * // With additional themes
265
- * provideTheme({
266
- * additionalThemes: ['wom', 'custom'] as const,
267
- * defaultTheme: 'custom', // IntelliSense: 'sixbell_telco' | string
268
- * excludeThemes: ['wom'] as const, // IntelliSense: 'sixbell_telco' | string
269
- * defaultScheme: 'system'
270
- * }),
271
- *
272
- * // ... other providers
273
- * ],
274
- * };
275
- * ```
1467
+ * Theme-specific IndexedDB database name for resource caching
1468
+ */
1469
+ const THEME_INDEXED_DB_NAME = 'sixbell-theme';
1470
+ const RUNTIME_THEME_LOADER_DEFAULTS = {
1471
+ cacheName: 'theme-runtime-config',
1472
+ indexedDBName: THEME_INDEXED_DB_NAME,
1473
+ storageOrder: ['indexedDB'],
1474
+ cacheTTL: 1000 * 60 * 60 * 24,
1475
+ freshOnNavigation: true, // Hot-reload on every navigation by default
1476
+ staleWhileRevalidate: true,
1477
+ useStaleOnError: true,
1478
+ revalidateOnFresh: true,
1479
+ retries: 3,
1480
+ retryDelayMs: 500,
1481
+ timeoutMs: 8000,
1482
+ seedCacheWithFallback: true,
1483
+ logErrors: true,
1484
+ };
1485
+
1486
+ function buildRuntimeThemeLoaderOptions(configPath, overrides) {
1487
+ const merged = { ...RUNTIME_THEME_LOADER_DEFAULTS, ...overrides };
1488
+ return {
1489
+ ...merged,
1490
+ cacheKey: overrides?.cacheKey ?? configPath,
1491
+ fallbackData: overrides?.fallbackData ?? FALLBACK_RUNTIME_THEME_CONFIG,
1492
+ parser: overrides?.parser ?? (async (response) => (await response.json())),
1493
+ };
1494
+ }
1495
+ /**
1496
+ * @deprecated Use provideRuntimeTheme instead.
276
1497
  */
277
- // Single overload that provides IntelliSense for all cases
278
1498
  function provideTheme(config) {
279
- return [
1499
+ return makeEnvironmentProviders([
280
1500
  {
281
1501
  provide: THEME_CONFIG_TOKEN,
282
- // Pass through original object so literal tuple types survive for IDE IntelliSense
283
1502
  useValue: (config || {}),
284
1503
  },
285
- // Automatically initialize theme service for MFE compatibility
286
1504
  provideAppInitializer(() => inject(ThemeService).init()),
287
- ];
1505
+ ]);
1506
+ }
1507
+ function provideRuntimeTheme(configPath, options) {
1508
+ const initialConfig = options?.loaderOptions?.fallbackData ?? FALLBACK_RUNTIME_THEME_CONFIG;
1509
+ return makeEnvironmentProviders([
1510
+ {
1511
+ provide: RUNTIME_THEME_CONFIG_TOKEN,
1512
+ useValue: initialConfig,
1513
+ },
1514
+ provideAppInitializer(() => {
1515
+ const themeService = inject(ThemeService);
1516
+ const logger = inject(LoggerService);
1517
+ // Create loader with global logger
1518
+ const loader = options?.loader ?? new ResourceLoader(RUNTIME_THEME_LOADER_DEFAULTS, logger);
1519
+ return (async () => {
1520
+ const loaderOptions = buildRuntimeThemeLoaderOptions(configPath, options?.loaderOptions);
1521
+ // Set up runtime loader and navigation listener
1522
+ themeService.setRuntimeLoader(configPath, loader, loaderOptions);
1523
+ try {
1524
+ const result = await loader.load(configPath, loaderOptions);
1525
+ // Pass the source so service knows if using cache, network, or fallback
1526
+ themeService.configureRuntimeWithSource(result.data, result.source);
1527
+ }
1528
+ catch (error) {
1529
+ if (loaderOptions.logErrors !== false) {
1530
+ logger.error(`Error loading runtime config from ${configPath}`, error, {
1531
+ component: 'ThemeProvider',
1532
+ action: 'provideRuntimeTheme',
1533
+ configPath,
1534
+ });
1535
+ }
1536
+ // When catching error, we're using fallback
1537
+ themeService.configureRuntimeWithSource(loaderOptions.fallbackData ?? FALLBACK_RUNTIME_THEME_CONFIG, 'fallback');
1538
+ }
1539
+ })();
1540
+ }),
1541
+ ]);
288
1542
  }
289
1543
 
290
1544
  /**
291
1545
  * Generated bundle index. Do not edit.
292
1546
  */
293
1547
 
294
- export { DEFAULT_BASE_THEME, DEFAULT_THEMES, DEFAULT_THEME_CODES, THEME_CONFIG_TOKEN, ThemeService, provideTheme };
1548
+ export { DARK_MODE_MEDIA_QUERY, DARK_THEME_CLASS, DEFAULT_BASE_THEME, DEFAULT_SCHEME, DEFAULT_THEMES, DEFAULT_THEME_CODES, FALLBACK_RUNTIME_THEME_CONFIG, RUNTIME_THEME_CONFIG_TOKEN, THEME_ATTRIBUTE_NAME, THEME_CONFIG_TOKEN, THEME_SCHEME_SEPARATOR, THEME_STORAGE_NAMESPACE, THEME_STORAGE_SCHEME_KEY, THEME_STORAGE_THEME_KEY, ThemeAssetsService, ThemeDomService, ThemeSchemeService, ThemeService, ThemeStorageService, VALID_SCHEMES, buildAvailableThemes, buildThemeIdentifier, formatSchemeName, formatThemeName, hasLocalStorage, isThemeAvailable, isValidScheme, parseThemeIdentifier, provideRuntimeTheme, provideTheme, resolveDefaultTheme, supportsMediaQuery, validateThemeConfig };
295
1549
  //# sourceMappingURL=sixbell-telco-sdk-utils-theme.mjs.map