aboutsummaryrefslogtreecommitdiffstats
path: root/modules/markup/html_node.go
blob: a7c323fcba8a92391cbdb9b2170ea0bbc6718fc5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright 2024 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package markup

import (
	"code.gitea.io/gitea/modules/util"

	"golang.org/x/net/html"
)

func visitNodeImg(ctx *RenderContext, img *html.Node) (next *html.Node) {
	next = img.NextSibling
	for i, attr := range img.Attr {
		if attr.Key != "src" {
			continue
		}

		if IsNonEmptyRelativePath(attr.Val) {
			attr.Val = util.URLJoin(ctx.RenderOptions.Links.ResolveMediaLink(ctx.IsMarkupContentWiki()), attr.Val)

			// By default, the "<img>" tag should also be clickable,
			// because frontend use `<img>` to paste the re-scaled image into the markdown,
			// so it must match the default markdown image behavior.
			hasParentAnchor := false
			for p := img.Parent; p != nil; p = p.Parent {
				if hasParentAnchor = p.Type == html.ElementNode && p.Data == "a"; hasParentAnchor {
					break
				}
			}
			if !hasParentAnchor {
				imgA := &html.Node{Type: html.ElementNode, Data: "a", Attr: []html.Attribute{
					{Key: "href", Val: attr.Val},
					{Key: "target", Val: "_blank"},
				}}
				parent := img.Parent
				imgNext := img.NextSibling
				parent.RemoveChild(img)
				parent.InsertBefore(imgA, imgNext)
				imgA.AppendChild(img)
			}
		}
		attr.Val = camoHandleLink(attr.Val)
		img.Attr[i] = attr
	}
	return next
}

func visitNodeVideo(ctx *RenderContext, node *html.Node) (next *html.Node) {
	next = node.NextSibling
	for i, attr := range node.Attr {
		if attr.Key != "src" {
			continue
		}
		if IsNonEmptyRelativePath(attr.Val) {
			attr.Val = util.URLJoin(ctx.RenderOptions.Links.ResolveMediaLink(ctx.IsMarkupContentWiki()), attr.Val)
		}
		attr.Val = camoHandleLink(attr.Val)
		node.Attr[i] = attr
	}
	return next
}