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:
1 parent
0efc907633
commit
d9c475a967
74 files changed
+2401
-630
No files matched your search
+11
-3
@@ -213,7 +213,7 @@ export async function publishRule(input: {
|
||||
document: Record<string, unknown>;
|
||||
stakeholderEmails?: string[];
|
||||
}): Promise<
|
||||
| { ok: true; id: string; title: string }
|
||||
| { ok: true; id: string; title: string; createdAt?: string }
|
||||
| { ok: false; error: string; status?: number }
|
||||
> {
|
||||
try {
|
||||
@@ -232,7 +232,7 @@ export async function publishRule(input: {
|
||||
});
|
||||
const data = (await safeParseJsonResponse(res)) as {
|
||||
error?: string | { message?: string };
|
||||
rule?: { id: string; title: string };
|
||||
rule?: { id: string; title: string; createdAt?: string };
|
||||
} | null;
|
||||
const rule = data && typeof data === "object" ? data.rule : undefined;
|
||||
if (!res.ok || !rule) {
|
||||
@@ -248,7 +248,14 @@ export async function publishRule(input: {
|
||||
status: res.status,
|
||||
};
|
||||
}
|
||||
return { ok: true, id: rule.id, title: rule.title };
|
||||
return {
|
||||
ok: true,
|
||||
id: rule.id,
|
||||
title: rule.title,
|
||||
...(typeof rule.createdAt === "string" && rule.createdAt.length > 0
|
||||
? { createdAt: rule.createdAt }
|
||||
: {}),
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
ok: false as const,
|
||||
@@ -344,6 +351,7 @@ export type PublishedRuleDetailForClient = {
|
||||
title: string;
|
||||
summary: string | null;
|
||||
document: unknown;
|
||||
createdAt?: string;
|
||||
};
|
||||
|
||||
export type FetchPublishedRuleDetailResult = {
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
replaceMethodSectionsWithMethodSelections,
|
||||
withoutUnpublishedDecisionConsensus,
|
||||
} from "./ruleSectionsFromMethodSelections";
|
||||
import { publishedRuleAnalyticsFromState } from "./publishedRuleAnalytics";
|
||||
import { LAUNCH_SUPERMAJORITY_SHARE } from "./sharedTermsSection";
|
||||
import { templateCategoryToGroupKey } from "./templateReviewMapping";
|
||||
|
||||
@@ -191,6 +192,14 @@ export function buildPublishPayload(
|
||||
document.customMethodCardFieldBlocksById = fieldBlocks;
|
||||
}
|
||||
|
||||
const analytics = publishedRuleAnalyticsFromState(state);
|
||||
if (analytics.communityLocation) {
|
||||
document.communityLocation = analytics.communityLocation;
|
||||
}
|
||||
if (analytics.orgType) {
|
||||
document.orgType = analytics.orgType;
|
||||
}
|
||||
|
||||
if (summary !== undefined) {
|
||||
return { ok: true, title, summary, document };
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ const IDENTITY_KEYS = [
|
||||
"communityAvatarFileName",
|
||||
"communityContext",
|
||||
"communityLocation",
|
||||
"orgType",
|
||||
"communitySaveEmail",
|
||||
"title",
|
||||
] as const;
|
||||
|
||||
@@ -12,11 +12,24 @@ export type StoredLastPublishedRule = {
|
||||
title: string;
|
||||
summary?: string | null;
|
||||
document: Record<string, unknown>;
|
||||
/** ISO date the Rule was finished, for RULE.md front matter. */
|
||||
finishedAt?: string;
|
||||
/** Present after Make a copy; drives the copy-ready banner and lavender surface. */
|
||||
copiedFromTitle?: string;
|
||||
copiedNameHit?: CopiedNameHit | null;
|
||||
};
|
||||
|
||||
export function finishedAtIso(value: unknown): string | undefined {
|
||||
if (typeof value === "string" && value.trim().length > 0) {
|
||||
const date = new Date(value);
|
||||
if (!Number.isNaN(date.getTime())) return date.toISOString();
|
||||
}
|
||||
if (value instanceof Date && !Number.isNaN(value.getTime())) {
|
||||
return value.toISOString();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function writeLastPublishedRule(data: StoredLastPublishedRule): void {
|
||||
if (typeof sessionStorage === "undefined") return;
|
||||
sessionStorage.setItem(CREATE_FLOW_LAST_PUBLISHED_KEY, JSON.stringify(data));
|
||||
@@ -44,6 +57,10 @@ export function readLastPublishedRule(): StoredLastPublishedRule | null {
|
||||
} else {
|
||||
summary = undefined;
|
||||
}
|
||||
let finishedAt: string | undefined;
|
||||
if (typeof o.finishedAt === "string" && o.finishedAt.trim().length > 0) {
|
||||
finishedAt = o.finishedAt;
|
||||
}
|
||||
let copiedFromTitle: string | undefined;
|
||||
if (
|
||||
typeof o.copiedFromTitle === "string" &&
|
||||
@@ -69,6 +86,7 @@ export function readLastPublishedRule(): StoredLastPublishedRule | null {
|
||||
title: o.title,
|
||||
summary,
|
||||
document: doc as Record<string, unknown>,
|
||||
...(finishedAt ? { finishedAt } : {}),
|
||||
...(copiedFromTitle ? { copiedFromTitle } : {}),
|
||||
...(copiedNameHit ? { copiedNameHit } : {}),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { CreateFlowState } from "../../app/(app)/create/types";
|
||||
import { KINDS, type Kind } from "./deckTypes";
|
||||
import { groupAnswersFromCreateFlowState } from "./groupAnswers";
|
||||
|
||||
const LOCATION_MAX = 200;
|
||||
|
||||
function isKind(value: string): value is Kind {
|
||||
return (KINDS as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
function trimmedLocation(raw: unknown): string | undefined {
|
||||
if (typeof raw !== "string") return undefined;
|
||||
const trimmed = raw.trim().replace(/\s+/g, " ");
|
||||
if (trimmed.length === 0) return undefined;
|
||||
return trimmed.slice(0, LOCATION_MAX);
|
||||
}
|
||||
|
||||
/** Place and main group type stored on a finished Rule for launch counts. */
|
||||
export function publishedRuleAnalyticsFromState(state: CreateFlowState): {
|
||||
communityLocation?: string;
|
||||
orgType?: Kind;
|
||||
} {
|
||||
const communityLocation = trimmedLocation(state.communityLocation);
|
||||
const orgType = groupAnswersFromCreateFlowState(state).mainKind ?? undefined;
|
||||
return {
|
||||
...(communityLocation ? { communityLocation } : {}),
|
||||
...(orgType ? { orgType } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function publishedRuleAnalyticsFromDocument(document: unknown): {
|
||||
communityLocation: string | null;
|
||||
orgType: string | null;
|
||||
} {
|
||||
if (!document || typeof document !== "object" || Array.isArray(document)) {
|
||||
return { communityLocation: null, orgType: null };
|
||||
}
|
||||
const row = document as Record<string, unknown>;
|
||||
const communityLocation = trimmedLocation(row.communityLocation) ?? null;
|
||||
const orgTypeRaw =
|
||||
typeof row.orgType === "string" ? row.orgType.trim() : "";
|
||||
const orgType = isKind(orgTypeRaw) ? orgTypeRaw : null;
|
||||
return { communityLocation, orgType };
|
||||
}
|
||||
+200
-357
@@ -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, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
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(``, "");
|
||||
} 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, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import type { CommunityRuleEntry } from "../../app/components/type/CommunityRule/CommunityRule.types";
|
||||
import exportCopy from "../../messages/en/create/export.json";
|
||||
import { communityInviteInitials } from "./ruleInviteCardMeta";
|
||||
import { parsePublishedDocumentForCommunityRuleDisplay } from "./publishedDocumentToDisplaySections";
|
||||
import { RULE_SECTION_CATEGORY } from "./ruleSectionsFromMethodSelections";
|
||||
import { sharedTermsSection } from "./sharedTermsSection";
|
||||
import { askOrganizerUrl } from "../sharePaths";
|
||||
|
||||
export type RuleExportSource = {
|
||||
id: string;
|
||||
title: string;
|
||||
summary?: string | null;
|
||||
document: Record<string, unknown>;
|
||||
finishedAt?: string | Date | null;
|
||||
};
|
||||
|
||||
export type RuleExportLine = {
|
||||
lead?: string;
|
||||
body: string;
|
||||
};
|
||||
|
||||
export type RuleExportCard = {
|
||||
title: string;
|
||||
lines: RuleExportLine[];
|
||||
};
|
||||
|
||||
export type RuleExportSection = {
|
||||
title: string;
|
||||
cards: RuleExportCard[];
|
||||
};
|
||||
|
||||
export type RuleExportTerm = {
|
||||
term: string;
|
||||
meaning: string;
|
||||
};
|
||||
|
||||
export type RuleExportDocument = {
|
||||
title: string;
|
||||
summary: string;
|
||||
initials: string;
|
||||
photoUrl?: string;
|
||||
finishedOn?: string;
|
||||
sections: RuleExportSection[];
|
||||
terms: RuleExportTerm[];
|
||||
takeaway: string;
|
||||
takeawayUrl: string;
|
||||
credit: string;
|
||||
};
|
||||
|
||||
function leadIn(label: string): string {
|
||||
const trimmed = label.trim();
|
||||
if (trimmed.length === 0) return "";
|
||||
return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`;
|
||||
}
|
||||
|
||||
function splitParagraphs(text: string): string[] {
|
||||
return text
|
||||
.trim()
|
||||
.split(/\n\s*\n/)
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
}
|
||||
|
||||
function valueLines(body: string): RuleExportLine[] {
|
||||
const parts = splitParagraphs(body);
|
||||
if (parts.length === 0) return [];
|
||||
if (parts.length === 1) {
|
||||
const only = parts[0];
|
||||
return only ? [{ body: only }] : [];
|
||||
}
|
||||
const meaning = parts[0] ?? "";
|
||||
const signals = parts.slice(1).join(" ");
|
||||
const lines: RuleExportLine[] = [];
|
||||
if (meaning.length > 0) lines.push({ body: meaning });
|
||||
if (signals.length > 0) {
|
||||
lines.push({ lead: exportCopy.signalsLead, body: signals });
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function entryLines(
|
||||
entry: CommunityRuleEntry,
|
||||
valuesSection: boolean,
|
||||
): RuleExportLine[] {
|
||||
if (valuesSection) {
|
||||
return valueLines(entry.body ?? "");
|
||||
}
|
||||
const lines: RuleExportLine[] = [];
|
||||
const intro = (entry.body ?? "").trim();
|
||||
if (intro.length > 0) {
|
||||
for (const paragraph of splitParagraphs(intro)) {
|
||||
lines.push({ body: paragraph });
|
||||
}
|
||||
}
|
||||
for (const block of entry.blocks ?? []) {
|
||||
const body = block.body.trim();
|
||||
if (body.length === 0) continue;
|
||||
const lead = leadIn(block.label);
|
||||
if (lead.length > 0) {
|
||||
lines.push({ lead, body });
|
||||
} else {
|
||||
lines.push({ body });
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function photoUrlFromDocument(document: Record<string, unknown>): string | undefined {
|
||||
const raw = document.communityAvatarUrl;
|
||||
if (typeof raw !== "string") return undefined;
|
||||
const trimmed = raw.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function finishedOn(value: string | Date | null | undefined): string | undefined {
|
||||
if (value == null) return undefined;
|
||||
const date = typeof value === "string" ? new Date(value) : value;
|
||||
if (Number.isNaN(date.getTime())) return undefined;
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function buildRuleExportDocument(
|
||||
rule: RuleExportSource,
|
||||
origin: string,
|
||||
): RuleExportDocument {
|
||||
const title = rule.title.trim();
|
||||
const summary =
|
||||
typeof rule.summary === "string" ? rule.summary.trim() : "";
|
||||
const display = parsePublishedDocumentForCommunityRuleDisplay(rule.document);
|
||||
const sharedTitle = sharedTermsSection().categoryName;
|
||||
const sections: RuleExportSection[] = [];
|
||||
for (const section of display) {
|
||||
if (section.categoryName === sharedTitle) continue;
|
||||
const valuesSection =
|
||||
section.categoryName === RULE_SECTION_CATEGORY.values;
|
||||
const cards: RuleExportCard[] = [];
|
||||
for (const entry of section.entries) {
|
||||
const lines = entryLines(entry, valuesSection);
|
||||
if (lines.length === 0 && entry.title.trim().length === 0) continue;
|
||||
cards.push({ title: entry.title.trim(), lines });
|
||||
}
|
||||
if (cards.length === 0) continue;
|
||||
sections.push({ title: section.categoryName, cards });
|
||||
}
|
||||
const terms: RuleExportTerm[] = sharedTermsSection().entries.map((entry) => ({
|
||||
term: entry.title,
|
||||
meaning: (entry.body ?? "").trim(),
|
||||
}));
|
||||
return {
|
||||
title: title.length > 0 ? title : "Rule",
|
||||
summary,
|
||||
initials: communityInviteInitials(title.length > 0 ? title : "Rule"),
|
||||
photoUrl: photoUrlFromDocument(rule.document),
|
||||
finishedOn: finishedOn(rule.finishedAt),
|
||||
sections,
|
||||
terms,
|
||||
takeaway: exportCopy.takeaway,
|
||||
takeawayUrl: askOrganizerUrl(origin),
|
||||
credit: exportCopy.credit,
|
||||
};
|
||||
}
|
||||
|
||||
export function yamlQuote(value: string): string {
|
||||
if (value.length === 0) return '""';
|
||||
if (/[:#\n"'\\]/.test(value) || value !== value.trim()) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function exportPdfFilename(title: string): string {
|
||||
const cleaned = title
|
||||
.trim()
|
||||
.replace(/[\\/:*?"<>|]/g, "")
|
||||
.replace(/\s+/g, " ");
|
||||
const base = cleaned.length > 0 ? cleaned : "Rule";
|
||||
return `${base} Rule.pdf`;
|
||||
}
|
||||
|
||||
export const RULE_MD_FILENAME = exportCopy.ruleMdFilename;
|
||||
@@ -0,0 +1,228 @@
|
||||
import { jsPDF } from "jspdf";
|
||||
|
||||
import exportCopy from "../../messages/en/create/export.json";
|
||||
import type {
|
||||
RuleExportCard,
|
||||
RuleExportDocument,
|
||||
RuleExportLine,
|
||||
RuleExportTerm,
|
||||
} from "./ruleExportModel";
|
||||
|
||||
const PAGE_W = 215.9;
|
||||
const PAGE_H = 279.4;
|
||||
const MARGIN_X = 16.9;
|
||||
const MARGIN_TOP = 12.7;
|
||||
const FOOTER_Y = PAGE_H - 9.5;
|
||||
const CONTENT_BOTTOM = PAGE_H - 16;
|
||||
const COL_GAP = 8.5;
|
||||
const COL_W = (PAGE_W - 2 * MARGIN_X - COL_GAP) / 2;
|
||||
|
||||
function lineText(line: RuleExportLine): string {
|
||||
return line.lead ? `${line.lead} ${line.body}` : line.body;
|
||||
}
|
||||
|
||||
export function ruleExportDocumentToPdfBytes(docModel: RuleExportDocument): Uint8Array {
|
||||
const doc = new jsPDF({ unit: "mm", format: "letter" });
|
||||
const maxW = PAGE_W - 2 * MARGIN_X;
|
||||
let y = MARGIN_TOP;
|
||||
|
||||
function addPage(): void {
|
||||
doc.addPage();
|
||||
y = MARGIN_TOP;
|
||||
}
|
||||
|
||||
function ensureSpace(height: number): void {
|
||||
if (y + height > CONTENT_BOTTOM) addPage();
|
||||
}
|
||||
|
||||
function writeWrapped(
|
||||
text: string,
|
||||
opts: {
|
||||
size: number;
|
||||
style: "normal" | "bold" | "italic";
|
||||
width?: number;
|
||||
x?: number;
|
||||
gap?: number;
|
||||
},
|
||||
): void {
|
||||
const width = opts.width ?? maxW;
|
||||
const x = opts.x ?? MARGIN_X;
|
||||
doc.setFont("helvetica", opts.style);
|
||||
doc.setFontSize(opts.size);
|
||||
const lines = doc.splitTextToSize(text, width) as string[];
|
||||
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: width });
|
||||
ensureSpace(dim.h + 0.4);
|
||||
doc.text(lines, x, y);
|
||||
y += dim.h + (opts.gap ?? 1.6);
|
||||
}
|
||||
|
||||
function writeCard(card: RuleExportCard): void {
|
||||
writeWrapped(card.title, { size: 11, style: "bold", gap: 1.4 });
|
||||
for (const line of card.lines) {
|
||||
writeWrapped(lineText(line), { size: 9.5, style: "normal", gap: 2 });
|
||||
}
|
||||
y += 1;
|
||||
}
|
||||
|
||||
function termHeight(term: RuleExportTerm, width: number): number {
|
||||
doc.setFont("helvetica", "italic");
|
||||
doc.setFontSize(9);
|
||||
const termLines = doc.splitTextToSize(
|
||||
`${term.term} ${term.meaning}`,
|
||||
width,
|
||||
) as string[];
|
||||
const dim = doc.getTextDimensions(termLines.join("\n"), { maxWidth: width });
|
||||
return dim.h + 2.2;
|
||||
}
|
||||
|
||||
function writeTermAt(
|
||||
term: RuleExportTerm,
|
||||
x: number,
|
||||
top: number,
|
||||
width: number,
|
||||
): number {
|
||||
const text = `${term.term} ${term.meaning}`;
|
||||
doc.setFont("helvetica", "italic");
|
||||
doc.setFontSize(9);
|
||||
const lines = doc.splitTextToSize(text, width) as string[];
|
||||
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: width });
|
||||
doc.text(lines, x, top);
|
||||
return dim.h + 2.2;
|
||||
}
|
||||
|
||||
function writeTerms(terms: RuleExportTerm[]): void {
|
||||
let index = 0;
|
||||
while (index < terms.length) {
|
||||
if (y > CONTENT_BOTTOM - 10) addPage();
|
||||
const colTop = y;
|
||||
const left: RuleExportTerm[] = [];
|
||||
let leftH = 0;
|
||||
while (index < terms.length) {
|
||||
const next = terms[index];
|
||||
if (!next) break;
|
||||
const height = termHeight(next, COL_W);
|
||||
if (leftH > 0 && colTop + leftH + height > CONTENT_BOTTOM) break;
|
||||
if (leftH === 0 && colTop + height > CONTENT_BOTTOM) {
|
||||
addPage();
|
||||
break;
|
||||
}
|
||||
left.push(next);
|
||||
leftH += height;
|
||||
index += 1;
|
||||
}
|
||||
if (left.length === 0) {
|
||||
const overflow = terms[index];
|
||||
if (!overflow) break;
|
||||
left.push(overflow);
|
||||
index += 1;
|
||||
}
|
||||
const right: RuleExportTerm[] = [];
|
||||
let rightH = 0;
|
||||
while (index < terms.length) {
|
||||
const next = terms[index];
|
||||
if (!next) break;
|
||||
const height = termHeight(next, COL_W);
|
||||
if (right.length > 0 && colTop + rightH + height > CONTENT_BOTTOM) {
|
||||
break;
|
||||
}
|
||||
if (right.length === 0 && colTop + height > CONTENT_BOTTOM) break;
|
||||
right.push(next);
|
||||
rightH += height;
|
||||
index += 1;
|
||||
}
|
||||
let leftY = colTop;
|
||||
for (const term of left) {
|
||||
leftY += writeTermAt(term, MARGIN_X, leftY, COL_W);
|
||||
}
|
||||
let rightY = colTop;
|
||||
for (const term of right) {
|
||||
rightY += writeTermAt(
|
||||
term,
|
||||
MARGIN_X + COL_W + COL_GAP,
|
||||
rightY,
|
||||
COL_W,
|
||||
);
|
||||
}
|
||||
y = Math.max(leftY, rightY);
|
||||
}
|
||||
}
|
||||
|
||||
doc.setTextColor(0, 0, 0);
|
||||
doc.setDrawColor(20, 20, 20);
|
||||
doc.setLineWidth(0.5);
|
||||
doc.circle(MARGIN_X + 9.5, y + 9.5, 9.5, "S");
|
||||
doc.setFont("helvetica", "bold");
|
||||
doc.setFontSize(11);
|
||||
doc.text(docModel.initials, MARGIN_X + 9.5, y + 11.2, { align: "center" });
|
||||
|
||||
const headerX = MARGIN_X + 25.4;
|
||||
const headerW = maxW - 25.4;
|
||||
const titleY = y;
|
||||
doc.setFont("helvetica", "bold");
|
||||
doc.setFontSize(16);
|
||||
const titleLines = doc.splitTextToSize(docModel.title, headerW) as string[];
|
||||
const titleDim = doc.getTextDimensions(titleLines.join("\n"), {
|
||||
maxWidth: headerW,
|
||||
});
|
||||
doc.text(titleLines, headerX, y + 6);
|
||||
let headerBottom = titleY + Math.max(19, titleDim.h + 4);
|
||||
if (docModel.summary.length > 0) {
|
||||
doc.setFont("helvetica", "normal");
|
||||
doc.setFontSize(10);
|
||||
const sumLines = doc.splitTextToSize(docModel.summary, headerW) as string[];
|
||||
const sumDim = doc.getTextDimensions(sumLines.join("\n"), {
|
||||
maxWidth: headerW,
|
||||
});
|
||||
doc.text(sumLines, headerX, titleY + titleDim.h + 8);
|
||||
headerBottom = titleY + titleDim.h + sumDim.h + 10;
|
||||
}
|
||||
y = Math.max(headerBottom, y + 22);
|
||||
|
||||
for (const section of docModel.sections) {
|
||||
doc.setDrawColor(20, 20, 20);
|
||||
doc.setLineWidth(0.25);
|
||||
ensureSpace(14);
|
||||
doc.line(MARGIN_X, y, PAGE_W - MARGIN_X, y);
|
||||
y += 5;
|
||||
writeWrapped(section.title, { size: 14, style: "bold", gap: 3 });
|
||||
for (const card of section.cards) {
|
||||
writeCard(card);
|
||||
}
|
||||
}
|
||||
|
||||
if (docModel.terms.length > 0) {
|
||||
doc.setDrawColor(20, 20, 20);
|
||||
doc.setLineWidth(0.25);
|
||||
ensureSpace(16);
|
||||
doc.line(MARGIN_X, y, PAGE_W - MARGIN_X, y);
|
||||
y += 5;
|
||||
writeWrapped(exportCopy.sharedTermsHeading, {
|
||||
size: 14,
|
||||
style: "bold",
|
||||
gap: 4,
|
||||
});
|
||||
writeTerms(docModel.terms);
|
||||
}
|
||||
|
||||
ensureSpace(8);
|
||||
y += 4;
|
||||
writeWrapped(`${docModel.takeaway} ${docModel.takeawayUrl}`, {
|
||||
size: 8,
|
||||
style: "normal",
|
||||
gap: 2,
|
||||
});
|
||||
|
||||
const pageCount = doc.getNumberOfPages();
|
||||
for (let i = 1; i <= pageCount; i += 1) {
|
||||
doc.setPage(i);
|
||||
doc.setFont("helvetica", "normal");
|
||||
doc.setFontSize(8);
|
||||
doc.setTextColor(70, 70, 70);
|
||||
doc.text(docModel.credit, MARGIN_X, FOOTER_Y);
|
||||
doc.text(String(i), PAGE_W - MARGIN_X, FOOTER_Y, { align: "right" });
|
||||
doc.setTextColor(0, 0, 0);
|
||||
}
|
||||
|
||||
const ab = doc.output("arraybuffer") as ArrayBuffer;
|
||||
return new Uint8Array(ab);
|
||||
}
|
||||
@@ -12,6 +12,10 @@ import {
|
||||
stakeholderInviteReplyTo,
|
||||
type RuleStakeholderInviteMailInput,
|
||||
} from "./ruleStakeholderInviteMail";
|
||||
import {
|
||||
buildRuleFollowUpMail,
|
||||
type RuleFollowUpMailInput,
|
||||
} from "./ruleFollowUpMail";
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value
|
||||
@@ -115,6 +119,20 @@ export async function sendRuleStakeholderInviteEmail(
|
||||
});
|
||||
}
|
||||
|
||||
/** 48-hour print follow-up to the address that holds the pen. */
|
||||
export async function sendRuleFollowUpEmail(
|
||||
input: RuleFollowUpMailInput,
|
||||
): Promise<void> {
|
||||
const { subject, text, html } = buildRuleFollowUpMail(input);
|
||||
await sendHtmlMail({
|
||||
to: input.to,
|
||||
subject,
|
||||
text,
|
||||
html,
|
||||
devLog: `[dev] Rule follow-up mail for ${input.to}`,
|
||||
});
|
||||
}
|
||||
|
||||
/** Notify support/organizers when a visitor submits the Ask an organizer form. */
|
||||
export async function sendOrganizerInquiryNotification(params: {
|
||||
/** Destination inbox (e.g. from ORGANIZER_INQUIRY_TO). */
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { publishedRuleAnalyticsFromDocument } from "../create/publishedRuleAnalytics";
|
||||
|
||||
export function publishedRuleAnalyticsColumns(document: unknown): {
|
||||
communityLocation: string | null;
|
||||
orgType: string | null;
|
||||
} {
|
||||
return publishedRuleAnalyticsFromDocument(document);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { createHmac, timingSafeEqual } from "crypto";
|
||||
|
||||
export function ruleExportToken(ruleId: string, pepper: string): string {
|
||||
return createHmac("sha256", pepper)
|
||||
.update(`rule-export:${ruleId}`)
|
||||
.digest("base64url");
|
||||
}
|
||||
|
||||
export function ruleExportTokenMatches(
|
||||
ruleId: string,
|
||||
token: string,
|
||||
pepper: string,
|
||||
): boolean {
|
||||
if (token.length === 0) return false;
|
||||
const expected = Buffer.from(ruleExportToken(ruleId, pepper));
|
||||
const actual = Buffer.from(token);
|
||||
if (expected.length !== actual.length) return false;
|
||||
return timingSafeEqual(expected, actual);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import type { PrismaClient } from "@prisma/client";
|
||||
import { logger } from "../logger";
|
||||
import { originFromHost } from "../siteMetadata";
|
||||
import { ruleExportMarkdownUrl, ruleExportPdfUrl } from "../sharePaths";
|
||||
import { getSessionPepper } from "./env";
|
||||
import { sendRuleFollowUpEmail } from "./mail";
|
||||
import { ruleExportToken } from "./ruleExportToken";
|
||||
|
||||
export const RULE_FOLLOW_UP_AFTER_MS = 48 * 60 * 60 * 1000;
|
||||
export const RULE_FOLLOW_UP_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export type RuleFollowUpResult = {
|
||||
sent: number;
|
||||
failed: number;
|
||||
skipped: number;
|
||||
};
|
||||
|
||||
export async function sendDueRuleFollowUpEmails(
|
||||
db: PrismaClient,
|
||||
now = new Date(),
|
||||
): Promise<RuleFollowUpResult> {
|
||||
const result: RuleFollowUpResult = { sent: 0, failed: 0, skipped: 0 };
|
||||
|
||||
let pepper: string;
|
||||
try {
|
||||
pepper = getSessionPepper();
|
||||
} catch (err) {
|
||||
logger.error({
|
||||
scope: "ruleFollowUp",
|
||||
message: err instanceof Error ? err.message : "SESSION_SECRET missing",
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
const origin = originFromHost(null);
|
||||
const dueBy = new Date(now.getTime() - RULE_FOLLOW_UP_AFTER_MS);
|
||||
const notBefore = new Date(now.getTime() - RULE_FOLLOW_UP_MAX_AGE_MS);
|
||||
|
||||
const rows = await db.publishedRule.findMany({
|
||||
where: {
|
||||
followUpEmailSentAt: null,
|
||||
userId: { not: null },
|
||||
createdAt: { lte: dueBy, gte: notBefore },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
user: { select: { email: true } },
|
||||
},
|
||||
});
|
||||
|
||||
for (const row of rows) {
|
||||
const email = row.user?.email?.trim().toLowerCase() ?? "";
|
||||
if (!email.includes("@")) {
|
||||
result.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const token = ruleExportToken(row.id, pepper);
|
||||
try {
|
||||
await sendRuleFollowUpEmail({
|
||||
to: email,
|
||||
origin,
|
||||
communityName: row.title,
|
||||
pdfUrl: ruleExportPdfUrl(origin, row.id, token),
|
||||
markdownUrl: ruleExportMarkdownUrl(origin, row.id, token),
|
||||
});
|
||||
await db.publishedRule.update({
|
||||
where: { id: row.id },
|
||||
data: { followUpEmailSentAt: now },
|
||||
});
|
||||
result.sent += 1;
|
||||
} catch (err) {
|
||||
result.failed += 1;
|
||||
logger.error({
|
||||
scope: "ruleFollowUp",
|
||||
message: err instanceof Error ? err.message : "send failed",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
logger.info({
|
||||
scope: "ruleFollowUp",
|
||||
sent: result.sent,
|
||||
failed: result.failed,
|
||||
skipped: result.skipped,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { ASSETS, getAssetPath } from "../assetUtils";
|
||||
import { communityPossessive } from "../create/ruleInviteCardMeta";
|
||||
import { RULE_MD_FILENAME } from "../create/ruleExportModel";
|
||||
|
||||
export const RULE_FOLLOW_UP_LOGO_PATH = getAssetPath(ASSETS.LOGO_MARK);
|
||||
|
||||
export type RuleFollowUpMailInput = {
|
||||
to: string;
|
||||
origin: string;
|
||||
communityName: string;
|
||||
pdfUrl: string;
|
||||
markdownUrl: string;
|
||||
};
|
||||
|
||||
export type RuleFollowUpMailContent = {
|
||||
subject: string;
|
||||
previewText: string;
|
||||
text: string;
|
||||
html: string;
|
||||
};
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
function originHost(origin: string): string {
|
||||
try {
|
||||
return new URL(origin).host;
|
||||
} catch {
|
||||
return origin.replace(/^https?:\/\//, "").replace(/\/$/, "");
|
||||
}
|
||||
}
|
||||
|
||||
export function buildRuleFollowUpMail(
|
||||
input: RuleFollowUpMailInput,
|
||||
): RuleFollowUpMailContent {
|
||||
const communityName = input.communityName.trim() || "A community";
|
||||
const possessive = communityPossessive(communityName);
|
||||
const origin = input.origin.replace(/\/$/, "");
|
||||
const kitUrl = `${origin}/kit`;
|
||||
const host = originHost(origin);
|
||||
const subject = `${possessive} Rule, printed`;
|
||||
const previewText = `Here is ${possessive} Rule as a PDF, ready to print.`;
|
||||
const intro = `Here is ${possessive} Rule as a PDF, ready to print or drop into your onboarding doc.`;
|
||||
const putIt =
|
||||
"Put it where members will see it, on the wall where you meet or at the top of the doc new members read.";
|
||||
const fixNow =
|
||||
"If anything in it already feels wrong, that is normal, and it is easier to fix now than in a year.";
|
||||
const officeHours = `Bring it to office hours if you want a second read. No signup, and the next one is listed at ${host}/kit.`;
|
||||
const signOff = "CommunityRule";
|
||||
const why = `Sent because you finished a Rule at ${host}.`;
|
||||
const madeBy =
|
||||
"CommunityRule is made by the Media Economies Design Lab at the University of Colorado Boulder.";
|
||||
const privacyUrl = `${origin}/privacy`;
|
||||
const aboutUrl = `${origin}/about`;
|
||||
const logoUrl = `${origin}${RULE_FOLLOW_UP_LOGO_PATH}`;
|
||||
|
||||
const text = [
|
||||
"Your Rule is ready to print",
|
||||
"",
|
||||
intro,
|
||||
"",
|
||||
"Download the PDF",
|
||||
input.pdfUrl,
|
||||
"",
|
||||
`Or download ${RULE_MD_FILENAME} for a wiki or a repository.`,
|
||||
input.markdownUrl,
|
||||
"",
|
||||
putIt,
|
||||
"",
|
||||
fixNow,
|
||||
"",
|
||||
officeHours,
|
||||
kitUrl,
|
||||
"",
|
||||
signOff,
|
||||
"",
|
||||
why,
|
||||
"",
|
||||
madeBy,
|
||||
`Privacy ${privacyUrl}`,
|
||||
].join("\n");
|
||||
|
||||
const html = followUpHtml({
|
||||
subject,
|
||||
previewText,
|
||||
intro,
|
||||
pdfUrl: input.pdfUrl,
|
||||
markdownUrl: input.markdownUrl,
|
||||
putIt,
|
||||
fixNow,
|
||||
officeHours,
|
||||
kitUrl,
|
||||
signOff,
|
||||
why,
|
||||
madeBy,
|
||||
privacyUrl,
|
||||
aboutUrl,
|
||||
logoUrl,
|
||||
kitHostPath: `${host}/kit`,
|
||||
});
|
||||
|
||||
return { subject, previewText, text, html };
|
||||
}
|
||||
|
||||
function followUpHtml(opts: {
|
||||
subject: string;
|
||||
previewText: string;
|
||||
intro: string;
|
||||
pdfUrl: string;
|
||||
markdownUrl: string;
|
||||
putIt: string;
|
||||
fixNow: string;
|
||||
officeHours: string;
|
||||
kitUrl: string;
|
||||
signOff: string;
|
||||
why: string;
|
||||
madeBy: string;
|
||||
privacyUrl: string;
|
||||
aboutUrl: string;
|
||||
logoUrl: string;
|
||||
kitHostPath: string;
|
||||
}): string {
|
||||
const pdfHref = escapeHtml(opts.pdfUrl);
|
||||
const mdHref = escapeHtml(opts.markdownUrl);
|
||||
const kitHref = escapeHtml(opts.kitUrl);
|
||||
const kitHostPath = escapeHtml(opts.kitHostPath);
|
||||
const officeLead = "Bring it to office hours if you want a second read. No signup, and the next one is listed at ";
|
||||
const officeHtml = opts.officeHours.startsWith(officeLead)
|
||||
? `${escapeHtml(officeLead)}<a href="${kitHref}" style="color:#000000;text-decoration:underline;">${kitHostPath}</a>.`
|
||||
: escapeHtml(opts.officeHours);
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>${escapeHtml(opts.subject)}</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:0;background:#e4e4e4;">
|
||||
<div style="display:none;max-height:0;overflow:hidden;mso-hide:all;">${escapeHtml(
|
||||
opts.previewText,
|
||||
)}</div>
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#e4e4e4;">
|
||||
<tr>
|
||||
<td align="center">
|
||||
<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="width:600px;max-width:600px;background:#ffffff;">
|
||||
<tr>
|
||||
<td style="background:#000000;padding:24px 32px;">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td style="font-family:'Bricolage Grotesque',Arial,sans-serif;font-size:22px;line-height:27px;color:#ffffff;padding-right:6px;">CommunityRule</td>
|
||||
<td>
|
||||
<img src="${escapeHtml(opts.logoUrl)}" width="27" height="27" alt="" style="display:block;border:0;width:27px;height:27px;" />
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding:40px 32px 56px;">
|
||||
<h1 style="margin:0 0 16px;font-family:'Bricolage Grotesque',Arial,sans-serif;font-size:36px;line-height:44px;font-weight:700;color:#000000;">Your Rule is ready to print</h1>
|
||||
<p style="margin:0 0 32px;font-family:Inter,Arial,sans-serif;font-size:18px;line-height:24px;color:#303030;">${escapeHtml(opts.intro)}</p>
|
||||
<p style="margin:0 0 16px;">
|
||||
<a href="${pdfHref}" style="display:inline-block;background:#141414;color:#ffffff;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:20px;font-weight:500;text-decoration:none;border-radius:9999px;padding:12px 16px;">Download the PDF</a>
|
||||
</p>
|
||||
<p style="margin:0 0 32px;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">
|
||||
Or download <a href="${mdHref}" style="color:#000000;text-decoration:underline;">${RULE_MD_FILENAME}</a> for a wiki or a repository.
|
||||
</p>
|
||||
<div style="height:1px;background:#e4e4e4;margin:0 0 32px;"></div>
|
||||
<p style="margin:0 0 20px;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:24px;color:#303030;">${escapeHtml(opts.putIt)}</p>
|
||||
<p style="margin:0 0 20px;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:24px;color:#303030;">${escapeHtml(opts.fixNow)}</p>
|
||||
<p style="margin:0 0 20px;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:24px;color:#303030;">${officeHtml}</p>
|
||||
<p style="margin:0 0 32px;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:24px;color:#000000;">${escapeHtml(opts.signOff)}</p>
|
||||
<div style="border-top:1px solid #e4e4e4;padding-top:24px;">
|
||||
<p style="margin:0 0 12px;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">${escapeHtml(opts.why)}</p>
|
||||
<p style="margin:0 0 12px;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">${escapeHtml(opts.madeBy)}</p>
|
||||
<p style="margin:0;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">
|
||||
<a href="${escapeHtml(opts.privacyUrl)}" style="color:#464646;text-decoration:underline;">Privacy</a>
|
||||
|
||||
<a href="${escapeHtml(opts.aboutUrl)}" style="color:#464646;text-decoration:underline;">About CommunityRule</a>
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
export const RULE_COUNT_FOLD_THRESHOLD = 5;
|
||||
|
||||
export type RuleCountRow = {
|
||||
orgType: string | null;
|
||||
place: string | null;
|
||||
};
|
||||
|
||||
export type RuleCountCell = {
|
||||
orgType: string | null;
|
||||
place: string | null;
|
||||
count: number;
|
||||
folded: boolean;
|
||||
};
|
||||
|
||||
export type RuleLaunchCounts = {
|
||||
finished: number;
|
||||
cells: RuleCountCell[];
|
||||
};
|
||||
|
||||
function normalizePlace(raw: string | null): string {
|
||||
return (raw ?? "").trim().replace(/\s+/g, " ").toLowerCase();
|
||||
}
|
||||
|
||||
function cellKey(orgType: string | null, placeKey: string): string {
|
||||
return `${orgType ?? ""}\u0000${placeKey}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finished-Rule counts by group type and place. Any cell under five is folded
|
||||
* so a single group cannot be picked out.
|
||||
*/
|
||||
export function aggregateRuleLaunchCounts(rows: RuleCountRow[]): RuleLaunchCounts {
|
||||
const grouped = new Map<
|
||||
string,
|
||||
{ orgType: string | null; place: string | null; count: number }
|
||||
>();
|
||||
for (const row of rows) {
|
||||
const orgType = row.orgType && row.orgType.trim().length > 0 ? row.orgType : null;
|
||||
const placeRaw = row.place && row.place.trim().length > 0 ? row.place.trim() : null;
|
||||
const key = cellKey(orgType, normalizePlace(placeRaw));
|
||||
const existing = grouped.get(key);
|
||||
if (existing) {
|
||||
existing.count += 1;
|
||||
} else {
|
||||
grouped.set(key, { orgType, place: placeRaw, count: 1 });
|
||||
}
|
||||
}
|
||||
|
||||
const shown: RuleCountCell[] = [];
|
||||
let foldedCount = 0;
|
||||
for (const cell of grouped.values()) {
|
||||
if (cell.count < RULE_COUNT_FOLD_THRESHOLD) {
|
||||
foldedCount += cell.count;
|
||||
continue;
|
||||
}
|
||||
shown.push({ ...cell, folded: false });
|
||||
}
|
||||
shown.sort((a, b) => b.count - a.count || (a.orgType ?? "").localeCompare(b.orgType ?? ""));
|
||||
if (foldedCount > 0) {
|
||||
shown.push({
|
||||
orgType: null,
|
||||
place: null,
|
||||
count: foldedCount,
|
||||
folded: true,
|
||||
});
|
||||
}
|
||||
return { finished: rows.length, cells: shown };
|
||||
}
|
||||
@@ -19,6 +19,38 @@ export function buildPublicRuleUrl(origin: string, ruleId: string): string {
|
||||
return `${base}${publishedRulePath(ruleId)}`;
|
||||
}
|
||||
|
||||
export const ASK_ORGANIZER_HASH = "ask-organizer";
|
||||
|
||||
/** Home Ask an organizer section. Exports link here; they do not embed the form. */
|
||||
export function askOrganizerUrl(origin: string): string {
|
||||
const base = origin.replace(/\/$/, "");
|
||||
return `${base}/#${ASK_ORGANIZER_HASH}`;
|
||||
}
|
||||
|
||||
export function ruleExportPdfPath(ruleId: string, token: string): string {
|
||||
return `/api/rules/${encodeURIComponent(ruleId)}/export/pdf?t=${encodeURIComponent(token)}`;
|
||||
}
|
||||
|
||||
export function ruleExportMarkdownPath(ruleId: string, token: string): string {
|
||||
return `/api/rules/${encodeURIComponent(ruleId)}/export/md?t=${encodeURIComponent(token)}`;
|
||||
}
|
||||
|
||||
export function ruleExportPdfUrl(
|
||||
origin: string,
|
||||
ruleId: string,
|
||||
token: string,
|
||||
): string {
|
||||
return `${origin.replace(/\/$/, "")}${ruleExportPdfPath(ruleId, token)}`;
|
||||
}
|
||||
|
||||
export function ruleExportMarkdownUrl(
|
||||
origin: string,
|
||||
ruleId: string,
|
||||
token: string,
|
||||
): string {
|
||||
return `${origin.replace(/\/$/, "")}${ruleExportMarkdownPath(ruleId, token)}`;
|
||||
}
|
||||
|
||||
export function buildShareRuleUrl(origin: string, shareSlug: string): string {
|
||||
const base = origin.replace(/\/$/, "");
|
||||
return `${base}${shareRulePath(shareSlug)}`;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Optional Umami tracker. Unset env vars mean no script ships.
|
||||
* Cookie-free mode is an Umami server setting, not this snippet.
|
||||
*/
|
||||
export function umamiTracker(): { src: string; websiteId: string } | null {
|
||||
const src = process.env.NEXT_PUBLIC_UMAMI_SRC?.trim() ?? "";
|
||||
const websiteId = process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID?.trim() ?? "";
|
||||
if (!src || !websiteId) return null;
|
||||
try {
|
||||
const url = new URL(src);
|
||||
if (url.protocol !== "https:" && url.protocol !== "http:") return null;
|
||||
return { src: url.href, websiteId };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user