From 733d872d8dc8f23442383d95e3eea5bf261b508e Mon Sep 17 00:00:00 2001 From: Brad Cornes Date: Thu, 20 Oct 2022 12:59:28 +0100 Subject: [PATCH] Improve extraction for variable colors (#638) --- .../tailwindcss-language-service/src/util/color.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/tailwindcss-language-service/src/util/color.ts b/packages/tailwindcss-language-service/src/util/color.ts index 8334a18..b7b55ca 100644 --- a/packages/tailwindcss-language-service/src/util/color.ts +++ b/packages/tailwindcss-language-service/src/util/color.ts @@ -42,16 +42,22 @@ function getKeywordColor(value: unknown): KeywordColor | null { // https://github.com/khalilgharbaoui/coloregex const colorRegex = new RegExp( - `(?:^|\\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( + `(?:^|\\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( namedColors ).join('|')})(?:$|\\s|\\)|,)`, 'gi' ) +function replaceColorVarsWithTheirDefaults(str: string): string { + // rgb(var(--primary, 66 66 66)) + // -> rgb(66 66 66) + return str.replace(/((?:rgb|hsl)a?\(\s*)var\([^,]+,\s*([^)]+)\)/gi, '$1$2') +} + function getColorsInString(str: string): (culori.Color | KeywordColor)[] { if (/(?:box|drop)-shadow/.test(str)) return [] - return Array.from(str.matchAll(colorRegex), (match) => { + return Array.from(replaceColorVarsWithTheirDefaults(str).matchAll(colorRegex), (match) => { let color = match[1].replace(/var\([^)]+\)/, '1') return getKeywordColor(color) ?? culori.parse(color) }).filter(Boolean)