Skip to content

Commit

Permalink
markup: Add blockquote render hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
bep committed Aug 5, 2024
1 parent c42bba4 commit b003386
Show file tree
Hide file tree
Showing 7 changed files with 380 additions and 0 deletions.
2 changes: 2 additions & 0 deletions hugolib/page__per_output.go
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,8 @@ func (pco *pageContentOutput) initRenderHooks() error {
if id != nil {
layoutDescriptor.KindVariants = id.(string)
}
case hooks.BlockquoteRendererType:
layoutDescriptor.Kind = "render-blockquote"
case hooks.CodeBlockRendererType:
layoutDescriptor.Kind = "render-codeblock"
if id != nil {
Expand Down
4 changes: 4 additions & 0 deletions hugolib/site.go
Original file line number Diff line number Diff line change
Expand Up @@ -919,6 +919,10 @@ func (hr hookRendererTemplate) RenderPassthrough(cctx context.Context, w io.Writ
return hr.templateHandler.ExecuteWithContext(cctx, hr.templ, w, ctx)
}

func (hr hookRendererTemplate) RenderBlockquote(cctx context.Context, w hugio.FlexiWriter, ctx hooks.BlockquoteContext) error {
return hr.templateHandler.ExecuteWithContext(cctx, hr.templ, w, ctx)
}

func (hr hookRendererTemplate) ResolvePosition(ctx any) text.Position {
return hr.resolvePosition(ctx)
}
Expand Down
33 changes: 33 additions & 0 deletions markup/converter/hooks/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,34 @@ type CodeblockContext interface {
Ordinal() int
}

// BlockquoteContext is the context passed to a blockquote render hook.
type BlockquoteContext interface {
AttributesProvider
text.Positioner
PageProvider

// Zero-based ordinal for all code blocks in the current document.
Ordinal() int

// The blockquote text.
Text() hstring.RenderedString

// The blockquote text as plain text.
PlainText() string

/// Returns true if the blockquote has an GitHub alert designator.
IsAlert() bool

// The GitHub alert type converted to lowercase, e.g. "note".
AlertType() string

// The blockquote text, excluding the GitHub alert designator.
AlertText() hstring.RenderedString

// The blockquote text, excluding the GitHub alert designator, as plain text.
AlertPlainText() string
}

// PassThroughContext is the context passed to a passthrough render hook.
type PassthroughContext interface {
AttributesProvider
Expand All @@ -104,6 +132,10 @@ type CodeBlockRenderer interface {
RenderCodeblock(cctx context.Context, w hugio.FlexiWriter, ctx CodeblockContext) error
}

type BlockquoteRenderer interface {
RenderBlockquote(cctx context.Context, w hugio.FlexiWriter, ctx BlockquoteContext) error
}

type PassthroughRenderer interface {
RenderPassthrough(cctx context.Context, w io.Writer, ctx PassthroughContext) error
}
Expand Down Expand Up @@ -161,6 +193,7 @@ const (
HeadingRendererType
CodeBlockRendererType
PassthroughRendererType
BlockquoteRendererType
)

type GetRendererFunc func(t RendererType, id any) any
233 changes: 233 additions & 0 deletions markup/goldmark/blockquotes/blockquotes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
// Copyright 2024 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package blockquotes

import (
"fmt"
"regexp"
"strings"
"sync"

bp "github.com/gohugoio/hugo/bufferpool"

"github.com/gohugoio/hugo/common/herrors"
htext "github.com/gohugoio/hugo/common/text"
"github.com/gohugoio/hugo/common/types/hstring"
"github.com/gohugoio/hugo/markup/converter/hooks"
"github.com/gohugoio/hugo/markup/goldmark/internal/render"
"github.com/gohugoio/hugo/markup/internal/attributes"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/renderer"
"github.com/yuin/goldmark/renderer/html"
"github.com/yuin/goldmark/util"
)

type (
blockquotesExtension struct{}
htmlRenderer struct{}
)

func New() goldmark.Extender {
return &blockquotesExtension{}
}

func (e *blockquotesExtension) Extend(m goldmark.Markdown) {
m.Renderer().AddOptions(renderer.WithNodeRenderers(
util.Prioritized(newHTMLRenderer(), 100),
))
}

func newHTMLRenderer() renderer.NodeRenderer {
r := &htmlRenderer{}
return r
}

func (r *htmlRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
reg.Register(ast.KindBlockquote, r.renderBlockquote)
}

func (r *htmlRenderer) renderBlockquote(w util.BufWriter, src []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
ctx := w.(*render.Context)

n := node.(*ast.Blockquote)

renderer := ctx.RenderContext().GetRenderer(hooks.BlockquoteRendererType, nil)
if renderer == nil {
return r.renderBlockquoteDefault(w, src, n, entering)
}

if entering {
first := n.FirstChild()
fmt.Println(fmt.Println("===>", string(first.Text(src))))
// Store the current pos so we can capture the rendered text.
ctx.PushPos(ctx.Buffer.Len())
return ast.WalkContinue, nil
}

pos := ctx.PopPos()
text := ctx.Buffer.Bytes()[pos:]
ctx.Buffer.Truncate(pos)

ordinal := ctx.GetAndIncrementOrdinal(ast.KindBlockquote)

plainText := r.blockQuoteToPlainText(n, src)

bqctx := &blockquoteBlockContext{
page: ctx.DocumentContext().Document,
pageInner: r.getPageInner(ctx),
text: hstring.RenderedString(text),
plainText: plainText,
ordinal: ordinal,
AttributesHolder: attributes.New(n.Attributes(), attributes.AttributesOwnerGeneral),
}

bqctx.createPos = func() htext.Position {
if resolver, ok := renderer.(hooks.ElementPositionResolver); ok {
return resolver.ResolvePosition(bqctx)
}
return htext.Position{
Filename: ctx.DocumentContext().Filename,
LineNumber: 1,
ColumnNumber: 1,
}
}

cr := renderer.(hooks.BlockquoteRenderer)

err := cr.RenderBlockquote(
ctx.RenderContext().Ctx,
w,
bqctx,
)
if err != nil {
return ast.WalkContinue, herrors.NewFileErrorFromPos(err, bqctx.createPos())
}

return ast.WalkContinue, nil
}

func (r *htmlRenderer) getPageInner(rctx *render.Context) any {
pid := rctx.PeekPid()
if pid > 0 {
if lookup := rctx.DocumentContext().DocumentLookup; lookup != nil {
if v := rctx.DocumentContext().DocumentLookup(pid); v != nil {
return v
}
}
}
return rctx.DocumentContext().Document
}

// Code borrowed from goldmark's html renderer.
func (r *htmlRenderer) renderBlockquoteDefault(
w util.BufWriter, source []byte, n ast.Node, entering bool,
) (ast.WalkStatus, error) {
if entering {
if n.Attributes() != nil {
_, _ = w.WriteString("<blockquote")
html.RenderAttributes(w, n, html.BlockquoteAttributeFilter)
_ = w.WriteByte('>')
} else {
_, _ = w.WriteString("<blockquote>\n")
}
} else {
_, _ = w.WriteString("</blockquote>\n")
}
return ast.WalkContinue, nil
}

func (r *htmlRenderer) blockQuoteToPlainText(n *ast.Blockquote, source []byte) string {
buf := bp.GetBuffer()
defer bp.PutBuffer(buf)

for c := n.FirstChild(); c != nil; c = c.NextSibling() {
buf.Write(c.Text(source))
}
return buf.String()
}

type blockquoteBlockContext struct {
page any
pageInner any
text hstring.RenderedString
plainText string
ordinal int

// This is only used in error situations and is expensive to create,
// so delay creation until needed.
pos htext.Position
posInit sync.Once
createPos func() htext.Position

*attributes.AttributesHolder
}

func (c *blockquoteBlockContext) Page() any {
return c.page
}

func (c *blockquoteBlockContext) PageInner() any {
return c.pageInner
}

func (c *blockquoteBlockContext) Text() hstring.RenderedString {
return c.text
}

func (c *blockquoteBlockContext) PlainText() string {
return c.plainText
}

func (c *blockquoteBlockContext) IsAlert() bool {
panic("not implemented TODO1")
}

func (c *blockquoteBlockContext) AlertPlainText() string {
panic("not implemented TODO1")
}

func (c *blockquoteBlockContext) AlertText() hstring.RenderedString {
panic("not implemented TODO1")
}

func (c *blockquoteBlockContext) AlertType() string {
panic("not implemented TODO1")
}

func (c *blockquoteBlockContext) Ordinal() int {
return c.ordinal
}

func (c *blockquoteBlockContext) Position() htext.Position {
c.posInit.Do(func() {
c.pos = c.createPos()
})
return c.pos
}

// https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts
// Five types:
// [!NOTE], [!TIP], [!WARNING], [!IMPORTANT], [!CAUTION]
var gitHubAlertRe = regexp.MustCompile(`^\[!(NOTE|TIP|WARNING|IMPORTANT|CAUTION)\]`)

// resolveGitHubAlert returns one of note, tip, warning, important or caution.
// An empty string if no match.
func resolveGitHubAlert(s string) string {
m := gitHubAlertRe.FindStringSubmatch(s)
if len(m) == 2 {
return strings.ToLower(m[1])
}
return ""
}
46 changes: 46 additions & 0 deletions markup/goldmark/blockquotes/blockquotes_integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright 2024 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package blockquotes_test

import (
"testing"

"github.com/gohugoio/hugo/hugolib"
)

func TestBlockquoteHook(t *testing.T) {
t.Parallel()

files := `
-- config.toml --
-- layouts/_default/_markup/render-blockquote.html --
Blockquote: {{ .Text | safeHTML }}|{{ .PlainText }}|
-- layouts/_default/single.html --
Content: {{ .Content }}
-- content/p1.md --
---
title: "p1"
---
> [!NOTE]
> Das ist meine Notiz.
`

b := hugolib.Test(t, files)

b.AssertFileContent("public/p1/index.html", `
foo
`)
}
Loading

0 comments on commit b003386

Please sign in to comment.