v4: weekly digests and monthly recaps go out by email, every email is written once as Markdown in the app's one catalog, and a review of the last two commits removes what they stated twice — users get a weekly digest (what happened to them, what the people and playlists they follow posted, the week's top dumps, the community) and a monthly recap (the month's top dumps and the community), both on by default, in their own style and scheme. digest-service sends what is due every quarter of an hour from digest_schedule (migration 0020), which holds each user's rolling 7- or 30-day period; existing users' first periods are spread over the coming week or month, a digest more than a period late covers the last full one, an empty one isn't sent, and an address like admin@localhost is skipped. Each digest carries a one-click unsubscribe (List-Unsubscribe and List-Unsubscribe-Post, POST /api/users/unsubscribe) and a link to the new /unsubscribe page, which asks before turning that cadence off, since mail scanners open every link; the token (lib/jwt) names the user and the cadence and never expires. The welcome email now says the digests are on. The emails' words moved out of a hand-written api/mail/strings.ts into the Lingui catalogs the interface uses: lingui extracts api/mail/ too, the catalogs moved to a top-level locales/ that both halves read, compile emits ES modules the server imports (api/mail/i18n.ts), messages take ICU plurals, and the labels the settings tab, the unsubscribe page and the emails share are one message each (their French had already drifted apart). Each template writes its email once as Markdown, which is the plain-text part, and EmailKit.render draws its blocks in the style (a lone link is a button, a list item starting with an image a thumbnail row, a numbered list a ranking, --- the footer), so no string is declared for an HTML and a text version; user text is escaped for Markdown, which the welcome body didn't do for usernames, whose _ read as emphasis. paint() set colors before a border-top shorthand that reset them, so every divider was black. The review also gave one home to what was written twice: the locale list (shared/locale.ts, read by lingui.config, the client, the server and its catalog loader), the base style and default scheme (shared/theme.ts), an email's look (lookOf, which digest-service, welcome and reset share), whether email is on (EMAIL_ENABLED, read by email-service and index.html), a setting's column and its default in the digests' SQL (SETTINGS_COLUMNS, DEFAULT_SETTINGS), the unsubscribe token (made once, not parsed back from a URL), AuthProvider's compare-and-store, ThemeProvider's twin style and scheme code (useThemeChoice), the test JWT encoder, and duplicate digest messages. The email palettes stay a flattened copy of the themes' tokens, now under a test that caught Times' secondary and link colors drifting. The Dockerfile copies api/mail and locales so the build extracts the emails' messages and the server finds its catalogs, and deno.json maps @lingui/core for the runtime image. 236 backend tests (new: digest building, sending, catch-up, scheduling and unsubscribing; the Markdown renderer; French from the catalog; palettes against themes; the stagger migration; unsubscribe tokens) and 661 frontend tests (new: the unsubscribe page) pass, and tsc, eslint, doc:lint, deno check, deno lint and deno fmt are clean.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
622
api/mail/digest.ts
Normal file
622
api/mail/digest.ts
Normal file
@@ -0,0 +1,622 @@
|
||||
/**
|
||||
* Renders the weekly digest and the monthly recap, as the drafts approved
|
||||
* them: the weekly one has four sections (what happened to the reader, what
|
||||
* the people and playlists they follow posted, the period's top dumps, and
|
||||
* the community), the monthly one only the last two. `digest-service.ts`
|
||||
* gathers a {@link DigestContent} and sends what this returns, drawn in the
|
||||
* reader's own style and scheme.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { EMAIL_LOCALE, OG_SITE_NAME } from "../config.ts";
|
||||
import type { DigestCadence } from "../../shared/settings.ts";
|
||||
import { i18n } from "./i18n.ts";
|
||||
import {
|
||||
EmailKit,
|
||||
type EmailLook,
|
||||
escMd,
|
||||
mdLink,
|
||||
type RenderedEmail,
|
||||
} from "./layout.ts";
|
||||
|
||||
/** The kinds of activity a weekly digest counts. */
|
||||
export type ActivityKind =
|
||||
| "upvotes"
|
||||
| "followers"
|
||||
| "comments"
|
||||
| "mentions"
|
||||
| "likes"
|
||||
| "playlistFollows";
|
||||
|
||||
/** What a highlight of the weekly digest says happened. */
|
||||
export type HighlightKind =
|
||||
| "mentionComment"
|
||||
| "mentionDump"
|
||||
| "mentionPlaylist"
|
||||
| "mentionChat"
|
||||
| "comment"
|
||||
| "playlistFollow"
|
||||
| "userFollow"
|
||||
| "commentLike";
|
||||
|
||||
/** A dump in a digest's lists, with its links made absolute. */
|
||||
export interface DigestDump {
|
||||
title: string;
|
||||
url: string;
|
||||
poster: string;
|
||||
/** The link's host, or null for an upload. */
|
||||
domain: string | null;
|
||||
/** An absolute image URL, or null to show no image. */
|
||||
thumbnail: string | null;
|
||||
votes: number;
|
||||
comments: number;
|
||||
/** Posted by the reader, which the lists mark. */
|
||||
mine: boolean;
|
||||
/** The followed playlist it was added to, when that's why it's listed. */
|
||||
addedTo?: string;
|
||||
}
|
||||
|
||||
/** One line of the weekly digest's "For you", made from a notification. */
|
||||
export interface DigestHighlight {
|
||||
kind: HighlightKind;
|
||||
/** Who did it. */
|
||||
who: string;
|
||||
/** What they did it on, absent for a follow of the reader or the chat. */
|
||||
target?: { title: string; url: string };
|
||||
/** The comment or message, flattened and shortened. */
|
||||
quote?: string;
|
||||
at: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Passed to {@link renderDigestEmail} by `digest-service.ts`. Each section is
|
||||
* null when it has nothing to show, and is left out; the service sends
|
||||
* nothing when all of them are.
|
||||
*/
|
||||
export interface DigestContent {
|
||||
cadence: DigestCadence;
|
||||
/** The period covered, from `from` to `to`. */
|
||||
from: Date;
|
||||
to: Date;
|
||||
reader: string;
|
||||
/** Weekly only. */
|
||||
activity: {
|
||||
counts: Partial<Record<ActivityKind, number>>;
|
||||
highlights: DigestHighlight[];
|
||||
/** Every notification of the period, which the link to them counts. */
|
||||
total: number;
|
||||
} | null;
|
||||
/** Weekly only. */
|
||||
network: { dumps: DigestDump[]; more: number } | null;
|
||||
top: DigestDump[];
|
||||
community: {
|
||||
members: { username: string; invitedBy: string | null }[];
|
||||
membersMore: number;
|
||||
playlists: { title: string; url: string; owner: string; dumps: number }[];
|
||||
playlistsMore: number;
|
||||
chatMessages: number;
|
||||
totals: { dumps: number; upvotes: number; comments: number };
|
||||
} | null;
|
||||
links: {
|
||||
notifications: string;
|
||||
followed: string;
|
||||
chat: string;
|
||||
settings: string;
|
||||
/** The one-click page that turns this cadence off. */
|
||||
unsubscribe: string;
|
||||
};
|
||||
}
|
||||
|
||||
const ACTIVITY_ORDER: ActivityKind[] = [
|
||||
"upvotes",
|
||||
"followers",
|
||||
"comments",
|
||||
"mentions",
|
||||
"likes",
|
||||
"playlistFollows",
|
||||
];
|
||||
|
||||
/** Returns the label of `n` of a kind of activity, as in "12 upvotes". */
|
||||
function countLabel(kind: ActivityKind, n: number): string {
|
||||
switch (kind) {
|
||||
case "upvotes":
|
||||
return i18n._({
|
||||
id: "email.digest.count.upvotes",
|
||||
message: "{n, plural, one {upvote} other {upvotes}}",
|
||||
values: { n },
|
||||
});
|
||||
case "followers":
|
||||
return i18n._({
|
||||
id: "email.digest.count.followers",
|
||||
message: "{n, plural, one {new follower} other {new followers}}",
|
||||
values: { n },
|
||||
});
|
||||
case "comments":
|
||||
return i18n._({
|
||||
id: "email.digest.count.comments",
|
||||
message: "{n, plural, one {comment} other {comments}}",
|
||||
values: { n },
|
||||
});
|
||||
case "mentions":
|
||||
return i18n._({
|
||||
id: "email.digest.count.mentions",
|
||||
message: "{n, plural, one {mention} other {mentions}}",
|
||||
values: { n },
|
||||
});
|
||||
case "likes":
|
||||
return i18n._({
|
||||
id: "email.digest.count.likes",
|
||||
message: "{n, plural, one {comment like} other {comment likes}}",
|
||||
values: { n },
|
||||
});
|
||||
case "playlistFollows":
|
||||
return i18n._({
|
||||
id: "email.digest.count.playlistFollows",
|
||||
message: "{n, plural, one {playlist follow} other {playlist follows}}",
|
||||
values: { n },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the sentence of a highlight, `who` and `target` already formatted
|
||||
* for the part it goes in (HTML or Markdown).
|
||||
*/
|
||||
function highlightSentence(
|
||||
kind: HighlightKind,
|
||||
who: string,
|
||||
target: string,
|
||||
): string {
|
||||
const values = { who, target };
|
||||
switch (kind) {
|
||||
case "mentionComment":
|
||||
return i18n._({
|
||||
id: "email.digest.hl.mentionComment",
|
||||
message: "{who} mentioned you in a comment on {target}",
|
||||
values,
|
||||
});
|
||||
case "mentionDump":
|
||||
case "mentionChat":
|
||||
return i18n._({
|
||||
id: "email.digest.hl.mentionIn",
|
||||
message: "{who} mentioned you in {target}",
|
||||
values,
|
||||
});
|
||||
case "mentionPlaylist":
|
||||
return i18n._({
|
||||
id: "email.digest.hl.mentionPlaylist",
|
||||
message: "{who} mentioned you in the playlist {target}",
|
||||
values,
|
||||
});
|
||||
case "comment":
|
||||
return i18n._({
|
||||
id: "email.digest.hl.comment",
|
||||
message: "{who} commented on your dump {target}",
|
||||
values,
|
||||
});
|
||||
case "playlistFollow":
|
||||
return i18n._({
|
||||
id: "email.digest.hl.playlistFollow",
|
||||
message: "{who} followed your playlist {target}",
|
||||
values,
|
||||
});
|
||||
case "userFollow":
|
||||
return i18n._({
|
||||
id: "email.digest.hl.userFollow",
|
||||
message: "{who} started following you",
|
||||
values,
|
||||
});
|
||||
case "commentLike":
|
||||
return i18n._({
|
||||
id: "email.digest.hl.commentLike",
|
||||
message: "{who} liked your comment on {target}",
|
||||
values,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const byLine = (username: string) =>
|
||||
i18n._({
|
||||
id: "email.digest.by",
|
||||
message: "by @{username}",
|
||||
values: { username },
|
||||
});
|
||||
const addedToLine = (playlist: string) =>
|
||||
i18n._({
|
||||
id: "email.digest.addedTo",
|
||||
message: "added to {playlist}",
|
||||
values: { playlist },
|
||||
});
|
||||
const uploadLabel = () =>
|
||||
i18n._({ id: "email.digest.upload", message: "upload" });
|
||||
const invitedLine = (inviter: string, reader: string) =>
|
||||
inviter === reader
|
||||
? i18n._({ id: "email.digest.invitedByYou", message: "invited by you" })
|
||||
: i18n._({
|
||||
id: "email.digest.invitedBy",
|
||||
message: "invited by @{username}",
|
||||
values: { username: inviter },
|
||||
});
|
||||
const andMoreLine = (n: number) =>
|
||||
i18n._({
|
||||
id: "email.digest.andMore",
|
||||
message: "and {n} more",
|
||||
values: { n },
|
||||
});
|
||||
const playlistMeta = (owner: string, n: number) =>
|
||||
i18n._({
|
||||
id: "email.digest.playlistMeta",
|
||||
message: "by @{username} · {n, plural, one {# dump} other {# dumps}}",
|
||||
values: { username: owner, n },
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns the digest `content` describes, written as Markdown and drawn in
|
||||
* `look`, with its subject and hidden preheader.
|
||||
*/
|
||||
export function renderDigestEmail(
|
||||
content: DigestContent,
|
||||
look: EmailLook,
|
||||
): RenderedEmail {
|
||||
const monthly = content.cadence === "monthly";
|
||||
const nf = new Intl.NumberFormat(EMAIL_LOCALE);
|
||||
const range = (year: boolean) =>
|
||||
new Intl.DateTimeFormat(
|
||||
EMAIL_LOCALE,
|
||||
year
|
||||
? { month: "short", day: "numeric", year: "numeric" }
|
||||
: { month: "short", day: "numeric" },
|
||||
).formatRange(content.from, content.to);
|
||||
const day = (d: Date) =>
|
||||
new Intl.DateTimeFormat(EMAIL_LOCALE, { weekday: "short" }).format(d);
|
||||
const figure = (n: number, label: string) =>
|
||||
`**${nf.format(n)}** ${escMd(label)}`;
|
||||
const yours = i18n._({ id: "email.digest.yours", message: "yours" });
|
||||
/** A dump as a list item: its thumbnail, title, pill and detail. */
|
||||
const dumpItem = (d: DigestDump, bullet: string, image = true) =>
|
||||
`${bullet} ${image && d.thumbnail ? ` ` : ""}${
|
||||
mdLink(d.title, d.url)
|
||||
}${d.mine ? ` *${escMd(yours)}*` : ""} · ${
|
||||
escMd(
|
||||
`${d.addedTo ? addedToLine(d.addedTo) : byLine(d.poster)}${
|
||||
d.addedTo ? "" : ` · ${d.domain ?? uploadLabel()}`
|
||||
} · ${nf.format(d.votes)} ${countLabel("upvotes", d.votes)} · ${
|
||||
nf.format(d.comments)
|
||||
} ${countLabel("comments", d.comments)}`,
|
||||
)
|
||||
}`;
|
||||
|
||||
const md: string[] = [
|
||||
`*${
|
||||
escMd(
|
||||
`${
|
||||
monthly
|
||||
? i18n._({
|
||||
id: "digest.monthly",
|
||||
message: "Monthly recap",
|
||||
})
|
||||
: i18n._({
|
||||
id: "digest.weekly",
|
||||
message: "Weekly digest",
|
||||
})
|
||||
} · ${range(true)}`,
|
||||
)
|
||||
}*`,
|
||||
`# ${
|
||||
escMd(
|
||||
monthly
|
||||
? i18n._({
|
||||
id: "email.digest.monthly.title",
|
||||
message: "The month on {site}",
|
||||
values: { site: OG_SITE_NAME },
|
||||
})
|
||||
: i18n._({
|
||||
id: "email.digest.weekly.title",
|
||||
message: "Your week, {username}",
|
||||
values: { username: content.reader },
|
||||
}),
|
||||
)
|
||||
}`,
|
||||
];
|
||||
|
||||
const { activity, network, community } = content;
|
||||
if (activity) {
|
||||
md.push(
|
||||
`## ${escMd(i18n._({ id: "email.digest.forYou", message: "For you" }))}`,
|
||||
ACTIVITY_ORDER.filter((k) => (activity.counts[k] ?? 0) > 0)
|
||||
.map((k) =>
|
||||
figure(activity.counts[k]!, countLabel(k, activity.counts[k]!))
|
||||
)
|
||||
.join(" · "),
|
||||
activity.highlights.map((h) => {
|
||||
const target = h.kind === "mentionChat"
|
||||
? mdLink(
|
||||
i18n._({ id: "email.digest.theChat", message: "the chat" }),
|
||||
content.links.chat,
|
||||
)
|
||||
: h.target
|
||||
? mdLink(h.target.title, h.target.url)
|
||||
: "";
|
||||
const line = `- ${
|
||||
highlightSentence(h.kind, `**@${escMd(h.who)}**`, target)
|
||||
} *${escMd(day(h.at))}*`;
|
||||
return h.quote ? `${line}\n > ${escMd(h.quote)}` : line;
|
||||
}).join("\n"),
|
||||
`${
|
||||
mdLink(
|
||||
i18n._({
|
||||
id: "email.digest.seeAll",
|
||||
message:
|
||||
"{n, plural, one {See the notification} other {See all # notifications}}",
|
||||
values: { n: activity.total },
|
||||
}),
|
||||
content.links.notifications,
|
||||
)
|
||||
} →`,
|
||||
);
|
||||
}
|
||||
|
||||
if (network) {
|
||||
md.push(
|
||||
`## ${
|
||||
escMd(i18n._({
|
||||
id: "email.digest.network",
|
||||
message: "From people you follow",
|
||||
}))
|
||||
}`,
|
||||
network.dumps.map((d) => dumpItem(d, "-")).join("\n"),
|
||||
);
|
||||
if (network.more > 0) {
|
||||
md.push(`${
|
||||
mdLink(
|
||||
i18n._({
|
||||
id: "email.digest.more",
|
||||
message: "{n} more on your Followed feed",
|
||||
values: { n: network.more },
|
||||
}),
|
||||
content.links.followed,
|
||||
)
|
||||
} →`);
|
||||
}
|
||||
}
|
||||
|
||||
if (content.top.length > 0) {
|
||||
const [first] = content.top;
|
||||
md.push(
|
||||
`## ${
|
||||
escMd(
|
||||
monthly
|
||||
? i18n._({ id: "email.digest.topMonth", message: "Top this month" })
|
||||
: i18n._({ id: "email.digest.topWeek", message: "Top this week" }),
|
||||
)
|
||||
}`,
|
||||
);
|
||||
// The recap gives its first dump a wide image and the next two a thumbnail.
|
||||
if (monthly && first.thumbnail) md.push(``);
|
||||
md.push(
|
||||
content.top.map((d, i) =>
|
||||
dumpItem(d, `${i + 1}.`, monthly ? i === 1 || i === 2 : true)
|
||||
).join("\n"),
|
||||
);
|
||||
}
|
||||
|
||||
if (community) {
|
||||
const { dumps, upvotes, comments } = community.totals;
|
||||
md.push(
|
||||
`## ${
|
||||
escMd(i18n._({ id: "email.digest.community", message: "Community" }))
|
||||
}`,
|
||||
);
|
||||
if (monthly) {
|
||||
md.push(
|
||||
[
|
||||
figure(
|
||||
dumps,
|
||||
i18n._({
|
||||
id: "email.digest.stat.dumps",
|
||||
message: "{n, plural, one {dump} other {dumps}}",
|
||||
values: { n: dumps },
|
||||
}),
|
||||
),
|
||||
figure(upvotes, countLabel("upvotes", upvotes)),
|
||||
figure(comments, countLabel("comments", comments)),
|
||||
figure(
|
||||
community.chatMessages,
|
||||
i18n._({
|
||||
id: "email.digest.stat.chat",
|
||||
message: "{n, plural, one {chat message} other {chat messages}}",
|
||||
values: { n: community.chatMessages },
|
||||
}),
|
||||
),
|
||||
].join(" · "),
|
||||
);
|
||||
}
|
||||
if (community.members.length > 0) {
|
||||
md.push(
|
||||
`### ${
|
||||
escMd(
|
||||
i18n._({ id: "email.digest.newMembers", message: "New members" }),
|
||||
)
|
||||
}`,
|
||||
[
|
||||
...community.members.map((m) =>
|
||||
`- **@${escMd(m.username)}**${
|
||||
m.invitedBy
|
||||
? ` ${escMd(invitedLine(m.invitedBy, content.reader))}`
|
||||
: ""
|
||||
}`
|
||||
),
|
||||
...(community.membersMore > 0
|
||||
? [`- ${escMd(andMoreLine(community.membersMore))}`]
|
||||
: []),
|
||||
].join("\n"),
|
||||
);
|
||||
}
|
||||
if (community.playlists.length > 0) {
|
||||
md.push(
|
||||
`### ${
|
||||
escMd(i18n._({
|
||||
id: "email.digest.newPlaylists",
|
||||
message: "New public playlists",
|
||||
}))
|
||||
}`,
|
||||
[
|
||||
...community.playlists.map((p) =>
|
||||
`- ${mdLink(p.title, p.url)} · ${
|
||||
escMd(playlistMeta(p.owner, p.dumps))
|
||||
}`
|
||||
),
|
||||
...(community.playlistsMore > 0
|
||||
? [`- ${escMd(andMoreLine(community.playlistsMore))}`]
|
||||
: []),
|
||||
].join("\n"),
|
||||
);
|
||||
}
|
||||
if (!monthly && community.chatMessages > 0) {
|
||||
md.push(
|
||||
`### ${
|
||||
escMd(i18n._({ id: "email.digest.inChat", message: "In the chat" }))
|
||||
}`,
|
||||
`${
|
||||
escMd(i18n._({
|
||||
id: "email.digest.chatWeek",
|
||||
message:
|
||||
"{n, plural, one {# message this week} other {# messages this week}}",
|
||||
values: { n: community.chatMessages },
|
||||
}))
|
||||
} · ${
|
||||
mdLink(
|
||||
i18n._({ id: "email.digest.openChat", message: "Open the chat" }),
|
||||
content.links.chat,
|
||||
)
|
||||
}`,
|
||||
);
|
||||
}
|
||||
if (!monthly && dumps + upvotes + comments > 0) {
|
||||
md.push(`*${
|
||||
escMd(i18n._({
|
||||
id: "email.digest.totals",
|
||||
message:
|
||||
"{dumps, plural, one {# dump} other {# dumps}}, {upvotes, plural, one {# upvote} other {# upvotes}} and {comments, plural, one {# comment} other {# comments}}.",
|
||||
values: { dumps, upvotes, comments },
|
||||
}))
|
||||
}*`);
|
||||
}
|
||||
}
|
||||
|
||||
md.push(
|
||||
"---",
|
||||
escMd(
|
||||
monthly
|
||||
? i18n._({
|
||||
id: "email.digest.monthly.reason",
|
||||
message:
|
||||
"You're getting the monthly recap because it's on in your settings.",
|
||||
})
|
||||
: i18n._({
|
||||
id: "email.digest.weekly.reason",
|
||||
message:
|
||||
"You're getting the weekly digest because it's on in your settings.",
|
||||
}),
|
||||
),
|
||||
`${
|
||||
mdLink(
|
||||
monthly
|
||||
? i18n._({
|
||||
id: "digest.monthly.off",
|
||||
message: "Turn off monthly recaps",
|
||||
})
|
||||
: i18n._({
|
||||
id: "digest.weekly.off",
|
||||
message: "Turn off weekly digests",
|
||||
}),
|
||||
content.links.unsubscribe,
|
||||
)
|
||||
} · ${
|
||||
mdLink(
|
||||
i18n._({ id: "email.settings", message: "Settings" }),
|
||||
content.links.settings,
|
||||
)
|
||||
}`,
|
||||
);
|
||||
|
||||
return new EmailKit(look).render({
|
||||
subject: monthly
|
||||
? i18n._({
|
||||
id: "email.digest.monthly.subject",
|
||||
message: "The month on {site}, {range}",
|
||||
values: { site: OG_SITE_NAME, range: range(false) },
|
||||
})
|
||||
: i18n._({
|
||||
id: "email.digest.weekly.subject",
|
||||
message: "Your week on {site}, {range}",
|
||||
values: { site: OG_SITE_NAME, range: range(false) },
|
||||
}),
|
||||
preheader: preheader(content),
|
||||
markdown: md.join("\n\n"),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the line an inbox shows beside the subject: the counts that make
|
||||
* the digest worth opening, at most three of them.
|
||||
*/
|
||||
function preheader(content: DigestContent): string {
|
||||
const parts: string[] = [];
|
||||
if (content.cadence === "weekly") {
|
||||
for (const k of ["upvotes", "followers", "comments"] as const) {
|
||||
const n = content.activity?.counts[k] ?? 0;
|
||||
if (n > 0) parts.push(`${n} ${countLabel(k, n)}`);
|
||||
}
|
||||
const n = (content.network?.dumps.length ?? 0) +
|
||||
(content.network?.more ?? 0);
|
||||
if (n > 0) {
|
||||
parts.push(i18n._({
|
||||
id: "email.digest.pre.network",
|
||||
message:
|
||||
"{n, plural, one {# new dump from people you follow} other {# new dumps from people you follow}}",
|
||||
values: { n },
|
||||
}));
|
||||
}
|
||||
} else {
|
||||
const members = (content.community?.members.length ?? 0) +
|
||||
(content.community?.membersMore ?? 0);
|
||||
const playlists = (content.community?.playlists.length ?? 0) +
|
||||
(content.community?.playlistsMore ?? 0);
|
||||
if (content.top.length > 0) {
|
||||
parts.push(i18n._({
|
||||
id: "email.digest.pre.topMonth",
|
||||
message:
|
||||
"{n, plural, one {the most upvoted dump of the month} other {the # most upvoted dumps of the month}}",
|
||||
values: { n: content.top.length },
|
||||
}));
|
||||
}
|
||||
if (members > 0) {
|
||||
parts.push(i18n._({
|
||||
id: "email.digest.pre.members",
|
||||
message: "{n, plural, one {# new member} other {# new members}}",
|
||||
values: { n: members },
|
||||
}));
|
||||
}
|
||||
if (playlists > 0) {
|
||||
parts.push(i18n._({
|
||||
id: "email.digest.pre.playlists",
|
||||
message: "{n, plural, one {# new playlist} other {# new playlists}}",
|
||||
values: { n: playlists },
|
||||
}));
|
||||
}
|
||||
}
|
||||
if (parts.length === 0 && content.top.length > 0) {
|
||||
parts.push(i18n._({
|
||||
id: "email.digest.pre.topWeek",
|
||||
message:
|
||||
"{n, plural, one {the most upvoted dump of the week} other {the # most upvoted dumps of the week}}",
|
||||
values: { n: content.top.length },
|
||||
}));
|
||||
}
|
||||
if (parts.length === 0) return "";
|
||||
const line = new Intl.ListFormat(EMAIL_LOCALE, { type: "conjunction" })
|
||||
.format(parts.slice(0, 3));
|
||||
return `${line.charAt(0).toUpperCase()}${line.slice(1)}.`;
|
||||
}
|
||||
33
api/mail/i18n.ts
Normal file
33
api/mail/i18n.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Lets the emails speak the instance's language from the same catalogs as
|
||||
* the interface. Their messages are written in `api/mail/` as
|
||||
* `i18n._({ id, message }, values)`, which `lingui extract` collects into
|
||||
* `locales/<lang>.po` beside the interface's and `lingui compile` turns into
|
||||
* the `locales/<lang>.mjs` imported here. The ids are spelled out, since the
|
||||
* server runs no Lingui macro to hash them.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { type I18n, type Messages, setupI18n } from "@lingui/core";
|
||||
|
||||
import { EMAIL_LOCALE } from "../config.ts";
|
||||
import { LOCALES } from "../../shared/locale.ts";
|
||||
|
||||
const catalogs: [string, Messages][] = await Promise.all(
|
||||
LOCALES.map(async (locale) =>
|
||||
[
|
||||
locale,
|
||||
(await import(`../../locales/${locale}.mjs`)).messages as Messages,
|
||||
] as [string, Messages]
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Translates the emails' messages, in {@link EMAIL_LOCALE}. Every catalog is
|
||||
* loaded, so a test can activate another language.
|
||||
*/
|
||||
export const i18n: I18n = setupI18n({
|
||||
locale: EMAIL_LOCALE,
|
||||
messages: Object.fromEntries(catalogs),
|
||||
});
|
||||
@@ -13,8 +13,20 @@
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { type EmailLocale, OG_SITE_NAME, SITE_EMOJI } from "../config.ts";
|
||||
import type { ColorScheme, StyleName } from "../../shared/theme.ts";
|
||||
import { Marked, Parser, type Token, type Tokens } from "marked";
|
||||
|
||||
import {
|
||||
DEFAULT_STYLE,
|
||||
EMAIL_LOCALE,
|
||||
OG_SITE_NAME,
|
||||
SITE_EMOJI,
|
||||
} from "../config.ts";
|
||||
import {
|
||||
type ColorScheme,
|
||||
DEFAULT_COLOR_SCHEME,
|
||||
type StyleName,
|
||||
} from "../../shared/theme.ts";
|
||||
import type { UserSettings } from "../../shared/settings.ts";
|
||||
import {
|
||||
EMAIL_STYLES,
|
||||
type EmailPalette,
|
||||
@@ -29,19 +41,36 @@ import {
|
||||
export interface RenderedEmail {
|
||||
subject: string;
|
||||
html: string;
|
||||
/** The plain-text part, for clients that show no HTML. */
|
||||
/**
|
||||
* The plain-text part, for clients that show no HTML. It is Markdown, so it
|
||||
* reads as text and renders as the email's outline.
|
||||
*/
|
||||
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.
|
||||
* Passed to {@link EmailKit}, made by {@link lookOf}: the instance's style for
|
||||
* the emails that aren't a user's own, their settings for a digest.
|
||||
*/
|
||||
export interface EmailLook {
|
||||
style: StyleName;
|
||||
scheme: ColorScheme;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the look of a reader's settings. An unset style is the instance's,
|
||||
* as on the site, and an unset scheme the system's; with no settings at all,
|
||||
* as for the welcome and reset emails, both are.
|
||||
*/
|
||||
export function lookOf(
|
||||
settings: Pick<UserSettings, "style" | "colorScheme"> | null = null,
|
||||
): EmailLook {
|
||||
return {
|
||||
style: settings?.style ?? DEFAULT_STYLE,
|
||||
scheme: settings?.colorScheme ?? DEFAULT_COLOR_SCHEME,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@@ -79,14 +108,31 @@ export function esc(value: string): string {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Escapes `value` for Markdown, so that user text in a plain-text part (a
|
||||
* title with `*` or `[`, say) stays text.
|
||||
*/
|
||||
export function escMd(value: string): string {
|
||||
return value.replace(/[\\`*_[\]<>#!|~]/g, "\\$&");
|
||||
}
|
||||
|
||||
/** Returns a Markdown link to `url` labelled with `text`, escaped. */
|
||||
export function mdLink(text: string, url: string): string {
|
||||
const safeUrl = url.replace(
|
||||
/[()\s]/g,
|
||||
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`,
|
||||
);
|
||||
return `[${escMd(text)}](${safeUrl})`;
|
||||
}
|
||||
|
||||
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}.
|
||||
* Draws an email in one {@link EmailLook}. A template writes the email as
|
||||
* Markdown and hands it to {@link EmailKit.render}, which draws each block in
|
||||
* the style. The block methods return HTML: text passed to them must already
|
||||
* be escaped with {@link esc}.
|
||||
*/
|
||||
export class EmailKit {
|
||||
/** The style being drawn. */
|
||||
@@ -98,10 +144,12 @@ export class EmailKit {
|
||||
/** The font stack, for templates that set their own blocks. */
|
||||
readonly font: string;
|
||||
|
||||
constructor(look: EmailLook, readonly locale: EmailLocale) {
|
||||
constructor(look: EmailLook) {
|
||||
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.darkPalette = look.scheme === DEFAULT_COLOR_SCHEME
|
||||
? this.style.dark
|
||||
: null;
|
||||
this.font = this.style.font;
|
||||
}
|
||||
|
||||
@@ -140,7 +188,9 @@ export class EmailKit {
|
||||
style += `border-color:${p[roles.bd] ?? p.rule};`;
|
||||
}
|
||||
const cls = classes.length ? ` class="${classes.join(" ")}"` : "";
|
||||
return `${cls} style="${style}${css}"`;
|
||||
// The colors come last: a shorthand such as `border-top` in `css` would
|
||||
// otherwise reset them.
|
||||
return `${cls} style="${css}${style}"`;
|
||||
}
|
||||
|
||||
/** Returns a link to `href` around `html`, in the link color. */
|
||||
@@ -156,21 +206,6 @@ export class EmailKit {
|
||||
}>${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;
|
||||
@@ -281,30 +316,6 @@ export class EmailKit {
|
||||
}>${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`.
|
||||
@@ -343,16 +354,327 @@ export class EmailKit {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Returns the email written as `markdown`: the Markdown itself is the
|
||||
* plain-text part, and its blocks, drawn in this kit's style, are the HTML.
|
||||
* Each template writes its email once this way. The blocks map as follows.
|
||||
*
|
||||
* - `# Title` is the heading; an `*emphasised*` paragraph above it, the
|
||||
* eyebrow. Elsewhere an emphasised paragraph is a note.
|
||||
* - `## Section` starts a section, with its divider; `### Name` a subhead.
|
||||
* - A link alone in a paragraph is a button, an image alone a wide image,
|
||||
* and a fenced block a box for a raw link.
|
||||
* - A list item whose text starts with an image, then a link, is a row
|
||||
* with that thumbnail and the link as its title; what follows is its
|
||||
* detail, and an emphasised word right after the link a pill. Other items
|
||||
* are sentences, where emphasis marks the date. A numbered list ranks its
|
||||
* rows, and a quote under an item is set as one.
|
||||
* - A bold number is a figure.
|
||||
* - What follows the last `---` is the footer.
|
||||
*/
|
||||
document(
|
||||
{ subject, preheader, eyebrow, title, body, footer }: {
|
||||
render(
|
||||
{ subject, preheader, markdown }: {
|
||||
subject: string;
|
||||
preheader: string;
|
||||
markdown: string;
|
||||
},
|
||||
): RenderedEmail {
|
||||
const cut = markdown.lastIndexOf("\n---\n");
|
||||
const body = cut === -1 ? markdown : markdown.slice(0, cut);
|
||||
const foot = cut === -1 ? "" : markdown.slice(cut + 5);
|
||||
return {
|
||||
subject,
|
||||
html: this.document({
|
||||
subject,
|
||||
preheader,
|
||||
body: this.blocks(this.marked.lexer(body)),
|
||||
footer: this.marked.lexer(foot)
|
||||
.filter((t): t is Tokens.Paragraph => t.type === "paragraph")
|
||||
.map((t) => this.inline(t.tokens, "footer")).join("<br>"),
|
||||
}),
|
||||
text: markdown,
|
||||
};
|
||||
}
|
||||
|
||||
/** How {@link inline} draws emphasis and links, by where they sit. */
|
||||
private mode: "text" | "footer" | "row" | "sentence" = "text";
|
||||
|
||||
/** Draws Markdown's inline tokens with the kit's colors. */
|
||||
private readonly marked: Marked = (() => {
|
||||
// deno-lint-ignore no-this-alias
|
||||
const kit = this;
|
||||
return new Marked({
|
||||
renderer: {
|
||||
link({ href, tokens }) {
|
||||
const html = this.parser.parseInline(tokens);
|
||||
return kit.mode === "footer"
|
||||
? `<a href="${esc(href)}"${
|
||||
kit.paint({ fg: "muted" }, "text-decoration:underline;")
|
||||
}>${html}</a>`
|
||||
: kit.link(html, href);
|
||||
},
|
||||
strong({ tokens }) {
|
||||
const html = this.parser.parseInline(tokens);
|
||||
const figure = /^[\d\s., ]+$/.test(html);
|
||||
return `<b${
|
||||
kit.paint(
|
||||
{ fg: "text" },
|
||||
figure
|
||||
? `font-size:${kit.fs(22)};font-weight:${kit.style.heavy};`
|
||||
: `font-weight:${Math.max(600, kit.style.heavy)};`,
|
||||
)
|
||||
}>${html}</b>`;
|
||||
},
|
||||
em({ tokens }) {
|
||||
const html = this.parser.parseInline(tokens);
|
||||
if (kit.mode === "row") return kit.pill(html);
|
||||
if (kit.mode === "sentence") {
|
||||
return `<span${
|
||||
kit.paint(
|
||||
{ fg: kit.palette.date ? "date" : "muted" },
|
||||
`font-size:${kit.fs(12.5)};white-space:nowrap;${
|
||||
kit.palette.date ? "font-style:italic;" : ""
|
||||
}`,
|
||||
)
|
||||
}>${html}</span>`;
|
||||
}
|
||||
return `<i>${html}</i>`;
|
||||
},
|
||||
codespan({ text }) {
|
||||
return `<code style="font-family:Menlo,Consolas,'Courier New',monospace;">${text}</code>`;
|
||||
},
|
||||
image({ href, text }) {
|
||||
return kit.image(href, text, 104, 78);
|
||||
},
|
||||
},
|
||||
});
|
||||
})();
|
||||
|
||||
private inline(tokens: Token[], mode: EmailKit["mode"]): string {
|
||||
this.mode = mode;
|
||||
try {
|
||||
return Parser.parseInline(tokens, this.marked.defaults);
|
||||
} finally {
|
||||
this.mode = "text";
|
||||
}
|
||||
}
|
||||
|
||||
/** Draws the body's blocks, gathering each `##` section with its content. */
|
||||
private blocks(tokens: Token[]): string {
|
||||
const out: string[] = [];
|
||||
let section: { title: string; parts: string[] } | null = null;
|
||||
let first = true;
|
||||
let headed = false;
|
||||
const push = (html: string) =>
|
||||
section ? section.parts.push(html) : out.push(html);
|
||||
const close = () => {
|
||||
if (!section) return;
|
||||
out.push(this.section(section.title, section.parts.join(""), first));
|
||||
first = false;
|
||||
section = null;
|
||||
};
|
||||
for (const token of tokens) {
|
||||
switch (token.type) {
|
||||
case "heading": {
|
||||
const html = this.inline(token.tokens ?? [], "text");
|
||||
if (token.depth === 1) {
|
||||
headed = true;
|
||||
push(this.heading(html));
|
||||
} else if (token.depth === 2) {
|
||||
close();
|
||||
section = { title: html, parts: [] };
|
||||
} else {
|
||||
push(this.subhead(html));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "paragraph": {
|
||||
const kids = (token.tokens ?? []).filter((t) =>
|
||||
!(t.type === "text" && !t.raw.trim())
|
||||
);
|
||||
const only = kids.length === 1 ? kids[0] : null;
|
||||
if (only?.type === "link") {
|
||||
push(
|
||||
this.button(this.inline(only.tokens ?? [], "text"), only.href),
|
||||
);
|
||||
} else if (only?.type === "image") {
|
||||
push(
|
||||
`${
|
||||
this.image(only.href, only.text, 528, 264)
|
||||
}<div style="height:14px;line-height:14px;font-size:0;"> </div>`,
|
||||
);
|
||||
} else if (only?.type === "em") {
|
||||
const html = this.inline(only.tokens ?? [], "text");
|
||||
push(headed ? this.note(html) : this.eyebrow(html));
|
||||
} else {
|
||||
push(this.para(this.inline(token.tokens ?? [], "text")));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "list":
|
||||
push(this.list(token as Tokens.List));
|
||||
break;
|
||||
case "blockquote":
|
||||
push(this.quote(this.inline(
|
||||
(token.tokens ?? []).flatMap((t) =>
|
||||
"tokens" in t ? t.tokens ?? [] : []
|
||||
),
|
||||
"text",
|
||||
)));
|
||||
break;
|
||||
case "code":
|
||||
push(this.linkBox(esc(token.text)));
|
||||
break;
|
||||
case "html":
|
||||
push(token.text);
|
||||
break;
|
||||
}
|
||||
}
|
||||
close();
|
||||
return out.join("");
|
||||
}
|
||||
|
||||
/** Draws a list as rows, ranked when it is numbered. */
|
||||
private list(list: Tokens.List): string {
|
||||
const start = typeof list.start === "number" ? list.start : 1;
|
||||
return list.items.map((item, i) => {
|
||||
const text = item.tokens.find((t) =>
|
||||
t.type === "text" || t.type === "paragraph"
|
||||
) as Tokens.Text | Tokens.Paragraph | undefined;
|
||||
const quote = item.tokens.find((t) => t.type === "blockquote") as
|
||||
| Tokens.Blockquote
|
||||
| undefined;
|
||||
let rest: Token[] = [...(text?.tokens ?? [])];
|
||||
const skipSpace = () => {
|
||||
while (rest[0]?.type === "text" && !rest[0].raw.trim()) {
|
||||
rest = rest.slice(1);
|
||||
}
|
||||
};
|
||||
skipSpace();
|
||||
const image = rest[0]?.type === "image"
|
||||
? rest.shift() as Tokens.Image
|
||||
: null;
|
||||
skipSpace();
|
||||
const link = rest[0]?.type === "link"
|
||||
? rest.shift() as Tokens.Link
|
||||
: null;
|
||||
|
||||
let content: string;
|
||||
if (link) {
|
||||
const pills: Token[] = [];
|
||||
skipSpace();
|
||||
while (rest[0]?.type === "em") {
|
||||
pills.push(rest.shift()!);
|
||||
skipSpace();
|
||||
}
|
||||
// The detail follows the title after a " · ".
|
||||
if (rest[0]?.type === "text") {
|
||||
const t = rest[0] as Tokens.Text;
|
||||
const trimmed = t.text.replace(/^\s*·\s*/, "");
|
||||
rest[0] = { ...t, text: trimmed, raw: trimmed, tokens: undefined };
|
||||
}
|
||||
content = `<a href="${esc(link.href)}"${
|
||||
this.paint(
|
||||
{ fg: "text" },
|
||||
`font-size:${
|
||||
this.fs(15)
|
||||
};line-height:1.35;font-weight:${this.style.heavy};text-decoration:none;`,
|
||||
)
|
||||
}>${this.inline(link.tokens, "text")}</a>${this.inline(pills, "row")}${
|
||||
rest.length
|
||||
? `<div${
|
||||
this.paint(
|
||||
{ fg: "muted" },
|
||||
`font-size:${this.fs(13)};line-height:1.5;margin-top:3px;`,
|
||||
)
|
||||
}>${this.inline(rest, "text")}</div>`
|
||||
: ""
|
||||
}`;
|
||||
} else {
|
||||
content = `<div${
|
||||
this.paint(
|
||||
{ fg: "sec" },
|
||||
`font-size:${this.fs(14.5)};line-height:1.5;`,
|
||||
)
|
||||
}>${this.inline(rest, "sentence")}</div>`;
|
||||
}
|
||||
if (quote) {
|
||||
content += this.quote(this.inline(
|
||||
quote.tokens.flatMap((t) => "tokens" in t ? t.tokens ?? [] : []),
|
||||
"text",
|
||||
));
|
||||
}
|
||||
|
||||
const size = list.ordered ? [64, 48] : [104, 78];
|
||||
return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:0 0 ${
|
||||
link || image ? 16 : 10
|
||||
}px;"><tr>${
|
||||
list.ordered
|
||||
? `<td width="30" valign="top"${
|
||||
this.paint(
|
||||
{ fg: "accent" },
|
||||
`font-family:${this.font};font-size:${this.fs(20)};font-weight:${
|
||||
Math.max(600, this.style.heavy)
|
||||
};line-height:1.2;`,
|
||||
)
|
||||
}>${start + i}</td>`
|
||||
: ""
|
||||
}${
|
||||
image
|
||||
? `<td width="${size[0]}" valign="top" style="padding-right:${
|
||||
list.ordered ? 12 : 14
|
||||
}px;">${
|
||||
this.image(image.href, image.text, size[0], size[1], link?.href)
|
||||
}</td>`
|
||||
: ""
|
||||
}<td valign="top" style="font-family:${this.font};">${content}</td></tr></table>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
/** Returns the small uppercase line above the heading. */
|
||||
private eyebrow(html: string): string {
|
||||
return `<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;`,
|
||||
)
|
||||
}>${html}</div>`;
|
||||
}
|
||||
|
||||
/** Returns a quoted comment or message. */
|
||||
private quote(html: string): string {
|
||||
return `<div${
|
||||
this.paint(
|
||||
{ fg: "quote" },
|
||||
`font-family:${this.font};font-size:${
|
||||
this.fs(14.5)
|
||||
};line-height:1.5;font-style:italic;margin:4px 0 0;`,
|
||||
)
|
||||
}>“${html}”</div>`;
|
||||
}
|
||||
|
||||
/** Returns a raw link set in a box, for clients that break buttons. */
|
||||
private linkBox(html: string): string {
|
||||
return `<div${
|
||||
this.paint(
|
||||
{ fg: "sec", bg: "soft" },
|
||||
`font-family:Menlo,Consolas,'Courier New',monospace;font-size:12px;line-height:1.5;border-radius:${
|
||||
Math.min(this.style.radius.img, 6)
|
||||
}px;padding:10px 12px;margin:0 0 22px;word-break:break-all;`,
|
||||
)
|
||||
}>${html}</div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the whole HTML document: the brand, the card holding `body`, and
|
||||
* the `footer`. `preheader` is the hidden first line inboxes show beside the
|
||||
* subject.
|
||||
*/
|
||||
private document(
|
||||
{ subject, preheader, body, footer }: {
|
||||
subject: string;
|
||||
preheader: string;
|
||||
eyebrow?: string;
|
||||
title?: string;
|
||||
body: string;
|
||||
footer: string;
|
||||
},
|
||||
@@ -390,7 +712,7 @@ export class EmailKit {
|
||||
: "light";
|
||||
|
||||
return `<!doctype html>
|
||||
<html lang="${this.locale}">
|
||||
<html lang="${EMAIL_LOCALE}">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
@@ -453,19 +775,6 @@ ${
|
||||
};${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${
|
||||
@@ -483,19 +792,6 @@ ${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.
|
||||
|
||||
@@ -6,9 +6,15 @@
|
||||
* @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";
|
||||
import { OG_SITE_NAME } from "../config.ts";
|
||||
import { i18n } from "./i18n.ts";
|
||||
import {
|
||||
EmailKit,
|
||||
escMd,
|
||||
lookOf,
|
||||
mdLink,
|
||||
type RenderedEmail,
|
||||
} from "./layout.ts";
|
||||
|
||||
/**
|
||||
* Returns the reset email of `username`, whose button opens `resetUrl`. The
|
||||
@@ -19,49 +25,60 @@ export function renderPasswordResetEmail(
|
||||
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),
|
||||
"",
|
||||
const markdown = [
|
||||
`# ${
|
||||
escMd(i18n._({ id: "email.reset.title", message: "Reset your password" }))
|
||||
}`,
|
||||
escMd(i18n._({
|
||||
id: "email.reset.hi",
|
||||
message: "Hi {username},",
|
||||
values: { username },
|
||||
})),
|
||||
escMd(i18n._({
|
||||
id: "email.reset.body",
|
||||
message:
|
||||
"Someone asked to reset the password of your {site} account. The button below lets you choose a new one. It works once, for {hours, plural, one {# hour} other {# hours}}.",
|
||||
values: { site: OG_SITE_NAME, hours },
|
||||
})),
|
||||
mdLink(
|
||||
i18n._({ id: "email.reset.button", message: "Reset password" }),
|
||||
resetUrl,
|
||||
"",
|
||||
t.ignore,
|
||||
"",
|
||||
"--",
|
||||
t.reason,
|
||||
].join("\n"),
|
||||
};
|
||||
),
|
||||
`*${
|
||||
escMd(i18n._({
|
||||
id: "email.reset.fallback",
|
||||
message:
|
||||
"If the button doesn't work, paste this link into your browser:",
|
||||
}))
|
||||
}*`,
|
||||
"```\n" + resetUrl + "\n```",
|
||||
`*${
|
||||
escMd(i18n._({
|
||||
id: "email.reset.ignore",
|
||||
message:
|
||||
"If you didn't ask for this, ignore this email. Your password stays the same.",
|
||||
}))
|
||||
}*`,
|
||||
"---",
|
||||
escMd(i18n._({
|
||||
id: "email.reset.reason",
|
||||
message:
|
||||
"You're getting this email because a password reset was requested for this address.",
|
||||
})),
|
||||
].join("\n\n");
|
||||
|
||||
return new EmailKit(lookOf()).render({
|
||||
subject: i18n._({
|
||||
id: "email.reset.subject",
|
||||
message: "Reset your {site} password",
|
||||
values: { site: OG_SITE_NAME },
|
||||
}),
|
||||
preheader: i18n._({
|
||||
id: "email.reset.preheader",
|
||||
message:
|
||||
"The link works once, for {hours, plural, one {# hour} other {# hours}}.",
|
||||
values: { hours },
|
||||
}),
|
||||
markdown,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
/**
|
||||
* 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.",
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -2,8 +2,9 @@
|
||||
* 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.
|
||||
* copied from its theme under `src/themes/` and flattened to plain colors, and
|
||||
* the few touches that make it recognisable once inlined. `layout.ts` reads
|
||||
* them. A test fails when a copied color no longer matches its theme's.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
@@ -227,10 +228,10 @@ export const EMAIL_STYLES: Record<StyleName, EmailStyle> = {
|
||||
outer: "#ffffff",
|
||||
card: "#ffffff",
|
||||
text: "#121212",
|
||||
sec: "#363636",
|
||||
sec: "#5a5a5a",
|
||||
muted: "#767676",
|
||||
accent: "#121212",
|
||||
link: "#121212",
|
||||
link: "#1a1a1a",
|
||||
onAccent: "#ffffff",
|
||||
rule: "#e2e2e2",
|
||||
soft: "#f3f3f3",
|
||||
@@ -240,7 +241,7 @@ export const EMAIL_STYLES: Record<StyleName, EmailStyle> = {
|
||||
outer: "#121212",
|
||||
card: "#1e1e1e",
|
||||
text: "#e6e6e6",
|
||||
sec: "#c4c4c4",
|
||||
sec: "#ababab",
|
||||
muted: "#8a8a8a",
|
||||
accent: "#ececec",
|
||||
link: "#ececec",
|
||||
|
||||
@@ -1,78 +1,76 @@
|
||||
/**
|
||||
* 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.
|
||||
* language. It opens with the instance's `GERBEUR_WELCOME_EMAIL_BODY`, or the
|
||||
* built-in body, then says the digests are on, since they are by default, and
|
||||
* where to turn them off.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { Marked } from "marked";
|
||||
|
||||
import { FRONTEND_URL, OG_SITE_NAME, WELCOME_EMAIL_BODY } from "../config.ts";
|
||||
import { i18n } from "./i18n.ts";
|
||||
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";
|
||||
EmailKit,
|
||||
escMd,
|
||||
lookOf,
|
||||
mdLink,
|
||||
type RenderedEmail,
|
||||
} from "./layout.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.
|
||||
* Returns the welcome email of `username`. The instance's body has
|
||||
* `{{username}}` and `{{site_name}}` filled in; raw HTML in it passes
|
||||
* through, since it comes from whoever runs the instance, never from a user.
|
||||
*/
|
||||
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);
|
||||
// A username may hold a `_`, which Markdown would read as emphasis.
|
||||
const body = WELCOME_EMAIL_BODY
|
||||
? WELCOME_EMAIL_BODY
|
||||
.replaceAll("{{username}}", escMd(username))
|
||||
.replaceAll("{{site_name}}", escMd(OG_SITE_NAME))
|
||||
: i18n._({
|
||||
id: "email.welcome.body",
|
||||
message:
|
||||
"# Welcome to {site}!\n\nHi **{username}**,\n\nYour account has been created successfully. Welcome aboard!",
|
||||
values: { site: escMd(OG_SITE_NAME), username: escMd(username) },
|
||||
});
|
||||
const markdown = [
|
||||
body,
|
||||
mdLink(
|
||||
i18n._({
|
||||
id: "email.welcome.button",
|
||||
message: "Open {site}",
|
||||
values: { site: OG_SITE_NAME },
|
||||
}),
|
||||
FRONTEND_URL,
|
||||
),
|
||||
`*${
|
||||
escMd(i18n._({
|
||||
id: "email.welcome.digests",
|
||||
message:
|
||||
"Once a week you'll get a digest of what happened here, and once a month a recap of the most upvoted dumps. You can turn either off in your settings.",
|
||||
}))
|
||||
}*`,
|
||||
"---",
|
||||
escMd(i18n._({
|
||||
id: "email.welcome.reason",
|
||||
message:
|
||||
"You're getting this email because an account was created on {site} with this address.",
|
||||
values: { site: OG_SITE_NAME },
|
||||
})),
|
||||
].join("\n\n");
|
||||
|
||||
return {
|
||||
subject,
|
||||
html: kit.document({
|
||||
subject,
|
||||
preheader: t.preheader,
|
||||
body,
|
||||
footer: kit.footer(esc(t.reason(OG_SITE_NAME))),
|
||||
return new EmailKit(lookOf()).render({
|
||||
subject: i18n._({
|
||||
id: "email.welcome.subject",
|
||||
message: "Welcome to {site}",
|
||||
values: { site: OG_SITE_NAME },
|
||||
}),
|
||||
text: `${markdown}\n\n${t.button(OG_SITE_NAME)}: ${FRONTEND_URL}\n\n--\n${
|
||||
t.reason(OG_SITE_NAME)
|
||||
}`,
|
||||
};
|
||||
preheader: i18n._({
|
||||
id: "email.welcome.preheader",
|
||||
message: "Your account is ready.",
|
||||
}),
|
||||
markdown,
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user