Debian Codegraph @

tpl/transform/transform.go

raw
1 // Copyright 2017 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package transform provides template functions for transforming content.
15 package transform
16
17 import (
18 "bytes"
19 "context"
20 "encoding/json"
21 "encoding/xml"
22 "errors"
23 "fmt"
24 "html"
25 "html/template"
26 "io"
27 "strings"
28 "sync/atomic"
29
30 htmltomarkdown "github.com/JohannesKaufmann/html-to-markdown/v2/converter"
31 "github.com/JohannesKaufmann/html-to-markdown/v2/plugin/base"
32 "github.com/JohannesKaufmann/html-to-markdown/v2/plugin/commonmark"
33 "github.com/JohannesKaufmann/html-to-markdown/v2/plugin/table"
34
35 bp "github.com/gohugoio/hugo/bufferpool"
36
37 "github.com/bep/goportabletext"
38
39 "github.com/gohugoio/hugo/cache/dynacache"
40 "github.com/gohugoio/hugo/common/hashing"
41 "github.com/gohugoio/hugo/common/hugio"
42 "github.com/gohugoio/hugo/internal/warpc"
43 "github.com/gohugoio/hugo/markup/converter/hooks"
44 "github.com/gohugoio/hugo/markup/highlight"
45 "github.com/gohugoio/hugo/markup/highlight/chromalexers"
46 "github.com/gohugoio/hugo/resources"
47 "github.com/gohugoio/hugo/tpl"
48 "github.com/mitchellh/mapstructure"
49
50 "github.com/gohugoio/hugo/deps"
51 "github.com/gohugoio/hugo/helpers"
52 "github.com/spf13/cast"
53 )
54
55 // New returns a new instance of the transform-namespaced template functions.
56 func New(deps *deps.Deps) *Namespace {
57 if deps.MemCache == nil {
58 panic("must provide MemCache")
59 }
60
61 return &Namespace{
62 deps: deps,
63 cacheUnmarshal: dynacache.GetOrCreatePartition[string, *resources.StaleValue[any]](
64 deps.MemCache,
65 "/tmpl/transform/unmarshal",
66 dynacache.OptionsPartition{Weight: 30, ClearWhen: dynacache.ClearOnChange},
67 ),
68 cacheMath: dynacache.GetOrCreatePartition[string, template.HTML](
69 deps.MemCache,
70 "/tmpl/transform/math",
71 dynacache.OptionsPartition{Weight: 30, ClearWhen: dynacache.ClearNever},
72 ),
73 }
74 }
75
76 // Namespace provides template functions for the "transform" namespace.
77 type Namespace struct {
78 cacheUnmarshal *dynacache.Partition[string, *resources.StaleValue[any]]
79 cacheMath *dynacache.Partition[string, template.HTML]
80
81 id atomic.Uint32
82 deps *deps.Deps
83 }
84
85 // Emojify returns a copy of s with all emoji codes replaced with actual emojis.
86 //
87 // See http://www.emoji-cheat-sheet.com/
88 func (ns *Namespace) Emojify(s any) (template.HTML, error) {
89 ss, err := cast.ToStringE(s)
90 if err != nil {
91 return "", err
92 }
93
94 return template.HTML(helpers.Emojify([]byte(ss))), nil
95 }
96
97 // Highlight returns a copy of CODE as an HTML string with syntax
98 // highlighting applied.
99 //
100 // transform.Highlight CODE [LANG] [OPTIONS]
101 //
102 // LANG is optional; it can also be set via the type option in OPTIONS, which
103 // makes this work the same way as HighlightCodeBlock.
104 func (ns *Namespace) Highlight(s any, args ...any) (template.HTML, error) {
105 code, err := cast.ToStringE(s)
106 if err != nil {
107 return "", err
108 }
109
110 var lang string
111 var opts any
112
113 switch len(args) {
114 case 0:
115 case 1:
116 // A single argument is either OPTIONS (a map or option string) or LANG.
117 if _, ok := args[0].(map[string]any); ok {
118 opts = args[0]
119 } else {
120 var arg string
121 if arg, err = cast.ToStringE(args[0]); err != nil {
122 return "", err
123 }
124 if strings.Contains(arg, "=") || strings.Contains(arg, ",") {
125 opts = arg
126 } else {
127 lang = arg
128 }
129 }
130 case 2:
131 if lang, err = cast.ToStringE(args[0]); err != nil {
132 return "", err
133 }
134 opts = args[1]
135 default:
136 return "", errors.New("transform.Highlight: expects at most 3 arguments")
137 }
138
139 hl := ns.deps.ContentSpec.Converters.GetHighlighter()
140 highlighted, err := hl.Highlight(code, lang, opts)
141 if err != nil {
142 return "", err
143 }
144 return template.HTML(highlighted), nil
145 }
146
147 // HighlightCodeBlock highlights a code block on the form received in the codeblock render hooks.
148 func (ns *Namespace) HighlightCodeBlock(ctx hooks.CodeblockContext, opts ...any) (highlight.HighlightResult, error) {
149 var optsv any
150 if len(opts) > 0 {
151 optsv = opts[0]
152 }
153
154 hl := ns.deps.ContentSpec.Converters.GetHighlighter()
155
156 return hl.HighlightCodeBlock(ctx, optsv)
157 }
158
159 // CanHighlight returns whether the given code language is supported by the Chroma highlighter.
160 func (ns *Namespace) CanHighlight(language string) bool {
161 return chromalexers.Get(language) != nil
162 }
163
164 // HTMLEscape returns a copy of s with reserved HTML characters escaped.
165 func (ns *Namespace) HTMLEscape(s any) (string, error) {
166 ss, err := cast.ToStringE(s)
167 if err != nil {
168 return "", err
169 }
170
171 return html.EscapeString(ss), nil
172 }
173
174 // HTMLUnescape returns a copy of s with HTML escape requences converted to plain
175 // text.
176 func (ns *Namespace) HTMLUnescape(s any) (string, error) {
177 ss, err := cast.ToStringE(s)
178 if err != nil {
179 return "", err
180 }
181
182 return html.UnescapeString(ss), nil
183 }
184
185 // XMLEscape returns the given string, removing disallowed characters then
186 // escaping the result to its XML equivalent.
187 func (ns *Namespace) XMLEscape(s any) (string, error) {
188 ss, err := cast.ToStringE(s)
189 if err != nil {
190 return "", err
191 }
192
193 // https://www.w3.org/TR/xml/#NT-Char
194 cleaned := strings.Map(func(r rune) rune {
195 if r == 0x9 || r == 0xA || r == 0xD ||
196 (r >= 0x20 && r <= 0xD7FF) ||
197 (r >= 0xE000 && r <= 0xFFFD) ||
198 (r >= 0x10000 && r <= 0x10FFFF) {
199 return r
200 }
201 return -1
202 }, ss)
203
204 var buf bytes.Buffer
205 err = xml.EscapeText(&buf, []byte(cleaned))
206 if err != nil {
207 return "", err
208 }
209
210 return buf.String(), nil
211 }
212
213 // Markdownify renders s from Markdown to HTML.
214 func (ns *Namespace) Markdownify(ctx context.Context, s any) (template.HTML, error) {
215 home := ns.deps.Site.Home()
216 if home == nil {
217 panic("home must not be nil")
218 }
219 ss, err := home.RenderString(ctx, s)
220 if err != nil {
221 return "", err
222 }
223
224 // Strip if this is a short inline type of text.
225 bb := ns.deps.ContentSpec.TrimShortHTML([]byte(ss), "markdown")
226
227 return helpers.BytesToHTML(bb), nil
228 }
229
230 // Plainify returns a copy of s with all HTML tags removed.
231 func (ns *Namespace) Plainify(s any) (template.HTML, error) {
232 ss, err := cast.ToStringE(s)
233 if err != nil {
234 return "", err
235 }
236
237 return template.HTML(tpl.StripHTML(ss)), nil
238 }
239
240 // PortableText converts the portable text in v to Markdown.
241 // We may add more options in the future.
242 func (ns *Namespace) PortableText(v any) (string, error) {
243 buf := bp.GetBuffer()
244 defer bp.PutBuffer(buf)
245 opts := goportabletext.ToMarkdownOptions{
246 Dst: buf,
247 Src: v,
248 }
249 if err := goportabletext.ToMarkdown(opts); err != nil {
250 return "", err
251 }
252 return buf.String(), nil
253 }
254
255 // ToMath converts a LaTeX string to math in the given format, default MathML.
256 // This uses KaTeX to render the math, see https://katex.org/.
257 func (ns *Namespace) ToMath(ctx context.Context, args ...any) (template.HTML, error) {
258 if len(args) < 1 {
259 return "", errors.New("must provide at least one argument")
260 }
261 expression, err := cast.ToStringE(args[0])
262 if err != nil {
263 return "", err
264 }
265
266 katexInput := warpc.KatexInput{
267 Expression: expression,
268 Options: warpc.KatexOptions{
269 Output: "mathml",
270 MinRuleThickness: 0.04,
271 ErrorColor: "#cc0000",
272 ThrowOnError: true,
273 Strict: "error",
274 },
275 }
276
277 if len(args) > 1 {
278 if err := mapstructure.WeakDecode(args[1], &katexInput.Options); err != nil {
279 return "", err
280 }
281 }
282
283 switch katexInput.Options.Strict {
284 case "error", "ignore", "warn":
285 // Valid strict mode, continue
286 default:
287 return "", fmt.Errorf("invalid strict mode; expected one of error, ignore, or warn; received %s", katexInput.Options.Strict)
288 }
289
290 type fileCacheEntry struct {
291 Version string `json:"version"`
292 Output string `json:"output"`
293 Warnings []string `json:"warnings,omitempty"`
294 }
295
296 const fileCacheEntryVersion = "v1" // Increment on incompatible changes.
297
298 s := hashing.HashString(args...)
299 key := "tomath/" + fileCacheEntryVersion + "/" + s[:2] + "/" + s[2:]
300 fileCache := ns.deps.ResourceSpec.FileCaches.MiscCache()
301
302 v, err := ns.cacheMath.GetOrCreate(key, func(string) (template.HTML, error) {
303 _, r, err := fileCache.GetOrCreate(key, func() (io.ReadCloser, error) {
304 message := warpc.Message[warpc.KatexInput]{
305 Header: warpc.Header{
306 Version: 1,
307 ID: ns.id.Add(1),
308 },
309 Data: katexInput,
310 }
311
312 k, err := ns.deps.WasmDispatchers.Katex()
313 if err != nil {
314 return nil, err
315 }
316 result, err := k.Execute(ctx, message)
317 if err != nil {
318 return nil, err
319 }
320
321 e := fileCacheEntry{
322 Version: fileCacheEntryVersion,
323 Output: result.Data.Output,
324 Warnings: result.Header.Warnings,
325 }
326
327 buf := &bytes.Buffer{}
328 enc := json.NewEncoder(buf)
329 enc.SetEscapeHTML(false)
330 if err := enc.Encode(e); err != nil {
331 return nil, fmt.Errorf("failed to encode file cache entry: %w", err)
332 }
333 return hugio.NewReadSeekerNoOpCloserFromBytes(buf.Bytes()), nil
334 })
335 if err != nil {
336 return "", err
337 }
338
339 var e fileCacheEntry
340 if err := json.NewDecoder(r).Decode(&e); err != nil {
341 return "", fmt.Errorf("failed to decode file cache entry: %w", err)
342 }
343
344 for _, warning := range e.Warnings {
345 ns.deps.Log.Warnf("transform.ToMath: %s", warning)
346 }
347
348 return template.HTML(e.Output), err
349 })
350 if err != nil {
351 return "", err
352 }
353
354 return v, nil
355 }
356
357 // For internal use.
358 func (ns *Namespace) Reset() {
359 ns.cacheUnmarshal.Clear()
360 }
361
362 // This was added in Hugo v0.151.0 and should be considered experimental for now.
363 // We need to test this out in the wild for a while before committing to this API,
364 // and there will eventually be more options here.
365 func (ns *Namespace) HTMLToMarkdown(ctx context.Context, args ...any) (string, error) {
366 if len(args) < 1 {
367 return "", errors.New("must provide at least one argument")
368 }
369 input, err := cast.ToStringE(args[0])
370 if err != nil {
371 return "", err
372 }
373
374 plugins := []htmltomarkdown.Plugin{
375 base.NewBasePlugin(),
376 commonmark.NewCommonmarkPlugin(),
377 table.NewTablePlugin(),
378 }
379
380 conv := htmltomarkdown.NewConverter(
381 htmltomarkdown.WithPlugins(plugins...),
382 )
383
384 markdown, err := conv.ConvertString(input)
385 if err != nil {
386 return "", err
387 }
388 return markdown, nil
389 }