Mail: merkkleur SLP Software (#ac0000) en dark-mode-robuuste knop

- SlpSoftware appsettings: Email:BrandColor = #ac0000 (primary uit de admin-CSS, BR-U1-07)
- Knop als bulletproof tabelknop (bgcolor + style, rand), tekstkleur automatisch >= 4.5:1
- color-scheme/supported-color-schemes meta + prefers-color-scheme: dark blok met lichtere accentkleur
- MailColours (contrastberekening); IsValidColour-pad ongewijzigd, tests incl. injectie

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 11:29:00 +01:00
co-authored by Claude Sonnet 5.5
parent 3a9e4ae7aa
commit f48642e6e8
4 changed files with 151 additions and 12 deletions
@@ -43,7 +43,7 @@
"FromName": "SLP Software",
"AllowedFromAddresses": [],
"LogoUrl": "",
"BrandColor": "",
"BrandColor": "#ac0000",
"Smtp": {
"Host": "",
"Port": 587,
@@ -185,6 +185,55 @@ public class MailTemplateRendererTests
mail.Html.Should().NotContain("red;}");
}
[Fact]
public void AnInvalidBrandColour_NeverReachesTheDarkModeBlockEither()
{
foreach (var bad in new[] { "red;}</style><script>x</script>", "#12345", "#12345g", "url(x)", "#ac0000;background:red" })
{
var mail = _renderer.Render(MailKind.Invitation, "nl", Model() with { BrandColor = bad });
mail.Html.Should().NotContain("<script>").And.NotContain("url(x)").And.NotContain("background:red;}")
.And.Contain("#1f2937");
}
}
[Theory]
[InlineData("#ac0000")]
[InlineData("#5f6a58")]
[InlineData("#2b6cb0")]
[InlineData("#1f2937")]
[InlineData("#ffffff")]
[InlineData("#000000")]
[InlineData("#ffee00")]
public void TheButton_IsReadableInLightAndDark_AndHasABorder(string brand)
{
var mail = _renderer.Render(MailKind.Invitation, "nl", Model() with { BrandColor = brand });
var html = mail.Html;
// bulletproof table button: bgcolor attribute and style, a visible border
html.Should().Contain($"bgcolor=\"{brand}\"").And.Contain($"border:2px solid {brand}");
// client hints for dark mode
html.Should().Contain("name=\"color-scheme\" content=\"light dark\"").And.Contain("supported-color-schemes")
.And.Contain("@media (prefers-color-scheme: dark)");
var text = MailColours.ReadableText(brand);
MailColours.Contrast(text, brand).Should().BeGreaterThanOrEqualTo(4.5);
html.Should().Contain($"background:{brand};color:{text};");
var dark = MailColours.DarkAccent(brand, "#1f2937");
var darkText = MailColours.ReadableText(dark);
MailColours.Contrast(dark, "#1f2937").Should().BeGreaterThanOrEqualTo(4.5); // heading and border on the dark card
MailColours.Contrast(darkText, dark).Should().BeGreaterThanOrEqualTo(4.5); // button text on the dark button
html.Should().Contain($".mail-btn a{{background:{dark} !important;color:{darkText} !important;");
html.Should().Contain($".mail-accent{{color:{dark} !important;");
}
[Fact]
public void TheSlpRed_GivesAWhiteButtonText()
{
MailColours.ReadableText("#ac0000").Should().Be("#ffffff");
MailColours.Contrast("#ffffff", "#ac0000").Should().BeGreaterThan(7);
}
[Fact]
public void LanguageResolver_UsesUserThenSiteDefaultThenDutch()
{
@@ -0,0 +1,65 @@
using System.Globalization;
namespace SlpModularCms.Core.Email;
/// <summary>
/// Colour maths for the mail layout (WCAG relative luminance and contrast). Only ever fed colours that passed
/// <see cref="EmailAddressRules.IsValidColour"/> or the fixed constants of the layout.
/// </summary>
public static class MailColours
{
public const double MinimumContrast = 4.5;
private const string Light = "#ffffff";
private const string Dark = "#111827";
public static double Contrast(string a, string b)
{
var (la, lb) = (Luminance(a), Luminance(b));
var (hi, lo) = la >= lb ? (la, lb) : (lb, la);
return (hi + 0.05) / (lo + 0.05);
}
/// <summary>White or near-black, whichever reads better on <paramref name="background"/>.</summary>
public static string ReadableText(string background) =>
Contrast(Light, background) >= Contrast(Dark, background) ? Light : Dark;
/// <summary>
/// A lighter variant of <paramref name="colour"/> for a dark surface: mixed towards white in steps until it has
/// at least <see cref="MinimumContrast"/> against the surface AND carries readable button text.
/// </summary>
public static string DarkAccent(string colour, string surface)
{
for (var step = 0; step <= 20; step++)
{
var candidate = MixWithWhite(colour, step / 20.0);
if (Contrast(candidate, surface) >= MinimumContrast
&& Contrast(candidate, ReadableText(candidate)) >= MinimumContrast)
return candidate;
}
return Light;
}
private static string MixWithWhite(string colour, double amount)
{
var (r, g, b) = Parse(colour);
int Mix(int c) => (int)Math.Round(c + (255 - c) * amount);
return $"#{Mix(r):x2}{Mix(g):x2}{Mix(b):x2}";
}
private static (int R, int G, int B) Parse(string colour) =>
(int.Parse(colour.AsSpan(1, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture),
int.Parse(colour.AsSpan(3, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture),
int.Parse(colour.AsSpan(5, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture));
private static double Luminance(string colour)
{
var (r, g, b) = Parse(colour);
static double Channel(int c)
{
var s = c / 255.0;
return s <= 0.03928 ? s / 12.92 : Math.Pow((s + 0.055) / 1.055, 2.4);
}
return 0.2126 * Channel(r) + 0.7152 * Channel(g) + 0.0722 * Channel(b);
}
}
@@ -131,7 +131,7 @@ public sealed class MailTemplateRenderer : IMailTemplateRenderer
? null
: (lang == "en" ? $"Hello {model.RecipientName.Trim()}," : $"Hallo {model.RecipientName.Trim()},");
var colour = EmailAddressRules.IsValidColour(model.BrandColor) ? model.BrandColor! : DefaultColour;
var colour = (EmailAddressRules.IsValidColour(model.BrandColor) ? model.BrandColor! : DefaultColour).ToLowerInvariant();
var hasAction = t.Button is not null && !string.IsNullOrEmpty(model.ActionUrl);
return new RenderedMail(subject, BuildHtml(model, site, colour, greeting, heading, intro, hasAction ? t.Button : null, note, footer),
@@ -158,31 +158,56 @@ public sealed class MailTemplateRenderer : IMailTemplateRenderer
private static string E(string value) => WebUtility.HtmlEncode(value);
private const string DarkPage = "#111827";
private const string DarkCard = "#1f2937";
private static string BuildHtml(
MailModel model, string site, string colour, string? greeting, string heading, string intro,
string? button, string? note, string footer)
{
// Light: the button is the brand colour with the best-contrasting text. Dark: a lighter variant of the
// brand colour (readable on the dark card) with its own best-contrasting text. Both are >= 4.5:1.
var buttonText = MailColours.ReadableText(colour);
var dark = MailColours.DarkAccent(colour, DarkCard);
var darkText = MailColours.ReadableText(dark);
var sb = new StringBuilder();
sb.Append("<!DOCTYPE html><html><body style=\"margin:0;padding:0;background:#f3f4f6;\">");
sb.Append("<table role=\"presentation\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:#f3f4f6;padding:24px 0;\"><tr><td align=\"center\">");
sb.Append("<table role=\"presentation\" width=\"560\" cellpadding=\"0\" cellspacing=\"0\" style=\"max-width:560px;width:100%;background:#ffffff;border-radius:8px;font-family:Arial,Helvetica,sans-serif;color:#111827;\">");
sb.Append($"<tr><td style=\"padding:24px 32px;border-bottom:3px solid {colour};\">");
sb.Append("<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\">");
sb.Append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
sb.Append("<meta name=\"color-scheme\" content=\"light dark\"><meta name=\"supported-color-schemes\" content=\"light dark\">");
sb.Append("<style>:root{color-scheme:light dark;supported-color-schemes:light dark;}");
sb.Append("@media (prefers-color-scheme: dark){");
sb.Append($".mail-page{{background:{DarkPage} !important;}}");
sb.Append($".mail-card{{background:{DarkCard} !important;color:#f3f4f6 !important;}}");
sb.Append($".mail-accent{{color:{dark} !important;border-color:{dark} !important;}}");
sb.Append($".mail-btn{{background:{dark} !important;border-color:{dark} !important;}}");
sb.Append($".mail-btn a{{background:{dark} !important;color:{darkText} !important;border-color:{darkText} !important;}}");
sb.Append(".mail-muted{color:#9ca3af !important;}.mail-rule{border-color:#374151 !important;}");
sb.Append("}</style></head>");
sb.Append("<body class=\"mail-page\" style=\"margin:0;padding:0;background:#f3f4f6;\">");
sb.Append("<table role=\"presentation\" class=\"mail-page\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" bgcolor=\"#f3f4f6\" style=\"background:#f3f4f6;padding:24px 0;\"><tr><td align=\"center\">");
sb.Append("<table role=\"presentation\" class=\"mail-card\" width=\"560\" cellpadding=\"0\" cellspacing=\"0\" bgcolor=\"#ffffff\" style=\"max-width:560px;width:100%;background:#ffffff;border-radius:8px;font-family:Arial,Helvetica,sans-serif;color:#111827;\">");
sb.Append($"<tr><td class=\"mail-accent\" style=\"padding:24px 32px;border-bottom:3px solid {colour};\">");
if (!string.IsNullOrEmpty(model.LogoUrl))
sb.Append($"<img src=\"{E(model.LogoUrl)}\" alt=\"{E(site)}\" height=\"48\" style=\"display:block;height:48px;width:auto;border:0;\">");
else
sb.Append($"<span style=\"font-size:20px;font-weight:bold;color:{colour};\">{E(site)}</span>");
sb.Append($"<span class=\"mail-accent\" style=\"font-size:20px;font-weight:bold;color:{colour};\">{E(site)}</span>");
sb.Append("</td></tr><tr><td style=\"padding:32px;font-size:15px;line-height:1.5;\">");
sb.Append($"<h1 style=\"margin:0 0 16px 0;font-size:22px;color:{colour};\">{E(heading)}</h1>");
sb.Append($"<h1 class=\"mail-accent\" style=\"margin:0 0 16px 0;font-size:22px;color:{colour};\">{E(heading)}</h1>");
if (greeting is not null) sb.Append($"<p style=\"margin:0 0 12px 0;\">{E(greeting)}</p>");
sb.Append($"<p style=\"margin:0 0 24px 0;\">{E(intro)}</p>");
if (button is not null && !string.IsNullOrEmpty(model.ActionUrl))
{
sb.Append($"<p style=\"margin:0 0 24px 0;\"><a href=\"{E(model.ActionUrl)}\" style=\"display:inline-block;background:{colour};color:#ffffff;text-decoration:none;padding:12px 24px;border-radius:6px;font-weight:bold;\">{E(button)}</a></p>");
sb.Append($"<p style=\"margin:0 0 24px 0;font-size:13px;color:#4b5563;word-break:break-all;\">{E(model.ActionUrl)}</p>");
// 'Bulletproof' button: a table cell with bgcolor + style, a visible border, and the link filling the cell.
sb.Append("<table role=\"presentation\" cellpadding=\"0\" cellspacing=\"0\" style=\"margin:0 0 24px 0;\"><tr>");
sb.Append($"<td class=\"mail-btn\" align=\"center\" bgcolor=\"{colour}\" style=\"background:{colour};border:2px solid {colour};border-radius:6px;\">");
sb.Append($"<a href=\"{E(model.ActionUrl)}\" style=\"display:inline-block;background:{colour};color:{buttonText};text-decoration:none;padding:12px 24px;border:1px solid {buttonText};border-radius:4px;font-weight:bold;\">{E(button)}</a>");
sb.Append("</td></tr></table>");
sb.Append($"<p class=\"mail-muted\" style=\"margin:0 0 24px 0;font-size:13px;color:#4b5563;word-break:break-all;\">{E(model.ActionUrl)}</p>");
}
if (note is not null) sb.Append($"<p style=\"margin:0 0 24px 0;font-size:13px;color:#4b5563;\">{E(note)}</p>");
if (note is not null) sb.Append($"<p class=\"mail-muted\" style=\"margin:0 0 24px 0;font-size:13px;color:#4b5563;\">{E(note)}</p>");
sb.Append("</td></tr>");
sb.Append($"<tr><td style=\"padding:16px 32px;font-size:12px;color:#6b7280;border-top:1px solid #e5e7eb;\">{E(footer)}</td></tr>");
sb.Append($"<tr><td class=\"mail-muted mail-rule\" style=\"padding:16px 32px;font-size:12px;color:#6b7280;border-top:1px solid #e5e7eb;\">{E(footer)}</td></tr>");
sb.Append("</table></td></tr></table></body></html>");
return sb.ToString();
}