-
Notifications
You must be signed in to change notification settings - Fork 0
/
theme-manager.service.ts
75 lines (59 loc) · 2.19 KB
/
theme-manager.service.ts
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
import { DOCUMENT } from '@angular/common';
import { Inject, Injectable } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { filter, map } from 'rxjs/operators';
const availableThemes = [
{ id: 'default', name: 'Lignt DeepPurple & Amber' },
{ id: 'dark-pink-bluegrey', name: 'Dark Pink & BlueGrey' },
];
@Injectable({
providedIn: 'root'
})
export class ThemeManagerService {
public static LOCAL_STORAGE_KEY = 'data-theme';
public static CSS_ATTRIBUTE_KEY = 'data-theme';
public static URL_PARAM_KEY = 'hreftheme';
constructor(
private route: ActivatedRoute,
@Inject(DOCUMENT) private document: Document,
) {
this.restoreTheme();
this.route.queryParamMap
.pipe(
map(paramMap => paramMap.get(ThemeManagerService.URL_PARAM_KEY)),
filter(theme => this.isSupportedTheme(theme)),
).subscribe(theme => this.setActiveTheme(`${theme}`));
}
public getSupportedTheme(): { id: string, name: string }[] {
return availableThemes;
}
public setActiveTheme(theme: string): void {
const isSupported = this.isSupportedTheme(theme);
if (!isSupported) {
// TODO: UPDATE_ME (Good to show some error)
console.warn(`Theme not supported : ${theme}`);
return;
}
this.changeTheme(theme);
}
private isSupportedTheme(theme: string | null): boolean {
if (!theme) { return false; }
return !!availableThemes
.find(({ id }) => id === theme);
}
private changeTheme(theme: string): void {
this.persistTheme(theme);
this.reflectTheme(theme);
}
private persistTheme(theme: string): void {
localStorage.setItem(ThemeManagerService.LOCAL_STORAGE_KEY, theme);
}
private reflectTheme(theme: string): void {
this.document.body.setAttribute(ThemeManagerService.CSS_ATTRIBUTE_KEY, theme);
}
private restoreTheme(): void {
const theme = localStorage.getItem(ThemeManagerService.LOCAL_STORAGE_KEY);
const isSupported = this.isSupportedTheme(theme);
if (isSupported) { this.reflectTheme(`${theme}`); }
}
}