avoid false positives when parsing colors (#415)

master
Brad Cornes 2021-09-24 15:05:07 +01:00
parent dce390d98c
commit 7e2b53cd11
1 changed files with 8 additions and 3 deletions

View File

@ -40,9 +40,9 @@ function getKeywordColor(value: unknown): KeywordColor | null {
// https://github.com/khalilgharbaoui/coloregex // https://github.com/khalilgharbaoui/coloregex
const colorRegex = new RegExp( const colorRegex = new RegExp(
`(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\\((-?[\\d.]+%?[,\\s]+){2,3}\\s*([\\d.]+%?|var\\([^)]+\\))?\\)|transparent|currentColor|${Object.keys( `(?:^|\\s|,)(#(?:[0-9a-f]{2}){2,4}|(#[0-9a-f]{3})|(rgb|hsl)a?\\((-?[\\d.]+%?[,\\s]+){2,3}\\s*([\\d.]+%?|var\\([^)]+\\))?\\)|transparent|currentColor|${Object.keys(
colorNames colorNames
).join('|')})`, ).join('|')})(?:$|\\s|,)`,
'gi' 'gi'
) )
@ -52,7 +52,12 @@ function getColorsInString(str: string): (TinyColor | KeywordColor)[] {
return ( return (
str str
.match(colorRegex) .match(colorRegex)
?.map((color) => color.replace(/var\([^)]+\)/, '1')) ?.map((color) =>
color
.trim()
.replace(/^,|,$/g, '')
.replace(/var\([^)]+\)/, '1')
)
.map((color) => getKeywordColor(color) ?? new TinyColor(color)) .map((color) => getKeywordColor(color) ?? new TinyColor(color))
.filter((color) => (color instanceof TinyColor ? color.isValid : true)) ?? [] .filter((color) => (color instanceof TinyColor ? color.isValid : true)) ?? []
) )