Skip to content

Commit

Permalink
Fix markdown color code detection (#30208)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
wxiaoguang committed Mar 31, 2024
1 parent 6d34ce2 commit ab02835
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
8 changes: 6 additions & 2 deletions modules/markup/markdown/markdown_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,10 @@ func TestColorPreview(t *testing.T) {
testcase string
expected string
}{
{ // do not render color names
"The CSS class `red` is there",
"<p>The CSS class <code>red</code> is there</p>\n",
},
{ // hex
"`#FF0000`",
`<p><code>#FF0000<span class="color-preview" style="background-color: #FF0000"></span></code></p>` + nl,
Expand All @@ -445,8 +449,8 @@ func TestColorPreview(t *testing.T) {
`<p><code>rgb(16, 32, 64)<span class="color-preview" style="background-color: rgb(16, 32, 64)"></span></code></p>` + nl,
},
{ // short hex
"This is the color white `#000`",
`<p>This is the color white <code>#000<span class="color-preview" style="background-color: #000"></span></code></p>` + nl,
"This is the color white `#0a0`",
`<p>This is the color white <code>#0a0<span class="color-preview" style="background-color: #0a0"></span></code></p>` + nl,
},
{ // hsl
"HSL stands for hue, saturation, and lightness. An example: `hsl(0, 100%, 50%)`.",
Expand Down
21 changes: 20 additions & 1 deletion modules/markup/markdown/transform_codespan.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,28 @@ func (r *HTMLRenderer) renderCodeSpan(w util.BufWriter, source []byte, n ast.Nod
return ast.WalkContinue, nil
}

// cssColorHandler checks if a string is a render-able CSS color value.
// The code is from "github.com/microcosm-cc/bluemonday/css.ColorHandler", except that it doesn't handle color words like "red".
func cssColorHandler(value string) bool {
value = strings.ToLower(value)
if css.HexRGB.MatchString(value) {
return true
}
if css.RGB.MatchString(value) {
return true
}
if css.RGBA.MatchString(value) {
return true
}
if css.HSL.MatchString(value) {
return true
}
return css.HSLA.MatchString(value)
}

func (g *ASTTransformer) transformCodeSpan(ctx *markup.RenderContext, v *ast.CodeSpan, reader text.Reader) {
colorContent := v.Text(reader.Source())
if css.ColorHandler(strings.ToLower(string(colorContent))) {
if cssColorHandler(string(colorContent)) {
v.AppendChild(v, NewColorPreview(colorContent))
}
}

0 comments on commit ab02835

Please sign in to comment.