|
1 | 1 | import { mergeConfigs, validators, type Config } from "tailwind-merge"; |
2 | 2 |
|
| 3 | +import { |
| 4 | + isArbitrarySpace, |
| 5 | + isArbitraryStep, |
| 6 | + isSpace, |
| 7 | + isStep, |
| 8 | +} from "./validators"; |
| 9 | + |
| 10 | +type ArrayElement<ArrayType extends readonly unknown[]> = |
| 11 | + ArrayType extends readonly (infer ElementType)[] ? ElementType : never; |
| 12 | + |
3 | 13 | export function withUtopia(config: Config<string, string>) { |
| 14 | + type ClassGroupKeys = keyof typeof config.classGroups; |
| 15 | + type ClassGroup = (typeof config.classGroups)[ClassGroupKeys]; |
| 16 | + type ClassDefinition = ArrayElement<ClassGroup>; |
| 17 | + interface ThemeGetter { |
| 18 | + (theme: (typeof config)["theme"]): ClassGroup; |
| 19 | + isThemeGetter: true; |
| 20 | + } |
| 21 | + |
| 22 | + const isThemeGetter = (def: ClassDefinition): def is ThemeGetter => |
| 23 | + typeof def === "function" && "isThemeGetter" in def && def.isThemeGetter; |
| 24 | + |
| 25 | + const resolveThemeGetters = ( |
| 26 | + group: ClassGroup, |
| 27 | + ): Exclude<ClassDefinition, ThemeGetter>[] => |
| 28 | + group.flatMap((def) => |
| 29 | + isThemeGetter(def) ? resolveThemeGetters(def(config.theme)) : [def], |
| 30 | + ); |
| 31 | + |
4 | 32 | const classGroups = Object.entries(config.classGroups) |
5 | 33 | .filter( |
6 | 34 | ([_name, group]) => group.length !== 0 && typeof group[0] !== "string", |
7 | 35 | ) |
| 36 | + .filter(([_name, group]) => { |
| 37 | + const classGroup = Object.values(group[0])[0] as ClassGroup; |
| 38 | + |
| 39 | + const resolvedClassGroup = resolveThemeGetters(classGroup); |
| 40 | + |
| 41 | + return resolvedClassGroup.some( |
| 42 | + (def) => |
| 43 | + def === validators.isLength || def === validators.isArbitraryLength, |
| 44 | + ); |
| 45 | + }) |
8 | 46 | .reduce((acc, [name, group]) => { |
9 | 47 | const groupName = Object.keys(group[0])[0]; |
10 | | - const def = [validators.isAny]; |
| 48 | + |
| 49 | + const classGroup = |
| 50 | + groupName === "text" |
| 51 | + ? [{ [`~${groupName}`]: [isStep, isArbitraryStep] }] |
| 52 | + : [ |
| 53 | + { [`~${groupName}`]: [isSpace, isArbitrarySpace] }, |
| 54 | + { [`~-${groupName}`]: [isSpace, isArbitrarySpace] }, |
| 55 | + ]; |
11 | 56 |
|
12 | 57 | return { |
13 | 58 | ...acc, |
14 | | - [name]: [{ [`~${groupName}`]: def }, { [`~-${groupName}`]: def }], |
| 59 | + [name]: classGroup, |
15 | 60 | }; |
16 | 61 | }, {}); |
17 | 62 |
|
|
0 commit comments