mancala/frontend/src/theme/ThemeManager.ts

51 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-07-13 15:40:54 +03:00
import lightTheme from "./LightTheme";
import greyTheme from "./GreyTheme";
2022-05-15 01:58:57 +03:00
import { Theme } from "./Theme";
2022-07-13 15:40:54 +03:00
import darkTheme from "./DarkTheme";
2022-09-02 00:01:09 +03:00
import EventEmitter2, { Listener } from "eventemitter2";
2022-05-15 01:58:57 +03:00
2022-07-13 15:40:54 +03:00
export const themes = [lightTheme, darkTheme, greyTheme];
2022-06-04 19:28:57 +03:00
const THEME_ID = "theme_id";
2022-09-02 00:01:09 +03:00
export type ThemeManagerEvents = "themechange";
export default class ThemeManager extends EventEmitter2 {
private _theme: Theme;
2022-06-04 19:28:57 +03:00
constructor() {
2022-09-02 00:01:09 +03:00
super();
2022-07-13 15:40:54 +03:00
this._theme = this.readFromLocalStorage() || lightTheme;
2022-05-15 01:58:57 +03:00
}
public get theme() {
return this._theme;
}
2022-06-04 19:28:57 +03:00
public set theme(value: Theme) {
2022-05-15 01:58:57 +03:00
this._theme = value;
2022-09-02 00:01:09 +03:00
this.emit("themechange", value);
2022-06-04 19:28:57 +03:00
this.writetToLocalStorage(value);
}
private writetToLocalStorage(value: Theme) {
localStorage.setItem(THEME_ID, value.id);
}
2022-09-02 00:01:09 +03:00
private readFromLocalStorage(): Theme | undefined {
2022-06-04 19:28:57 +03:00
const themeID = localStorage.getItem(THEME_ID);
const theme = themes.find((eachTheme: Theme) => themeID === eachTheme.id);
return theme;
}
public get themes(): Theme[] {
return themes;
2022-05-15 01:58:57 +03:00
}
2022-09-02 00:01:09 +03:00
public on(event: ThemeManagerEvents, callback: (...value: any[]) => void): Listener | this {
return super.on(event, callback);
}
public off(event: ThemeManagerEvents, callback: (...value: any[]) => void): this {
return super.off(event, callback);
}
2022-05-15 01:58:57 +03:00
}