All files / app/services theme.service.ts

83.05% Statements 49/59
58.13% Branches 25/43
90.9% Functions 10/11
86.79% Lines 46/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170          1x                                                                 17x 17x 17x     17x     17x   17x     16x   16x     16x               16x 1x 1x 1x       16x                 22x               3x   3x   1x   2x               6x 6x 6x 6x 6x       32x       32x 32x       32x       1x 1x         17x       17x 16x   16x   1x 1x     17x 17x       17x     17x 17x                 16x   16x 16x 16x          
import { Injectable, signal, effect, PLATFORM_ID, inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { Theme } from '../types';
 
 
const THEME_STORAGE_KEY = 'nimmit-theme';
 
/**
 * Theme Service für Dark/Light Mode Management
 *
 * Verwendung:
 *
 * ```typescript
 * // In einer Component
 * export class MyComponent {
 *   private themeService = inject(ThemeService);
 *
 *   // Aktuelles Theme lesen
 *   currentTheme = this.themeService.theme;
 *
 *   // Ob Dark Mode aktiv ist
 *   isDark = this.themeService.isDarkMode;
 *
 *   // Theme wechseln
 *   toggleTheme() {
 *     this.themeService.toggleTheme();
 *   }
 *
 *   // Bestimmtes Theme setzen
 *   setDark() {
 *     this.themeService.setTheme('dark');
 *   }
 * }
 * ```
 */
@Injectable({
  providedIn: 'root',
})
export class ThemeService {
  private readonly platformId = inject(PLATFORM_ID);
  private readonly isBrowser = isPlatformBrowser(this.platformId);
 
  /** Aktuelles Theme ('light', 'dark', oder 'system') */
  readonly theme = signal<Theme>(this.getInitialTheme());
 
  /** Ob aktuell Dark Mode aktiv ist (auch bei 'system' Theme) */
  readonly isDarkMode = signal(this.checkIsDarkMode());
 
  private mediaQuery: MediaQueryList | null = null;
 
  constructor() {
    Eif (this.isBrowser) {
      // Media Query für System-Präferenz
      this.mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
 
      // Listener für System-Präferenz-Änderungen
      this.mediaQuery.addEventListener('change', (e) => {
        if (this.theme() === 'system') {
          this.applyTheme(e.matches ? 'dark' : 'light');
          this.isDarkMode.set(e.matches);
        }
      });
 
      // Effect um Theme-Änderungen zu verarbeiten
      effect(() => {
        const theme = this.theme();
        this.saveTheme(theme);
        this.updateTheme(theme);
      });
 
      // Initial Theme anwenden
      this.updateTheme(this.theme());
    }
  }
 
  /**
   * Setzt das Theme
   * @param theme 'light', 'dark', oder 'system'
   */
  setTheme(theme: Theme): void {
    this.theme.set(theme);
  }
 
  /**
   * Wechselt zwischen Light und Dark Mode
   * (System wird zu Light wenn aktuell dunkel, sonst zu Dark)
   */
  toggleTheme(): void {
    const current = this.theme();
 
    if (current === 'system') {
      // Bei System: Wechsel zu entgegengesetztem Modus
      this.setTheme(this.isDarkMode() ? 'light' : 'dark');
    } else {
      this.setTheme(current === 'dark' ? 'light' : 'dark');
    }
  }
 
  /**
   * Zykliert durch alle Themes: light -> dark -> system -> light
   */
  cycleTheme(): void {
    const current = this.theme();
    const themes: Theme[] = ['light', 'dark', 'system'];
    const currentIndex = themes.indexOf(current);
    const nextIndex = (currentIndex + 1) % themes.length;
    this.setTheme(themes[nextIndex]);
  }
 
  private getInitialTheme(): Theme {
    Iif (!this.isBrowser) {
      return 'system';
    }
 
    const stored = localStorage.getItem(THEME_STORAGE_KEY);
    Iif (stored && ['light', 'dark', 'system'].includes(stored)) {
      return stored as Theme;
    }
 
    return 'system';
  }
 
  private saveTheme(theme: Theme): void {
    Eif (this.isBrowser) {
      localStorage.setItem(THEME_STORAGE_KEY, theme);
    }
  }
 
  private updateTheme(theme: Theme): void {
    Iif (!this.isBrowser) return;
 
    let effectiveTheme: 'light' | 'dark';
 
    if (theme === 'system') {
      effectiveTheme = this.mediaQuery?.matches ? 'dark' : 'light';
      // Entferne data-theme um System-Präferenz zu nutzen
      document.documentElement.removeAttribute('data-theme');
    } else {
      effectiveTheme = theme;
      document.documentElement.setAttribute('data-theme', theme);
    }
 
    this.isDarkMode.set(effectiveTheme === 'dark');
    this.applyTheme(effectiveTheme);
  }
 
  private applyTheme(theme: 'light' | 'dark'): void {
    Iif (!this.isBrowser) return;
 
    // Für iOS/Safari: meta theme-color anpassen
    const metaThemeColor = document.querySelector('meta[name="theme-color"]');
    Iif (metaThemeColor) {
      metaThemeColor.setAttribute(
        'content',
        theme === 'dark' ? '#121212' : '#ffffff'
      );
    }
  }
 
  private checkIsDarkMode(): boolean {
    Iif (!this.isBrowser) return false;
 
    const theme = this.getInitialTheme();
    Eif (theme === 'system') {
      return window.matchMedia('(prefers-color-scheme: dark)').matches;
    }
    return theme === 'dark';
  }
}