forked from tangled.org/core
Monorepo for Tangled — https://tangled.org
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 treeblood "github.com/wyatt915/goldmark-treeblood" 16 "github.com/yuin/goldmark" 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 htmlparse "golang.org/x/net/html" 26 27 "tangled.org/core/api/tangled" 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 RendererType RendererType 50 Sanitizer Sanitizer 51 Files fs.FS 52} 53 54func NewMarkdown() goldmark.Markdown { 55 md := goldmark.New( 56 goldmark.WithExtensions( 57 extension.GFM, 58 highlighting.NewHighlighting( 59 highlighting.WithFormatOptions( 60 chromahtml.Standalone(false), 61 chromahtml.WithClasses(true), 62 ), 63 highlighting.WithCustomStyle(styles.Get("catppuccin-latte")), 64 ), 65 extension.NewFootnote( 66 extension.WithFootnoteIDPrefix([]byte("footnote")), 67 ), 68 treeblood.MathML(), 69 callout.CalloutExtention, 70 textension.AtExt, 71 ), 72 goldmark.WithParserOptions( 73 parser.WithAutoHeadingID(), 74 ), 75 goldmark.WithRendererOptions(html.WithUnsafe()), 76 ) 77 return md 78} 79 80func (rctx *RenderContext) RenderMarkdown(source string) string { 81 md := NewMarkdown() 82 83 if rctx != nil { 84 var transformers []util.PrioritizedValue 85 86 transformers = append(transformers, util.Prioritized(&MarkdownTransformer{rctx: rctx}, 10000)) 87 88 md.Parser().AddOptions( 89 parser.WithASTTransformers(transformers...), 90 ) 91 } 92 93 var buf bytes.Buffer 94 if err := md.Convert([]byte(source), &buf); err != nil { 95 return source 96 } 97 98 var processed strings.Builder 99 if err := postProcess(rctx, strings.NewReader(buf.String()), &processed); err != nil { 100 return source 101 } 102 103 return processed.String() 104} 105 106func postProcess(ctx *RenderContext, input io.Reader, output io.Writer) error { 107 node, err := htmlparse.Parse(io.MultiReader( 108 strings.NewReader("<html><body>"), 109 input, 110 strings.NewReader("</body></html>"), 111 )) 112 if err != nil { 113 return fmt.Errorf("failed to parse html: %w", err) 114 } 115 116 if node.Type == htmlparse.DocumentNode { 117 node = node.FirstChild 118 } 119 120 visitNode(ctx, node) 121 122 newNodes := make([]*htmlparse.Node, 0, 5) 123 124 if node.Data == "html" { 125 node = node.FirstChild 126 for node != nil && node.Data != "body" { 127 node = node.NextSibling 128 } 129 } 130 if node != nil { 131 if node.Data == "body" { 132 child := node.FirstChild 133 for child != nil { 134 newNodes = append(newNodes, child) 135 child = child.NextSibling 136 } 137 } else { 138 newNodes = append(newNodes, node) 139 } 140 } 141 142 for _, node := range newNodes { 143 if err := htmlparse.Render(output, node); err != nil { 144 return fmt.Errorf("failed to render processed html: %w", err) 145 } 146 } 147 148 return nil 149} 150 151func visitNode(ctx *RenderContext, node *htmlparse.Node) { 152 switch node.Type { 153 case htmlparse.ElementNode: 154 switch node.Data { 155 case "img", "source": 156 for i, attr := range node.Attr { 157 if attr.Key != "src" { 158 continue 159 } 160 161 camoUrl, _ := url.Parse(ctx.CamoUrl) 162 dstUrl, _ := url.Parse(attr.Val) 163 if dstUrl.Host != camoUrl.Host { 164 attr.Val = ctx.imageFromKnotTransformer(attr.Val) 165 attr.Val = ctx.camoImageLinkTransformer(attr.Val) 166 node.Attr[i] = attr 167 } 168 } 169 } 170 171 for n := node.FirstChild; n != nil; n = n.NextSibling { 172 visitNode(ctx, n) 173 } 174 default: 175 } 176} 177 178func (rctx *RenderContext) SanitizeDefault(html string) string { 179 return rctx.Sanitizer.SanitizeDefault(html) 180} 181 182func (rctx *RenderContext) SanitizeDescription(html string) string { 183 return rctx.Sanitizer.SanitizeDescription(html) 184} 185 186type MarkdownTransformer struct { 187 rctx *RenderContext 188} 189 190func (a *MarkdownTransformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) { 191 _ = ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) { 192 if !entering { 193 return ast.WalkContinue, nil 194 } 195 196 switch a.rctx.RendererType { 197 case RendererTypeRepoMarkdown: 198 switch n := n.(type) { 199 case *ast.Heading: 200 a.rctx.anchorHeadingTransformer(n) 201 case *ast.Link: 202 a.rctx.relativeLinkTransformer(n) 203 case *ast.Image: 204 a.rctx.imageFromKnotAstTransformer(n) 205 a.rctx.camoImageLinkAstTransformer(n) 206 } 207 case RendererTypeDefault: 208 switch n := n.(type) { 209 case *ast.Heading: 210 a.rctx.anchorHeadingTransformer(n) 211 case *ast.Image: 212 a.rctx.imageFromKnotAstTransformer(n) 213 a.rctx.camoImageLinkAstTransformer(n) 214 } 215 } 216 217 return ast.WalkContinue, nil 218 }) 219} 220 221func (rctx *RenderContext) relativeLinkTransformer(link *ast.Link) { 222 223 dst := string(link.Destination) 224 225 if isAbsoluteUrl(dst) || isFragment(dst) || isMail(dst) { 226 return 227 } 228 229 actualPath := rctx.actualPath(dst) 230 231 newPath := path.Join("/", rctx.RepoInfo.FullName(), "tree", rctx.RepoInfo.Ref, actualPath) 232 link.Destination = []byte(newPath) 233} 234 235func (rctx *RenderContext) imageFromKnotTransformer(dst string) string { 236 if isAbsoluteUrl(dst) { 237 return dst 238 } 239 240 scheme := "https" 241 if rctx.IsDev { 242 scheme = "http" 243 } 244 245 actualPath := rctx.actualPath(dst) 246 247 repoName := fmt.Sprintf("%s/%s", rctx.RepoInfo.OwnerDid, rctx.RepoInfo.Name) 248 249 query := fmt.Sprintf("repo=%s&ref=%s&path=%s&raw=true", 250 url.PathEscape(repoName), url.PathEscape(rctx.RepoInfo.Ref), actualPath) 251 252 parsedURL := &url.URL{ 253 Scheme: scheme, 254 Host: rctx.Knot, 255 Path: path.Join("/xrpc", tangled.RepoBlobNSID), 256 RawQuery: query, 257 } 258 newPath := parsedURL.String() 259 return newPath 260} 261 262func (rctx *RenderContext) imageFromKnotAstTransformer(img *ast.Image) { 263 dst := string(img.Destination) 264 img.Destination = []byte(rctx.imageFromKnotTransformer(dst)) 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 305// FindUserMentions returns Set of user handles from given markup soruce. 306// It doesn't guarntee unique DIDs 307func FindUserMentions(source string) []string { 308 var ( 309 mentions []string 310 mentionsSet = make(map[string]struct{}) 311 md = NewMarkdown() 312 sourceBytes = []byte(source) 313 root = md.Parser().Parse(text.NewReader(sourceBytes)) 314 ) 315 ast.Walk(root, func(n ast.Node, entering bool) (ast.WalkStatus, error) { 316 if entering && n.Kind() == textension.KindAt { 317 handle := n.(*textension.AtNode).Handle 318 mentionsSet[handle] = struct{}{} 319 return ast.WalkSkipChildren, nil 320 } 321 return ast.WalkContinue, nil 322 }) 323 for handle := range mentionsSet { 324 mentions = append(mentions, handle) 325 } 326 return mentions 327} 328 329func isAbsoluteUrl(link string) bool { 330 parsed, err := url.Parse(link) 331 if err != nil { 332 return false 333 } 334 return parsed.IsAbs() 335} 336 337func isFragment(link string) bool { 338 return strings.HasPrefix(link, "#") 339} 340 341func isMail(link string) bool { 342 return strings.HasPrefix(link, "mailto:") 343}