theme-variables.uts 2.79 KB
// utils/theme-variables.uts
// CSS 变量主题系统 - 动态设置 CSS 变量值

import { getThemeManager } from "./theme-manager.uts";

/**
 * CSS 变量名称映射
 * key: CSS 变量名(如 '--p-base')
 * value: 主题变量键名(如 'base')
 */
const CSS_VARIABLES: Record<string, string> = {
	// 间距 (Spacing)
	"--p-page": "base", // p-page 使用 base 间距
	"--p-xs": "xs",
	"--p-sm": "sm",
	"--p-md": "md",
	"--p-base": "base",
	"--p-lg": "lg",
	"--p-xl": "xl",
	"--p-2xl": "2xl",
	"--p-3xl": "3xl",
	"--p-4xl": "4xl",
	
	// 圆角 (Border Radius)
	"--r-none": "none",
	"--r-sm": "sm",
	"--r-base": "base",
	"--r-md": "md",
	"--r-lg": "lg",
	"--r-xl": "xl",
	"--r-2xl": "2xl",
	"--r-full": "full",
	
	// 字体大小 (Font Size)
	"--t-xs": "xs",
	"--t-sm": "sm",
	"--t-base": "base",
	"--t-md": "md",
	"--t-lg": "lg",
	"--t-xl": "xl",
	"--t-2xl": "2xl",
	"--t-3xl": "3xl",
	"--t-4xl": "4xl",
	
	// 尺寸 (Size)
	"--s-xs": "xs",
	"--s-sm": "sm",
	"--s-md": "md",
	"--s-base": "base",
	"--s-lg": "lg",
	"--s-xl": "xl"
};

/**
 * 设置 CSS 变量到根元素
 * 注意:uni-app x 中需要在根 view 上设置 style
 */
export function setThemeVariables(rootElement: any = null): void {
	const themeManager = getThemeManager();
	const theme = themeManager.getCurrentTheme();
	
	if (theme == null) {
		console.warn("[theme-variables] Theme not loaded");
		return;
	}
	
	// 构建 CSS 变量对象
	const cssVars: Record<string, string> = {};
	
	// 设置间距变量
	Object.keys(CSS_VARIABLES).forEach((cssVar) => {
		const varName = CSS_VARIABLES[cssVar];
		
		if (cssVar.startsWith("--p-")) {
			// 间距变量
			cssVars[cssVar] = `${themeManager.getSpacing(varName)  }px`;
		} else if (cssVar.startsWith("--r-")) {
			// 圆角变量
			cssVars[cssVar] = `${themeManager.getBorderRadius(varName)  }px`;
		} else if (cssVar.startsWith("--t-")) {
			// 字体大小变量
			cssVars[cssVar] = `${themeManager.getFontSize(varName)  }px`;
		} else if (cssVar.startsWith("--s-")) {
			// 尺寸变量
			cssVars[cssVar] = `${themeManager.getSize(varName)  }px`;
		}
	});
	
	// 在 uni-app x 中,需要通过 :style 绑定到根元素
	// 这里返回样式对象,供组件使用
	return cssVars;
}

/**
 * 获取主题 CSS 变量样式对象
 * 用于绑定到根元素的 :style
 */
export function getThemeVariablesStyle(): Record<string, string> {
	return setThemeVariables();
}

/**
 * 在 App.uvue 中使用
 * 
 * @example
 * <template>
 *   <view :style="themeVars">
 *     <!-- 应用内容 -->
 *   </view>
 * </template>
 * 
 * <script setup lang="uts">
 * import { ref, onMounted } from 'vue'
 * import { getThemeVariablesStyle } from '@/utils/theme-variables.uts'
 * 
 * const themeVars = ref<Record<string, string>>({})
 * 
 * onMounted(() => {
 *   themeVars.value = getThemeVariablesStyle()
 * })
 * </script>
 */