v4: every email is rendered by its template in api/mail/ on one layout that takes the instance's style, and sent one way — the welcome email was built and sent inside the register route and the reset link in its service, each writing Markdown, running marked, and calling a nodemailer wrapper whose cc, bcc, replyTo and send result nothing used. Now api/mail/ holds one template per email (welcome.ts, password-reset.ts) on layout.ts's EmailKit, which draws each block with inline styles in a style from styles.ts: the six site styles' palettes, copied from src/themes/, and what makes each recognisable in a mail client (Brutalist's hard border and shadow, GeoCities' ridge and rainbow rules, Times' underlined ink links, Kanagawa's colored quotes, dates and wordmark, Melange's spice bar). On the "auto" scheme the light palette is inlined and the dark one swapped in by a prefers-color-scheme block; a chosen scheme sends only its own. User-written text is escaped where it lands. strings.ts holds every email's words in English and French. GERBEUR_EMAIL_LOCALE picks the language and GERBEUR_DEFAULT_STYLE the instance's style, which the welcome and reset emails are drawn in; GERBEUR_WELCOME_EMAIL_BODY still replaces the welcome's Markdown, whose blocks now take the style too. email-service sends a rendered email with its recipient and headers, refuses to load when GERBEUR_SMTPS_URL is set without GERBEUR_FROM_EMAIL (sends used to fail one by one), and takes a test transport, through which the tests now read what was sent. The welcome send moves to user-service's sendWelcomeEmail. The style and scheme names move to shared/theme.ts, which the server now needs. README, mod.ts and .env.example describe mail/ and the new variables, and drop the "notifications, invites" email that never existed. 221 backend tests pass (new: the layout's schemes, styles and escaping, both templates, the welcome on sign-up, a reset link from the email that works), and deno check, deno lint, doc:lint, deno fmt, tsc and eslint are clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-10-04 21:11:54 +00:00
parent 5f0cf86fe6
commit f20ca83f0c
21 changed files with 1459 additions and 179 deletions

534
api/mail/layout.ts Normal file
View File

@@ -0,0 +1,534 @@
/**
* Every email the site sends shares one layout: the site's emoji and name,
* then a card holding the content, then a footer. The templates beside this
* module (welcome, password reset, digest) build their content with an
* {@link EmailKit}, which draws each block in a style from `styles.ts`, and
* `email-service.ts` sends what they return.
*
* Mail clients drop stylesheets, so every block carries inline styles. A
* reader on the "auto" scheme gets the light palette inline and the dark one
* in a `prefers-color-scheme` block that Apple's mail apps honour; elsewhere
* the light one shows.
*
* @module
*/
import { type EmailLocale, OG_SITE_NAME, SITE_EMOJI } from "../config.ts";
import type { ColorScheme, StyleName } from "../../shared/theme.ts";
import {
EMAIL_STYLES,
type EmailPalette,
type EmailStyle,
RAINBOW,
} from "./styles.ts";
/**
* Returned by each template to its caller, which hands it to `sendEmail`
* with a recipient.
*/
export interface RenderedEmail {
subject: string;
html: string;
/** The plain-text part, for clients that show no HTML. */
text: string;
}
/**
* Passed to {@link EmailKit}. The instance's style draws the emails that
* aren't a user's own; a digest takes its reader's settings.
*/
export interface EmailLook {
style: StyleName;
scheme: ColorScheme;
}
/**
* Names a color of an {@link EmailPalette}, as {@link EmailKit.paint} takes
* it, so that the dark block can recolor the element by the same name.
*/
export type PaletteRole = Exclude<keyof EmailPalette, "spice">;
const ROLES: PaletteRole[] = [
"outer",
"card",
"text",
"sec",
"muted",
"accent",
"link",
"onAccent",
"rule",
"soft",
"quote",
"date",
"brand",
"border",
];
/**
* Escapes `value` for HTML text and attributes. Everything users wrote (names,
* titles, quotes) goes through it, since none of it may become markup.
*/
export function esc(value: string): string {
return value.replace(
/[&<>"']/g,
(c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
c
]!,
);
}
const gradient = (colors: string[]) =>
`linear-gradient(90deg,${colors.join(",")})`;
/**
* Draws the blocks of an email in one {@link EmailLook}. A template creates
* one, builds its body with the block methods, and wraps it with
* {@link EmailKit.document}. The blocks return HTML: text passed to them must
* already be escaped with {@link esc}.
*/
export class EmailKit {
/** The style being drawn. */
readonly style: EmailStyle;
/** The palette inlined into the HTML. */
readonly palette: EmailPalette;
/** The palette that replaces it in dark mode, on the "auto" scheme only. */
readonly darkPalette: EmailPalette | null;
/** The font stack, for templates that set their own blocks. */
readonly font: string;
constructor(look: EmailLook, readonly locale: EmailLocale) {
this.style = EMAIL_STYLES[look.style];
this.palette = look.scheme === "dark" ? this.style.dark : this.style.light;
this.darkPalette = look.scheme === "auto" ? this.style.dark : null;
this.font = this.style.font;
}
/** Returns `px`, scaled for the style, as a CSS length. */
fs(px: number): string {
return `${Math.round(px * this.style.scale * 2) / 2}px`;
}
/**
* Returns the `class` and `style` attributes of an element colored by
* roles: `fg` for its text, `bg` for its fill, `bd` for its border. The
* classes let the dark block recolor it; `css` is the rest of its style.
*/
paint(
roles: {
fg?: PaletteRole;
bg?: PaletteRole;
bd?: PaletteRole;
extra?: string[];
},
css = "",
): string {
const p = this.palette;
const classes: string[] = [...(roles.extra ?? [])];
let style = "";
if (roles.fg) {
classes.push(`f-${roles.fg}`);
style += `color:${p[roles.fg] ?? p.text};`;
}
if (roles.bg) {
classes.push(`b-${roles.bg}`);
style += `background-color:${p[roles.bg] ?? p.card};`;
}
if (roles.bd) {
classes.push(`d-${roles.bd}`);
style += `border-color:${p[roles.bd] ?? p.rule};`;
}
const cls = classes.length ? ` class="${classes.join(" ")}"` : "";
return `${cls} style="${style}${css}"`;
}
/** Returns a link to `href` around `html`, in the link color. */
link(html: string, href: string, strong = false): string {
const s = this.style;
return `<a href="${esc(href)}"${
this.paint(
{ fg: "link" },
`text-decoration:${s.linkUnderline ? "underline" : "none"};${
strong ? `font-weight:${s.heavy};` : ""
}`,
)
}>${html}</a>`;
}
/** Returns `@username`, set off as a name. */
name(username: string): string {
return `<b${
this.paint(
{ fg: "text" },
`font-weight:${Math.max(600, this.style.heavy)};`,
)
}>@${esc(username)}</b>`;
}
/** Returns `html` in the muted color, inline. */
muted(html: string): string {
return `<span${this.paint({ fg: "muted" })}>${html}</span>`;
}
/** Returns the email's heading, in the style's title type. */
heading(html: string, marginBottom = 24): string {
const t = this.style.title;
return `<h1${
this.paint(
{ fg: t.accent ? "accent" : "text" },
`font-family:${this.font};font-size:${
this.fs(t.size)
};line-height:1.15;font-weight:${t.weight};${
t.upper ? "text-transform:uppercase;" : ""
}${
t.spacing ? `letter-spacing:${t.spacing};` : ""
}margin:0 0 ${marginBottom}px;`,
)
}>${html}</h1>`;
}
/** Returns a paragraph. `css` adds to or overrides its style. */
para(html: string, css = ""): string {
return `<p${
this.paint(
{ fg: "text" },
`font-family:${this.font};font-size:${
this.fs(15)
};line-height:1.6;margin:0 0 16px;${css}`,
)
}>${html}</p>`;
}
/** Returns a smaller paragraph in the muted color. */
note(html: string, css = ""): string {
return `<p${
this.paint(
{ fg: "muted" },
`font-family:${this.font};font-size:${
this.fs(13.5)
};line-height:1.6;margin:0 0 16px;${css}`,
)
}>${html}</p>`;
}
/** Returns a button linking to `href`. */
button(label: string, href: string): string {
const s = this.style;
const frame = s.frame === "hard"
? `border:2px solid ${this.palette.text};box-shadow:2px 2px 0 ${this.palette.text};`
: "";
return `<table role="presentation" cellpadding="0" cellspacing="0" style="margin:6px 0 22px;"><tr><td${
this.paint(
{
bg: "accent",
bd: s.frame === "hard" ? "text" : undefined,
extra: s.frame === "hard" ? ["sh-btn"] : [],
},
`border-radius:${s.radius.btn}px;${frame}`,
)
}><a href="${esc(href)}"${
this.paint(
{ fg: "onAccent" },
`display:inline-block;padding:13px 22px;font-family:${this.font};font-size:${
this.fs(13.5)
};font-weight:${
Math.max(600, s.heavy)
};letter-spacing:0.08em;text-transform:uppercase;line-height:1;text-decoration:none;`,
)
}>${label}</a></td></tr></table>`;
}
/** Returns a small uppercase pill, as on one's own dump in a list. */
pill(label: string): string {
return `<span${
this.paint(
{ fg: "sec", bg: "soft" },
`display:inline-block;margin-left:6px;padding:1px 7px;border-radius:${this.style.radius.pill}px;font-size:${
this.fs(11)
};font-weight:600;letter-spacing:0.08em;text-transform:uppercase;vertical-align:2px;`,
)
}>${label}</span>`;
}
/** Returns an image block, rounded as the style rounds images. */
image(
src: string,
alt: string,
width: number,
height: number,
href?: string,
): string {
const img = `<img src="${
esc(src)
}" width="${width}" height="${height}" alt="${
esc(alt)
}" style="display:block;max-width:100%;height:auto;border:0;border-radius:${
Math.min(this.style.radius.img, width / 8)
}px;">`;
return href ? `<a href="${esc(href)}">${img}</a>` : img;
}
/** Returns a small bold heading inside a section. */
subhead(html: string): string {
return `<div${
this.paint(
{ fg: "text" },
`font-family:${this.font};font-size:${this.fs(14)};font-weight:${
Math.max(600, this.style.heavy)
};margin:0 0 8px;`,
)
}>${html}</div>`;
}
/** Returns `lines`, one per line, in the secondary color. */
lines(lines: string[]): string {
return `<div${
this.paint(
{ fg: "sec" },
`font-family:${this.font};font-size:${
this.fs(14)
};line-height:1.7;margin:0 0 18px;`,
)
}>${lines.join("<br>")}</div>`;
}
/** Returns a block set off from what precedes it by a hairline. */
aside(html: string): string {
return `<div${
this.paint(
{ fg: "muted", bd: "rule" },
`border-top:1px solid;font-family:${this.font};font-size:${
this.fs(13.5)
};line-height:1.6;padding:16px 0 14px;`,
)
}>${html}</div>`;
}
/**
* Returns a section of the card: a divider in the style's rule (none before
* the first), an uppercase title in the accent color, and `html`.
*/
section(title: string, html: string, first = false): string {
const s = this.style;
let divider = "";
let border = "";
if (!first) {
if (s.rule === "rainbow") {
divider =
`<div style="height:3px;line-height:3px;font-size:0;background-color:${
RAINBOW[0]
};background-image:${
gradient(RAINBOW)
};margin:0 0 26px;">&nbsp;</div>`;
} else {
border = `border-top:${
s.rule === "thick" ? 2 : 1
}px solid;padding-top:26px;`;
}
}
return `<div${
this.paint(
{ bd: border ? (s.rule === "thick" ? "text" : "rule") : undefined },
`${border}padding-bottom:26px;`,
)
}>${divider}<div${
this.paint(
{ fg: "accent" },
`font-family:${this.font};font-size:${this.fs(12)};font-weight:${
Math.max(600, s.heavy)
};letter-spacing:0.12em;text-transform:uppercase;margin:0 0 16px;`,
)
}>${title}</div>${html}</div>`;
}
/**
* Returns the whole HTML document: the brand, the card with the optional
* `eyebrow` and `title` over `body`, and the `footer`. `preheader` is the
* hidden first line inboxes show beside the subject.
*/
document(
{ subject, preheader, eyebrow, title, body, footer }: {
subject: string;
preheader: string;
eyebrow?: string;
title?: string;
body: string;
footer: string;
},
): string {
const s = this.style;
const p = this.palette;
const R = s.radius.card;
const bar = s.topBar === "rainbow"
? RAINBOW
: s.topBar === "spice"
? p.spice ?? null
: null;
const frame = s.frame === "hard"
? `border:2px solid ${p.text};box-shadow:5px 5px 0 ${p.text};`
: s.frame === "ridge"
? `border:3px ridge ${p.border};`
: s.frame === "hairline"
? `border:1px solid ${p.rule};`
: s.frame === "soft"
? `box-shadow:0 14px 34px -10px ${p.shadow};`
: "";
const frameRoles = s.frame === "hard"
? { bd: "text" as const, extra: ["sh-card"] }
: s.frame === "ridge"
? { bd: "border" as const }
: s.frame === "hairline"
? { bd: "rule" as const }
: s.frame === "soft"
? { extra: ["sh-soft"] }
: {};
const scheme = this.darkPalette
? "light dark"
: p === s.dark
? "dark"
: "light";
return `<!doctype html>
<html lang="${this.locale}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="color-scheme" content="${scheme}">
<meta name="supported-color-schemes" content="${scheme}">
<title>${esc(subject)}</title>
${
s.webFont
? `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=${s.webFont}&display=swap">`
: ""
}
<style>
body{margin:0;padding:0;}
@media (max-width:620px){.wrap{padding:20px 10px 28px!important}.card{padding:24px 20px 8px!important}}
${this.darkCss()}
</style>
</head>
<body${this.paint({ bg: "outer" }, "margin:0;padding:0;")}>
<div style="display:none;max-height:0;overflow:hidden;opacity:0;">${
esc(preheader)
}</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0"${
this.paint({ bg: "outer" })
}>
<tr><td align="center" class="wrap" style="padding:32px 16px 40px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:600px;">
<tr><td style="padding:0 6px 16px;">
<table role="presentation" cellpadding="0" cellspacing="0"><tr>
<td style="padding-right:10px;vertical-align:middle;font-size:24px;line-height:1;">${
esc(SITE_EMOJI)
}</td>
<td${
this.paint(
{ fg: p.brand ? "brand" : "text" },
`vertical-align:middle;font-family:${this.font};font-weight:700;font-size:${
this.fs(21)
};line-height:1;letter-spacing:-0.01em;`,
)
}>${esc(OG_SITE_NAME)}</td>
</tr></table>
</td></tr>
${
bar
? `<tr><td class="bar" style="height:5px;line-height:5px;font-size:0;background-color:${
bar[0]
};background-image:${
gradient(bar)
};border-radius:${R}px ${R}px 0 0;">&nbsp;</td></tr>`
: ""
}
<tr><td${
this.paint(
{
bg: "card",
...frameRoles,
extra: ["card", ...(frameRoles.extra ?? [])],
},
`border-radius:${
bar ? `0 0 ${R}px ${R}px` : `${R}px`
};${frame}padding:34px 36px 12px;`,
)
}>
${
eyebrow
? `<div${
this.paint(
{ fg: "muted" },
`font-family:${this.font};font-size:${
this.fs(12)
};font-weight:600;letter-spacing:0.12em;text-transform:uppercase;margin:0 0 8px;`,
)
}>${eyebrow}</div>`
: ""
}
${title ? this.heading(title) : ""}
${body}
</td></tr>
<tr><td${
this.paint(
{ fg: "muted" },
`padding:22px 6px 0;font-family:${this.font};font-size:${
this.fs(12.5)
};line-height:1.6;`,
)
}>${footer}</td></tr>
</table>
</td></tr>
</table>
</body>
</html>`;
}
/**
* Returns a footer: `reason` (why the reader gets this email), then
* `links`, each `[label, href]`, joined on one line.
*/
footer(reason: string, links: [string, string][] = []): string {
const linkHtml = links.map(([label, href]) =>
`<a href="${esc(href)}"${
this.paint({ fg: "muted" }, "text-decoration:underline;")
}>${label}</a>`
).join(" · ");
return `${reason}${linkHtml ? `<br>${linkHtml}` : ""}`;
}
/**
* Returns the CSS that recolors every painted element in dark mode, or
* nothing off the "auto" scheme.
*/
private darkCss(): string {
const d = this.darkPalette;
if (!d) return "";
const rules: string[] = [];
for (const role of ROLES) {
const color = d[role];
if (!color) continue;
rules.push(
`.f-${role}{color:${color}!important}`,
`.b-${role}{background-color:${color}!important}`,
`.d-${role}{border-color:${color}!important}`,
);
}
rules.push(
`.sh-card{box-shadow:5px 5px 0 ${d.text}!important}`,
`.sh-btn{box-shadow:2px 2px 0 ${d.text}!important}`,
);
if (d.shadow) {
rules.push(
`.sh-soft{box-shadow:0 14px 34px -10px ${d.shadow}!important}`,
);
}
if (this.style.topBar === "spice" && d.spice) {
rules.push(
`.bar{background-color:${d.spice[0]}!important;background-image:${
gradient(d.spice)
}!important}`,
);
}
return `@media (prefers-color-scheme:dark){${rules.join("")}}`;
}
}

View File

@@ -0,0 +1,67 @@
/**
* Renders the email carrying a password reset link. `requestPasswordReset`
* (`password-reset-service.ts`) sends it, in the instance's style and
* language: whoever asks isn't signed in, so their own settings don't apply.
*
* @module
*/
import { DEFAULT_STYLE, EMAIL_LOCALE, OG_SITE_NAME } from "../config.ts";
import { EmailKit, esc, type RenderedEmail } from "./layout.ts";
import { STRINGS } from "./strings.ts";
/**
* Returns the reset email of `username`, whose button opens `resetUrl`. The
* link stays usable for `hours`, which the email states.
*/
export function renderPasswordResetEmail(
username: string,
resetUrl: string,
hours: number,
): RenderedEmail {
const t = STRINGS[EMAIL_LOCALE].reset;
const kit = new EmailKit(
{ style: DEFAULT_STYLE, scheme: "auto" },
EMAIL_LOCALE,
);
const subject = t.subject(OG_SITE_NAME);
const urlBox = `<div${
kit.paint(
{ fg: "sec", bg: "soft" },
`font-family:Menlo,Consolas,'Courier New',monospace;font-size:12px;line-height:1.5;border-radius:${
Math.min(kit.style.radius.img, 6)
}px;padding:10px 12px;margin:0 0 22px;word-break:break-all;`,
)
}>${esc(resetUrl)}</div>`;
const body = kit.para(esc(t.hi(username))) +
kit.para(esc(t.body(OG_SITE_NAME, hours))) +
kit.button(esc(t.button), resetUrl) +
kit.note(esc(t.fallback), "margin-bottom:8px;") +
urlBox +
kit.note(esc(t.ignore));
return {
subject,
html: kit.document({
subject,
preheader: t.preheader(hours),
title: esc(t.title),
body,
footer: kit.footer(esc(t.reason)),
}),
text: [
t.title,
"",
t.hi(username),
"",
t.body(OG_SITE_NAME, hours),
"",
resetUrl,
"",
t.ignore,
"",
"--",
t.reason,
].join("\n"),
};
}

108
api/mail/strings.ts Normal file
View File

@@ -0,0 +1,108 @@
/**
* The words of every email, in each language an instance can pick with
* `GERBEUR_EMAIL_LOCALE`. The templates beside this module read
* `STRINGS[EMAIL_LOCALE]`. French follows the interface's own words (a dump is
* a "reco", a playlist a "collection") and puts a no-break space before
* `: ! ?`.
*
* @module
*/
import type { EmailLocale } from "../config.ts";
/** A no-break space, which French typography puts before `: ! ?`. */
const NB = " ";
/**
* Read by the templates for one language. A function takes what varies, the
* site's name first; none escapes what it is given.
*/
export interface MailStrings {
/** The footer's link to the settings. */
settings: string;
welcome: {
subject: (site: string) => string;
preheader: string;
/** The Markdown body, unless `GERBEUR_WELCOME_EMAIL_BODY` replaces it. */
body: string;
button: (site: string) => string;
reason: (site: string) => string;
};
reset: {
subject: (site: string) => string;
preheader: (hours: number) => string;
title: string;
hi: (username: string) => string;
body: (site: string, hours: number) => string;
button: string;
fallback: string;
ignore: string;
reason: string;
};
}
/** Every email's words, by language. */
export const STRINGS: Record<EmailLocale, MailStrings> = {
en: {
settings: "Settings",
welcome: {
subject: (site) => `Welcome to ${site}`,
preheader: "Your account is ready.",
body:
"# Welcome to {{site_name}}!\n\nHi **{{username}}**,\n\nYour account has been created successfully. Welcome aboard!",
button: (site) => `Open ${site}`,
reason: (site) =>
`You're getting this email because an account was created on ${site} with this address.`,
},
reset: {
subject: (site) => `Reset your ${site} password`,
preheader: (hours) =>
`The link works once, for ${hours} ${hours === 1 ? "hour" : "hours"}.`,
title: "Reset your password",
hi: (username) => `Hi ${username},`,
body: (site, hours) =>
`Someone asked to reset the password of your ${site} account. The button below lets you choose a new one. It works once, for ${hours} ${
hours === 1 ? "hour" : "hours"
}.`,
button: "Reset password",
fallback:
"If the button doesn't work, paste this link into your browser:",
ignore:
"If you didn't ask for this, ignore this email. Your password stays the same.",
reason:
"You're getting this email because a password reset was requested for this address.",
},
},
fr: {
settings: "Paramètres",
welcome: {
subject: (site) => `Bienvenue sur ${site}`,
preheader: "Votre compte est prêt.",
body:
`# Bienvenue sur {{site_name}}${NB}!\n\nBonjour **{{username}}**,\n\nVotre compte a bien été créé. Bienvenue à bord${NB}!`,
button: (site) => `Ouvrir ${site}`,
reason: (site) =>
`Vous recevez cet e-mail car un compte ${site} a été créé avec cette adresse.`,
},
reset: {
subject: (site) => `Réinitialisez votre mot de passe ${site}`,
preheader: (hours) =>
`Le lien ne fonctionne qu'une fois, pendant ${hours}${NB}${
hours < 2 ? "heure" : "heures"
}.`,
title: "Réinitialiser votre mot de passe",
hi: (username) => `Bonjour ${username},`,
body: (site, hours) =>
`Quelqu'un a demandé à réinitialiser le mot de passe de votre compte ${site}. Le bouton ci-dessous vous permet d'en choisir un nouveau. Il ne fonctionne qu'une fois, pendant ${hours}${NB}${
hours < 2 ? "heure" : "heures"
}.`,
button: "Choisir un nouveau mot de passe",
fallback:
`Si le bouton ne fonctionne pas, collez ce lien dans votre navigateur${NB}:`,
ignore:
"Si vous n'êtes pas à l'origine de cette demande, ignorez cet e-mail. Votre mot de passe ne change pas.",
reason:
"Vous recevez cet e-mail car une réinitialisation de mot de passe a été demandée pour cette adresse.",
},
},
};

