import {
Component,
Input,
Output,
EventEmitter,
ChangeDetectionStrategy,
ChangeDetectorRef,
inject,
OnInit,
PLATFORM_ID,
} from '@angular/core';
import { CommonModule, isPlatformBrowser } from '@angular/common';
@Component({
selector: 'mayvio-theme-toggle',
standalone: true,
imports: [CommonModule],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
`,
})
export class ThemeToggleComponent implements OnInit {
private cdr = inject(ChangeDetectorRef);
private platformId = inject(PLATFORM_ID);
@Input() className = '';
private _theme?: 'light' | 'dark';
@Input()
set theme(value: 'light' | 'dark' | undefined) {
this._theme = value;
this.cdr.markForCheck();
}
get theme(): 'light' | 'dark' | undefined {
return this._theme;
}
@Output() themeToggled = new EventEmitter();
private internalTheme: 'light' | 'dark' = 'light';
get isDark(): boolean {
return (this.theme || this.internalTheme) === 'dark';
}
ngOnInit() {
if (this.theme === undefined && isPlatformBrowser(this.platformId)) {
const isDark = document.documentElement.classList.contains('dark');
this.internalTheme = isDark ? 'dark' : 'light';
this.cdr.markForCheck();
}
}
toggleTheme() {
if (this.themeToggled.observed) {
this.themeToggled.emit();
} else {
if (isPlatformBrowser(this.platformId)) {
const root = document.documentElement;
if (root.classList.contains('dark')) {
root.classList.remove('dark');
this.internalTheme = 'light';
} else {
root.classList.add('dark');
this.internalTheme = 'dark';
}
this.cdr.markForCheck();
}
}
}
}