Skip to content

wip: Improve value parsing #1330

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

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
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
20 changes: 20 additions & 0 deletions packages/tailwindcss-language-service/src/util/default-map.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* A Map that can generate default values for keys that don't exist.
* Generated default values are added to the map to avoid recomputation.
*/
export class DefaultMap<T = string, V = any> extends Map<T, V> {
constructor(private factory: (key: T, self: DefaultMap<T, V>) => V) {
super()
}

get(key: T): V {
let value = super.get(key)

if (value === undefined) {
value = this.factory(key, this)
this.set(key, value)
}

return value
}
}
86 changes: 85 additions & 1 deletion packages/tailwindcss-language-service/src/util/find.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { test } from 'vitest'
import { findClassListsInHtmlRange } from './find'
import { findClassListsInHtmlRange, findClassNameAtPosition } from './find'
import { js, html, pug, createDocument } from './test-utils'

test('class regex works in astro', async ({ expect }) => {
Expand Down Expand Up @@ -791,3 +791,87 @@ test('classAttributes find class lists inside Vue bindings', async ({ expect })
},
])
})

test('Can find class name inside JS/TS functions in <script> tags (HTML)', async ({ expect }) => {
let file = createDocument({
name: 'file.html',
lang: 'html',
settings: {
tailwindCSS: {
classFunctions: ['clsx'],
},
},
content: html`
<script>
let classes = clsx('flex relative')
</script>
`,
})

let className = await findClassNameAtPosition(file.state, file.doc, {
line: 1,
character: 23,
})

expect(className).toEqual({
className: 'flex',
range: {
start: { line: 1, character: 22 },
end: { line: 1, character: 26 },
},
relativeRange: {
start: { line: 0, character: 0 },
end: { line: 0, character: 4 },
},
classList: {
classList: 'flex relative',
important: undefined,
range: {
start: { character: 22, line: 1 },
end: { character: 35, line: 1 },
},
},
})
})

test('Can find class name inside JS/TS functions in <script> tags (Svelte)', async ({ expect }) => {
let file = createDocument({
name: 'file.svelte',
lang: 'svelte',
settings: {
tailwindCSS: {
classFunctions: ['clsx'],
},
},
content: html`
<script>
let classes = clsx('flex relative')
</script>
`,
})

let className = await findClassNameAtPosition(file.state, file.doc, {
line: 1,
character: 23,
})

expect(className).toEqual({
className: 'flex',
range: {
start: { line: 1, character: 22 },
end: { line: 1, character: 26 },
},
relativeRange: {
start: { line: 0, character: 0 },
end: { line: 0, character: 4 },
},
classList: {
classList: 'flex relative',
important: undefined,
range: {
start: { character: 22, line: 1 },
end: { character: 35, line: 1 },
},
},
})
})
4 changes: 2 additions & 2 deletions packages/tailwindcss-language-service/src/util/find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import lineColumn from 'line-column'
import { isCssContext, isCssDoc } from './css'
import { isHtmlContext, isVueDoc } from './html'
import { isWithinRange } from './isWithinRange'
import { isJsxContext } from './js'
import { isJsContext } from './js'
import { dedupeByRange, flatten } from './array'
import { getClassAttributeLexer, getComputedClassAttributeLexer } from './lexers'
import { getLanguageBoundaries } from './getLanguageBoundaries'
Expand Down Expand Up @@ -526,7 +526,7 @@ export async function findClassNameAtPosition(
classNames = await findClassNamesInRange(state, doc, searchRange, 'css')
} else if (isHtmlContext(state, doc, position)) {
classNames = await findClassNamesInRange(state, doc, searchRange, 'html')
} else if (isJsxContext(state, doc, position)) {
} else if (isJsContext(state, doc, position)) {
classNames = await findClassNamesInRange(state, doc, searchRange, 'jsx')
} else {
classNames = await findClassNamesInRange(state, doc, searchRange)
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
@@ -0,0 +1,44 @@
import * as culori from 'culori'
import { expect, test } from 'vitest'
import { colorFromString, colorMix, colorMixFromString } from './color'

test('colorFromString', () => {
expect(colorFromString('red')).toEqual({ mode: 'rgb', r: 1, g: 0, b: 0 })
expect(colorFromString('rgb(255 0 0)')).toEqual({ mode: 'rgb', r: 1, g: 0, b: 0 })
expect(colorFromString('hsl(0 100% 50%)')).toEqual({ mode: 'hsl', h: 0, s: 1, l: 0.5 })
expect(colorFromString('#f00')).toEqual({ mode: 'rgb', r: 1, g: 0, b: 0 })
expect(colorFromString('#f003')).toEqual({ mode: 'rgb', r: 1, g: 0, b: 0, alpha: 0.2 })
expect(colorFromString('#ff0000')).toEqual({ mode: 'rgb', r: 1, g: 0, b: 0 })
expect(colorFromString('#ff000033')).toEqual({ mode: 'rgb', r: 1, g: 0, b: 0, alpha: 0.2 })

expect(colorFromString('color(srgb 1 0 0 )')).toEqual({ mode: 'rgb', r: 1, g: 0, b: 0 })
expect(colorFromString('color(srgb-linear 1 0 0 )')).toEqual({ mode: 'lrgb', r: 1, g: 0, b: 0 })
expect(colorFromString('color(display-p3 1 0 0 )')).toEqual({ mode: 'p3', r: 1, g: 0, b: 0 })
expect(colorFromString('color(a98-rgb 1 0 0 )')).toEqual({ mode: 'a98', r: 1, g: 0, b: 0 })
expect(colorFromString('color(prophoto-rgb 1 0 0 )')).toEqual({
mode: 'prophoto',
r: 1,
g: 0,
b: 0,
})
expect(colorFromString('color(rec2020 1 0 0 )')).toEqual({ mode: 'rec2020', r: 1, g: 0, b: 0 })

expect(colorFromString('color(xyz 1 0 0 )')).toEqual({ mode: 'xyz65', x: 1, y: 0, z: 0 })
expect(colorFromString('color(xyz-d65 1 0 0 )')).toEqual({ mode: 'xyz65', x: 1, y: 0, z: 0 })
expect(colorFromString('color(xyz-d50 1 0 0 )')).toEqual({ mode: 'xyz50', x: 1, y: 0, z: 0 })

expect(colorFromString('#ff000033cccc')).toEqual(null)

// none keywords work too
expect(colorFromString('rgb(255 none 0)')).toEqual({ mode: 'rgb', r: 1, b: 0 })
})

test('colorMixFromString', () => {
expect(colorMixFromString('color-mix(in srgb, #f00 50%, transparent)')).toEqual({
mode: 'rgb',
r: 1,
g: 0,
b: 0,
alpha: 0.5,
})
})
Loading