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:
@@ -16,6 +16,12 @@ The file format is WinterCMS's: an INI header with the `subject`, the `layout` a
|
||||
|
||||
Each message gets an HTML part, rendered from the Markdown, and a plain-text part. `mail.css` and the brand CSS go into the layout's style block; see [Branding](#branding).
|
||||
|
||||
### CSS inlining
|
||||
|
||||
Many mail clients drop a style block, so postcard also copies the CSS onto the elements it styles, as WinterCMS does: after the layout has rendered, every rule of the HTML's style elements is written into the `style` attribute of the elements it matches (with go-premailer), and CSS widths and heights also become `width` and `height` attributes. Classes stay on the elements. Rules that cannot be inlined, such as media queries and `:hover`, stay in a style element in the head; the style block holds only those afterwards. The preview, the test send and real mail are inlined the same way, and the plain-text part is never touched.
|
||||
|
||||
A layout keeps its CSS in the style block only when it opts out: a layout file with `disable_auto_inline_css = true` in its header (`1` and `yes` also work), or a layout edited in the admin with **Do not inline CSS** switched on (its CSS tab). The built-in layouts all inline. If the inliner fails on a message, that message is sent with its style block only and a warning is logged; mail is never stopped by it.
|
||||
|
||||
## Partials
|
||||
|
||||
A partial is a block that several templates and layouts share, such as a button or a footer note. A plugin implements `pact.HasMailPartials`: it returns its embedded `views/mail` files and the partial names it ships. A partial named `acme.blog::mail.partials.note` lives in `views/mail/partials/note.htm`, and its file has the layout format, with a text section and an HTML section:
|
||||
|
||||
24
go.mod
24
go.mod
@@ -40,14 +40,15 @@ require (
|
||||
github.com/spf13/pflag v1.0.9
|
||||
github.com/testcontainers/testcontainers-go v0.44.0
|
||||
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0
|
||||
github.com/vanng822/go-premailer v1.38.0
|
||||
github.com/wneessen/go-mail v0.8.1
|
||||
github.com/yuin/goldmark v1.8.6
|
||||
gocloud.dev v0.46.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
golang.org/x/crypto v0.58.0
|
||||
golang.org/x/image v0.46.0
|
||||
golang.org/x/net v0.58.0
|
||||
golang.org/x/term v0.46.0
|
||||
golang.org/x/text v0.42.0
|
||||
golang.org/x/net v0.62.0
|
||||
golang.org/x/term v0.47.0
|
||||
golang.org/x/text v0.43.0
|
||||
gorm.io/driver/postgres v1.6.3
|
||||
gorm.io/gorm v1.31.2
|
||||
)
|
||||
@@ -56,6 +57,8 @@ require (
|
||||
dario.cat/mergo v1.0.2 // indirect
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/PuerkitoBio/goquery v1.13.0 // indirect
|
||||
github.com/andybalholm/cascadia v1.3.4 // indirect
|
||||
github.com/atotto/clipboard v0.1.4 // indirect
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.9 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 // indirect
|
||||
@@ -100,6 +103,7 @@ require (
|
||||
github.com/docker/go-units v0.5.0 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/ebitengine/purego v0.10.1 // indirect
|
||||
github.com/fatih/color v1.18.0 // indirect
|
||||
github.com/felixge/httpsnoop v1.1.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
@@ -112,6 +116,7 @@ require (
|
||||
github.com/google/wire v0.7.0 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.19.0 // indirect
|
||||
github.com/gorilla/css v1.0.1 // indirect
|
||||
github.com/inbucket/html2text v1.0.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
@@ -125,6 +130,8 @@ require (
|
||||
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect
|
||||
github.com/magiconair/properties v1.8.10 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.30 // indirect
|
||||
github.com/mitchellh/copystructure v1.2.0 // indirect
|
||||
github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
|
||||
@@ -139,6 +146,9 @@ require (
|
||||
github.com/moby/sys/userns v0.1.0 // indirect
|
||||
github.com/moby/term v0.5.2 // indirect
|
||||
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||
github.com/olekukonko/errors v1.1.0 // indirect
|
||||
github.com/olekukonko/ll v0.0.9 // indirect
|
||||
github.com/olekukonko/tablewriter v1.0.7 // indirect
|
||||
github.com/opencontainers/go-digest v1.0.0 // indirect
|
||||
github.com/opencontainers/image-spec v1.1.1 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
|
||||
@@ -150,6 +160,7 @@ require (
|
||||
github.com/segmentio/encoding v0.5.4 // indirect
|
||||
github.com/shirou/gopsutil/v4 v4.26.6 // indirect
|
||||
github.com/sirupsen/logrus v1.9.4 // indirect
|
||||
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect
|
||||
github.com/stretchr/testify v1.12.1 // indirect
|
||||
github.com/tidwall/gjson v1.19.0 // indirect
|
||||
github.com/tidwall/match v1.2.0 // indirect
|
||||
@@ -157,6 +168,7 @@ require (
|
||||
github.com/tidwall/sjson v1.2.5 // indirect
|
||||
github.com/tklauser/go-sysconf v0.4.0 // indirect
|
||||
github.com/tklauser/numcpus v0.12.0 // indirect
|
||||
github.com/vanng822/css v1.0.1 // indirect
|
||||
github.com/xo/terminfo v1.0.0 // indirect
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||
github.com/yuin/gopher-lua v1.1.1 // indirect
|
||||
@@ -171,8 +183,8 @@ require (
|
||||
go.uber.org/atomic v1.12.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/oauth2 v0.36.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/sync v0.24.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
|
||||
google.golang.org/api v0.272.0 // indirect
|
||||
|
||||
53
go.sum
53
go.sum
@@ -40,6 +40,8 @@ github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ
|
||||
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/PuerkitoBio/goquery v1.13.0 h1:mqHbjD7Jmnul4DTR24LKTjo1uUmHUh072kteGV+xpFM=
|
||||
github.com/PuerkitoBio/goquery v1.13.0/go.mod h1:Hip5mdBL8K2wEGKJdr27sRaNwIdDajmCwB/ExUPwW+g=
|
||||
github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0=
|
||||
github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
|
||||
github.com/alecthomas/chroma/v2 v2.27.0 h1:FodwmyOBgJULFYmDqibcp9pvfDLWdtPRh9v/r5BXYZs=
|
||||
@@ -48,6 +50,8 @@ github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs
|
||||
github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
|
||||
github.com/alicebob/miniredis/v2 v2.40.0 h1:6IgTQbvm2JiMYZ8yur/acNJzVjtSOWCelxXbk/LUBXc=
|
||||
github.com/alicebob/miniredis/v2 v2.40.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM=
|
||||
github.com/andybalholm/cascadia v1.3.4 h1:vM2lgh0Vru9Vwyfm4cQqWP2HHMW0u0+2PAW7Q38Qufg=
|
||||
github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM=
|
||||
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
|
||||
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.9 h1:/rYeyO2+HrMztAmxAq9++XJtFMqSIpSsNA0yDGALYq4=
|
||||
@@ -167,6 +171,8 @@ github.com/envoyproxy/go-control-plane/envoy v1.37.0 h1:u3riX6BoYRfF4Dr7dwSOroNf
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A=
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds=
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
|
||||
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
||||
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
|
||||
@@ -227,6 +233,8 @@ github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
|
||||
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
|
||||
github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
|
||||
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
|
||||
github.com/inbucket/html2text v1.0.0 h1:N5kza++4uBBDJ2Z3KUnTRyPNoBcW+YfOgNiNmNB+sgs=
|
||||
github.com/inbucket/html2text v1.0.0/go.mod h1:5TrhXQKGU+LXurODaSm55Y9eXoPBRnYiOz4x2XfUoJU=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438 h1:Dj0L5fhJ9F82ZJyVOmBx6msDp/kfd1t9GRfny/mfJA0=
|
||||
@@ -269,6 +277,10 @@ github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRt
|
||||
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
|
||||
github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE=
|
||||
github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-runewidth v0.0.30 h1:+KUuiDA4fF0R1p5FeueHefjDm+GIM+kWfFnDjybOPgk=
|
||||
github.com/mattn/go-runewidth v0.0.30/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
@@ -309,6 +321,12 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU
|
||||
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.1 h1:JDEJraFsQE17Dut9HFDHzCoAWGEQJom5s0TRd17NIEQ=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.1/go.mod h1:Vee0/9RD3Quc/NmwEjzzD7VTZ+Ir7QbXocrkhOzmUKA=
|
||||
github.com/olekukonko/errors v1.1.0 h1:RNuGIh15QdDenh+hNvKrJkmxxjV4hcS50Db478Ou5sM=
|
||||
github.com/olekukonko/errors v1.1.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y=
|
||||
github.com/olekukonko/ll v0.0.9 h1:Y+1YqDfVkqMWuEQMclsF9HUR5+a82+dxJuL1HHSRpxI=
|
||||
github.com/olekukonko/ll v0.0.9/go.mod h1:En+sEW0JNETl26+K8eZ6/W4UQ7CYSrrgg/EdIYT2H8g=
|
||||
github.com/olekukonko/tablewriter v1.0.7 h1:HCC2e3MM+2g72M81ZcJU11uciw6z/p82aEnm4/ySDGw=
|
||||
github.com/olekukonko/tablewriter v1.0.7/go.mod h1:H428M+HzoUXC6JU2Abj9IT9ooRmdq9CxuDmKMtrOCMs=
|
||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
|
||||
@@ -351,6 +369,8 @@ github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo=
|
||||
github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs=
|
||||
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo=
|
||||
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
|
||||
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
|
||||
@@ -377,6 +397,10 @@ github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRU
|
||||
github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI=
|
||||
github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4=
|
||||
github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=
|
||||
github.com/vanng822/css v1.0.1 h1:10yiXc4e8NI8ldU6mSrWmSWMuyWgPr9DZ63RSlsgDw8=
|
||||
github.com/vanng822/css v1.0.1/go.mod h1:tcnB1voG49QhCrwq1W0w5hhGasvOg+VQp9i9H1rCM1w=
|
||||
github.com/vanng822/go-premailer v1.38.0 h1:nYXopG+L6lcRV6dEAemLLE71bihun3gxgfNJZ9iYm1Q=
|
||||
github.com/vanng822/go-premailer v1.38.0/go.mod h1:6Jcm7sYO8ON3J/IIlox2fWq+YPgGopwx7VbETlZRZtY=
|
||||
github.com/wneessen/go-mail v0.8.1 h1:tVcncj02/QySVFw3zr/kXOzZcuFQqBNT6K+Rbgm/pcM=
|
||||
github.com/wneessen/go-mail v0.8.1/go.mod h1:dWZ61zadzCIyvB4y1/YzC5O7MrbbzBfPkARmbosdf8w=
|
||||
github.com/xo/terminfo v1.0.0 h1:2ZpYzqWzyyytjk3TP6aJVDhkMAkc99/1xKQdA3TDTBY=
|
||||
@@ -420,34 +444,35 @@ go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
gocloud.dev v0.46.0 h1:niIuZwSjMtBx8K+ITB2s5kZullB13PGOS2ZoQPZxQ4Q=
|
||||
gocloud.dev v0.46.0/go.mod h1:ACQe+2qO+hEO+pdcvvsM+RB63r8TyGD1W3ESCLFyzvM=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
|
||||
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
|
||||
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
|
||||
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
|
||||
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
|
||||
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
|
||||
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
|
||||
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
|
||||
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
|
||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY=
|
||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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 ""
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -673,6 +673,8 @@ mail:
|
||||
text_comment: "Wraps the plain-text message. Put {{ .Content }} where the message goes."
|
||||
css: "CSS"
|
||||
css_comment: "Styles for this layout. They are inlined into the HTML message after the branding styles."
|
||||
disable_inline_css: "Do not inline CSS"
|
||||
disable_inline_css_comment: "By default the CSS is also copied into each element's style attribute, so mail clients that drop the style block still show it. Turn this on to keep the style block only."
|
||||
delete_confirm: "Delete this layout? This cannot be undone. A layout that customized templates still use cannot be deleted."
|
||||
reset_confirm: "Reset this layout to the file version? Your HTML, plain-text and CSS changes are deleted, and unsaved edits on this page are discarded. This cannot be undone."
|
||||
delete_in_use:
|
||||
|
||||
@@ -709,6 +709,8 @@ mail:
|
||||
text_comment: "Otacza wiadomość tekstową. Wstaw {{ .Content }} w miejscu treści."
|
||||
css: "CSS"
|
||||
css_comment: "Style tego układu. Są wstawiane do wiadomości HTML po stylach wyglądu."
|
||||
disable_inline_css: "Nie wstawiaj CSS do elementów"
|
||||
disable_inline_css_comment: "Domyślnie CSS jest też kopiowany do atrybutu style każdego elementu, aby klienty poczty usuwające blok stylów nadal go pokazywały. Włącz, aby zostawić tylko blok stylów."
|
||||
delete_confirm: "Usunąć ten układ? Tej operacji nie można cofnąć. Nie można usunąć układu, którego używają dostosowane szablony."
|
||||
reset_confirm: "Przywrócić wersję układu z pliku? Twoje zmiany HTML, tekstu i CSS zostaną usunięte, a niezapisane zmiany na tej stronie odrzucone. Tej operacji nie można cofnąć."
|
||||
delete_in_use:
|
||||
|
||||
@@ -26,7 +26,7 @@ Use cases:
|
||||
- WinterCMS file format: an INI header (`subject`, `layout`, `description`), a `==` separator, then a Markdown body rendered with Go `html/template` variables such as `{{ .name }}`.
|
||||
- Layouts with a header, a text wrapper and an HTML wrapper, referenced from templates by a short alias (`pact.HasMailTemplates` maps aliases to full names). Three layouts are built in and usable from any plugin's templates: `default`, `system` and `minimal`.
|
||||
- Partials: reusable blocks named `<plugin>::mail.partials.<name>`, loaded from `views/mail/partials/<name>.htm` and declared through `pact.HasMailPartials`. Bodies and layouts call them with `{{ partial "<name>" "key" value }}`. The partials `button`, `panel`, `table` and `subcopy` are built in.
|
||||
- Every message gets an HTML part (Markdown converted with goldmark) and a plain-text part. The brand CSS (`mail.brandCss`, or the saved Branding) and `mail.css` go into the layout's style block.
|
||||
- Every message gets an HTML part (Markdown converted with goldmark) and a plain-text part. The brand CSS (`mail.brandCss`, or the saved Branding) and `mail.css` go into the layout's style block, and the rendered HTML is then inlined: each CSS rule is copied into the `style` attribute of the elements it matches (go-premailer), so mail clients that drop style blocks still show the design. A layout opts out with `disable_auto_inline_css`.
|
||||
- Safety checks: rendered HTML with script, iframe, object or embed tags, inline event handlers or `javascript:`/`vbscript:`/`data:` URLs is rejected; CR/LF in the subject or address headers is rejected; addresses are parsed with `net/mail`.
|
||||
- Drivers behind the `postcard.Driver` interface: `postcard.MemoryDriver` (keeps messages for tests), `postcard.LogDriver` (logs headers and the text part through `log/slog`, never the HTML or credentials), `postcard.SMTPDriver` (go-mail with an explicit TLS policy) and `postcard.FailDriver` (a deterministic failure for tests).
|
||||
- Database overrides: a customized row of `system_mail_templates` replaces a template's subject, body and layout, a customized row of `system_mail_layouts` or `system_mail_partials` replaces a layout or a partial, and `system_mail_layouts` also holds layouts that exist only in the database. The mailer reads them on every send, with no cache, in every process that publishes a `*gorm.DB`. A missing database, tables that are not migrated yet, or an override that does not render or fails the safety checks sends the file version.
|
||||
@@ -181,6 +181,18 @@ Markdown drops raw HTML, so a call in a body does not insert the partial's HTML
|
||||
|
||||
A template selects one with `layout = "system"`. A plugin's own alias of the same name wins, except `default`, which plugins cannot redefine. Every built-in layout has the `{{ .brandCss }}{{ .css }}` style block.
|
||||
|
||||
### CSS inlining
|
||||
|
||||
After a layout's HTML wrapper has rendered and passed the safety checks, postcard inlines it, as WinterCMS's `MailManager` does with CssToInlineStyles: `github.com/vanng822/go-premailer` with its default options reads the rules of every style element, writes them into the `style` attributes of the matching elements by specificity, mirrors CSS `width` and `height` to the attributes of the same name, keeps `class` attributes, and puts the rules it cannot inline (media queries, pseudo-classes such as `:hover`, selectors with `*`) back in one style element, marked `!important`. The inlined HTML is checked again, so a `javascript:`, `vbscript:` or `data:` address that reaches a `style` attribute fails the render as before. HTML with no style element is left as it is. Preview, test send and sends run the same code; the text part is never changed.
|
||||
|
||||
A layout opts out with WinterCMS's option name, `disable_auto_inline_css`:
|
||||
|
||||
- a layout file sets the header key `disable_auto_inline_css = true` (`1` or `yes`, in any case, also work); `postcard.LayoutFile.DisableAutoInlineCSS` reports it;
|
||||
- a row of `system_mail_layouts` sets the column `disable_auto_inline_css` (`postcard.LayoutOverride.DisableAutoInlineCSS`); `postcard.SyncIndex` mirrors the file's value into rows that are not customized and `postcard.ResetOverride` writes it back;
|
||||
- a layout draft sets `postcard.Draft.DisableAutoInlineCSS`.
|
||||
|
||||
An opted-out layout keeps its style block as rendered. When the inliner fails on a message, the message is sent with its style block only and a warning keyed by the layout is logged at most once a minute.
|
||||
|
||||
Both wrappers of every layout get these keys: `Content`, `Subject`, `css`, `brandCss`, `logoUrl` (see [Branding](#branding)), `siteName` (the Branding's site name, else the display name of `mail.from`, else empty) and `year` (the current year). The default layout calls the header only when `logoUrl` or `siteName` is set, and builds the footer line from `year` and `siteName`, `© 2026 Acme`, or `© 2026` without a name. Its text wrapper is the message, a blank line and the footer's text section.
|
||||
|
||||
| Partial | Arguments | Renders |
|
||||
@@ -394,7 +406,7 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
|
||||
| `postcard.OverrideSource` | Supplies the database overrides of one render. `postcard.OverrideSource.MailOverrides` takes the template name; an empty name asks for everything except a template override. |
|
||||
| `postcard.Overrides` | What a source returns: the template override in `postcard.Overrides.Template` (nil when there is none), layout content by code in `postcard.Overrides.Layouts`, partial content by name in `postcard.Overrides.Partials` and the saved Branding in `postcard.Overrides.Brand` (nil while it has never been saved). |
|
||||
| `postcard.TemplateOverride` | A template's customized subject, body and layout code. An empty `postcard.TemplateOverride.Layout` keeps the file's layout. |
|
||||
| `postcard.LayoutOverride` | A layout's name, HTML wrapper, text wrapper and CSS from the database. In `postcard.Overrides.Layouts` under a file layout's full name it replaces that layout; under another code it is a database-only layout. |
|
||||
| `postcard.LayoutOverride` | A layout's name, HTML wrapper, text wrapper and CSS from the database, and `postcard.LayoutOverride.DisableAutoInlineCSS`, the layout's opt-out of CSS inlining. In `postcard.Overrides.Layouts` under a file layout's full name it replaces that layout; under another code it is a database-only layout. |
|
||||
| `postcard.PartialOverride` | A partial's HTML and text sections from the database, in `postcard.Overrides.Partials` under the partial's full name. |
|
||||
| `postcard.NewDBSource` | The source over postcard's tables. It looks the `*gorm.DB` up on the app at every call and returns no overrides when none is published. It builds the Branding logo's URL from the app's configuration. |
|
||||
| `postcard.Brand` | The Branding: thirteen colours, `postcard.Brand.LogoURL`, the logo's absolute URL, and `postcard.Brand.SiteName`, the name the built-in layouts show. |
|
||||
@@ -412,9 +424,9 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
|
||||
| `postcard.Editor.Validate` | Checks a draft; returns nil or a `postcard.DraftError`. |
|
||||
| `postcard.Editor.Preview` | Renders a draft to a `postcard.Preview` (subject, HTML part, text part). |
|
||||
| `postcard.Editor.SendDraft` | Renders a draft and delivers it to one address. |
|
||||
| `postcard.Draft` | Unsaved content of one kind. |
|
||||
| `postcard.Draft` | Unsaved content of one kind. A layout draft's `postcard.Draft.DisableAutoInlineCSS` previews it without CSS inlining. |
|
||||
| `postcard.DraftError` | Why a draft cannot be saved: field, rule, message and, for an unknown partial, its name. |
|
||||
| `postcard.TemplateFile`, `postcard.LayoutFile`, `postcard.PartialFile` | A registered file with its parts, its normalized `Source` and its `Hash`. `postcard.TemplateFile.Samples` holds the sample values and `postcard.TemplateFile.Layout` the full name of the file's layout. |
|
||||
| `postcard.TemplateFile`, `postcard.LayoutFile`, `postcard.PartialFile` | A registered file with its parts, its normalized `Source` and its `Hash`. `postcard.TemplateFile.Samples` holds the sample values and `postcard.TemplateFile.Layout` the full name of the file's layout; `postcard.LayoutFile.DisableAutoInlineCSS` is the layout's `disable_auto_inline_css` header key. |
|
||||
| `postcard.Catalog.Templates`, `postcard.Catalog.Layouts`, `postcard.Catalog.Partials` | The registered files, sorted by name. |
|
||||
| `postcard.Catalog.Template`, `postcard.Catalog.Layout`, `postcard.Catalog.Partial` | One registered file by full name. |
|
||||
| `postcard.Catalog.TemplateFor` | The file a template name renders from: its own file, or the base template's file for a `<template>-<locale>` name whose locale ships none. |
|
||||
@@ -454,7 +466,7 @@ mail:
|
||||
## Dependencies
|
||||
|
||||
- SummerCMS modules: [backpack](../backpack/README.md), [compass](../compass/README.md), [diary](../diary/README.md) (component logger `postcard` when the app publishes no logger), [pact](../pact/README.md), and the `attach` package of [lagoon](../lagoon/README.md) (`attach.AbsolutePublicURL` and `attach.BlobKey` for the logo's URL; lagoon itself is not imported).
|
||||
- Third-party: `github.com/wneessen/go-mail` (SMTP), `github.com/yuin/goldmark` (Markdown, and its table extension inside partials), `gorm.io/gorm` (reading overrides), `github.com/go-gormigrate/gormigrate/v2` (the mail tables' migrations).
|
||||
- Third-party: `github.com/wneessen/go-mail` (SMTP), `github.com/yuin/goldmark` (Markdown, and its table extension inside partials), `github.com/vanng822/go-premailer` (CSS inlining, pinned at v1.38.0; see `.planning/notes/2026-11-13-mail-layouts-css-inlining.md`), `gorm.io/gorm` (reading overrides), `github.com/go-gormigrate/gormigrate/v2` (the mail tables' migrations).
|
||||
- Standard library: `bytes`, `context`, `crypto/rand`, `crypto/sha256`, `database/sql`, `embed`, `encoding/hex`, `errors`, `fmt`, `html/template`, `io/fs`, `log/slog`, `net/mail`, `regexp`, `sort`, `strconv`, `strings`, `sync`, `text/template` (and `text/template/parse`), `time`.
|
||||
- Tests additionally use `github.com/testcontainers/testcontainers-go` (Mailpit and Postgres containers), `gorm.io/driver/postgres` and `github.com/jackc/pgx/v5`.
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -36,6 +37,17 @@ func styleBlock(t *testing.T, html string) string {
|
||||
return css
|
||||
}
|
||||
|
||||
// styleAttr matches a style attribute, which inlining adds to elements.
|
||||
var styleAttr = regexp.MustCompile(` style="[^"]*"`)
|
||||
|
||||
// unstyled returns html without its style attributes, for assertions on
|
||||
// the markup of inlined mail.
|
||||
func unstyled(html string) string { return styleAttr.ReplaceAllString(html, "") }
|
||||
|
||||
// noInline is an inliner that leaves the HTML as it is, for tests of what
|
||||
// fills the CSS slots rather than of inlining (TestMailPartialsSmoke/inline).
|
||||
func noInline(html string) (string, error) { return html, nil }
|
||||
|
||||
// TestMailBrandSmoke covers Branding: the compiled brand CSS and its colour
|
||||
// checks, the precedence over mail.brandCss once the settings row exists,
|
||||
// the logo URL built at send time from configuration, and the editor's
|
||||
@@ -173,8 +185,11 @@ func TestMailBrandSmoke(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
// The preview checks read the style block: what fills the CSS slots, not
|
||||
// how it is inlined.
|
||||
t.Run("preview", func(t *testing.T) {
|
||||
ed, drv := newEditor(t, nil)
|
||||
ed.m.inline = noInline
|
||||
ed.m.opts.CSS, ed.m.opts.BrandCSS = "p{margin:1px}", ".cfg{color:blue}"
|
||||
draft := Draft{Kind: KindBrand, Brand: &Brand{LinkColor: "#112233", ButtonPrimaryBg: "#445566"}}
|
||||
if problem := ed.Validate(ctx, draft); problem != nil {
|
||||
@@ -219,6 +234,7 @@ func TestMailBrandSmoke(t *testing.T) {
|
||||
Brand: &Brand{LinkColor: "#999999", LogoURL: "https://cdn.example.com/saved.png"},
|
||||
Layouts: map[string]LayoutOverride{defaultLayoutName: {HTML: `<img src="{{ .logoUrl }}" alt=""><style>{{ .brandCss }}</style>{{ .Content }}`, Text: "{{ .logoUrl }}\n{{ .Content }}"}},
|
||||
})
|
||||
ed.m.inline = noInline
|
||||
got, err = ed.Preview(ctx, Draft{Kind: KindBrand, Brand: &Brand{LinkColor: "#112233", LogoURL: "https://cdn.example.com/u/logo.png"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -263,9 +279,13 @@ func TestMailBrandSmoke(t *testing.T) {
|
||||
// A logo and a site name: the logo in the header, the name as its
|
||||
// alternative text, the card, the styled button and the footer.
|
||||
got := send("blog@example.com", &Brand{LogoURL: logo, SiteName: " Acme Mail "})
|
||||
if style := buttonStyle(t, got.HTML); !strings.Contains(style, "background-color:#d66829") {
|
||||
t.Errorf("logo and name: the button is not styled: %q", style)
|
||||
}
|
||||
got.HTML = unstyled(got.HTML)
|
||||
for _, want := range []string{
|
||||
`class="wrapper layout-default"`,
|
||||
"<td class=\"header\">\n<img src=\"" + logo + "\" class=\"logo\" alt=\"Acme Mail\" />",
|
||||
"<td class=\"header\">\n<img src=\"" + logo + "\" class=\"logo\" alt=\"Acme Mail\"/>",
|
||||
`class="inner-body"`,
|
||||
"<td class=\"content-cell\">\n<p>Hi Ada</p>",
|
||||
`class="button button-primary"`,
|
||||
@@ -285,29 +305,34 @@ func TestMailBrandSmoke(t *testing.T) {
|
||||
|
||||
// A site name without a logo: the name in the header.
|
||||
got = send("blog@example.com", &Brand{SiteName: "Acme Mail"})
|
||||
got.HTML = unstyled(got.HTML)
|
||||
if !strings.Contains(got.HTML, "<td class=\"header\">\n<span>Acme Mail</span>") || strings.Contains(got.HTML, "<img") {
|
||||
t.Errorf("name only: HTML = %s", got.HTML)
|
||||
}
|
||||
|
||||
// The name reaches the HTML escaped, also in the alt attribute.
|
||||
got = send("blog@example.com", &Brand{LogoURL: logo, SiteName: `Bob "&" <b>Co</b>`})
|
||||
got.HTML = unstyled(got.HTML)
|
||||
if !strings.Contains(got.HTML, `alt="Bob "&" <b>Co</b>"`) || strings.Contains(got.HTML, "<b>Co</b>") {
|
||||
t.Errorf("the site name is not escaped:\n%s", got.HTML)
|
||||
}
|
||||
|
||||
// No Branding row: the display name of mail.from.
|
||||
got = send("Acme <no-reply@acme.test>", nil)
|
||||
got.HTML = unstyled(got.HTML)
|
||||
if !strings.Contains(got.HTML, "<td class=\"header\">\n<span>Acme</span>") || !strings.Contains(got.HTML, "<p>"+copyright()+" Acme</p>") {
|
||||
t.Errorf("mail.from name: HTML = %s", got.HTML)
|
||||
}
|
||||
// A Branding row with an empty name falls back to mail.from too.
|
||||
got = send("Acme <no-reply@acme.test>", &Brand{SiteName: " "})
|
||||
got.HTML = unstyled(got.HTML)
|
||||
if !strings.Contains(got.HTML, "<span>Acme</span>") {
|
||||
t.Errorf("empty site name: HTML = %s", got.HTML)
|
||||
}
|
||||
|
||||
// Neither a name nor a logo: no header row, the year alone.
|
||||
got = send("no-reply@acme.test", nil)
|
||||
got.HTML = unstyled(got.HTML)
|
||||
if strings.Contains(got.HTML, `class="header"`) || !strings.Contains(got.HTML, "<p>"+copyright()+"</p>") {
|
||||
t.Errorf("no name, no logo: HTML = %s", got.HTML)
|
||||
}
|
||||
@@ -330,6 +355,9 @@ func TestMailBrandSmoke(t *testing.T) {
|
||||
gdb := mailPostgres(t)
|
||||
cfg := brandCfg(t, map[string]string{"mail.yaml": "driver: memory\ncss: \"p{margin:1px}\"\nbrandCss: \".cfg{color:blue}\"\n"})
|
||||
m, drv, logs := bootMailAppCfg(t, gdb, cfg)
|
||||
// The style block shows which CSS fills the slots; inlining would
|
||||
// move it onto the elements.
|
||||
m.inline = noInline
|
||||
|
||||
// No Branding row: the configured brand CSS, as before.
|
||||
sendFixture(t, m, acmeNotice, "")
|
||||
|
||||
@@ -71,6 +71,8 @@ func TestBrand(t *testing.T) {
|
||||
CSS: ".mail-css{margin:0}",
|
||||
Overrides: fakeOverrides{ov: ov},
|
||||
})
|
||||
// Which CSS fills the slots, not how it is inlined.
|
||||
m.(*mailer).inline = noInline
|
||||
sendFixture(t, m, acmeNotice, "")
|
||||
got := lastMessage(t, drv)
|
||||
if !strings.Contains(got.HTML, "#112233") {
|
||||
@@ -92,6 +94,7 @@ func TestBrand(t *testing.T) {
|
||||
}
|
||||
drv := NewMemoryDriver()
|
||||
m := NewMailer(cat, drv, Options{BrandCSS: ".from-config{color:red}", CSS: ".mail-css{margin:0}"})
|
||||
m.(*mailer).inline = noInline
|
||||
sendFixture(t, m, acmeNotice, "")
|
||||
got := lastMessage(t, drv)
|
||||
if !strings.Contains(got.HTML, ".from-config") || !strings.Contains(got.HTML, ".mail-css") {
|
||||
|
||||
@@ -44,6 +44,8 @@ type Draft struct {
|
||||
HTML string
|
||||
Text string
|
||||
CSS string
|
||||
// DisableAutoInlineCSS is a layout draft's opt-out of CSS inlining.
|
||||
DisableAutoInlineCSS bool
|
||||
|
||||
// Brand is a branding draft. Nil is the default brand.
|
||||
Brand *Brand
|
||||
@@ -261,7 +263,7 @@ func (e *Editor) renderLayout(d Draft, ov Overrides, opts renderOptions) (Render
|
||||
for k, v := range ov.Layouts {
|
||||
layouts[k] = v
|
||||
}
|
||||
layouts[code] = LayoutOverride{Name: code, HTML: d.HTML, Text: d.Text, CSS: d.CSS}
|
||||
layouts[code] = LayoutOverride{Name: code, HTML: d.HTML, Text: d.Text, CSS: d.CSS, DisableAutoInlineCSS: d.DisableAutoInlineCSS}
|
||||
ov.Layouts = layouts
|
||||
opts.overrides = ov
|
||||
sample := sampleMessage()
|
||||
|
||||
@@ -301,8 +301,9 @@ func TestMailEditorSmoke(t *testing.T) {
|
||||
t.Errorf("draft layout not applied: %q / %q", got.Subject, got.HTML)
|
||||
}
|
||||
|
||||
// A layout draft wraps the sample message.
|
||||
got, err = ed.Preview(ctx, Draft{Kind: KindLayout, Name: "promo", HTML: `<div class="promo">{{ .Content }}</div><style>{{ .css }}</style>`, Text: "PROMO\n{{ .Content }}", CSS: ".promo{margin:0}"})
|
||||
// A layout draft wraps the sample message; this one keeps its style
|
||||
// block.
|
||||
got, err = ed.Preview(ctx, Draft{Kind: KindLayout, Name: "promo", HTML: `<div class="promo">{{ .Content }}</div><style>{{ .css }}</style>`, Text: "PROMO\n{{ .Content }}", CSS: ".promo{margin:0}", DisableAutoInlineCSS: true})
|
||||
if err != nil {
|
||||
t.Fatalf("layout preview: %v", err)
|
||||
}
|
||||
@@ -756,6 +757,73 @@ FROM `+TemplatesTable+` t LEFT JOIN `+LayoutsTable+` l ON l.id = t.layout_id WHE
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("inline_flag", func(t *testing.T) {
|
||||
gdb := mailPostgres(t)
|
||||
const plain = "acme.shop::mail.layouts.plain"
|
||||
cat := NewCatalog()
|
||||
fsys := fstest.MapFS{
|
||||
"views/mail/x.htm": {Data: []byte("subject = \"X\"\nlayout = \"plain\"\n==\nx\n")},
|
||||
"views/mail/layouts/plain.htm": {Data: []byte("name = \"Plain\"\ndisable_auto_inline_css = true\n==\n{{ .Content }}\n==\n<div>{{ .Content }}</div>\n")},
|
||||
}
|
||||
if err := cat.Register("acme.shop", fsys, []string{"acme.shop::mail.x"}, map[string]string{"plain": plain}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
flag := func(code string) bool {
|
||||
t.Helper()
|
||||
var v []bool
|
||||
if err := gdb.Raw(`SELECT disable_auto_inline_css FROM `+LayoutsTable+` WHERE code = ?`, code).Scan(&v).Error; err != nil || len(v) != 1 {
|
||||
t.Fatalf("flag of %s: %v %v", code, v, err)
|
||||
}
|
||||
return v[0]
|
||||
}
|
||||
sync := func() {
|
||||
t.Helper()
|
||||
if err := SyncIndex(ctx, gdb, cat, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// The index row mirrors the file's header key while not customized.
|
||||
sync()
|
||||
if !flag(plain) || flag(defaultLayoutName) {
|
||||
t.Fatalf("after sync: plain %v, default %v", flag(plain), flag(defaultLayoutName))
|
||||
}
|
||||
if err := gdb.Exec(`UPDATE ` + LayoutsTable + ` SET disable_auto_inline_css = FALSE WHERE code = '` + plain + `'`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sync()
|
||||
if !flag(plain) {
|
||||
t.Error("sync did not restore the file's value on a row that is not customized")
|
||||
}
|
||||
// A customized row keeps its own value, and the source reports it.
|
||||
if err := gdb.Exec(`UPDATE ` + LayoutsTable + ` SET disable_auto_inline_css = FALSE, is_custom = TRUE, base_hash = file_hash WHERE code = '` + plain + `'`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sync()
|
||||
if flag(plain) {
|
||||
t.Error("sync overwrote the value of a customized row")
|
||||
}
|
||||
ov, err := NewDBSource(appWith(t, gdb)).MailOverrides(ctx, "")
|
||||
if err != nil || ov.Layouts[plain].DisableAutoInlineCSS {
|
||||
t.Errorf("overrides = %+v, %v", ov.Layouts, err)
|
||||
}
|
||||
if err := gdb.Exec(`UPDATE ` + LayoutsTable + ` SET disable_auto_inline_css = TRUE WHERE code = '` + plain + `'`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ov, err = NewDBSource(appWith(t, gdb)).MailOverrides(ctx, ""); err != nil || !ov.Layouts[plain].DisableAutoInlineCSS {
|
||||
t.Errorf("overrides = %+v, %v", ov.Layouts, err)
|
||||
}
|
||||
// Reset writes the file's value back.
|
||||
if err := gdb.Exec(`UPDATE ` + LayoutsTable + ` SET disable_auto_inline_css = FALSE WHERE code = '` + plain + `'`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ResetOverride(ctx, gdb, cat, KindLayout, plain); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !flag(plain) {
|
||||
t.Error("reset did not write the file's value back")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func with(d Draft, edit func(*Draft)) Draft { edit(&d); return d }
|
||||
|
||||
31
modules/postcard/inline.go
Normal file
31
modules/postcard/inline.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package postcard
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/vanng822/go-premailer/premailer"
|
||||
)
|
||||
|
||||
// inlineCSS copies the rules of html's style elements onto the elements they
|
||||
// match, as WinterCMS does with CssToInlineStyles, so that mail clients that
|
||||
// drop the style block still show the design. Rules that cannot be inlined,
|
||||
// such as media queries and pseudo-classes, are kept in a style element.
|
||||
// Classes are kept, and CSS widths and heights are mirrored to the width
|
||||
// and height attributes (go-premailer's default options). A panic in the
|
||||
// inliner is returned as an error.
|
||||
func inlineCSS(html string) (out string, err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
out, err = "", fmt.Errorf("postcard: inline CSS: %v", r)
|
||||
}
|
||||
}()
|
||||
p, err := premailer.NewPremailerFromString(html, premailer.NewOptions())
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("postcard: inline CSS: %w", err)
|
||||
}
|
||||
out, err = p.Transform()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("postcard: inline CSS: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -54,6 +54,9 @@ type mailer struct {
|
||||
// log receives override warnings and failures; nil means moduleLog.
|
||||
log *slog.Logger
|
||||
warned warnGate
|
||||
// inline inlines a message's CSS; nil means inlineCSS. Tests set it to
|
||||
// force an inliner error.
|
||||
inline func(html string) (string, error)
|
||||
}
|
||||
|
||||
// NewMailer returns a mailer that renders from cat and delivers through
|
||||
@@ -149,7 +152,10 @@ func (m *mailer) render(ctx context.Context, msg Message) (RenderedMessage, erro
|
||||
// keeps mail.brandCss. The site name is the Branding's, else the display
|
||||
// name of mail.from.
|
||||
func (m *mailer) options(brand *Brand) renderOptions {
|
||||
opts := renderOptions{css: m.opts.CSS, brandCSS: m.opts.BrandCSS, siteName: siteName(brand, m.opts.From), year: time.Now().Year()}
|
||||
opts := renderOptions{
|
||||
css: m.opts.CSS, brandCSS: m.opts.BrandCSS, siteName: siteName(brand, m.opts.From), year: time.Now().Year(),
|
||||
inline: m.inline, warn: m.warn,
|
||||
}
|
||||
if brand == nil {
|
||||
return opts
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ Body **{{ .Name }}**.
|
||||
t.Fatalf("Register: %v", err)
|
||||
}
|
||||
drv := NewMemoryDriver()
|
||||
mail := NewMailer(cat, drv, Options{CSS: "p{color:red}", BrandCSS: ".brand{color:blue}"})
|
||||
mail := NewMailer(cat, drv, Options{CSS: "p{color:red}", BrandCSS: ".layout-hello{color:blue}"})
|
||||
if err := mail.Send(context.Background(), Message{
|
||||
Template: "golem15.hello::mail.note",
|
||||
To: []string{"ada@example.test"},
|
||||
@@ -154,7 +154,8 @@ Body **{{ .Name }}**.
|
||||
if !strings.Contains(got[0].HTML, `class="layout-hello"`) || !strings.Contains(got[0].HTML, "<strong>Ada</strong>") {
|
||||
t.Fatalf("HTML wrapper = %q", got[0].HTML)
|
||||
}
|
||||
if !strings.Contains(got[0].HTML, "p{color:red}") || !strings.Contains(got[0].HTML, ".brand{color:blue}") {
|
||||
// mail.css and the brand CSS are inlined onto the elements they match.
|
||||
if !strings.Contains(got[0].HTML, `<p style="color:red">`) || !strings.Contains(got[0].HTML, `<div class="layout-hello" style="color:blue">`) {
|
||||
t.Fatalf("shared css missing: %q", got[0].HTML)
|
||||
}
|
||||
|
||||
|
||||
@@ -343,12 +343,13 @@ func TestMailOverrideSmoke(t *testing.T) {
|
||||
gdb := mailPostgres(t)
|
||||
m, drv, logs := bootMailApp(t, gdb)
|
||||
stmts := []string{
|
||||
// A customized file layout, a database-only layout and an index
|
||||
// row that is not customized.
|
||||
`INSERT INTO ` + LayoutsTable + ` (code, source, name, content_html, content_text, content_css, is_custom) VALUES
|
||||
('acme.blog::mail.layouts.blog', 'acme.blog', 'Blog', '<div class="custom-blog">{{ .Content }}</div><style>{{ .css }}</style>', '[custom] {{ .Content }}', '.custom{margin:0}', TRUE),
|
||||
('promo', NULL, 'Promo', '<div class="promo">{{ .Content }}{{ partial "button" "url" "https://example.com" "body" "Shop" }}</div>', 'PROMO {{ .Content }}', '', TRUE),
|
||||
('` + defaultLayoutName + `', 'postcard', 'Default', '<div class="mirror">{{ .Content }}</div>', 'MIRROR {{ .Content }}', '', FALSE)`,
|
||||
// A customized file layout that keeps its style block (no
|
||||
// inlining), a database-only layout and an index row that is not
|
||||
// customized.
|
||||
`INSERT INTO ` + LayoutsTable + ` (code, source, name, content_html, content_text, content_css, is_custom, disable_auto_inline_css) VALUES
|
||||
('acme.blog::mail.layouts.blog', 'acme.blog', 'Blog', '<div class="custom-blog">{{ .Content }}</div><style>{{ .css }}</style>', '[custom] {{ .Content }}', '.custom{margin:0}', TRUE, TRUE),
|
||||
('promo', NULL, 'Promo', '<div class="promo">{{ .Content }}{{ partial "button" "url" "https://example.com" "body" "Shop" }}</div>', 'PROMO {{ .Content }}', '', TRUE, FALSE),
|
||||
('` + defaultLayoutName + `', 'postcard', 'Default', '<div class="mirror">{{ .Content }}</div>', 'MIRROR {{ .Content }}', '', FALSE, FALSE)`,
|
||||
// A customized built-in partial.
|
||||
`INSERT INTO ` + PartialsTable + ` (code, source, name, content_html, content_text, is_custom) VALUES
|
||||
('postcard::mail.partials.button', 'postcard', 'Button', '<a class="btn" href="{{ .url }}">{{ .body }}</a>', '{{ .body }}: {{ .url }}', TRUE),
|
||||
@@ -387,9 +388,12 @@ func TestMailOverrideSmoke(t *testing.T) {
|
||||
if all.Template != nil || len(all.Layouts) != 2 || len(all.Partials) != 1 {
|
||||
t.Errorf("overrides without a template name = %+v", all)
|
||||
}
|
||||
if l := all.Layouts["promo"]; l.Name != "Promo" || !strings.HasPrefix(l.Text, "PROMO") {
|
||||
if l := all.Layouts["promo"]; l.Name != "Promo" || !strings.HasPrefix(l.Text, "PROMO") || l.DisableAutoInlineCSS {
|
||||
t.Errorf("promo layout = %+v", l)
|
||||
}
|
||||
if l := all.Layouts["acme.blog::mail.layouts.blog"]; !l.DisableAutoInlineCSS {
|
||||
t.Errorf("blog layout = %+v, want the inlining opt-out", l)
|
||||
}
|
||||
if logs.Len() != 0 {
|
||||
t.Errorf("unexpected log output:\n%s", logs)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
package postcard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -51,6 +55,25 @@ var (
|
||||
_ pact.HasMailTemplates = templatesOnly{}
|
||||
)
|
||||
|
||||
// buttonTag finds the opening tag of the button partial's link.
|
||||
var buttonTag = regexp.MustCompile(`<a [^>]*button-primary[^>]*>`)
|
||||
|
||||
// buttonStyle returns the style attribute of the button partial's link, or
|
||||
// empty when it has none.
|
||||
func buttonStyle(t *testing.T, html string) string {
|
||||
t.Helper()
|
||||
tag := buttonTag.FindString(html)
|
||||
if tag == "" {
|
||||
t.Fatalf("no button in %s", html)
|
||||
}
|
||||
_, style, ok := strings.Cut(tag, ` style="`)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
style, _, _ = strings.Cut(style, `"`)
|
||||
return style
|
||||
}
|
||||
|
||||
// copyright is the footer line of the built-in layouts without a site name.
|
||||
func copyright() string { return "© " + strconv.Itoa(time.Now().Year()) }
|
||||
|
||||
@@ -219,7 +242,7 @@ func TestMailPartialsSmoke(t *testing.T) {
|
||||
}
|
||||
for _, want := range []string{
|
||||
"<p>Hi Ada</p>\n<table class=\"action\"",
|
||||
`<a href="https://example.com/go?a=1&b=2" class="button button-primary" target="_blank">Go</a>`,
|
||||
`<a class="button button-primary" href="https://example.com/go?a=1&b=2" target="_blank">Go</a>`,
|
||||
"</table>\n<p>Bye</p>",
|
||||
} {
|
||||
if !strings.Contains(msg.HTML, want) {
|
||||
@@ -340,9 +363,9 @@ func TestMailPartialsSmoke(t *testing.T) {
|
||||
m, drv := partialsMailer(t, Options{CSS: "p{color:red}", BrandCSS: ".brand{color:blue}"}, nil)
|
||||
msg := sendTemplate(t, m, drv, "acme.blog::mail.auto", nil)
|
||||
for _, want := range []string{
|
||||
`class="wrapper layout-system"`, "<p>Done.</p>",
|
||||
// mail.css is inlined onto the paragraph.
|
||||
`class="wrapper layout-system"`, `<p style="color:red">Done.</p>`,
|
||||
`<table class="subcopy"`, "<strong>This is an automatic message. Please do not reply to it.</strong>",
|
||||
".brand{color:blue}", "p{color:red}",
|
||||
} {
|
||||
if !strings.Contains(msg.HTML, want) {
|
||||
t.Errorf("system layout: HTML lacks %q:\n%s", want, msg.HTML)
|
||||
@@ -353,11 +376,12 @@ func TestMailPartialsSmoke(t *testing.T) {
|
||||
}
|
||||
|
||||
msg = sendTemplate(t, m, drv, "acme.blog::mail.bare", nil)
|
||||
if !strings.Contains(msg.HTML, "<body>\n<p>Done.</p>\n\n</body>") || strings.Contains(msg.HTML, "content-body") || strings.Contains(msg.HTML, "layout-system") {
|
||||
if !strings.Contains(msg.HTML, "<body>\n<p style=\"color:red\">Done.</p>\n\n\n</body>") || strings.Contains(msg.HTML, "content-body") || strings.Contains(msg.HTML, "layout-system") {
|
||||
t.Errorf("minimal layout: HTML = %q", msg.HTML)
|
||||
}
|
||||
if !strings.Contains(msg.HTML, "<style type=\"text/css\">.brand{color:blue}p{color:red}</style>") {
|
||||
t.Errorf("minimal layout: style block = %q", msg.HTML)
|
||||
// Every rule was inlined or matched nothing: no style block is left.
|
||||
if strings.Contains(msg.HTML, "<style") {
|
||||
t.Errorf("minimal layout: style block left = %q", msg.HTML)
|
||||
}
|
||||
if msg.Text != "Done." {
|
||||
t.Errorf("minimal layout: text = %q", msg.Text)
|
||||
@@ -385,6 +409,111 @@ func TestMailPartialsSmoke(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("inline", func(t *testing.T) {
|
||||
brand := &Brand{ButtonPrimaryBg: "#445566"}
|
||||
welcome := map[string]any{"Name": "Ada", "Link": "https://example.com/go"}
|
||||
const media = "@media only screen and (max-width: 600px) { .inner-body { width: 100% !important; } }"
|
||||
|
||||
// The default layout: the brand CSS is on the elements, the DOCTYPE
|
||||
// and the classes are kept, and the safety checks still pass.
|
||||
m, drv := partialsMailer(t, Options{CSS: media}, &Overrides{Brand: brand})
|
||||
inlined := sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome)
|
||||
if !strings.HasPrefix(inlined.HTML, `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"`) {
|
||||
t.Errorf("the DOCTYPE line was lost:\n%s", inlined.HTML)
|
||||
}
|
||||
if style := buttonStyle(t, inlined.HTML); !strings.Contains(style, "background-color:#445566") {
|
||||
t.Errorf("the button carries no inlined brand colour: style=%q\n%s", style, inlined.HTML)
|
||||
}
|
||||
if !strings.Contains(inlined.HTML, `class="inner-body"`) || validateHTML(inlined.HTML) != nil {
|
||||
t.Errorf("classes lost or the inlined HTML fails the safety checks:\n%s", inlined.HTML)
|
||||
}
|
||||
// A media query cannot be inlined: it stays in a style element.
|
||||
if css := styleBlock(t, inlined.HTML); !strings.Contains(css, "@media only screen and (max-width: 600px)") || !strings.Contains(css, ".inner-body") {
|
||||
t.Errorf("the media query is not in a style element:\n%s", css)
|
||||
}
|
||||
if strings.Contains(inlined.HTML, "width:100% !important") {
|
||||
t.Errorf("a media-query rule reached an element:\n%s", inlined.HTML)
|
||||
}
|
||||
|
||||
// optedOut checks a message whose layout kept its style block only.
|
||||
optedOut := func(name string, msg RenderedMessage) {
|
||||
t.Helper()
|
||||
if style := buttonStyle(t, msg.HTML); style != "" {
|
||||
t.Errorf("%s: the button has an inlined style %q", name, style)
|
||||
}
|
||||
if css := styleBlock(t, msg.HTML); !strings.Contains(css, "#445566") {
|
||||
t.Errorf("%s: the style block lost the brand CSS:\n%s", name, css)
|
||||
}
|
||||
}
|
||||
|
||||
// A file layout with the header key opts out.
|
||||
for _, value := range []string{"true", "1", "Yes"} {
|
||||
fsys := fstest.MapFS{
|
||||
"views/mail/plain.htm": {Data: []byte("subject = \"Plain\"\nlayout = \"plain\"\n==\n{{ partial \"button\" \"url\" \"https://example.com\" \"body\" \"Go\" }}\n")},
|
||||
"views/mail/layouts/plain.htm": {Data: []byte("name = \"Plain\"\ndisable_auto_inline_css = " + value + "\n==\n{{ .Content }}\n==\n<html><head><style>{{ .brandCss }}</style></head><body>{{ .Content }}</body></html>\n")},
|
||||
}
|
||||
cat := NewCatalog()
|
||||
if err := cat.Register("acme.shop", fsys, []string{"acme.shop::mail.plain"}, map[string]string{"plain": "acme.shop::mail.layouts.plain"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f, ok := cat.Layout("acme.shop::mail.layouts.plain"); !ok || !f.DisableAutoInlineCSS {
|
||||
t.Errorf("header value %q: LayoutFile = %+v", value, f)
|
||||
}
|
||||
drv := NewMemoryDriver()
|
||||
optedOut("file layout "+value, sendTemplate(t, NewMailer(cat, drv, Options{Overrides: fakeOverrides{ov: Overrides{Brand: brand}}}), drv, "acme.shop::mail.plain", nil))
|
||||
}
|
||||
if f, _ := NewCatalog().Layout(defaultLayoutName); f.DisableAutoInlineCSS {
|
||||
t.Error("the built-in default layout opts out")
|
||||
}
|
||||
|
||||
// A database layout with the column set opts out; without it, it inlines.
|
||||
def, _ := NewCatalog().Layout(defaultLayoutName)
|
||||
ov := &Overrides{Brand: brand, Layouts: map[string]LayoutOverride{defaultLayoutName: {HTML: def.HTML, Text: def.Text, DisableAutoInlineCSS: true}}}
|
||||
m, drv = partialsMailer(t, Options{}, ov)
|
||||
dbOptedOut := sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome)
|
||||
optedOut("database layout", dbOptedOut)
|
||||
if dbOptedOut.Text != inlined.Text {
|
||||
t.Errorf("the text part changed with the opt-out: %q, want %q", dbOptedOut.Text, inlined.Text)
|
||||
}
|
||||
ov.Layouts[defaultLayoutName] = LayoutOverride{HTML: def.HTML, Text: def.Text}
|
||||
m, drv = partialsMailer(t, Options{}, ov)
|
||||
if style := buttonStyle(t, sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome).HTML); !strings.Contains(style, "#445566") {
|
||||
t.Errorf("a database layout without the column did not inline: %q", style)
|
||||
}
|
||||
|
||||
// A layout draft with the flag previews the same way.
|
||||
ed, _ := newEditor(t, &Overrides{Brand: brand})
|
||||
draft := Draft{Kind: KindLayout, HTML: `<html><head><style>{{ .brandCss }}</style></head><body>{{ .Content }}</body></html>`, Text: "{{ .Content }}"}
|
||||
prev, err := ed.Preview(context.Background(), draft)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if style := buttonStyle(t, prev.HTML); !strings.Contains(style, "#445566") {
|
||||
t.Errorf("a layout draft without the flag did not inline: %q", style)
|
||||
}
|
||||
draft.DisableAutoInlineCSS = true
|
||||
if prev, err = ed.Preview(context.Background(), draft); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
optedOut("layout draft", RenderedMessage{HTML: prev.HTML})
|
||||
|
||||
// An inliner error sends the un-inlined HTML and warns once.
|
||||
m, drv = partialsMailer(t, Options{CSS: media}, &Overrides{Brand: brand})
|
||||
mm := m.(*mailer)
|
||||
var logs bytes.Buffer
|
||||
mm.log = slog.New(slog.NewTextHandler(&logs, nil))
|
||||
mm.inline = func(string) (string, error) { return "", errors.New("inliner broke") }
|
||||
failed := sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome)
|
||||
sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome)
|
||||
optedOut("inliner error", failed)
|
||||
if n := strings.Count(logs.String(), "level=WARN"); n != 1 || !strings.Contains(logs.String(), "inliner broke") {
|
||||
t.Errorf("log = %q, want one warning naming the error", logs.String())
|
||||
}
|
||||
if failed.Text != inlined.Text {
|
||||
t.Errorf("the text part changed with inlining: %q, want %q", failed.Text, inlined.Text)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("layout_partials", func(t *testing.T) {
|
||||
m, drv := partialsMailer(t, Options{}, nil)
|
||||
msg := sendTemplate(t, m, drv, "acme.blog::mail.note", map[string]any{"Text": "<b>hi</b>"})
|
||||
@@ -399,11 +528,13 @@ func TestMailPartialsSmoke(t *testing.T) {
|
||||
|
||||
t.Run("overrides", func(t *testing.T) {
|
||||
ov := Overrides{
|
||||
// A customized file layout, by its full name.
|
||||
// A customized file layout, by its full name. Both layouts keep
|
||||
// their style block (no inlining), so the order of the CSS slots
|
||||
// shows in it.
|
||||
Layouts: map[string]LayoutOverride{
|
||||
"acme.blog::mail.layouts.blog": {Name: "Blog", HTML: `<div class="custom-blog">{{ .Content }}</div><style>{{ .brandCss }}{{ .css }}</style>`, Text: "[custom] {{ .Content }}", CSS: ".custom{margin:0}"},
|
||||
"acme.blog::mail.layouts.blog": {Name: "Blog", HTML: `<div class="custom-blog">{{ .Content }}</div><style>{{ .brandCss }}{{ .css }}</style>`, Text: "[custom] {{ .Content }}", CSS: ".custom{margin:0}", DisableAutoInlineCSS: true},
|
||||
// A database-only layout, by its code.
|
||||
"promo": {Name: "Promo", HTML: `<div class="promo">{{ .Content }}{{ partial "acme.blog::mail.partials.note" "text" "promo" }}</div><style>{{ .css }}</style>`, Text: "PROMO {{ .Content }}", CSS: ".promo{margin:0}"},
|
||||
"promo": {Name: "Promo", HTML: `<div class="promo">{{ .Content }}{{ partial "acme.blog::mail.partials.note" "text" "promo" }}</div><style>{{ .css }}</style>`, Text: "PROMO {{ .Content }}", CSS: ".promo{margin:0}", DisableAutoInlineCSS: true},
|
||||
},
|
||||
Partials: map[string]PartialOverride{
|
||||
"acme.blog::mail.partials.note": {HTML: `<aside>{{ .text }}</aside>`, Text: "* {{ .text }}"},
|
||||
|
||||
@@ -166,6 +166,18 @@ var Migrations = []*gormigrate.Migration{
|
||||
return tx.Exec(`ALTER TABLE ` + BrandTable + ` DROP COLUMN IF EXISTS site_name`).Error
|
||||
},
|
||||
},
|
||||
{
|
||||
// disable_auto_inline_css keeps a layout's CSS in its style block
|
||||
// only (LayoutOverride.DisableAutoInlineCSS); file-backed rows that
|
||||
// are not customized mirror the file's header key.
|
||||
ID: "202611130003_mail_layout_disable_auto_inline_css",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`ALTER TABLE ` + LayoutsTable + ` ADD COLUMN disable_auto_inline_css BOOLEAN NOT NULL DEFAULT FALSE`).Error
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`ALTER TABLE ` + LayoutsTable + ` DROP COLUMN IF EXISTS disable_auto_inline_css`).Error
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// OverrideSource supplies the database overrides one render needs.
|
||||
@@ -218,6 +230,9 @@ type LayoutOverride struct {
|
||||
HTML string
|
||||
Text string
|
||||
CSS string
|
||||
// DisableAutoInlineCSS keeps the CSS in the style block only: it is not
|
||||
// copied onto the elements (the disable_auto_inline_css column).
|
||||
DisableAutoInlineCSS bool
|
||||
}
|
||||
|
||||
// PartialOverride replaces a partial's HTML and text sections.
|
||||
@@ -283,15 +298,16 @@ WHERE t.code = ? AND t.is_custom`, name).Scan(&rows).Error
|
||||
ContentHTML string `gorm:"column:content_html"`
|
||||
ContentText string `gorm:"column:content_text"`
|
||||
ContentCSS string `gorm:"column:content_css"`
|
||||
NoInline bool `gorm:"column:disable_auto_inline_css"`
|
||||
}
|
||||
if err := tx.Raw(`SELECT code, name, content_html, content_text, content_css FROM ` + LayoutsTable + ` WHERE is_custom`).Scan(&layouts).Error; err != nil {
|
||||
if err := tx.Raw(`SELECT code, name, content_html, content_text, content_css, disable_auto_inline_css FROM ` + LayoutsTable + ` WHERE is_custom`).Scan(&layouts).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, l := range layouts {
|
||||
if out.Layouts == nil {
|
||||
out.Layouts = make(map[string]LayoutOverride, len(layouts))
|
||||
}
|
||||
out.Layouts[l.Code] = LayoutOverride{Name: l.Name, HTML: l.ContentHTML, Text: l.ContentText, CSS: l.ContentCSS}
|
||||
out.Layouts[l.Code] = LayoutOverride{Name: l.Name, HTML: l.ContentHTML, Text: l.ContentText, CSS: l.ContentCSS, DisableAutoInlineCSS: l.NoInline}
|
||||
}
|
||||
var partials []struct {
|
||||
Code string
|
||||
@@ -386,11 +402,11 @@ const syncLockKey = "summercms.postcard.sync"
|
||||
// It runs layouts first, then templates (whose layout_id points at the
|
||||
// layout row of the file's layout), then partials.
|
||||
//
|
||||
// For a row that is not customized the content columns mirror the file. For
|
||||
// a customized row they are left alone: only source, description, locale,
|
||||
// base_code, name and file_hash follow the file, which is what makes a
|
||||
// changed file show as a difference between base_hash and file_hash. No row
|
||||
// is deleted, database-only layouts are not touched, and a row that already
|
||||
// For a row that is not customized the content columns (and a layout's
|
||||
// disable_auto_inline_css) mirror the file. For a customized row they are
|
||||
// left alone: only source, description, locale, base_code, name and
|
||||
// file_hash follow the file, which is what makes a changed file show as a
|
||||
// difference between base_hash and file_hash. No row is deleted, database-only layouts are not touched, and a row that already
|
||||
// matches is not written. locales are the application's locales, for
|
||||
// TemplateLocale and TemplateBase.
|
||||
//
|
||||
@@ -409,8 +425,8 @@ func SyncIndex(ctx context.Context, db *gorm.DB, cat *Catalog, locales []string)
|
||||
return err
|
||||
}
|
||||
for _, l := range layouts {
|
||||
if err := tx.Exec(`INSERT INTO `+LayoutsTable+` AS t (code, source, name, content_html, content_text, content_css, file_hash)
|
||||
VALUES (?, ?, ?, ?, ?, '', ?)
|
||||
if err := tx.Exec(`INSERT INTO `+LayoutsTable+` AS t (code, source, name, content_html, content_text, content_css, disable_auto_inline_css, file_hash)
|
||||
VALUES (?, ?, ?, ?, ?, '', ?, ?)
|
||||
ON CONFLICT (code) DO UPDATE SET
|
||||
source = EXCLUDED.source,
|
||||
name = EXCLUDED.name,
|
||||
@@ -418,13 +434,14 @@ ON CONFLICT (code) DO UPDATE SET
|
||||
content_html = CASE WHEN t.is_custom THEN t.content_html ELSE EXCLUDED.content_html END,
|
||||
content_text = CASE WHEN t.is_custom THEN t.content_text ELSE EXCLUDED.content_text END,
|
||||
content_css = CASE WHEN t.is_custom THEN t.content_css ELSE EXCLUDED.content_css END,
|
||||
disable_auto_inline_css = CASE WHEN t.is_custom THEN t.disable_auto_inline_css ELSE EXCLUDED.disable_auto_inline_css END,
|
||||
updated_at = NOW()
|
||||
WHERE t.source IS DISTINCT FROM EXCLUDED.source
|
||||
OR t.name IS DISTINCT FROM EXCLUDED.name
|
||||
OR t.file_hash IS DISTINCT FROM EXCLUDED.file_hash
|
||||
OR (NOT t.is_custom AND (t.content_html, t.content_text, t.content_css)
|
||||
IS DISTINCT FROM (EXCLUDED.content_html, EXCLUDED.content_text, EXCLUDED.content_css))`,
|
||||
l.Name, l.PluginID, rowName(l.Title, l.Name), l.HTML, l.Text, l.Hash).Error; err != nil {
|
||||
OR (NOT t.is_custom AND (t.content_html, t.content_text, t.content_css, t.disable_auto_inline_css)
|
||||
IS DISTINCT FROM (EXCLUDED.content_html, EXCLUDED.content_text, EXCLUDED.content_css, EXCLUDED.disable_auto_inline_css))`,
|
||||
l.Name, l.PluginID, rowName(l.Title, l.Name), l.HTML, l.Text, l.DisableAutoInlineCSS, l.Hash).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -607,8 +624,8 @@ WHERE code = ? AND source IS NOT NULL`, f.Subject, f.Body, f.Layout, f.Hash, cod
|
||||
return fmt.Errorf("postcard: reset %s: no file version", code)
|
||||
}
|
||||
res = db.Exec(`UPDATE `+LayoutsTable+` SET name = ?, content_html = ?, content_text = ?, content_css = '',
|
||||
file_hash = ?, is_custom = FALSE, base_hash = NULL, customized_at = NULL, updated_at = NOW()
|
||||
WHERE code = ? AND source IS NOT NULL`, rowName(f.Title, f.Name), f.HTML, f.Text, f.Hash, code)
|
||||
disable_auto_inline_css = ?, file_hash = ?, is_custom = FALSE, base_hash = NULL, customized_at = NULL, updated_at = NOW()
|
||||
WHERE code = ? AND source IS NOT NULL`, rowName(f.Title, f.Name), f.HTML, f.Text, f.DisableAutoInlineCSS, f.Hash, code)
|
||||
case KindPartial:
|
||||
f, ok := cat.Partial(code)
|
||||
if !ok {
|
||||
|
||||
@@ -86,6 +86,8 @@ type parsedLayout struct {
|
||||
htmlWrap string
|
||||
source string
|
||||
hash string
|
||||
// disableInline is the disable_auto_inline_css header key.
|
||||
disableInline bool
|
||||
}
|
||||
|
||||
// parsedPartial is a partial file: the layout file format, a header, a text
|
||||
@@ -387,16 +389,31 @@ func parseLayout(name, pluginID, src string) (*parsedLayout, error) {
|
||||
return nil, fmt.Errorf("postcard: parse %s: %w", name, err)
|
||||
}
|
||||
return &parsedLayout{
|
||||
name: name,
|
||||
pluginID: pluginID,
|
||||
headerName: fields["name"],
|
||||
textWrap: strings.TrimSuffix(textWrap, "\n"),
|
||||
htmlWrap: strings.TrimSuffix(htmlWrap, "\n"),
|
||||
source: src,
|
||||
hash: fileHash(src),
|
||||
name: name,
|
||||
pluginID: pluginID,
|
||||
headerName: fields["name"],
|
||||
textWrap: strings.TrimSuffix(textWrap, "\n"),
|
||||
htmlWrap: strings.TrimSuffix(htmlWrap, "\n"),
|
||||
source: src,
|
||||
hash: fileHash(src),
|
||||
disableInline: headerBool(fields[disableInlineKey]),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// disableInlineKey is the layout header key (and the layouts table column)
|
||||
// that keeps a layout's CSS in its style block only, WinterCMS's option of
|
||||
// the same name.
|
||||
const disableInlineKey = "disable_auto_inline_css"
|
||||
|
||||
// headerBool reads a header value as a switch: true, 1 or yes, in any case.
|
||||
func headerBool(v string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(v)) {
|
||||
case "true", "1", "yes":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func normalizeNewlines(src string) string {
|
||||
return strings.ReplaceAll(src, "\r\n", "\n")
|
||||
}
|
||||
@@ -506,6 +523,8 @@ type renderOptions struct {
|
||||
siteName string
|
||||
// year is the year of the copyright line; zero is the current year.
|
||||
year int
|
||||
// inline copies the CSS onto the elements; nil is inlineCSS.
|
||||
inline func(html string) (string, error)
|
||||
// overrides are the database overrides to apply; the zero value renders
|
||||
// the file version.
|
||||
overrides Overrides
|
||||
@@ -682,6 +701,12 @@ func (c *Catalog) renderParts(msg Message, src renderSource, opts renderOptions)
|
||||
if err := validateHTML(html); err != nil {
|
||||
return out, partLayoutHTML, err
|
||||
}
|
||||
if !layout.disableInline {
|
||||
html, err = inlineHTML(html, layout.name, opts)
|
||||
if err != nil {
|
||||
return out, partLayoutHTML, err
|
||||
}
|
||||
}
|
||||
out = RenderedMessage{
|
||||
To: append([]string(nil), msg.To...),
|
||||
Cc: append([]string(nil), msg.Cc...),
|
||||
@@ -694,6 +719,37 @@ func (c *Catalog) renderParts(msg Message, src renderSource, opts renderOptions)
|
||||
return out, "", nil
|
||||
}
|
||||
|
||||
// styleElement finds a style element, the only place inlining reads CSS from.
|
||||
var styleElement = regexp.MustCompile(`(?i)<style[\s>]`)
|
||||
|
||||
// inlineHTML copies the CSS of a rendered message onto its elements. HTML
|
||||
// without a style element has nothing to inline and is returned as it is.
|
||||
// An inliner error keeps html as it is, with its style block, and is
|
||||
// reported through opts.warn; mail is never stopped by it. The inlined HTML
|
||||
// passes the safety checks again, since CSS values now sit in style
|
||||
// attributes.
|
||||
func inlineHTML(html, layout string, opts renderOptions) (string, error) {
|
||||
if !styleElement.MatchString(html) {
|
||||
return html, nil
|
||||
}
|
||||
inline := opts.inline
|
||||
if inline == nil {
|
||||
inline = inlineCSS
|
||||
}
|
||||
inlined, err := inline(html)
|
||||
if err != nil {
|
||||
if opts.warn != nil {
|
||||
opts.warn("inline:"+layout, "postcard: CSS could not be inlined, sending the style block only",
|
||||
"layout", layout, "error", err.Error())
|
||||
}
|
||||
return html, nil
|
||||
}
|
||||
if err := validateHTML(inlined); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return inlined, nil
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -701,6 +757,8 @@ type renderLayout struct {
|
||||
textWrap string
|
||||
htmlWrap string
|
||||
css string
|
||||
// disableInline keeps the CSS in the style block only.
|
||||
disableInline bool
|
||||
}
|
||||
|
||||
// layoutFor returns the layout src renders in. An override of that layout,
|
||||
@@ -733,7 +791,7 @@ func (c *Catalog) layoutFor(src renderSource, opts renderOptions) (renderLayout,
|
||||
|
||||
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
|
||||
return renderLayout{name: code, textWrap: ov.Text, htmlWrap: ov.HTML, css: ov.CSS, disableInline: ov.DisableAutoInlineCSS}, true, nil
|
||||
}
|
||||
c.mu.RLock()
|
||||
l, ok := c.layouts[code]
|
||||
@@ -741,7 +799,7 @@ func (c *Catalog) layoutByCode(code string, overrides map[string]LayoutOverride)
|
||||
if !ok {
|
||||
return renderLayout{}, false, nil
|
||||
}
|
||||
return renderLayout{name: l.name, textWrap: l.textWrap, htmlWrap: l.htmlWrap}, true, nil
|
||||
return renderLayout{name: l.name, textWrap: l.textWrap, htmlWrap: l.htmlWrap, disableInline: l.disableInline}, true, nil
|
||||
}
|
||||
|
||||
func markdownHTML(src string) (string, error) {
|
||||
@@ -830,6 +888,9 @@ type LayoutFile struct {
|
||||
HTML string
|
||||
Source string
|
||||
Hash string
|
||||
// DisableAutoInlineCSS is the file's disable_auto_inline_css header
|
||||
// key: the layout keeps its CSS in the style block only.
|
||||
DisableAutoInlineCSS bool
|
||||
}
|
||||
|
||||
// PartialFile is a registered partial as its plugin (or postcard) ships it.
|
||||
@@ -860,7 +921,7 @@ func (t *parsedTemplate) file() TemplateFile {
|
||||
}
|
||||
|
||||
func (l *parsedLayout) file() LayoutFile {
|
||||
return LayoutFile{Name: l.name, PluginID: l.pluginID, Title: l.headerName, Text: l.textWrap, HTML: l.htmlWrap, Source: l.source, Hash: l.hash}
|
||||
return LayoutFile{Name: l.name, PluginID: l.pluginID, Title: l.headerName, Text: l.textWrap, HTML: l.htmlWrap, Source: l.source, Hash: l.hash, DisableAutoInlineCSS: l.disableInline}
|
||||
}
|
||||
|
||||
func (p *parsedPartial) file() PartialFile {
|
||||
|
||||
Reference in New Issue
Block a user