feat(postcard): finished default layout with logo header, footer and site name
- default.htm ports WinterCMS's default layout: wrapper, header row with the Branding logo (or the site name), the inner-body card and a copyright footer; its text wrapper ends with the footer - built-in header and footer partials (logo/body/url, body) - layouts get siteName (Branding site name, else the display name of mail.from) and year; Brand.SiteName and migration 202611130002_mail_brand_site_name - cabana Branding form gets site_name (trimmed, max 255), mapped into the Branding preview draft; en/pl copy; img.logo brand CSS - 35-06 Task 1 (G-35-8)
This commit is contained in:
@@ -46,6 +46,8 @@ A bare name is one of the built-in partials; a plugin's partial is called by its
|
||||
| `panel` | `body` | A highlighted block; the body is Markdown. |
|
||||
| `table` | `body` | A Markdown table. |
|
||||
| `subcopy` | `body` | Small print under a rule; the body is Markdown. |
|
||||
| `header` | `logo` (an image URL), `body` (a name), `url` (optional link) | A table row for a layout's header: the logo, with the name as its alternative text, or the name when there is no logo. |
|
||||
| `footer` | `body` | A table row for a layout's footer; the body is Markdown. |
|
||||
|
||||
In a body, write the call on a line of its own with blank lines around it. Bodies are Markdown and raw HTML in them is still dropped; postcard inserts a partial's HTML after the Markdown conversion, through a random token that a variable's value cannot contain. Inside a partial's HTML section, `{{ markdown .body }}` renders a value as Markdown.
|
||||
|
||||
@@ -55,12 +57,14 @@ Three layouts are available to every plugin's templates without declaring an ali
|
||||
|
||||
| `layout` | Renders |
|
||||
|----------|---------|
|
||||
| `default` | The message in a plain page. Used when the template names no layout. |
|
||||
| `default` | WinterCMS's default layout: a header with the Branding logo (or the site name when no logo is set), the message on a white card, and a footer with the copyright year and the site name. Used when the template names no layout. |
|
||||
| `system` | WinterCMS's system layout: the message in a centred table, then a note that it was sent automatically. |
|
||||
| `minimal` | The message directly in the page body, with the style block only. |
|
||||
|
||||
A plugin's own alias wins over `system` and `minimal`; `default` cannot be redefined.
|
||||
|
||||
Every layout gets these values besides `{{ .Content }}`: `{{ .Subject }}`, the CSS slots `{{ .brandCss }}` and `{{ .css }}`, `{{ .logoUrl }}` (see [Branding](#branding)), `{{ .siteName }}`, the site name, and `{{ .year }}`, the current year. The default layout uses the `header` and `footer` partials with them; the footer reads `© <year> <site name>`, or `© <year>` when there is no name, and the header row is left out when there is neither a logo nor a name.
|
||||
|
||||
## Branding
|
||||
|
||||
A layout's style block has a brand slot, `{{ .brandCss }}`, before `{{ .css }}`. Until the branding settings are saved for the first time, the brand slot holds `mail.brandCss` from the configuration. From the first save on, it holds CSS that postcard compiles from the saved colours, and `mail.brandCss` is no longer used. `mail.css` is applied either way.
|
||||
@@ -73,6 +77,8 @@ The settings also hold a logo. A layout shows it where it uses `{{ .logoUrl }}`:
|
||||
{{ if .logoUrl }}<img src="{{ .logoUrl }}" alt="">{{ end }}
|
||||
```
|
||||
|
||||
The settings also hold a site name, given to layouts as `{{ .siteName }}`. The built-in layouts show it in the header (as the logo's alternative text when there is a logo) and in the footer. Left empty, the display name of `mail.from` is used (`Acme` for `Acme <no-reply@acme.test>`), so mail from an application that never saved Branding still carries a name.
|
||||
|
||||
A mail client needs an absolute address, so the logo's URL is built at send time from the configuration: `storage.uploads.public_url` when it is set, otherwise `app.url` with `storage.uploads.public_path_prefix`; see [Absolute URLs for mail](storage.md#absolute-urls-for-mail). Set one of them, or the logo is left out and a warning is logged.
|
||||
|
||||
## Sample values for previews
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -4,6 +4,11 @@ fields:
|
||||
comment: backend::lang.mail.brand.logo_comment
|
||||
type: mailimage
|
||||
span: full
|
||||
site_name:
|
||||
label: backend::lang.mail.brand.site_name
|
||||
comment: backend::lang.mail.brand.site_name_comment
|
||||
type: text
|
||||
span: left
|
||||
body_bg:
|
||||
label: backend::lang.mail.brand.body_bg
|
||||
type: colorpicker
|
||||
|
||||
@@ -1745,6 +1745,7 @@ func partialUsage(code, sections string) string {
|
||||
type MailBrandSetting struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
LogoFileID *uint `gorm:"column:logo_file_id"`
|
||||
SiteName string `gorm:"column:site_name"`
|
||||
BodyBg string `gorm:"column:body_bg"`
|
||||
ContentBg string `gorm:"column:content_bg"`
|
||||
HeaderColor string `gorm:"column:header_color"`
|
||||
@@ -1766,7 +1767,7 @@ func (MailBrandSetting) TableName() string { return postcard.BrandTable }
|
||||
|
||||
func (MailBrandSetting) Fillable() []string {
|
||||
return []string{
|
||||
"logo_file_id", "body_bg", "content_bg", "header_color", "footer_color",
|
||||
"logo_file_id", "site_name", "body_bg", "content_bg", "header_color", "footer_color",
|
||||
"heading_color", "text_color", "link_color", "button_text_color",
|
||||
"button_primary_bg", "button_positive_bg", "button_negative_bg",
|
||||
"panel_bg", "table_border_color",
|
||||
@@ -1776,6 +1777,7 @@ func (MailBrandSetting) Fillable() []string {
|
||||
func (MailBrandSetting) Rules() map[string]string {
|
||||
return map[string]string{
|
||||
"logo_file_id": "nullable",
|
||||
"site_name": "nullable|max:255",
|
||||
"body_bg": "nullable",
|
||||
"content_bg": "nullable",
|
||||
"header_color": "nullable",
|
||||
@@ -1794,9 +1796,10 @@ func (MailBrandSetting) Rules() map[string]string {
|
||||
|
||||
var brandColourPattern = regexp.MustCompile(`^#[0-9a-f]{6}$`)
|
||||
|
||||
// BeforeValidate lower-cases colours, refuses anything but #rrggbb or empty,
|
||||
// and checks logo_file_id is null or a library image.
|
||||
// BeforeValidate trims the site name, lower-cases colours, refuses anything
|
||||
// but #rrggbb or empty, and checks logo_file_id is null or a library image.
|
||||
func (b *MailBrandSetting) BeforeValidate(tx *gorm.DB) error {
|
||||
b.SiteName = strings.TrimSpace(b.SiteName)
|
||||
details := map[string]any{}
|
||||
for _, col := range []struct {
|
||||
name string
|
||||
|
||||
@@ -587,6 +587,7 @@ func (s *service) mailBrandDraft(ctx context.Context, values map[string]any) (po
|
||||
ButtonNegativeBg: stringValue(values["button_negative_bg"]),
|
||||
PanelBg: stringValue(values["panel_bg"]),
|
||||
TableBorderColor: stringValue(values["table_border_color"]),
|
||||
SiteName: strings.TrimSpace(stringValue(values["site_name"])),
|
||||
}
|
||||
if raw, ok := values["logo_file_id"]; ok && raw != nil {
|
||||
id, err := asUint(raw)
|
||||
|
||||
@@ -908,6 +908,24 @@ Hi **{{ .name }}**, thanks for joining the Acme blog.
|
||||
t.Fatalf("stored colour = %#v", row["button_primary_bg"])
|
||||
}
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, "/settings/mail_brand", rootToken, map[string]any{"logo_file_id": 999999})
|
||||
|
||||
// The site name is saved trimmed and is shown in the default
|
||||
// layout's header and footer by the Branding preview.
|
||||
saved = env.expect(t, http.StatusOK, http.MethodPut, "/settings/mail_brand", rootToken, map[string]any{"button_primary_bg": "#d66829", "site_name": " Acme Mail "})
|
||||
if name := saved["data"].(map[string]any)["data"].(map[string]any)["site_name"]; name != "Acme Mail" {
|
||||
t.Fatalf("stored site_name = %#v", name)
|
||||
}
|
||||
var stored cabana.MailBrandSetting
|
||||
if err := env.gdb.First(&stored, 1).Error; err != nil || stored.SiteName != "Acme Mail" {
|
||||
t.Fatalf("brand row = %+v err=%v", stored, err)
|
||||
}
|
||||
env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, "/settings/mail_brand", rootToken, map[string]any{"site_name": strings.Repeat("x", 256)})
|
||||
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>") {
|
||||
t.Fatalf("branding preview lacks the site name: %s", html)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("images", func(t *testing.T) {
|
||||
|
||||
@@ -698,7 +698,9 @@ mail:
|
||||
menu_label: "Mail branding"
|
||||
menu_description: "Set the colours and logo used by every message."
|
||||
logo: "Logo"
|
||||
logo_comment: "Layouts show the logo where they use {{ .logoUrl }}."
|
||||
logo_comment: "The built-in layouts show the logo in their header. Your own layouts show it where they use {{ .logoUrl }}."
|
||||
site_name: "Site name"
|
||||
site_name_comment: "Shown in the header and footer of the built-in layouts. Leave it empty to use the sender name from mail.from."
|
||||
body_bg: "Body background"
|
||||
content_bg: "Content background"
|
||||
header_color: "Header colour"
|
||||
|
||||
@@ -736,7 +736,9 @@ mail:
|
||||
menu_label: "Wygląd wiadomości"
|
||||
menu_description: "Ustaw kolory i logo używane we wszystkich wiadomościach."
|
||||
logo: "Logo"
|
||||
logo_comment: "Układy pokazują logo tam, gdzie używają {{ .logoUrl }}."
|
||||
logo_comment: "Wbudowane układy pokazują logo w nagłówku. Własne układy pokazują je tam, gdzie używają {{ .logoUrl }}."
|
||||
site_name: "Nazwa witryny"
|
||||
site_name_comment: "Wyświetlana w nagłówku i stopce wbudowanych układów. Zostaw puste, aby użyć nazwy nadawcy z mail.from."
|
||||
body_bg: "Główne tło"
|
||||
content_bg: "Tło treści"
|
||||
header_color: "Kolor górnego nagłówka"
|
||||
|
||||
@@ -30,7 +30,7 @@ Use cases:
|
||||
- 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.
|
||||
- Branding: once the branding settings have been saved, the brand CSS is compiled from their colours (`postcard.CompileBrandCSS`) and replaces `mail.brandCss`, and layouts get the logo's absolute URL as `{{ .logoUrl }}`.
|
||||
- Branding: once the branding settings have been saved, the brand CSS is compiled from their colours (`postcard.CompileBrandCSS`) and replaces `mail.brandCss`, and layouts get the logo's absolute URL as `{{ .logoUrl }}` and the site name as `{{ .siteName }}` (else the display name of `mail.from`). The built-in default layout shows them in a header and a copyright footer.
|
||||
- Sample values: a template's header may give its variables sample values with `sample.<path>` keys. Previews and save checks use them, and show every other variable as a visible `[path]` placeholder.
|
||||
- An editor API for admin code (`postcard.Editor`): validate, preview and test-send an unsaved draft of a template, layout or partial through the same render path as a real send; one index row per file (`postcard.SyncIndex`) with a hash of the file for detecting that it changed under an override, and reset to the file version (`postcard.ResetOverride`).
|
||||
- No locale selection: callers pass the full template name, including any locale suffix. A `<template>-<locale>` name whose locale ships no file sends the default-locale version (see "Locale variants").
|
||||
@@ -175,18 +175,22 @@ Markdown drops raw HTML, so a call in a body does not insert the partial's HTML
|
||||
|
||||
| Layout alias | Full name | Renders |
|
||||
|--------------|-----------|---------|
|
||||
| `default` | `postcard::mail.layouts.default` | The message in a `content-body` block. Used when a template names no layout. |
|
||||
| `default` | `postcard::mail.layouts.default` | WinterCMS's default layout (`wrapper layout-default`): the `header` partial with the logo or the site name, the message in the `inner-body` card, and the `footer` partial with `© <year> <site name>`. Used when a template names no layout. |
|
||||
| `system` | `postcard::mail.layouts.system` | WinterCMS's system layout: the message in a centred table, followed by a note that the message is automatic. |
|
||||
| `minimal` | `postcard::mail.layouts.minimal` | The message directly in the page body. |
|
||||
|
||||
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.
|
||||
|
||||
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 |
|
||||
|---------|-----------|---------|
|
||||
| `button` | `url`, `body`, `type` (`primary` by default, `positive` or `negative`) | A link styled as a button (`button button-<type>`); in text, the label and the address. |
|
||||
| `panel` | `body` (Markdown) | A highlighted block (`panel`). |
|
||||
| `table` | `body` (a Markdown table) | A table in a `table` block. |
|
||||
| `subcopy` | `body` (Markdown) | Small print under a rule (`subcopy`). |
|
||||
| `header` | `logo` (an image URL), `body` (a name), `url` (optional) | A layout's header row (`td.header`): `img.logo` with `body` as its alternative text when `logo` is set, else `body` in a `span`; wrapped in a link when `url` is set. In text, the name. |
|
||||
| `footer` | `body` (Markdown) | A layout's footer row (`table.footer`). In text, a rule line and the body. |
|
||||
|
||||
### Overrides from the admin
|
||||
|
||||
@@ -240,7 +244,7 @@ func newTestMailer(cat *postcard.Catalog, driver postcard.Driver) postcard.Maile
|
||||
|
||||
### Branding
|
||||
|
||||
Layouts have two CSS slots, `{{ .brandCss }}` and `{{ .css }}`, and a logo slot, `{{ .logoUrl }}`. What fills the brand slot depends on the row with `id` 1 of `system_mail_brand_settings`:
|
||||
Layouts have two CSS slots, `{{ .brandCss }}` and `{{ .css }}`, a logo slot, `{{ .logoUrl }}`, and a name slot, `{{ .siteName }}`. What fills the brand slot depends on the row with `id` 1 of `system_mail_brand_settings`:
|
||||
|
||||
- While the row does not exist, the slot holds `mail.brandCss` from the configuration and `{{ .logoUrl }}` is empty, so an application that never saves Branding is unchanged.
|
||||
- Once the row exists, the slot holds `postcard.CompileBrandCSS` of the row's colours, and `mail.brandCss` is no longer used. An empty colour column is that colour's default (`postcard.DefaultBrand`).
|
||||
@@ -271,6 +275,8 @@ The row's `logo_file_id` names a public `system_files` row. Its URL is not store
|
||||
{{ if .logoUrl }}<img src="{{ .logoUrl }}" alt="">{{ end }}
|
||||
```
|
||||
|
||||
The row's `site_name` column is `postcard.Brand.SiteName`. The built-in layouts show it in their header (as the logo's alternative text when there is a logo) and footer. While it is empty, and while no Branding row exists, `{{ .siteName }}` is the display name of `mail.from` parsed with `net/mail` (`Acme` for `Acme <no-reply@acme.test>`), or empty when the address has none. The name is HTML-escaped by `html/template` wherever a layout prints it.
|
||||
|
||||
A mail that falls back to its file version because an override failed still gets the Branding.
|
||||
|
||||
### Sample values
|
||||
@@ -391,7 +397,7 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
|
||||
| `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.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 and `postcard.Brand.LogoURL`, the logo's absolute URL. |
|
||||
| `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. |
|
||||
| `postcard.DefaultBrand` | WinterCMS's default mail colours. |
|
||||
| `postcard.CompileBrandCSS` | Checks a brand's colours and returns the brand CSS compiled from them. |
|
||||
| `postcard.Migrations` | The gormigrate set that creates the mail tables; lagoon runs it under the `summercms.postcard` history. |
|
||||
@@ -423,7 +429,7 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
|
||||
| Key | Default | Controls |
|
||||
|-----|---------|----------|
|
||||
| `mail.driver` | `memory` | Delivery driver: `memory`, `log` or `smtp`. Any other value fails at boot. |
|
||||
| `mail.from` | empty | Sender address. Required by the SMTP driver. |
|
||||
| `mail.from` | empty | Sender address. Required by the SMTP driver. Its display name is the layouts' `{{ .siteName }}` while the Branding has no site name. |
|
||||
| `mail.css` | empty | CSS placed in the layout's style block, after the brand CSS. Always applied. |
|
||||
| `mail.brandCss` | empty | Brand CSS placed before `mail.css`. Used only until the branding settings are saved; from then on the CSS compiled from their colours replaces it (see [Branding](#branding)). |
|
||||
| `mail.smtp.host` | none | SMTP host. Required when `mail.driver` is `smtp`. |
|
||||
|
||||
@@ -90,6 +90,14 @@ img {
|
||||
font-weight: bold;
|
||||
text-decoration: none;
|
||||
}
|
||||
img.logo {
|
||||
border: 0;
|
||||
display: inline-block;
|
||||
height: auto;
|
||||
max-height: 60px;
|
||||
max-width: 200px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
/* Body */
|
||||
.body {
|
||||
background-color: {{ .ContentBg }};
|
||||
|
||||
@@ -1,14 +1,37 @@
|
||||
name = "Default"
|
||||
==
|
||||
{{ .Content }}
|
||||
|
||||
{{ $copy := printf "© %v" .year }}{{ with .siteName }}{{ $copy = printf "%s %s" $copy . }}{{ end }}{{ partial "footer" "body" $copy }}
|
||||
==
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
<style type="text/css">{{ .brandCss }}{{ .css }}</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="content-body">{{ .Content }}</div>
|
||||
<table class="wrapper layout-default" width="100%" cellpadding="0" cellspacing="0">
|
||||
{{ if or .logoUrl .siteName }}{{ partial "header" "logo" .logoUrl "body" .siteName }}{{ end }}
|
||||
<tr>
|
||||
<td align="center">
|
||||
<table class="content" width="100%" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td class="body" width="100%" cellpadding="0" cellspacing="0">
|
||||
<table class="inner-body" align="center" width="570" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td class="content-cell">
|
||||
{{ .Content }}
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
{{ $copy := printf "© %v" .year }}{{ with .siteName }}{{ $copy = printf "%s %s" $copy . }}{{ end }}{{ partial "footer" "body" $copy }}
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
16
modules/postcard/assets/partials/footer.htm
Normal file
16
modules/postcard/assets/partials/footer.htm
Normal file
@@ -0,0 +1,16 @@
|
||||
name = "Footer"
|
||||
==
|
||||
-------------------
|
||||
{{ .body }}
|
||||
==
|
||||
<tr>
|
||||
<td>
|
||||
<table class="footer" align="center" width="570" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td class="content-cell" align="center">
|
||||
{{ markdown .body }}
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
9
modules/postcard/assets/partials/header.htm
Normal file
9
modules/postcard/assets/partials/header.htm
Normal file
@@ -0,0 +1,9 @@
|
||||
name = "Header"
|
||||
==
|
||||
{{ .body }}
|
||||
==
|
||||
<tr>
|
||||
<td class="header">
|
||||
{{ if .url }}<a href="{{ .url }}">{{ if .logo }}<img src="{{ .logo }}" class="logo" alt="{{ .body }}" />{{ else }}{{ .body }}{{ end }}</a>{{ else if .logo }}<img src="{{ .logo }}" class="logo" alt="{{ .body }}" />{{ else }}<span>{{ .body }}</span>{{ end }}
|
||||
</td>
|
||||
</tr>
|
||||
@@ -29,6 +29,11 @@ type Brand struct {
|
||||
// LogoURL is the absolute URL of the logo, given to layouts as
|
||||
// {{ .logoUrl }}. It is not part of the CSS.
|
||||
LogoURL string
|
||||
// SiteName is the name the built-in layouts show in their header (when
|
||||
// there is no logo, and as the logo's alternative text) and footer,
|
||||
// given to layouts as {{ .siteName }}. Empty uses the display name of
|
||||
// mail.from. It is not part of the CSS.
|
||||
SiteName string
|
||||
}
|
||||
|
||||
// DefaultBrand returns WinterCMS's default mail colours.
|
||||
|
||||
@@ -191,7 +191,7 @@ func TestMailBrandSmoke(t *testing.T) {
|
||||
if strings.Contains(css, ".cfg{color:blue}") || !strings.HasSuffix(css, "p{margin:1px}") {
|
||||
t.Errorf("the draft CSS must replace mail.brandCss and leave mail.css after it:\n%s", css)
|
||||
}
|
||||
for _, want := range []string{`<div class="content-body"><h1>`, `class="button button-primary"`, `<table class="panel`} {
|
||||
for _, want := range []string{"<td class=\"content-cell\">\n<h1>", `class="button button-primary"`, `<table class="panel`} {
|
||||
if !strings.Contains(got.HTML, want) {
|
||||
t.Errorf("brand preview lacks %q:\n%s", want, got.HTML)
|
||||
}
|
||||
@@ -248,6 +248,84 @@ func TestMailBrandSmoke(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("default_layout", func(t *testing.T) {
|
||||
send := func(from string, brand *Brand) RenderedMessage {
|
||||
t.Helper()
|
||||
var ov *Overrides
|
||||
if brand != nil {
|
||||
ov = &Overrides{Brand: brand}
|
||||
}
|
||||
m, drv := partialsMailer(t, Options{From: from}, ov)
|
||||
return sendTemplate(t, m, drv, "acme.blog::mail.welcome", map[string]any{"Name": "Ada", "Link": "https://example.com/go"})
|
||||
}
|
||||
const logo = "https://cdn.example.com/u/logo.png"
|
||||
|
||||
// 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 "})
|
||||
for _, want := range []string{
|
||||
`class="wrapper layout-default"`,
|
||||
"<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"`,
|
||||
`<table class="footer"`,
|
||||
"<p>" + copyright() + " Acme Mail</p>",
|
||||
} {
|
||||
if !strings.Contains(got.HTML, want) {
|
||||
t.Errorf("logo and name: HTML lacks %q:\n%s", want, got.HTML)
|
||||
}
|
||||
}
|
||||
if strings.Contains(got.HTML, "<span>Acme Mail</span>") {
|
||||
t.Errorf("logo and name: the header shows the name next to the logo:\n%s", got.HTML)
|
||||
}
|
||||
if !strings.HasSuffix(got.Text, "Bye\n\n-------------------\n"+copyright()+" Acme Mail") {
|
||||
t.Errorf("logo and name: text = %q", got.Text)
|
||||
}
|
||||
|
||||
// A site name without a logo: the name in the header.
|
||||
got = send("blog@example.com", &Brand{SiteName: "Acme Mail"})
|
||||
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>`})
|
||||
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)
|
||||
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: " "})
|
||||
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)
|
||||
if strings.Contains(got.HTML, `class="header"`) || !strings.Contains(got.HTML, "<p>"+copyright()+"</p>") {
|
||||
t.Errorf("no name, no logo: HTML = %s", got.HTML)
|
||||
}
|
||||
if !strings.HasSuffix(got.Text, "\n-------------------\n"+copyright()) {
|
||||
t.Errorf("no name, no logo: text = %q", got.Text)
|
||||
}
|
||||
|
||||
// The Branding preview shows the draft's name.
|
||||
ed, _ := newEditor(t, nil)
|
||||
prev, err := ed.Preview(ctx, Draft{Kind: KindBrand, Brand: &Brand{SiteName: "Draft Name", LogoURL: logo}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(prev.HTML, `alt="Draft Name"`) || !strings.Contains(prev.HTML, copyright()+" Draft Name") {
|
||||
t.Errorf("brand preview with a site name:\n%s", prev.HTML)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("precedence", func(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"})
|
||||
@@ -308,8 +386,11 @@ func TestMailBrandSmoke(t *testing.T) {
|
||||
}
|
||||
|
||||
// The source reports the row as it is, without a template name too.
|
||||
if err := gdb.Exec(`UPDATE ` + BrandTable + ` SET site_name = 'Acme Mail' WHERE id = 1`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ov, err := NewDBSource(appWith(t, gdb)).MailOverrides(ctx, "")
|
||||
if err != nil || ov.Brand == nil || ov.Brand.LinkColor != "#112233" || ov.Brand.PanelBg != "red" || ov.Brand.LogoURL != "" {
|
||||
if err != nil || ov.Brand == nil || ov.Brand.LinkColor != "#112233" || ov.Brand.PanelBg != "red" || ov.Brand.LogoURL != "" || ov.Brand.SiteName != "Acme Mail" {
|
||||
t.Errorf("Brand from the source = %+v, %v", ov.Brand, err)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -310,7 +310,7 @@ func (e *Editor) renderPartial(d Draft, ov Overrides, opts renderOptions) (Rende
|
||||
}
|
||||
|
||||
// renderBrand renders the sample message in the default layout with the
|
||||
// draft's colours and logo in place of the saved Branding.
|
||||
// draft's colours, logo and site name in place of the saved Branding.
|
||||
func (e *Editor) renderBrand(d Draft, ov Overrides, opts renderOptions) (RenderedMessage, error) {
|
||||
brand := DefaultBrand()
|
||||
if d.Brand != nil {
|
||||
@@ -321,6 +321,7 @@ func (e *Editor) renderBrand(d Draft, ov Overrides, opts renderOptions) (Rendere
|
||||
return RenderedMessage{}, err
|
||||
}
|
||||
opts.brandCSS, opts.logoURL = css, brand.LogoURL
|
||||
opts.siteName = siteName(&brand, e.m.opts.From)
|
||||
opts.overrides = ov
|
||||
sample := sampleMessage()
|
||||
return e.m.catalog.renderFrom(Message{
|
||||
|
||||
@@ -406,7 +406,7 @@ func TestMailEditorSmoke(t *testing.T) {
|
||||
}
|
||||
|
||||
templates, layouts, partials := lf.Templates(), lf.Layouts(), lf.Partials()
|
||||
if len(templates) != 2 || len(layouts) != 4 || len(partials) != 5 {
|
||||
if len(templates) != 2 || len(layouts) != 4 || len(partials) != 7 {
|
||||
t.Fatalf("catalog holds %d templates, %d layouts, %d partials", len(templates), len(layouts), len(partials))
|
||||
}
|
||||
if templates[0].Name != editorWelcome || templates[1].Name != "acme.blog::mail.welcome-en" || layouts[0].Name != editorBlogLayout || partials[0].Name != editorNote {
|
||||
@@ -541,7 +541,7 @@ func TestMailEditorSmoke(t *testing.T) {
|
||||
return out
|
||||
}
|
||||
templates, layouts, partials := rows(TemplatesTable), rows(LayoutsTable), rows(PartialsTable)
|
||||
if len(templates) != 2 || len(layouts) != 4 || len(partials) != 5 {
|
||||
if len(templates) != 2 || len(layouts) != 4 || len(partials) != 7 {
|
||||
t.Fatalf("index holds %d templates, %d layouts, %d partials", len(templates), len(layouts), len(partials))
|
||||
}
|
||||
file, _ := cat.Template(editorWelcome)
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
netmail "net/mail"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -145,9 +146,10 @@ func (m *mailer) render(ctx context.Context, msg Message) (RenderedMessage, erro
|
||||
// options returns the render options of the file version: mail.css, and
|
||||
// either the saved Branding (its compiled CSS and its logo) or, while none
|
||||
// has been saved, mail.brandCss. A Branding whose colours do not compile
|
||||
// keeps mail.brandCss.
|
||||
// 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}
|
||||
opts := renderOptions{css: m.opts.CSS, brandCSS: m.opts.BrandCSS, siteName: siteName(brand, m.opts.From), year: time.Now().Year()}
|
||||
if brand == nil {
|
||||
return opts
|
||||
}
|
||||
@@ -162,6 +164,22 @@ func (m *mailer) options(brand *Brand) renderOptions {
|
||||
return opts
|
||||
}
|
||||
|
||||
// siteName returns the name the built-in layouts show: the Branding's site
|
||||
// name, trimmed, else the display name of the sender address from, else
|
||||
// empty.
|
||||
func siteName(brand *Brand, from string) string {
|
||||
if brand != nil {
|
||||
if name := strings.TrimSpace(brand.SiteName); name != "" {
|
||||
return name
|
||||
}
|
||||
}
|
||||
addr, err := netmail.ParseAddress(from)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(addr.Name)
|
||||
}
|
||||
|
||||
// overrides asks the source once. A failed lookup (no connection, tables not
|
||||
// migrated yet) is a warning, not a send failure: the file version is sent.
|
||||
func (m *mailer) overrides(ctx context.Context, template string) Overrides {
|
||||
|
||||
@@ -88,7 +88,7 @@ Hello **{{ .Name }}**.
|
||||
if !strings.Contains(en.HTML, "<strong>Ada</strong>") || !strings.Contains(en.HTML, `href="https://example.test"`) {
|
||||
t.Fatalf("-en HTML = %q", en.HTML)
|
||||
}
|
||||
if !strings.Contains(pl.HTML, `class="content-body"`) || !strings.Contains(en.HTML, `class="content-body"`) {
|
||||
if !strings.Contains(pl.HTML, `class="inner-body"`) || !strings.Contains(en.HTML, `class="inner-body"`) {
|
||||
t.Fatalf("neutral default layout missing from HTML")
|
||||
}
|
||||
|
||||
|
||||
@@ -319,7 +319,7 @@ func TestMailOverrideSmoke(t *testing.T) {
|
||||
customizeWelcome(t, gdb, "Hello", "Plain.", defaultLayoutName)
|
||||
sendWelcome(t, m, "")
|
||||
got := lastMessage(t, drv)
|
||||
if !strings.Contains(got.HTML, `<div class="content-body"><p>Plain.</p>`) || strings.Contains(got.HTML, "blog-mail") {
|
||||
if !strings.Contains(got.HTML, "<td class=\"content-cell\">\n<p>Plain.</p>") || strings.Contains(got.HTML, "blog-mail") {
|
||||
t.Errorf("HTML = %q, want the default layout", got.HTML)
|
||||
}
|
||||
if logs.Len() != 0 {
|
||||
@@ -331,7 +331,7 @@ func TestMailOverrideSmoke(t *testing.T) {
|
||||
customizeWelcome(t, gdb, "Hello", "Plain.", "gone")
|
||||
sendWelcome(t, m, "")
|
||||
got = lastMessage(t, drv)
|
||||
if !strings.Contains(got.HTML, `<div class="content-body"><p>Plain.</p>`) {
|
||||
if !strings.Contains(got.HTML, "<td class=\"content-cell\">\n<p>Plain.</p>") {
|
||||
t.Errorf("HTML = %q, want the default layout for an unknown layout code", got.HTML)
|
||||
}
|
||||
if !strings.Contains(logs.String(), "level=WARN") || !strings.Contains(logs.String(), "unknown layout") || !strings.Contains(logs.String(), "layout=gone") {
|
||||
|
||||
@@ -186,7 +186,7 @@ func TestFallback(t *testing.T) {
|
||||
if len(drv.Messages()) != 1 {
|
||||
t.Fatalf("sent %d messages", len(drv.Messages()))
|
||||
}
|
||||
if !strings.Contains(got.HTML, `<div class="content-body"><p>Hi <strong>Ada</strong>`) {
|
||||
if !strings.Contains(got.HTML, "<td class=\"content-cell\">\n<p>Hi <strong>Ada</strong>") {
|
||||
t.Fatalf("HTML = %q, want default layout", got.HTML)
|
||||
}
|
||||
out := logs.String()
|
||||
|
||||
@@ -3,9 +3,11 @@ package postcard
|
||||
import (
|
||||
"context"
|
||||
"io/fs"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
@@ -49,6 +51,9 @@ var (
|
||||
_ pact.HasMailTemplates = templatesOnly{}
|
||||
)
|
||||
|
||||
// copyright is the footer line of the built-in layouts without a site name.
|
||||
func copyright() string { return "© " + strconv.Itoa(time.Now().Year()) }
|
||||
|
||||
// fakeOverrides is an OverrideSource with a fixed answer.
|
||||
type fakeOverrides struct{ ov Overrides }
|
||||
|
||||
@@ -224,7 +229,7 @@ func TestMailPartialsSmoke(t *testing.T) {
|
||||
if strings.Contains(msg.HTML, "MAILPARTIAL") || strings.Contains(msg.Text, "MAILPARTIAL") {
|
||||
t.Errorf("a token was left in the message:\n%s\n%s", msg.HTML, msg.Text)
|
||||
}
|
||||
if msg.Text != "Hi Ada\n\nGo <https://example.com/go?a=1&b=2>\n\nBye" {
|
||||
if msg.Text != "Hi Ada\n\nGo <https://example.com/go?a=1&b=2>\n\nBye\n\n-------------------\n"+copyright() {
|
||||
t.Errorf("text = %q", msg.Text)
|
||||
}
|
||||
|
||||
|
||||
@@ -155,6 +155,17 @@ var Migrations = []*gormigrate.Migration{
|
||||
return nil
|
||||
},
|
||||
},
|
||||
{
|
||||
// site_name is the name the built-in layouts show in their header
|
||||
// and footer (Brand.SiteName); empty uses mail.from's display name.
|
||||
ID: "202611130002_mail_brand_site_name",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`ALTER TABLE ` + BrandTable + ` ADD COLUMN site_name TEXT NOT NULL DEFAULT ''`).Error
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
return tx.Exec(`ALTER TABLE ` + BrandTable + ` DROP COLUMN IF EXISTS site_name`).Error
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// OverrideSource supplies the database overrides one render needs.
|
||||
@@ -322,9 +333,11 @@ func (s *dbSource) brand(tx *gorm.DB, out *Overrides) error {
|
||||
ButtonNegativeBg string
|
||||
PanelBg string
|
||||
TableBorderColor string
|
||||
SiteName string
|
||||
}
|
||||
err := tx.Raw(`SELECT logo_file_id, body_bg, content_bg, header_color, footer_color, heading_color, text_color,
|
||||
link_color, button_text_color, button_primary_bg, button_positive_bg, button_negative_bg, panel_bg, table_border_color
|
||||
link_color, button_text_color, button_primary_bg, button_positive_bg, button_negative_bg, panel_bg, table_border_color,
|
||||
site_name
|
||||
FROM ` + BrandTable + ` WHERE id = 1`).Scan(&rows).Error
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -337,7 +350,7 @@ FROM ` + BrandTable + ` WHERE id = 1`).Scan(&rows).Error
|
||||
BodyBg: r.BodyBg, ContentBg: r.ContentBg, HeaderColor: r.HeaderColor, FooterColor: r.FooterColor,
|
||||
HeadingColor: r.HeadingColor, TextColor: r.TextColor, LinkColor: r.LinkColor, ButtonTextColor: r.ButtonTextColor,
|
||||
ButtonPrimaryBg: r.ButtonPrimaryBg, ButtonPositiveBg: r.ButtonPositiveBg, ButtonNegativeBg: r.ButtonNegativeBg,
|
||||
PanelBg: r.PanelBg, TableBorderColor: r.TableBorderColor,
|
||||
PanelBg: r.PanelBg, TableBorderColor: r.TableBorderColor, SiteName: r.SiteName,
|
||||
}
|
||||
if r.LogoFileID == nil {
|
||||
return nil
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
texttemplate "text/template"
|
||||
"time"
|
||||
|
||||
"github.com/yuin/goldmark"
|
||||
)
|
||||
@@ -38,7 +39,7 @@ var builtinLayoutAliases = map[string]string{
|
||||
}
|
||||
|
||||
// builtinPartials are the partials postcard ships, callable by bare name.
|
||||
var builtinPartials = []string{"button", "panel", "subcopy", "table"}
|
||||
var builtinPartials = []string{"button", "panel", "subcopy", "table", "header", "footer"}
|
||||
|
||||
var (
|
||||
dangerousScheme = regexp.MustCompile(`(?i)(?:javascript|vbscript|data):`)
|
||||
@@ -100,8 +101,8 @@ type parsedPartial struct {
|
||||
}
|
||||
|
||||
// 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.
|
||||
// layouts (default, system and minimal) and partials (button, panel, table,
|
||||
// subcopy, header and footer). It holds no template.
|
||||
func NewCatalog() *Catalog {
|
||||
c := &Catalog{
|
||||
templates: make(map[string]*parsedTemplate),
|
||||
@@ -500,6 +501,11 @@ type renderOptions struct {
|
||||
brandCSS string
|
||||
// logoURL is the Branding logo's absolute URL, or empty.
|
||||
logoURL string
|
||||
// siteName is the name the built-in layouts show in their header and
|
||||
// footer: the Branding's site name, else the display name of mail.from.
|
||||
siteName string
|
||||
// year is the year of the copyright line; zero is the current year.
|
||||
year int
|
||||
// overrides are the database overrides to apply; the zero value renders
|
||||
// the file version.
|
||||
overrides Overrides
|
||||
@@ -645,12 +651,18 @@ func (c *Catalog) renderParts(msg Message, src renderSource, opts renderOptions)
|
||||
css += "\n" + opts.css
|
||||
}
|
||||
}
|
||||
year := opts.year
|
||||
if year == 0 {
|
||||
year = time.Now().Year()
|
||||
}
|
||||
text, err := execTextFuncs(layout.name+".text", layout.textWrap, map[string]any{
|
||||
"Content": textBody,
|
||||
"Subject": subject,
|
||||
"css": css,
|
||||
"brandCss": opts.brandCSS,
|
||||
"logoUrl": opts.logoURL,
|
||||
"siteName": opts.siteName,
|
||||
"year": year,
|
||||
}, texttemplate.FuncMap{"partial": partials.textCall})
|
||||
if err != nil {
|
||||
return out, partLayoutText, err
|
||||
@@ -661,6 +673,8 @@ func (c *Catalog) renderParts(msg Message, src renderSource, opts renderOptions)
|
||||
"css": template.CSS(css),
|
||||
"brandCss": template.CSS(opts.brandCSS),
|
||||
"logoUrl": opts.logoURL,
|
||||
"siteName": opts.siteName,
|
||||
"year": year,
|
||||
}, template.FuncMap{"partial": partials.htmlCall})
|
||||
if err != nil {
|
||||
return out, partLayoutHTML, err
|
||||
|
||||
Reference in New Issue
Block a user