75 lines
2.2 KiB
TypeScript
75 lines
2.2 KiB
TypeScript
import { DomTools } from './domtools.classes.domtools.js';
|
|
import * as plugins from './domtools.plugins.js';
|
|
|
|
export class ThemeManager {
|
|
public domtoolsRef: DomTools;
|
|
|
|
public goBrightBoolean = false;
|
|
public preferredColorSchemeMediaMatch = window.matchMedia('(prefers-color-scheme: light)');
|
|
|
|
public themeObservable = new plugins.smartrx.rxjs.ReplaySubject<boolean>(1);
|
|
private automaticGlobalThemeChangeSubscription: plugins.smartrx.rxjs.Subscription | null = null;
|
|
private readonly preferredColorSchemeChangeHandler = (eventArg: MediaQueryListEvent) => {
|
|
this.goBrightBoolean = eventArg.matches;
|
|
this.updateAllConnectedElements();
|
|
};
|
|
|
|
constructor(domtoolsRefArg: DomTools) {
|
|
this.domtoolsRef = domtoolsRefArg;
|
|
|
|
// lets care
|
|
this.goBrightBoolean = this.preferredColorSchemeMediaMatch.matches;
|
|
this.preferredColorSchemeMediaMatch.addEventListener('change', this.preferredColorSchemeChangeHandler);
|
|
this.updateAllConnectedElements();
|
|
}
|
|
|
|
public async enableAutomaticGlobalThemeChange() {
|
|
await this.domtoolsRef.domReady.promise;
|
|
if (!this.automaticGlobalThemeChangeSubscription) {
|
|
this.automaticGlobalThemeChangeSubscription = this.themeObservable.subscribe({
|
|
next: (goBright) => {
|
|
document.body.style.background = goBright ? '#fff' : '#000';
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|
|
private updateAllConnectedElements() {
|
|
if (this.domtoolsRef.disposed) {
|
|
return;
|
|
}
|
|
this.themeObservable.next(this.goBrightBoolean);
|
|
}
|
|
|
|
/**
|
|
* set the theme of the website to bright
|
|
*/
|
|
public goBright() {
|
|
this.goBrightBoolean = true;
|
|
this.updateAllConnectedElements();
|
|
}
|
|
|
|
/**
|
|
* set the theme of the website to dark
|
|
*/
|
|
public goDark() {
|
|
this.goBrightBoolean = false;
|
|
this.updateAllConnectedElements();
|
|
}
|
|
|
|
/**
|
|
* simply toggle between bright and dark
|
|
*/
|
|
public toggleDarkBright() {
|
|
this.goBrightBoolean = !this.goBrightBoolean;
|
|
this.updateAllConnectedElements();
|
|
}
|
|
|
|
public dispose() {
|
|
this.preferredColorSchemeMediaMatch.removeEventListener('change', this.preferredColorSchemeChangeHandler);
|
|
this.automaticGlobalThemeChangeSubscription?.unsubscribe();
|
|
this.automaticGlobalThemeChangeSubscription = null;
|
|
this.themeObservable.complete();
|
|
}
|
|
}
|