diff --git a/demo/src/app/app.component.ts b/demo/src/app/app.component.ts index 764c700..8daa238 100644 --- a/demo/src/app/app.component.ts +++ b/demo/src/app/app.component.ts @@ -4,6 +4,8 @@ import { Route, Router, RouterOutlet } from '@angular/router'; import { AnchorService } from '@shared/anchor/anchor.service'; import { ROUTE_ANIMATION } from './app.animation'; +import { DEFAULT_THEME, LOCAL_STORAGE_THEME_KEY } from './app.constant'; +import { isTheme, Theme } from './app.models'; @Component({ animations: [ROUTE_ANIMATION], @@ -17,7 +19,7 @@ export class AppComponent implements OnInit { private readonly stickyClassName = 'mat-tab-nav-bar--sticky'; routes: Route[]; - theme = 'light'; + theme = DEFAULT_THEME; @ViewChild('tabHeader', { read: ElementRef, static: true }) tabHeader: ElementRef | undefined; @@ -53,14 +55,19 @@ export class AppComponent implements OnInit { } ngOnInit(): void { - this.setTheme(localStorage.getItem('theme') || 'light'); + const storedTheme = localStorage.getItem(LOCAL_STORAGE_THEME_KEY); + this.setTheme( + isTheme(storedTheme) + ? storedTheme + : DEFAULT_THEME, + ); } handleFragment(): void { this.anchorService.scrollToAnchor(); } - setTheme(theme: string): void { + setTheme(theme: Theme): void { this.theme = theme; const bodyClassList = this.document.querySelector('body')!.classList; const removeClassList = /\w*-theme\b/.exec(bodyClassList.value); @@ -68,7 +75,7 @@ export class AppComponent implements OnInit { bodyClassList.remove(...removeClassList); } bodyClassList.add(`${this.theme}-theme`); - localStorage.setItem('theme', this.theme); + localStorage.setItem(LOCAL_STORAGE_THEME_KEY, this.theme); } getRouteAnimation(outlet: RouterOutlet): string { @@ -78,6 +85,10 @@ export class AppComponent implements OnInit { } toggleTheme(): void { - this.setTheme(this.theme === 'light' ? 'dark' : 'light'); + this.setTheme( + this.theme === Theme.Light + ? Theme.Dark + : Theme.Light, + ); } } diff --git a/demo/src/app/app.constant.ts b/demo/src/app/app.constant.ts new file mode 100644 index 0000000..eb2d9f2 --- /dev/null +++ b/demo/src/app/app.constant.ts @@ -0,0 +1,4 @@ +import { Theme } from './app.models'; + +export const DEFAULT_THEME = Theme.Light; +export const LOCAL_STORAGE_THEME_KEY = 'ngx-markdown:theme'; diff --git a/demo/src/app/app.models.ts b/demo/src/app/app.models.ts new file mode 100644 index 0000000..5faeb64 --- /dev/null +++ b/demo/src/app/app.models.ts @@ -0,0 +1,10 @@ +export enum Theme { + Light = 'light', + Dark = 'dark', +} + +export function isTheme(value: unknown): value is Theme { + return value != null + && typeof value === 'string' + && Object.values(Theme).includes(value as Theme); +}