You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

util_render.go 7.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package templates
  4. import (
  5. "context"
  6. "encoding/hex"
  7. "fmt"
  8. "html/template"
  9. "math"
  10. "net/url"
  11. "regexp"
  12. "strings"
  13. "unicode"
  14. issues_model "code.gitea.io/gitea/models/issues"
  15. "code.gitea.io/gitea/modules/emoji"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/markup"
  18. "code.gitea.io/gitea/modules/markup/markdown"
  19. "code.gitea.io/gitea/modules/setting"
  20. "code.gitea.io/gitea/modules/util"
  21. )
  22. // RenderCommitMessage renders commit message with XSS-safe and special links.
  23. func RenderCommitMessage(ctx context.Context, msg string, metas map[string]string) template.HTML {
  24. cleanMsg := template.HTMLEscapeString(msg)
  25. // we can safely assume that it will not return any error, since there
  26. // shouldn't be any special HTML.
  27. fullMessage, err := markup.RenderCommitMessage(&markup.RenderContext{
  28. Ctx: ctx,
  29. Metas: metas,
  30. }, cleanMsg)
  31. if err != nil {
  32. log.Error("RenderCommitMessage: %v", err)
  33. return ""
  34. }
  35. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  36. if len(msgLines) == 0 {
  37. return template.HTML("")
  38. }
  39. return template.HTML(msgLines[0])
  40. }
  41. // RenderCommitMessageLinkSubject renders commit message as a XSS-safe link to
  42. // the provided default url, handling for special links without email to links.
  43. func RenderCommitMessageLinkSubject(ctx context.Context, msg, urlDefault string, metas map[string]string) template.HTML {
  44. msgLine := strings.TrimLeftFunc(msg, unicode.IsSpace)
  45. lineEnd := strings.IndexByte(msgLine, '\n')
  46. if lineEnd > 0 {
  47. msgLine = msgLine[:lineEnd]
  48. }
  49. msgLine = strings.TrimRightFunc(msgLine, unicode.IsSpace)
  50. if len(msgLine) == 0 {
  51. return template.HTML("")
  52. }
  53. // we can safely assume that it will not return any error, since there
  54. // shouldn't be any special HTML.
  55. renderedMessage, err := markup.RenderCommitMessageSubject(&markup.RenderContext{
  56. Ctx: ctx,
  57. DefaultLink: urlDefault,
  58. Metas: metas,
  59. }, template.HTMLEscapeString(msgLine))
  60. if err != nil {
  61. log.Error("RenderCommitMessageSubject: %v", err)
  62. return template.HTML("")
  63. }
  64. return template.HTML(renderedMessage)
  65. }
  66. // RenderCommitBody extracts the body of a commit message without its title.
  67. func RenderCommitBody(ctx context.Context, msg string, metas map[string]string) template.HTML {
  68. msgLine := strings.TrimSpace(msg)
  69. lineEnd := strings.IndexByte(msgLine, '\n')
  70. if lineEnd > 0 {
  71. msgLine = msgLine[lineEnd+1:]
  72. } else {
  73. return ""
  74. }
  75. msgLine = strings.TrimLeftFunc(msgLine, unicode.IsSpace)
  76. if len(msgLine) == 0 {
  77. return ""
  78. }
  79. renderedMessage, err := markup.RenderCommitMessage(&markup.RenderContext{
  80. Ctx: ctx,
  81. Metas: metas,
  82. }, template.HTMLEscapeString(msgLine))
  83. if err != nil {
  84. log.Error("RenderCommitMessage: %v", err)
  85. return ""
  86. }
  87. return template.HTML(renderedMessage)
  88. }
  89. // Match text that is between back ticks.
  90. var codeMatcher = regexp.MustCompile("`([^`]+)`")
  91. // RenderCodeBlock renders "`…`" as highlighted "<code>" block, intended for issue and PR titles
  92. func RenderCodeBlock(htmlEscapedTextToRender template.HTML) template.HTML {
  93. htmlWithCodeTags := codeMatcher.ReplaceAllString(string(htmlEscapedTextToRender), `<code class="inline-code-block">$1</code>`) // replace with HTML <code> tags
  94. return template.HTML(htmlWithCodeTags)
  95. }
  96. // RenderIssueTitle renders issue/pull title with defined post processors
  97. func RenderIssueTitle(ctx context.Context, text string, metas map[string]string) template.HTML {
  98. renderedText, err := markup.RenderIssueTitle(&markup.RenderContext{
  99. Ctx: ctx,
  100. Metas: metas,
  101. }, template.HTMLEscapeString(text))
  102. if err != nil {
  103. log.Error("RenderIssueTitle: %v", err)
  104. return template.HTML("")
  105. }
  106. return template.HTML(renderedText)
  107. }
  108. // RenderLabel renders a label
  109. func RenderLabel(ctx context.Context, label *issues_model.Label) template.HTML {
  110. labelScope := label.ExclusiveScope()
  111. textColor := "#111"
  112. r, g, b := util.HexToRBGColor(label.Color)
  113. // Determine if label text should be light or dark to be readable on background color
  114. if util.UseLightTextOnBackground(r, g, b) {
  115. textColor = "#eee"
  116. }
  117. description := emoji.ReplaceAliases(template.HTMLEscapeString(label.Description))
  118. if labelScope == "" {
  119. // Regular label
  120. s := fmt.Sprintf("<div class='ui label' style='color: %s !important; background-color: %s !important' data-tooltip-content title='%s'>%s</div>",
  121. textColor, label.Color, description, RenderEmoji(ctx, label.Name))
  122. return template.HTML(s)
  123. }
  124. // Scoped label
  125. scopeText := RenderEmoji(ctx, labelScope)
  126. itemText := RenderEmoji(ctx, label.Name[len(labelScope)+1:])
  127. // Make scope and item background colors slightly darker and lighter respectively.
  128. // More contrast needed with higher luminance, empirically tweaked.
  129. luminance := util.GetLuminance(r, g, b)
  130. contrast := 0.01 + luminance*0.03
  131. // Ensure we add the same amount of contrast also near 0 and 1.
  132. darken := contrast + math.Max(luminance+contrast-1.0, 0.0)
  133. lighten := contrast + math.Max(contrast-luminance, 0.0)
  134. // Compute factor to keep RGB values proportional.
  135. darkenFactor := math.Max(luminance-darken, 0.0) / math.Max(luminance, 1.0/255.0)
  136. lightenFactor := math.Min(luminance+lighten, 1.0) / math.Max(luminance, 1.0/255.0)
  137. scopeBytes := []byte{
  138. uint8(math.Min(math.Round(r*darkenFactor), 255)),
  139. uint8(math.Min(math.Round(g*darkenFactor), 255)),
  140. uint8(math.Min(math.Round(b*darkenFactor), 255)),
  141. }
  142. itemBytes := []byte{
  143. uint8(math.Min(math.Round(r*lightenFactor), 255)),
  144. uint8(math.Min(math.Round(g*lightenFactor), 255)),
  145. uint8(math.Min(math.Round(b*lightenFactor), 255)),
  146. }
  147. itemColor := "#" + hex.EncodeToString(itemBytes)
  148. scopeColor := "#" + hex.EncodeToString(scopeBytes)
  149. s := fmt.Sprintf("<span class='ui label scope-parent' data-tooltip-content title='%s'>"+
  150. "<div class='ui label scope-left' style='color: %s !important; background-color: %s !important'>%s</div>"+
  151. "<div class='ui label scope-right' style='color: %s !important; background-color: %s !important'>%s</div>"+
  152. "</span>",
  153. description,
  154. textColor, scopeColor, scopeText,
  155. textColor, itemColor, itemText)
  156. return template.HTML(s)
  157. }
  158. // RenderEmoji renders html text with emoji post processors
  159. func RenderEmoji(ctx context.Context, text string) template.HTML {
  160. renderedText, err := markup.RenderEmoji(&markup.RenderContext{Ctx: ctx},
  161. template.HTMLEscapeString(text))
  162. if err != nil {
  163. log.Error("RenderEmoji: %v", err)
  164. return template.HTML("")
  165. }
  166. return template.HTML(renderedText)
  167. }
  168. // ReactionToEmoji renders emoji for use in reactions
  169. func ReactionToEmoji(reaction string) template.HTML {
  170. val := emoji.FromCode(reaction)
  171. if val != nil {
  172. return template.HTML(val.Emoji)
  173. }
  174. val = emoji.FromAlias(reaction)
  175. if val != nil {
  176. return template.HTML(val.Emoji)
  177. }
  178. return template.HTML(fmt.Sprintf(`<img alt=":%s:" src="%s/assets/img/emoji/%s.png"></img>`, reaction, setting.StaticURLPrefix, url.PathEscape(reaction)))
  179. }
  180. func RenderMarkdownToHtml(ctx context.Context, input string) template.HTML { //nolint:revive
  181. output, err := markdown.RenderString(&markup.RenderContext{
  182. Ctx: ctx,
  183. Metas: map[string]string{"mode": "document"},
  184. }, input)
  185. if err != nil {
  186. log.Error("RenderString: %v", err)
  187. }
  188. return template.HTML(output)
  189. }
  190. func RenderLabels(ctx context.Context, labels []*issues_model.Label, repoLink string) template.HTML {
  191. htmlCode := `<span class="labels-list">`
  192. for _, label := range labels {
  193. // Protect against nil value in labels - shouldn't happen but would cause a panic if so
  194. if label == nil {
  195. continue
  196. }
  197. htmlCode += fmt.Sprintf("<a href='%s/issues?labels=%d'>%s</a> ",
  198. repoLink, label.ID, RenderLabel(ctx, label))
  199. }
  200. htmlCode += "</span>"
  201. return template.HTML(htmlCode)
  202. }