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.

transform_image.go 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2024 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package markdown
  4. import (
  5. "strings"
  6. "code.gitea.io/gitea/modules/markup"
  7. giteautil "code.gitea.io/gitea/modules/util"
  8. "github.com/yuin/goldmark/ast"
  9. )
  10. func (g *ASTTransformer) transformImage(ctx *markup.RenderContext, v *ast.Image) {
  11. // Images need two things:
  12. //
  13. // 1. Their src needs to munged to be a real value
  14. // 2. If they're not wrapped with a link they need a link wrapper
  15. // Check if the destination is a real link
  16. if len(v.Destination) > 0 && !markup.IsFullURLBytes(v.Destination) {
  17. v.Destination = []byte(giteautil.URLJoin(
  18. ctx.Links.ResolveMediaLink(ctx.IsWiki),
  19. strings.TrimLeft(string(v.Destination), "/"),
  20. ))
  21. }
  22. parent := v.Parent()
  23. // Create a link around image only if parent is not already a link
  24. if _, ok := parent.(*ast.Link); !ok && parent != nil {
  25. next := v.NextSibling()
  26. // Create a link wrapper
  27. wrap := ast.NewLink()
  28. wrap.Destination = v.Destination
  29. wrap.Title = v.Title
  30. wrap.SetAttributeString("target", []byte("_blank"))
  31. // Duplicate the current image node
  32. image := ast.NewImage(ast.NewLink())
  33. image.Destination = v.Destination
  34. image.Title = v.Title
  35. for _, attr := range v.Attributes() {
  36. image.SetAttribute(attr.Name, attr.Value)
  37. }
  38. for child := v.FirstChild(); child != nil; {
  39. next := child.NextSibling()
  40. image.AppendChild(image, child)
  41. child = next
  42. }
  43. // Append our duplicate image to the wrapper link
  44. wrap.AppendChild(wrap, image)
  45. // Wire in the next sibling
  46. wrap.SetNextSibling(next)
  47. // Replace the current node with the wrapper link
  48. parent.ReplaceChild(parent, v, wrap)
  49. // But most importantly ensure the next sibling is still on the old image too
  50. v.SetNextSibling(next)
  51. }
  52. }