Skip to content

Commit

Permalink
Update demo theme localstorage key to avoid conflicts
Browse files Browse the repository at this point in the history
  • Loading branch information
jfcere committed Feb 4, 2023
1 parent 7f28a1b commit ffd8a4c
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 5 deletions.
21 changes: 16 additions & 5 deletions demo/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand All @@ -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;
Expand Down Expand Up @@ -53,22 +55,27 @@ 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);
if (removeClassList) {
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 {
Expand All @@ -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,
);
}
}
4 changes: 4 additions & 0 deletions demo/src/app/app.constant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { Theme } from './app.models';

export const DEFAULT_THEME = Theme.Light;
export const LOCAL_STORAGE_THEME_KEY = 'ngx-markdown:theme';
10 changes: 10 additions & 0 deletions demo/src/app/app.models.ts
Original file line number Diff line number Diff line change
@@ -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);
}

0 comments on commit ffd8a4c

Please sign in to comment.