Handle KaTeX warnings (#13760)

Co-authored-by: Joe Mooring <joe.mooring@veriphor.com>

Fixes #13735
This commit is contained in:
Bjørn Erik Pedersen
2025-05-30 20:57:54 +02:00
committed by GitHub
parent 75259636c8
commit 6334948515
10 changed files with 76 additions and 15 deletions

View File

@@ -17,6 +17,7 @@ package transform
import (
"bytes"
"context"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
@@ -252,8 +253,16 @@ func (ns *Namespace) ToMath(ctx context.Context, args ...any) (template.HTML, er
return "", fmt.Errorf("invalid strict mode; expected one of error, ignore, or warn; received %s", katexInput.Options.Strict)
}
type fileCacheEntry struct {
Version string `json:"version"`
Output string `json:"output"`
Warnings []string `json:"warnings,omitempty"`
}
const fileCacheEntryVersion = "v1" // Increment on incompatible changes.
s := hashing.HashString(args...)
key := "tomath/" + s[:2] + "/" + s[2:]
key := "tomath/" + fileCacheEntryVersion + "/" + s[:2] + "/" + s[2:]
fileCache := ns.deps.ResourceSpec.FileCaches.MiscCache()
v, err := ns.cacheMath.GetOrCreate(key, func(string) (template.HTML, error) {
@@ -274,15 +283,35 @@ func (ns *Namespace) ToMath(ctx context.Context, args ...any) (template.HTML, er
if err != nil {
return nil, err
}
return hugio.NewReadSeekerNoOpCloserFromString(result.Data.Output), nil
e := fileCacheEntry{
Version: fileCacheEntryVersion,
Output: result.Data.Output,
Warnings: result.Header.Warnings,
}
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
if err := enc.Encode(e); err != nil {
return nil, fmt.Errorf("failed to encode file cache entry: %w", err)
}
return hugio.NewReadSeekerNoOpCloserFromBytes(buf.Bytes()), nil
})
if err != nil {
return "", err
}
s, err := hugio.ReadString(r)
var e fileCacheEntry
if err := json.NewDecoder(r).Decode(&e); err != nil {
return "", fmt.Errorf("failed to decode file cache entry: %w", err)
}
return template.HTML(s), err
for _, warning := range e.Warnings {
ns.deps.Log.Warnf("transform.ToMath: %s", warning)
}
return template.HTML(e.Output), err
})
if err != nil {
return "", err

View File

@@ -525,11 +525,10 @@ disableKinds = ['page','rss','section','sitemap','taxonomy','term']
b.AssertFileContent("public/index.html", `<annotation encoding="application/x-tex">a %</annotation>`)
// strict: warn
// TODO: see https://github.com/gohugoio/hugo/issues/13735
// f = strings.ReplaceAll(files, "dict", `(dict "strict" "warn")`)
// b = hugolib.Test(t, f, hugolib.TestOptWarn())
// b.AssertLogMatches("[commentAtEnd]")
// b.AssertFileContent("public/index.html", `<annotation encoding="application/x-tex">a %</annotation>`)
f = strings.ReplaceAll(files, "dict", `(dict "strict" "warn")`)
b = hugolib.Test(t, f, hugolib.TestOptWarn())
b.AssertLogMatches("[commentAtEnd]")
b.AssertFileContent("public/index.html", `<annotation encoding="application/x-tex">a %</annotation>`)
// strict mode: invalid value
f = strings.ReplaceAll(files, "dict", `(dict "strict" "foo")`)