mirror of
https://github.com/prdlk/leetcode.git
synced 2026-09-16 23:16:26 +00:00
mise ~/.config/mise/config.toml tools: crush@0.91.0
feat(api): add React Email rendering and PNG heatmap endpoint
This commit is contained in:
+164
-47
@@ -1,17 +1,21 @@
|
||||
/**
|
||||
* Hand-rolled SVG chart generation for the SRS Worker.
|
||||
*
|
||||
* Feeds four endpoints — /chart/progress.svg, /chart/ladder.svg,
|
||||
* /chart/heatmap.svg, /badge/gate.svg — each served with
|
||||
* `Cache-Control: public, max-age=300`.
|
||||
* Feeds five endpoints — /chart/progress.svg, /chart/ladder.svg,
|
||||
* /chart/heatmap.svg, /chart/heatmap.png, /badge/gate.svg — each served with
|
||||
* `Cache-Control: public, max-age=300`. The heatmap has a raster twin because
|
||||
* every major email client blocks SVG, so the digest cannot embed the vector.
|
||||
*
|
||||
* Everything is string-built: no chart library, no runtime imports. The only
|
||||
* dynamic values entering the markup are numbers, percentages, and dates the
|
||||
* Worker itself computes, plus the fixed phase/stage labels — so nothing here
|
||||
* needs XML escaping. Styling is shadcn dark zinc to match the README's
|
||||
* shieldcn badges: rounded #09090b cards, #fafafa/#a1a1aa text, GitHub
|
||||
* dark-mode green ramp. Every function renders valid SVG on a zero-row DB.
|
||||
* The SVG is string-built: no chart library, no dependencies, and the one
|
||||
* import is the hand-rolled PNG encoder next door. The only dynamic values
|
||||
* entering the markup are numbers, percentages, and dates the Worker itself
|
||||
* computes, plus the fixed phase/stage labels — so nothing here needs XML
|
||||
* escaping. Styling is shadcn dark zinc to match the README's shieldcn
|
||||
* badges: rounded #09090b cards, #fafafa/#a1a1aa text, GitHub dark-mode
|
||||
* green ramp. Every function renders on a zero-row DB.
|
||||
*/
|
||||
import { Canvas, textWidth } from "./png.ts";
|
||||
|
||||
// D1Database comes from the generated worker-configuration.d.ts runtime types.
|
||||
|
||||
const FONT = "Verdana,DejaVu Sans,sans-serif";
|
||||
@@ -195,9 +199,43 @@ export async function ladderChart(db: D1Database): Promise<string> {
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
|
||||
export async function heatmapChart(db: D1Database, start: string, days: number): Promise<string> {
|
||||
// YYYY-MM-DD → UTC midnight; all per-day dates derive from this timestamp,
|
||||
// so local-timezone drift never shifts a cell.
|
||||
// Layout in CSS pixels. heatmapPng multiplies every one of these by its device
|
||||
// scale, so the vector and raster pictures cannot drift apart.
|
||||
const HEAT_W = 560;
|
||||
const HEAT_H = 160;
|
||||
const HEAT_GRID_X = 34;
|
||||
const HEAT_GRID_Y = 24;
|
||||
const HEAT_CELL = 16;
|
||||
const HEAT_STEP = 19; // cell + 3px gap
|
||||
|
||||
// Grid row → left-hand label; both renderers print only these three.
|
||||
const WEEKDAYS: [number, string][] = [
|
||||
[0, "Mon"],
|
||||
[2, "Wed"],
|
||||
[4, "Fri"],
|
||||
];
|
||||
|
||||
/** One grid square: column, Mon-based row, and index into GREENS. */
|
||||
interface HeatmapCell {
|
||||
col: number;
|
||||
row: number;
|
||||
level: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The heatmap's whole data model — one cell per campaign day, plus the week
|
||||
* count that positions the legend — shared by both renderers.
|
||||
*
|
||||
* Every per-day date derives from one UTC-midnight timestamp, so local-timezone
|
||||
* drift never shifts a cell. The campaign starts on a Monday, so day i sits at
|
||||
* column i/7; the row comes from the real weekday, so an off-Monday start still
|
||||
* lands correctly.
|
||||
*/
|
||||
async function heatmapCells(
|
||||
db: D1Database,
|
||||
start: string,
|
||||
days: number,
|
||||
): Promise<{ cells: HeatmapCell[]; weeks: number }> {
|
||||
const [sy, sm, sd] = start.split("-").map(Number);
|
||||
const base = Date.UTC(sy!, sm! - 1, sd!);
|
||||
const end = new Date(base + (days - 1) * DAY_MS).toISOString().slice(0, 10);
|
||||
@@ -209,56 +247,135 @@ export async function heatmapChart(db: D1Database, start: string, days: number):
|
||||
|
||||
const byDate = new Map(results.map((r) => [r.date, r.attempts]));
|
||||
|
||||
const width = 560;
|
||||
const height = 160;
|
||||
const gridX = 34;
|
||||
const gridY = 24;
|
||||
const cell = 16;
|
||||
const step = 19; // cell + 3px gap
|
||||
const weeks = Math.ceil(days / 7);
|
||||
|
||||
const parts = [svgOpen(width, height)];
|
||||
|
||||
// Week numbers across the top, Mon/Wed/Fri down the left.
|
||||
for (let w = 0; w < weeks; w++) {
|
||||
parts.push(text(gridX + w * step + cell / 2, gridY - 7, `W${w + 1}`, { size: 10, fill: MUTED, anchor: "middle" }));
|
||||
}
|
||||
const weekdays: [number, string][] = [
|
||||
[0, "Mon"],
|
||||
[2, "Wed"],
|
||||
[4, "Fri"],
|
||||
];
|
||||
for (const [row, label] of weekdays) {
|
||||
parts.push(text(gridX - 6, gridY + row * step + cell - 4, label, { size: 10, fill: MUTED, anchor: "end" }));
|
||||
}
|
||||
|
||||
// One cell per campaign day; the start date is a Monday, so day i sits at
|
||||
// column i/7, row i%7 — but the row is derived from the real weekday so an
|
||||
// off-Monday start still lands correctly.
|
||||
const cells: HeatmapCell[] = [];
|
||||
for (let i = 0; i < days; i++) {
|
||||
const day = new Date(base + i * DAY_MS);
|
||||
const attempts = byDate.get(day.toISOString().slice(0, 10)) ?? 0;
|
||||
const col = Math.floor(i / 7);
|
||||
const row = (day.getUTCDay() + 6) % 7; // Mon = 0
|
||||
const color = GREENS[Math.min(attempts, 4)];
|
||||
cells.push({
|
||||
col: Math.floor(i / 7),
|
||||
row: (day.getUTCDay() + 6) % 7, // Mon = 0
|
||||
level: Math.min(attempts, 4),
|
||||
});
|
||||
}
|
||||
|
||||
return { cells, weeks: Math.ceil(days / 7) };
|
||||
}
|
||||
|
||||
export async function heatmapChart(db: D1Database, start: string, days: number): Promise<string> {
|
||||
const { cells, weeks } = await heatmapCells(db, start, days);
|
||||
|
||||
const parts = [svgOpen(HEAT_W, HEAT_H)];
|
||||
|
||||
// Week numbers across the top, Mon/Wed/Fri down the left.
|
||||
for (let w = 0; w < weeks; w++) {
|
||||
parts.push(
|
||||
`<rect x="${gridX + col * step}" y="${gridY + row * step}" width="${cell}" height="${cell}" rx="2" fill="${color}"/>`,
|
||||
text(HEAT_GRID_X + w * HEAT_STEP + HEAT_CELL / 2, HEAT_GRID_Y - 7, `W${w + 1}`, {
|
||||
size: 10,
|
||||
fill: MUTED,
|
||||
anchor: "middle",
|
||||
}),
|
||||
);
|
||||
}
|
||||
for (const [row, label] of WEEKDAYS) {
|
||||
parts.push(
|
||||
text(HEAT_GRID_X - 6, HEAT_GRID_Y + row * HEAT_STEP + HEAT_CELL - 4, label, {
|
||||
size: 10,
|
||||
fill: MUTED,
|
||||
anchor: "end",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
for (const { col, row, level } of cells) {
|
||||
parts.push(
|
||||
`<rect x="${HEAT_GRID_X + col * HEAT_STEP}" y="${HEAT_GRID_Y + row * HEAT_STEP}" width="${HEAT_CELL}" height="${HEAT_CELL}" rx="2" fill="${GREENS[level]}"/>`,
|
||||
);
|
||||
}
|
||||
|
||||
// Less → More ramp fills the space right of the grid.
|
||||
const legendX = gridX + weeks * step + 40;
|
||||
const legendY = gridY + 3 * step;
|
||||
parts.push(text(legendX - 6, legendY + cell - 4, "Less", { size: 10, fill: MUTED, anchor: "end" }));
|
||||
const legendX = HEAT_GRID_X + weeks * HEAT_STEP + 40;
|
||||
const legendY = HEAT_GRID_Y + 3 * HEAT_STEP;
|
||||
parts.push(text(legendX - 6, legendY + HEAT_CELL - 4, "Less", { size: 10, fill: MUTED, anchor: "end" }));
|
||||
GREENS.forEach((color, i) => {
|
||||
parts.push(`<rect x="${legendX + i * step}" y="${legendY}" width="${cell}" height="${cell}" rx="2" fill="${color}"/>`);
|
||||
parts.push(
|
||||
`<rect x="${legendX + i * HEAT_STEP}" y="${legendY}" width="${HEAT_CELL}" height="${HEAT_CELL}" rx="2" fill="${color}"/>`,
|
||||
);
|
||||
});
|
||||
parts.push(text(legendX + GREENS.length * step + 3, legendY + cell - 4, "More", { size: 10, fill: MUTED }));
|
||||
parts.push(text(legendX + GREENS.length * HEAT_STEP + 3, legendY + HEAT_CELL - 4, "More", { size: 10, fill: MUTED }));
|
||||
|
||||
parts.push("</svg>");
|
||||
return parts.join("");
|
||||
}
|
||||
|
||||
// The PNG carries no alpha channel, so whatever the rounded card does not cover
|
||||
// has to be painted with the colour sitting behind the image: the digest
|
||||
// email's GitHub-dark card.
|
||||
const EMAIL_CARD = "#0d1117";
|
||||
|
||||
// Device-pixel multiplier. The email hands the image the full 552px card
|
||||
// width, so 3x lands a little over 2x density on a retina screen; the labels
|
||||
// stay 10 CSS px, the size of the SVG's. Flat colour compresses to a few KB
|
||||
// either way, so the extra resolution is close to free.
|
||||
const HEAT_SCALE = 3;
|
||||
|
||||
/**
|
||||
* The same picture as heatmapChart, rastered for email.
|
||||
*
|
||||
* Two deliberate departures from the SVG. The canvas is trimmed to the width
|
||||
* the content actually occupies instead of HEAT_W: the README's SVG sits in a
|
||||
* narrow table cell and scales up, whereas the email gives the image the full
|
||||
* 552px card, and the SVG's slack right margin would otherwise shrink the
|
||||
* grid to nothing. And the bitmap font hangs off a top-left origin rather than
|
||||
* a baseline, so each SVG baseline becomes "baseline minus one cap height".
|
||||
*/
|
||||
export async function heatmapPng(db: D1Database, start: string, days: number): Promise<Uint8Array> {
|
||||
const { cells, weeks } = await heatmapCells(db, start, days);
|
||||
|
||||
const s = HEAT_SCALE;
|
||||
const gridX = HEAT_GRID_X * s;
|
||||
const gridY = HEAT_GRID_Y * s;
|
||||
const cell = HEAT_CELL * s;
|
||||
const step = HEAT_STEP * s;
|
||||
const capH = 7 * s;
|
||||
|
||||
const legendX = gridX + weeks * step + 40 * s;
|
||||
const legendY = gridY + 3 * step;
|
||||
const moreX = legendX + GREENS.length * step + 3 * s;
|
||||
const width = moreX + textWidth("More", s) + gridX;
|
||||
const height = HEAT_H * s;
|
||||
|
||||
const canvas = new Canvas(width, height, EMAIL_CARD);
|
||||
canvas.rect(0, 0, width, height, BG, 6 * s);
|
||||
|
||||
for (let w = 0; w < weeks; w++) {
|
||||
const label = `W${w + 1}`;
|
||||
const middle = gridX + w * step + cell / 2;
|
||||
canvas.text(middle - textWidth(label, s) / 2, gridY - 7 * s - capH, label, MUTED, s);
|
||||
}
|
||||
for (const [row, label] of WEEKDAYS) {
|
||||
canvas.text(
|
||||
gridX - 6 * s - textWidth(label, s),
|
||||
gridY + row * step + cell - 4 * s - capH,
|
||||
label,
|
||||
MUTED,
|
||||
s,
|
||||
);
|
||||
}
|
||||
|
||||
for (const { col, row, level } of cells) {
|
||||
canvas.rect(gridX + col * step, gridY + row * step, cell, cell, GREENS[level]!, 2 * s);
|
||||
}
|
||||
|
||||
const legendBase = legendY + cell - 4 * s - capH;
|
||||
canvas.text(legendX - 6 * s - textWidth("Less", s), legendBase, "Less", MUTED, s);
|
||||
GREENS.forEach((color, i) => {
|
||||
canvas.rect(legendX + i * step, legendY, cell, cell, color, 2 * s);
|
||||
});
|
||||
canvas.text(moreX, legendBase, "More", MUTED, s);
|
||||
|
||||
return await canvas.encode();
|
||||
}
|
||||
|
||||
// ── gate badge: shieldcn-style dark pill ─────────────────────────
|
||||
|
||||
export async function gateBadge(db: D1Database): Promise<string> {
|
||||
|
||||
+74
-120
@@ -1,10 +1,13 @@
|
||||
/**
|
||||
* The daily digest email — built from D1 + the bundled schedule, sent at
|
||||
* 8 AM ET via the send_email binding. Plain inline-styled HTML that renders
|
||||
* clean in Gmail mobile; always sent with a text alternative.
|
||||
* 8 AM ET via the send_email binding. This module owns data only: it turns
|
||||
* D1 rows into a `DigestData` and hands it to email.tsx, which renders both
|
||||
* the HTML and the plain-text alternative from that single tree (React Email
|
||||
* `render`), so the two can never drift.
|
||||
*
|
||||
* Retrieval rules: review and drill lines carry number + difficulty only —
|
||||
* never the topic, never a solution link. The learning day's core list is
|
||||
* Retrieval rules: review and drill rows carry number + difficulty only —
|
||||
* never the topic, never a solution link. `DigestRow` has no field for
|
||||
* either, so the rule holds by construction. The learning day's core list is
|
||||
* the only labeled section. Reviews + drills ≤ 6, reviews first, overflow
|
||||
* simply stays due (oldest tomorrow). Sunday is a two-line rest note.
|
||||
*
|
||||
@@ -26,62 +29,58 @@ import {
|
||||
streak,
|
||||
weekdayOf,
|
||||
} from "./srs.ts";
|
||||
import { type DigestData, type DigestRow, renderDigest } from "./email.tsx";
|
||||
import { signLink } from "./links.ts";
|
||||
|
||||
const DAILY_CAP = 6;
|
||||
|
||||
function cap(difficulty: string): string {
|
||||
return difficulty[0]!.toUpperCase() + difficulty.slice(1);
|
||||
}
|
||||
|
||||
export interface Digest {
|
||||
subject: string;
|
||||
html: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** One-tap pass/fail anchor pair for a problem line. */
|
||||
async function tapLinks(env: Env, lc: number, date: string): Promise<string> {
|
||||
const pass = await signLink(env.LINK_KEY, lc, "pass", date);
|
||||
const fail = await signLink(env.LINK_KEY, lc, "fail", date);
|
||||
const url = (r: string, sig: string) =>
|
||||
`${env.PUBLIC_URL}/log?p=${lc}&r=${r}&d=${date}&sig=${sig}`;
|
||||
return (
|
||||
`<a href="${url("pass", pass)}" style="color:#1a7f37;font-weight:bold">pass</a>` +
|
||||
` · <a href="${url("fail", fail)}" style="color:#cf222e;font-weight:bold">fail</a>`
|
||||
);
|
||||
/** A problem row plus its signed one-tap pass/fail URLs. */
|
||||
async function tapRow(env: Env, p: ProblemRow, date: string, staged: boolean): Promise<DigestRow> {
|
||||
const [pass, fail] = await Promise.all([
|
||||
signLink(env.LINK_KEY, p.lc_number, "pass", date),
|
||||
signLink(env.LINK_KEY, p.lc_number, "fail", date),
|
||||
]);
|
||||
const base = `${env.PUBLIC_URL}/log?p=${p.lc_number}&d=${date}&r=`;
|
||||
return {
|
||||
lc: p.lc_number,
|
||||
difficulty: p.difficulty,
|
||||
...(staged ? { stage: p.stage } : {}),
|
||||
passUrl: `${base}pass&sig=${pass}`,
|
||||
failUrl: `${base}fail&sig=${fail}`,
|
||||
};
|
||||
}
|
||||
|
||||
export async function buildDigest(env: Env, date: string): Promise<Digest> {
|
||||
/** Everything the email needs, read straight out of D1 and the schedule. */
|
||||
export async function collectDigest(env: Env, date: string): Promise<DigestData> {
|
||||
const db = env.DB;
|
||||
const day = campaignDay(date);
|
||||
const week = campaignWeek(date);
|
||||
const header = `${prettyDate(date)} — Day ${day}/${CAMPAIGN_DAYS} · Week ${week}`;
|
||||
const rest = weekdayOf(date) === 0;
|
||||
|
||||
if (weekdayOf(date) === 0) {
|
||||
return {
|
||||
subject: `SRS — ${prettyDate(date)} — rest day`,
|
||||
html: `<p><strong>${header}</strong></p><p>Rest day. Nothing is due. Overdue reviews moved to Monday.</p>`,
|
||||
text: `${header}\nRest day. Nothing is due. Overdue reviews moved to Monday.`,
|
||||
};
|
||||
}
|
||||
// Reviews take the cap first; drills fill whatever is left.
|
||||
const due = rest ? [] : await dueReviews(db, date);
|
||||
const capped = due.slice(0, DAILY_CAP);
|
||||
const drills = rest ? [] : await pickDrills(db, date, DAILY_CAP - capped.length);
|
||||
|
||||
const due = await dueReviews(db, date);
|
||||
const reviews = due.slice(0, DAILY_CAP);
|
||||
const carried = due.length - reviews.length;
|
||||
const drills = await pickDrills(db, date, DAILY_CAP - reviews.length);
|
||||
const currentStreak = await streak(db, date);
|
||||
const data: DigestData = {
|
||||
day: prettyDate(date),
|
||||
progress: `Day ${campaignDay(date)} of ${CAMPAIGN_DAYS} · Week ${campaignWeek(date)}`,
|
||||
streak: await streak(db, date),
|
||||
rest,
|
||||
reviews: await Promise.all(capped.map((p) => tapRow(env, p, date, true))),
|
||||
carried: due.length - capped.length,
|
||||
drills: await Promise.all(drills.map((p) => tapRow(env, p, date, false))),
|
||||
yesterday: { total: 0, failed: [] },
|
||||
heatmapUrl: `${env.PUBLIC_URL}/chart/heatmap.png`,
|
||||
progressUrl: `${env.DOCS_URL}/progress`,
|
||||
};
|
||||
|
||||
const htmlParts: string[] = [];
|
||||
const textParts: string[] = [];
|
||||
htmlParts.push(
|
||||
`<h2 style="margin:0 0 4px">${header}</h2>`,
|
||||
`<p style="margin:0 0 16px;color:#57606a">🔥 streak: ${currentStreak} day${currentStreak === 1 ? "" : "s"}</p>`,
|
||||
);
|
||||
textParts.push(header, `streak: ${currentStreak}`);
|
||||
|
||||
// New topic — the only labeled section.
|
||||
const topicIssue = SCHEDULE[date];
|
||||
// New topic — the only section allowed to name problems and link them.
|
||||
const topicIssue = rest ? undefined : SCHEDULE[date];
|
||||
if (topicIssue !== undefined) {
|
||||
const topic = await db
|
||||
.prepare("SELECT name FROM topics WHERE issue = ?")
|
||||
@@ -93,57 +92,14 @@ export async function buildDigest(env: Env, date: string): Promise<Digest> {
|
||||
)
|
||||
.bind(topicIssue)
|
||||
.all<ProblemRow>();
|
||||
const links = core
|
||||
.map(
|
||||
(p) =>
|
||||
`<a href="https://github.com/${env.REPO}/issues/${p.issue}">LC ${p.lc_number}</a>${p.stage === "new" ? "" : " ✓"}`,
|
||||
)
|
||||
.join(" · ");
|
||||
htmlParts.push(
|
||||
`<h3 style="margin:16px 0 4px">New topic: ${topic?.name ?? `#${topicIssue}`}</h3>`,
|
||||
`<p style="margin:0">Core: ${links}</p>`,
|
||||
);
|
||||
textParts.push(`New topic: ${topic?.name ?? topicIssue} — core: ${core.map((p) => `LC ${p.lc_number}`).join(", ")}`);
|
||||
}
|
||||
|
||||
// Reviews due — unlabeled lines, one-tap links.
|
||||
htmlParts.push(`<h3 style="margin:16px 0 4px">Reviews due (${reviews.length})</h3>`);
|
||||
textParts.push(`Reviews due (${reviews.length})`);
|
||||
if (reviews.length) {
|
||||
htmlParts.push(
|
||||
`<p style="margin:0 0 4px;color:#57606a">Solve each from scratch. Do not open your old solution first.</p>`,
|
||||
);
|
||||
for (const p of reviews) {
|
||||
htmlParts.push(
|
||||
`<p style="margin:2px 0">LC ${p.lc_number} — ${cap(p.difficulty)} — stage ${p.stage} — ${await tapLinks(env, p.lc_number, date)}</p>`,
|
||||
);
|
||||
textParts.push(`- LC ${p.lc_number} — ${cap(p.difficulty)} — stage ${p.stage}`);
|
||||
}
|
||||
if (carried > 0) {
|
||||
htmlParts.push(`<p style="margin:4px 0;color:#57606a">${carried} more carried to tomorrow (cap ${DAILY_CAP}).</p>`);
|
||||
textParts.push(`${carried} more carried to tomorrow.`);
|
||||
}
|
||||
} else {
|
||||
htmlParts.push(`<p style="margin:0">None.</p>`);
|
||||
textParts.push("none");
|
||||
}
|
||||
|
||||
// Blind drills — unlabeled.
|
||||
htmlParts.push(`<h3 style="margin:16px 0 4px">Blind drills (${drills.length})</h3>`);
|
||||
textParts.push(`Blind drills (${drills.length})`);
|
||||
if (drills.length) {
|
||||
htmlParts.push(
|
||||
`<p style="margin:0 0 4px;color:#57606a">No topic given. Name the pattern out loud before you code.</p>`,
|
||||
);
|
||||
for (const p of drills) {
|
||||
htmlParts.push(
|
||||
`<p style="margin:2px 0">LC ${p.lc_number} — ${cap(p.difficulty)} — ${await tapLinks(env, p.lc_number, date)}</p>`,
|
||||
);
|
||||
textParts.push(`- LC ${p.lc_number} — ${cap(p.difficulty)}`);
|
||||
}
|
||||
} else {
|
||||
htmlParts.push(`<p style="margin:0">None today.</p>`);
|
||||
textParts.push("none");
|
||||
data.topic = {
|
||||
name: topic?.name ?? `#${topicIssue}`,
|
||||
core: core.map((p) => ({
|
||||
lc: p.lc_number,
|
||||
url: `https://github.com/${env.REPO}/issues/${p.issue}`,
|
||||
solved: p.stage !== "new",
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
// Saturday: the review issue already exists (created at midnight ET).
|
||||
@@ -153,40 +109,38 @@ export async function buildDigest(env: Env, date: string): Promise<Digest> {
|
||||
.bind(isoWeek(date))
|
||||
.first<{ issue: number }>();
|
||||
if (gate) {
|
||||
htmlParts.push(
|
||||
`<h3 style="margin:16px 0 4px">Saturday gate</h3>`,
|
||||
`<p style="margin:0"><a href="https://github.com/${env.REPO}/issues/${gate.issue}">Review — Week ${campaignWeek(date)} (#${gate.issue})</a> — timed, blind, then close the issue.</p>`,
|
||||
);
|
||||
textParts.push(`Saturday gate: https://github.com/${env.REPO}/issues/${gate.issue}`);
|
||||
data.gate = {
|
||||
week: campaignWeek(date),
|
||||
url: `https://github.com/${env.REPO}/issues/${gate.issue}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Footer: yesterday's log, gate rate to date, progress page.
|
||||
const yesterday = addDays(date, -1);
|
||||
// Footer: yesterday's log summarised (failures named — they are the
|
||||
// actionable part) and the gate rate to date.
|
||||
const { results: logged } = await db
|
||||
.prepare("SELECT lc_number, kind, result FROM attempts WHERE date = ? ORDER BY id")
|
||||
.bind(yesterday)
|
||||
.all<{ lc_number: number; kind: string; result: string }>();
|
||||
.prepare("SELECT lc_number, result FROM attempts WHERE date = ? ORDER BY id")
|
||||
.bind(addDays(date, -1))
|
||||
.all<{ lc_number: number; result: string }>();
|
||||
data.yesterday = {
|
||||
total: logged.length,
|
||||
failed: logged.filter((a) => a.result !== "pass").map((a) => a.lc_number),
|
||||
};
|
||||
const lastGate = await db
|
||||
.prepare("SELECT pass_rate FROM gates WHERE pass_rate IS NOT NULL ORDER BY week DESC LIMIT 1")
|
||||
.first<{ pass_rate: number }>();
|
||||
const footerBits = [
|
||||
logged.length
|
||||
? `Yesterday: ${logged.map((a) => `LC ${a.lc_number} ${a.result === "pass" ? "✅" : "❌"}`).join(" · ")}`
|
||||
: "Yesterday: no attempts logged.",
|
||||
lastGate ? `Gate pass rate: ${Math.round(lastGate.pass_rate * 100)}%` : "No gates scored yet.",
|
||||
];
|
||||
htmlParts.push(
|
||||
`<hr style="border:none;border-top:1px solid #d0d7de;margin:16px 0">`,
|
||||
`<p style="margin:0;color:#57606a;font-size:13px">${footerBits.join(" · ")} · <a href="${env.DOCS_URL}/progress">progress page</a></p>`,
|
||||
);
|
||||
textParts.push(...footerBits, `progress: ${env.DOCS_URL}/progress`);
|
||||
if (lastGate) data.gateRate = lastGate.pass_rate;
|
||||
|
||||
const load = reviews.length + drills.length;
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function buildDigest(env: Env, date: string): Promise<Digest> {
|
||||
const data = await collectDigest(env, date);
|
||||
const { html, text } = await renderDigest(data);
|
||||
return {
|
||||
subject: `SRS — ${prettyDate(date)} — ${load} on deck`,
|
||||
html: `<div style="font-family:-apple-system,Segoe UI,Helvetica,Arial,sans-serif;max-width:600px;margin:0 auto;padding:12px">${htmlParts.join("\n")}</div>`,
|
||||
text: textParts.join("\n"),
|
||||
subject: `(Day ${campaignDay(date)}/${CAMPAIGN_DAYS}) LeetCode Daily Digest`,
|
||||
html,
|
||||
text,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,451 @@
|
||||
/**
|
||||
* Presentation layer for the daily digest — React Email components rendered
|
||||
* to HTML (and to the plain-text alternative) inside the Worker.
|
||||
*
|
||||
* This file owns *only* layout and wording. Every number, URL and signature
|
||||
* is computed in digest.ts and handed over as `DigestData`, so the retrieval
|
||||
* rules (review/drill rows carry number + difficulty only — never the topic,
|
||||
* never a solution link) are enforced by what the data model can express:
|
||||
* `DigestRow` has no title and no issue field.
|
||||
*
|
||||
* Dark by design. The theme is hard-coded rather than left to the client's
|
||||
* dark-mode heuristics: `color-scheme: dark` tells Apple Mail and Outlook not
|
||||
* to re-invert it, and the canvas colour is painted by a full-width <Section>
|
||||
* table because Gmail drops styles on <body>.
|
||||
*
|
||||
* Other email constraints that shape the markup: inline styles only (clients
|
||||
* strip <style>), real <table> layout for the problem lists so Outlook and
|
||||
* Gmail agree on column alignment, React Email's <Button> for the one-tap
|
||||
* links (it emits the MSO padding conditionals a bare <a> lacks), and the
|
||||
* heatmap arrives as PNG — every major client refuses remote SVG.
|
||||
*/
|
||||
import {
|
||||
Body,
|
||||
Button,
|
||||
Container,
|
||||
Head,
|
||||
Heading,
|
||||
Hr,
|
||||
Html,
|
||||
Img,
|
||||
Link,
|
||||
Preview,
|
||||
Section,
|
||||
Text,
|
||||
} from "@react-email/components";
|
||||
import { render } from "@react-email/render";
|
||||
import type { CSSProperties } from "react";
|
||||
|
||||
// ── palette (GitHub dark) ────────────────────────────────────────
|
||||
const CANVAS = "#010409";
|
||||
const CARD = "#0d1117";
|
||||
const BORDER = "#30363d";
|
||||
const RULE = "#21262d";
|
||||
const INK = "#e6edf3";
|
||||
const MUTED = "#8b949e";
|
||||
const LINK = "#58a6ff";
|
||||
const GREEN = "#3fb950";
|
||||
const AMBER = "#d29922";
|
||||
const RED = "#f85149";
|
||||
const PASS_BG = "#238636";
|
||||
const FAIL_BG = "#da3633";
|
||||
const GATE_BG = "#1f6feb";
|
||||
|
||||
const FONT = '-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif';
|
||||
|
||||
// Outlook's Word engine is unreliable with text-transform, so display labels
|
||||
// are table lookups rather than a CSS trick.
|
||||
const DIFFICULTY: Record<string, { label: string; color: string }> = {
|
||||
easy: { label: "Easy", color: GREEN },
|
||||
medium: { label: "Medium", color: AMBER },
|
||||
hard: { label: "Hard", color: RED },
|
||||
};
|
||||
|
||||
// The SRS ladder in plain English — "+5" means the last look was 5 days back.
|
||||
const LAST_SEEN: Record<string, string> = {
|
||||
new: "first look",
|
||||
"+2": "2 days ago",
|
||||
"+5": "5 days ago",
|
||||
"+10": "10 days ago",
|
||||
retired: "retired",
|
||||
};
|
||||
|
||||
// ── data model ───────────────────────────────────────────────────
|
||||
|
||||
/** A review or drill line: number + difficulty + one-tap links, nothing else. */
|
||||
export interface DigestRow {
|
||||
lc: number;
|
||||
difficulty: string;
|
||||
/** Reviews only — drills are unstaged by design. */
|
||||
stage?: string;
|
||||
passUrl: string;
|
||||
failUrl: string;
|
||||
}
|
||||
|
||||
export interface DigestData {
|
||||
/** "Tuesday, August 25" */
|
||||
day: string;
|
||||
/** "Day 9 of 56 · Week 2" */
|
||||
progress: string;
|
||||
streak: number;
|
||||
rest: boolean;
|
||||
topic?: { name: string; core: { lc: number; url: string; solved: boolean }[] };
|
||||
reviews: DigestRow[];
|
||||
/** Reviews past the daily cap; they simply stay due. */
|
||||
carried: number;
|
||||
drills: DigestRow[];
|
||||
gate?: { week: number; url: string };
|
||||
yesterday: { total: number; failed: number[] };
|
||||
gateRate?: number;
|
||||
/** PNG, not SVG — email clients refuse the latter. */
|
||||
heatmapUrl: string;
|
||||
progressUrl: string;
|
||||
}
|
||||
|
||||
// ── styles ───────────────────────────────────────────────────────
|
||||
|
||||
const page: CSSProperties = { backgroundColor: CANVAS, padding: "28px 0" };
|
||||
const card: CSSProperties = {
|
||||
backgroundColor: CARD,
|
||||
border: `1px solid ${BORDER}`,
|
||||
borderRadius: "10px",
|
||||
margin: "0 auto",
|
||||
maxWidth: "600px",
|
||||
padding: "28px 24px",
|
||||
};
|
||||
const h1: CSSProperties = { color: INK, fontSize: "20px", fontWeight: 600, lineHeight: "26px", margin: 0 };
|
||||
const label: CSSProperties = {
|
||||
color: MUTED,
|
||||
fontSize: "11px",
|
||||
fontWeight: 700,
|
||||
letterSpacing: "0.8px",
|
||||
margin: "0 0 10px",
|
||||
textTransform: "uppercase",
|
||||
};
|
||||
const hint: CSSProperties = { color: MUTED, fontSize: "13px", lineHeight: "19px", margin: "0 0 12px" };
|
||||
const th: CSSProperties = {
|
||||
borderBottom: `1px solid ${BORDER}`,
|
||||
color: MUTED,
|
||||
fontSize: "12px",
|
||||
fontWeight: 400,
|
||||
padding: "0 0 8px",
|
||||
textAlign: "left",
|
||||
};
|
||||
const td: CSSProperties = {
|
||||
borderBottom: `1px solid ${RULE}`,
|
||||
color: INK,
|
||||
fontSize: "14px",
|
||||
padding: "12px 0",
|
||||
textAlign: "left",
|
||||
};
|
||||
const tap: CSSProperties = {
|
||||
borderRadius: "6px",
|
||||
color: "#ffffff",
|
||||
display: "inline-block",
|
||||
fontSize: "12px",
|
||||
fontWeight: 600,
|
||||
lineHeight: "12px",
|
||||
padding: "9px 15px",
|
||||
textDecoration: "none",
|
||||
};
|
||||
|
||||
/**
|
||||
* A problem list as a real table. The "last seen" column appears only for
|
||||
* reviews, which keeps drills at three columns on a phone.
|
||||
*/
|
||||
function ProblemTable({ rows, staged }: { rows: DigestRow[]; staged: boolean }) {
|
||||
return (
|
||||
<table
|
||||
width="100%"
|
||||
border={0}
|
||||
cellPadding={0}
|
||||
cellSpacing={0}
|
||||
style={{ borderCollapse: "collapse", width: "100%" }}
|
||||
>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={th}>Problem</th>
|
||||
<th style={th}>Level</th>
|
||||
{staged ? <th style={th}>Last seen</th> : null}
|
||||
<th style={{ ...th, textAlign: "right" }}>How did it go?</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => {
|
||||
const difficulty = DIFFICULTY[row.difficulty];
|
||||
return (
|
||||
<tr key={row.lc}>
|
||||
<td style={{ ...td, fontWeight: 600 }}>LC {row.lc}</td>
|
||||
<td style={{ ...td, color: difficulty?.color ?? INK }}>{difficulty?.label ?? row.difficulty}</td>
|
||||
{staged ? (
|
||||
<td style={{ ...td, color: MUTED }}>{(row.stage && LAST_SEEN[row.stage]) ?? row.stage}</td>
|
||||
) : null}
|
||||
<td style={{ ...td, textAlign: "right", whiteSpace: "nowrap" }}>
|
||||
<Button href={row.passUrl} style={{ ...tap, backgroundColor: PASS_BG }}>
|
||||
got it
|
||||
</Button>
|
||||
<Button href={row.failUrl} style={{ ...tap, backgroundColor: FAIL_BG, marginLeft: "6px" }}>
|
||||
missed it
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
function Block({
|
||||
title,
|
||||
note,
|
||||
rows,
|
||||
staged,
|
||||
empty,
|
||||
}: {
|
||||
title: string;
|
||||
note: string;
|
||||
rows: DigestRow[];
|
||||
staged: boolean;
|
||||
empty: string;
|
||||
}) {
|
||||
return (
|
||||
<Section style={{ marginTop: "28px" }}>
|
||||
<Text style={label}>{title}</Text>
|
||||
{rows.length === 0 ? (
|
||||
<Text style={{ ...hint, margin: 0 }}>{empty}</Text>
|
||||
) : (
|
||||
<>
|
||||
<Text style={hint}>{note}</Text>
|
||||
<ProblemTable rows={rows} staged={staged} />
|
||||
</>
|
||||
)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
// ── email ────────────────────────────────────────────────────────
|
||||
|
||||
function DigestEmail({ data }: { data: DigestData }) {
|
||||
const load = data.reviews.length + data.drills.length;
|
||||
const preview = data.rest
|
||||
? "Rest day — nothing to do but rest."
|
||||
: `${load} to work through today${data.topic ? `, starting with ${data.topic.name}` : ""}.`;
|
||||
|
||||
const passed = data.yesterday.total - data.yesterday.failed.length;
|
||||
const missed = data.yesterday.failed.map((lc) => `LC ${lc}`).join(", ");
|
||||
|
||||
return (
|
||||
<Html lang="en" dir="ltr">
|
||||
<Head>
|
||||
<meta name="color-scheme" content="dark" />
|
||||
<meta name="supported-color-schemes" content="dark" />
|
||||
</Head>
|
||||
<Preview>{preview}</Preview>
|
||||
<Body style={{ backgroundColor: CANVAS, fontFamily: FONT, margin: 0, padding: 0 }}>
|
||||
<Section style={page}>
|
||||
<Container style={card}>
|
||||
<Heading as="h1" style={h1}>
|
||||
{data.rest ? `Take the day off — ${data.day}` : `Good morning. It's ${data.day}.`}
|
||||
</Heading>
|
||||
<Text style={{ color: MUTED, fontSize: "13px", margin: "8px 0 0" }}>
|
||||
{data.progress}
|
||||
{data.rest
|
||||
? " · nothing is due today, and anything overdue waits for Monday."
|
||||
: data.streak === 0
|
||||
? " · no streak going yet — today is a good day to start one."
|
||||
: ` · 🔥 ${data.streak} day${data.streak === 1 ? "" : "s"} in a row, keep it going.`}
|
||||
</Text>
|
||||
|
||||
{data.rest ? null : (
|
||||
<>
|
||||
{data.topic ? (
|
||||
<Section style={{ marginTop: "28px" }}>
|
||||
<Text style={label}>Something new today</Text>
|
||||
<Text style={{ color: INK, fontSize: "16px", fontWeight: 600, margin: "0 0 8px" }}>
|
||||
{data.topic.name}
|
||||
</Text>
|
||||
<Text style={{ ...hint, margin: 0 }}>
|
||||
Work through these — ticked ones you have already solved:{" "}
|
||||
{data.topic.core.map((p, i) => (
|
||||
<span key={p.lc}>
|
||||
{i > 0 ? " · " : ""}
|
||||
<Link href={p.url} style={{ color: p.solved ? MUTED : LINK, textDecoration: "none" }}>
|
||||
LC {p.lc}
|
||||
</Link>
|
||||
{p.solved ? <span style={{ color: GREEN }}> ✓</span> : null}
|
||||
</span>
|
||||
))}
|
||||
</Text>
|
||||
</Section>
|
||||
) : null}
|
||||
|
||||
<Block
|
||||
title="Time to see these again"
|
||||
note="Solve each one from scratch, and resist opening your old answer first."
|
||||
rows={data.reviews}
|
||||
staged
|
||||
empty="Nothing is due for review today."
|
||||
/>
|
||||
{data.carried > 0 ? (
|
||||
<Text style={{ ...hint, margin: "12px 0 0" }}>
|
||||
{data.carried} more {data.carried === 1 ? "is" : "are"} waiting — they come back
|
||||
tomorrow, oldest first.
|
||||
</Text>
|
||||
) : null}
|
||||
|
||||
<Block
|
||||
title="Cold start, no hints"
|
||||
note="You are not told the topic. Say the pattern out loud before you write a line."
|
||||
rows={data.drills}
|
||||
staged={false}
|
||||
empty="No cold starts today."
|
||||
/>
|
||||
|
||||
{data.gate ? (
|
||||
<Section style={{ marginTop: "28px" }}>
|
||||
<Text style={label}>Weekly checkpoint</Text>
|
||||
<Text style={hint}>Timed and blind. Close the issue when you are done.</Text>
|
||||
<Button
|
||||
href={data.gate.url}
|
||||
style={{ ...tap, backgroundColor: GATE_BG, fontSize: "13px", padding: "11px 18px" }}
|
||||
>
|
||||
Open week {data.gate.week} review
|
||||
</Button>
|
||||
</Section>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Eight weeks at a glance — the one thing here that is pure
|
||||
encouragement rather than instruction. */}
|
||||
<Section style={{ marginTop: "28px" }}>
|
||||
<Text style={label}>Every day you showed up</Text>
|
||||
<Link href={data.progressUrl}>
|
||||
<Img
|
||||
src={data.heatmapUrl}
|
||||
alt="Attempt heatmap across the eight-week campaign"
|
||||
width="552"
|
||||
style={{ border: `1px solid ${BORDER}`, borderRadius: "8px", display: "block", width: "100%" }}
|
||||
/>
|
||||
</Link>
|
||||
</Section>
|
||||
|
||||
<Hr style={{ borderColor: BORDER, margin: "28px 0 18px" }} />
|
||||
<Text style={{ color: MUTED, fontSize: "12px", lineHeight: "19px", margin: 0 }}>
|
||||
{data.yesterday.total === 0
|
||||
? "You did not log anything yesterday."
|
||||
: `Yesterday you logged ${data.yesterday.total} and got ${passed} of them` +
|
||||
(missed ? `; ${missed} got away.` : ".")}{" "}
|
||||
{data.gateRate === undefined
|
||||
? "No checkpoints scored yet."
|
||||
: `Checkpoints are running at ${Math.round(data.gateRate * 100)}%.`}{" "}
|
||||
<Link href={data.progressUrl} style={{ color: LINK, textDecoration: "none" }}>
|
||||
See the full picture →
|
||||
</Link>
|
||||
</Text>
|
||||
</Container>
|
||||
</Section>
|
||||
</Body>
|
||||
</Html>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The plain-text alternative. React Email's `plainText` mode flattens the
|
||||
* problem tables into one unreadable run, so text gets its own writer — fed
|
||||
* by the same `DigestData`, so the numbers and links can never disagree with
|
||||
* the HTML even though the wording lives in two places.
|
||||
*/
|
||||
function plainDigest(data: DigestData): string {
|
||||
const out: string[] = [
|
||||
data.rest ? `Take the day off — ${data.day}` : `Good morning. It's ${data.day}.`,
|
||||
data.progress +
|
||||
(data.rest
|
||||
? " · nothing is due today, and anything overdue waits for Monday."
|
||||
: data.streak === 0
|
||||
? " · no streak going yet — today is a good day to start one."
|
||||
: ` · ${data.streak} day${data.streak === 1 ? "" : "s"} in a row, keep it going.`),
|
||||
];
|
||||
|
||||
if (!data.rest) {
|
||||
if (data.topic) {
|
||||
out.push(
|
||||
"",
|
||||
`SOMETHING NEW TODAY — ${data.topic.name}`,
|
||||
"Work through these; the ones marked done you have already solved.",
|
||||
...data.topic.core.map((p) => ` LC ${p.lc}${p.solved ? " (done)" : ""} — ${p.url}`),
|
||||
);
|
||||
}
|
||||
|
||||
const lists: [string, string, DigestRow[], string][] = [
|
||||
[
|
||||
"TIME TO SEE THESE AGAIN",
|
||||
"Solve each one from scratch, and resist opening your old answer first.",
|
||||
data.reviews,
|
||||
"Nothing is due for review today.",
|
||||
],
|
||||
[
|
||||
"COLD START, NO HINTS",
|
||||
"You are not told the topic. Say the pattern out loud before you write a line.",
|
||||
data.drills,
|
||||
"No cold starts today.",
|
||||
],
|
||||
];
|
||||
for (const [title, note, rows, empty] of lists) {
|
||||
out.push("", title);
|
||||
if (rows.length === 0) {
|
||||
out.push(empty);
|
||||
continue;
|
||||
}
|
||||
out.push(note);
|
||||
for (const row of rows) {
|
||||
const seen = row.stage ? `, last seen ${LAST_SEEN[row.stage] ?? row.stage}` : "";
|
||||
out.push(
|
||||
` LC ${row.lc} — ${DIFFICULTY[row.difficulty]?.label ?? row.difficulty}${seen}`,
|
||||
` got it: ${row.passUrl}`,
|
||||
` missed it: ${row.failUrl}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (data.carried > 0) {
|
||||
out.push(
|
||||
"",
|
||||
`${data.carried} more ${data.carried === 1 ? "is" : "are"} waiting — they come back tomorrow, oldest first.`,
|
||||
);
|
||||
}
|
||||
if (data.gate) {
|
||||
out.push(
|
||||
"",
|
||||
"WEEKLY CHECKPOINT",
|
||||
"Timed and blind. Close the issue when you are done.",
|
||||
` Week ${data.gate.week} review — ${data.gate.url}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const passed = data.yesterday.total - data.yesterday.failed.length;
|
||||
const missed = data.yesterday.failed.map((lc) => `LC ${lc}`).join(", ");
|
||||
out.push(
|
||||
"",
|
||||
"─".repeat(48),
|
||||
data.yesterday.total === 0
|
||||
? "You did not log anything yesterday."
|
||||
: `Yesterday you logged ${data.yesterday.total} and got ${passed} of them` +
|
||||
(missed ? `; ${missed} got away.` : "."),
|
||||
data.gateRate === undefined
|
||||
? "No checkpoints scored yet."
|
||||
: `Checkpoints are running at ${Math.round(data.gateRate * 100)}%.`,
|
||||
`Every day you showed up: ${data.heatmapUrl}`,
|
||||
`See the full picture: ${data.progressUrl}`,
|
||||
);
|
||||
return out.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* The HTML body plus its plain-text alternative — always sent as a pair so a
|
||||
* client that refuses HTML still gets the same problems and the same links.
|
||||
*/
|
||||
export async function renderDigest(data: DigestData): Promise<{ html: string; text: string }> {
|
||||
return { html: await render(<DigestEmail data={data} />), text: plainDigest(data) };
|
||||
}
|
||||
+10
-1
@@ -10,7 +10,7 @@
|
||||
* admin routes); everything else is read-only public.
|
||||
*/
|
||||
import { reconcileCatalog } from "./catalog.ts";
|
||||
import { gateBadge, heatmapChart, ladderChart, progressChart } from "./charts.ts";
|
||||
import { gateBadge, heatmapChart, heatmapPng, ladderChart, progressChart } from "./charts.ts";
|
||||
import { sendDigest } from "./digest.ts";
|
||||
import { createReviewIssue, scoreReview } from "./gate.ts";
|
||||
import { type GitHub, github } from "./github.ts";
|
||||
@@ -233,6 +233,12 @@ const SVG_HEADERS = {
|
||||
"cache-control": "public, max-age=300",
|
||||
};
|
||||
|
||||
// The digest embeds the raster heatmap; email clients refuse SVG entirely.
|
||||
const PNG_HEADERS = {
|
||||
"content-type": "image/png",
|
||||
"cache-control": "public, max-age=300",
|
||||
};
|
||||
|
||||
export default {
|
||||
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
@@ -256,6 +262,9 @@ export default {
|
||||
if (path === "/chart/heatmap.svg") {
|
||||
return new Response(await heatmapChart(env.DB, CAMPAIGN_START, 56), { headers: SVG_HEADERS });
|
||||
}
|
||||
if (path === "/chart/heatmap.png") {
|
||||
return new Response(await heatmapPng(env.DB, CAMPAIGN_START, 56), { headers: PNG_HEADERS });
|
||||
}
|
||||
if (path === "/badge/gate.svg") {
|
||||
return new Response(await gateBadge(env.DB), { headers: SVG_HEADERS });
|
||||
}
|
||||
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
/**
|
||||
* Hand-rolled PNG encoder for the SRS Worker.
|
||||
*
|
||||
* Every major email client — Gmail, Outlook, Apple Mail — refuses to render
|
||||
* SVG, inline or remote, so the daily digest cannot reuse /chart/heatmap.svg;
|
||||
* it needs raster bytes. The Worker ships with no runtime dependencies by
|
||||
* design (SVG, HMAC and GraphQL are all hand-rolled here), so this file
|
||||
* encodes PNG itself instead of pulling in a codec.
|
||||
*
|
||||
* The format reduces to four things the runtime already provides:
|
||||
* - an 8-byte signature plus chunks (IHDR, IDAT, IEND), each one
|
||||
* length + type + payload + CRC32, every integer big-endian;
|
||||
* - one filter byte per scanline, always 0 here: these images are flat
|
||||
* rectangles, so a predictor would buy nothing;
|
||||
* - zlib-wrapped deflate for IDAT, which is exactly what
|
||||
* `new CompressionStream("deflate")` emits ("deflate-raw" would not);
|
||||
* - CRC32, a 256-entry table built lazily on the first chunk.
|
||||
*
|
||||
* Colour type 2 (truecolour, 8-bit, no alpha): these charts are opaque cards,
|
||||
* so an alpha channel would cost a third more bytes for nothing. That does mean
|
||||
* transparency is unavailable — a caller wanting rounded corners paints the
|
||||
* colour that sits behind the image first, then the rounded card on top.
|
||||
*/
|
||||
|
||||
// ── crc32 ────────────────────────────────────────────────────────
|
||||
|
||||
// One table for every chunk of every image; built on first use.
|
||||
let crcTable: Uint32Array | undefined;
|
||||
|
||||
function crc32(bytes: Uint8Array): number {
|
||||
let table = crcTable;
|
||||
if (!table) {
|
||||
table = new Uint32Array(256);
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = (c & 1) !== 0 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
table[n] = c;
|
||||
}
|
||||
crcTable = table;
|
||||
}
|
||||
let crc = 0xffffffff;
|
||||
for (const byte of bytes) crc = table[(crc ^ byte) & 0xff]! ^ (crc >>> 8);
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
// ── chunks ───────────────────────────────────────────────────────
|
||||
|
||||
const SIGNATURE = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
|
||||
/** length, 4-char type, payload, then CRC32 over the type and payload. */
|
||||
function chunk(type: string, data: Uint8Array): Uint8Array {
|
||||
const out = new Uint8Array(data.length + 12);
|
||||
const view = new DataView(out.buffer);
|
||||
view.setUint32(0, data.length);
|
||||
for (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i);
|
||||
out.set(data, 8);
|
||||
view.setUint32(data.length + 8, crc32(out.subarray(4, data.length + 8)));
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── 5x7 bitmap font ──────────────────────────────────────────────
|
||||
|
||||
const GLYPH_W = 5;
|
||||
const GLYPH_H = 7;
|
||||
|
||||
/**
|
||||
* Seven row bitmasks per glyph, five low bits each, MSB (0b10000) leftmost.
|
||||
* Uppercase only: chart labels are short and mechanical, and a lowercase set
|
||||
* would double the table for no gain. Unlisted characters render blank.
|
||||
*/
|
||||
const GLYPHS: Record<string, number[]> = {
|
||||
A: [0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
|
||||
B: [0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110],
|
||||
C: [0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110],
|
||||
D: [0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110],
|
||||
E: [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111],
|
||||
F: [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000],
|
||||
G: [0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01110],
|
||||
H: [0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
|
||||
I: [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b11111],
|
||||
J: [0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100],
|
||||
K: [0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001],
|
||||
L: [0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111],
|
||||
M: [0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001],
|
||||
N: [0b10001, 0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001],
|
||||
O: [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
|
||||
P: [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000],
|
||||
Q: [0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10011, 0b01101],
|
||||
R: [0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001],
|
||||
S: [0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110],
|
||||
T: [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100],
|
||||
U: [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
|
||||
V: [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100],
|
||||
W: [0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001],
|
||||
X: [0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001],
|
||||
Y: [0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100],
|
||||
Z: [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111],
|
||||
"0": [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110],
|
||||
"1": [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
|
||||
"2": [0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111],
|
||||
"3": [0b11111, 0b00010, 0b00100, 0b00010, 0b00001, 0b10001, 0b01110],
|
||||
"4": [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010],
|
||||
"5": [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110],
|
||||
"6": [0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110],
|
||||
"7": [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000],
|
||||
"8": [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110],
|
||||
"9": [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100],
|
||||
" ": [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000],
|
||||
"-": [0b00000, 0b00000, 0b00000, 0b11111, 0b00000, 0b00000, 0b00000],
|
||||
"/": [0b00001, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b10000],
|
||||
":": [0b00000, 0b00100, 0b00100, 0b00000, 0b00100, 0b00100, 0b00000],
|
||||
};
|
||||
|
||||
/**
|
||||
* Device pixels `content` occupies at `scale`, inter-glyph gaps included.
|
||||
* Exported because callers need it to size a canvas before constructing one.
|
||||
*/
|
||||
export function textWidth(content: string, scale = 1): number {
|
||||
return content.length === 0 ? 0 : (content.length * (GLYPH_W + 1) - 1) * scale;
|
||||
}
|
||||
|
||||
// ── canvas ───────────────────────────────────────────────────────
|
||||
|
||||
/** "#rrggbb" to its three channel bytes; called once per draw, not per pixel. */
|
||||
function rgb(color: string): [number, number, number] {
|
||||
const packed = Number.parseInt(color.slice(1), 16);
|
||||
return [(packed >> 16) & 0xff, (packed >> 8) & 0xff, packed & 0xff];
|
||||
}
|
||||
|
||||
/** Fixed-size RGB canvas: filled rectangles plus 5x7 bitmap text. */
|
||||
export class Canvas {
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
/** Row-major RGB triples, unpadded; encode() interleaves the filter bytes. */
|
||||
private readonly pixels: Uint8Array;
|
||||
|
||||
constructor(width: number, height: number, background: string) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.pixels = new Uint8Array(width * height * 3);
|
||||
const [r, g, b] = rgb(background);
|
||||
for (let i = 0; i < this.pixels.length; i += 3) {
|
||||
this.pixels[i] = r;
|
||||
this.pixels[i + 1] = g;
|
||||
this.pixels[i + 2] = b;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filled rectangle, clipped to the canvas. `radius` rounds all four corners
|
||||
* by dropping the pixels whose centre falls outside the corner circle —
|
||||
* enough for the small cell roundings and the card these charts draw.
|
||||
*/
|
||||
rect(x: number, y: number, w: number, h: number, color: string, radius = 0): void {
|
||||
const [r, g, b] = rgb(color);
|
||||
// Device pixels only: a fractional origin would index the buffer between
|
||||
// bytes and silently drop the whole rectangle.
|
||||
const left = Math.round(x);
|
||||
const top = Math.round(y);
|
||||
const rw = Math.round(w);
|
||||
const rh = Math.round(h);
|
||||
const rad = Math.min(radius, rw / 2, rh / 2);
|
||||
|
||||
const y1 = Math.min(this.height, top + rh);
|
||||
const x1 = Math.min(this.width, left + rw);
|
||||
for (let py = Math.max(0, top); py < y1; py++) {
|
||||
// How far this row lies past the nearer corner centre; 0 in between.
|
||||
const cy = py + 0.5;
|
||||
const dy = cy < top + rad ? top + rad - cy : cy > top + rh - rad ? cy - (top + rh - rad) : 0;
|
||||
const rowBase = py * this.width * 3;
|
||||
for (let px = Math.max(0, left); px < x1; px++) {
|
||||
const cx = px + 0.5;
|
||||
const dx = cx < left + rad ? left + rad - cx : cx > left + rw - rad ? cx - (left + rw - rad) : 0;
|
||||
if (dx * dx + dy * dy > rad * rad) continue;
|
||||
const at = rowBase + px * 3;
|
||||
this.pixels[at] = r;
|
||||
this.pixels[at + 1] = g;
|
||||
this.pixels[at + 2] = b;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bitmap text from a top-left origin (not a baseline), `scale` device pixels
|
||||
* per glyph pixel, 1 glyph pixel of advance between characters. Input is
|
||||
* uppercased; unknown characters advance without drawing.
|
||||
*/
|
||||
text(x: number, y: number, content: string, color: string, scale = 1): void {
|
||||
const [r, g, b] = rgb(color);
|
||||
const left = Math.round(x);
|
||||
const top = Math.round(y);
|
||||
const upper = content.toUpperCase();
|
||||
|
||||
for (let i = 0; i < upper.length; i++) {
|
||||
const glyph = GLYPHS[upper[i]!];
|
||||
if (!glyph) continue;
|
||||
const originX = left + i * (GLYPH_W + 1) * scale;
|
||||
for (let gy = 0; gy < GLYPH_H; gy++) {
|
||||
const bits = glyph[gy]!;
|
||||
if (bits === 0) continue;
|
||||
for (let gx = 0; gx < GLYPH_W; gx++) {
|
||||
if ((bits & (1 << (GLYPH_W - 1 - gx))) === 0) continue;
|
||||
// Every set glyph pixel is a scale x scale block of device pixels.
|
||||
const blockX = originX + gx * scale;
|
||||
const blockY = top + gy * scale;
|
||||
const y1 = Math.min(this.height, blockY + scale);
|
||||
const x1 = Math.min(this.width, blockX + scale);
|
||||
for (let py = Math.max(0, blockY); py < y1; py++) {
|
||||
const rowBase = py * this.width * 3;
|
||||
for (let px = Math.max(0, blockX); px < x1; px++) {
|
||||
const at = rowBase + px * 3;
|
||||
this.pixels[at] = r;
|
||||
this.pixels[at + 1] = g;
|
||||
this.pixels[at + 2] = b;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** PNG bytes: 8-bit truecolour, one IDAT, zlib via CompressionStream. */
|
||||
async encode(): Promise<Uint8Array> {
|
||||
const stride = this.width * 3;
|
||||
const raw = new Uint8Array((stride + 1) * this.height);
|
||||
for (let y = 0; y < this.height; y++) {
|
||||
// Leading 0 of each scanline slot is the "no filter" byte.
|
||||
raw.set(this.pixels.subarray(y * stride, (y + 1) * stride), y * (stride + 1) + 1);
|
||||
}
|
||||
const deflated = new Response(raw).body!.pipeThrough(new CompressionStream("deflate"));
|
||||
const idat = new Uint8Array(await new Response(deflated).arrayBuffer());
|
||||
|
||||
const ihdr = new Uint8Array(13);
|
||||
const header = new DataView(ihdr.buffer);
|
||||
header.setUint32(0, this.width);
|
||||
header.setUint32(4, this.height);
|
||||
ihdr[8] = 8; // bit depth
|
||||
ihdr[9] = 2; // colour type 2: truecolour RGB
|
||||
// Bytes 10-12 stay 0: deflate, adaptive filtering, no interlace.
|
||||
|
||||
const chunks = [chunk("IHDR", ihdr), chunk("IDAT", idat), chunk("IEND", new Uint8Array(0))];
|
||||
let total = SIGNATURE.length;
|
||||
for (const c of chunks) total += c.length;
|
||||
|
||||
const png = new Uint8Array(total);
|
||||
png.set(SIGNATURE);
|
||||
let at = SIGNATURE.length;
|
||||
for (const c of chunks) {
|
||||
png.set(c, at);
|
||||
at += c.length;
|
||||
}
|
||||
return png;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user