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 1 commit
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
Prev Previous commit
wip
  • Loading branch information
thecrypticace committed Apr 22, 2025
commit 4877d8d539b83ec05aada83b516c1c7ca7f56b98
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
}
}
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,
})
})
155 changes: 155 additions & 0 deletions packages/tailwindcss-language-service/src/util/rewriting/color.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import * as culori from 'culori'
import {
ComponentValue,
isFunctionNode,
isTokenNode,
isWhitespaceNode,
parseComponentValue,
} from '@csstools/css-parser-algorithms'
import {
isTokenComma,
isTokenHash,
isTokenIdent,
isTokenNumber,
isTokenNumeric,
isTokenPercentage,
stringify,
tokenize,
} from '@csstools/css-tokenizer'

const COLOR_FN = /^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color)$/i

export type KeywordColor = 'currentColor'
export type ParsedColor = culori.Color | KeywordColor | null

export function colorFromString(value: string): ParsedColor {
let tokens = tokenize({ css: value })
let cv = parseComponentValue(tokens)
let color = colorFromComponentValue(cv)

return color
}

export function colorFromComponentValue(cv: ComponentValue): ParsedColor {
if (isTokenNode(cv)) {
if (isTokenIdent(cv.value)) {
let str = cv.value[4].value.toLowerCase()

if (str === 'currentcolor') return 'currentColor'

if (str === 'transparent') {
// We omit rgb channels instead of using transparent black because we
// use `culori.interpolate` to mix colors and it handles `transparent`
// differently from the spec (all channels are mixed, not just alpha)
return culori.parse('rgb(none none none / 0.5)')
}

if (str in culori.colorsNamed) {
return culori.parseNamed(str as keyof typeof culori.colorsNamed) ?? null
}
}

//
else if (isTokenHash(cv.value)) {
let hex = cv.value[4].value.toLowerCase()

return culori.parseHex(hex) ?? null
}

return null
}

//
else if (isFunctionNode(cv)) {
let fn = cv.getName()

if (COLOR_FN.test(fn)) {
return culori.parse(stringify(...cv.tokens())) ?? null
}
}

return null
}

export function equivalentColorFromString(value: string): string {
let color = colorFromString(value)
let equivalent = computeEquivalentColor(color)

return equivalent ?? value
}

function computeEquivalentColor(color: ParsedColor): string | null {
if (!color) return null
if (typeof color === 'string') return null
if (!culori.inGamut('rgb')(color)) return null

if (color.alpha === undefined || color.alpha === 1) {
return culori.formatHex(color)
}

return culori.formatHex8(color)
}

export function colorMixFromString(value: string): ParsedColor {
let tokens = tokenize({ css: value })
let cv = parseComponentValue(tokens)
let color = colorMixFromComponentValue(cv)

return color
}

export function colorMixFromComponentValue(cv: ComponentValue): ParsedColor {
if (!isFunctionNode(cv)) return null
if (cv.getName() !== 'color-mix') return null

let state: 'in' | 'colorspace' | 'colors' = 'in'
let colorspace: string = ''
let colors: Array<culori.Color | number> = []

for (let i = 0; i < cv.value.length; ++i) {
let value = cv.value[i]

if (isWhitespaceNode(value)) continue

if (state === 'in') {
if (isTokenNode(value)) {
if (isTokenIdent(value.value)) {
if (value.value[4].value === 'in') {
state = 'colorspace'
}
}
}
} else if (state === 'colorspace') {
if (isTokenNode(value)) {
if (isTokenIdent(value.value)) {
if (colorspace !== '') return null

colorspace = value.value[4].value
} else if (isTokenComma(value.value)) {
state = 'colors'
}
}
} else if (state === 'colors') {
if (isTokenNode(value)) {
if (isTokenPercentage(value.value)) {
colors.push(value.value[4].value / 100)
continue
} else if (isTokenNumber(value.value)) {
colors.push(value.value[4].value)
continue
} else if (isTokenComma(value.value)) {
continue
}
}

let color = colorFromComponentValue(value)
if (!color) return null
if (typeof color === 'string') return null
colors.push(color)
}
}

let t = culori.interpolate(colors, colorspace as any)

return t(0.5) ?? null
}
Loading