useTheme.uts 2.22 KB
// composables/useTheme.uts
// 主题 Composable - 提供响应式主题变量和切换接口

import { ref, computed, onMounted } from 'vue'
import { getThemeManager, ThemeName, ThemeVariables } from '@/utils/theme-manager.uts'
import { getScreenSize } from '@/utils/screen-adapt.uts'

/**
 * 主题 Composable
 * 类似 i18n 的使用方式,提供主题变量和切换接口
 */
export function useTheme() {
	const themeManager = getThemeManager()
	const currentThemeName = ref<ThemeName>(themeManager.getCurrentThemeName())
	const theme = ref<ThemeVariables | null>(themeManager.getCurrentTheme())
	
	/**
	 * 设置主题
	 */
	function setTheme(themeName: ThemeName): boolean {
		const success = themeManager.setTheme(themeName)
		if (success) {
			currentThemeName.value = themeName
			theme.value = themeManager.getCurrentTheme()
		}
		return success
	}
	
	/**
	 * 自动选择主题(根据屏幕尺寸)
	 */
	function autoSelectTheme(): void {
		themeManager.autoSelectTheme()
		currentThemeName.value = themeManager.getCurrentThemeName()
		theme.value = themeManager.getCurrentTheme()
	}
	
	/**
	 * 获取间距值
	 */
	const spacing = computed(() => {
		return (key: string): number => {
			return themeManager.getSpacing(key)
		}
	})
	
	/**
	 * 获取圆角值
	 */
	const borderRadius = computed(() => {
		return (key: string): number => {
			return themeManager.getBorderRadius(key)
		}
	})
	
	/**
	 * 获取字体大小
	 */
	const fontSize = computed(() => {
		return (key: string): number => {
			return themeManager.getFontSize(key)
		}
	})
	
	/**
	 * 获取尺寸值
	 */
	const size = computed(() => {
		return (key: string): number => {
			return themeManager.getSize(key)
		}
	})
	
	/**
	 * 获取行高值
	 */
	const lineHeight = computed(() => {
		return (key: string): number => {
			return themeManager.getLineHeight(key)
		}
	})
	
	// 初始化时自动选择主题
	onMounted(() => {
		autoSelectTheme()
	})
	
	return {
		// 当前主题名称
		currentThemeName,
		// 当前主题变量
		theme,
		// 设置主题
		setTheme,
		// 自动选择主题
		autoSelectTheme,
		// 获取间距值
		spacing,
		// 获取圆角值
		borderRadius,
		// 获取字体大小
		fontSize,
		// 获取尺寸值
		size,
		// 获取行高值
		lineHeight
	}
}