|
| 1 | +import { validators } from 'tailwind-merge' |
| 2 | +import { createClassGroupUtils, createParseClassName } from 'tailwind-merge/unstable-do-not-import' |
| 3 | + |
| 4 | +import { materializeConfig } from './materialize.ts' |
| 5 | +import { type ConfigPlan, type PlanValue, filterConflictMap } from './plan.ts' |
| 6 | + |
| 7 | +/** |
| 8 | + * Shrinks a plan to the class names a project actually uses: class groups no used class belongs to are dropped, and within the kept groups only the members some used class reaches survive — literals a used class names, nested prefix objects a used class descends into, and validators a used class's remaining tail satisfies. |
| 9 | + * |
| 10 | + * The pruned plan merges exactly like the full plan for every class list made of used classes, by construction: it is a subset of the full plan with tailwind-merge's lookup precedence intact. Classification of a used class runs through tailwind-merge's own parser and class map (prefix, variants, important marker, postfix modifiers — mirroring `mergeClassList`'s lookup order), so a class matched via a literal keeps that literal and a class matched via a validator keeps that validator, in the same group and at the same trie position; removing other members can never promote a previously losing candidate, because lookup tries deeper literal paths first and validators in definition order, and that order is preserved among the survivors. Members are only ever removed, never re-encoded, and validators are kept whenever any used tail satisfies them — over-keeping is always safe, under-keeping never is. Classes outside the used set lose their classification and pass through unmerged, which is the intended effect: a class Tailwind never saw has no styles, so keeping it next to a used class is at least as correct as merging it away. |
| 11 | + * |
| 12 | + * Used classes are raw tokens as a scanner finds them (`hover:bg-red-500/50`, `tw:p-4!`, `-mt-2`), deduplicated here; anything that does not classify is ignored. Conflict maps are filtered to the kept groups, `scales` stay untouched (the emitter drops shared consts nothing references anymore), and the result records what happened in `report.pruning`. The input plan is not mutated. |
| 13 | + */ |
| 14 | +export function prunePlan(plan: ConfigPlan, usedClasses: Iterable<string>): ConfigPlan { |
| 15 | + const config = materializeConfig(plan) |
| 16 | + const parseClassName = createParseClassName(config) |
| 17 | + const { getClassGroupId } = createClassGroupUtils(config) |
| 18 | + const postfixLookupClassGroupIds = new Set(config.postfixLookupClassGroups ?? []) |
| 19 | + |
| 20 | + /** Used class names that classified, per class group — already stripped to the part the class map matched (no variants, no important marker, no postfix modifier unless the postfix lookup matched it, no leading minus). */ |
| 21 | + const matchedNamesByGroup = new Map<string, Set<string>>() |
| 22 | + const seen = new Set<string>() |
| 23 | + let classifiedClassCount = 0 |
| 24 | + |
| 25 | + for (const rawClassName of usedClasses) { |
| 26 | + const className = rawClassName.trim() |
| 27 | + if (className === '' || seen.has(className)) { |
| 28 | + continue |
| 29 | + } |
| 30 | + seen.add(className) |
| 31 | + |
| 32 | + const classification = classify(className) |
| 33 | + if (classification === null) { |
| 34 | + continue |
| 35 | + } |
| 36 | + classifiedClassCount += 1 |
| 37 | + |
| 38 | + let names = matchedNamesByGroup.get(classification.classGroupId) |
| 39 | + if (!names) { |
| 40 | + names = new Set() |
| 41 | + matchedNamesByGroup.set(classification.classGroupId, names) |
| 42 | + } |
| 43 | + names.add(lookupName(classification.matchedClassName)) |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Mirrors the lookup in tailwind-merge's `mergeClassList`: a class with a postfix modifier (`bg-red-500/50`) is first looked up without it, groups listed in `postfixLookupClassGroups` get a second chance with the postfix included, and a class that only resolves with the postfix kept is taken as is. Returns the group and the exact string the class map matched — that string is what the member-level walk has to keep reachable. |
| 48 | + */ |
| 49 | + function classify( |
| 50 | + className: string, |
| 51 | + ): { classGroupId: string; matchedClassName: string } | null { |
| 52 | + const { isExternal, baseClassName, maybePostfixModifierPosition } = |
| 53 | + parseClassName(className) |
| 54 | + if (isExternal) { |
| 55 | + return null |
| 56 | + } |
| 57 | + |
| 58 | + if (maybePostfixModifierPosition) { |
| 59 | + const withoutPostfix = baseClassName.substring(0, maybePostfixModifierPosition) |
| 60 | + let classGroupId = getClassGroupId(withoutPostfix) |
| 61 | + let matchedClassName = withoutPostfix |
| 62 | + |
| 63 | + const classGroupIdWithPostfix = |
| 64 | + classGroupId && postfixLookupClassGroupIds.has(classGroupId) |
| 65 | + ? getClassGroupId(baseClassName) |
| 66 | + : undefined |
| 67 | + if (classGroupIdWithPostfix && classGroupIdWithPostfix !== classGroupId) { |
| 68 | + classGroupId = classGroupIdWithPostfix |
| 69 | + matchedClassName = baseClassName |
| 70 | + } |
| 71 | + if (!classGroupId) { |
| 72 | + classGroupId = getClassGroupId(baseClassName) |
| 73 | + matchedClassName = baseClassName |
| 74 | + } |
| 75 | + return classGroupId ? { classGroupId, matchedClassName } : null |
| 76 | + } |
| 77 | + |
| 78 | + const classGroupId = getClassGroupId(baseClassName) |
| 79 | + return classGroupId ? { classGroupId, matchedClassName: baseClassName } : null |
| 80 | + } |
| 81 | + |
| 82 | + const classGroups = new Map<string, PlanValue[]>() |
| 83 | + const removedClassGroups: string[] = [] |
| 84 | + const unprunedClassGroups: string[] = [] |
| 85 | + |
| 86 | + for (const [classGroupId, items] of plan.classGroups) { |
| 87 | + const names = matchedNamesByGroup.get(classGroupId) |
| 88 | + if (!names) { |
| 89 | + removedClassGroups.push(classGroupId) |
| 90 | + continue |
| 91 | + } |
| 92 | + const prunedItems = pruneItems(items, names) |
| 93 | + if (prunedItems.length === 0) { |
| 94 | + // A used class resolved into this group, but the walk found nothing it reaches — keep the group whole rather than risk undermatching; the report makes the discrepancy visible. |
| 95 | + unprunedClassGroups.push(classGroupId) |
| 96 | + classGroups.set(classGroupId, items) |
| 97 | + } else { |
| 98 | + classGroups.set(classGroupId, prunedItems) |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + return { |
| 103 | + ...plan, |
| 104 | + classGroups, |
| 105 | + conflictingClassGroups: filterConflictMap( |
| 106 | + Object.fromEntries(plan.conflictingClassGroups), |
| 107 | + classGroups, |
| 108 | + ), |
| 109 | + conflictingClassGroupModifiers: filterConflictMap( |
| 110 | + Object.fromEntries(plan.conflictingClassGroupModifiers), |
| 111 | + classGroups, |
| 112 | + ), |
| 113 | + postfixLookupClassGroups: plan.postfixLookupClassGroups.filter((classGroupId) => |
| 114 | + classGroups.has(classGroupId), |
| 115 | + ), |
| 116 | + report: { |
| 117 | + ...plan.report, |
| 118 | + pruning: { |
| 119 | + usedClassCount: seen.size, |
| 120 | + classifiedClassCount, |
| 121 | + classGroupsBefore: plan.classGroups.size, |
| 122 | + classGroupsAfter: classGroups.size, |
| 123 | + removedClassGroups, |
| 124 | + unprunedClassGroups, |
| 125 | + }, |
| 126 | + }, |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +/** |
| 131 | + * Keeps the items of one class-group level that some name in `names` reaches, walking nested prefix objects the way tailwind-merge's class map does: an object entry's key is a dash-separated prefix, so a name descends into it with the key stripped (`red-500` enters `{ red: […] }` as `500`), a name equal to the key enters as the empty string (the `''` literal marks "the prefix alone is a class"), and validators see the remaining tail at their level. Literal strings must match the remaining name exactly. |
| 132 | + */ |
| 133 | +function pruneItems(items: PlanValue[], names: Set<string>): PlanValue[] { |
| 134 | + const kept: PlanValue[] = [] |
| 135 | + |
| 136 | + for (const item of items) { |
| 137 | + if (item.kind === 'class') { |
| 138 | + if (names.has(item.value)) { |
| 139 | + kept.push(item) |
| 140 | + } |
| 141 | + } else if (item.kind === 'validator') { |
| 142 | + const validator = validators[item.name] |
| 143 | + for (const name of names) { |
| 144 | + if (validator(name)) { |
| 145 | + kept.push(item) |
| 146 | + break |
| 147 | + } |
| 148 | + } |
| 149 | + } else { |
| 150 | + const entries: [string, PlanValue[]][] = [] |
| 151 | + for (const [key, entryItems] of item.entries) { |
| 152 | + const tails = new Set<string>() |
| 153 | + for (const name of names) { |
| 154 | + if (name === key) { |
| 155 | + tails.add('') |
| 156 | + } else if (name.startsWith(`${key}-`)) { |
| 157 | + tails.add(name.slice(key.length + 1)) |
| 158 | + } |
| 159 | + } |
| 160 | + if (tails.size === 0) { |
| 161 | + continue |
| 162 | + } |
| 163 | + const prunedEntryItems = pruneItems(entryItems, tails) |
| 164 | + if (prunedEntryItems.length > 0) { |
| 165 | + entries.push([key, prunedEntryItems]) |
| 166 | + } |
| 167 | + } |
| 168 | + if (entries.length > 0) { |
| 169 | + kept.push({ kind: 'object', entries }) |
| 170 | + } |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + return kept |
| 175 | +} |
| 176 | + |
| 177 | +/** The string the class map walks for a matched class: negative classes like `-mt-2` start their lookup after the empty first part, exactly as `getClassGroupId` skips it. */ |
| 178 | +function lookupName(matchedClassName: string): string { |
| 179 | + const parts = matchedClassName.split('-') |
| 180 | + return parts[0] === '' && parts.length > 1 ? parts.slice(1).join('-') : matchedClassName |
| 181 | +} |
0 commit comments