@su-labs/theme 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Yevheniy Alekseyev <yev.alekseyev@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,139 @@
1
+ # SuThemeService
2
+
3
+ A robust and reactive Angular service for managing application themes. It provides a full-featured solution that supports dynamic switching, user preference persistence, and automatic system theme detection.
4
+
5
+ ## Features
6
+
7
+ * Reactive State: Uses Angular signals for efficient, reactive theme management.
8
+ * System Theme Integration: Automatically follows the user's system theme preference (`prefers-color-scheme`).
9
+ * Persistence: Remembers the user's last-selected theme using `localStorage`.
10
+ * Configurable: Customizable with a configuration object for storage keys, CSS variable prefixes, and default themes.
11
+ * Programmatic Control: Simple public API to set, get, and track the active theme.
12
+
13
+ ## Available Themes
14
+
15
+ The service currently supports the following theme names by default:
16
+
17
+ * `light`
18
+ * `dark`
19
+ * `contrast`
20
+ * `custom`
21
+ * `system` (follows OS preference)
22
+
23
+ You can provide custom variables for any of these themes via the `themes` property in `SuThemeConfig`.
24
+
25
+ ## Usage
26
+
27
+ The `SuThemeService` must be initialized at application startup to load its configuration and initial theme.
28
+
29
+ ### Example 1: Global Initialization with provideAppInitializer
30
+
31
+ ```typescript
32
+ // main.ts or app.config.ts
33
+ import { provideAppInitializer, inject } from '@angular/core';
34
+ import { SuThemeService, SuThemeConfig } from './path/to/su-theme.service';
35
+
36
+ const myThemeConfig: SuThemeConfig = {
37
+ // Optional: Set a default theme if none is saved
38
+ defaultTheme: 'dark',
39
+ // Optional: Provide custom CSS variables for any theme
40
+ themes: {
41
+ dark: {
42
+ color: '#333',
43
+ background: '#eee',
44
+ 'main-accent': '#007bff',
45
+ },
46
+ },
47
+ };
48
+
49
+ export const appConfig = {
50
+ providers: [
51
+ provideAppInitializer(() => {
52
+ const themeService = inject(SuThemeService);
53
+ themeService.init(myThemeConfig);
54
+ }),
55
+ ],
56
+ };
57
+ ```
58
+
59
+ ✅ This ensures the theme is loaded and applied before the application renders. The `SuThemeService` handles all the logic internally, including loading from `localStorage` and applying the initial theme.
60
+
61
+ ### Example 2: Using the Theme in a Component
62
+ Your service automatically applies CSS variables to the `:root` element. Your application stylesheets can use these variables, and the service will handle updating their values when the theme changes.
63
+
64
+ ```CSS
65
+
66
+ /* styles.css */
67
+ /* Use the CSS variables in your stylesheet */
68
+ body {
69
+ color: var(--su-theme-color);
70
+ background-color: var(--su-theme-background);
71
+ }
72
+
73
+ h1 {
74
+ color: var(--su-theme-main-accent);
75
+ }
76
+ ```
77
+
78
+ The service dynamically updates these variables based on the active theme, applying a combination of its internal defaults and any custom overrides you provide in the configuration.
79
+
80
+ ### Example 3: Dynamic Theme Switching
81
+ Use the setTheme() method to switch themes and the theme signal to read the current state.
82
+
83
+ ```TypeScript
84
+
85
+ import { Component, inject } from '@angular/core';
86
+ import { SuThemeService, SuThemeName } from './path/to/su-theme.service';
87
+
88
+ @Component({
89
+ selector: 'app-theme-switcher',
90
+ standalone: true,
91
+ imports: [],
92
+ template: `
93
+ <h1>Dynamic Theme Switching</h1>
94
+ <p>Current Theme: {{ themeService.theme() }}</p>
95
+ <button (click)="setTheme('light')">Light</button>
96
+ <button (click)="setTheme('dark')">Dark</button>
97
+ <button (click)="setTheme('system')">System</button>
98
+ `,
99
+ })
100
+ export class ThemeSwitcherComponent {
101
+ // Use the service directly in the template
102
+ public readonly themeService = inject(SuThemeService);
103
+
104
+ setTheme(themeName: SuThemeName) {
105
+ this.themeService.setTheme(themeName);
106
+ }
107
+ }
108
+ ```
109
+
110
+ ✅ This correctly shows how to use your service's public API to switch between themes. The service handles the underlying logic, including persistence and CSS variable application.
111
+
112
+ ## Configuration Options
113
+
114
+ The service can be configured to fit your application's needs.
115
+
116
+ | Option | Description | Default Value |
117
+ |--------------------|---------------------------------------------------------------|------------------|
118
+ | `storageKey` | The key used to persist the selected theme in `localStorage`. | `'su:theme'` |
119
+ | `cssVarPrefix` | The prefix for all CSS variables managed by the service. | `'--su-theme-'` |
120
+ | `defaultTheme` | The theme to use if no preference is saved in `localStorage`. | `'system'` |
121
+ | `themes` | An object with custom CSS variable overrides for each theme. | `undefined` |
122
+
123
+ ## Notes
124
+ - The service safely handles properties and ignores null or undefined values, preventing issues like prototype pollution.
125
+
126
+ - Works seamlessly with standalone components and reactive setups thanks to its signal-based API.
127
+
128
+ - Persistence is handled automatically: The service saves the user's preference to `localStorage` when you call `setTheme(..., true)`. On initialization, it automatically restores this saved preference. You do not need to add this logic in your components.
129
+
130
+ ## Contributing
131
+
132
+ If you find any bugs or have feature requests, please open an issue or submit a pull request on our [**GitHub repository**](https://github.com/Greezaaa/settings-utils-lib.git).
133
+
134
+ To contribute code, please ensure your changes include unit tests to maintain code quality. Please see the main repository's `README.md` for details on the monorepo structure.
135
+
136
+ ## License
137
+
138
+ This project is licensed under the MIT License. See the [**LICENSE**](https://github.com/Greezaaa/settings-utils-lib/blob/main/projects/su-labs/theme/LICENSE) file for details.
139
+
@@ -0,0 +1,309 @@
1
+ import * as i0 from '@angular/core';
2
+ import { signal, Injectable } from '@angular/core';
3
+ import { beforeAll, vi, describe, beforeEach, it, expect } from 'vitest';
4
+
5
+ /**
6
+ * Service for managing application themes.
7
+ *
8
+ * Provides reactive theme state via signals and methods to set/get the theme.
9
+ * Supports user preference, system-based themes, and custom CSS variable overrides.
10
+ */
11
+ class SuThemeService {
12
+ /** Configuration for the theme, provided during initialization */
13
+ suThemeConfig = {};
14
+ /** CSS variable prefix, can be customized */
15
+ cssVarPrefix = '--su-theme-';
16
+ /** localStorage key for storing user preference, can be customized */
17
+ storageKey = 'su:theme';
18
+ /** User selected theme (can be 'system') */
19
+ userPreference = 'light';
20
+ /** Current resolved theme signal ('light' | 'dark' | 'contrast' | 'custom') */
21
+ currentThemeSignal = signal('light', ...(ngDevMode ? [{ debugName: "currentThemeSignal" }] : []));
22
+ /** Read-only access to the resolved theme signal */
23
+ theme = this.currentThemeSignal.asReadonly();
24
+ /** System media query listener callback */
25
+ systemChangeHandler = null;
26
+ /** MediaQueryList instance for system theme changes */
27
+ mediaQuery;
28
+ /**
29
+ * Initialize the service with optional configuration.
30
+ * Should be called from APP_INITIALIZER for default setup.
31
+ * @param config Optional configuration object.
32
+ */
33
+ init(config) {
34
+ // Apply configuration and defaults
35
+ this.suThemeConfig = { ...this.suThemeConfig, ...config };
36
+ this.cssVarPrefix = this.suThemeConfig.cssVarPrefix ?? this.cssVarPrefix;
37
+ this.storageKey = this.suThemeConfig.storageKey ?? this.storageKey;
38
+ // Set user preference from localStorage or default
39
+ this.userPreference = localStorage.getItem(this.storageKey) ?? this.suThemeConfig.defaultTheme ?? 'system';
40
+ // Set the initial theme based on the resolved preference
41
+ this.setTheme(this.userPreference, false);
42
+ }
43
+ /**
44
+ * Get the currently active, resolved theme.
45
+ * @returns The resolved theme name ('light', 'dark', 'contrast', 'custom').
46
+ */
47
+ getTheme() {
48
+ return this.currentThemeSignal();
49
+ }
50
+ /**
51
+ * Get the user's theme preference (may be 'system').
52
+ * @returns The user preference ('light', 'dark', 'contrast', 'custom', 'system').
53
+ */
54
+ getUserPreference() {
55
+ return this.userPreference;
56
+ }
57
+ /**
58
+ * Set a new theme.
59
+ * @param theme The theme to set ('light', 'dark', 'contrast', 'custom', 'system').
60
+ * @param persist Whether to store the preference in localStorage (default: true).
61
+ */
62
+ setTheme(theme, persist = true) {
63
+ // Stop listening to system changes if we are setting a non-system theme
64
+ if (theme !== 'system') {
65
+ this.stopListeningToSystemChanges();
66
+ }
67
+ // Resolve the final theme name
68
+ const resolvedTheme = theme === 'system' ? this.resolveSystemTheme() : theme;
69
+ // Update internal state and signals
70
+ this.userPreference = theme;
71
+ this.currentThemeSignal.set(resolvedTheme);
72
+ // Apply the theme to the document and manage system listeners
73
+ document.documentElement.setAttribute('data-theme', resolvedTheme);
74
+ this.applyThemeVariables(resolvedTheme);
75
+ // Persist preference to localStorage
76
+ if (persist) {
77
+ localStorage.setItem(this.storageKey, theme);
78
+ }
79
+ // Start listening for system changes if the new preference is 'system'
80
+ if (theme === 'system') {
81
+ this.listenToSystemChanges();
82
+ }
83
+ }
84
+ /**
85
+ * Resolve the current system theme using prefers-color-scheme.
86
+ * @returns 'dark' if system prefers dark mode, otherwise 'light'.
87
+ */
88
+ resolveSystemTheme() {
89
+ if (typeof window !== 'undefined' && window.matchMedia('(prefers-color-scheme: dark)').matches) {
90
+ return 'dark';
91
+ }
92
+ return 'light';
93
+ }
94
+ /**
95
+ * Listen to system theme changes and automatically update the theme.
96
+ * Only active when user preference is 'system'.
97
+ */
98
+ listenToSystemChanges() {
99
+ // Only set up the listener if it's not already active
100
+ if (!this.mediaQuery) {
101
+ this.mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
102
+ this.systemChangeHandler = (event) => {
103
+ // Only react if the user preference is still 'system'
104
+ if (this.userPreference === 'system') {
105
+ this.currentThemeSignal.set(event.matches ? 'dark' : 'light');
106
+ document.documentElement.setAttribute('data-theme', this.currentThemeSignal());
107
+ this.applyThemeVariables(this.currentThemeSignal());
108
+ }
109
+ };
110
+ this.mediaQuery.addEventListener('change', this.systemChangeHandler);
111
+ }
112
+ }
113
+ /**
114
+ * Stop listening to system theme changes.
115
+ * Should be called when the service is destroyed or theme is no longer 'system'.
116
+ */
117
+ stopListeningToSystemChanges() {
118
+ if (this.mediaQuery && this.systemChangeHandler) {
119
+ this.mediaQuery.removeEventListener('change', this.systemChangeHandler);
120
+ this.systemChangeHandler = null;
121
+ this.mediaQuery = undefined;
122
+ }
123
+ }
124
+ /**
125
+ * Apply CSS variables for the given theme.
126
+ * This method applies default variables if they are not overridden in the config.
127
+ * @param theme The theme whose variables should be applied.
128
+ */
129
+ applyThemeVariables(theme) {
130
+ // Map of default variables for light and dark themes
131
+ const defaultThemes = {
132
+ light: {
133
+ color: '#333',
134
+ background: '#fff',
135
+ 'main-accent': '#007bff',
136
+ 'second-accent': '#6c757d',
137
+ 'third-accent': '#28a745',
138
+ },
139
+ dark: {
140
+ color: '#f0f0f0',
141
+ background: '#1a1a1a',
142
+ 'main-accent': '#38a8e1',
143
+ 'second-accent': '#a8b0b5',
144
+ 'third-accent': '#2ee057',
145
+ },
146
+ // You can add more default themes here
147
+ contrast: {
148
+ color: '#000',
149
+ background: '#fff',
150
+ 'main-accent': '#ff0000',
151
+ },
152
+ custom: {},
153
+ system: {},
154
+ };
155
+ // Use a combination of default and user-defined variables
156
+ const variablesToApply = {
157
+ ...defaultThemes[theme],
158
+ ...(this.suThemeConfig.themes?.[theme] ?? {}),
159
+ };
160
+ // Apply the variables to the root element
161
+ for (const [key, value] of Object.entries(variablesToApply)) {
162
+ if (value) {
163
+ document.documentElement.style.setProperty(`${this.cssVarPrefix}${key}`, value);
164
+ }
165
+ }
166
+ }
167
+ /** Angular lifecycle hook for service destruction */
168
+ ngOnDestroy() {
169
+ this.stopListeningToSystemChanges();
170
+ }
171
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.7", ngImport: i0, type: SuThemeService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
172
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.7", ngImport: i0, type: SuThemeService, providedIn: 'root' });
173
+ }
174
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.7", ngImport: i0, type: SuThemeService, decorators: [{
175
+ type: Injectable,
176
+ args: [{
177
+ providedIn: 'root',
178
+ }]
179
+ }] });
180
+
181
+ let matchMediaCallback = null;
182
+ let currentMatches = false;
183
+ beforeAll(() => {
184
+ vi.stubGlobal('matchMedia', (query) => ({
185
+ matches: currentMatches,
186
+ media: query,
187
+ addEventListener: (_, cb) => {
188
+ matchMediaCallback = cb;
189
+ },
190
+ removeEventListener: () => {
191
+ matchMediaCallback = null;
192
+ },
193
+ onchange: null,
194
+ dispatchEvent: vi.fn(),
195
+ }));
196
+ });
197
+ describe('SuThemeService', () => {
198
+ let service;
199
+ beforeEach(() => {
200
+ localStorage.clear();
201
+ currentMatches = false;
202
+ matchMediaCallback = null;
203
+ service = new SuThemeService();
204
+ // Reset the DOM for each test
205
+ document.documentElement.setAttribute('data-theme', '');
206
+ document.documentElement.style.cssText = '';
207
+ });
208
+ it('should initialize with default theme "system" if no config', () => {
209
+ service.init();
210
+ expect(service.getUserPreference()).toBe('system');
211
+ // The resolved theme can be either 'light' or 'dark' based on the initial `currentMatches`
212
+ expect(['light', 'dark']).toContain(service.getTheme());
213
+ });
214
+ it('should apply custom CSS variables from a configuration', () => {
215
+ const customConfig = {
216
+ themes: {
217
+ light: {
218
+ color: 'red',
219
+ background: 'black',
220
+ },
221
+ },
222
+ };
223
+ service.init(customConfig);
224
+ service.setTheme('light');
225
+ const rootStyle = getComputedStyle(document.documentElement);
226
+ expect(rootStyle.getPropertyValue('--su-theme-color')).toBe('red');
227
+ expect(rootStyle.getPropertyValue('--su-theme-background')).toBe('black');
228
+ });
229
+ it('should save user preference to localStorage', () => {
230
+ service.init();
231
+ service.setTheme('dark');
232
+ expect(localStorage.getItem('su:theme')).toBe('dark');
233
+ });
234
+ it('should resolve system theme when preference is "system"', () => {
235
+ currentMatches = true; // Simulates dark mode
236
+ service.init({ defaultTheme: 'system' });
237
+ expect(service.getTheme()).toBe('dark');
238
+ expect(service.getUserPreference()).toBe('system');
239
+ });
240
+ describe('setTheme method', () => {
241
+ it('should update the theme and apply default variables', () => {
242
+ service.init();
243
+ service.setTheme('dark');
244
+ expect(service.getTheme()).toBe('dark');
245
+ const rootStyle = getComputedStyle(document.documentElement);
246
+ expect(rootStyle.getPropertyValue('--su-theme-background')).toBe('#1a1a1a');
247
+ });
248
+ it('should update theme and apply custom variables for the specified theme', () => {
249
+ const customConfig = {
250
+ themes: {
251
+ dark: {
252
+ background: '#000000',
253
+ color: '#ffffff',
254
+ },
255
+ },
256
+ };
257
+ service.init(customConfig);
258
+ service.setTheme('dark');
259
+ const rootStyle = getComputedStyle(document.documentElement);
260
+ expect(service.getTheme()).toBe('dark');
261
+ expect(rootStyle.getPropertyValue('--su-theme-background')).toBe('#000000');
262
+ expect(rootStyle.getPropertyValue('--su-theme-color')).toBe('#ffffff');
263
+ });
264
+ });
265
+ it('should listen and react to system theme changes only when preference is "system"', () => {
266
+ // Initial state: system preference, light mode
267
+ service.init({ defaultTheme: 'system' });
268
+ expect(service.getTheme()).toBe('light');
269
+ // System switches to dark mode
270
+ currentMatches = true;
271
+ matchMediaCallback?.({ matches: true });
272
+ expect(service.getTheme()).toBe('dark');
273
+ // System switches back to light mode
274
+ currentMatches = false;
275
+ matchMediaCallback?.({ matches: false });
276
+ expect(service.getTheme()).toBe('light');
277
+ // User switches to a specific theme, listener should no longer react
278
+ service.setTheme('dark', true);
279
+ expect(service.getUserPreference()).toBe('dark');
280
+ currentMatches = true;
281
+ matchMediaCallback?.({ matches: true });
282
+ expect(service.getTheme()).toBe('dark'); // Theme should not change
283
+ });
284
+ it('should remove event listeners on destroy', () => {
285
+ const removeSpy = vi.fn();
286
+ vi.stubGlobal('matchMedia', () => ({
287
+ matches: false,
288
+ addEventListener: vi.fn(),
289
+ removeEventListener: removeSpy,
290
+ media: '',
291
+ onchange: null,
292
+ dispatchEvent: vi.fn(),
293
+ }));
294
+ service.init({ defaultTheme: 'system' });
295
+ service.ngOnDestroy();
296
+ expect(removeSpy).toHaveBeenCalled();
297
+ });
298
+ });
299
+
300
+ /*
301
+ * Public API Surface of theme
302
+ */
303
+
304
+ /**
305
+ * Generated bundle index. Do not edit.
306
+ */
307
+
308
+ export { SuThemeService };
309
+ //# sourceMappingURL=su-labs-theme.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"su-labs-theme.mjs","sources":["../../../../projects/su-labs/theme/src/lib/theme.service.ts","../../../../projects/su-labs/theme/src/lib/theme.service.spec.ts","../../../../projects/su-labs/theme/src/public-api.ts","../../../../projects/su-labs/theme/src/su-labs-theme.ts"],"sourcesContent":["import { Injectable, signal, WritableSignal, OnDestroy, computed } from '@angular/core';\nimport { SuThemeConfig, SuThemeName, ThemeCssVariables } from './theme.types';\n\n/**\n * Service for managing application themes.\n *\n * Provides reactive theme state via signals and methods to set/get the theme.\n * Supports user preference, system-based themes, and custom CSS variable overrides.\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class SuThemeService implements OnDestroy {\n /** Configuration for the theme, provided during initialization */\n private suThemeConfig: SuThemeConfig = {};\n\n /** CSS variable prefix, can be customized */\n private cssVarPrefix = '--su-theme-';\n\n /** localStorage key for storing user preference, can be customized */\n private storageKey = 'su:theme';\n\n /** User selected theme (can be 'system') */\n private userPreference: SuThemeName = 'light';\n\n /** Current resolved theme signal ('light' | 'dark' | 'contrast' | 'custom') */\n private currentThemeSignal: WritableSignal<SuThemeName> = signal('light');\n\n /** Read-only access to the resolved theme signal */\n readonly theme = this.currentThemeSignal.asReadonly();\n\n /** System media query listener callback */\n private systemChangeHandler: ((event: MediaQueryListEvent) => void) | null = null;\n\n /** MediaQueryList instance for system theme changes */\n private mediaQuery?: MediaQueryList;\n\n /**\n * Initialize the service with optional configuration.\n * Should be called from APP_INITIALIZER for default setup.\n * @param config Optional configuration object.\n */\n public init(config?: SuThemeConfig): void {\n // Apply configuration and defaults\n this.suThemeConfig = { ...this.suThemeConfig, ...config };\n this.cssVarPrefix = this.suThemeConfig.cssVarPrefix ?? this.cssVarPrefix;\n this.storageKey = this.suThemeConfig.storageKey ?? this.storageKey;\n\n // Set user preference from localStorage or default\n this.userPreference = (localStorage.getItem(this.storageKey) as SuThemeName | null) ?? this.suThemeConfig.defaultTheme ?? 'system';\n\n // Set the initial theme based on the resolved preference\n this.setTheme(this.userPreference, false);\n }\n\n /**\n * Get the currently active, resolved theme.\n * @returns The resolved theme name ('light', 'dark', 'contrast', 'custom').\n */\n public getTheme(): SuThemeName {\n return this.currentThemeSignal();\n }\n\n /**\n * Get the user's theme preference (may be 'system').\n * @returns The user preference ('light', 'dark', 'contrast', 'custom', 'system').\n */\n public getUserPreference(): SuThemeName {\n return this.userPreference;\n }\n\n /**\n * Set a new theme.\n * @param theme The theme to set ('light', 'dark', 'contrast', 'custom', 'system').\n * @param persist Whether to store the preference in localStorage (default: true).\n */\n public setTheme(theme: SuThemeName, persist: boolean = true): void {\n // Stop listening to system changes if we are setting a non-system theme\n if (theme !== 'system') {\n this.stopListeningToSystemChanges();\n }\n\n // Resolve the final theme name\n const resolvedTheme: SuThemeName = theme === 'system' ? this.resolveSystemTheme() : theme;\n\n // Update internal state and signals\n this.userPreference = theme;\n this.currentThemeSignal.set(resolvedTheme);\n\n // Apply the theme to the document and manage system listeners\n document.documentElement.setAttribute('data-theme', resolvedTheme);\n this.applyThemeVariables(resolvedTheme);\n\n // Persist preference to localStorage\n if (persist) {\n localStorage.setItem(this.storageKey, theme);\n }\n\n // Start listening for system changes if the new preference is 'system'\n if (theme === 'system') {\n this.listenToSystemChanges();\n }\n }\n\n /**\n * Resolve the current system theme using prefers-color-scheme.\n * @returns 'dark' if system prefers dark mode, otherwise 'light'.\n */\n private resolveSystemTheme(): SuThemeName {\n if (typeof window !== 'undefined' && window.matchMedia('(prefers-color-scheme: dark)').matches) {\n return 'dark';\n }\n return 'light';\n }\n\n /**\n * Listen to system theme changes and automatically update the theme.\n * Only active when user preference is 'system'.\n */\n private listenToSystemChanges(): void {\n // Only set up the listener if it's not already active\n if (!this.mediaQuery) {\n this.mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');\n this.systemChangeHandler = (event: MediaQueryListEvent): void => {\n // Only react if the user preference is still 'system'\n if (this.userPreference === 'system') {\n this.currentThemeSignal.set(event.matches ? 'dark' : 'light');\n document.documentElement.setAttribute('data-theme', this.currentThemeSignal());\n this.applyThemeVariables(this.currentThemeSignal());\n }\n };\n this.mediaQuery.addEventListener('change', this.systemChangeHandler);\n }\n }\n\n /**\n * Stop listening to system theme changes.\n * Should be called when the service is destroyed or theme is no longer 'system'.\n */\n private stopListeningToSystemChanges(): void {\n if (this.mediaQuery && this.systemChangeHandler) {\n this.mediaQuery.removeEventListener('change', this.systemChangeHandler);\n this.systemChangeHandler = null;\n this.mediaQuery = undefined;\n }\n }\n\n /**\n * Apply CSS variables for the given theme.\n * This method applies default variables if they are not overridden in the config.\n * @param theme The theme whose variables should be applied.\n */\n private applyThemeVariables(theme: SuThemeName): void {\n // Map of default variables for light and dark themes\n const defaultThemes: Record<SuThemeName, ThemeCssVariables> = {\n light: {\n color: '#333',\n background: '#fff',\n 'main-accent': '#007bff',\n 'second-accent': '#6c757d',\n 'third-accent': '#28a745',\n },\n dark: {\n color: '#f0f0f0',\n background: '#1a1a1a',\n 'main-accent': '#38a8e1',\n 'second-accent': '#a8b0b5',\n 'third-accent': '#2ee057',\n },\n // You can add more default themes here\n contrast: {\n color: '#000',\n background: '#fff',\n 'main-accent': '#ff0000',\n },\n custom: {},\n system: {},\n };\n\n // Use a combination of default and user-defined variables\n const variablesToApply = {\n ...defaultThemes[theme],\n ...(this.suThemeConfig.themes?.[theme] ?? {}),\n };\n\n // Apply the variables to the root element\n for (const [key, value] of Object.entries(variablesToApply)) {\n if (value) {\n document.documentElement.style.setProperty(\n `${this.cssVarPrefix}${key}`,\n value,\n );\n }\n }\n }\n\n /** Angular lifecycle hook for service destruction */\n ngOnDestroy(): void {\n this.stopListeningToSystemChanges();\n }\n}","import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';\nimport { SuThemeService } from './theme.service';\nimport { SuThemeConfig } from './theme.types';\n\nlet matchMediaCallback: ((e: MediaQueryListEvent) => void) | null = null;\nlet currentMatches = false;\n\nbeforeAll(() => {\n vi.stubGlobal('matchMedia', (query: string) => ({\n matches: currentMatches,\n media: query,\n addEventListener: (_: string, cb: (e: MediaQueryListEvent) => void) => {\n matchMediaCallback = cb;\n },\n removeEventListener: () => {\n matchMediaCallback = null;\n },\n onchange: null,\n dispatchEvent: vi.fn(),\n }));\n});\n\ndescribe('SuThemeService', () => {\n let service: SuThemeService;\n\n beforeEach(() => {\n localStorage.clear();\n currentMatches = false;\n matchMediaCallback = null;\n service = new SuThemeService();\n // Reset the DOM for each test\n document.documentElement.setAttribute('data-theme', '');\n document.documentElement.style.cssText = '';\n });\n\n it('should initialize with default theme \"system\" if no config', () => {\n service.init();\n expect(service.getUserPreference()).toBe('system');\n // The resolved theme can be either 'light' or 'dark' based on the initial `currentMatches`\n expect(['light', 'dark']).toContain(service.getTheme());\n });\n\n it('should apply custom CSS variables from a configuration', () => {\n const customConfig: SuThemeConfig = {\n themes: {\n light: {\n color: 'red',\n background: 'black',\n },\n },\n };\n service.init(customConfig);\n service.setTheme('light');\n\n const rootStyle = getComputedStyle(document.documentElement);\n expect(rootStyle.getPropertyValue('--su-theme-color')).toBe('red');\n expect(rootStyle.getPropertyValue('--su-theme-background')).toBe('black');\n });\n\n it('should save user preference to localStorage', () => {\n service.init();\n service.setTheme('dark');\n expect(localStorage.getItem('su:theme')).toBe('dark');\n });\n\n it('should resolve system theme when preference is \"system\"', () => {\n currentMatches = true; // Simulates dark mode\n service.init({ defaultTheme: 'system' });\n expect(service.getTheme()).toBe('dark');\n expect(service.getUserPreference()).toBe('system');\n });\n\n describe('setTheme method', () => {\n it('should update the theme and apply default variables', () => {\n service.init();\n service.setTheme('dark');\n expect(service.getTheme()).toBe('dark');\n const rootStyle = getComputedStyle(document.documentElement);\n expect(rootStyle.getPropertyValue('--su-theme-background')).toBe('#1a1a1a');\n });\n\n it('should update theme and apply custom variables for the specified theme', () => {\n const customConfig: SuThemeConfig = {\n themes: {\n dark: {\n background: '#000000',\n color: '#ffffff',\n },\n },\n };\n service.init(customConfig);\n service.setTheme('dark');\n\n const rootStyle = getComputedStyle(document.documentElement);\n expect(service.getTheme()).toBe('dark');\n expect(rootStyle.getPropertyValue('--su-theme-background')).toBe('#000000');\n expect(rootStyle.getPropertyValue('--su-theme-color')).toBe('#ffffff');\n });\n });\n\n it('should listen and react to system theme changes only when preference is \"system\"', () => {\n // Initial state: system preference, light mode\n service.init({ defaultTheme: 'system' });\n expect(service.getTheme()).toBe('light');\n\n // System switches to dark mode\n currentMatches = true;\n matchMediaCallback?.({ matches: true } as MediaQueryListEvent);\n expect(service.getTheme()).toBe('dark');\n\n // System switches back to light mode\n currentMatches = false;\n matchMediaCallback?.({ matches: false } as MediaQueryListEvent);\n expect(service.getTheme()).toBe('light');\n\n // User switches to a specific theme, listener should no longer react\n service.setTheme('dark', true);\n expect(service.getUserPreference()).toBe('dark');\n\n currentMatches = true;\n matchMediaCallback?.({ matches: true } as MediaQueryListEvent);\n expect(service.getTheme()).toBe('dark'); // Theme should not change\n });\n\n it('should remove event listeners on destroy', () => {\n const removeSpy = vi.fn();\n vi.stubGlobal('matchMedia', () => ({\n matches: false,\n addEventListener: vi.fn(),\n removeEventListener: removeSpy,\n media: '',\n onchange: null,\n dispatchEvent: vi.fn(),\n }));\n service.init({ defaultTheme: 'system' });\n service.ngOnDestroy();\n expect(removeSpy).toHaveBeenCalled();\n });\n});","/*\n * Public API Surface of theme\n */\n\nexport * from './lib/theme.service';\nexport * from './lib/theme.service.spec';\nexport * from './lib/theme.types';\n\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;AAGA;;;;;AAKG;MAIU,cAAc,CAAA;;IAEjB,aAAa,GAAkB,EAAE;;IAGjC,YAAY,GAAG,aAAa;;IAG5B,UAAU,GAAG,UAAU;;IAGvB,cAAc,GAAgB,OAAO;;AAGrC,IAAA,kBAAkB,GAAgC,MAAM,CAAC,OAAO,8DAAC;;AAGhE,IAAA,KAAK,GAAG,IAAI,CAAC,kBAAkB,CAAC,UAAU,EAAE;;IAG7C,mBAAmB,GAAkD,IAAI;;AAGzE,IAAA,UAAU;AAElB;;;;AAIG;AACI,IAAA,IAAI,CAAC,MAAsB,EAAA;;AAEhC,QAAA,IAAI,CAAC,aAAa,GAAG,EAAE,GAAG,IAAI,CAAC,aAAa,EAAE,GAAG,MAAM,EAAE;AACzD,QAAA,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,aAAa,CAAC,YAAY,IAAI,IAAI,CAAC,YAAY;AACxE,QAAA,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,aAAa,CAAC,UAAU,IAAI,IAAI,CAAC,UAAU;;AAGlE,QAAA,IAAI,CAAC,cAAc,GAAI,YAAY,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAwB,IAAI,IAAI,CAAC,aAAa,CAAC,YAAY,IAAI,QAAQ;;QAGlI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,cAAc,EAAE,KAAK,CAAC;;AAG3C;;;AAGG;IACI,QAAQ,GAAA;AACb,QAAA,OAAO,IAAI,CAAC,kBAAkB,EAAE;;AAGlC;;;AAGG;IACI,iBAAiB,GAAA;QACtB,OAAO,IAAI,CAAC,cAAc;;AAG5B;;;;AAIG;AACI,IAAA,QAAQ,CAAC,KAAkB,EAAE,OAAA,GAAmB,IAAI,EAAA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EAAyB,CAAC;AAC9D,QAAA,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC1C,KAAC,CAAC;AAEF,IAAA,EAAE,CAAC,0CAA0C,EAAE,MAAK;AAClD,QAAA,MAAM,SAAS,GAAG,EAAE,CAAC,EAAE,EAAE;QACzB,EAAE,CAAC,UAAU,CAAC,YAAY,EAAE,OAAO;AACjC,YAAA,OAAO,EAAE,KAAK;AACd,YAAA,gBAAgB,EAAE,EAAE,CAAC,EAAE,EAAE;AACzB,YAAA,mBAAmB,EAAE,SAAS;AAC9B,YAAA,KAAK,EAAE,EAAE;AACT,YAAA,QAAQ,EAAE,IAAI;AACd,YAAA,aAAa,EAAE,EAAE,CAAC,EAAE,EAAE;AACvB,SAAA,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,CAAC,EAAE,YAAY,EAAE,QAAQ,EAAE,CAAC;QACxC,OAAO,CAAC,WAAW,EAAE;AACrB,QAAA,MAAM,CAAC,SAAS,CAAC,CAAC,gBAAgB,EAAE;AACtC,KAAC,CAAC;AACJ,CAAC,CAAC;;AC1IF;;AAEG;;ACFH;;AAEG;;;;"}
package/index.d.ts ADDED
@@ -0,0 +1,100 @@
1
+ import * as i0 from '@angular/core';
2
+ import { OnDestroy } from '@angular/core';
3
+
4
+ /** Available theme names */
5
+ type SuThemeName = 'light' | 'dark' | 'contrast' | 'custom' | 'system';
6
+ /** Theme configuration */
7
+ interface SuThemeConfig {
8
+ /** localStorage key for storing selected theme */
9
+ storageKey?: string;
10
+ /** CSS variable prefix, applied to all theme variables */
11
+ cssVarPrefix?: string;
12
+ /** Default theme if nothing saved in localStorage */
13
+ defaultTheme?: SuThemeName;
14
+ /** Optional CSS variable overrides for specific themes */
15
+ themes?: Partial<Record<SuThemeName, ThemeCssVariables>>;
16
+ }
17
+ /** Available CSS variables for theming */
18
+ interface ThemeCssVariables {
19
+ color?: string;
20
+ background?: string;
21
+ 'main-accent'?: string;
22
+ 'second-accent'?: string;
23
+ 'third-accent'?: string;
24
+ [key: string]: string | undefined;
25
+ }
26
+
27
+ /**
28
+ * Service for managing application themes.
29
+ *
30
+ * Provides reactive theme state via signals and methods to set/get the theme.
31
+ * Supports user preference, system-based themes, and custom CSS variable overrides.
32
+ */
33
+ declare class SuThemeService implements OnDestroy {
34
+ /** Configuration for the theme, provided during initialization */
35
+ private suThemeConfig;
36
+ /** CSS variable prefix, can be customized */
37
+ private cssVarPrefix;
38
+ /** localStorage key for storing user preference, can be customized */
39
+ private storageKey;
40
+ /** User selected theme (can be 'system') */
41
+ private userPreference;
42
+ /** Current resolved theme signal ('light' | 'dark' | 'contrast' | 'custom') */
43
+ private currentThemeSignal;
44
+ /** Read-only access to the resolved theme signal */
45
+ readonly theme: i0.Signal<SuThemeName>;
46
+ /** System media query listener callback */
47
+ private systemChangeHandler;
48
+ /** MediaQueryList instance for system theme changes */
49
+ private mediaQuery?;
50
+ /**
51
+ * Initialize the service with optional configuration.
52
+ * Should be called from APP_INITIALIZER for default setup.
53
+ * @param config Optional configuration object.
54
+ */
55
+ init(config?: SuThemeConfig): void;
56
+ /**
57
+ * Get the currently active, resolved theme.
58
+ * @returns The resolved theme name ('light', 'dark', 'contrast', 'custom').
59
+ */
60
+ getTheme(): SuThemeName;
61
+ /**
62
+ * Get the user's theme preference (may be 'system').
63
+ * @returns The user preference ('light', 'dark', 'contrast', 'custom', 'system').
64
+ */
65
+ getUserPreference(): SuThemeName;
66
+ /**
67
+ * Set a new theme.
68
+ * @param theme The theme to set ('light', 'dark', 'contrast', 'custom', 'system').
69
+ * @param persist Whether to store the preference in localStorage (default: true).
70
+ */
71
+ setTheme(theme: SuThemeName, persist?: boolean): void;
72
+ /**
73
+ * Resolve the current system theme using prefers-color-scheme.
74
+ * @returns 'dark' if system prefers dark mode, otherwise 'light'.
75
+ */
76
+ private resolveSystemTheme;
77
+ /**
78
+ * Listen to system theme changes and automatically update the theme.
79
+ * Only active when user preference is 'system'.
80
+ */
81
+ private listenToSystemChanges;
82
+ /**
83
+ * Stop listening to system theme changes.
84
+ * Should be called when the service is destroyed or theme is no longer 'system'.
85
+ */
86
+ private stopListeningToSystemChanges;
87
+ /**
88
+ * Apply CSS variables for the given theme.
89
+ * This method applies default variables if they are not overridden in the config.
90
+ * @param theme The theme whose variables should be applied.
91
+ */
92
+ private applyThemeVariables;
93
+ /** Angular lifecycle hook for service destruction */
94
+ ngOnDestroy(): void;
95
+ static ɵfac: i0.ɵɵFactoryDeclaration<SuThemeService, never>;
96
+ static ɵprov: i0.ɵɵInjectableDeclaration<SuThemeService>;
97
+ }
98
+
99
+ export { SuThemeService };
100
+ export type { SuThemeConfig, SuThemeName, ThemeCssVariables };
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@su-labs/theme",
3
+ "version": "1.0.0",
4
+ "peerDependencies": {
5
+ "@angular/common": "^20.1.0",
6
+ "@angular/core": "^20.1.0"
7
+ },
8
+ "dependencies": {
9
+ "tslib": "^2.3.0"
10
+ },
11
+ "sideEffects": false,
12
+ "module": "fesm2022/su-labs-theme.mjs",
13
+ "typings": "index.d.ts",
14
+ "exports": {
15
+ "./package.json": {
16
+ "default": "./package.json"
17
+ },
18
+ ".": {
19
+ "types": "./index.d.ts",
20
+ "default": "./fesm2022/su-labs-theme.mjs"
21
+ }
22
+ }
23
+ }