334
api/mail/styles.ts Normal file
View File

@@ -0,0 +1,334 @@
/**
* Carries each site style into email, so a digest looks like the site its
* reader chose and the other emails like the instance's style. A mail client
* takes no stylesheet of ours, so each style is spelled out here: its palettes,
* copied from its theme under `src/themes/`, and the few touches that make it
* recognisable once flattened into inline styles. `layout.ts` reads them.
*
* @module
*/
import type { StyleName } from "../../shared/theme.ts";
/**
* The colors of one style in one scheme, by role. Most are the theme's own
* tokens; the optional ones carry a style's particular touches.
*/
export interface EmailPalette {
/** The page around the card (`--color-bg`). */
outer: string;
/** The card holding the content (`--color-surface`). */
card: string;
text: string;
sec: string;
muted: string;
/** Section titles, ranks and button fills (`--color-accent`). */
accent: string;
link: string;
/** Text on an accent fill. */
onAccent: string;
/** Dividers and hairlines. */
rule: string;
/** Pills and the reset link's box. */
soft: string;
/** Quoted comments and messages. */
quote: string;
/** Kanagawa's fujiGray dates; others use `muted`. */
date?: string;
/** Kanagawa's oniViolet wordmark; others use `text`. */
brand?: string;
/** GeoCities' ridged border. */
border?: string;
/** Melange's warm card shadow. */
shadow?: string;
/** Melange's spice gradient, left to right. */
spice?: string[];
}
/**
* How a style draws an email. `layout.ts` builds every block from it, so
* adding a style to `shared/theme.ts` means adding its entry here.
*/
export interface EmailStyle {
/**
* The font stack. Its first family is a web font only Apple's mail apps
* load, through {@link webFont}; other clients fall back along the stack.
*/
font: string;
/** The Google Fonts `family` parameter of the web font, if it is one. */
webFont?: string;
/** Multiplies every font size: Times sets its serif larger, Kanagawa its monospace smaller. */
scale: number;
/** Corner radii, in pixels. */
radius: {
card: number;
img: number;
btn: number;
pill: number;
avatar: number;
};
/** The heading: its size in pixels, weight, and Brutalist's uppercase and spacing. */
title: {
size: number;
weight: number;
upper?: boolean;
spacing?: string;
accent?: boolean;
};
/** The weight of titles of items, figures and names. */
heavy: number;
/** How the card stands out from the page. */
frame: "none" | "hard" | "ridge" | "hairline" | "soft";
/** The divider between sections. */
rule: "hairline" | "thick" | "rainbow";
/** A colored bar along the card's top. */
topBar?: "rainbow" | "spice";
/** Underlines links, for styles whose links are the color of the text. */
linkUnderline?: boolean;
light: EmailPalette;
dark: EmailPalette;
}
/** GeoCities' rainbow, as its theme draws its dividers. */
export const RAINBOW = [
"#ff004d",
"#ff8a00",
"#ffee00",
"#00d11a",
"#00b3ff",
"#b300ff",
];
/** Every style's email look, keyed by its name. */
export const EMAIL_STYLES: Record<StyleName, EmailStyle> = {
smooth: {
font: "Saira, 'Helvetica Neue', Helvetica, Arial, sans-serif",
webFont: "Saira:wght@400;600;700",
scale: 1,
radius: { card: 14, img: 6, btn: 8, pill: 999, avatar: 16 },
title: { size: 30, weight: 600 },
heavy: 600,
frame: "none",
rule: "hairline",
light: {
outer: "#faf5e9",
card: "#fffdf8",
text: "#0e3a42",
sec: "#35626b",
muted: "#4d7178",
accent: "#b54a41",
link: "#b54a41",
onAccent: "#fffaf0",
rule: "#ebe4d4",
soft: "#f3ecdd",
quote: "#5c7d83",
},
dark: {
outer: "#01152a",
card: "#0a2139",
text: "#e9eef2",
sec: "#a3b9c7",
muted: "#7b93a6",
accent: "#f4d58d",
link: "#f4d58d",
onAccent: "#001427",
rule: "#1b3350",
soft: "#112a46",
quote: "#a3b9c7",
},
},
brutalist: {
font: "'Space Grotesk', Arial, Helvetica, sans-serif",
webFont: "Space+Grotesk:wght@400;700",
scale: 1,
radius: { card: 0, img: 0, btn: 0, pill: 0, avatar: 0 },
title: { size: 30, weight: 900, upper: true, spacing: "0.03em" },
heavy: 700,
frame: "hard",
rule: "thick",
light: {
outer: "#f4f1de",
card: "#f8f5e8",
text: "#3d405b",
sec: "#5a5e80",
muted: "#7a7e9a",
accent: "#e07a5f",
link: "#b85a3a",
onAccent: "#f4f1de",
rule: "#8a8da8",
soft: "#ede9d4",
quote: "#5a5e80",
},
dark: {
outer: "#252838",
card: "#2e3145",
text: "#f4f1de",
sec: "#c8c5b2",
muted: "#8e8c80",
accent: "#f2cc8f",
link: "#f2cc8f",
onAccent: "#3d405b",
rule: "#4a4e6a",
soft: "#222436",
quote: "#c8c5b2",
},
},
geocities: {
font:
"'Comic Sans MS', 'Comic Sans', 'Chalkboard SE', 'Comic Neue', cursive",
scale: 1,
radius: { card: 0, img: 0, btn: 0, pill: 0, avatar: 0 },
title: { size: 30, weight: 700, accent: true },
heavy: 700,
frame: "ridge",
rule: "rainbow",
topBar: "rainbow",
linkUnderline: true,
light: {
outer: "#fff0f8",
card: "#ffffff",
text: "#2a1a4e",
sec: "#aa00aa",
muted: "#7a6a9a",
accent: "#d000d0",
link: "#0000ee",
onAccent: "#ffffff",
rule: "#f0c0f0",
soft: "#fff0fb",
quote: "#aa00aa",
border: "#d000d0",
},
dark: {
outer: "#0a0a2e",
card: "#1b1b46",
text: "#f2f0ff",
sec: "#7fdbff",
muted: "#a99ad6",
accent: "#ff00ff",
link: "#00ffff",
onAccent: "#000000",
rule: "#34346e",
soft: "#14143a",
quote: "#7fdbff",
border: "#00ffff",
},
},
nyt: {
font: "'Instrument Serif', Georgia, 'Times New Roman', serif",
webFont: "Instrument+Serif:ital@0;1",
scale: 1.12,
radius: { card: 0, img: 0, btn: 0, pill: 0, avatar: 16 },
title: { size: 38, weight: 400 },
heavy: 400,
frame: "hairline",
rule: "hairline",
linkUnderline: true,
light: {
outer: "#ffffff",
card: "#ffffff",
text: "#121212",
sec: "#363636",
muted: "#767676",
accent: "#121212",
link: "#121212",
onAccent: "#ffffff",
rule: "#e2e2e2",
soft: "#f3f3f3",
quote: "#5a5a5a",
},
dark: {
outer: "#121212",
card: "#1e1e1e",
text: "#e6e6e6",
sec: "#c4c4c4",
muted: "#8a8a8a",
accent: "#ececec",
link: "#ececec",
onAccent: "#121212",
rule: "#3a3a3a",
soft: "#2a2a2a",
quote: "#ababab",
},
},
kanagawa: {
font: "'JetBrains Mono', Menlo, Consolas, 'Courier New', monospace",
webFont: "JetBrains+Mono:ital,wght@0,400;0,600;1,400",
scale: 0.9,
radius: { card: 6, img: 4, btn: 4, pill: 3, avatar: 4 },
title: { size: 26, weight: 600 },
heavy: 600,
frame: "hairline",
rule: "hairline",
light: {
outer: "#f2ecbc",
card: "#e7dfb2",
text: "#545464",
sec: "#716e61",
muted: "#766b90",
accent: "#4d699b",
link: "#4d699b",
onAccent: "#f2ecbc",
rule: "#d0c79d",
soft: "#dcd5ac",
quote: "#6f894e",
date: "#8a8980",
brand: "#624c83",
},
dark: {
outer: "#1f1f28",
card: "#2a2a37",
text: "#dcd7ba",
sec: "#c8c093",
muted: "#938aa9",
accent: "#7e9cd8",
link: "#7e9cd8",
onAccent: "#16161d",
rule: "#43435a",
soft: "#16161d",
quote: "#98bb6c",
date: "#727169",
brand: "#957fb8",
},
},
melange: {
font: "Fraunces, Georgia, serif",
webFont: "Fraunces:opsz,wght@9..144,400;9..144,600;9..144,700",
scale: 1,
radius: { card: 18, img: 10, btn: 12, pill: 999, avatar: 16 },
title: { size: 32, weight: 600 },
heavy: 600,
frame: "soft",
rule: "hairline",
topBar: "spice",
light: {
outer: "#e9e1db",
card: "#f6f2ef",
text: "#54433a",
sec: "#7d6658",
muted: "#a98a78",
accent: "#a06d00",
link: "#a06d00",
onAccent: "#f7f4f1",
rule: "#e0d3ca",
soft: "#ece4dd",
quote: "#7d6658",
shadow: "rgba(84,67,58,0.28)",
spice: ["#a06d00", "#bc5c00", "#c77b8b", "#be79bb", "#6e9b72"],
},
dark: {
outer: "#292522",
card: "#34302c",
text: "#ece1d7",
sec: "#c1a78e",
muted: "#867462",
accent: "#ebc06d",
link: "#ebc06d",
onAccent: "#292522",
rule: "#4a423b",
soft: "#403a36",
quote: "#c1a78e",
shadow: "rgba(0,0,0,0.5)",
spice: ["#ebc06d", "#e49b5d", "#bd8183", "#b380b0", "#78997a"],
},
},
};

