Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changelog/upgrade-variant-conditional.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- Upgrade: Do not migrate a `variant` value that sits inside an expression, like `variant={active ? "outline" : "ghost"}`
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,39 @@ describe('is-safe-migration', async () => {
[`function Button({ variant='outline' }) {}`, 'outline'],
[`Button({ variant: "outline" })`, 'outline'],
[`Button({ variant: 'outline' })`, 'outline'],
[`Button({ variant: isActive ? "outline" : "ghost" })`, 'outline'],
[`<Button variant={first ? "default" : "outline"} />`, 'outline'],
[`<Button variant={variant ?? "outline"} />`, 'outline'],
[`<Button variant={required ? 'secondary' : 'outline'} />`, 'outline'],
[`<div data-variant={variant ?? "outline"} />`, 'outline'],
[`<Button variant={isActive(foo, bar) ? "outline" : "ghost"} />`, 'outline'],
[`<Button variant={isActive(getState(foo, bar), x) ? "outline" : "ghost"} />`, 'outline'],
[`<div :variant="active ? 'ghost' : 'outline'"></div>`, 'outline'],
[`Button({ variant: (value ?? "outline") })`, 'outline'],
[`Button({ variant: theme === "dark" ? "outline" : "ghost" })`, 'outline'],
[`<div :variant="isActive({ x: 1 }) ? 'ghost' : 'outline'"></div>`, 'outline'],
[`<Button variant={{ tone: "dark" }.tone === "dark" ? "outline" : "ghost"} />`, 'outline'],
[`<Button variant={cond ? ("outline") : "ghost"} />`, 'outline'],
[`<Button variant={cond ? "ghost" : ("outline")} />`, 'outline'],
[`<Button variant={{ tone: "}" }.tone === "}" ? "outline" : "ghost"} />`, 'outline'],
[`<Button variant={{ a: { b: { c: 1 } } }.a ? "outline" : "ghost"} />`, 'outline'],
[`Button({ variant: { a: { b: 1 } }.a ? "outline" : "ghost" })`, 'outline'],
[`<Button variant={obj["state"] ? "outline" : "ghost"} />`, 'outline'],
[`<Button variant={getVariant(cond ? "outline" : "ghost")} />`, 'outline'],
[`<Button variant={getVariant (cond ? "outline" : "ghost")} />`, 'outline'],
[`<Button variant={cn("ghost", active ? "shadow" : "none")} />`, 'shadow'],
[`<Button variant={variant === "outline" ? "ghost" : "default"} />`, 'outline'],
[`const isOutline = variant === "outline"`, 'outline'],
[`if (props.variant == 'outline') {}`, 'outline'],
[`if (variant !== "outline") {}`, 'outline'],
[`const variant = active ? "outline" : "ghost"`, 'outline'],
[`let variant = props.variant ?? "outline";`, 'outline'],
[`function Button({ variant = active ? "outline" : "ghost" }) {}`, 'outline'],
[`Button(variant=active ? "outline" : "ghost")`, 'outline'],
[`<Button variant={value = active ? "outline" : "ghost"} />`, 'outline'],
[`<?php $variant = $active ? 'outline' : 'ghost'; ?>`, 'outline'],
[`@php($variant = $active ? 'outline' : 'ghost')`, 'outline'],
[`$variant = $attributes->get('variant') ?? 'outline';`, 'outline'],
])('does not replace classes in invalid positions #%#', async (example, candidate) => {
expect(
await migrateCandidate(designSystem, {}, candidate, {
Expand All @@ -142,6 +175,52 @@ describe('is-safe-migration', async () => {

// Preact-style
[`<div enterClass="shadow"></div>`, 'shadow', 'shadow-sm'],

// A conditional class is still a class, even next to a `variant` prop
[`<div className={active ? "shadow" : "none"}></div>`, 'shadow', 'shadow-sm'],
[`<Button variant="ghost" className={active ? "shadow" : "none"} />`, 'shadow', 'shadow-sm'],
[
`Button({ variant: a ? "ghost" : "x", className: b ? "shadow" : "y" })`,
'shadow',
'shadow-sm',
],
[`<div variant="ghost" :class="active ? 'shadow' : 'none'"></div>`, 'shadow', 'shadow-sm'],
[`<Button variant={{ a: 1 }} className={b ? "shadow" : "none"} />`, 'shadow', 'shadow-sm'],
[
`<div title="variant: outline" className={b ? "shadow" : "none"}></div>`,
'shadow',
'shadow-sm',
],

// A class after the `variant` value is still a class
[`<Button variant="primary" className="outline" />`, 'outline', 'outline-solid'],
[`Button({ variant: "primary", className: "outline" })`, 'outline', 'outline-solid'],
[`<a href="/?variant=primary" class="outline">`, 'outline', 'outline-solid'],

// A comparison against `variant` is not the value of a `variant` prop
[`cn(variant === "primary" && "outline")`, 'outline', 'outline-solid'],
[`cn(variant == "primary" && "outline")`, 'outline', 'outline-solid'],
[`cn(variant === "primary" ? "shadow" : "none")`, 'shadow', 'shadow-sm'],

// A `variant` assignment ends at a separator or at the next assignment
[`let variant = x ?? "ghost"; cn("shadow")`, 'shadow', 'shadow-sm'],
[`let variant = x, classes = cn("shadow")`, 'shadow', 'shadow-sm'],
[`items.map((variant) => cn("shadow"))`, 'shadow', 'shadow-sm'],
[`items.map(variant => cn("shadow"))`, 'shadow', 'shadow-sm'],
[`<div data-variant=outline class="shadow"></div>`, 'shadow', 'shadow-sm'],

// A name that only ends in `variant` is another variable
[`const invariant = cn("shadow")`, 'shadow', 'shadow-sm'],
[`Foo({ invariant: cn("shadow") })`, 'shadow', 'shadow-sm'],

// A cva `variant: { … }` map holds class names
[` variant: { outline: "border shadow" },`, 'shadow', 'shadow-sm'],
[` variant: { default: "border", outline: "border shadow" },`, 'shadow', 'shadow-sm'],
[
`const buttonVariants = cva("", { variants: { variant: { default: "bg-primary shadow" } } })`,
'shadow',
'shadow-sm',
],
])('replaces classes in valid positions #%#', async (example, candidate, expected) => {
expect(
await migrateCandidate(designSystem, {}, candidate, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,14 @@ export function isSafeMigration(
}
}

// Heuristic: Disallow anything inside a shadcn/ui `variant` prop, because a
// conditional can sit between the prop and the string
//
// E.g.: `<Button variant={active ? "outline" : "ghost"} />`
if (isInsideVariantValue(currentLineBeforeCandidate)) {
return false
}

// Heuristic: Disallow Next.js Image `placeholder` prop
if (NEXT_PLACEHOLDER_PROP.test(currentLineBeforeCandidate)) {
return false
Expand All @@ -202,6 +210,90 @@ export function isSafeMigration(
return true
}

// A name that only ends in `variant`, like `invariant`, is another variable, but
// `data-variant`, `props.variant` and the PHP variable `$variant` still count
const VARIANT_PROP = /(?<!\w)variant\s*(:|=(?![=>]))\s*/g
const VARIANT_COMPARISON = /\bvariant\s*[!=]==?\s*['"`]$/

// The candidate is the last thing on the line, so the `variant` value it sits in
// is the one that has not ended yet. Each form ends somewhere different:
// `variant={…}` at its matching brace, `variant="…"` at its own quote, and
// `{ variant: … }` or `const variant = …` at a separator or at the brace around
// it.
function isInsideVariantValue(line: string): boolean {
// A string compared against `variant` is a variant name too
//
// E.g.: `if (variant === "outline") {}`
if (VARIANT_COMPARISON.test(line)) return true

for (let match of line.matchAll(VARIANT_PROP)) {
// The prop itself is never inside a string, so a `variant:` that is only
// mentioned in some other attribute value does not count
if (isMiddleOfString(line.slice(0, match.index))) continue

let start = match.index + match[0].length
let char = line[start]

if (match[1] === ':') {
// A cva `variant: { … }` map holds class names, so a candidate that still
// sits inside that object is a class, not a variant name
if (char === '{' && isOpenValue(line, start + 1, false)) continue
if (isOpenValue(line, start)) return true
} else if (char === '{') {
// A JSX value ends only at its matching brace, also when it holds an
// assignment or a comma
if (isOpenValue(line, start + 1, false)) return true
} else if (char === '"' || char === "'" || char === '`') {
if (!line.includes(char, start + 1)) return true
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
} else {
// E.g.: `const variant = active ? "outline" : "ghost"`
if (isOpenValue(line, start)) return true
Comment thread
RobinMalfait marked this conversation as resolved.
Resolved
}
}

return false
}

// Every string inside the value is part of it, also an argument of a call:
// `variant={getVariant(active ? "outline" : "ghost")}` computes a variant name.
//
// With `separators` off, only a closing bracket ends the value, so it tells
// whether the group that opens right before `start` is still open.
function isOpenValue(line: string, start: number, separators = true): boolean {
let depth = 0
let quote: string | null = null

for (let i = start; i < line.length; i++) {
let char = line[i]

if (quote !== null) {
if (char === '\\') i++
else if (char === quote) quote = null
} else if (char === '"' || char === "'" || char === '`') {
quote = char
} else if (char === '(' || char === '[' || char === '{') {
depth++
} else if (char === ')' || char === ']' || char === '}') {
if (depth === 0) return false
depth--
} else if (separators && depth === 0 && (char === ',' || char === ';')) {
return false
} else if (separators && depth === 0 && char === '=' && isAssignment(line, i)) {
// The next attribute or assignment starts, e.g. `class=` in
// `<div data-variant=outline class="…">`
return false
Comment thread
RobinMalfait marked this conversation as resolved.
Resolved
}
}

return true
}

// Whether the `=` at `index` is an assignment, not a part of `==`, `!=`, `<=`,
// `>=` or `=>`
function isAssignment(line: string, index: number): boolean {
return !'=>'.includes(line[index + 1] ?? '') && !'=!<>'.includes(line[index - 1] ?? '')
}

// Assumptions:
// - All `<style` tags appear before the next `</style>` tag
// - All `<style` tags are closed with `</style>`
Expand Down
Loading