feat(postcard): mail partials, built-in layouts and layout and partial overrides
- pact.HasMailPartials: plugins declare <plugin>::mail.partials.<name>,
loaded from views/mail/partials/<name>.htm; HasMailTemplates is unchanged
- bodies and layouts call {{ partial "name" "key" value ... }}; a call in a
Markdown body leaves a per-render random token swapped after goldmark, so
raw HTML stays disabled for bodies
- built-in partials button, panel, table and subcopy, built-in layouts
system and minimal next to the unchanged default, reachable by alias
after a plugin's own aliases
- NewDBSource also reads customized and database-only layouts and
customized partials; a layout's CSS goes before mail.css
Plan 35-01, task 3.
This commit is contained in:
@@ -2,7 +2,7 @@ package postcard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
_ "embed"
|
||||
"embed"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
@@ -15,12 +15,27 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
builtinPluginID = "postcard"
|
||||
defaultLayoutAlias = "default"
|
||||
defaultLayoutName = "postcard::mail.layouts.default"
|
||||
systemLayoutName = "postcard::mail.layouts.system"
|
||||
minimalLayoutName = "postcard::mail.layouts.minimal"
|
||||
mailPrefix = "mail."
|
||||
assetRoot = "views/mail/"
|
||||
)
|
||||
|
||||
// builtinLayoutAliases are the layout aliases every plugin's templates can
|
||||
// use. A plugin's own alias of the same name wins, except default, which is
|
||||
// reserved.
|
||||
var builtinLayoutAliases = map[string]string{
|
||||
defaultLayoutAlias: defaultLayoutName,
|
||||
"system": systemLayoutName,
|
||||
"minimal": minimalLayoutName,
|
||||
}
|
||||
|
||||
// builtinPartials are the partials postcard ships, callable by bare name.
|
||||
var builtinPartials = []string{"button", "panel", "subcopy", "table"}
|
||||
|
||||
var (
|
||||
dangerousScheme = regexp.MustCompile(`(?i)(?:javascript|vbscript|data):`)
|
||||
eventHandler = regexp.MustCompile(`(?i)\son[a-z]+\s*=`)
|
||||
@@ -32,11 +47,17 @@ var (
|
||||
//go:embed assets/default.htm
|
||||
var defaultLayoutSource string
|
||||
|
||||
// Catalog holds registered mail templates and layouts.
|
||||
// builtinAssets holds postcard's own layouts and partials.
|
||||
//
|
||||
//go:embed assets
|
||||
var builtinAssets embed.FS
|
||||
|
||||
// Catalog holds registered mail templates, layouts and partials.
|
||||
type Catalog struct {
|
||||
mu sync.RWMutex
|
||||
templates map[string]*parsedTemplate
|
||||
layouts map[string]*parsedLayout
|
||||
partials map[string]*parsedPartial
|
||||
aliases map[string]map[string]string // pluginID -> short name -> full name
|
||||
}
|
||||
|
||||
@@ -57,19 +78,53 @@ type parsedLayout struct {
|
||||
htmlWrap string
|
||||
}
|
||||
|
||||
// NewCatalog returns an empty catalog that already contains postcard's
|
||||
// neutral default layout.
|
||||
// parsedPartial is a partial file: the layout file format, a header, a text
|
||||
// section and an HTML section.
|
||||
type parsedPartial struct {
|
||||
name string
|
||||
pluginID string
|
||||
headerName string
|
||||
textWrap string
|
||||
htmlWrap string
|
||||
}
|
||||
|
||||
// NewCatalog returns a catalog that already contains postcard's built-in
|
||||
// layouts (default, system and minimal) and partials (button, panel, table
|
||||
// and subcopy). It holds no template.
|
||||
func NewCatalog() *Catalog {
|
||||
c := &Catalog{
|
||||
templates: make(map[string]*parsedTemplate),
|
||||
layouts: make(map[string]*parsedLayout),
|
||||
partials: make(map[string]*parsedPartial),
|
||||
aliases: make(map[string]map[string]string),
|
||||
}
|
||||
layout, err := parseLayout(defaultLayoutName, "postcard", defaultLayoutSource)
|
||||
layout, err := parseLayout(defaultLayoutName, builtinPluginID, defaultLayoutSource)
|
||||
if err != nil {
|
||||
panic("postcard: default layout: " + err.Error())
|
||||
}
|
||||
c.layouts[defaultLayoutName] = layout
|
||||
for file, name := range map[string]string{"system": systemLayoutName, "minimal": minimalLayoutName} {
|
||||
raw, err := builtinAssets.ReadFile("assets/" + file + ".htm")
|
||||
if err != nil {
|
||||
panic("postcard: " + file + " layout: " + err.Error())
|
||||
}
|
||||
layout, err := parseLayout(name, builtinPluginID, string(raw))
|
||||
if err != nil {
|
||||
panic("postcard: " + file + " layout: " + err.Error())
|
||||
}
|
||||
c.layouts[name] = layout
|
||||
}
|
||||
for _, short := range builtinPartials {
|
||||
raw, err := builtinAssets.ReadFile("assets/partials/" + short + ".htm")
|
||||
if err != nil {
|
||||
panic("postcard: " + short + " partial: " + err.Error())
|
||||
}
|
||||
partial, err := parsePartial(builtinPartialPrefix+short, builtinPluginID, string(raw))
|
||||
if err != nil {
|
||||
panic("postcard: " + short + " partial: " + err.Error())
|
||||
}
|
||||
c.partials[partial.name] = partial
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
@@ -160,6 +215,10 @@ func (c *Catalog) resolveLayoutLocked(t *parsedTemplate) error {
|
||||
return nil
|
||||
}
|
||||
full, ok := c.aliases[t.pluginID][short]
|
||||
if !ok {
|
||||
// Not one of the plugin's own aliases: a built-in layout.
|
||||
full, ok = builtinLayoutAliases[short]
|
||||
}
|
||||
if !ok {
|
||||
return fmt.Errorf("postcard: unknown layout %s", short)
|
||||
}
|
||||
@@ -180,17 +239,50 @@ func (c *Catalog) lookupTemplate(name string) (*parsedTemplate, error) {
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (c *Catalog) lookupLayout(name string) (*parsedLayout, error) {
|
||||
// RegisterPartials loads declared partial names from fsys. Each name must
|
||||
// be owned by pluginID, have the form <plugin>::mail.partials.<name> and map
|
||||
// to views/mail/partials/<name>.htm.
|
||||
func (c *Catalog) RegisterPartials(pluginID string, fsys fs.FS, partials []string) error {
|
||||
if c == nil {
|
||||
return fmt.Errorf("postcard: catalog is nil")
|
||||
}
|
||||
if pluginID == "" {
|
||||
return fmt.Errorf("postcard: plugin id is empty")
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
for _, name := range partials {
|
||||
if err := assertOwner(pluginID, name); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, rest, _ := strings.Cut(name, "::"); !strings.HasPrefix(rest, partialSegment) || rest == partialSegment {
|
||||
return fmt.Errorf("postcard: invalid partial name %s (want %s::%s<name>)", name, pluginID, partialSegment)
|
||||
}
|
||||
if _, exists := c.partials[name]; exists {
|
||||
return fmt.Errorf("postcard: duplicate partial %s", name)
|
||||
}
|
||||
path, err := assetPath(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
raw, err := fs.ReadFile(fsys, path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("postcard: missing partial %s", name)
|
||||
}
|
||||
parsed, err := parsePartial(name, pluginID, string(raw))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.partials[name] = parsed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Catalog) lookupPartial(name string) (*parsedPartial, bool) {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
if name == "" || name == defaultLayoutAlias {
|
||||
name = defaultLayoutName
|
||||
}
|
||||
l, ok := c.layouts[name]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("postcard: missing layout %s", name)
|
||||
}
|
||||
return l, nil
|
||||
p, ok := c.partials[name]
|
||||
return p, ok
|
||||
}
|
||||
|
||||
func assertOwner(pluginID, fullName string) error {
|
||||
@@ -253,6 +345,14 @@ func parseLayout(name, pluginID, src string) (*parsedLayout, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parsePartial(name, pluginID, src string) (*parsedPartial, error) {
|
||||
l, err := parseLayout(name, pluginID, src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &parsedPartial{name: l.name, pluginID: l.pluginID, headerName: l.headerName, textWrap: l.textWrap, htmlWrap: l.htmlWrap}, nil
|
||||
}
|
||||
|
||||
func splitTwo(src string) (header, body string, err error) {
|
||||
parts, err := splitEQ(src, 2)
|
||||
if err != nil {
|
||||
@@ -373,7 +473,10 @@ func (c *Catalog) renderFrom(msg Message, src renderSource, opts renderOptions)
|
||||
if strings.ContainsAny(subject, "\r\n") {
|
||||
return out, fmt.Errorf("postcard: subject contains CR/LF")
|
||||
}
|
||||
markdownBody, err := execHTML(src.name+".body", src.body, vars)
|
||||
// Partial calls in the body leave tokens that are swapped for the
|
||||
// rendered partials once Markdown has run; see partialRun.
|
||||
partials := newPartialRun(c, opts.overrides.Partials)
|
||||
markdownBody, err := execHTMLFuncs(src.name+".body", src.body, vars, template.FuncMap{"partial": partials.bodyCall})
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
@@ -381,6 +484,8 @@ func (c *Catalog) renderFrom(msg Message, src renderSource, opts renderOptions)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
htmlBody = partials.swapHTML(htmlBody)
|
||||
textBody := partials.swapText(markdownBody)
|
||||
if err := validateHTML(htmlBody); err != nil {
|
||||
return out, err
|
||||
}
|
||||
@@ -388,21 +493,29 @@ func (c *Catalog) renderFrom(msg Message, src renderSource, opts renderOptions)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
text, err := execText(layout.name+".text", layout.textWrap, map[string]any{
|
||||
"Content": markdownBody,
|
||||
// A layout's own CSS goes before mail.css in the css slot.
|
||||
css := opts.css
|
||||
if layout.css != "" {
|
||||
css = layout.css
|
||||
if opts.css != "" {
|
||||
css += "\n" + opts.css
|
||||
}
|
||||
}
|
||||
text, err := execTextFuncs(layout.name+".text", layout.textWrap, map[string]any{
|
||||
"Content": textBody,
|
||||
"Subject": subject,
|
||||
"css": opts.css,
|
||||
"css": css,
|
||||
"brandCss": opts.brandCSS,
|
||||
})
|
||||
}, texttemplate.FuncMap{"partial": partials.textCall})
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
html, err := execHTML(layout.name+".html", layout.htmlWrap, map[string]any{
|
||||
html, err := execHTMLFuncs(layout.name+".html", layout.htmlWrap, map[string]any{
|
||||
"Content": template.HTML(htmlBody),
|
||||
"Subject": subject,
|
||||
"css": template.CSS(opts.css),
|
||||
"css": template.CSS(css),
|
||||
"brandCss": template.CSS(opts.brandCSS),
|
||||
})
|
||||
}, template.FuncMap{"partial": partials.htmlCall})
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
@@ -421,20 +534,54 @@ func (c *Catalog) renderFrom(msg Message, src renderSource, opts renderOptions)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// layoutFor returns the layout src renders in. A layout code from an
|
||||
// override that names no layout is reported through opts.warn and replaced
|
||||
// by the default layout.
|
||||
func (c *Catalog) layoutFor(src renderSource, opts renderOptions) (*parsedLayout, error) {
|
||||
layout, err := c.lookupLayout(src.layout)
|
||||
if err == nil || !src.layoutFromOverride {
|
||||
// renderLayout is the layout one render uses: a file layout, a file layout
|
||||
// with its override applied, or a database-only layout.
|
||||
type renderLayout struct {
|
||||
name string // layout code, used in parse and execute errors
|
||||
textWrap string
|
||||
htmlWrap string
|
||||
css string
|
||||
}
|
||||
|
||||
// layoutFor returns the layout src renders in. An override of that layout,
|
||||
// or a database-only layout of that code, wins over the file. A layout code
|
||||
// from a template override that names no layout is reported through
|
||||
// opts.warn and replaced by the default layout.
|
||||
func (c *Catalog) layoutFor(src renderSource, opts renderOptions) (renderLayout, error) {
|
||||
code := src.layout
|
||||
if code == "" || code == defaultLayoutAlias {
|
||||
code = defaultLayoutName
|
||||
}
|
||||
layout, ok, err := c.layoutByCode(code, opts.overrides.Layouts)
|
||||
if err != nil || ok {
|
||||
return layout, err
|
||||
}
|
||||
if opts.warn != nil {
|
||||
opts.warn("layout:"+src.name+":"+src.layout,
|
||||
"postcard: override names an unknown layout, using the default layout",
|
||||
"template", src.name, "layout", src.layout)
|
||||
if !src.layoutFromOverride {
|
||||
return renderLayout{}, fmt.Errorf("postcard: missing layout %s", code)
|
||||
}
|
||||
return c.lookupLayout(defaultLayoutAlias)
|
||||
if opts.warn != nil {
|
||||
opts.warn("layout:"+src.name+":"+code,
|
||||
"postcard: override names an unknown layout, using the default layout",
|
||||
"template", src.name, "layout", code)
|
||||
}
|
||||
layout, ok, err = c.layoutByCode(defaultLayoutName, opts.overrides.Layouts)
|
||||
if err == nil && !ok {
|
||||
err = fmt.Errorf("postcard: missing layout %s", defaultLayoutName)
|
||||
}
|
||||
return layout, err
|
||||
}
|
||||
|
||||
func (c *Catalog) layoutByCode(code string, overrides map[string]LayoutOverride) (renderLayout, bool, error) {
|
||||
if ov, ok := overrides[code]; ok {
|
||||
return renderLayout{name: code, textWrap: ov.Text, htmlWrap: ov.HTML, css: ov.CSS}, true, nil
|
||||
}
|
||||
c.mu.RLock()
|
||||
l, ok := c.layouts[code]
|
||||
c.mu.RUnlock()
|
||||
if !ok {
|
||||
return renderLayout{}, false, nil
|
||||
}
|
||||
return renderLayout{name: l.name, textWrap: l.textWrap, htmlWrap: l.htmlWrap}, true, nil
|
||||
}
|
||||
|
||||
func markdownHTML(src string) (string, error) {
|
||||
@@ -459,7 +606,17 @@ func validateHTML(html string) error {
|
||||
}
|
||||
|
||||
func execHTML(name, src string, data any) (string, error) {
|
||||
tmpl, err := template.New(name).Option("missingkey=zero").Parse(src)
|
||||
return execHTMLFuncs(name, src, data, nil)
|
||||
}
|
||||
|
||||
func execText(name, src string, data any) (string, error) {
|
||||
return execTextFuncs(name, src, data, nil)
|
||||
}
|
||||
|
||||
// execHTMLFuncs is execHTML with template funcs; they must be set before
|
||||
// the source is parsed.
|
||||
func execHTMLFuncs(name, src string, data any, funcs template.FuncMap) (string, error) {
|
||||
tmpl, err := template.New(name).Option("missingkey=zero").Funcs(funcs).Parse(src)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("postcard: parse %s: %w", name, err)
|
||||
}
|
||||
@@ -470,8 +627,8 @@ func execHTML(name, src string, data any) (string, error) {
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
func execText(name, src string, data any) (string, error) {
|
||||
tmpl, err := texttemplate.New(name).Option("missingkey=zero").Parse(src)
|
||||
func execTextFuncs(name, src string, data any, funcs texttemplate.FuncMap) (string, error) {
|
||||
tmpl, err := texttemplate.New(name).Option("missingkey=zero").Funcs(funcs).Parse(src)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("postcard: parse %s: %w", name, err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user