Merge pull request #2492 from melsonic/issue--2490

validate gradient color stops
This commit is contained in:
Alexander Wang 2025-04-22 08:33:01 -07:00 committed by GitHub
commit 7150096840
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 32 additions and 1 deletions

View file

@ -21,6 +21,7 @@
- Compiler:
- `link`s can be set to root path, e.g. `/xyz`. [#2357](https://github.com/terrastruct/d2/issues/2357)
- When importing a file, attempt resolving substitutions at the imported file scope first [#2482](https://github.com/terrastruct/d2/pull/2482)
- validate gradient color stops. [#2492](https://github.com/terrastruct/d2/pull/2492)
- Parser:
- impose max key length. It's almost certainly a mistake if an ID gets too long, e.g. missing quotes [#2465](https://github.com/terrastruct/d2/pull/2465)
- Render:

View file

@ -3956,6 +3956,14 @@ svc_1.t2 -> b: do with B
tassert.Equal(t, "d2/testdata/d2compiler/TestCompile/meow.d2", g.Layers[0].Layers[0].AST.Range.Path)
},
},
{
name: "invalid_gradient_color_stop",
text: `
x
x.style.fill: "linear-gradient(#ggg, #000)"
`,
expErr: `d2/testdata/d2compiler/TestCompile/invalid_gradient_color_stop.d2:3:19: expected "fill" to be a valid named color ("orange"), a hex code ("#f0ff3a"), or a gradient ("linear-gradient(red, blue)")`,
},
}
for _, tc := range testCases {

View file

@ -512,7 +512,18 @@ var NamedColors = []string{
var ColorHexRegex = regexp.MustCompile(`^#(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$`)
func ValidColor(color string) bool {
if !go2.Contains(NamedColors, strings.ToLower(color)) && !ColorHexRegex.MatchString(color) && !IsGradient(color) {
if IsGradient(color) {
gradient, err := ParseGradient(color)
if err != nil {
return false
}
for _, colorStop := range gradient.ColorStops {
_, err = csscolorparser.Parse(colorStop.Color)
if err != nil {
return false
}
}
} else if !go2.Contains(NamedColors, strings.ToLower(color)) && !ColorHexRegex.MatchString(color) {
return false
}

View file

@ -0,0 +1,11 @@
{
"graph": null,
"err": {
"errs": [
{
"range": "d2/testdata/d2compiler/TestCompile/invalid_gradient_color_stop.d2,2:18:25-2:47:54",
"errmsg": "d2/testdata/d2compiler/TestCompile/invalid_gradient_color_stop.d2:3:19: expected \"fill\" to be a valid named color (\"orange\"), a hex code (\"#f0ff3a\"), or a gradient (\"linear-gradient(red, blue)\")"
}
]
}
}