From bf22be90b76d06aa1cc12a417e1d20400a8f1626 Mon Sep 17 00:00:00 2001 From: Giteabot Date: Sun, 31 Mar 2024 20:25:15 +0800 Subject: [PATCH] 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 --- modules/markup/markdown/markdown_test.go | 8 +++++-- modules/markup/markdown/transform_codespan.go | 21 ++++++++++++++++++- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/modules/markup/markdown/markdown_test.go b/modules/markup/markdown/markdown_test.go index ebac3fbe9e..c664758a27 100644 --- a/modules/markup/markdown/markdown_test.go +++ b/modules/markup/markdown/markdown_test.go @@ -436,6 +436,10 @@ func TestColorPreview(t *testing.T) { testcase string expected string }{ + { // do not render color names + "The CSS class `red` is there", + "

The CSS class red is there

\n", + }, { // hex "`#FF0000`", `

#FF0000

` + nl, @@ -445,8 +449,8 @@ func TestColorPreview(t *testing.T) { `

rgb(16, 32, 64)

` + nl, }, { // short hex - "This is the color white `#000`", - `

This is the color white #000

` + nl, + "This is the color white `#0a0`", + `

This is the color white #0a0

` + nl, }, { // hsl "HSL stands for hue, saturation, and lightness. An example: `hsl(0, 100%, 50%)`.", diff --git a/modules/markup/markdown/transform_codespan.go b/modules/markup/markdown/transform_codespan.go index bfff2897b0..5b07d72999 100644 --- a/modules/markup/markdown/transform_codespan.go +++ b/modules/markup/markdown/transform_codespan.go @@ -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)) } }