Skip to content

Commit 36917ce

Browse files
scan the variant value instead of matching it with a regex
the four regex rules could only reach a fixed nesting depth so an object inside a condition or a brace inside a string still got through. this walks the value from the prop until whatever ends its own syntax so there is no depth limit any more. it also drops two over guards the regexes had. a class inside a call in a variant prop migrates again and so does a class next to an attribute that only mentions variant in its text.
1 parent 467f9fc commit 36917ce

2 files changed

Lines changed: 75 additions & 32 deletions

File tree

‎packages/@tailwindcss-upgrade/src/codemods/template/is-safe-migration.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,10 @@ describe('is-safe-migration', async () => {
132132
[`<Button variant={{ tone: "dark" }.tone === "dark" ? "outline" : "ghost"} />`, 'outline'],
133133
[`<Button variant={cond ? ("outline") : "ghost"} />`, 'outline'],
134134
[`<Button variant={cond ? "ghost" : ("outline")} />`, 'outline'],
135+
[`<Button variant={{ tone: "}" }.tone === "}" ? "outline" : "ghost"} />`, 'outline'],
136+
[`<Button variant={{ a: { b: { c: 1 } } }.a ? "outline" : "ghost"} />`, 'outline'],
137+
[`Button({ variant: { a: { b: 1 } }.a ? "outline" : "ghost" })`, 'outline'],
138+
[`<Button variant={obj["state"] ? "outline" : "ghost"} />`, 'outline'],
135139
])('does not replace classes in invalid positions #%#', async (example, candidate) => {
136140
expect(
137141
await migrateCandidate(designSystem, {}, candidate, {
@@ -165,6 +169,13 @@ describe('is-safe-migration', async () => {
165169
'shadow-sm',
166170
],
167171
[`<div variant="ghost" :class="active ? 'shadow' : 'none'"></div>`, 'shadow', 'shadow-sm'],
172+
[`<Button variant={{ a: 1 }} className={b ? "shadow" : "none"} />`, 'shadow', 'shadow-sm'],
173+
[`<Button variant={cn("ghost", active ? "shadow" : "none")} />`, 'shadow', 'shadow-sm'],
174+
[
175+
`<div title="variant: outline" className={b ? "shadow" : "none"}></div>`,
176+
'shadow',
177+
'shadow-sm',
178+
],
168179
])('replaces classes in valid positions #%#', async (example, candidate, expected) => {
169180
expect(
170181
await migrateCandidate(designSystem, {}, candidate, {

‎packages/@tailwindcss-upgrade/src/codemods/template/is-safe-migration.ts‎

Lines changed: 64 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,6 @@ import { DefaultMap } from '../../../../tailwindcss/src/utils/default-map'
44
import * as version from '../../utils/version'
55

66
const LOGICAL_OPERATORS = ['&&', '||', '?', '===', '==', '!=', '!==', '>', '>=', '<', '<=']
7-
8-
// A parenthesised group with one level of nesting, so a call in a condition keeps
9-
// its own commas instead of ending the match early.
10-
const PAREN_GROUP = String.raw`\((?:[^()]|\([^()]*\))*\)`
11-
// An object literal with one level of nesting, so a condition may contain one
12-
// without the surrounding value looking like it ended there.
13-
const OBJECT_GROUP = String.raw`\{(?:[^{}]|\{[^{}]*\})*\}`
14-
// A ternary or nullish operator, then whatever sits before the string literal.
15-
const CONDITION_TAIL = String.raw`(?:\?\?|\?|:)\s*\(*\s*['"\`]$`
16-
177
const CONDITIONAL_TEMPLATE_SYNTAX = [
188
// Skip any generic attributes like `xxx="shadow"`,
199
// including Vue conditions like `v-if="something && shadow"`
@@ -27,29 +17,8 @@ const CONDITIONAL_TEMPLATE_SYNTAX = [
2717
// Alpine
2818
/wire:[^\s]*?$/,
2919

30-
// shadcn/ui variants. A conditional can sit between the prop and the literal,
31-
// so each form below stops at whatever actually ends its own value. Getting
32-
// that boundary wrong in either direction is costly: too narrow and a prop is
33-
// rewritten as a class, too wide and a real class stops being migrated.
34-
35-
// `variant="outline"`, `variant={"outline"}`, `variant: "outline"`
20+
// shadcn/ui variants
3621
/variant\s*[:=]\s*\{?['"`]$/,
37-
38-
// `variant={cond ? "outline" : "ghost"}` — a brace ends the value, and a
39-
// quoted branch inside it is ordinary
40-
new RegExp(
41-
String.raw`variant\s*[:=]\s*\{(?:[^{}]|${PAREN_GROUP}|${OBJECT_GROUP})*?${CONDITION_TAIL}`,
42-
),
43-
44-
// `:variant="active ? 'outline' : 'ghost'"` — the opening quote ends the value,
45-
// so the match cannot run on into a neighbouring attribute such as `:class`
46-
new RegExp(String.raw`variant\s*=\s*(["'])(?:(?!\1)[^{}]|${OBJECT_GROUP})*?${CONDITION_TAIL}`),
47-
48-
// `{ variant: theme === "dark" ? "outline" : "ghost" }` — a comma or brace ends
49-
// the value, quotes do not
50-
new RegExp(
51-
String.raw`variant\s*:\s*(?:[^{},]|${PAREN_GROUP}|${OBJECT_GROUP})*?${CONDITION_TAIL}`,
52-
),
5322
]
5423
const NEXT_PLACEHOLDER_PROP = /placeholder=\{?['"`]$/
5524
const VUE_3_EMIT = /\b\$?emit\(['"`]$/
@@ -220,6 +189,14 @@ export function isSafeMigration(
220189
}
221190
}
222191

192+
// Heuristic: Disallow anything inside a shadcn/ui `variant` prop, because a
193+
// conditional can sit between the prop and the string
194+
//
195+
// E.g.: `<Button variant={active ? "outline" : "ghost"} />`
196+
if (isInsideVariantValue(currentLineBeforeCandidate)) {
197+
return false
198+
}
199+
223200
// Heuristic: Disallow Next.js Image `placeholder` prop
224201
if (NEXT_PLACEHOLDER_PROP.test(currentLineBeforeCandidate)) {
225202
return false
@@ -233,6 +210,61 @@ export function isSafeMigration(
233210
return true
234211
}
235212

213+
const VARIANT_PROP = /variant\s*([:=])\s*/g
214+
const CALLEE = /[\w$.)\]]/
215+
216+
// The candidate is the last thing on the line, so the `variant` value it sits in
217+
// is the one that has not ended yet. Each form ends somewhere different:
218+
// `variant={…}` at its matching brace, `variant="…"` at its own quote, and
219+
// `{ variant: … }` at a comma or at the brace around it.
220+
function isInsideVariantValue(line: string): boolean {
221+
for (let match of line.matchAll(VARIANT_PROP)) {
222+
// The prop itself is never inside a string, so a `variant:` that is only
223+
// mentioned in some other attribute value does not count
224+
if (isMiddleOfString(line.slice(0, match.index))) continue
225+
226+
let start = match.index + match[0].length
227+
let char = line[start]
228+
229+
if (match[1] === ':') {
230+
if (isOpenValue(line, start)) return true
231+
} else if (char === '{') {
232+
if (isOpenValue(line, start + 1)) return true
233+
} else if (char === '"' || char === "'" || char === '`') {
234+
if (!line.includes(char, start + 1)) return true
235+
}
236+
}
237+
238+
return false
239+
}
240+
241+
function isOpenValue(line: string, start: number): boolean {
242+
// Whether each open group is the argument list of a call, because an argument
243+
// is passed to that call and is not the value itself
244+
let groups: boolean[] = []
245+
let quote: string | null = null
246+
247+
for (let i = start; i < line.length; i++) {
248+
let char = line[i]
249+
250+
if (quote !== null) {
251+
if (char === '\\') i++
252+
else if (char === quote) quote = null
253+
} else if (char === '"' || char === "'" || char === '`') {
254+
quote = char
255+
} else if (char === '(' || char === '[' || char === '{') {
256+
groups.push(char === '(' && CALLEE.test(line[i - 1] ?? ''))
257+
} else if (char === ')' || char === ']' || char === '}') {
258+
if (groups.length === 0) return false
259+
groups.pop()
260+
} else if (char === ',' && groups.length === 0) {
261+
return false
262+
}
263+
}
264+
265+
return !groups.includes(true)
266+
}
267+
236268
// Assumptions:
237269
// - All `<style` tags appear before the next `</style>` tag
238270
// - All `<style` tags are closed with `</style>`

0 commit comments

Comments
 (0)