Files
summercms/modules/postcard/partials.go
Jakub Zych 495319ee21 feat(postcard): sample values, file hashes, index sync and the draft editor
- sample.<path> header keys and a parse-tree walker that fills every other
  variable with a visible [path] placeholder, nested fields and range
  targets included
- every file entry carries the sha256 of its CRLF-normalized text; the
  catalog lists its files (Templates, Layouts, Partials) for admin code
- SyncIndex upserts one index row per file and never touches the override
  columns of a customized row; ResetOverride returns a row to its file
- Editor validates, previews and test-sends a template, layout or partial
  draft through the render path of Send and reports field and rule
- pact.RowStateCustomized and pact.RowStateOutdated

Plan 35-01, task 4.
2026-11-13 10:57:05 +01:00

229 lines
6.6 KiB
Go

package postcard
import (
"bytes"
"crypto/rand"
"encoding/hex"
"fmt"
"html/template"
"strconv"
"strings"
texttemplate "text/template"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
)
const (
partialSegment = "mail.partials."
// builtinPartialPrefix is what a bare partial name such as "button"
// resolves under.
builtinPartialPrefix = "postcard::" + partialSegment
// partialTokenPrefix starts the placeholder a partial call leaves in a
// Markdown body until the body has been converted to HTML.
partialTokenPrefix = "MAILPARTIAL"
)
// partialMarkdown renders the argument of the markdown func inside
// partials: goldmark with tables, raw HTML still dropped.
var partialMarkdown = goldmark.New(goldmark.WithExtensions(extension.Table))
// partialError is a failed partial call. name is the partial's full name;
// unknown is set when no such partial is registered.
type partialError struct {
name string
msg string
unknown bool
}
func (e *partialError) Error() string {
return "postcard: " + e.msg + " " + e.name
}
// partialRun renders the partial calls of one message. Partials come from
// the catalog, with the run's overrides replacing their sections.
//
// goldmark drops raw HTML, so a call in a Markdown body cannot return its
// HTML directly. It returns a token instead, made of letters and digits
// only so that neither html/template nor goldmark changes it, and carrying
// a nonce drawn for this run so that no variable value can contain it.
// swapHTML and swapText put the rendered partial in its place afterwards.
type partialRun struct {
cat *Catalog
overrides map[string]PartialOverride
nonce string
calls []partialCall
}
// partialCall is one rendered call from a body.
type partialCall struct {
token string
html string
text string
}
func newPartialRun(cat *Catalog, overrides map[string]PartialOverride) *partialRun {
return &partialRun{cat: cat, overrides: overrides}
}
// partialName returns the full name a call refers to: a bare name is one of
// postcard's built-in partials.
func partialName(name string) string {
if strings.Contains(name, "::") {
return name
}
return builtinPartialPrefix + name
}
// sections returns the text and HTML sections of a partial, from its
// override when the run has one.
func (r *partialRun) sections(full string) (text, html string, err error) {
p, ok := r.cat.lookupPartial(full)
if !ok {
return "", "", &partialError{name: full, msg: "unknown partial", unknown: true}
}
if ov, ok := r.overrides[full]; ok {
return ov.Text, ov.HTML, nil
}
return p.textWrap, p.htmlWrap, nil
}
// partialArgs turns the key/value arguments of a call into the partial's
// data.
func partialArgs(full string, kv []any) (map[string]any, error) {
if len(kv)%2 != 0 {
return nil, &partialError{name: full, msg: "arguments must be pairs of a key and a value in a call of partial"}
}
data := make(map[string]any, len(kv)/2)
for i := 0; i < len(kv); i += 2 {
key, ok := kv[i].(string)
if !ok {
return nil, &partialError{name: full, msg: "argument " + strconv.Itoa(i+1) + " is not a string key in a call of partial"}
}
data[key] = kv[i+1]
}
return data, nil
}
func (r *partialRun) renderHTML(name string, kv []any) (string, error) {
full := partialName(name)
_, src, err := r.sections(full)
if err != nil {
return "", err
}
data, err := partialArgs(full, kv)
if err != nil {
return "", err
}
out, err := execHTMLFuncs(full+".html", src, data, template.FuncMap{"markdown": partialMarkdownHTML})
if err != nil {
return "", err
}
if err := validateHTML(out); err != nil {
return "", err
}
return out, nil
}
func (r *partialRun) renderText(name string, kv []any) (string, error) {
full := partialName(name)
src, _, err := r.sections(full)
if err != nil {
return "", err
}
data, err := partialArgs(full, kv)
if err != nil {
return "", err
}
return execTextFuncs(full+".text", src, data, texttemplate.FuncMap{"markdown": partialMarkdownText})
}
// bodyCall is the partial func of a Markdown body: it renders both sections
// now and returns the token that stands for them.
func (r *partialRun) bodyCall(name string, kv ...any) (string, error) {
html, err := r.renderHTML(name, kv)
if err != nil {
return "", err
}
text, err := r.renderText(name, kv)
if err != nil {
return "", err
}
if r.nonce == "" {
var raw [16]byte
if _, err := rand.Read(raw[:]); err != nil {
return "", fmt.Errorf("postcard: partial token: %w", err)
}
r.nonce = strings.ToUpper(hex.EncodeToString(raw[:]))
}
// X is not a hexadecimal digit: it ends the nonce and the counter, so
// one token is never the prefix of another.
token := partialTokenPrefix + r.nonce + "X" + strconv.Itoa(len(r.calls)+1) + "X"
r.calls = append(r.calls, partialCall{token: token, html: html, text: text})
return token, nil
}
// htmlCall is the partial func of a layout's HTML wrapper.
func (r *partialRun) htmlCall(name string, kv ...any) (template.HTML, error) {
out, err := r.renderHTML(name, kv)
return template.HTML(out), err
}
// textCall is the partial func of a layout's text wrapper.
func (r *partialRun) textCall(name string, kv ...any) (string, error) {
return r.renderText(name, kv)
}
// swapHTML replaces the tokens in a converted body with the partials' HTML.
// A token alone in a paragraph takes the paragraph with it.
func (r *partialRun) swapHTML(html string) string {
if len(r.calls) == 0 {
return html
}
pairs := make([]string, 0, len(r.calls)*4)
for _, c := range r.calls {
pairs = append(pairs, "<p>"+c.token+"</p>", c.html)
}
for _, c := range r.calls {
pairs = append(pairs, c.token, c.html)
}
// One pass: text a partial rendered is never scanned again.
return strings.NewReplacer(pairs...).Replace(html)
}
// swapText replaces the tokens in a body with the partials' text.
func (r *partialRun) swapText(text string) string {
if len(r.calls) == 0 {
return text
}
pairs := make([]string, 0, len(r.calls)*2)
for _, c := range r.calls {
pairs = append(pairs, c.token, c.text)
}
return strings.NewReplacer(pairs...).Replace(text)
}
// partialMarkdownHTML is the markdown func of a partial's HTML section.
func partialMarkdownHTML(v any) (template.HTML, error) {
if v == nil {
return "", nil
}
var buf bytes.Buffer
if err := partialMarkdown.Convert([]byte(fmt.Sprint(v)), &buf); err != nil {
return "", fmt.Errorf("postcard: markdown: %w", err)
}
if err := validateHTML(buf.String()); err != nil {
return "", err
}
return template.HTML(buf.String()), nil
}
// partialMarkdownText is the markdown func of a partial's text section: the
// Markdown source is the text.
func partialMarkdownText(v any) string {
if v == nil {
return ""
}
return fmt.Sprint(v)
}