78
api/mail/welcome.ts Normal file
View File

@@ -0,0 +1,78 @@
/**
* Renders the email that greets a new account. `sendWelcomeEmail`
* (`user-service.ts`) sends it after sign-up, in the instance's style and
* language. Its body is Markdown: the instance's `GERBEUR_WELCOME_EMAIL_BODY`,
* or the built-in one.
*
* @module
*/
import { Marked } from "marked";
import {
DEFAULT_STYLE,
EMAIL_LOCALE,
FRONTEND_URL,
OG_SITE_NAME,
WELCOME_EMAIL_BODY,
} from "../config.ts";
import { EmailKit, esc, type RenderedEmail } from "./layout.ts";
import { STRINGS } from "./strings.ts";
/**
* Returns a Markdown renderer whose blocks are `kit`'s, so the body takes the
* email's style. Raw HTML in the Markdown passes through: the body comes from
* whoever runs the instance, never from a user.
*/
function markdownIn(kit: EmailKit): Marked {
return new Marked({
renderer: {
heading({ tokens, depth }) {
const html = this.parser.parseInline(tokens);
return depth === 1 ? kit.heading(html, 20) : kit.subhead(html);
},
paragraph({ tokens }) {
return kit.para(this.parser.parseInline(tokens));
},
link({ href, tokens }) {
return kit.link(this.parser.parseInline(tokens), href);
},
strong({ tokens }) {
return `<strong style="font-weight:${
Math.max(600, kit.style.heavy)
};">${this.parser.parseInline(tokens)}</strong>`;
},
},
});
}
/**
* Returns the welcome email of `username`, with `{{username}}` and
* `{{site_name}}` filled into the body.
*/
export function renderWelcomeEmail(username: string): RenderedEmail {
const t = STRINGS[EMAIL_LOCALE].welcome;
const kit = new EmailKit(
{ style: DEFAULT_STYLE, scheme: "auto" },
EMAIL_LOCALE,
);
const markdown = (WELCOME_EMAIL_BODY ?? t.body)
.replaceAll("{{username}}", username)
.replaceAll("{{site_name}}", OG_SITE_NAME);
const subject = t.subject(OG_SITE_NAME);
const body = markdownIn(kit).parse(markdown, { async: false }) +
kit.button(esc(t.button(OG_SITE_NAME)), FRONTEND_URL);
return {
subject,
html: kit.document({
subject,
preheader: t.preheader,
body,
footer: kit.footer(esc(t.reason(OG_SITE_NAME))),
}),
text: `${markdown}\n\n${t.button(OG_SITE_NAME)}: ${FRONTEND_URL}\n\n--\n${
t.reason(OG_SITE_NAME)
}`,
};
}