From 080a8e19dee6ac53ae12bf82339789d8d5a0e41e Mon Sep 17 00:00:00 2001 From: Mohammed Abad Date: Fri, 5 Apr 2024 02:42:47 +0000 Subject: [PATCH] add default theme selection based on system prefrence --- .../src/app/core/services/theme.service.ts | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/frontend/src/app/core/services/theme.service.ts b/frontend/src/app/core/services/theme.service.ts index c8028e6..294a4a5 100644 --- a/frontend/src/app/core/services/theme.service.ts +++ b/frontend/src/app/core/services/theme.service.ts @@ -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'; } }