This repository has no description
0

Configure Feed

Select the types of activity you want to include in your feed.

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