Files

62 lines
2.1 KiB
Go
Raw Permalink Normal View History

2022-09-13 17:33:37 +01:00
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
2022-09-13 17:33:37 +01:00
package math
import (
"html/template"
2024-11-18 13:25:42 +08:00
"code.gitea.io/gitea/modules/markup/internal"
2024-12-06 20:00:24 +08:00
giteaUtil "code.gitea.io/gitea/modules/util"
2024-11-18 13:25:42 +08:00
2022-09-13 17:33:37 +01:00
gast "github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/renderer"
"github.com/yuin/goldmark/util"
)
2024-12-13 14:45:32 +08:00
// Block render output:
// <pre class="code-block is-loading"><code class="language-math display">...</code></pre>
//
// Keep in mind that there is another "code block" render in "func (r *GlodmarkRender) highlightingRenderer"
// "highlightingRenderer" outputs the math block with extra "chroma" class:
// <pre class="code-block is-loading"><code class="chroma language-math display">...</code></pre>
//
// Special classes:
// * "is-loading": show a loading indicator
// * "display": used by JS to decide to render as a block, otherwise render as inline
2022-09-13 17:33:37 +01:00
// BlockRenderer represents a renderer for math Blocks
2024-11-18 13:25:42 +08:00
type BlockRenderer struct {
renderInternal *internal.RenderInternal
}
2022-09-13 17:33:37 +01:00
// NewBlockRenderer creates a new renderer for math Blocks
2024-11-18 13:25:42 +08:00
func NewBlockRenderer(renderInternal *internal.RenderInternal) renderer.NodeRenderer {
return &BlockRenderer{renderInternal: renderInternal}
2022-09-13 17:33:37 +01:00
}
// RegisterFuncs registers the renderer for math Blocks
func (r *BlockRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
reg.Register(KindBlock, r.renderBlock)
}
func (r *BlockRenderer) writeLines(w util.BufWriter, source []byte, n gast.Node) {
l := n.Lines().Len()
2025-06-18 03:48:09 +02:00
for i := range l {
2022-09-13 17:33:37 +01:00
line := n.Lines().At(i)
_, _ = w.Write(util.EscapeHTML(line.Value(source)))
}
}
func (r *BlockRenderer) renderBlock(w util.BufWriter, source []byte, node gast.Node, entering bool) (gast.WalkStatus, error) {
n := node.(*Block)
if entering {
2025-06-24 01:27:35 +08:00
codeHTML := giteaUtil.Iif[template.HTML](n.Inline, "", `<pre class="code-block is-loading">`) + `<code class="language-math display">`
_, _ = w.WriteString(string(r.renderInternal.ProtectSafeAttrs(codeHTML)))
2022-09-13 17:33:37 +01:00
r.writeLines(w, source, n)
} else {
2024-12-06 20:00:24 +08:00
_, _ = w.WriteString(`</code>` + giteaUtil.Iif(n.Inline, "", `</pre>`) + "\n")
2022-09-13 17:33:37 +01:00
}
return gast.WalkContinue, nil
}