Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
wxiaoguang committed Nov 5, 2024
1 parent b068dbd commit 88490e3
Show file tree
Hide file tree
Showing 52 changed files with 252 additions and 195 deletions.
35 changes: 18 additions & 17 deletions modules/templates/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,6 @@ func NewFuncMap() template.FuncMap {
return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
},

// for backward compatibility only, do not use them anymore
"TimeSince": timeSinceLegacy,
"TimeSinceUnix": timeSinceLegacy,
"DateTime": dateTimeLegacy,

// -----------------------------------------------------------------
// setting
"AppName": func() string {
Expand Down Expand Up @@ -156,18 +151,8 @@ func NewFuncMap() template.FuncMap {

// -----------------------------------------------------------------
// render
"RenderCommitMessage": RenderCommitMessage,
"RenderCommitMessageLinkSubject": renderCommitMessageLinkSubject,

"RenderCommitBody": renderCommitBody,
"RenderCodeBlock": renderCodeBlock,
"RenderIssueTitle": renderIssueTitle,
"RenderEmoji": renderEmoji,
"ReactionToEmoji": reactionToEmoji,

"RenderMarkdownToHtml": RenderMarkdownToHtml,
"RenderLabel": renderLabel,
"RenderLabels": RenderLabels,
"RenderCodeBlock": renderCodeBlock,
"ReactionToEmoji": reactionToEmoji,

// -----------------------------------------------------------------
// misc
Expand All @@ -179,6 +164,22 @@ func NewFuncMap() template.FuncMap {

"FilenameIsImage": filenameIsImage,
"TabSizeClass": tabSizeClass,

// for backward compatibility only, do not use them anymore
"TimeSince": timeSinceLegacy,
"TimeSinceUnix": timeSinceLegacy,
"DateTime": dateTimeLegacy,

"RenderEmoji": renderEmojiLegacy,
"RenderLabel": renderLabelLegacy,
"RenderLabels": renderLabelsLegacy,
"RenderIssueTitle": renderIssueTitleLegacy,

"RenderMarkdownToHtml": renderMarkdownToHtmlLegacy,

"RenderCommitMessage": renderCommitMessageLegacy,
"RenderCommitMessageLinkSubject": renderCommitMessageLinkSubjectLegacy,
"RenderCommitBody": renderCommitBodyLegacy,
}
}

Expand Down
26 changes: 0 additions & 26 deletions modules/templates/util_date.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (

"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/translation"
)

type DateUtils struct{}
Expand Down Expand Up @@ -46,31 +45,6 @@ func (du *DateUtils) ParseLegacy(datetime string) time.Time {
return parseLegacy(datetime)
}

func parseLegacy(datetime string) time.Time {
t, err := time.Parse(time.RFC3339, datetime)
if err != nil {
t, _ = time.ParseInLocation(time.DateOnly, datetime, setting.DefaultUILocation)
}
return t
}

func dateTimeLegacy(format string, datetime any, _ ...string) template.HTML {
if !setting.IsProd || setting.IsInTesting {
panic("dateTimeLegacy is for backward compatibility only, do not use it in new code")
}
if s, ok := datetime.(string); ok {
datetime = parseLegacy(s)
}
return dateTimeFormat(format, datetime)
}

func timeSinceLegacy(time any, _ translation.Locale) template.HTML {
if !setting.IsProd || setting.IsInTesting {
panic("timeSinceLegacy is for backward compatibility only, do not use it in new code")
}
return TimeSince(time)
}

func anyToTime(any any) (t time.Time, isZero bool) {
switch v := any.(type) {
case nil:
Expand Down
33 changes: 33 additions & 0 deletions modules/templates/util_date_legacy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package templates

import (
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/translation"
"html/template"
"time"
)

func parseLegacy(datetime string) time.Time {
t, err := time.Parse(time.RFC3339, datetime)
if err != nil {
t, _ = time.ParseInLocation(time.DateOnly, datetime, setting.DefaultUILocation)
}
return t
}

func dateTimeLegacy(format string, datetime any, _ ...string) template.HTML {
if !setting.IsProd || setting.IsInTesting {
panic("dateTimeLegacy is for backward compatibility only, do not use it in new code")
}
if s, ok := datetime.(string); ok {
datetime = parseLegacy(s)
}
return dateTimeFormat(format, datetime)
}

func timeSinceLegacy(time any, _ translation.Locale) template.HTML {
if !setting.IsProd || setting.IsInTesting {
panic("timeSinceLegacy is for backward compatibility only, do not use it in new code")
}
return TimeSince(time)
}
61 changes: 34 additions & 27 deletions modules/templates/util_render.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,21 @@ import (
"code.gitea.io/gitea/modules/util"
)

type RenderUtils struct {
ctx context.Context
}

func NewRenderUtils(ctx context.Context) *RenderUtils {
return &RenderUtils{ctx: ctx}
}

// RenderCommitMessage renders commit message with XSS-safe and special links.
func RenderCommitMessage(ctx context.Context, msg string, metas map[string]string) template.HTML {
func (ut *RenderUtils) RenderCommitMessage(msg string, metas map[string]string) template.HTML {
cleanMsg := template.HTMLEscapeString(msg)
// we can safely assume that it will not return any error, since there
// shouldn't be any special HTML.
fullMessage, err := markup.RenderCommitMessage(&markup.RenderContext{
Ctx: ctx,
Ctx: ut.ctx,
Metas: metas,
}, cleanMsg)
if err != nil {
Expand All @@ -44,9 +52,9 @@ func RenderCommitMessage(ctx context.Context, msg string, metas map[string]strin
return renderCodeBlock(template.HTML(msgLines[0]))
}

// renderCommitMessageLinkSubject renders commit message as a XSS-safe link to
// RenderCommitMessageLinkSubject renders commit message as a XSS-safe link to
// the provided default url, handling for special links without email to links.
func renderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string, metas map[string]string) template.HTML {
func (ut *RenderUtils) RenderCommitMessageLinkSubject(msg, urlDefault string, metas map[string]string) template.HTML {
msgLine := strings.TrimLeftFunc(msg, unicode.IsSpace)
lineEnd := strings.IndexByte(msgLine, '\n')
if lineEnd > 0 {
Expand All @@ -60,7 +68,7 @@ func renderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string,
// we can safely assume that it will not return any error, since there
// shouldn't be any special HTML.
renderedMessage, err := markup.RenderCommitMessageSubject(&markup.RenderContext{
Ctx: ctx,
Ctx: ut.ctx,
DefaultLink: urlDefault,
Metas: metas,
}, template.HTMLEscapeString(msgLine))
Expand All @@ -71,8 +79,8 @@ func renderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string,
return renderCodeBlock(template.HTML(renderedMessage))
}

// renderCommitBody extracts the body of a commit message without its title.
func renderCommitBody(ctx context.Context, msg string, metas map[string]string) template.HTML {
// RenderCommitBody extracts the body of a commit message without its title.
func (ut *RenderUtils) RenderCommitBody(msg string, metas map[string]string) template.HTML {
msgLine := strings.TrimSpace(msg)
lineEnd := strings.IndexByte(msgLine, '\n')
if lineEnd > 0 {
Expand All @@ -86,7 +94,7 @@ func renderCommitBody(ctx context.Context, msg string, metas map[string]string)
}

renderedMessage, err := markup.RenderCommitMessage(&markup.RenderContext{
Ctx: ctx,
Ctx: ut.ctx,
Metas: metas,
}, template.HTMLEscapeString(msgLine))
if err != nil {
Expand All @@ -105,22 +113,22 @@ func renderCodeBlock(htmlEscapedTextToRender template.HTML) template.HTML {
return template.HTML(htmlWithCodeTags)
}

// renderIssueTitle renders issue/pull title with defined post processors
func renderIssueTitle(ctx context.Context, text string, metas map[string]string) template.HTML {
// RenderIssueTitle renders issue/pull title with defined post processors
func (ut *RenderUtils) RenderIssueTitle(text string, metas map[string]string) template.HTML {
renderedText, err := markup.RenderIssueTitle(&markup.RenderContext{
Ctx: ctx,
Ctx: ut.ctx,
Metas: metas,
}, template.HTMLEscapeString(text))
if err != nil {
log.Error("RenderIssueTitle: %v", err)
return template.HTML("")
return ""
}
return template.HTML(renderedText)
}

// renderLabel renders a label
// locale is needed due to an import cycle with our context providing the `Tr` function
func renderLabel(ctx context.Context, locale translation.Locale, label *issues_model.Label) template.HTML {
// RenderLabel renders a label
func (ut *RenderUtils) RenderLabel(label *issues_model.Label) template.HTML {
locale := ut.ctx.Value(translation.ContextKey).(translation.Locale)
var extraCSSClasses string
textColor := util.ContrastColor(label.Color)
labelScope := label.ExclusiveScope()
Expand All @@ -134,12 +142,12 @@ func renderLabel(ctx context.Context, locale translation.Locale, label *issues_m
if labelScope == "" {
// Regular label
return HTMLFormat(`<div class="ui label %s" style="color: %s !important; background-color: %s !important;" data-tooltip-content title="%s">%s</div>`,
extraCSSClasses, textColor, label.Color, descriptionText, renderEmoji(ctx, label.Name))
extraCSSClasses, textColor, label.Color, descriptionText, ut.RenderEmoji(label.Name))
}

// Scoped label
scopeHTML := renderEmoji(ctx, labelScope)
itemHTML := renderEmoji(ctx, label.Name[len(labelScope)+1:])
scopeHTML := ut.RenderEmoji(labelScope)
itemHTML := ut.RenderEmoji(label.Name[len(labelScope)+1:])

// Make scope and item background colors slightly darker and lighter respectively.
// More contrast needed with higher luminance, empirically tweaked.
Expand Down Expand Up @@ -176,13 +184,12 @@ func renderLabel(ctx context.Context, locale translation.Locale, label *issues_m
textColor, itemColor, itemHTML)
}

// renderEmoji renders html text with emoji post processors
func renderEmoji(ctx context.Context, text string) template.HTML {
renderedText, err := markup.RenderEmoji(&markup.RenderContext{Ctx: ctx},
template.HTMLEscapeString(text))
// RenderEmoji renders html text with emoji post processors
func (ut *RenderUtils) RenderEmoji(text string) template.HTML {
renderedText, err := markup.RenderEmoji(&markup.RenderContext{Ctx: ut.ctx}, template.HTMLEscapeString(text))
if err != nil {
log.Error("RenderEmoji: %v", err)
return template.HTML("")
return ""
}
return template.HTML(renderedText)
}
Expand All @@ -200,9 +207,9 @@ func reactionToEmoji(reaction string) template.HTML {
return template.HTML(fmt.Sprintf(`<img alt=":%s:" src="%s/assets/img/emoji/%s.png"></img>`, reaction, setting.StaticURLPrefix, url.PathEscape(reaction)))
}

func RenderMarkdownToHtml(ctx context.Context, input string) template.HTML { //nolint:revive
func (ut *RenderUtils) MarkdownToHtml(input string) template.HTML { //nolint:revive
output, err := markdown.RenderString(&markup.RenderContext{
Ctx: ctx,
Ctx: ut.ctx,
Metas: map[string]string{"mode": "document"},
}, input)
if err != nil {
Expand All @@ -211,7 +218,7 @@ func RenderMarkdownToHtml(ctx context.Context, input string) template.HTML { //n
return output
}

func RenderLabels(ctx context.Context, locale translation.Locale, labels []*issues_model.Label, repoLink string, issue *issues_model.Issue) template.HTML {
func (ut *RenderUtils) RenderLabels(labels []*issues_model.Label, repoLink string, issue *issues_model.Issue) template.HTML {
isPullRequest := issue != nil && issue.IsPull
baseLink := fmt.Sprintf("%s/%s", repoLink, util.Iif(isPullRequest, "pulls", "issues"))
htmlCode := `<span class="labels-list">`
Expand All @@ -220,7 +227,7 @@ func RenderLabels(ctx context.Context, locale translation.Locale, labels []*issu
if label == nil {
continue
}
htmlCode += fmt.Sprintf(`<a href="%s?labels=%d">%s</a>`, baseLink, label.ID, renderLabel(ctx, locale, label))
htmlCode += fmt.Sprintf(`<a href="%s?labels=%d">%s</a>`, baseLink, label.ID, ut.RenderLabel(label))
}
htmlCode += "</span>"
return template.HTML(htmlCode)
Expand Down
40 changes: 40 additions & 0 deletions modules/templates/util_render_legacy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package templates

import (
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/modules/translation"
"context"
"html/template"
)

func renderEmojiLegacy(ctx context.Context, text string) template.HTML {
return NewRenderUtils(ctx).RenderEmoji(text)
}

func renderLabelLegacy(ctx context.Context, locale translation.Locale, label *issues_model.Label) template.HTML {
return NewRenderUtils(ctx).RenderLabel(label)
}

func renderLabelsLegacy(ctx context.Context, locale translation.Locale, labels []*issues_model.Label, repoLink string, issue *issues_model.Issue) template.HTML {
return NewRenderUtils(ctx).RenderLabels(labels, repoLink, issue)
}

func renderMarkdownToHtmlLegacy(ctx context.Context, input string) template.HTML { //nolint:revive
return NewRenderUtils(ctx).MarkdownToHtml(input)
}

func renderCommitMessageLegacy(ctx context.Context, msg string, metas map[string]string) template.HTML {
return NewRenderUtils(ctx).RenderCommitMessage(msg, metas)
}

func renderCommitMessageLinkSubjectLegacy(ctx context.Context, msg, urlDefault string, metas map[string]string) template.HTML {
return NewRenderUtils(ctx).RenderCommitMessageLinkSubject(msg, urlDefault, metas)
}

func renderIssueTitleLegacy(ctx context.Context, text string, metas map[string]string) template.HTML {
return NewRenderUtils(ctx).RenderIssueTitle(text, metas)
}

func renderCommitBodyLegacy(ctx context.Context, msg string, metas map[string]string) template.HTML {
return NewRenderUtils(ctx).RenderCommitBody(msg, metas)
}
3 changes: 2 additions & 1 deletion routers/web/feed/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ func renderMarkdown(ctx *context.Context, act *activities_model.Action, content

// feedActionsToFeedItems convert gitea's Action feed to feeds Item
func feedActionsToFeedItems(ctx *context.Context, actions activities_model.ActionList) (items []*feeds.Item, err error) {
renderUtils := templates.NewRenderUtils(ctx)
for _, act := range actions {
act.LoadActUser(ctx)

Expand Down Expand Up @@ -215,7 +216,7 @@ func feedActionsToFeedItems(ctx *context.Context, actions activities_model.Actio
desc += fmt.Sprintf("<a href=\"%s\">%s</a>\n%s",
html.EscapeString(fmt.Sprintf("%s/commit/%s", act.GetRepoAbsoluteLink(ctx), commit.Sha1)),
commit.Sha1,
templates.RenderCommitMessage(ctx, commit.Message, nil),
renderUtils.RenderCommitMessage(commit.Message, nil),
)
}

Expand Down
6 changes: 3 additions & 3 deletions routers/web/org/projects.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,9 @@ func Projects(ctx *context.Context) {
} else {
ctx.Data["State"] = "open"
}

renderUtils := templates.NewRenderUtils(ctx)
for _, project := range projects {
project.RenderedContent = templates.RenderMarkdownToHtml(ctx, project.Description)
project.RenderedContent = renderUtils.MarkdownToHtml(project.Description)
}

err = shared_user.LoadHeaderCount(ctx)
Expand Down Expand Up @@ -435,7 +435,7 @@ func ViewProject(ctx *context.Context) {
ctx.Data["SelectLabels"] = selectLabels
ctx.Data["AssigneeID"] = assigneeID

project.RenderedContent = templates.RenderMarkdownToHtml(ctx, project.Description)
project.RenderedContent = templates.NewRenderUtils(ctx).MarkdownToHtml(project.Description)
ctx.Data["LinkedPRs"] = linkedPrsMap
ctx.Data["PageIsViewProjects"] = true
ctx.Data["CanWriteProjects"] = canWriteProjects(ctx)
Expand Down
2 changes: 1 addition & 1 deletion routers/web/repo/issue.go
Original file line number Diff line number Diff line change
Expand Up @@ -2215,7 +2215,7 @@ func GetIssueInfo(ctx *context.Context) {

ctx.JSON(http.StatusOK, map[string]any{
"convertedIssue": convert.ToIssue(ctx, ctx.Doer, issue),
"renderedLabels": templates.RenderLabels(ctx, ctx.Locale, issue.Labels, ctx.Repo.RepoLink, issue),
"renderedLabels": templates.NewRenderUtils(ctx).RenderLabels(issue.Labels, ctx.Repo.RepoLink, issue),
})
}

Expand Down
1 change: 1 addition & 0 deletions services/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ func NewTemplateContextForWeb(ctx *Context) TemplateContext {
tmplCtx := NewTemplateContext(ctx)
tmplCtx["Locale"] = ctx.Base.Locale
tmplCtx["AvatarUtils"] = templates.NewAvatarUtils(ctx)
tmplCtx["RenderUtils"] = templates.NewRenderUtils(ctx)
tmplCtx["RootData"] = ctx.Data
tmplCtx["Consts"] = map[string]any{
"RepoUnitTypeCode": unit.TypeCode,
Expand Down
4 changes: 2 additions & 2 deletions templates/base/head_script.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ If you introduce mistakes in it, Gitea JavaScript code wouldn't run correctly.
{{if or .Participants .Assignees .MentionableTeams}}
mentionValues: Array.from(new Map([
{{- range .Participants -}}
['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}', name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink $.Context}}'}],
['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}', name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink ctx}}'}],
{{- end -}}
{{- range .Assignees -}}
['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}', name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink $.Context}}'}],
['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}', name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink ctx}}'}],
{{- end -}}
{{- range .MentionableTeams -}}
['{{$.MentionableTeamsOrg}}/{{.Name}}', {key: '{{$.MentionableTeamsOrg}}/{{.Name}}', value: '{{$.MentionableTeamsOrg}}/{{.Name}}', name: '{{$.MentionableTeamsOrg}}/{{.Name}}', avatar: '{{$.MentionableTeamsOrgAvatar}}'}],
Expand Down
Loading

0 comments on commit 88490e3

Please sign in to comment.