add default theme selection based on system prefrence

This commit is contained in:
X4Lo committed 2024-04-05 02:42:47 +00:00
1 parent 5e6be9892b
commit 080a8e19de
1 file changed
+18 -4
@@ -7,7 +7,7 @@ export class ThemeService {
private theme: 'light' | 'dark' = 'light';
constructor() {
this.loadTheme(); // Load the theme when the service is initialized
this.loadTheme();
}
toggleTheme(): void {
@@ -16,13 +16,27 @@ export class ThemeService {
}
private loadTheme(): void {
// Load theme from localStorage or default to 'light'
this.theme = (localStorage.getItem('theme') as 'light' | 'dark') || 'light';
if (!localStorage.getItem('theme')) {
this.theme = this.getSystemTheme();
} else {
this.theme =
(localStorage.getItem('theme') as 'light' | 'dark') || 'light';
}
this.applyTheme();
}
private applyTheme(): void {
document.documentElement.setAttribute('data-bs-theme', this.theme);
localStorage.setItem('theme', this.theme); // Save theme to localStorage
localStorage.setItem('theme', this.theme);
}
private getSystemTheme() {
if (
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches
)
return 'dark';
return 'light';
}
}