Give finished Rules a print path, folded launch counts, and a two-day follow-up.

Export is PDF, RULE.md, and Print on US Letter, with every shared term, no member names, and a takeaway that points at Ask an organizer. Finished Rules keep type and place so the team can read folded counts without a database, Umami can sit beside the app with no cookies, and the person who holds the pen gets working PDF and RULE.md links 48 hours later.
This commit is contained in:
adilallo committed 2026-11-10 18:32:33 -07:00
1 parent 0efc907633
commit d9c475a967
74 files changed
+2401 -630

No files matched your search

+200 -357
View File
@@ -1,12 +1,15 @@
import { jsPDF } from "jspdf";
import type {
CommunityRuleEntry,
CommunityRuleLabeledBlock,
CommunityRuleSection,
} from "../../app/components/type/CommunityRule/CommunityRule.types";
import exportCopy from "../../messages/en/create/export.json";
import type { StoredLastPublishedRule } from "./lastPublishedRule";
import { parsePublishedDocumentForCommunityRuleDisplay } from "./publishedDocumentToDisplaySections";
import {
RULE_MD_FILENAME,
buildRuleExportDocument,
exportPdfFilename,
yamlQuote,
type RuleExportDocument,
type RuleExportLine,
type RuleExportSource,
} from "./ruleExportModel";
import { ruleExportDocumentToPdfBytes } from "./ruleExportPdf";
export {
buildPublicRuleUrl,
@@ -14,6 +17,159 @@ export {
formatShareUrlDisplay,
shareCopyUrl,
} from "../sharePaths";
export {
RULE_MD_FILENAME,
exportPdfFilename,
type RuleExportSource,
} from "./ruleExportModel";
export type RuleExportFormat = "pdf" | "markdown" | "print";
function lineMarkdown(line: RuleExportLine): string {
if (line.lead) return `**${line.lead}** ${line.body}`;
return line.body;
}
export function ruleExportDocumentToMarkdown(doc: RuleExportDocument): string {
const front: string[] = ["---", `title: ${yamlQuote(doc.title)}`];
if (doc.summary.length > 0) {
front.push(`summary: ${yamlQuote(doc.summary)}`);
}
if (doc.finishedOn) {
front.push(`finished: ${doc.finishedOn}`);
}
front.push("---", "", `# ${doc.title}`, "");
if (doc.summary.length > 0) {
front.push(doc.summary, "");
}
for (const section of doc.sections) {
front.push(`## ${section.title}`, "");
for (const card of section.cards) {
front.push(`### ${card.title}`, "");
for (const line of card.lines) {
front.push(lineMarkdown(line), "");
}
}
}
if (doc.terms.length > 0) {
front.push(`## ${exportCopy.sharedTermsHeading}`, "");
for (const term of doc.terms) {
front.push(`**${term.term}**`, `: ${term.meaning}`, "");
}
}
front.push(`${doc.takeaway}: ${doc.takeawayUrl}`, "");
return `${front.join("\n").trimEnd()}\n`;
}
function escapeHtml(value: string): string {
return value
.replace(/&/g, "&")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function lineHtml(line: RuleExportLine): string {
if (line.lead) {
return `<p><span class="lead">${escapeHtml(line.lead)}</span> ${escapeHtml(line.body)}</p>`;
}
return `<p>${escapeHtml(line.body)}</p>`;
}
export function ruleExportDocumentToPrintHtml(doc: RuleExportDocument): string {
const photo = doc.photoUrl
? `<img class="photo" src="${escapeHtml(doc.photoUrl)}" alt="" />`
: `<div class="photo initials">${escapeHtml(doc.initials)}</div>`;
const summary =
doc.summary.length > 0
? `<p class="summary">${escapeHtml(doc.summary)}</p>`
: "";
const sections = doc.sections
.map((section) => {
const cards = section.cards
.map(
(card) =>
`<article class="card"><h3>${escapeHtml(card.title)}</h3>${card.lines
.map(lineHtml)
.join("")}</article>`,
)
.join("");
return `<section><h2>${escapeHtml(section.title)}</h2>${cards}</section>`;
})
.join("");
const terms = doc.terms
.map(
(term) =>
`<p class="term"><i>${escapeHtml(term.term)}</i> ${escapeHtml(term.meaning)}</p>`,
)
.join("");
const termsBlock =
doc.terms.length > 0
? `<section class="terms"><h2>${escapeHtml(exportCopy.sharedTermsHeading)}</h2><div class="term-columns">${terms}</div></section>`
: "";
const styles = `
@page { size: letter; margin: 12.7mm 16.9mm 12mm; }
html, body { margin: 0; padding: 0; background: #fff; color: #141414; }
body { font-family: Inter, system-ui, sans-serif; font-size: 12pt; line-height: 1.35; }
h1, h2, h3 { font-family: "Bricolage Grotesque", Inter, system-ui, sans-serif; font-weight: 700; margin: 0; }
.header { display: flex; gap: 24px; align-items: center; padding-bottom: 12px; }
.photo { width: 72px; height: 72px; border-radius: 9999px; object-fit: cover; flex-shrink: 0; }
.photo.initials { border: 2px solid #141414; display: flex; align-items: center; justify-content: center; font-size: 24px; font-weight: 500; }
.group { min-width: 0; flex: 1; }
h1 { font-size: 32px; line-height: 40px; }
.summary { font-size: 16px; line-height: 24px; margin: 8px 0 0; font-weight: 400; }
section { border-top: 1px solid #141414; padding-top: 16px; margin-top: 20px; }
h2 { font-size: 24px; line-height: 32px; margin-bottom: 12px; }
.card { margin: 0 0 12px; }
h3 { font-size: 16px; line-height: 22px; margin-bottom: 8px; }
p { margin: 0 0 8px; font-size: 14px; line-height: 20px; }
.lead { font-weight: 500; }
.terms h2 { margin-bottom: 16px; }
.term-columns { column-count: 2; column-gap: 32px; }
.term { font-size: 12px; line-height: 16px; break-inside: avoid; margin: 0 0 12px; }
.term i { font-style: italic; }
.takeaway { margin-top: 24px; font-size: 12px; }
.takeaway a { color: #141414; }
.footer { display: flex; justify-content: space-between; color: #464646; font-size: 12px; margin-top: 24px; }
@media print {
.footer { position: running(pageFooter); }
@page { @bottom-center { content: none; } }
}
`.replace(/\n/g, "");
return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><title>${escapeHtml(doc.title)}</title><style>${styles}</style></head><body><header class="header">${photo}<div class="group"><h1>${escapeHtml(doc.title)}</h1>${summary}</div></header>${sections}${termsBlock}<p class="takeaway">${escapeHtml(doc.takeaway)} <a href="${escapeHtml(doc.takeawayUrl)}">${escapeHtml(doc.takeawayUrl)}</a></p><div class="footer"><span>${escapeHtml(doc.credit)}</span></div></body></html>`;
}
export function exportStoredRuleAsMarkdown(
rule: RuleExportSource,
origin: string,
): string {
return ruleExportDocumentToMarkdown(buildRuleExportDocument(rule, origin));
}
export function buildPrintableRuleHtmlDocument(
rule: RuleExportSource,
origin: string,
): string {
return ruleExportDocumentToPrintHtml(buildRuleExportDocument(rule, origin));
}
export function buildStoredRulePdfBytes(
rule: RuleExportSource,
origin: string,
): Uint8Array {
return ruleExportDocumentToPdfBytes(buildRuleExportDocument(rule, origin));
}
export function buildStoredRulePdfBlob(
rule: RuleExportSource,
origin: string,
): Blob {
const bytes = buildStoredRulePdfBytes(rule, origin);
const copy = new Uint8Array(bytes.byteLength);
copy.set(bytes);
return new Blob([copy.buffer], { type: "application/pdf" });
}
/** Safe filename fragment from rule title, with stable fallback. */
export function exportFilenameBase(rule: StoredLastPublishedRule): string {
@@ -26,346 +182,8 @@ export function exportFilenameBase(rule: StoredLastPublishedRule): string {
return fromTitle.length > 0 ? fromTitle : `rule-${rule.id.slice(0, 8)}`;
}
function labeledBlockMedia(b: CommunityRuleLabeledBlock): {
img?: string;
file?: string;
bodyTrim: string;
} {
const imgRaw = b.imageUrl?.trim();
const fileRaw = b.fileUrl?.trim();
return {
img: imgRaw && imgRaw.length > 0 ? imgRaw : undefined,
file: fileRaw && fileRaw.length > 0 ? fileRaw : undefined,
bodyTrim: b.body.trim(),
};
}
function entryToMarkdown(entry: CommunityRuleEntry): string {
const lines: string[] = [`### ${entry.title}`, ""];
if (entry.blocks && entry.blocks.length > 0) {
for (const b of entry.blocks) {
lines.push(`#### ${b.label}`, "");
const { img, file, bodyTrim } = labeledBlockMedia(b);
if (img) {
lines.push(`![${bodyTrim || b.label}](${img})`, "");
} else if (file) {
lines.push(`[${bodyTrim || "file"}](${file})`, "");
} else {
lines.push(b.body, "");
}
}
} else {
const body = (entry.body ?? "").trim();
if (body.length > 0) {
const paras = body.split(/\n\s*\n/);
for (const p of paras) {
const t = p.trim();
if (t.length > 0) lines.push(t, "");
}
}
}
return lines.join("\n").trimEnd();
}
export function sectionsToMarkdown(
title: string,
summary: string | null | undefined,
sections: CommunityRuleSection[],
): string {
const parts: string[] = [`# ${title}`, ""];
const sum = typeof summary === "string" ? summary.trim() : "";
if (sum.length > 0) {
parts.push(sum, "");
}
for (const sec of sections) {
parts.push(`## ${sec.categoryName}`, "");
for (const ent of sec.entries) {
parts.push(entryToMarkdown(ent), "");
}
}
return `${parts.join("\n").trimEnd()}\n`;
}
function escapeCsvCell(value: string): string {
if (/[",\r\n]/.test(value)) {
return `"${value.replace(/"/g, '""')}"`;
}
return value;
}
/** Tabular snapshot of parsed rule content (RFC 4180-style; UTF-8 with BOM when downloaded). */
export function sectionsToCsv(
title: string,
summary: string | null | undefined,
sections: CommunityRuleSection[],
): string {
const rows: string[][] = [
["Section", "Entry", "Block label", "Content"],
["", "Title", "", title],
];
const sum = typeof summary === "string" ? summary.trim() : "";
if (sum.length > 0) {
rows.push(["", "Summary", "", sum]);
}
for (const sec of sections) {
for (const ent of sec.entries) {
if (ent.blocks && ent.blocks.length > 0) {
for (const b of ent.blocks) {
const { img, file, bodyTrim } = labeledBlockMedia(b);
const content = img
? bodyTrim.length > 0
? `${bodyTrim}\n${img}`
: img
: file
? bodyTrim.length > 0
? `${bodyTrim}\n${file}`
: file
: b.body;
rows.push([sec.categoryName, ent.title, b.label, content]);
}
} else {
rows.push([sec.categoryName, ent.title, "", ent.body ?? ""]);
}
}
}
return `${rows.map((r) => r.map(escapeCsvCell).join(",")).join("\n")}\n`;
}
export function exportStoredRuleAsMarkdown(rule: StoredLastPublishedRule): string {
const sections = parsePublishedDocumentForCommunityRuleDisplay(rule.document);
if (sections.length === 0) {
throw new Error("exportEmptyDocument");
}
return sectionsToMarkdown(rule.title, rule.summary, sections);
}
export function exportStoredRuleAsCsv(rule: StoredLastPublishedRule): string {
const sections = parsePublishedDocumentForCommunityRuleDisplay(rule.document);
if (sections.length === 0) {
throw new Error("exportEmptyDocument");
}
return `\uFEFF${sectionsToCsv(rule.title, rule.summary, sections)}`;
}
function escapeHtml(s: string): string {
return s
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function paragraphsHtml(text: string): string {
const paras = text
.trim()
.split(/\n\s*\n/)
.filter((p) => p.trim().length > 0);
if (paras.length === 0) return "";
return paras
.map((p) => `<p>${escapeHtml(p.trim()).replace(/\n/g, "<br />")}</p>`)
.join("\n");
}
function entryToPrintHtml(entry: CommunityRuleEntry): string {
let inner = "";
if (entry.blocks && entry.blocks.length > 0) {
for (const b of entry.blocks) {
inner += `<h4 class="block-label">${escapeHtml(b.label)}</h4>`;
const { img, file, bodyTrim } = labeledBlockMedia(b);
if (img) {
inner += `<p><img src="${escapeHtml(img)}" alt="${escapeHtml(bodyTrim || b.label)}" /></p>`;
if (bodyTrim.length > 0) {
inner += paragraphsHtml(b.body);
}
} else if (file) {
inner += `<p><a href="${escapeHtml(file)}">${escapeHtml(bodyTrim || file)}</a></p>`;
} else {
inner += paragraphsHtml(b.body);
}
}
} else {
inner += paragraphsHtml(entry.body ?? "");
}
return `<article class="entry"><h3>${escapeHtml(entry.title)}</h3>${inner}</article>`;
}
/** Full HTML document for static preview or tests; PDF export uses {@link sectionsToPdfBlob}. */
export function buildPrintableRuleHtmlDocument(
title: string,
summary: string | null | undefined,
sections: CommunityRuleSection[],
): string {
const sum = typeof summary === "string" ? summary.trim() : "";
const summaryBlock =
sum.length > 0 ? `<div class="summary">${paragraphsHtml(sum)}</div>` : "";
const body = sections
.map(
(sec) =>
`<section><h2>${escapeHtml(sec.categoryName)}</h2>${sec.entries.map(entryToPrintHtml).join("\n")}</section>`,
)
.join("\n");
const styles = `body{font-family:system-ui,sans-serif;line-height:1.5;margin:2rem auto;max-width:48rem;padding:0 1rem;color:#111;background:#fff}h1{font-size:1.75rem;margin-bottom:.5rem}h2{font-size:1.25rem;margin-top:1.5rem;margin-bottom:.75rem;border-bottom:1px solid #ccc}h3{font-size:1.05rem;margin-top:1rem}h4.block-label{font-size:.95rem;font-weight:600;margin-top:.75rem;margin-bottom:.25rem}p{margin:0 0 .75rem}.summary{color:#333;margin-bottom:1.25rem}@media print{body{margin:0;max-width:none}h2,h3{break-after:avoid}}`;
return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><title>${escapeHtml(title)}</title><style>${styles}</style></head><body><h1>${escapeHtml(title)}</h1>${summaryBlock}${body}</body></html>`;
}
function splitDisplayParagraphs(text: string): string[] {
return text
.trim()
.split(/\n\s*\n/)
.filter((p) => p.trim().length > 0)
.map((p) => p.trim());
}
/**
* Same section structure as {@link buildPrintableRuleHtmlDocument}; renders a
* simple multi-page PDF (Helvetica, headings + wrapped body text).
*/
export function sectionsToPdfBlob(
title: string,
summary: string | null | undefined,
sections: CommunityRuleSection[],
): Blob {
const doc = new jsPDF({ unit: "mm", format: "a4" });
const margin = 20;
const pageW = doc.internal.pageSize.getWidth();
const pageH = doc.internal.pageSize.getHeight();
const maxW = pageW - 2 * margin;
let y = margin;
function ensureSpace(h: number): void {
if (y + h > pageH - margin) {
doc.addPage();
y = margin;
}
}
function writeBlockBodyParagraphs(body: string): void {
for (const p of splitDisplayParagraphs(body)) {
doc.setFont("helvetica", "normal");
doc.setFontSize(11);
const lines = doc.splitTextToSize(p, maxW);
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: maxW });
ensureSpace(dim.h + 1);
doc.text(lines, margin, y);
y += dim.h + 2;
}
}
/** Plain URL line(s); italic for images so captions vs URL read distinctly in print. */
function writeMediaUrlLines(url: string, fontStyle: "normal" | "italic"): void {
doc.setFont("helvetica", fontStyle);
doc.setFontSize(10);
const urlLines = doc.splitTextToSize(url, maxW);
const urlDim = doc.getTextDimensions(urlLines.join("\n"), { maxWidth: maxW });
ensureSpace(urlDim.h + 1);
doc.text(urlLines, margin, y);
y += urlDim.h + 2;
}
doc.setFont("helvetica", "bold");
doc.setFontSize(16);
{
const lines = doc.splitTextToSize(title, maxW);
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: maxW });
ensureSpace(dim.h + 4);
doc.text(lines, margin, y);
y += dim.h + 6;
}
const sum = typeof summary === "string" ? summary.trim() : "";
if (sum.length > 0) {
for (const p of splitDisplayParagraphs(sum)) {
doc.setFont("helvetica", "normal");
doc.setFontSize(11);
const lines = doc.splitTextToSize(p, maxW);
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: maxW });
ensureSpace(dim.h + 2);
doc.text(lines, margin, y);
y += dim.h + 3;
}
y += 2;
}
for (const sec of sections) {
doc.setFont("helvetica", "bold");
doc.setFontSize(13);
{
const lines = doc.splitTextToSize(sec.categoryName, maxW);
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: maxW });
ensureSpace(dim.h + 3);
doc.text(lines, margin, y);
y += dim.h + 5;
}
for (const ent of sec.entries) {
doc.setFont("helvetica", "bold");
doc.setFontSize(11);
{
const lines = doc.splitTextToSize(ent.title, maxW);
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: maxW });
ensureSpace(dim.h + 2);
doc.text(lines, margin, y);
y += dim.h + 3;
}
if (ent.blocks && ent.blocks.length > 0) {
for (const b of ent.blocks) {
doc.setFont("helvetica", "bold");
doc.setFontSize(10);
{
const lines = doc.splitTextToSize(b.label, maxW);
const dim = doc.getTextDimensions(lines.join("\n"), {
maxWidth: maxW,
});
ensureSpace(dim.h + 1);
doc.text(lines, margin, y);
y += dim.h + 2;
}
const { img, file } = labeledBlockMedia(b);
if (img) {
writeBlockBodyParagraphs(b.body);
writeMediaUrlLines(img, "italic");
} else if (file) {
writeBlockBodyParagraphs(b.body);
writeMediaUrlLines(file, "normal");
} else {
writeBlockBodyParagraphs(b.body);
}
}
} else {
for (const p of splitDisplayParagraphs(ent.body ?? "")) {
doc.setFont("helvetica", "normal");
doc.setFontSize(11);
const lines = doc.splitTextToSize(p, maxW);
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: maxW });
ensureSpace(dim.h + 1);
doc.text(lines, margin, y);
y += dim.h + 2;
}
}
}
}
const ab = doc.output("arraybuffer") as ArrayBuffer;
return new Blob([ab], { type: "application/pdf" });
}
export function buildStoredRulePdfBlob(rule: StoredLastPublishedRule): Blob {
const sections = parsePublishedDocumentForCommunityRuleDisplay(rule.document);
if (sections.length === 0) {
throw new Error("exportEmptyDocument");
}
return sectionsToPdfBlob(rule.title, rule.summary, sections);
}
export function downloadStoredRuleAsPdf(rule: StoredLastPublishedRule): void {
if (typeof document === "undefined") return;
const blob = buildStoredRulePdfBlob(rule);
const base = exportFilenameBase(rule);
downloadBlob(`${base}-community-rule.pdf`, blob);
}
export function downloadBlob(filename: string, blob: Blob): void {
if (typeof document === "undefined") return;
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
@@ -382,14 +200,39 @@ export function downloadTextFile(
contents: string,
mime: string,
): void {
const blob = new Blob([contents], { type: mime });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.rel = "noopener";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
downloadBlob(filename, new Blob([contents], { type: mime }));
}
export function downloadStoredRuleAsPdf(
rule: RuleExportSource,
origin: string,
): void {
downloadBlob(exportPdfFilename(rule.title), buildStoredRulePdfBlob(rule, origin));
}
export function downloadStoredRuleAsMarkdown(
rule: RuleExportSource,
origin: string,
): void {
downloadTextFile(
RULE_MD_FILENAME,
exportStoredRuleAsMarkdown(rule, origin),
"text/markdown;charset=utf-8",
);
}
export function printStoredRule(
rule: RuleExportSource,
origin: string,
): boolean {
if (typeof window === "undefined") return false;
const html = buildPrintableRuleHtmlDocument(rule, origin);
const popup = window.open("", "_blank");
if (!popup) return false;
popup.document.open();
popup.document.write(html);
popup.document.close();
popup.focus();
popup.print();
return true;
}