Files
dg-js-workspace/packages/ui-react/src/styles/utils/create-class-recipe.ts
T
2026-11-29 07:30:49 +08:00

60 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 1. 允许变体值的键可以是字符串,也可以是布尔值(为了开发体验,允许传 true/false)
import { mergeClass } from "./merge-class";
// 但底层存储我们统一视为字符串处理
type VariantValue = string | boolean;
type VariantsConfig<V extends Record<string, Record<string, string>>> = {
base?: string;
variants?: V;
compoundVariants?: Array<
// 修改这里:允许 compoundVariants 的值是 VariantValue,而不仅仅是 keyof V[K]
Partial<{ [K in keyof V]: VariantValue }> & { class: string }
>;
};
// 2. 修改 Props 定义,允许传入 boolean,因为 JS 对象 key 访问时,boolean 会被转为 string
type VariantProps<V extends Record<string, Record<string, string>>> = Partial<{
[K in keyof V]: keyof V[K] | boolean;
}>;
export function createClassRecipe<
V extends Record<string, Record<string, string>>,
>(config: VariantsConfig<V>) {
return function (props: VariantProps<V> = {}): string {
const classes: string[] = [];
if (config.base) classes.push(config.base);
if (config.variants) {
for (const [key, map] of Object.entries(config.variants)) {
const value = props[key];
// 运行时修复:如果传入的是 boolean true,需要转为字符串 "true" 才能匹配 map
const stringifiedValue = String(value);
if (value && map[stringifiedValue]) {
classes.push(map[stringifiedValue]);
}
}
}
if (config.compoundVariants) {
for (const cv of config.compoundVariants) {
const match = Object.entries(cv)
.filter(([k]) => k !== "class")
.every(([k, v]) => {
const propValue = props[k as keyof V];
// 运行时修复:统一转为字符串比较,确保 "true" === true 能匹配(虽然不建议混用,但要兼容)
return String(propValue) === String(v);
});
if (match && cv.class) {
classes.push(cv.class);
}
}
}
return mergeClass(...classes);
};
}