Files
summercms/modules/postcard/samples.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

254 lines
6.5 KiB
Go

package postcard
import (
"strings"
"text/template/parse"
)
// samplePrefix starts the header keys that give a template's variables
// sample values, as in sample.order.code = "ZAM-1".
const samplePrefix = "sample."
// placeholderVars builds the variables a draft is validated and previewed
// with. It walks the parse trees of sources and gives every variable they
// read a value: its sample from samples (keyed by dotted path), or the
// visible placeholder "[path]". A field of a variable becomes a nested map
// and the target of a range a slice of one element, so that templates that
// read .order.code or range over .order.items render instead of failing on a
// missing value. A source that does not parse contributes nothing; the
// render that follows reports it.
func placeholderVars(samples map[string]string, sources ...string) map[string]any {
root := &phNode{}
for _, src := range sources {
tree := parse.New("placeholders")
// Function names are not checked: partial and markdown exist only
// in the real render.
tree.Mode = parse.SkipFuncCheck
if _, err := tree.Parse(src, "", "", map[string]*parse.Tree{}); err != nil || tree.Root == nil {
continue
}
w := phWalker{root: root}
w.list(tree.Root, phScope{dot: root})
}
// Samples the sources do not read are still variables of the template.
for path := range samples {
node := root
for _, name := range strings.Split(path, ".") {
if name == "" {
node = nil
break
}
node = node.field(name)
}
}
vars, _ := root.value("", samples).(map[string]any)
if vars == nil {
vars = map[string]any{}
}
return vars
}
// phNode is one variable, or one field of one, that the sources read.
type phNode struct {
fields map[string]*phNode
// elem is set when the sources range over the node: the node of one
// element.
elem *phNode
}
// field returns the node of a field of n. A field of a ranged node is a
// field of its elements.
func (n *phNode) field(name string) *phNode {
if n == nil {
return nil
}
if n.elem != nil {
n = n.elem
}
if n.fields == nil {
n.fields = make(map[string]*phNode)
}
child, ok := n.fields[name]
if !ok {
child = &phNode{}
n.fields[name] = child
}
return child
}
func (n *phNode) path(names []string) *phNode {
for _, name := range names {
n = n.field(name)
}
return n
}
// value turns the node into template data. path is its dotted path; the
// elements of a ranged node keep the path of the node.
func (n *phNode) value(path string, samples map[string]string) any {
if n.elem != nil {
return []any{n.elem.value(path, samples)}
}
if len(n.fields) > 0 {
out := make(map[string]any, len(n.fields))
for name, child := range n.fields {
childPath := name
if path != "" {
childPath = path + "." + name
}
out[name] = child.value(childPath, samples)
}
return out
}
if sample, ok := samples[path]; ok {
return sample
}
return "[" + path + "]"
}
// phScope is what a template action sees: the node of the dot (nil when it
// is not a variable the walker follows) and the nodes of declared variables.
type phScope struct {
dot *phNode
vars map[string]*phNode
}
func (s phScope) with(dot *phNode) phScope {
return phScope{dot: dot, vars: s.vars}
}
// bind returns the scope with a variable declared. Scopes share nothing, so
// a declaration inside a block does not leak out of it.
func (s phScope) bind(name string, node *phNode) phScope {
vars := make(map[string]*phNode, len(s.vars)+1)
for k, v := range s.vars {
vars[k] = v
}
vars[name] = node
return phScope{dot: s.dot, vars: vars}
}
type phWalker struct {
root *phNode
}
func (w *phWalker) list(list *parse.ListNode, scope phScope) {
if list == nil {
return
}
for _, node := range list.Nodes {
scope = w.node(node, scope)
}
}
// node walks one node and returns the scope for the nodes after it, which
// differs when the node declares a variable.
func (w *phWalker) node(node parse.Node, scope phScope) phScope {
switch n := node.(type) {
case *parse.ActionNode:
_, scope = w.pipe(n.Pipe, scope)
case *parse.IfNode:
_, inner := w.pipe(n.Pipe, scope)
w.list(n.List, inner)
w.list(n.ElseList, inner)
case *parse.WithNode:
target, inner := w.pipe(n.Pipe, scope)
w.list(n.List, inner.with(target))
w.list(n.ElseList, inner)
case *parse.RangeNode:
w.rangeNode(n, scope)
case *parse.TemplateNode:
w.pipe(n.Pipe, scope)
case *parse.ListNode:
w.list(n, scope)
}
return scope
}
func (w *phWalker) rangeNode(n *parse.RangeNode, scope phScope) {
if n.Pipe == nil {
return
}
// The declarations of a range name the index and the element, not the
// pipeline's value: walk the commands only.
var target *phNode
for _, cmd := range n.Pipe.Cmds {
target = w.command(cmd, scope)
}
if len(n.Pipe.Cmds) != 1 {
target = nil
}
var elem *phNode
if target != nil {
if target.elem == nil {
// Fields read before the range belong to the elements too.
target.elem = &phNode{fields: target.fields}
target.fields = nil
}
elem = target.elem
}
body := scope.with(elem)
if decl := n.Pipe.Decl; len(decl) > 0 {
for _, v := range decl[:len(decl)-1] {
body = body.bind(v.Ident[0], nil)
}
body = body.bind(decl[len(decl)-1].Ident[0], elem)
}
w.list(n.List, body)
w.list(n.ElseList, scope)
}
// pipe walks a pipeline. It returns the node the pipeline evaluates to when
// that is a variable the walker follows, and the scope with the pipeline's
// declarations.
func (w *phWalker) pipe(pipe *parse.PipeNode, scope phScope) (*phNode, phScope) {
if pipe == nil {
return nil, scope
}
var target *phNode
for _, cmd := range pipe.Cmds {
target = w.command(cmd, scope)
}
if len(pipe.Cmds) != 1 {
target = nil
}
for _, v := range pipe.Decl {
scope = scope.bind(v.Ident[0], target)
}
return target, scope
}
// command walks one command of a pipeline and returns its node when the
// command is a single variable reference.
func (w *phWalker) command(cmd *parse.CommandNode, scope phScope) *phNode {
var target *phNode
for _, arg := range cmd.Args {
target = w.arg(arg, scope)
}
if len(cmd.Args) != 1 {
return nil
}
return target
}
func (w *phWalker) arg(arg parse.Node, scope phScope) *phNode {
switch a := arg.(type) {
case *parse.FieldNode:
return scope.dot.path(a.Ident)
case *parse.DotNode:
return scope.dot
case *parse.VariableNode:
base := scope.vars[a.Ident[0]]
if a.Ident[0] == "$" {
base = w.root
}
return base.path(a.Ident[1:])
case *parse.ChainNode:
return w.arg(a.Node, scope).path(a.Field)
case *parse.PipeNode:
target, _ := w.pipe(a, scope)
return target
}
return nil
}