* Remove all classes matching a regex pattern from a JSX element's className. * Handles StringLiteral, Literal, TemplateLiteral, and CallExpression className forms.
(nodePath: any, pattern: RegExp)
| 884 | * Handles StringLiteral, Literal, TemplateLiteral, and CallExpression className forms. |
| 885 | */ |
| 886 | function removeClassByPattern(nodePath: any, pattern: RegExp): void { |
| 887 | const openingElement = nodePath.node.openingElement; |
| 888 | const attrs = openingElement?.attributes ?? []; |
| 889 | const classNameAttr = attrs.find( |
| 890 | (a: any) => a.type === "JSXAttribute" && a.name?.name === "className" |
| 891 | ); |
| 892 | if (!classNameAttr?.value) return; |
| 893 | |
| 894 | const val = classNameAttr.value; |
| 895 | |
| 896 | const removeFromStr = (s: string) => |
| 897 | s.split(/\s+/).filter((c: string) => c && !pattern.test(c)).join(" "); |
| 898 | |
| 899 | if (val.type === "StringLiteral" || val.type === "Literal") { |
| 900 | val.value = removeFromStr(val.value); |
| 901 | return; |
| 902 | } |
| 903 | if (val.type === "JSXExpressionContainer") { |
| 904 | const expr = val.expression; |
| 905 | if (expr.type === "TemplateLiteral") { |
| 906 | for (const quasi of expr.quasis ?? []) { |
| 907 | const raw = quasi.value.raw; |
| 908 | const leadingWs = raw.match(/^(\s*)/)?.[1] ?? ""; |
| 909 | const trailingWs = raw.match(/(\s*)$/)?.[1] ?? ""; |
| 910 | const cleaned = removeFromStr(raw.trim()); |
| 911 | quasi.value = { raw: `${leadingWs}${cleaned}${trailingWs}`, cooked: `${leadingWs}${cleaned}${trailingWs}` }; |
| 912 | } |
| 913 | return; |
| 914 | } |
| 915 | if (expr.type === "CallExpression") { |
| 916 | for (const arg of expr.arguments ?? []) { |
| 917 | if (arg.type === "StringLiteral" || arg.type === "Literal") { |
| 918 | arg.value = removeFromStr(arg.value ?? ""); |
| 919 | } |
| 920 | } |
| 921 | } |
| 922 | } |
| 923 | } |
| 924 | |
| 925 | /** Default Tailwind spacing scale: token → px. Used by the batch engine to |
| 926 | * read back existing translate classes and accumulate deltas. */ |
no test coverage detected