this repo has no description
1// Package markup is an umbrella package for all markups and their renderers.
2package markup
3
4import (
5 "bytes"
6 "fmt"
7 "io"
8 "net/url"
9 "path"
10 "strings"
11
12 chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
13 "github.com/alecthomas/chroma/v2/styles"
14 "github.com/yuin/goldmark"
15 highlighting "github.com/yuin/goldmark-highlighting/v2"
16 "github.com/yuin/goldmark/ast"
17 "github.com/yuin/goldmark/extension"
18 "github.com/yuin/goldmark/parser"
19 "github.com/yuin/goldmark/renderer/html"
20 "github.com/yuin/goldmark/text"
21 "github.com/yuin/goldmark/util"
22 htmlparse "golang.org/x/net/html"
23
24 "tangled.sh/tangled.sh/core/appview/pages/repoinfo"
25)
26
27// RendererType defines the type of renderer to use based on context
28type RendererType int
29
30const (
31 // RendererTypeRepoMarkdown is for repository documentation markdown files
32 RendererTypeRepoMarkdown RendererType = iota
33 // RendererTypeDefault is non-repo markdown, like issues/pulls/comments.
34 RendererTypeDefault
35)
36
37// RenderContext holds the contextual data for rendering markdown.
38// It can be initialized empty, and that'll skip any transformations.
39type RenderContext struct {
40 CamoUrl string
41 CamoSecret string
42 repoinfo.RepoInfo
43 IsDev bool
44 RendererType RendererType
45 Sanitizer Sanitizer
46}
47
48func (rctx *RenderContext) RenderMarkdown(source string) string {
49 md := goldmark.New(
50 goldmark.WithExtensions(
51 extension.GFM,
52 highlighting.NewHighlighting(
53 highlighting.WithFormatOptions(
54 chromahtml.Standalone(false),
55 chromahtml.WithClasses(true),
56 ),
57 highlighting.WithCustomStyle(styles.Get("catppuccin-latte")),
58 ),
59 extension.NewFootnote(
60 extension.WithFootnoteIDPrefix([]byte("footnote")),
61 ),
62 ),
63 goldmark.WithParserOptions(
64 parser.WithAutoHeadingID(),
65 ),
66 goldmark.WithRendererOptions(html.WithUnsafe()),
67 )
68
69 if rctx != nil {
70 var transformers []util.PrioritizedValue
71
72 transformers = append(transformers, util.Prioritized(&MarkdownTransformer{rctx: rctx}, 10000))
73
74 md.Parser().AddOptions(
75 parser.WithASTTransformers(transformers...),
76 )
77 }
78
79 var buf bytes.Buffer
80 if err := md.Convert([]byte(source), &buf); err != nil {
81 return source
82 }
83
84 var processed strings.Builder
85 if err := postProcess(rctx, strings.NewReader(buf.String()), &processed); err != nil {
86 return source
87 }
88
89 return processed.String()
90}
91
92func postProcess(ctx *RenderContext, input io.Reader, output io.Writer) error {
93 node, err := htmlparse.Parse(io.MultiReader(
94 strings.NewReader("<html><body>"),
95 input,
96 strings.NewReader("</body></html>"),
97 ))
98 if err != nil {
99 return fmt.Errorf("failed to parse html: %w", err)
100 }
101
102 if node.Type == htmlparse.DocumentNode {
103 node = node.FirstChild
104 }
105
106 visitNode(ctx, node)
107
108 newNodes := make([]*htmlparse.Node, 0, 5)
109
110 if node.Data == "html" {
111 node = node.FirstChild
112 for node != nil && node.Data != "body" {
113 node = node.NextSibling
114 }
115 }
116 if node != nil {
117 if node.Data == "body" {
118 child := node.FirstChild
119 for child != nil {
120 newNodes = append(newNodes, child)
121 child = child.NextSibling
122 }
123 } else {
124 newNodes = append(newNodes, node)
125 }
126 }
127
128 for _, node := range newNodes {
129 if err := htmlparse.Render(output, node); err != nil {
130 return fmt.Errorf("failed to render processed html: %w", err)
131 }
132 }
133
134 return nil
135}
136
137func visitNode(ctx *RenderContext, node *htmlparse.Node) {
138 switch node.Type {
139 case htmlparse.ElementNode:
140 if node.Data == "img" || node.Data == "source" {
141 for i, attr := range node.Attr {
142 if attr.Key != "src" {
143 continue
144 }
145
146 camoUrl, _ := url.Parse(ctx.CamoUrl)
147 dstUrl, _ := url.Parse(attr.Val)
148 if dstUrl.Host != camoUrl.Host {
149 attr.Val = ctx.imageFromKnotTransformer(attr.Val)
150 attr.Val = ctx.camoImageLinkTransformer(attr.Val)
151 node.Attr[i] = attr
152 }
153 }
154 }
155
156 for n := node.FirstChild; n != nil; n = n.NextSibling {
157 visitNode(ctx, n)
158 }
159 default:
160 }
161}
162
163func (rctx *RenderContext) SanitizeDefault(html string) string {
164 return rctx.Sanitizer.defaultPolicy.Sanitize(html)
165}
166
167type MarkdownTransformer struct {
168 rctx *RenderContext
169}
170
171func (a *MarkdownTransformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) {
172 _ = ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
173 if !entering {
174 return ast.WalkContinue, nil
175 }
176
177 switch a.rctx.RendererType {
178 case RendererTypeRepoMarkdown:
179 switch n := n.(type) {
180 case *ast.Heading:
181 a.rctx.anchorHeadingTransformer(n)
182 case *ast.Link:
183 a.rctx.relativeLinkTransformer(n)
184 case *ast.Image:
185 a.rctx.imageFromKnotAstTransformer(n)
186 a.rctx.camoImageLinkAstTransformer(n)
187 }
188 case RendererTypeDefault:
189 switch n := n.(type) {
190 case *ast.Heading:
191 a.rctx.anchorHeadingTransformer(n)
192 case *ast.Image:
193 a.rctx.imageFromKnotAstTransformer(n)
194 a.rctx.camoImageLinkAstTransformer(n)
195 }
196 }
197
198 return ast.WalkContinue, nil
199 })
200}
201
202func (rctx *RenderContext) relativeLinkTransformer(link *ast.Link) {
203
204 dst := string(link.Destination)
205
206 if isAbsoluteUrl(dst) || isFragment(dst) || isMail(dst) {
207 return
208 }
209
210 actualPath := rctx.actualPath(dst)
211
212 newPath := path.Join("/", rctx.RepoInfo.FullName(), "tree", rctx.RepoInfo.Ref, actualPath)
213 link.Destination = []byte(newPath)
214}
215
216func (rctx *RenderContext) imageFromKnotTransformer(dst string) string {
217 if isAbsoluteUrl(dst) {
218 return dst
219 }
220
221 scheme := "https"
222 if rctx.IsDev {
223 scheme = "http"
224 }
225
226 actualPath := rctx.actualPath(dst)
227
228 parsedURL := &url.URL{
229 Scheme: scheme,
230 Host: rctx.Knot,
231 Path: path.Join("/",
232 rctx.RepoInfo.OwnerDid,
233 rctx.RepoInfo.Name,
234 "raw",
235 url.PathEscape(rctx.RepoInfo.Ref),
236 actualPath),
237 }
238 newPath := parsedURL.String()
239 return newPath
240}
241
242func (rctx *RenderContext) imageFromKnotAstTransformer(img *ast.Image) {
243 dst := string(img.Destination)
244 img.Destination = []byte(rctx.imageFromKnotTransformer(dst))
245}
246
247func (rctx *RenderContext) anchorHeadingTransformer(h *ast.Heading) {
248 idGeneric, exists := h.AttributeString("id")
249 if !exists {
250 return // no id, nothing to do
251 }
252 id, ok := idGeneric.([]byte)
253 if !ok {
254 return
255 }
256
257 // create anchor link
258 anchor := ast.NewLink()
259 anchor.Destination = fmt.Appendf(nil, "#%s", string(id))
260 anchor.SetAttribute([]byte("class"), []byte("anchor"))
261
262 // create icon text
263 iconText := ast.NewString([]byte("#"))
264 anchor.AppendChild(anchor, iconText)
265
266 // set class on heading
267 h.SetAttribute([]byte("class"), []byte("heading"))
268
269 // append anchor to heading
270 h.AppendChild(h, anchor)
271}
272
273// actualPath decides when to join the file path with the
274// current repository directory (essentially only when the link
275// destination is relative. if it's absolute then we assume the
276// user knows what they're doing.)
277func (rctx *RenderContext) actualPath(dst string) string {
278 if path.IsAbs(dst) {
279 return dst
280 }
281
282 return path.Join(rctx.CurrentDir, dst)
283}
284
285func isAbsoluteUrl(link string) bool {
286 parsed, err := url.Parse(link)
287 if err != nil {
288 return false
289 }
290 return parsed.IsAbs()
291}
292
293func isFragment(link string) bool {
294 return strings.HasPrefix(link, "#")
295}
296
297func isMail(link string) bool {
298 return strings.HasPrefix(link, "mailto:")
299}