SPB Git

Repository Public MIT

pdf.ts 1.3 KB 39 lines typescript

1import { reloadIfLocked } from "@/lib/queryClient";23function slug(text: string): string {4  const s = text5    .normalize("NFD")6    .replace(/[\u0300-\u036f]/g, "")7    .replace(/[^a-zA-Z0-9]+/g, "-")8    .replace(/^-+|-+$/g, "")9    .toLowerCase()10    .slice(0, 60)11    .replace(/-+$/, "");12  return s || "analyse";13}1415/** Title of an analysis: its own top heading when it has one, otherwise the question. */16function titleOf(question: string, answer: string): string {17  const h1 = answer.trimStart().match(/^#\s+(.+)$/m);18  return h1 && answer.trimStart().startsWith("#") ? h1[1].replace(/[*_`#]/g, "").trim() : question;19}2021/** Renders the analysis as a PDF research note on the server and saves it. Throws on failure. */22export async function downloadAnalysisPdf(question: string, answer: string): Promise<void> {23  const res = await fetch("/api/generate-pdf", {24    method: "POST",25    headers: { "Content-Type": "application/json" },26    body: JSON.stringify({ question, answer }),27  });28  reloadIfLocked(res);29  if (!res.ok) throw new Error(`HTTP ${res.status}`);30  const url = URL.createObjectURL(await res.blob());31  const a = document.createElement("a");32  a.href = url;33  a.download = `VQuant-${slug(titleOf(question, answer))}-${new Date().toISOString().slice(0, 10)}.pdf`;34  document.body.appendChild(a);35  a.click();36  a.remove();37  URL.revokeObjectURL(url);38}39
Files main
Menu

Theme