feat(postcard): inline mail CSS at render with a per-layout opt-out

- github.com/vanng822/go-premailer v1.38.0 (default options) inlines the
  rendered HTML after the safety checks; the result is checked again,
  HTML without a style element is left as it is, an inliner error sends
  the style block only and warns (key inline:<layout>)
- opt-out: layout header key disable_auto_inline_css, the layouts column
  of the same name (migration 202611130003), LayoutFile/LayoutOverride/
  Draft.DisableAutoInlineCSS; SyncIndex mirrors and ResetOverride restores
  the file's value
- cabana layout form switch on the CSS tab, mapped into the layout draft
  and the save validation; en/pl copy
- tests: TestMailPartialsSmoke/inline, TestMailEditorSmoke/inline_flag,
  the layouts switch in TestMailScreensSmoke; CSS-slot tests read the
  style block through a no-op inliner
- 35-06 Task 2 (G-35-8)
This commit is contained in:
Jakub Zych
2026-11-13 21:12:01 +01:00
parent dcd0ae5338
commit d320733510
22 changed files with 551 additions and 85 deletions

File diff suppressed because one or more lines are too long

View File

@@ -51,6 +51,12 @@ fields:
mode: layout
span: full
tab: backend::lang.mail.layout.tab_text
disable_auto_inline_css:
label: backend::lang.mail.layout.disable_inline_css
comment: backend::lang.mail.layout.disable_inline_css_comment
type: switch
span: full
tab: backend::lang.mail.layout.tab_css
content_css:
label: backend::lang.mail.layout.css
comment: backend::lang.mail.layout.css_comment

View File

