mirror of
https://codeberg.org/forgejo/forgejo.git
synced 2025-09-12 22:07:17 +00:00
This PR fixes the duplicate HTML ID issue (#8778) that can occur when rendering an issue page. An issue page contains multiple renderings of Markdown elements (the issue description and issue comments). When there is more than one Markdown rendering that uses footnotes we have an ID collision because the footnote ID count starts anew for each rendering. This PR adds a `Metas["scope"]` entry to the `RenderContext` and sets it to "comment-{index}" when rendering Markdown for a comment. `Metas["scope"]` gets used as suffix during ID generation. Fixes #8778. ## Additional Notes - ID collision also happens if there are multiple header elements with the same ID. It does not seem to impact users because there are no links referencing headers. However, to err on the safe side, this PR also adds scope to the header IDs. - `Metas["scope"]` might be useful for other Markdown renderings beside comments, e.g. multiple Markdown renderings are possible on Wiki pages. - We apply `Metas["scope"]` as suffix instead of prefix because there are several places in the code that expect `user-content-` to be the ID's prefix. ## Checklist The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org). ### Tests - I added test coverage for Go changes... - [X] in their respective `*_test.go` for unit tests. - [ ] in the `tests/integration` directory if it involves interactions with a live Forgejo server. - I added test coverage for JavaScript changes... - [ ] in `web_src/js/*.test.js` if it can be unit tested. - [ ] in `tests/e2e/*.test.e2e.js` if it requires interactions with a live Forgejo server (see also the [developer guide for JavaScript testing](https://codeberg.org/forgejo/forgejo/src/branch/forgejo/tests/e2e/README.md#end-to-end-tests)). ### Documentation - [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change. - [ ] I did not document these changes and I do not expect someone else to do it. ### Release notes - [ ] I do not want this change to show in the release notes. - [X] I want the title to show in the release notes with a link to this pull request. - [ ] I want the content of the `release-notes/<pull request number>.md` to be be used for the release notes instead of the title. Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/8880 Reviewed-by: Otto <otto@codeberg.org> Co-authored-by: psii <psii@posteo.de> Co-committed-by: psii <psii@posteo.de>
226 lines
5.9 KiB
Go
226 lines
5.9 KiB
Go
// Copyright 2019 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package markdown
|
|
|
|
import (
|
|
"fmt"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"forgejo.org/modules/markup"
|
|
"forgejo.org/modules/markup/common"
|
|
markdownutil "forgejo.org/modules/markup/markdown/util"
|
|
"forgejo.org/modules/setting"
|
|
|
|
"github.com/yuin/goldmark/ast"
|
|
east "github.com/yuin/goldmark/extension/ast"
|
|
"github.com/yuin/goldmark/parser"
|
|
"github.com/yuin/goldmark/renderer"
|
|
"github.com/yuin/goldmark/renderer/html"
|
|
"github.com/yuin/goldmark/text"
|
|
"github.com/yuin/goldmark/util"
|
|
)
|
|
|
|
var byteMailto = []byte("mailto:")
|
|
|
|
// ASTTransformer is a default transformer of the goldmark tree.
|
|
type ASTTransformer struct{}
|
|
|
|
func (g *ASTTransformer) applyElementDir(n ast.Node) {
|
|
if markup.DefaultProcessorHelper.ElementDir != "" {
|
|
n.SetAttributeString("dir", []byte(markup.DefaultProcessorHelper.ElementDir))
|
|
}
|
|
}
|
|
|
|
// Transform transforms the given AST tree.
|
|
func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) {
|
|
firstChild := node.FirstChild()
|
|
tocMode := ""
|
|
ctx := pc.Get(markdownutil.RenderContextKey).(*markup.RenderContext)
|
|
rc := pc.Get(markdownutil.RenderConfigKey).(*RenderConfig)
|
|
|
|
tocList := make([]markup.Header, 0, 20)
|
|
if rc.yamlNode != nil {
|
|
metaNode := rc.toMetaNode()
|
|
if metaNode != nil {
|
|
node.InsertBefore(node, firstChild, metaNode)
|
|
}
|
|
tocMode = rc.TOC
|
|
}
|
|
|
|
_ = ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
|
|
if !entering {
|
|
return ast.WalkContinue, nil
|
|
}
|
|
|
|
switch v := n.(type) {
|
|
case *ast.Heading:
|
|
g.transformHeading(ctx, v, reader, &tocList)
|
|
case *ast.Paragraph:
|
|
g.applyElementDir(v)
|
|
case *ast.Image:
|
|
g.transformImage(ctx, v)
|
|
case *ast.Link:
|
|
g.transformLink(ctx, v)
|
|
case *ast.List:
|
|
g.transformList(ctx, v, rc)
|
|
case *ast.Text:
|
|
if v.SoftLineBreak() && !v.HardLineBreak() {
|
|
if ctx.Metas["mode"] != "document" {
|
|
v.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInComments)
|
|
} else {
|
|
v.SetHardLineBreak(setting.Markdown.EnableHardLineBreakInDocuments)
|
|
}
|
|
}
|
|
case *ast.CodeSpan:
|
|
g.transformCodeSpan(ctx, v, reader)
|
|
case *common.Footnote:
|
|
if scope, found := ctx.Metas["scope"]; found {
|
|
v.Name = fmt.Appendf(v.Name, "-%s", scope)
|
|
}
|
|
case *common.FootnoteLink:
|
|
if scope, found := ctx.Metas["scope"]; found {
|
|
v.Name = fmt.Appendf(v.Name, "-%s", scope)
|
|
}
|
|
case *common.FootnoteBackLink:
|
|
if scope, found := ctx.Metas["scope"]; found {
|
|
v.Name = fmt.Appendf(v.Name, "-%s", scope)
|
|
}
|
|
}
|
|
return ast.WalkContinue, nil
|
|
})
|
|
|
|
showTocInMain := tocMode == "true" /* old behavior, in main view */ || tocMode == "main"
|
|
showTocInSidebar := !showTocInMain && tocMode != "false" // not hidden, not main, then show it in sidebar
|
|
if len(tocList) > 0 && (showTocInMain || showTocInSidebar) {
|
|
if showTocInMain {
|
|
tocNode := createTOCNode(tocList, rc.Lang, nil)
|
|
node.InsertBefore(node, firstChild, tocNode)
|
|
} else {
|
|
tocNode := createTOCNode(tocList, rc.Lang, map[string]string{"open": "open"})
|
|
ctx.SidebarTocNode = tocNode
|
|
}
|
|
}
|
|
|
|
if len(rc.Lang) > 0 {
|
|
node.SetAttributeString("lang", []byte(rc.Lang))
|
|
}
|
|
}
|
|
|
|
// NewHTMLRenderer creates a HTMLRenderer to render
|
|
// in the gitea form.
|
|
func NewHTMLRenderer(opts ...html.Option) renderer.NodeRenderer {
|
|
r := &HTMLRenderer{
|
|
Config: html.NewConfig(),
|
|
}
|
|
for _, opt := range opts {
|
|
opt.SetHTMLOption(&r.Config)
|
|
}
|
|
return r
|
|
}
|
|
|
|
// HTMLRenderer is a renderer.NodeRenderer implementation that
|
|
// renders gitea specific features.
|
|
type HTMLRenderer struct {
|
|
html.Config
|
|
}
|
|
|
|
// RegisterFuncs implements renderer.NodeRenderer.RegisterFuncs.
|
|
func (r *HTMLRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
|
|
reg.Register(ast.KindDocument, r.renderDocument)
|
|
reg.Register(KindDetails, r.renderDetails)
|
|
reg.Register(KindSummary, r.renderSummary)
|
|
reg.Register(KindIcon, r.renderIcon)
|
|
reg.Register(ast.KindCodeSpan, r.renderCodeSpan)
|
|
reg.Register(KindTaskCheckBoxListItem, r.renderTaskCheckBoxListItem)
|
|
reg.Register(east.KindTaskCheckBox, r.renderTaskCheckBox)
|
|
}
|
|
|
|
func (r *HTMLRenderer) renderDocument(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
|
|
n := node.(*ast.Document)
|
|
|
|
if val, has := n.AttributeString("lang"); has {
|
|
var err error
|
|
if entering {
|
|
_, err = w.WriteString("<div")
|
|
if err == nil {
|
|
_, err = fmt.Fprintf(w, ` lang=%q`, val)
|
|
}
|
|
if err == nil {
|
|
_, err = w.WriteRune('>')
|
|
}
|
|
} else {
|
|
_, err = w.WriteString("</div>")
|
|
}
|
|
|
|
if err != nil {
|
|
return ast.WalkStop, err
|
|
}
|
|
}
|
|
|
|
return ast.WalkContinue, nil
|
|
}
|
|
|
|
func (r *HTMLRenderer) renderDetails(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
|
|
var err error
|
|
if entering {
|
|
if _, err = w.WriteString("<details"); err != nil {
|
|
return ast.WalkStop, err
|
|
}
|
|
html.RenderAttributes(w, node, nil)
|
|
_, err = w.WriteString(">")
|
|
} else {
|
|
_, err = w.WriteString("</details>")
|
|
}
|
|
|
|
if err != nil {
|
|
return ast.WalkStop, err
|
|
}
|
|
|
|
return ast.WalkContinue, nil
|
|
}
|
|
|
|
func (r *HTMLRenderer) renderSummary(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
|
|
var err error
|
|
if entering {
|
|
_, err = w.WriteString("<summary>")
|
|
} else {
|
|
_, err = w.WriteString("</summary>")
|
|
}
|
|
|
|
if err != nil {
|
|
return ast.WalkStop, err
|
|
}
|
|
|
|
return ast.WalkContinue, nil
|
|
}
|
|
|
|
var validNameRE = regexp.MustCompile("^[a-z ]+$")
|
|
|
|
func (r *HTMLRenderer) renderIcon(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
|
|
if !entering {
|
|
return ast.WalkContinue, nil
|
|
}
|
|
|
|
n := node.(*Icon)
|
|
|
|
name := strings.TrimSpace(strings.ToLower(string(n.Name)))
|
|
|
|
if len(name) == 0 {
|
|
// skip this
|
|
return ast.WalkContinue, nil
|
|
}
|
|
|
|
if !validNameRE.MatchString(name) {
|
|
// skip this
|
|
return ast.WalkContinue, nil
|
|
}
|
|
|
|
_, err := fmt.Fprintf(w, `<i class="icon %s"></i>`, name)
|
|
if err != nil {
|
|
return ast.WalkStop, err
|
|
}
|
|
|
|
return ast.WalkContinue, nil
|
|
}
|