Skip to content

Implement better calc(…) evaluation for completions and equivalents #1316

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 5 commits into from
Apr 23, 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
5 changes: 3 additions & 2 deletions packages/tailwindcss-language-service/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@
"test": "vitest"
},
"dependencies": {
"@csstools/css-parser-algorithms": "2.1.1",
"@csstools/css-tokenizer": "2.1.1",
"@csstools/css-calc": "2.1.2",
"@csstools/css-parser-algorithms": "3.0.4",
"@csstools/css-tokenizer": "3.0.3",
"@csstools/media-query-list-parser": "2.0.4",
"@types/culori": "^2.1.0",
"@types/moo": "0.5.3",
Expand Down
66 changes: 20 additions & 46 deletions packages/tailwindcss-language-service/src/util/rewriting/calc.ts
Original file line number Diff line number Diff line change
@@ -1,56 +1,30 @@
function parseLength(length: string): [number, string] | null {
let regex = /^(-?\d*\.?\d+)([a-z%]*)$/i
let match = length.match(regex)

if (!match) return null

let numberPart = parseFloat(match[1])
if (isNaN(numberPart)) return null

return [numberPart, match[2]]
}

function round(n: number, precision: number): number {
return Math.round(n * Math.pow(10, precision)) / Math.pow(10, precision)
}
import { stringify, tokenize } from '@csstools/css-tokenizer'
import { isFunctionNode, parseComponentValue } from '@csstools/css-parser-algorithms'
import { calcFromComponentValues } from '@csstools/css-calc'

export function evaluateExpression(str: string): string | null {
// We're only interested simple calc expressions of the form
// A + B, A - B, A * B, A / B
let tokens = tokenize({ css: `calc(${str})` })

let parts = str.split(/\s+([+*/-])\s+/)
let components = parseComponentValue(tokens, {})
if (!components) return null

if (parts.length === 1) return null
if (parts.length !== 3) return null
let result = calcFromComponentValues([[components]], {
// Ensure evaluation of random() is deterministic
randomSeed: 1,

let a = parseLength(parts[0])
let b = parseLength(parts[2])
// Limit precision to keep values environment independent
precision: 4,
})

// Not parsable
if (!a || !b) {
return null
}

// Addition and subtraction require the same units
if ((parts[1] === '+' || parts[1] === '-') && a[1] !== b[1]) {
return null
}

// Multiplication and division require at least one unit to be empty
if ((parts[1] === '*' || parts[1] === '/') && a[1] !== '' && b[1] !== '') {
return null
}
// The result array is the same shape as the original so we're guaranteed to
// have an element here
let node = result[0][0]

switch (parts[1]) {
case '+':
return round(a[0] + b[0], 4).toString() + a[1]
case '*':
return round(a[0] * b[0], 4).toString() + a[1]
case '-':
return round(a[0] - b[0], 4).toString() + a[1]
case '/':
return round(a[0] / b[0], 4).toString() + a[1]
// If we have a top-level `calc(…)` node then the evaluation did not resolve
// to a single value and we consider it to be incomplete
if (isFunctionNode(node)) {
if (node.name[1] === 'calc(') return null
}

return null
return stringify(...node.tokens())
}
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ test('Evaluating CSS calc expressions', () => {
expect(replaceCssCalc('calc(1.25 / 0.875)', (node) => evaluateExpression(node.value))).toBe(
'1.4286',
)

expect(replaceCssCalc('calc(1/4 * 100%)', (node) => evaluateExpression(node.value))).toBe('25%')
})

test('Inlining calc expressions using the design system', () => {
Expand Down
4 changes: 2 additions & 2 deletions packages/tailwindcss-language-service/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"include": ["src", "../../types"],
"compilerOptions": {
"module": "NodeNext",
"module": "ES2022",
"lib": ["ES2022"],
"target": "ES2022",
"importHelpers": true,
Expand All @@ -13,7 +13,7 @@
"noUnusedParameters": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "NodeNext",
"moduleResolution": "Bundler",
"skipLibCheck": true,
"jsx": "react",
"esModuleInterop": true
Expand Down
59 changes: 33 additions & 26 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.