| 1 |
import { ref, computed } from 'vue' |
| 2 |
import { useCookies } from '@vueuse/integrations/useCookies' |
| 3 |
import { eventBus } from '@/utils/eventBus' |
| 4 |
import type { ThemeType } from '@/types/theme' |
| 5 |
|
| 6 |
// Create a singleton theme state that can be shared across all components |
| 7 |
const themeState = ref<ThemeType>('light') |
| 8 |
const cookies = useCookies(['ivyforms_theme']) |
| 9 |
|
| 10 |
// Initialize the theme from cookies |
| 11 |
const savedTheme = cookies.get('ivyforms_theme') |
| 12 |
if (savedTheme && (savedTheme === 'light' || savedTheme === 'dark')) { |
| 13 |
themeState.value = savedTheme |
| 14 |
} |
| 15 |
|
| 16 |
// Function to set the theme and broadcast the change |
| 17 |
const setTheme = (value: ThemeType) => { |
| 18 |
themeState.value = value |
| 19 |
cookies.set('ivyforms_theme', value) |
| 20 |
|
| 21 |
// Update body classes for theme styling |
| 22 |
if (value === 'dark') { |
| 23 |
document.body.classList.add('ivyforms-theme-dark') |
| 24 |
} else { |
| 25 |
document.body.classList.remove('ivyforms-theme-dark') |
| 26 |
} |
| 27 |
|
| 28 |
// Broadcast theme change |
| 29 |
eventBus.emit('theme-changed', value) |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* Composable function that provides access to the current theme state |
| 34 |
* and helper functions for theme management |
| 35 |
*/ |
| 36 |
export function useTheme() { |
| 37 |
// Create a computed ref for v-model compatibility |
| 38 |
const theme = computed({ |
| 39 |
get: () => themeState.value, |
| 40 |
set: (value) => setTheme(value), |
| 41 |
}) |
| 42 |
|
| 43 |
return { |
| 44 |
// Raw ref - can be used with v-model |
| 45 |
theme, |
| 46 |
// Helper functions for checking theme |
| 47 |
isDark: () => themeState.value === 'dark', |
| 48 |
isLight: () => themeState.value === 'light', |
| 49 |
// Function to explicitly set the theme |
| 50 |
setTheme, |
| 51 |
getTheme: () => themeState.value, |
| 52 |
} |
| 53 |
} |
| 54 |
|