@@ -410,9 +410,13 @@ type MailLayout struct {
ContentHTML string `gorm:"column:content_html"`
ContentText string `gorm:"column:content_text"`
ContentCSS string `gorm:"column:content_css"`
IsCustom bool `gorm:"column:is_custom"`
FileHash *string `gorm:"column:file_hash"`
BaseHash *string `gorm:"column:base_hash"`
// DisableAutoInlineCSS keeps the layout's CSS in its style block only
// (postcard copies it onto the elements otherwise). A new custom layout
// starts with it off.
DisableAutoInlineCSS bool `gorm:"column:disable_auto_inline_css"`
IsCustom bool `gorm:"column:is_custom"`
FileHash *string `gorm:"column:file_hash"`
BaseHash *string `gorm:"column:base_hash"`
// CustomizedAt is when the layout was last saved from the admin.
CustomizedAt *time.Time `gorm:"column:customized_at"`
CreatedAt time.Time `gorm:"column:created_at"`
@@ -1036,7 +1040,7 @@ func stamp(custom *bool, base, file **string, at **time.Time, hash string) {
// Fillable lists the columns the layout form writes. code is written only
// when a custom layout is created (its field's context is create).
func (MailLayout) Fillable() []string {
return []string{"name", "code", "content_html", "content_text", "content_css"}
return []string{"name", "code", "content_html", "content_text", "content_css", "disable_auto_inline_css"}
}
// Rules require a name and a code.
@@ -1249,7 +1253,7 @@ func (c mailLayoutsAdmin) validate(ctx context.Context, model any) error {
if err != nil {
return err
}
draft := postcard.Draft{Kind: postcard.KindLayout, Name: l.Code, HTML: l.ContentHTML, Text: l.ContentText, CSS: l.ContentCSS}
draft := postcard.Draft{Kind: postcard.KindLayout, Name: l.Code, HTML: l.ContentHTML, Text: l.ContentText, CSS: l.ContentCSS, DisableAutoInlineCSS: l.DisableAutoInlineCSS}
if de := c.mail.editor.Validate(ctx, draft); de != nil {
return c.mail.draftFailure(ctx, de)
}

View File

@@ -546,11 +546,12 @@ func (s *service) mailLayoutDraft(ctx context.Context, id uint64, values map[str
name = code
}
return postcard.Draft{
Kind: postcard.KindLayout,
Name: name,
HTML: stringValue(values["content_html"]),
Text: stringValue(values["content_text"]),
CSS: stringValue(values["content_css"]),
Kind: postcard.KindLayout,
Name: name,
HTML: stringValue(values["content_html"]),
Text: stringValue(values["content_text"]),
CSS: stringValue(values["content_css"]),
DisableAutoInlineCSS: boolValue(values["disable_auto_inline_css"]),
}, nil
}
@@ -653,6 +654,25 @@ func (s *service) mailLayoutCodeByID(ctx context.Context, id uint) (string, erro
return codes[0], nil
}
// boolValue reads a switch value from a form payload: a JSON boolean, a
// number, or a string such as "1", "true" or "on".
func boolValue(v any) bool {
switch b := v.(type) {
case bool:
return b
case float64:
return b != 0
case int:
return b != 0
case string:
switch strings.ToLower(strings.TrimSpace(b)) {
case "1", "true", "on", "yes":
return true
}
}
return false
}
func stringValue(v any) string {
if v == nil {
return ""

View File

@@ -13,6 +13,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"sync/atomic"
@@ -671,7 +672,7 @@ func mailLayoutsAndPartials(t *testing.T, env *mailEnv, rootToken string) {
if err := env.gdb.First(&custom, customID).Error; err != nil {
t.Fatal(err)
}
if !custom.IsCustom || custom.Source != nil || custom.Code != "promo-2026" {
if !custom.IsCustom || custom.Source != nil || custom.Code != "promo-2026" || custom.DisableAutoInlineCSS {
t.Fatalf("custom layout = %+v", custom)
}
env.expectFieldRefusal(t, http.StatusUnprocessableEntity, http.MethodPost, mailLayoutsPath, rootToken, map[string]any{
@@ -714,6 +715,30 @@ func mailLayoutsAndPartials(t *testing.T, env *mailEnv, rootToken string) {
if msgs := env.driver.messages(); !strings.Contains(msgs[len(msgs)-1].HTML, "customized-layout") {
t.Fatalf("send did not use the customized layout: %s", msgs[len(msgs)-1].HTML)
}
// The CSS tab's switch keeps the layout's CSS in its style block:
// the next send has no inlined style on the button.
withButton := `<style>{{ .css }}</style><div class="blog-mail customized-layout">{{ .Content }}{{ partial "button" "url" "https://example.com" "body" "Go" }}</div>`
for _, optOut := range []bool{true, false} {
env.expect(t, http.StatusOK, http.MethodPut, blogPath, rootToken, map[string]any{
"name": "Blog", "content_html": withButton, "content_text": blogFile.Text, "content_css": ".button { color: #123456; }", "disable_auto_inline_css": optOut,
})
if err := env.gdb.First(&blog, blogID).Error; err != nil || blog.DisableAutoInlineCSS != optOut {
t.Fatalf("saved switch = %v, want %v (err %v)", blog.DisableAutoInlineCSS, optOut, err)
}
if err := env.mailer.Send(context.Background(), postcard.Message{Template: blogWelcomeEn, To: []string{"reader@example.test"}, Vars: map[string]any{"name": "Grace"}}); err != nil {
t.Fatal(err)
}
msgs := env.driver.messages()
html := msgs[len(msgs)-1].HTML
button := regexp.MustCompile(`<a [^>]*button-primary[^>]*>`).FindString(html)
if inlined := strings.Contains(button, `style="color:#123456"`); button == "" || inlined == optOut {
t.Fatalf("opt-out %v: button %q in %s", optOut, button, html)
}
if optOut && !strings.Contains(html, "<style>.button { color: #123456; }") {
t.Fatalf("opt-out: the style block was not kept: %s", html)
}
}
})
t.Run("partials", func(t *testing.T) {
@@ -923,7 +948,7 @@ Hi **{{ .name }}**, thanks for joining the Acme blog.
preview := env.expect(t, http.StatusOK, http.MethodPost, "/mail/preview", rootToken, map[string]any{
"mode": "branding", "id": 0, "values": map[string]any{"site_name": "Preview Name"},
})
if html := fmt.Sprint(preview["data"].(map[string]any)["html"]); !strings.Contains(html, "<span>Preview Name</span>") || !strings.Contains(html, "Preview Name</p>") {
if html := fmt.Sprint(preview["data"].(map[string]any)["html"]); !strings.Contains(html, "Preview Name</span>") || !strings.Contains(html, "Preview Name</p>") {
t.Fatalf("branding preview lacks the site name: %s", html)
}
})