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 8.5KB

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