forked from devsecopsmaturitymodel/DevSecOps-MaturityModel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeme.service.ts
More file actions
42 lines (32 loc) · 1.15 KB
/
theme.service.ts
File metadata and controls
42 lines (32 loc) · 1.15 KB
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
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
export type AppTheme = 'light' | 'dark';
@Injectable({ providedIn: 'root' })
export class ThemeService {
private readonly STORAGE_KEY = 'theme';
private readonly defaultTheme: AppTheme = 'light';
private themeSubject = new BehaviorSubject<AppTheme>(this.defaultTheme);
public readonly theme$ = this.themeSubject.asObservable();
constructor() {}
initTheme(): void {
const stored = localStorage.getItem(this.STORAGE_KEY);
const theme: AppTheme = stored === 'dark' ? 'dark' : this.defaultTheme;
this.setTheme(theme);
}
setTheme(theme: AppTheme): void {
if (this.themeSubject.value === theme) return;
this.applyTheme(theme);
}
private applyTheme(theme: AppTheme): void {
document.body.classList.remove('light-theme', 'dark-theme');
document.body.classList.add(`${theme}-theme`);
localStorage.setItem(this.STORAGE_KEY, theme);
this.themeSubject.next(theme);
}
getTheme(): AppTheme {
return this.themeSubject.value;
}
toggleTheme(): void {
this.setTheme(this.themeSubject.value === 'light' ? 'dark' : 'light');
}
}