angular/devtools/projects/ng-devtools/src/lib/theme-service.ts
AleksanderBodurri 2a1ff17b42 refactor(devtools): run tslint --fix on devtools codebase
This commit runs tslint --fix with the angular/angular tslint configuration on the files inside the devtools codebase.

Notably, the file-header rule in `tslint.json` was missing a default attribute. This commit adds that default attribute and sets it to the
license header that is present in all files in this repo. After running tslint --fix with this default added, this commit added the license header to all files in the devtools directory. Note for the reviewer: the automatically added license headers were added as comments with the "/*!" prefix. Since we want these comments removed in builds, and the rest of the codebase uses "/**", a simple find and replace was performed on the devtools directory to change these prefixes to "/**".
2022-01-26 16:35:31 -05:00

43 lines
1.3 KiB
TypeScript

/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injectable, Renderer2, RendererFactory2} from '@angular/core';
import {ReplaySubject, Subject} from 'rxjs';
export type Theme = 'dark-theme'|'light-theme';
@Injectable({
providedIn: 'root',
})
export class ThemeService {
private renderer: Renderer2;
currentTheme: Subject<Theme> = new ReplaySubject();
constructor(private _rendererFactory: RendererFactory2) {
this.renderer = this._rendererFactory.createRenderer(null, null);
this.toggleDarkMode(this._prefersDarkMode);
}
toggleDarkMode(isDark: boolean): void {
const removeClass = isDark ? 'light-theme' : 'dark-theme';
const addClass = !isDark ? 'light-theme' : 'dark-theme';
this.renderer.removeClass(document.body, removeClass);
this.renderer.addClass(document.body, addClass);
this.currentTheme.next(addClass);
}
initializeThemeWatcher(): void {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
this.toggleDarkMode(this._prefersDarkMode);
});
}
private get _prefersDarkMode(): boolean {
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
}
}