import { transform } from 'lightningcss'
import { randomUUID } from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
import { describe, expect, test, vi } from 'vitest'
import { __unstable__loadDesignSystem } from '.'
import { intersection, normalizeEscapes } from './canonicalize-candidates'
import { cartesian } from './cartesian'
import type { CanonicalizeOptions } from './intellisense'
import plugin from './plugin'
import { DefaultMap } from './utils/default-map'
import { LRUDefaultMap } from './utils/lru-default-map'
const css = String.raw
const timeout = 25_000
const defaultTheme = fs.readFileSync(path.resolve(__dirname, '../theme.css'), 'utf8')
const MAX_CACHED_DESIGN_SYSTEMS = 32
const designSystems = new DefaultMap((base: string) => {
return new LRUDefaultMap(MAX_CACHED_DESIGN_SYSTEMS, (input: string) => {
return __unstable__loadDesignSystem(input, {
base,
async loadStylesheet() {
return {
path: '',
base: '',
content: css`
@tailwind utilities;
${defaultTheme}
@theme {
--*: initial;
--breakpoint-lg: 64rem;
--breakpoint-md: 48rem;
--color-blue-200: oklch(88.2% 0.059 254.128);
--color-blue-500: oklch(62.3% 0.214 259.815);
--color-red-500: oklch(63.7% 0.237 25.331);
--color-white: #fff;
--container-md: 28rem;
--font-weight-normal: 400;
--leading-relaxed: 1.625;
--spacing: 0.25rem;
--text-sm--line-height: calc(1.25 / 0.875);
--text-sm: 0.875rem;
--text-xs--line-height: calc(1 / 0.75);
--text-xs: 0.75rem;
}
`,
}
},
})
})
})
const DEFAULT_CANONICALIZATION_OPTIONS: CanonicalizeOptions = {
rem: 16,
collapse: true,
logicalToPhysical: true,
}
describe.each([['default'], ['with-variant'], ['important'], ['prefix']])('%s', (strategy) => {
let testName = '%s → %s (%#)'
if (strategy === 'with-variant') {
testName = testName.replaceAll('%s', 'focus:%s')
} else if (strategy === 'important') {
testName = testName.replaceAll('%s', '%s!')
} else if (strategy === 'prefix') {
testName = testName.replaceAll('%s', 'tw:%s')
}
function prepare(candidate: string) {
if (strategy === 'with-variant') {
candidate = `focus:${candidate}`
} else if (strategy === 'important') {
candidate = `${candidate}!`
} else if (strategy === 'prefix') {
candidate = `tw:${candidate}`
if (candidate.includes('--')) {
candidate = candidate
.replace(
/([(:])--([\w-]+)([,)])/g,
(_, start, variable, end) => `${start}--tw-${variable}${end}`,
)
.replaceAll('--theme(--tw-', '--theme(--')
}
}
return candidate
}
async function expectCanonicalization(
input: string,
candidates: string,
expected: string,
options: CanonicalizeOptions = DEFAULT_CANONICALIZATION_OPTIONS,
) {
let preparedCandidates = candidates.split(/\s+/g).map(prepare)
let preparedExpected = expected.split(/\s+/g).map(prepare)
if (strategy === 'prefix') {
input = input.replace("@import 'tailwindcss';", "@import 'tailwindcss' prefix(tw);")
}
let designSystem = await designSystems.get(__dirname).get(input)
let actual = designSystem.canonicalizeCandidates(preparedCandidates, options)
try {
expect(actual).toEqual(preparedExpected)
} catch (err) {
if (err instanceof Error) Error.captureStackTrace(err, expectCanonicalization)
throw err
}
}
describe('deprecated utilities', () => {
test.each([
['bg-gradient-to-t', 'bg-linear-to-t'],
['bg-gradient-to-tr', 'bg-linear-to-tr'],
['bg-gradient-to-r', 'bg-linear-to-r'],
['bg-gradient-to-br', 'bg-linear-to-br'],
['bg-gradient-to-b', 'bg-linear-to-b'],
['bg-gradient-to-bl', 'bg-linear-to-bl'],
['bg-gradient-to-l', 'bg-linear-to-l'],
['bg-gradient-to-tl', 'bg-linear-to-tl'],
])(testName, { timeout }, async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
`
await expectCanonicalization(input, candidate, expected)
})
let deprecated: [string, string][] = [
['order-none', 'order-0'],
['break-words', 'wrap-break-word'],
['overflow-ellipsis', 'text-ellipsis'],
['start-full', 'inset-s-full'],
['-start-full', '-inset-s-full'],
['start-auto', 'inset-s-auto'],
['start-px', 'inset-s-px'],
['-start-px', '-inset-s-px'],
['start-8', 'inset-s-8'],
['-start-8', '-inset-s-8'],
['start-123', 'inset-s-123'],
['-start-123', '-inset-s-123'],
['end-full', 'inset-e-full'],
['-end-full', '-inset-e-full'],
['end-auto', 'inset-e-auto'],
['end-px', 'inset-e-px'],
['-end-px', '-inset-e-px'],
['end-8', 'inset-e-8'],
['-end-8', '-inset-e-8'],
['end-123', 'inset-e-123'],
['-end-123', '-inset-e-123'],
]
test.each(deprecated)(testName, { timeout }, async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
`
await expectCanonicalization(input, candidate, expected)
})
describe('With custom implementation', () => {
let customImplementations = deprecated
.map(
([candidate]) => css`
@utility ${candidate} {
--custom-${randomUUID()}: implementation;
}
`,
)
.join('\n')
test.each(deprecated.map(([candidate]) => [candidate, candidate]))(
testName,
{ timeout },
async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
${customImplementations}
`
await expectCanonicalization(input, candidate, expected)
},
)
})
})
describe('arbitrary properties', () => {
test.each([
['[color:red]', 'text-[red]'],
['[--value:theme(spacing.1)]', '[--value:--spacing(1)]'],
['[--value:theme(fontSize.xs.1.lineHeight)]', '[--value:var(--text-xs--line-height)]'],
['[--value:theme(spacing[1.25])]', '[--value:--spacing(1.25)]'],
['[--value:theme(spacing[1.1])]', '[--value:theme(spacing[1.1])]'],
['[color:theme(colors.red.500)]', 'text-red-500'],
['[color:theme(colors.red.500)]/50', 'text-red-500/50'],
[
'[color:theme(colors.red.500/50,theme(colors.blue.500/50))]',
'text-[--theme(--color-red-500/50,--theme(--color-blue-500/50))]',
],
[
'[color:theme(colors.red.500/50,theme(colors.blue.500/50))]/50',
'text-[--theme(--color-red-500/50,--theme(--color-blue-500/50))]/50',
],
['[color:theme(colors.red.500/75%)]', 'text-red-500/75'],
['[color:theme(colors.red.500/.12)]', 'text-red-500/12'],
['[color:theme(colors.red.500/0.12)]', 'text-red-500/12'],
['[color:theme(colors.red.500/12.34%)]', 'text-red-500/[12.34%]'],
['[color:theme(colors.red.500/var(--opacity))]', 'text-red-500/(--opacity)'],
['[color:theme(colors.red.500/.12345)]', 'text-red-500/[12.345%]'],
['[color:theme(colors.red.500/.29)]', 'text-red-500/29'],
['[color:theme(colors.red.500/50.25%)]', 'text-red-500/50.25'],
['[color:theme(colors.red.500/50%)]/50', 'text-[--theme(--color-red-500/50%)]/50'],
['[padding-top:min(20%,calc(var(--spacing)*8))]', 'pt-[min(20%,--spacing(8))]'],
[
'[padding-top:min(20%,calc(var(--spacing)*var(--other)))]',
'pt-[min(20%,--spacing(var(--other)))]',
],
['[padding-top:calc(var(--spacing)*8)]', 'pt-8'],
['[padding-top:calc(var(--spacing)*var(--other))]', 'pt-[--spacing(var(--other))]'],
['[--foo:theme(transitionDuration.500)]', '[--foo:theme(transitionDuration.500)]'],
['[--foo:theme(colors.red.500/50/50)]', '[--foo:theme(colors.red.500/50/50)]'],
['[--foo:theme(colors.red.500/50/50)]/50', '[--foo:theme(colors.red.500/50/50)]/50'],
[
'[--foo:theme(colors.red.500/50/50)_theme(colors.blue.200)]',
'[--foo:theme(colors.red.500/50/50)_var(--color-blue-200)]',
],
[
'[--foo:theme(colors.red.500/50/50)_theme(colors.blue.200)]/50',
'[--foo:theme(colors.red.500/50/50)_var(--color-blue-200)]/50',
],
['[font-weight:400]', 'font-normal'],
['[line-height:0]', 'leading-0'],
['[border-style:solid]', 'border-solid'],
['[--foo:0px]', '[--foo:0px]'],
['[--foo:calc(0px*1)]', '[--foo:calc(0px*1)]'],
['[--foo:calc(0*1rem)]', '[--foo:calc(0*1rem)]'],
])(testName, { timeout }, async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
`
await expectCanonicalization(input, candidate, expected)
})
test.each([
['[text-wrap:balance]', 'text-balance'],
['[display:_flex_]', 'flex'],
['[display:_flex]', 'flex'],
['[display:flex_]', 'flex'],
['[color:var(--color-red-500)]', 'text-red-500'],
['[background-color:var(--color-red-500)]', 'bg-red-500'],
['[color:#fff]', 'text-white'],
['[color:#FFF]', 'text-white'],
['[color:var(--color-red-500)]/25', 'text-red-500/25'],
['[color:var(--color-red-500)]/[25%]', 'text-red-500/25'],
['[color:var(--color-red-500)]/[100%]', 'text-red-500'],
['[color:var(--color-red-500)]/100', 'text-red-500'],
['[color:var(--color-red-500)]/[10%]', 'text-red-500/10'],
['[color:var(--color-red-500)]/[10.0%]', 'text-red-500/10'],
['[color:var(--color-red-500)]/[.1]', 'text-red-500/10'],
['[color:var(--color-red-500)]/[.10]', 'text-red-500/10'],
['[color:oklch(62.3%_0.214_259.815)]/50', 'text-primary'],
['[max-height:20%]', 'max-h-[20%]'],
['[grid-column:2]', 'col-2'],
['[grid-column:1234]', 'col-1234'],
[
'[grid-template-columns:repeat(2,minmax(100px,1fr))]',
'grid-cols-[repeat(2,minmax(100px,1fr))]',
],
['[grid-template-columns:repeat(2,minmax(0,1fr))]', 'grid-cols-2'],
])(testName, { timeout }, async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
--spacing: 0.25rem;
--color-red-500: red;
--color-white: #fff;
--color-primary: color-mix(in oklab, oklch(62.3% 0.214 259.815) 50%, transparent);
}
`
await expectCanonicalization(input, candidate, expected)
})
})
describe('arbitrary values', () => {
test.each([
['bg-[theme(colors.red.500)]', 'bg-red-500'],
['bg-[size:theme(spacing.4)]', 'bg-size-[--spacing(4)]'],
['w-[calc(100dvh-theme(spacing.2))]', 'w-[calc(100dvh-(--spacing(2)))]'],
['w-[calc(100dvh+theme(spacing.2))]', 'w-[calc(100dvh+(--spacing(2)))]'],
['w-[calc(100dvh/theme(spacing.2))]', 'w-[calc(100dvh/(--spacing(2)))]'],
['w-[calc(100dvh*theme(spacing.2))]', 'w-[calc(100dvh*(--spacing(2)))]'],
['bg-[theme(colors.red.500,red)]', 'bg-(--color-red-500,red)'],
['bg-[theme(colors.foo.1000)]', 'bg-[theme(colors.foo.1000)]'],
['bg-[theme(colors.foo.1000,theme(colors.red.500))]', 'bg-red-500'],
['text-[calc(theme(fontSize.xs)*2)]', 'text-[calc(var(--text-xs)*2)]'],
['bg-[theme(colors.red.500/75%)]', 'bg-red-500/75'],
['bg-[theme(colors.red.500/12.34%)]', 'bg-red-500/[12.34%]'],
['bg-[#fff]', 'bg-white'],
['bg-[#FFF]', 'bg-white'],
[
'shadow-[shadow:inset_0px_1px_theme(colors.white/15%)]',
'shadow-[inset_0px_1px_--theme(--color-white/15%)]',
],
['bg-[theme(colors.red.500/50%)]/50', 'bg-[--theme(--color-red-500/50%)]/50'],
['max-[theme(screens.lg)]:flex', 'max-lg:flex'],
['min-[theme(screens.lg)]:flex', 'lg:flex'],
['max-[theme(spacing.4)]:flex', 'max-[theme(spacing.4)]:flex'],
['max-[theme(spacing.4/50)]:flex', 'max-[theme(spacing.4/50)]:flex'],
['grid-cols-[min(50%_,_theme(spacing.80))_auto]', 'grid-cols-[min(50%,--spacing(80))_auto]'],
['pt-[min(20%,calc(var(--spacing)*8))]', 'pt-[min(20%,--spacing(8))]'],
['pt-[min(20%,calc(var(--spacing)*var(--other)))]', 'pt-[min(20%,--spacing(var(--other)))]'],
['pt-[calc(var(--spacing)*8)]', 'pt-8'],
['pt-[calc(var(--spacing)*var(--other))]', 'pt-[--spacing(var(--other))]'],
['max-w-[theme(screens.md)]', 'max-w-(--breakpoint-md)'],
['w-[theme(maxWidth.md)]', 'w-md'],
['leading-[1]', 'leading-none'],
['border-[2px]', 'border-2'],
['border-[1234px]', 'border-1234'],
['bg-[position:123px]', 'bg-position-[123px]'],
['bg-[size:123px]', 'bg-size-[123px]'],
['bg-[123px]', 'bg-position-[123px]'],
['w-[64rem]', 'w-256'],
['from-[25%]', 'from-25%'],
['from-[2.5%]', 'from-[2.5%]'],
['-mt-[12rem]', '-mt-48'],
['-mt-[-12rem]', 'mt-48'],
['-mt-[12.34rem]', 'mt-[-12.34rem]'],
['-mt-[-12.34rem]', 'mt-[12.34rem]'],
['-mt-[12.34px]', 'mt-[-12.34px]'],
['-mt-[-12.34px]', 'mt-[12.34px]'],
['-mt-[492px]', '-mt-123'],
['-mt-[calc(-1*492px)]', 'mt-123'],
['-mt-[-492px]', 'mt-123'],
['-mt-[calc(-1*-492px)]', '-mt-123'],
['-mt-(--my-var)', '-mt-(--my-var)'],
['-mt-[var(--my-var)]', '-mt-(--my-var)'],
['mt-[calc(var(--my-var)*-1)]', '-mt-(--my-var)'],
['mt-[calc(-1*var(--my-var))]', '-mt-(--my-var)'],
['-mt-[calc(var(--my-var)*-1)]', 'mt-(--my-var)'],
['-mt-[calc(-1*var(--my-var))]', 'mt-(--my-var)'],
['mt-[calc(-1*calc(-1*var(--my-var)))]', 'mt-(--my-var)'],
['-mt-[calc(-1*calc(-1*var(--my-var)))]', '-mt-(--my-var)'],
])(testName, { timeout }, async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
@theme {
--color-white: #fff;
}
`
await expectCanonicalization(input, candidate, expected)
})
})
describe('arbitrary utilities', () => {
test('migrate with custom static utility `@utility custom {…}`', { timeout }, async () => {
let candidate = '[--key:value]'
let expected = 'custom'
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
}
@utility custom {
--key: value;
}
`
await expectCanonicalization(input, candidate, expected)
})
test(
'migrate with custom functional utility `@utility custom-* {…}`',
{ timeout },
async () => {
let candidate = '[--key:value]'
let expected = 'custom-value'
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
}
@utility custom-* {
--key: --value('value');
}
`
await expectCanonicalization(input, candidate, expected)
},
)
test(
'migrate with custom functional utility `@utility custom-* {…}` that supports bare values',
{ timeout },
async () => {
let candidate = '[--resolved-value:4]'
let expected = 'example-4'
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
}
@utility example-* {
--resolved-value: --value(integer);
}
`
await expectCanonicalization(input, candidate, expected)
},
)
test.each([
['[--resolved-value:0]', 'example-0'],
['[--resolved-value:4]', 'example-4'],
['[--resolved-value:8]', 'example-a'],
['example-[0]', 'example-0'],
['example-[4]', 'example-4'],
['example-[8]', 'example-a'],
])(
'migrate custom @utility from arbitrary values to bare values and named values (based on theme)',
async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
--example-a: 8;
}
@utility example-* {
--resolved-value: --value(--example, integer, [integer]);
}
`
await expectCanonicalization(input, candidate, expected)
},
)
describe.each([['@theme'], ['@theme inline']])('%s', (theme) => {
test.each([
['[color:CanvasText]', 'text-canvas'],
['text-[CanvasText]', 'text-canvas'],
])(`migrate arbitrary value to theme value ${testName}`, async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
${theme} {
--*: initial;
--color-canvas: CanvasText;
}
`
await expectCanonicalization(input, candidate, expected)
})
test.each([
['max-w-(--breakpoint-md)', 'max-w-(--breakpoint-md)'],
['max-w-(--container-3xl)', 'max-w-3xl'],
])(
`migrate arbitrary value to theme value ${testName}`,
{ timeout },
async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
${theme} {
--*: initial;
--breakpoint-md: 48rem;
--container-3xl: 48rem;
}
`
await expectCanonicalization(input, candidate, expected)
},
)
test.each([
['[color:theme(colors.red.500/50%)]', 'text-red-500/[50%]'],
['[color:theme(colors.red.500/.12)]', 'text-red-500/[12%]'],
['[color:theme(colors.red.500/.29)]', 'text-red-500/[29%]'],
['[color:theme(colors.red.500/40%)]', 'text-red-500/[40%]'],
['[color:theme(colors.red.500/75%)]', 'text-red-500/75'],
['[color:theme(colors.red.500/.25)]', 'text-red-500/25'],
['[color:theme(colors.red.500/.3)]', 'text-red-500/30'],
])(
`migrate an inline \`theme(…)\` alpha to a modifier ${testName}`,
{ timeout },
async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
${theme} {
--*: initial;
--color-red-500: oklch(63.7% 0.237 25.331);
--opacity-12: 0.5;
--opacity-25: 25%;
--opacity-29: 0.5;
--opacity-40: var(--my-opacity);
--opacity-50: 10%;
--opacity-75: 0.75;
}
`
await expectCanonicalization(input, candidate, expected)
},
)
})
test(
'migrate an arbitrary property without spaces, to a theme value with spaces (canonicalization)',
{ timeout },
async () => {
let candidate = 'font-[foo,bar,baz]'
let expected = 'font-example'
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
--font-example: foo, bar, baz;
}
`
await expectCanonicalization(input, candidate, expected)
},
)
test.each([
['w-[64rem]', 'w-256', '0.25rem'],
['gap-[7.25rem]', 'gap-29', '0.25rem'],
['gap-[calc(7rem+0.25rem)]', 'gap-29', '0.25rem'],
['gap-[116px]', 'gap-29', '0.25rem'],
['gap-[7.25rem]', 'gap-29', '4px'],
['gap-[calc(7rem+0.25rem)]', 'gap-29', '4px'],
['gap-[116px]', 'gap-29', '4px'],
['gap-[7.25rem]', 'gap-116', '1px'],
['gap-[calc(7rem+0.25rem)]', 'gap-116', '1px'],
['gap-[116px]', 'gap-116', '1px'],
['w-[124px]', 'w-31', '0.25rem'],
['w-[0.123rem]', 'w-[0.123rem]', '0.25rem'],
['w-[123px]', 'w-123', '1px'],
['w-[256px]', 'w-128', '2px'],
])(`${testName} (spacing = \`%s\`)`, { timeout }, async (candidate, expected, spacing) => {
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
--spacing: ${spacing};
}
`
await expectCanonicalization(input, candidate, expected)
})
})
describe('bare values', () => {
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
--spacing: 0.25rem;
--aspect-video: 16 / 9;
--example-a: 8;
}
@utility example-* {
--resolved-value: --value(--example, integer);
}
`
test.each([
['aspect-16/9', 'aspect-video'],
['example-8', 'example-a'],
])(testName, { timeout }, async (candidate, expected) => {
await expectCanonicalization(input, candidate, expected)
})
})
describe('arbitrary variants', () => {
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
--breakpoint-lg: 64rem;
}
`
test.each([
['[&:focus]:flex', 'focus:flex'],
['[@media(scripting:_none)]:flex', 'noscript:flex'],
['[@media(scripting:none)]:flex', 'noscript:flex'],
['[@media(scripting:_none)]:flex', 'noscript:flex'],
['[@media_(scripting:_none)]:flex', 'noscript:flex'],
['[@media(width>=theme(screens.lg))]:flex', 'lg:flex'],
['[@media(width<theme(screens.lg))]:flex', 'max-lg:flex'],
['has-[&:focus]:flex', 'has-focus:flex'],
['not-[&:focus]:flex', 'not-focus:flex'],
['group-[&:focus]:flex', 'group-focus:flex'],
['peer-[&:focus]:flex', 'peer-focus:flex'],
['in-[&:focus]:flex', 'in-focus:flex'],
])(testName, { timeout }, async (candidate, expected) => {
await expectCanonicalization(input, candidate, expected)
})
test('unsafe migrations keep the candidate as-is', { timeout }, async () => {
let candidate = '[&:hover]:flex'
let expected = '[&:hover]:flex'
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
}
`
await expectCanonicalization(input, candidate, expected)
})
test('make unsafe migration safe (1)', { timeout }, async () => {
let candidate = '[&:hover]:flex'
let expected = 'hover:flex'
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
}
@variant hover (&:hover);
`
await expectCanonicalization(input, candidate, expected)
})
test('make unsafe migration safe (2)', { timeout }, async () => {
let candidate = '[&:hover]:flex'
let expected = 'hover:flex'
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
}
@variant hover {
&:hover {
@slot;
}
}
`
await expectCanonicalization(input, candidate, expected)
})
test('custom selector-based variants', { timeout }, async () => {
let candidate = '[&.macos]:flex'
let expected = 'is-macos:flex'
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
}
@variant is-macos (&.macos);
`
await expectCanonicalization(input, candidate, expected)
})
test('custom @media-based variants', { timeout }, async () => {
let candidate = '[@media(prefers-reduced-transparency:reduce)]:flex'
let expected = 'transparency-safe:flex'
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
}
@variant transparency-safe {
@media (prefers-reduced-transparency: reduce) {
@slot;
}
}
`
await expectCanonicalization(input, candidate, expected)
})
})
describe('drop unnecessary data types', () => {
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
--color-red-500: red;
}
`
test.each([
['bg-[color:#008cc]', 'bg-[#008cc]'],
['bg-(color:--my-value)', 'bg-(--my-value)'],
['bg-(color:--color-red-500)', 'bg-red-500'],
])(testName, { timeout }, async (candidate, expected) => {
await expectCanonicalization(input, candidate, expected)
})
})
describe('arbitrary value to bare value', () => {
test.each([
['aspect-[12/34]', 'aspect-12/34'],
['aspect-[1.2/34]', 'aspect-[1.2/34]'],
['col-start-[7]', 'col-start-7'],
['flex-[2]', 'flex-2'],
['grid-cols-[subgrid]', 'grid-cols-subgrid'],
['grid-rows-[subgrid]', 'grid-rows-subgrid'],
['m-[0]', 'm-0'],
['m-[0px]', 'm-0'],
['m-[0rem]', 'm-0'],
['-m-[0]', 'm-0'],
['-m-[0px]', 'm-0'],
['-m-[0rem]', 'm-0'],
['m-[-0]', 'm-0'],
['m-[-0px]', 'm-0'],
['m-[-0rem]', 'm-0'],
['-m-[-0]', 'm-0'],
['-m-[-0px]', 'm-0'],
['-m-[-0rem]', 'm-0'],
['[margin:0]', 'm-0'],
['[margin:-0]', 'm-0'],
['[margin:0px]', 'm-0'],
['left-[99999px]', 'left-[99999px]'],
['left-[-99999px]', 'left-[-99999px]'],
['left-[96rem]', 'left-384'],
['left-[-96rem]', '-left-384'],
['left-[calc(96rem+1px)]', 'left-[calc(96rem+1px)]'],
['left-[calc(-96rem-1px)]', 'left-[calc(-96rem-1px)]'],
['z-[9999999]', 'z-9999999'],
['[margin:0%]', 'm-[0%]'],
['font-stretch-[50%]', 'font-stretch-50%'],
['font-stretch-[50.5%]', 'font-stretch-[50.5%]'],
['font-stretch-[201%]', 'font-stretch-[201%]'],
['font-stretch-[49%]', 'font-stretch-[49%]'],
['font-stretch-[1/2]', 'font-stretch-[1/2]'],
['from-[28%]', 'from-28%'],
['via-[28%]', 'via-28%'],
['to-[28%]', 'to-28%'],
['from-[28.5%]', 'from-[28.5%]'],
['via-[28.5%]', 'via-[28.5%]'],
['to-[28.5%]', 'to-[28.5%]'],
['text-[1/2]', 'text-[1/2]'],
['leading-[123]', 'leading-[123]'],
['data-[selected]:flex', 'data-selected:flex'],
['data-[foo=bar]:flex', 'data-[foo=bar]:flex'],
['supports-[gap]:flex', 'supports-gap:flex'],
['supports-[display:grid]:flex', 'supports-[display:grid]:flex'],
['group-data-[selected]:flex', 'group-data-selected:flex'],
['group-data-[foo=bar]:flex', 'group-data-[foo=bar]:flex'],
['group-has-data-[selected]:flex', 'group-has-data-selected:flex'],
['aria-[selected]:flex', 'aria-[selected]:flex'],
['aria-[selected="true"]:flex', 'aria-selected:flex'],
['aria-[selected*="true"]:flex', 'aria-[selected*="true"]:flex'],
['group-aria-[selected]:flex', 'group-aria-[selected]:flex'],
['group-aria-[selected="true"]:flex', 'group-aria-selected:flex'],
['group-has-aria-[selected]:flex', 'group-has-aria-[selected]:flex'],
['max-lg:hover:data-[selected]:flex', 'max-lg:hover:data-selected:flex'],
[
'data-[selected]:aria-[selected="true"]:aspect-[12/34]',
'data-selected:aria-selected:aspect-12/34',
],
])(testName, { timeout }, async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
`
await expectCanonicalization(input, candidate, expected)
})
})
describe('media query and container query variants', () => {
test.each([
['min-[64rem]:flex', 'lg:flex'],
['max-[64rem]:flex', 'max-lg:flex'],
['min-[48rem]:flex', 'md:flex'],
['max-[48rem]:flex', 'max-md:flex'],
['min-[1024px]:flex', 'lg:flex'],
['max-[1024px]:flex', 'max-lg:flex'],
['@min-[28rem]:flex', '@md:flex'],
['@max-[28rem]:flex', '@max-md:flex'],
['@min-[448px]:flex', '@md:flex'],
['@max-[448px]:flex', '@max-md:flex'],
['min-[123px]:flex', 'min-[123px]:flex'],
['max-[123px]:flex', 'max-[123px]:flex'],
['@min-[123px]:flex', '@min-[123px]:flex'],
['@max-[123px]:flex', '@max-[123px]:flex'],
['min-lg:flex', 'min-lg:flex'],
['@min-md:flex', '@min-md:flex'],
])(testName, { timeout }, async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
`
await expectCanonicalization(input, candidate, expected)
})
test.each([
['min-[1024px]:flex', 'min-[1024px]:flex'],
['@min-[448px]:flex', '@min-[448px]:flex'],
['min-[64rem]:flex', 'lg:flex'],
['max-[64rem]:flex', 'max-lg:flex'],
['@min-[28rem]:flex', '@md:flex'],
['@max-[28rem]:flex', '@max-md:flex'],
])(`${testName} (no rem option)`, { timeout }, async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
`
await expectCanonicalization(input, candidate, expected, {
collapse: true,
logicalToPhysical: true,
})
})
})
describe('modernize arbitrary variants', () => {
test.each([
['[[data-visible]]:flex', 'data-visible:flex'],
['[&[data-visible]]:flex', 'data-visible:flex'],
['[[data-visible]&]:flex', 'data-visible:flex'],
['[&>[data-visible]]:flex', '*:data-visible:flex'],
['[&_>_[data-visible]]:flex', '*:data-visible:flex'],
['[&>*]:flex', '*:flex'],
['[&_>_*]:flex', '*:flex'],
['[&_>_[foo]]:flex', '*:[[foo]]:flex'],
['[&_[foo]]:flex', '**:[[foo]]:flex'],
['[&_>_[foo=bar]]:flex', '*:[[foo=bar]]:flex'],
['[&_[foo=bar]]:flex', '**:[[foo=bar]]:flex'],
['[&_[data-visible]]:flex', '**:data-visible:flex'],
['[&_*]:flex', '**:flex'],
['[&:first-child]:flex', 'first:flex'],
['[&:not(:first-child)]:flex', 'not-first:flex'],
['[&_:first-child]:flex', '**:first:flex'],
['[&_>_:first-child]:flex', '*:first:flex'],
['[&_:--custom]:flex', '**:[:--custom]:flex'],
['[&_>_:--custom]:flex', '*:[:--custom]:flex'],
['[&_::before]:flex', '**:[&::before]:flex'],
['[&_>_::before]:flex', '*:[&::before]:flex'],
['[&_:before]:flex', '**:[&:before]:flex'],
['[&_>_:before]:flex', '*:[&:before]:flex'],
['[&_:BEFORE]:flex', '**:[&:BEFORE]:flex'],
['[p_&]:flex', 'in-[p]:flex'],
['[.foo_&]:flex', 'in-[.foo]:flex'],
['[[data-visible]_&]:flex', 'in-data-visible:flex'],
['[[data-foo][data-bar]_&]:flex', '[[data-foo][data-bar]_&]:flex'],
['[figure>&]:my-0', '[figure>&]:my-0'],
['[&:nth-child(2)]:flex', 'nth-2:flex'],
['[&:not(:nth-child(2))]:flex', 'not-nth-2:flex'],
['[&:nth-child(-n+3)]:flex', 'nth-[-n+3]:flex'],
['[&:not(:nth-child(-n+3))]:flex', 'not-nth-[-n+3]:flex'],
['[&:nth-child(-n_+_3)]:flex', 'nth-[-n+3]:flex'],
['[&:not(:nth-child(-n_+_3))]:flex', 'not-nth-[-n+3]:flex'],
['[&:nth-last-child(2)]:flex', 'nth-last-2:flex'],
['[&:not(:nth-last-child(2))]:flex', 'not-nth-last-2:flex'],
['[&:nth-last-child(-n+3)]:flex', 'nth-last-[-n+3]:flex'],
['[&:not(:nth-last-child(-n+3))]:flex', 'not-nth-last-[-n+3]:flex'],
['[&:nth-last-child(-n_+_3)]:flex', 'nth-last-[-n+3]:flex'],
['[&:not(:nth-last-child(-n_+_3))]:flex', 'not-nth-last-[-n+3]:flex'],
['[&:nth-child(odd)]:flex', 'odd:flex'],
['[&:not(:nth-child(odd))]:flex', 'even:flex'],
['[&:nth-child(even)]:flex', 'even:flex'],
['[&:not(:nth-child(even))]:flex', 'odd:flex'],
['[[data-visible][data-dark]]:flex', '[[data-visible][data-dark]]:flex'],
['[:where([data-visible])]:flex', '[:where([data-visible])]:flex'],
['[[data-url*="example"]]:flex', 'data-[url*="example"]:flex'],
['[[data-url$=".com"_i]]:flex', 'data-[url$=".com"_i]:flex'],
['[[data-url$=.com_i]]:flex', 'data-[url$=.com_i]:flex'],
['[&:is([data-visible])]:flex', 'data-visible:flex'],
['[@media(pointer:fine)]:flex', 'pointer-fine:flex'],
['[@media_(pointer_:_fine)]:flex', 'pointer-fine:flex'],
['[@media_(pointer_:fine)]:flex', 'pointer-fine:flex'],
['[@media_not_(pointer_:_fine)]:flex', 'not-pointer-fine:flex'],
['[@media_print]:flex', 'print:flex'],
['[@media_not_print]:flex', 'not-print:flex'],
['[@media_not_(prefers-color-scheme:dark)]:flex', 'not-dark:flex'],
[
'[@media_not_(prefers-color-scheme:unknown)]:flex',
'not-[@media_(prefers-color-scheme:unknown)]:flex',
],
['has-[[data-visible]]:flex', 'has-data-visible:flex'],
['has-[&:is([data-visible])]:flex', 'has-data-visible:flex'],
['has-[&>[data-visible]]:flex', 'has-[&>[data-visible]]:flex'],
['has-[[data-slot=description]]:flex', 'has-data-[slot=description]:flex'],
['has-[&:is([data-slot=description])]:flex', 'has-data-[slot=description]:flex'],
['has-[[aria-visible="true"]]:flex', 'has-aria-visible:flex'],
['has-[[aria-visible]]:flex', 'has-aria-[visible]:flex'],
['has-[&:not(:nth-child(even))]:flex', 'has-odd:flex'],
['[&:has([role=checkbox])]:flex', 'has-[[role=checkbox]]:flex'],
['[&:has([aria-visible="true"])]:flex', 'has-aria-visible:flex'],
['[&:has([data-slot=description])]:flex', 'has-data-[slot=description]:flex'],
])(testName, { timeout }, async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
`
await expectCanonicalization(input, candidate, expected)
})
})
describe('optimize modifier', () => {
let input = css`
@import 'tailwindcss';
@theme {
--*: initial;
--color-red-500: red;
}
`
test.each([
['bg-red-500/25', 'bg-red-500/25'],
['bg-red-500/[25%]', 'bg-red-500/25'],
['bg-[#f00]/[0.16]', 'bg-[#f00]/16'],
['bg-red-500/[100%]', 'bg-red-500'],
['bg-red-500/100', 'bg-red-500'],
['group/name', 'group/name'],
])(testName, { timeout }, async (candidate, expected) => {
await expectCanonicalization(input, candidate, expected)
})
})
describe('combine to shorthand utilities', () => {
test.each([
['mt-1 mr-1 mb-1 ml-1', 'm-1'],
['border-t-123 border-r-123 border-b-123 border-l-123', 'border-123'],
['border-t-1 border-r-1 border-b-1 border-l-1', 'border'],
['border-t-red-500 border-r-red-500 border-b-red-500 border-l-red-500', 'border-red-500'],
['scroll-mt-1 scroll-mr-1 scroll-mb-1 scroll-ml-1', 'scroll-m-1'],
['scroll-pt-1 scroll-pr-1 scroll-pb-1 scroll-pl-1', 'scroll-p-1'],
['mt-1 mb-1', 'my-1'],
['border-t-123 border-b-123', 'border-y-123'],
['border-t-1 border-b-1', 'border-y'],
['border-t-red-500 border-b-red-500', 'border-y-red-500'],
['scroll-mt-1 scroll-mb-1', 'scroll-my-1'],
['scroll-pt-1 scroll-pb-1', 'scroll-py-1'],
['overflow-x-hidden overflow-y-hidden', 'overflow-hidden'],
['overscroll-x-contain overscroll-y-contain', 'overscroll-contain'],
['mb-1 mt-1', 'my-1'],
['w-4 h-4', 'size-4'],
['w-123 h-123', 'size-123'],
['w-128 h-128', 'size-128'],
['mt-123 mb-123', 'my-123'],
['w-8 w-8', 'w-8'],
['w-[calc(1rem+0.25rem)] h-[calc(1rem+0.25rem)] size-5', 'size-5'],
['w-[calc(1rem+0.25rem)] h-[calc(1rem+0.25rem)] size-5 flex', 'size-5 flex'],
['hover:w-4 h-4', 'hover:w-4 h-4'],
['[width:_16px_] [height:16px]', 'size-4'],
['[font-size:14px] [line-height:1.625]', 'text-sm/relaxed'],
])(testName, { timeout }, async (candidates, expected) => {
let input = css`
@import 'tailwindcss';
`
await expectCanonicalization(input, candidates, expected)
})
})
describe('font-size/line-height to text-{x}/{y}', () => {
test.each([
...Array.from(
cartesian(
['[font-size:14px]', 'text-[14px]', 'text-[14px]/6', 'text-sm', 'text-sm/6'],
['[line-height:28px]', 'leading-[28px]', 'leading-7'],
),
).map((classes) => [classes.join(' ').padEnd(40, ' '), 'text-sm/7']),
...Array.from(
cartesian(
['[font-size:15px]', 'text-[15px]', 'text-[15px]/6'],
['[line-height:28px]', 'leading-[28px]', 'leading-7'],
),
).map((classes) => [classes.join(' ').padEnd(40, ' '), 'text-[15px]/7']),
...Array.from(
cartesian(
['[font-size:14px]', 'text-[14px]', 'text-[14px]/6', 'text-sm', 'text-sm/6'],
['[line-height:28.5px]', 'leading-[28.5px]'],
),
).map((classes) => [classes.join(' ').padEnd(40, ' '), 'text-sm/[28.5px]']),
...Array.from(
cartesian(
['[font-size:15px]', 'text-[15px]', 'text-[15px]/6'],
['[line-height:28.5px]', 'leading-[28.5px]'],
),
).map((classes) => [classes.join(' ').padEnd(40, ' '), 'text-[15px]/[28.5px]']),
])(testName, { timeout }, async (candidates, expected) => {
let input = css`
@import 'tailwindcss';
`
await expectCanonicalization(input, candidates.trim(), expected)
})
})
describe('escapes', () => {
test.each([
["bg-[u\\72l('a.png')]", "bg-[url('a.png')]"],
["bg-[\\75rl('a.png')]", "bg-[url('a.png')]"],
["bg-[\\000075rl('a.png')]", "bg-[url('a.png')]"],
["bg-[u\\72_l('a.png')]", "bg-[url('a.png')]"],
["bg-[\\75_rl('a.png')]", "bg-[url('a.png')]"],
["bg-[u\\rl('a.png')]", "bg-[url('a.png')]"],
['[\\63olor:red]', 'text-[red]'],
['[color:\\72_ed]', 'text-[red]'],
['[&_.f\\6f_o]:flex', '[&_.foo]:flex'],
['[&_.a\\31]:flex', '[&_.a1]:flex'],
['[&_.a\\-b]:flex', '[&_.a-b]:flex'],
['[&_.\\-a]:flex', '[&_.-a]:flex'],
['bg-red-500/[m\\69n(50%,60%)]', 'bg-red-500/[min(50%,60%)]'],
['[&_.a\\_b]:flex', '[&_.a\\_b]:flex'],
["content-['\\61']", "content-['\\61']"],
['content-["\\61"]', 'content-["\\61"]'],
['[&_.a\\,b]:flex', '[&_.a\\,b]:flex'],
['[&_.a\\2c_b]:flex', '[&_.a\\2c_b]:flex'],
['[&_.\\31_0]:flex', '[&_.\\31_0]:flex'],
['[&_.\\-1]:flex', '[&_.\\-1]:flex'],
['[&_.-\\31]:flex', '[&_.-\\31]:flex'],
['content-[1\\65_3]', 'content-[1\\65_3]'],
['[&_.\\31\\61]:flex', '[&_.\\31\\61]:flex'],
['[&_.\\31\\67]:flex', '[&_.\\31g]:flex'],
['content-[-\\->]', 'content-[-\\->]'],
['content-[<!--\\2d]', 'content-[<!--\\2d]'],
['bg-[url(\\61_b.png)]', 'bg-[url(\\61_b.png)]'],
['bg-[u\\72l(a_b.png)]', 'bg-[u\\72l(a_b.png)]'],
["bg-[u\\72l('a_b.png')]", "bg-[u\\72l('a_b.png')]"],
['[co\\6c_or:red]', '[co\\6c_or:red]'],
])(testName, { timeout }, async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
`
await expectCanonicalization(input, candidate, expected)
})
})
test.each([
['tracking-[-0.05em]', 'tracking-tighter'],
['tracking-[-0.025em]', 'tracking-tight'],
['tracking-[0em]', 'tracking-normal'],
['tracking-[0.025em]', 'tracking-wide'],
['tracking-[0.05em]', 'tracking-wider'],
['tracking-[0.1em]', 'tracking-widest'],
['-tracking-tighter', 'tracking-wider'],
['-tracking-tight', 'tracking-wide'],
['-tracking-normal', 'tracking-normal'],
['-tracking-wide', 'tracking-tight'],
['-tracking-wider', 'tracking-tighter'],
])(testName, { timeout }, async (candidate, expected) => {
await expectCanonicalization(
css`
@import 'tailwindcss';
@theme {
--tracking-tighter: -0.05em;
--tracking-tight: -0.025em;
--tracking-normal: 0em;
--tracking-wide: 0.025em;
--tracking-wider: 0.05em;
--tracking-widest: 0.1em;
}
`,
candidate,
expected,
)
})
test.each([
['[&:has(~_*_*:checked)]:flex', '[&:has(~_*_*:checked)]:flex'],
[
'shadow-[inset_0px_1px_--theme(--color-white/15%)]',
'shadow-[inset_0px_1px_--theme(--color-white/15%)]',
],
['[--foo:_]', '[--foo:_]'],
['w-[calc(100%_-_calc(var(--spacing)*60))]', 'w-[calc(100%-(--spacing(60)))]'],
['w-[calc(100%_-_--spacing(60))]', 'w-[calc(100%-(--spacing(60)))]'],
['m-[min(100%,_--spacing(6))]', 'm-[min(100%,--spacing(6))]'],
['m-[min(100%_,_--spacing(6))]', 'm-[min(100%,--spacing(6))]'],
['m-[min(100%,--spacing(6))]', 'm-[min(100%,--spacing(6))]'],
])(testName, async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
`
await expectCanonicalization(input, candidate, expected)
})
test.each([
['-mt-[0.04in]', 'mt-[-0.04in]'],
['mt-[-0.04in]', 'mt-[-0.04in]'],
['-mt-[-0.04in]', 'mt-[0.04in]'],
])(testName, { timeout }, async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
`
await expectCanonicalization(input, candidate, expected)
})
test.each([
['w-[calc(100%/3.5)]', 'w-[calc(100%/3.5)]'],
])(testName, { timeout }, async (candidate, expected) => {
let input = css`
@import 'tailwindcss';
`
await expectCanonicalization(input, candidate, expected)
})
})
describe('theme to var', () => {
test('extended space scale converts to var or calc', { timeout }, async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
@theme {
--spacing: 0.25rem;
--spacing-2: 2px;
--spacing-miami: 0.875rem;
}
`,
{ base: __dirname },
)
expect(
designSystem.canonicalizeCandidates([
'[--value:theme(spacing.1)]',
'[--value:theme(spacing.2)]',
'[--value:theme(spacing.miami)]',
'[--value:theme(spacing.nyc)]',
]),
).toEqual([
'[--value:--spacing(1)]',
'[--value:var(--spacing-2)]',
'[--value:var(--spacing-miami)]',
'[--value:theme(spacing.nyc)]',
])
})
test('custom space scale converts to var', { timeout }, async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
@theme {
--spacing-*: initial;
--spacing-1: 0.25rem;
--spacing-2: 0.5rem;
}
`,
{ base: __dirname },
)
expect(
designSystem.canonicalizeCandidates([
'[--value:theme(spacing.1)]',
'[--value:theme(spacing.2)]',
'[--value:theme(spacing.3)]',
]),
).toEqual([
'[--value:var(--spacing-1)]',
'[--value:var(--spacing-2)]',
'[--value:theme(spacing.3)]',
])
})
})
describe('options', () => {
test('normalize `rem` units to `px`', { timeout }, async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
@theme {
--spacing: 0.25rem;
}
`,
{ base: __dirname },
)
expect(designSystem.canonicalizeCandidates(['m-[16px]'])).toEqual(['m-[16px]'])
expect(designSystem.canonicalizeCandidates(['m-[16px]'], { rem: 16 })).toEqual(['m-4'])
expect(designSystem.canonicalizeCandidates(['m-[16px]'], { rem: 64 })).toEqual(['m-1'])
expect(designSystem.canonicalizeCandidates(['m-[16px]'])).toEqual(['m-[16px]'])
})
})
describe('regressions', () => {
test(
'collapsing keeps the winning candidate instead of a theme value that only matches by default',
{ timeout },
async () => {
let designSystem = await designSystems.get(__dirname).get(css`
@import 'tailwindcss';
@theme {
--color-foreground: black;
--color-primary: red;
--color-card-checked-border: red;
}
`)
let options: CanonicalizeOptions = {
collapse: true,
logicalToPhysical: true,
rem: 16,
}
expect(
designSystem.canonicalizeCandidates(['text-foreground', 'text-primary'], options),
).toEqual(['text-primary'])
expect(
designSystem.canonicalizeCandidates(['text-card-checked-border', 'text-primary'], options),
).toEqual(['text-primary'])
expect(
designSystem.canonicalizeCandidates(['text-[red]', 'text-card-checked-border'], options),
).toEqual(['text-card-checked-border'])
},
)
test(
'collapsing does not replace a theme variable with another one that only matches by default',
{ timeout },
async () => {
let designSystem = await designSystems.get(__dirname).get(css`
@import 'tailwindcss';
@theme {
--spacing-card: 1rem;
--spacing-other: 1rem;
}
`)
let options: CanonicalizeOptions = {
collapse: true,
logicalToPhysical: true,
rem: 16,
}
expect(designSystem.canonicalizeCandidates(['mt-card', 'mb-card'], options)).toEqual([
'my-card',
])
expect(designSystem.canonicalizeCandidates(['w-card', 'h-card'], options)).toEqual([
'size-card',
])
expect(designSystem.canonicalizeCandidates(['mt-card', 'mb-other'], options)).toEqual([
'mt-card',
'mb-other',
])
expect(designSystem.canonicalizeCandidates(['w-card', 'h-other'], options)).toEqual([
'w-card',
'h-other',
])
expect(designSystem.canonicalizeCandidates(['mt-card', 'mb-4'], options)).toEqual([
'mt-card',
'mb-4',
])
expect(designSystem.canonicalizeCandidates(['p-card', 'px-other'], options)).toEqual([
'p-card',
'px-other',
])
},
)
{
test('a subset of classes should be canonicalizable', { timeout }, async () => {
let designSystem = await designSystems.get(__dirname).get(css`
@import 'tailwindcss';
`)
let options: CanonicalizeOptions = {
collapse: true,
logicalToPhysical: true,
rem: 16,
}
expect(
designSystem.canonicalizeCandidates(['underline', 'h-4', 'w-4', 'text-sm'], options),
).toEqual(['underline', 'text-sm', 'size-4'])
})
test('collapse canonicalization is not affected by previous calls', { timeout }, async () => {
let designSystem = await designSystems.get(__dirname).get(css`
@import 'tailwindcss';
`)
let options: CanonicalizeOptions = {
collapse: true,
logicalToPhysical: true,
rem: 16,
}
let target = ['underline', 'h-4', 'w-4']
expect(designSystem.canonicalizeCandidates(target, options)).toEqual(['underline', 'size-4'])
designSystem.canonicalizeCandidates(['mb-4', 'text-sm'], options)
designSystem.canonicalizeCandidates(['underline', 'mb-4'], options)
expect(designSystem.canonicalizeCandidates(target, options)).toEqual(['underline', 'size-4'])
expect(designSystem.canonicalizeCandidates(target.concat('text-sm'), options)).toEqual([
'underline',
'text-sm',
'size-4',
])
})
}
test(
'collapse does not try every combination of candidates linked by a utility that sets many properties',
{ timeout },
async () => {
let designSystem = await designSystems.get(__dirname).get(css`
@import 'tailwindcss';
@utility pill {
position: relative;
display: inline-flex;
align-items: center;
gap: 0.5rem;
height: 2rem;
padding: 0.25rem 0.75rem;
margin: 0;
border-radius: 9999px;
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 500;
color: white;
background-color: black;
white-space: nowrap;
overflow: hidden;
cursor: pointer;
}
`)
let candidates = [
'relative',
'mt-1',
'mr-2',
'mb-3',
'ml-4',
'pt-1',
'pr-2',
'pb-3',
'pl-4',
'w-64',
'h-10',
'overflow-x-auto',
'overflow-y-hidden',
'whitespace-nowrap',
'flex',
'items-center',
'gap-2.5',
'rounded-full',
'bg-white',
'cursor-pointer',
'font-normal',
'text-sm',
'leading-5',
]
let start = performance.now()
let result = designSystem.canonicalizeCandidates(candidates, DEFAULT_CANONICALIZATION_OPTIONS)
let duration = performance.now() - start
expect(result).toEqual([
...candidates.filter((candidate) => candidate !== 'text-sm' && candidate !== 'leading-5'),
'text-sm/5',
])
expect(duration).toBeLessThan(5_000)
},
)
test(
'collapse does not crash when utilities with no standard properties are present',
{ timeout },
async () => {
let designSystem = await designSystems.get(__dirname).get(css`
@import 'tailwindcss';
`)
let options: CanonicalizeOptions = {
collapse: true,
logicalToPhysical: true,
rem: 16,
}
expect(() =>
designSystem.canonicalizeCandidates(['shadow-sm', 'border'], options),
).not.toThrow()
expect(() => designSystem.canonicalizeCandidates(['shadow-md', 'p-4'], options)).not.toThrow()
expect(() =>
designSystem.canonicalizeCandidates(['shadow-sm', 'shadow-md'], options),
).not.toThrow()
expect(designSystem.canonicalizeCandidates(['shadow-sm', 'border'], options)).toEqual(
expect.arrayContaining(['shadow-sm', 'border']),
)
expect(designSystem.canonicalizeCandidates(['shadow-sm', 'shadow-md'], options)).toEqual(
expect.arrayContaining(['shadow-sm', 'shadow-md']),
)
},
)
test.each([
[
['px-[1.2rem]', 'py-[1.2rem]', 'text-left'],
['text-left', 'p-[1.2rem]'],
],
[
['px-[30.75rem]', 'py-[30.75rem]', 'text-left'],
['text-left', 'p-123'],
],
])(
'collapse canonicalization works for arbitrary values',
{ timeout },
async (candidates, expected) => {
let designSystem = await designSystems.get(__dirname).get(css`
@import 'tailwindcss';
`)
let options: CanonicalizeOptions = {
collapse: true,
logicalToPhysical: true,
rem: 16,
}
expect(designSystem.canonicalizeCandidates(candidates, options)).toEqual(expected)
},
)
test(
'does not crash when plugin matchComponents rejects speculative values during collapse',
{ timeout },
async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@import 'tailwindcss';
@plugin "./plugin.js";
`,
{
async loadStylesheet(_, base) {
return {
base,
path: '',
content: '@tailwind utilities;',
}
},
async loadModule() {
return {
base: '',
path: '',
module: plugin(({ matchComponents }) => {
matchComponents(
{
myicon: () => {
throw new Error('Mimic as-if a custom plugin failed for some reason')
},
},
{ values: { icon: __filename } },
)
}),
}
},
},
)
expect(
designSystem.canonicalizeCandidates(['border-[1.5px]', 'flex'], {
collapse: true,
logicalToPhysical: true,
rem: 16,
}),
).toEqual(expect.arrayContaining(['border-[1.5px]', 'flex']))
},
)
test(
'does not crash when a plugin utility throws for one of the candidates during collapse',
{ timeout },
async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@import 'tailwindcss';
@plugin "./plugin.js";
`,
{
async loadStylesheet(_, base) {
return {
base,
path: '',
content: '@tailwind utilities;',
}
},
async loadModule() {
return {
base: '',
path: '',
module: plugin(({ matchUtilities }) => {
matchUtilities(
{
boom: (value) => {
if (value === 'bad') {
throw new Error('Mimic as-if a custom plugin failed for some reason')
}
return { color: value }
},
},
{ values: { bad: 'bad', good: 'red' } },
)
}),
}
},
},
)
expect(
designSystem.canonicalizeCandidates(['boom-bad', 'mt-[1px]', 'mb-[1px]'], {
collapse: true,
logicalToPhysical: true,
rem: 16,
}),
).toEqual(['boom-bad', 'my-px'])
},
)
test(
'does not crash when only another meaning of a linked candidate throws during collapse',
{ timeout },
async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@import 'tailwindcss';
@plugin "./plugin.js";
`,
{
async loadStylesheet(_, base) {
return {
base,
path: '',
content: '@tailwind utilities;',
}
},
async loadModule() {
return {
base: '',
path: '',
module: plugin(({ addUtilities, matchUtilities }) => {
addUtilities({
'.boom-bad': { color: 'red' },
'.safe': { color: 'red' },
})
matchUtilities(
{
boom: (value) => {
if (value === 'bad') {
throw new Error('Mimic as-if a custom plugin failed for some reason')
}
return { color: value }
},
},
{ values: { bad: 'bad', good: 'red' } },
)
}),
}
},
},
)
expect(
designSystem.canonicalizeCandidates(['boom-bad', 'safe', 'mt-[1px]', 'mb-[1px]'], {
collapse: true,
logicalToPhysical: true,
rem: 16,
}),
).toEqual(['boom-bad', 'safe', 'my-px'])
},
)
test('does not suggest invalid alternative when canonicalizing calc expressions', async () => {
let designSystem = await designSystems.get(__dirname).get(css`
@import 'tailwindcss';
`)
let options: CanonicalizeOptions = {
collapse: true,
logicalToPhysical: true,
rem: 16,
}
expect(designSystem.canonicalizeCandidates(['px-[calc(1rem+0px)]'], options)).toEqual(['px-4'])
})
test('canonicalizations work when casing of arbitrary values is different', async () => {
let designSystem = await designSystems.get(__dirname).get(css`
@import 'tailwindcss';
@theme {
--color-brand-purple: #3f3cbb;
}
`)
let options: CanonicalizeOptions = {
collapse: true,
logicalToPhysical: true,
rem: 16,
}
expect(designSystem.canonicalizeCandidates(['bg-[#3F3cbb]'], options)).toEqual([
'bg-brand-purple',
])
expect(designSystem.canonicalizeCandidates(['bg-[#3F3Cbb]'], options)).toEqual([
'bg-brand-purple',
])
expect(designSystem.canonicalizeCandidates(['bg-[#3F3CBB]'], options)).toEqual([
'bg-brand-purple',
])
})
test('canonicalizes min/max media query and container query variants', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
@theme {
--breakpoint-lg: 64rem;
--container-lg: 32rem;
--spacing: 0.25rem;
}
`,
{ base: __dirname },
)
expect(designSystem.canonicalizeCandidates(['min-[64rem]:flex'])).toEqual(['lg:flex'])
expect(designSystem.canonicalizeCandidates(['max-[64rem]:flex'])).toEqual(['max-lg:flex'])
expect(designSystem.canonicalizeCandidates(['@min-[32rem]:flex'])).toEqual(['@lg:flex'])
expect(designSystem.canonicalizeCandidates(['@max-[32rem]:flex'])).toEqual(['@max-lg:flex'])
expect(designSystem.canonicalizeCandidates(['min-[1024px]:flex'], { rem: 16 })).toEqual([
'lg:flex',
])
})
test('does not merge utilities whose theme variables resolve to CSS-wide keywords', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
@theme {
--foreground: unset;
--default: unset;
}
@theme inline {
--color-foreground: var(--foreground);
--color-default-soft-hover: color-mix(in oklab, var(--default) 60%, transparent);
}
`,
{ base: __dirname },
)
expect(
designSystem.canonicalizeCandidates(['text-foreground/60', 'text-default-soft-hover']),
).toEqual(['text-foreground/60', 'text-default-soft-hover'])
})
test('keeps `--tw-*` declarations that are not related to a sibling with the same value', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
@theme {
--spacing: 0.25rem;
}
@utility link {
margin-top: 16px;
--tw-translate-x: 16px;
}
`,
{ base: __dirname },
)
let options: CanonicalizeOptions = { rem: 16, collapse: true }
expect(designSystem.canonicalizeCandidates(['link', 'mt-4'], options)).toEqual(['link', 'mt-4'])
expect(
designSystem.canonicalizeCandidates(
['link', 'mt-[16px]', '[--tw-translate-x:16px]'],
options,
),
).toEqual(['link', 'mt-4'])
})
test('does not sort the parsed variants when compiling a single candidate', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
@plugin "my-plugin";
`,
{
async loadModule() {
return {
path: '',
base: '',
module: plugin(({ matchVariant }) => {
let values = Object.fromEntries(
Array.from({ length: 250 }, (_, i) => [`value-${i}`, `.value-${i}`]),
)
matchVariant('foo', (value) => `&:has(${value})`, { values })
}),
}
},
},
)
using compare = vi.spyOn(designSystem.variants, 'compare')
expect(designSystem.canonicalizeCandidates(['foo-[.value-42]:flex'])).toEqual([
'foo-value-42:flex',
])
expect(compare).not.toHaveBeenCalled()
})
test('does not treat different `@scope` variants as the same', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
@custom-variant in-blue {
@scope ([data-theme='blue']) to ([data-theme]) {
@slot;
}
}
`,
{ base: __dirname },
)
expect(designSystem.canonicalizeCandidates(['[@scope_(.card)]:flex'])).toEqual([
'[@scope_(.card)]:flex',
])
expect(
designSystem.canonicalizeCandidates([
"[@scope_([data-theme='blue'])_to_([data-theme])]:flex",
]),
).toEqual(['in-blue:flex'])
})
test('does not treat a descendant combinator in an at-rule as a compound selector', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
@custom-variant in-foo-bar {
@scope (.foo.bar) {
@slot;
}
}
@custom-variant supports-foo-bar {
@supports selector(.foo.bar) {
@slot;
}
}
@custom-variant in-foo-plus-bar {
@scope (.foo\+.bar) {
@slot;
}
}
@custom-variant in-foo-hex-plus-bar {
@scope (.foo\2b .bar) {
@slot;
}
}
@custom-variant in-foo-hex-plus-child-bar {
@scope (.foo\2b>.bar) {
@slot;
}
}
`,
{ base: __dirname },
)
expect(
designSystem.canonicalizeCandidates([
'[@scope_(.foo_.bar)]:flex',
'[@supports_selector(.foo_.bar)]:flex',
]),
).toEqual(['[@scope_(.foo_.bar)]:flex', '[@supports_selector(.foo_.bar)]:flex'])
expect(
designSystem.canonicalizeCandidates([
'[@scope_(.foo.bar)]:flex',
'[@supports_selector(.foo.bar)]:flex',
]),
).toEqual(['in-foo-bar:flex', 'supports-foo-bar:flex'])
expect(designSystem.canonicalizeCandidates(['[@scope_(.foo\\+_.bar)]:flex'])).toEqual([
'[@scope_(.foo\\+_.bar)]:flex',
])
expect(designSystem.canonicalizeCandidates(['[@scope_(.foo\\+.bar)]:flex'])).toEqual([
'in-foo-plus-bar:flex',
])
expect(designSystem.canonicalizeCandidates(['[@scope_(.foo\\2b__.bar)]:flex'])).toEqual([
'[@scope_(.foo\\2b__.bar)]:flex',
])
expect(designSystem.canonicalizeCandidates(['[@scope_(.foo\\2b_.bar)]:flex'])).toEqual([
'in-foo-hex-plus-bar:flex',
])
expect(
designSystem.canonicalizeCandidates([
'[@scope_(.foo\\2b>.bar)]:flex',
'[@scope_(.foo\\2b_>.bar)]:flex',
'[@scope_(.foo\\2b__>_.bar)]:flex',
]),
).toEqual(['in-foo-hex-plus-child-bar:flex'])
})
test('treats CRLF after a hex escape in an at-rule as one whitespace character', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
@plugin "my-plugin";
`,
{
async loadModule() {
return {
path: '',
base: '',
module: plugin(({ addVariant }) => {
addVariant('in-foo-hex-plus-bar', '@scope (.foo\\2b\r\n.bar) to (.limit)')
}),
}
},
},
)
expect(
designSystem.canonicalizeCandidates(['[@scope_(.foo\\2b__.bar)_to_(.limit)]:flex']),
).toEqual(['[@scope_(.foo\\2b__.bar)_to_(.limit)]:flex'])
expect(
designSystem.canonicalizeCandidates(['[@scope_(.foo\\2b_.bar)_to_(.limit)]:flex']),
).toEqual(['in-foo-hex-plus-bar:flex'])
})
test('reuses dynamic utility lookups across candidate collapse groups', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
@theme {
--spacing: 0.25rem;
}
`,
{ base: __dirname },
)
let options: CanonicalizeOptions = {
collapse: true,
logicalToPhysical: true,
rem: 16,
}
designSystem.canonicalizeCandidates(['mt-2'], options)
using keysSpy = vi.spyOn(designSystem.utilities, 'keys')
expect(
designSystem.canonicalizeCandidates(
['mt-2', 'mb-2', 'hover:mt-2', 'hover:mb-2', 'focus:mt-2', 'focus:mb-2'],
options,
),
).toEqual(['my-2', 'hover:my-2', 'focus:my-2'])
let functionalKeysCalls = keysSpy.mock.calls.filter((args) => args[0] === 'functional').length
expect(functionalKeysCalls).toBe(2)
let countBefore = keysSpy.mock.calls.length
expect(designSystem.canonicalizeCandidates(['active:mt-2', 'active:mb-2'], options)).toEqual([
'active:my-2',
])
let countAfter = keysSpy.mock.calls.length
expect(countAfter).toBe(countBefore)
})
})
describe('normalizeEscapes', () => {
const PIECES = [
...['a', 'e', 'f', 'g', 'r', 'u', 'l', 'c', '0', '1', '5', '-', '-', '_', '_'],
...['.', '(', ')', ',', '%', '>', '<!', "'q'", "'_'", '#'],
...['\\61', '\\72', '\\31', '\\2d', '\\-', '\\65', '\\66', '\\67', '\\_', '\\,', '\\5f'],
...['\\000072', '\\0000311', '\\61_', '\\31_', '\\2d_', '\\65_', '\\72_', '\\g', '\\\\'],
...['url(', 'u\\72l(', 'var(', 'calc(', 'v\\61r('],
]
function minify(css: string) {
try {
return transform({
filename: 'input.css',
code: Buffer.from(css),
minify: true,
}).code.toString()
} catch {
return null
}
}
test('keeps the CSS the same', { timeout }, async () => {
let designSystem = await __unstable__loadDesignSystem('@tailwind utilities;')
let seed = 1
function random(max: number) {
seed = (seed * 1103515245 + 12345) & 0x7fffffff
return seed % max
}
let forms: [(value: string) => string, (candidate: any) => string][] = [
[(value) => `content-[${value}]`, (candidate) => `.x{foo:${candidate.value.value}}`],
[(value) => `[${value}:red]`, (candidate) => `.x{${candidate.property}:red}`],
[
(value) => `[&_.${value}]:flex`,
(candidate) => `.x{${candidate.variants[0].selector.replace('&', '.y')}{a:b}}`,
],
]
let replaced = 0
let failures: string[] = []
for (let i = 0; i < 20_000; i++) {
let value = ''
for (let j = 0, length = 1 + random(7); j < length; j++) {
value += PIECES[random(PIECES.length)]
}
for (let [toCandidate, toCss] of forms) {
let before = toCandidate(value)
let after = normalizeEscapes(before)
if (before === after) continue
let [beforeCandidate] = designSystem.parseCandidate(before)
let [afterCandidate] = designSystem.parseCandidate(after)
if (!beforeCandidate || !afterCandidate) continue
let beforeCss = minify(toCss(beforeCandidate))
let afterCss = minify(toCss(afterCandidate))
if (beforeCss !== afterCss) {
failures.push(`${before} → ${after}: ${beforeCss} → ${afterCss}`)
} else if (beforeCss !== null) {
replaced++
}
}
}
expect(failures).toEqual([])
expect(replaced).toBeGreaterThan(5_000)
})
})
describe('intersection', () => {
function withoutNative<T>(set: Set<T>): Set<T> {
return Object.assign(set, { intersection: undefined })
}
test('polyfill keeps only the items that are in both sets', () => {
let a = withoutNative(new Set([1, 2, 3, 4]))
let b = new Set([3, 4, 5, 6])
expect(intersection(a, b)).toEqual(new Set([3, 4]))
expect(intersection(withoutNative(new Set(b)), a)).toEqual(new Set([3, 4]))
})
test('polyfill returns an empty set when the sets are disjoint', () => {
expect(intersection(withoutNative(new Set([1, 2])), new Set([3, 4]))).toEqual(new Set())
})
test('polyfill returns an empty set when one of the sets is empty', () => {
expect(intersection(withoutNative(new Set<number>()), new Set([1]))).toEqual(new Set())
expect(intersection(withoutNative(new Set([1])), new Set<number>())).toEqual(new Set())
})
test('polyfill does not mutate the input sets', () => {
let a = withoutNative(new Set([1, 2, 3]))
let b = new Set([2, 3, 4])
intersection(a, b)
expect(a).toEqual(new Set([1, 2, 3]))
expect(b).toEqual(new Set([2, 3, 4]))
})
test('native and polyfill implementations agree', () => {
let a = new Set(['a', 'b', 'c', 'd'])
let b = new Set(['b', 'd', 'e'])
expect(intersection(withoutNative(new Set(a)), b)).toEqual(intersection(a, b))
})
})