Skip to content

Commit bf22be9

Browse files
GiteaBotwxiaoguang
andauthored
Fix markdown color code detection (#30208) (#30211)
Backport #30208 by wxiaoguang When reviewing PRs, some color names might be mentioned, the `transformCodeSpan` (which calls `css.ColorHandler`) considered it as a valid color, but actually it shouldn't be rendered as a color codespan. Co-authored-by: wxiaoguang <[email protected]>
1 parent f86ec4c commit bf22be9

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

modules/markup/markdown/markdown_test.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,10 @@ func TestColorPreview(t *testing.T) {
436436
testcase string
437437
expected string
438438
}{
439+
{ // do not render color names
440+
"The CSS class `red` is there",
441+
"<p>The CSS class <code>red</code> is there</p>\n",
442+
},
439443
{ // hex
440444
"`#FF0000`",
441445
`<p><code>#FF0000<span class="color-preview" style="background-color: #FF0000"></span></code></p>` + nl,
@@ -445,8 +449,8 @@ func TestColorPreview(t *testing.T) {
445449
`<p><code>rgb(16, 32, 64)<span class="color-preview" style="background-color: rgb(16, 32, 64)"></span></code></p>` + nl,
446450
},
447451
{ // short hex
448-
"This is the color white `#000`",
449-
`<p>This is the color white <code>#000<span class="color-preview" style="background-color: #000"></span></code></p>` + nl,
452+
"This is the color white `#0a0`",
453+
`<p>This is the color white <code>#0a0<span class="color-preview" style="background-color: #0a0"></span></code></p>` + nl,
450454
},
451455
{ // hsl
452456
"HSL stands for hue, saturation, and lightness. An example: `hsl(0, 100%, 50%)`.",

modules/markup/markdown/transform_codespan.go

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,28 @@ func (r *HTMLRenderer) renderCodeSpan(w util.BufWriter, source []byte, n ast.Nod
4949
return ast.WalkContinue, nil
5050
}
5151

52+
// cssColorHandler checks if a string is a render-able CSS color value.
53+
// The code is from "github.com/microcosm-cc/bluemonday/css.ColorHandler", except that it doesn't handle color words like "red".
54+
func cssColorHandler(value string) bool {
55+
value = strings.ToLower(value)
56+
if css.HexRGB.MatchString(value) {
57+
return true
58+
}
59+
if css.RGB.MatchString(value) {
60+
return true
61+
}
62+
if css.RGBA.MatchString(value) {
63+
return true
64+
}
65+
if css.HSL.MatchString(value) {
66+
return true
67+
}
68+
return css.HSLA.MatchString(value)
69+
}
70+
5271
func (g *ASTTransformer) transformCodeSpan(ctx *markup.RenderContext, v *ast.CodeSpan, reader text.Reader) {
5372
colorContent := v.Text(reader.Source())
54-
if css.ColorHandler(strings.ToLower(string(colorContent))) {
73+
if cssColorHandler(string(colorContent)) {
5574
v.AppendChild(v, NewColorPreview(colorContent))
5675
}
5776
}

0 commit comments

Comments
 (0)