Skip to content

Commit 9112e96

Browse files
Gracefully handle color parsing failures (#1363)
Fixes #1362 Basically when we'd see `rgb(1rem)` and tried to parse it with Culori it would throw an error instead of returning `undefined` as would normally be the case. Pretty sure this isn't supposed to throw but 🤷‍♂️
1 parent 1c77f60 commit 9112e96

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

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

+14-4
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ function getColorsInString(state: State, str: string): (culori.Color | KeywordCo
6161

6262
function toColor(match: RegExpMatchArray) {
6363
let color = match[1].replace(/var\([^)]+\)/, '1')
64-
return getKeywordColor(color) ?? culori.parse(color)
64+
return getKeywordColor(color) ?? tryParseColor(color)
6565
}
6666

6767
str = replaceCssVarsWithFallbacks(state, str)
@@ -275,8 +275,8 @@ export function getColorFromValue(value: unknown): culori.Color | KeywordColor |
275275
) {
276276
return null
277277
}
278-
const color = culori.parse(trimmedValue)
279-
return color ?? null
278+
279+
return tryParseColor(trimmedValue)
280280
}
281281

282282
let toRgb = culori.converter('rgb')
@@ -296,11 +296,21 @@ export function formatColor(color: culori.Color): string {
296296

297297
const COLOR_MIX_REGEX = /color-mix\(in [^,]+,\s*(.*?)\s*(\d+|\.\d+|\d+\.\d+)%,\s*transparent\)/g
298298

299+
function tryParseColor(color: string) {
300+
try {
301+
return culori.parse(color) ?? null
302+
} catch (err) {
303+
console.error('Error parsing color', color)
304+
console.error(err)
305+
return null
306+
}
307+
}
308+
299309
function removeColorMixWherePossible(str: string) {
300310
return str.replace(COLOR_MIX_REGEX, (match, color, percentage) => {
301311
if (color.startsWith('var(')) return match
302312

303-
let parsed = culori.parse(color)
313+
let parsed = tryParseColor(color)
304314
if (!parsed) return match
305315

306316
let alpha = Number(percentage) / 100

packages/vscode-tailwindcss/CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
- Ignore Python virtual env directories by default ([#1336](https://github.com/tailwindlabs/tailwindcss-intellisense/pull/1336))
77
- Ignore Yarn v2+ metadata & cache directories by default ([#1336](https://github.com/tailwindlabs/tailwindcss-intellisense/pull/1336))
88
- Ignore some build caches by default ([#1336](https://github.com/tailwindlabs/tailwindcss-intellisense/pull/1336))
9+
- Gracefully handle color parsing failures ([#1363](https://github.com/tailwindlabs/tailwindcss-intellisense/pull/1363))
910

1011
# 0.14.16
1112

0 commit comments

Comments
 (0)