Skip to content

fix: don't break CSS keywords when formatting math expressions #18220

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

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ describe('adds spaces around math operators', () => {
['calc(theme(spacing.foo-2))', 'calc(theme(spacing.foo-2))'],
['calc(theme(spacing.foo-bar))', 'calc(theme(spacing.foo-bar))'],

// Preserving CSS keyword tokens like fit-content without splitting around hyphens in complex expressions
['min(fit-content,calc(100dvh-4rem))', 'min(fit-content, calc(100dvh - 4rem))'],
['min(theme(spacing.foo-bar),fit-content,calc(20*calc(40-30)))', 'min(theme(spacing.foo-bar), fit-content, calc(20 * calc(40 - 30)))'],
['min(fit-content,calc(100dvh-4rem)-calc(50dvh--2px))', 'min(fit-content, calc(100dvh - 4rem) - calc(50dvh - -2px))'],

// A negative number immediately after a `,` should not have spaces inserted
['clamp(-3px+4px,-3px+4px,-3px+4px)', 'clamp(-3px + 4px, -3px + 4px, -3px + 4px)'],

Expand Down
7 changes: 7 additions & 0 deletions packages/tailwindcss/src/utils/math-operators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ export function addWhitespaceAroundMathOperators(input: string) {
else if ((char === '+' || char === '*' || char === '/' || char === '-') && formattable[0]) {
let trimmed = result.trimEnd()
let prev = trimmed[trimmed.length - 1]
let next = input[i + 1]

// If we're preceded by an operator don't add spaces
if (prev === '+' || prev === '*' || prev === '/' || prev === '-') {
Expand All @@ -124,6 +125,12 @@ export function addWhitespaceAroundMathOperators(input: string) {
continue
}

// If there's no number/operator before or after it and it's not followed by a math function, don't add spaces
else if (!/\d/.test(prev + next) && !/^[a-zA-Z_$][a-zA-Z0-9_$]*\(/.test(input.slice(i + 1)) && next !== '(' && next !== '+' && next !== '-') {
result += char
continue
}

// Add spaces only after the operator if we already have spaces before it
else if (input[i - 1] === ' ') {
result += `${char} `
Expand Down
Loading