Skip to content

Commit

Permalink
Merge remote-tracking branch 'giteaofficial/main'
Browse files Browse the repository at this point in the history
* giteaofficial/main:
  Add attention blocks within quote blocks for `Note` and `Warning` (go-gitea#21711)
  Move svg html render to modules/svg (go-gitea#21716)
  Fix tests on migrations (go-gitea#21705)
  • Loading branch information
zjjhot committed Nov 9, 2022
2 parents 5363f0e + cb83288 commit 0ac5fce
Show file tree
Hide file tree
Showing 9 changed files with 185 additions and 50 deletions.
15 changes: 15 additions & 0 deletions models/migrations/v1_19/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright 2021 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package v1_19 // nolint

import (
"testing"

"code.gitea.io/gitea/models/migrations/base"
)

func TestMain(m *testing.M) {
base.MainTest(m)
}
2 changes: 1 addition & 1 deletion models/migrations/v1_19/v233_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
"github.com/stretchr/testify/assert"
)

func Test_addHeaderAuthorizationEncryptedColWebhook(t *testing.T) {
func Test_AddHeaderAuthorizationEncryptedColWebhook(t *testing.T) {
// Create Webhook table
type Webhook struct {
ID int64 `xorm:"pk autoincr"`
Expand Down
34 changes: 34 additions & 0 deletions modules/html/html.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package html

// ParseSizeAndClass get size and class from string with default values
// If present, "others" expects the new size first and then the classes to use
func ParseSizeAndClass(defaultSize int, defaultClass string, others ...interface{}) (int, string) {
if len(others) == 0 {
return defaultSize, defaultClass
}

size := defaultSize
_size, ok := others[0].(int)
if ok && _size != 0 {
size = _size
}

if len(others) == 1 {
return size, defaultClass
}

class := defaultClass
if _class, ok := others[1].(string); ok && _class != "" {
if defaultClass == "" {
class = _class
} else {
class = defaultClass + " " + _class
}
}

return size, class
}
34 changes: 34 additions & 0 deletions modules/markup/markdown/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,37 @@ func IsColorPreview(node ast.Node) bool {
_, ok := node.(*ColorPreview)
return ok
}

const (
AttentionNote string = "Note"
AttentionWarning string = "Warning"
)

// Attention is an inline for a color preview
type Attention struct {
ast.BaseInline
AttentionType string
}

// Dump implements Node.Dump.
func (n *Attention) Dump(source []byte, level int) {
m := map[string]string{}
m["AttentionType"] = n.AttentionType
ast.DumpHelper(n, source, level, m, nil)
}

// KindAttention is the NodeKind for Attention
var KindAttention = ast.NewNodeKind("Attention")

// Kind implements Node.Kind.
func (n *Attention) Kind() ast.NodeKind {
return KindAttention
}

// NewAttention returns a new Attention node.
func NewAttention(attentionType string) *Attention {
return &Attention{
BaseInline: ast.BaseInline{},
AttentionType: attentionType,
}
}
37 changes: 37 additions & 0 deletions modules/markup/markdown/goldmark.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"code.gitea.io/gitea/modules/markup"
"code.gitea.io/gitea/modules/markup/common"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/svg"
giteautil "code.gitea.io/gitea/modules/util"

"github.com/microcosm-cc/bluemonday/css"
Expand Down Expand Up @@ -46,6 +47,7 @@ func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc pa
ctx.TableOfContents = make([]markup.Header, 0, 100)
}

attentionMarkedBlockquotes := make(container.Set[*ast.Blockquote])
_ = ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
if !entering {
return ast.WalkContinue, nil
Expand Down Expand Up @@ -184,6 +186,18 @@ func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc pa
if css.ColorHandler(strings.ToLower(string(colorContent))) {
v.AppendChild(v, NewColorPreview(colorContent))
}
case *ast.Emphasis:
// check if inside blockquote for attention, expected hierarchy is
// Emphasis < Paragraph < Blockquote
blockquote, isInBlockquote := n.Parent().Parent().(*ast.Blockquote)
if isInBlockquote && !attentionMarkedBlockquotes.Contains(blockquote) {
fullText := string(n.Text(reader.Source()))
if fullText == AttentionNote || fullText == AttentionWarning {
v.SetAttributeString("class", []byte("attention-"+strings.ToLower(fullText)))
v.Parent().InsertBefore(v.Parent(), v, NewAttention(fullText))
attentionMarkedBlockquotes.Add(blockquote)
}
}
}
return ast.WalkContinue, nil
})
Expand Down Expand Up @@ -273,6 +287,7 @@ func (r *HTMLRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
reg.Register(KindSummary, r.renderSummary)
reg.Register(KindIcon, r.renderIcon)
reg.Register(ast.KindCodeSpan, r.renderCodeSpan)
reg.Register(KindAttention, r.renderAttention)
reg.Register(KindTaskCheckBoxListItem, r.renderTaskCheckBoxListItem)
reg.Register(east.KindTaskCheckBox, r.renderTaskCheckBox)
}
Expand Down Expand Up @@ -309,6 +324,28 @@ func (r *HTMLRenderer) renderCodeSpan(w util.BufWriter, source []byte, n ast.Nod
return ast.WalkContinue, nil
}

// renderAttention renders a quote marked with i.e. "> **Note**" or "> **Warning**" with a corresponding svg
func (r *HTMLRenderer) renderAttention(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
if entering {
_, _ = w.WriteString(`<span class="attention-icon attention-`)
n := node.(*Attention)
_, _ = w.WriteString(strings.ToLower(n.AttentionType))
_, _ = w.WriteString(`">`)

var octiconType string
switch n.AttentionType {
case AttentionNote:
octiconType = "info"
case AttentionWarning:
octiconType = "alert"
}
_, _ = w.WriteString(string(svg.RenderHTML("octicon-" + octiconType)))
} else {
_, _ = w.WriteString("</span>\n")
}
return ast.WalkContinue, nil
}

func (r *HTMLRenderer) renderDocument(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
n := node.(*ast.Document)

Expand Down
7 changes: 7 additions & 0 deletions modules/markup/sanitizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ func createDefaultPolicy() *bluemonday.Policy {
// For color preview
policy.AllowAttrs("class").Matching(regexp.MustCompile(`^color-preview$`)).OnElements("span")

// For attention
policy.AllowAttrs("class").Matching(regexp.MustCompile(`^attention-\w+$`)).OnElements("strong")
policy.AllowAttrs("class").Matching(regexp.MustCompile(`^attention-icon attention-\w+$`)).OnElements("span", "strong")
policy.AllowAttrs("class").Matching(regexp.MustCompile(`^svg octicon-\w+$`)).OnElements("svg")
policy.AllowAttrs("viewBox", "width", "height", "aria-hidden").OnElements("svg")
policy.AllowAttrs("fill-rule", "d").OnElements("path")

// For Chroma markdown plugin
policy.AllowAttrs("class").Matching(regexp.MustCompile(`^(chroma )?language-[\w-]+( display)?( is-loading)?$`)).OnElements("code")

Expand Down
37 changes: 35 additions & 2 deletions modules/svg/svg.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,43 @@

package svg

// SVGs contains discovered SVGs
var SVGs map[string]string
import (
"fmt"
"html/template"
"regexp"
"strings"

"code.gitea.io/gitea/modules/html"
)

var (
// SVGs contains discovered SVGs
SVGs map[string]string

widthRe = regexp.MustCompile(`width="[0-9]+?"`)
heightRe = regexp.MustCompile(`height="[0-9]+?"`)
)

const defaultSize = 16

// Init discovers SVGs and populates the `SVGs` variable
func Init() {
SVGs = Discover()
}

// Render render icons - arguments icon name (string), size (int), class (string)
func RenderHTML(icon string, others ...interface{}) template.HTML {
size, class := html.ParseSizeAndClass(defaultSize, "", others...)

if svgStr, ok := SVGs[icon]; ok {
if size != defaultSize {
svgStr = widthRe.ReplaceAllString(svgStr, fmt.Sprintf(`width="%d"`, size))
svgStr = heightRe.ReplaceAllString(svgStr, fmt.Sprintf(`height="%d"`, size))
}
if class != "" {
svgStr = strings.Replace(svgStr, `class="`, fmt.Sprintf(`class="%s `, class), 1)
}
return template.HTML(svgStr)
}
return template.HTML("")
}
55 changes: 8 additions & 47 deletions modules/templates/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
"code.gitea.io/gitea/modules/emoji"
"code.gitea.io/gitea/modules/git"
giturl "code.gitea.io/gitea/modules/git/url"
gitea_html "code.gitea.io/gitea/modules/html"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/markup"
Expand Down Expand Up @@ -348,7 +349,7 @@ func NewFuncMap() []template.FuncMap {
}
return false
},
"svg": SVG,
"svg": svg.RenderHTML,
"avatar": Avatar,
"avatarHTML": AvatarHTML,
"avatarByAction": AvatarByAction,
Expand All @@ -363,17 +364,17 @@ func NewFuncMap() []template.FuncMap {
if len(urlSort) == 0 && isDefault {
// if sort is sorted as default add arrow tho this table header
if isDefault {
return SVG("octicon-triangle-down", 16)
return svg.RenderHTML("octicon-triangle-down", 16)
}
} else {
// if sort arg is in url test if it correlates with column header sort arguments
// the direction of the arrow should indicate the "current sort order", up means ASC(normal), down means DESC(rev)
if urlSort == normSort {
// the table is sorted with this header normal
return SVG("octicon-triangle-up", 16)
return svg.RenderHTML("octicon-triangle-up", 16)
} else if urlSort == revSort {
// the table is sorted with this header reverse
return SVG("octicon-triangle-down", 16)
return svg.RenderHTML("octicon-triangle-down", 16)
}
}
// the table is NOT sorted with this header
Expand Down Expand Up @@ -594,29 +595,6 @@ func NewTextFuncMap() []texttmpl.FuncMap {
}}
}

var (
widthRe = regexp.MustCompile(`width="[0-9]+?"`)
heightRe = regexp.MustCompile(`height="[0-9]+?"`)
)

func parseOthers(defaultSize int, defaultClass string, others ...interface{}) (int, string) {
size := defaultSize
if len(others) > 0 && others[0].(int) != 0 {
size = others[0].(int)
}

class := defaultClass
if len(others) > 1 && others[1].(string) != "" {
if defaultClass == "" {
class = others[1].(string)
} else {
class = defaultClass + " " + others[1].(string)
}
}

return size, class
}

// AvatarHTML creates the HTML for an avatar
func AvatarHTML(src string, size int, class, name string) template.HTML {
sizeStr := fmt.Sprintf(`%d`, size)
Expand All @@ -628,26 +606,9 @@ func AvatarHTML(src string, size int, class, name string) template.HTML {
return template.HTML(`<img class="` + class + `" src="` + src + `" title="` + html.EscapeString(name) + `" width="` + sizeStr + `" height="` + sizeStr + `"/>`)
}

// SVG render icons - arguments icon name (string), size (int), class (string)
func SVG(icon string, others ...interface{}) template.HTML {
size, class := parseOthers(16, "", others...)

if svgStr, ok := svg.SVGs[icon]; ok {
if size != 16 {
svgStr = widthRe.ReplaceAllString(svgStr, fmt.Sprintf(`width="%d"`, size))
svgStr = heightRe.ReplaceAllString(svgStr, fmt.Sprintf(`height="%d"`, size))
}
if class != "" {
svgStr = strings.Replace(svgStr, `class="`, fmt.Sprintf(`class="%s `, class), 1)
}
return template.HTML(svgStr)
}
return template.HTML("")
}

// Avatar renders user avatars. args: user, size (int), class (string)
func Avatar(item interface{}, others ...interface{}) template.HTML {
size, class := parseOthers(avatars.DefaultAvatarPixelSize, "ui avatar vm", others...)
size, class := gitea_html.ParseSizeAndClass(avatars.DefaultAvatarPixelSize, "ui avatar vm", others...)

switch t := item.(type) {
case *user_model.User:
Expand Down Expand Up @@ -678,7 +639,7 @@ func AvatarByAction(action *activities_model.Action, others ...interface{}) temp

// RepoAvatar renders repo avatars. args: repo, size(int), class (string)
func RepoAvatar(repo *repo_model.Repository, others ...interface{}) template.HTML {
size, class := parseOthers(avatars.DefaultAvatarPixelSize, "ui avatar", others...)
size, class := gitea_html.ParseSizeAndClass(avatars.DefaultAvatarPixelSize, "ui avatar", others...)

src := repo.RelAvatarLink()
if src != "" {
Expand All @@ -689,7 +650,7 @@ func RepoAvatar(repo *repo_model.Repository, others ...interface{}) template.HTM

// AvatarByEmail renders avatars by email address. args: email, name, size (int), class (string)
func AvatarByEmail(email, name string, others ...interface{}) template.HTML {
size, class := parseOthers(avatars.DefaultAvatarPixelSize, "ui avatar", others...)
size, class := gitea_html.ParseSizeAndClass(avatars.DefaultAvatarPixelSize, "ui avatar", others...)
src := avatars.GenerateEmailAvatarFastLink(email, size*setting.Avatar.RenderedSizeFactor)

if src != "" {
Expand Down
14 changes: 14 additions & 0 deletions web_src/less/_base.less
Original file line number Diff line number Diff line change
Expand Up @@ -1732,6 +1732,20 @@ a.ui.card:hover,
border-radius: .15em;
}

.attention-icon {
vertical-align: text-top;
}

.attention-note {
font-weight: unset;
color: var(--color-info-text);
}

.attention-warning {
font-weight: unset;
color: var(--color-warning-text);
}

footer {
background-color: var(--color-footer);
border-top: 1px solid var(--color-secondary);
Expand Down

0 comments on commit 0ac5fce

Please sign in to comment.