Skip to content

Make candidate template migrations faster #18025

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
May 15, 2025
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Ensure that running the Standalone build does not leave temporary files behind ([#17981](https://github.com/tailwindlabs/tailwindcss/pull/17981))
- Fix `-rotate-*` utilities with arbitrary values ([#18014](https://github.com/tailwindlabs/tailwindcss/pull/18014))
- Upgrade: Change casing of utilities with named values to kebab-case to match updated theme variables ([#18017](https://github.com/tailwindlabs/tailwindcss/pull/18017))
- Upgrade: Fix unsafe migrations in Vue files ([#18025](https://github.com/tailwindlabs/tailwindcss/pull/18025))
- Ignore custom variants using `:merge(…)` selectors in legacy JS plugins ([#18020](https://github.com/tailwindlabs/tailwindcss/pull/18020))

### Added

- Upgrade: Migrate bare values to named values ([#18000](https://github.com/tailwindlabs/tailwindcss/pull/18000))
- Upgrade: Make candidate template migrations faster using caching ([#18025](https://github.com/tailwindlabs/tailwindcss/pull/18025))

## [4.1.6] - 2025-05-09

Expand Down
4 changes: 2 additions & 2 deletions integrations/upgrade/js-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ test(
<div
class="[letter-spacing:theme(letterSpacing.superWide)] [line-height:theme(lineHeight.superLoose)]"
></div>
<div class="text-red-superRed/superOpaque leading-superLoose"></div>
<div class="text-superRed/superOpaque leading-superLoose"></div>
`,
'node_modules/my-external-lib/src/template.html': html`
<div class="text-red-500">
Expand All @@ -169,7 +169,7 @@ test(
<div
class="[letter-spacing:var(--tracking-super-wide)] [line-height:var(--leading-super-loose)]"
></div>
<div class="text-red-super-red/super-opaque leading-super-loose"></div>
<div class="text-super-red/super-opaque leading-super-loose"></div>

--- src/input.css ---
@import 'tailwindcss';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { __unstable__loadDesignSystem } from '@tailwindcss/node'
import { expect, test, vi } from 'vitest'
import * as versions from '../../utils/version'
import { migrateCandidate } from './migrate'
vi.spyOn(versions, 'isMajor').mockReturnValue(true)

test('does not replace classes in invalid positions', async () => {
let designSystem = await __unstable__loadDesignSystem('@import "tailwindcss";', {
base: __dirname,
})

async function shouldNotReplace(example: string, candidate = '!border') {
expect(
await migrateCandidate(designSystem, {}, candidate, {
contents: example,
start: example.indexOf(candidate),
end: example.indexOf(candidate) + candidate.length,
}),
).toEqual(candidate)
}

await shouldNotReplace(`let notBorder = !border \n`)
await shouldNotReplace(`{ "foo": !border.something + ""}\n`)
await shouldNotReplace(`<div v-if="something && !border"></div>\n`)
await shouldNotReplace(`<div v-else-if="something && !border"></div>\n`)
await shouldNotReplace(`<div v-show="something && !border"></div>\n`)
await shouldNotReplace(`<div v-if="!border || !border"></div>\n`)
await shouldNotReplace(`<div v-else-if="!border || !border"></div>\n`)
await shouldNotReplace(`<div v-show="!border || !border"></div>\n`)
await shouldNotReplace(`<div v-if="!border"></div>\n`)
await shouldNotReplace(`<div v-else-if="!border"></div>\n`)
await shouldNotReplace(`<div v-show="!border"></div>\n`)
await shouldNotReplace(`<div x-if="!border"></div>\n`)

await shouldNotReplace(`let notShadow = shadow \n`, 'shadow')
await shouldNotReplace(`{ "foo": shadow.something + ""}\n`, 'shadow')
await shouldNotReplace(`<div v-if="something && shadow"></div>\n`, 'shadow')
await shouldNotReplace(`<div v-else-if="something && shadow"></div>\n`, 'shadow')
await shouldNotReplace(`<div v-show="something && shadow"></div>\n`, 'shadow')
await shouldNotReplace(`<div v-if="shadow || shadow"></div>\n`, 'shadow')
await shouldNotReplace(`<div v-else-if="shadow || shadow"></div>\n`, 'shadow')
await shouldNotReplace(`<div v-show="shadow || shadow"></div>\n`, 'shadow')
await shouldNotReplace(`<div v-if="shadow"></div>\n`, 'shadow')
await shouldNotReplace(`<div v-else-if="shadow"></div>\n`, 'shadow')
await shouldNotReplace(`<div v-show="shadow"></div>\n`, 'shadow')
await shouldNotReplace(`<div x-if="shadow"></div>\n`, 'shadow')
await shouldNotReplace(
`<div style={{filter: 'drop-shadow(30px 10px 4px #4444dd)'}}/>\n`,
'shadow',
)

// Next.js Image placeholder cases
await shouldNotReplace(`<Image placeholder="blur" src="/image.jpg" />`, 'blur')
await shouldNotReplace(`<Image placeholder={'blur'} src="/image.jpg" />`, 'blur')
await shouldNotReplace(`<Image placeholder={blur} src="/image.jpg" />`, 'blur')

// https://github.com/tailwindlabs/tailwindcss/issues/17974
await shouldNotReplace('<div v-if="!duration">', '!duration')
await shouldNotReplace('<div :active="!duration">', '!duration')
await shouldNotReplace('<div :active="!visible">', '!visible')
})
Original file line number Diff line number Diff line change
@@ -1,18 +1,84 @@
import { parseCandidate } from '../../../../tailwindcss/src/candidate'
import type { DesignSystem } from '../../../../tailwindcss/src/design-system'
import * as version from '../../utils/version'

const QUOTES = ['"', "'", '`']
const LOGICAL_OPERATORS = ['&&', '||', '?', '===', '==', '!=', '!==', '>', '>=', '<', '<=']
const CONDITIONAL_TEMPLATE_SYNTAX = [
// Vue
/v-else-if=['"]$/,
/v-if=['"]$/,
/v-show=['"]$/,
/(?<!:?class)=['"]$/,

// Alpine
/x-if=['"]$/,
/x-show=['"]$/,
]
const NEXT_PLACEHOLDER_PROP = /placeholder=\{?['"]$/

export function isSafeMigration(location: { contents: string; start: number; end: number }) {
export function isSafeMigration(
rawCandidate: string,
location: { contents: string; start: number; end: number },
designSystem: DesignSystem,
): boolean {
let [candidate] = Array.from(parseCandidate(rawCandidate, designSystem))

// If we can't parse the candidate, then it's not a candidate at all. However,
// we could be dealing with legacy classes like `tw__flex` in Tailwind CSS v3
// land, which also wouldn't parse.
//
// So let's only skip if we couldn't parse and we are not in Tailwind CSS v3.
//
if (!candidate && version.isGreaterThan(3)) {
return true
}

// Parsed a candidate succesfully, verify if it's a valid candidate
else if (candidate) {
// When we have variants, we can assume that the candidate is safe to migrate
// because that requires colons.
//
// E.g.: `hover:focus:flex`
if (candidate.variants.length > 0) {
return true
}

// When we have an arbitrary property, the candidate has such a particular
// structure it's very likely to be safe.
//
// E.g.: `[color:red]`
if (candidate.kind === 'arbitrary') {
return true
}

// A static candidate is very likely safe if it contains a dash.
//
// E.g.: `items-center`
if (candidate.kind === 'static' && candidate.root.includes('-')) {
return true
}

// A functional candidate is very likely safe if it contains a value (which
// implies a `-`). Or if the root contains a dash.
//
// E.g.: `bg-red-500`, `bg-position-20`
if (
(candidate.kind === 'functional' && candidate.value !== null) ||
(candidate.kind === 'functional' && candidate.root.includes('-'))
) {
return true
}

// If the candidate contains a modifier, it's very likely to be safe because
// it implies that it contains a `/`.
//
// E.g.: `text-sm/7`
if (candidate.kind === 'functional' && candidate.modifier) {
return true
}
}

let currentLineBeforeCandidate = ''
for (let i = location.start - 1; i >= 0; i--) {
let char = location.contents.at(i)!
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,27 +51,6 @@ export function migrateArbitraryUtilities(
continue
}

// 1. Canonicalize the value. This might be a bit wasteful because it might
// have been done by other migrations before, but essentially we want to
// canonicalize the arbitrary value to its simplest canonical form. We
// won't be constant folding `calc(…)` expressions (yet?), but we can
// remove unnecessary whitespace (which the `printCandidate` already
// handles for us).
//
// E.g.:
//
// ```
// [display:_flex_] => [display:flex]
// [display:_flex] => [display:flex]
// [display:flex_] => [display:flex]
// [display:flex] => [display:flex]
// ```
//
let canonicalizedCandidate = designSystem.printCandidate(readonlyCandidate)
if (canonicalizedCandidate !== rawCandidate) {
return migrateArbitraryUtilities(designSystem, _userConfig, canonicalizedCandidate)
}

// The below logic makes use of mutation. Since candidates in the
// DesignSystem are cached, we can't mutate them directly.
let candidate = structuredClone(readonlyCandidate) as Writable<typeof readonlyCandidate>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { __unstable__loadDesignSystem } from '@tailwindcss/node'
import { expect, test, vi } from 'vitest'
import * as versions from '../../utils/version'
import { migrateCanonicalizeCandidate } from './migrate-canonicalize-candidate'
vi.spyOn(versions, 'isMajor').mockReturnValue(true)

test.each([
// Normalize whitespace in arbitrary properties
['[display:flex]', '[display:flex]'],
['[display:_flex]', '[display:flex]'],
['[display:flex_]', '[display:flex]'],
['[display:_flex_]', '[display:flex]'],

// Normalize whitespace in `calc` expressions
['w-[calc(100%-2rem)]', 'w-[calc(100%-2rem)]'],
['w-[calc(100%_-_2rem)]', 'w-[calc(100%-2rem)]'],

// Normalize the important modifier
['!flex', 'flex!'],
['flex!', 'flex!'],
])('%s => %s', async (candidate, result) => {
let designSystem = await __unstable__loadDesignSystem('@import "tailwindcss";', {
base: __dirname,
})

expect(migrateCanonicalizeCandidate(designSystem, {}, candidate)).toEqual(result)
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { Config } from '../../../../tailwindcss/src/compat/plugin-api'
import type { DesignSystem } from '../../../../tailwindcss/src/design-system'

// Canonicalize the value to its minimal form. This will normalize whitespace,
// and print the important modifier `!` in the correct place.
//
// E.g.:
//
// ```
// [display:_flex_] => [display:flex]
// [display:_flex] => [display:flex]
// [display:flex_] => [display:flex]
// [display:flex] => [display:flex]
// ```
//
export function migrateCanonicalizeCandidate(
designSystem: DesignSystem,
_userConfig: Config | null,
rawCandidate: string,
) {
for (let readonlyCandidate of designSystem.parseCandidate(rawCandidate)) {
let canonicalizedCandidate = designSystem.printCandidate(readonlyCandidate)
if (canonicalizedCandidate !== rawCandidate) {
return canonicalizedCandidate
}
}

return rawCandidate
}

This file was deleted.

This file was deleted.

Loading