Skip to content

Commit 733d872

Browse files
authored
Improve extraction for variable colors (#638)
1 parent 6c47780 commit 733d872

File tree

1 file changed

+8
-2
lines changed
  • packages/tailwindcss-language-service/src/util

1 file changed

+8
-2
lines changed

packages/tailwindcss-language-service/src/util/color.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,16 +42,22 @@ function getKeywordColor(value: unknown): KeywordColor | null {
4242

4343
// https://github.com/khalilgharbaoui/coloregex
4444
const colorRegex = new RegExp(
45-
`(?:^|\\s|\\(|,)(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\\((-?[\\d.]+%?(\\s*[,/]\\s*|\\s+)+){2,3}\\s*([\\d.]+%?|var\\([^)]+\\))?\\)|transparent|currentColor|${Object.keys(
45+
`(?:^|\\s|\\(|,)(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\\(\\s*(-?[\\d.]+%?(\\s*[,/]\\s*|\\s+)+){2,3}\\s*([\\d.]+%?|var\\([^)]+\\))?\\)|transparent|currentColor|${Object.keys(
4646
namedColors
4747
).join('|')})(?:$|\\s|\\)|,)`,
4848
'gi'
4949
)
5050

51+
function replaceColorVarsWithTheirDefaults(str: string): string {
52+
// rgb(var(--primary, 66 66 66))
53+
// -> rgb(66 66 66)
54+
return str.replace(/((?:rgb|hsl)a?\(\s*)var\([^,]+,\s*([^)]+)\)/gi, '$1$2')
55+
}
56+
5157
function getColorsInString(str: string): (culori.Color | KeywordColor)[] {
5258
if (/(?:box|drop)-shadow/.test(str)) return []
5359

54-
return Array.from(str.matchAll(colorRegex), (match) => {
60+
return Array.from(replaceColorVarsWithTheirDefaults(str).matchAll(colorRegex), (match) => {
5561
let color = match[1].replace(/var\([^)]+\)/, '1')
5662
return getKeywordColor(color) ?? culori.parse(color)
5763
}).filter(Boolean)

0 commit comments

Comments
 (0)