theme-variables.uts
2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// 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>
*/