|
| 1 | +import { isPlatformBrowser } from '@angular/common'; |
| 2 | +import { inject, Injectable, PLATFORM_ID } from '@angular/core'; |
| 3 | +import { signalStore, withMethods, withState } from '@ngrx/signals'; |
| 4 | + |
| 5 | +type Theme = 'dark' | 'light'; |
| 6 | + |
| 7 | +interface AppThemeStore { |
| 8 | + theme: Theme; |
| 9 | +} |
| 10 | + |
| 11 | +export const AppThemeStore = signalStore( |
| 12 | + { providedIn: 'root' }, |
| 13 | + withState<AppThemeStore>({ theme: 'light' }), |
| 14 | + withMethods( |
| 15 | + ( |
| 16 | + store, |
| 17 | + platformId = inject(PLATFORM_ID), |
| 18 | + ccConsumer = inject(CCAppThemeConsumer), |
| 19 | + ) => ({ |
| 20 | + syncWithSystemTheme: () => { |
| 21 | + if (isPlatformBrowser(platformId)) { |
| 22 | + ccConsumer.setThemeClass(getSystemTheme()); |
| 23 | + } |
| 24 | + }, |
| 25 | + }), |
| 26 | + ), |
| 27 | +); |
| 28 | + |
| 29 | +function getSystemTheme(): Theme { |
| 30 | + return window.matchMedia('(prefers-color-scheme: dark)').matches |
| 31 | + ? 'dark' |
| 32 | + : 'light'; |
| 33 | +} |
| 34 | + |
| 35 | +/* todo: create consumer interface and decouple AppThemeStore from CCAppThemeConsumer*/ |
| 36 | +@Injectable({ providedIn: 'root' }) |
| 37 | +export class CCAppThemeConsumer { |
| 38 | + setThemeClass(theme: Theme): void { |
| 39 | + const htmlElement = document.documentElement; |
| 40 | + switch (theme) { |
| 41 | + case 'dark': |
| 42 | + htmlElement.classList.add('cc--darkmode'); |
| 43 | + break; |
| 44 | + case 'light': |
| 45 | + htmlElement.classList.remove('cc--darkmode'); |
| 46 | + break; |
| 47 | + } |
| 48 | + } |
| 49 | +} |
0 commit comments