Skip to content

Commit 4543d6a

Browse files
Refactor theme management logic for clarity and efficiency
1 parent 730a0bc commit 4543d6a

1 file changed

Lines changed: 17 additions & 11 deletions

File tree

resources/js/dashboard/composables/useAppearance.ts

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,25 @@ import { onMounted, ref } from 'vue';
22

33
type Appearance = 'light' | 'dark' | 'system';
44

5+
const getCurrentTheme = (): Appearance => {
6+
return document.documentElement.classList.contains('dark') ? 'dark' : 'light';
7+
};
8+
59
export function updateTheme(value: Appearance) {
610
if (typeof window === 'undefined') {
711
return;
812
}
913

10-
const toggleMode = () => {
11-
if (value === 'system') {
12-
const systemTheme = mediaQuery()?.matches ? 'dark' : 'light';
14+
const systemTheme = mediaQuery()?.matches ? 'dark' : 'light';
15+
const desiredTheme = value === 'system' ? systemTheme : value;
16+
const currentTheme = getCurrentTheme();
1317

14-
document.documentElement.classList.toggle('dark', systemTheme === 'dark');
15-
} else {
16-
document.documentElement.classList.toggle('dark', value === 'dark');
17-
}
18+
if (currentTheme === desiredTheme) {
19+
return;
20+
}
21+
22+
const toggleMode = () => {
23+
document.documentElement.classList.toggle('dark', desiredTheme === 'dark');
1824
};
1925

2026
if (typeof document.startViewTransition === 'function') {
@@ -46,7 +52,7 @@ const handleSystemThemeChange = () => {
4652
updateTheme(currentAppearance || 'system');
4753
};
4854

49-
export function initializeTheme() {
55+
export const initializeTheme = () => {
5056
if (typeof window === 'undefined') {
5157
return;
5258
}
@@ -55,7 +61,7 @@ export function initializeTheme() {
5561
updateTheme(savedAppearance || 'system');
5662

5763
mediaQuery()?.addEventListener('change', handleSystemThemeChange);
58-
}
64+
};
5965

6066
export function useAppearance() {
6167
const appearance = ref<Appearance>('system');
@@ -70,13 +76,13 @@ export function useAppearance() {
7076
}
7177
});
7278

73-
function updateAppearance(value: Appearance) {
79+
const updateAppearance = (value: Appearance) => {
7480
appearance.value = value;
7581

7682
localStorage.setItem('appearance', value);
7783

7884
updateTheme(value);
79-
}
85+
};
8086

8187
return {
8288
appearance,

0 commit comments

Comments
 (0)