Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
feat(cover-letter-export): add contact-parts helper, letter template, PDF generator and export guard
Khuram Niaz8716e59ef4f7
diff --git a/__tests__/canExportCoverLetter.spec.ts b/__tests__/canExportCoverLetter.spec.tsnew file mode 100644index 0000000..0da2dcd--- /dev/null+++ b/__tests__/canExportCoverLetter.spec.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from "vitest";+import { canExportCoverLetter } from "@/components/profile/cover-letter-export-dialog/canExportCoverLetter";++describe("canExportCoverLetter", () => {+ it("is false for empty, null and undefined content", () => {+ expect(canExportCoverLetter("")).toBe(false);+ expect(canExportCoverLetter(null)).toBe(false);+ expect(canExportCoverLetter(undefined)).toBe(false);+ });++ it("is false for whitespace-only content", () => {+ expect(canExportCoverLetter(" \n\t ")).toBe(false);+ });++ it("is false for markup carrying no text", () => {+ expect(canExportCoverLetter("<p></p>")).toBe(false);+ expect(canExportCoverLetter("<p> </p><p><br></p>")).toBe(false);+ expect(canExportCoverLetter("<ul><li></li></ul>")).toBe(false);+ });++ it("is true for real content", () => {+ expect(canExportCoverLetter("<p>Dear hiring manager,</p>")).toBe(true);+ });++ it("is true for text inside nested markup", () => {+ expect(canExportCoverLetter("<p><strong>Hi</strong></p>")).toBe(true);+ });++ it("is true for a bare text node with no tags", () => {+ expect(canExportCoverLetter("Hi")).toBe(true);+ });+});diff --git a/__tests__/coverLetterPdf.spec.ts b/__tests__/coverLetterPdf.spec.tsnew file mode 100644index 0000000..2929148--- /dev/null+++ b/__tests__/coverLetterPdf.spec.ts@@ -0,0 +1,171 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type React from "react";+import type { ContactInfo } from "@/models/profile.model";+import type { HtmlStyleSet } from "@/components/pdf-export/types";+import { defaultCoverLetterExportSettings } from "@/models/coverLetterExport.model";+import { stripEmptyParagraphs } from "@/components/profile/cover-letter-pdf/stripEmptyParagraphs";++const { pdf, toBlob, registerHyphenationCallback, htmlToPdfNodes } = vi.hoisted(+ () => {+ const toBlob = vi.fn(+ async () => new Blob(["%PDF"], { type: "application/pdf" }),+ );+ return {+ toBlob,+ // Typed params, so mock.calls is a tuple tsc can index into.+ pdf: vi.fn((_document: any) => ({ toBlob })),+ registerHyphenationCallback: vi.fn(),+ htmlToPdfNodes: vi.fn(+ (_html: string, _styleSet?: HtmlStyleSet) =>+ [] as React.ReactElement[],+ ),+ };+ },+);++// The real renderer never loads in jsdom; StyleSheet.create is identity so+// letter.styles.ts still returns a plain object tree.+vi.mock("@react-pdf/renderer", () => ({+ pdf,+ Font: { registerHyphenationCallback },+ StyleSheet: { create: (sheet: unknown) => sheet },+ Document: () => null,+ Page: () => null,+ Text: () => null,+ View: () => null,+ Link: () => null,+}));++vi.mock("@/components/pdf-export/html-to-pdf", () => ({ htmlToPdfNodes }));++import { generateCoverLetterPdfBlob } from "@/components/profile/cover-letter-pdf/generateCoverLetterPdf";++const contactInfo = {+ firstName: "Ada",+ lastName: "Lovelace",+ headline: "Engineer",+ email: "[email protected]",+} as ContactInfo;++const generate = (+ letter: { title: string; content: string },+ contact: ContactInfo | null = contactInfo,+) =>+ generateCoverLetterPdfBlob(letter, contact, defaultCoverLetterExportSettings);++beforeEach(() => {+ vi.clearAllMocks();+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-08-21T10:00:00Z"));+});++afterEach(() => {+ vi.useRealTimers();+});++describe("generateCoverLetterPdfBlob — filename", () => {+ it("derives the filename from the title, with no layout suffix", async () => {+ const { filename } = await generate({+ title: "Software Engineer - Google",+ content: "<p>Hi</p>",+ });+ expect(filename).toBe("Software Engineer - Google.pdf");+ });++ it("strips path and control characters from the title", async () => {+ const { filename } = await generate({+ title: "Dev/Ops: \x00report\x1f",+ content: "<p>Hi</p>",+ });+ expect(filename).toBe("DevOps report.pdf");+ });++ it("falls back to 'cover-letter' when the title sanitizes to nothing", async () => {+ const { filename } = await generate({+ title: '///:*?"<>|',+ content: "<p>Hi</p>",+ });+ expect(filename).toBe("cover-letter.pdf");+ });+});++describe("generateCoverLetterPdfBlob — document props", () => {+ it("passes the contact info through for the letterhead", async () => {+ await generate({ title: "Letter", content: "<p>Hi</p>" });+ expect(pdf.mock.calls[0][0].props.contactInfo).toBe(contactInfo);+ });++ it("passes null when there is no default resume contact info", async () => {+ await generate({ title: "Letter", content: "<p>Hi</p>" }, null);+ expect(pdf.mock.calls[0][0].props.contactInfo).toBeNull();+ });++ it("formats today's date as a business-letter date", async () => {+ await generate({ title: "Letter", content: "<p>Hi</p>" });+ expect(pdf.mock.calls[0][0].props.dateLabel).toBe("August 21, 2026");+ });++ it("titles the document from the letter title", async () => {+ await generate({ title: "Letter", content: "<p>Hi</p>" });+ expect(pdf.mock.calls[0][0].props.title).toBe("Letter");+ });++ it("returns the rendered blob", async () => {+ const { blob } = await generate({ title: "Letter", content: "<p>Hi</p>" });+ expect(blob.type).toBe("application/pdf");+ expect(toBlob).toHaveBeenCalledTimes(1);+ });++ it("registers the no-op hyphenation callback", async () => {+ await generate({ title: "Letter", content: "<p>Hi</p>" });+ expect(registerHyphenationCallback).toHaveBeenCalledTimes(1);+ });+});++describe("generateCoverLetterPdfBlob — body conversion", () => {+ it("converts the body with the letter's own htmlStyles", async () => {+ await generate({ title: "Letter", content: "<p>Hi</p>" });+ const [, styleSet] = htmlToPdfNodes.mock.calls[0];+ // paragraphSpacing lands on bodyText.marginBottom, which is what+ // distinguishes the letter's style set from the resume's.+ expect(styleSet!.bodyText).toEqual({ fontSize: 11, marginBottom: 10 });+ expect(styleSet!.bulletChar).toBe("•");+ });++ it("drops blank paragraphs before converting", async () => {+ await generate({+ title: "Letter",+ content: "<p>One</p><p></p><p>Two</p>",+ });+ expect(htmlToPdfNodes.mock.calls[0][0]).toBe("<p>One</p><p>Two</p>");+ });+});++describe("stripEmptyParagraphs", () => {+ it("drops an empty paragraph", () => {+ expect(stripEmptyParagraphs("<p>a</p><p></p><p>b</p>")).toBe(+ "<p>a</p><p>b</p>",+ );+ });++ it("drops a whitespace-only and an nbsp-only paragraph", () => {+ expect(stripEmptyParagraphs("<p>a</p><p> </p><p> </p>")).toBe(+ "<p>a</p>",+ );+ });++ it("drops a paragraph holding only a line break", () => {+ expect(stripEmptyParagraphs("<p><br></p><p>a</p>")).toBe("<p>a</p>");+ });++ it("keeps a paragraph with real text", () => {+ expect(stripEmptyParagraphs("<p>Dear hiring manager,</p>")).toBe(+ "<p>Dear hiring manager,</p>",+ );+ });++ it("leaves lists and headings alone", () => {+ const html = "<h2>Why me</h2><ul><li>One</li></ul>";+ expect(stripEmptyParagraphs(html)).toBe(html);+ });+});diff --git a/__tests__/pdfContactParts.spec.ts b/__tests__/pdfContactParts.spec.tsnew file mode 100644index 0000000..fc9dcb7--- /dev/null+++ b/__tests__/pdfContactParts.spec.ts@@ -0,0 +1,51 @@+import { describe, it, expect } from "vitest";+import type { ContactInfo } from "@/models/profile.model";+import { buildContactParts } from "@/components/profile/pdf-contact-parts";++const contact = (patch: Partial<ContactInfo>) => patch as ContactInfo;++describe("buildContactParts", () => {+ it("returns an empty list for null or undefined", () => {+ expect(buildContactParts(null)).toEqual([]);+ expect(buildContactParts(undefined)).toEqual([]);+ });++ it("orders email, phone, address, url1, url2", () => {+ const parts = buildContactParts(+ contact({+ email: "[email protected]",+ phone: "555-0100",+ address: "London",+ url1: "https://www.example.com/ada",+ url2: "http://github.com/ada",+ }),+ );+ expect(parts.map((p) => p.text)).toEqual([+ "[email protected]",+ "555-0100",+ "London",+ "example.com/ada",+ "github.com/ada",+ ]);+ });++ // The display text drops the scheme and www; the href keeps them, so the+ // link still resolves.+ it("keeps the full URL as the href", () => {+ const [part] = buildContactParts(+ contact({ url1: "https://www.example.com/ada" }),+ );+ expect(part.href).toBe("https://www.example.com/ada");+ });++ it("gives non-URL parts no href", () => {+ const [part] = buildContactParts(contact({ email: "[email protected]" }));+ expect(part.href).toBeUndefined();+ });++ it("skips every empty field", () => {+ expect(+ buildContactParts(contact({ email: "", phone: undefined, address: "" })),+ ).toEqual([]);+ });+});diff --git a/src/components/profile/cover-letter-export-dialog/canExportCoverLetter.ts b/src/components/profile/cover-letter-export-dialog/canExportCoverLetter.tsnew file mode 100644index 0000000..95a0f93--- /dev/null+++ b/src/components/profile/cover-letter-export-dialog/canExportCoverLetter.ts@@ -0,0 +1,14 @@+// The one rule for what counts as an exportable letter. The dialog reads it+// to disable Export up front; the export handler keeps it as a safety net.+//+// A plain module with no @react-pdf/renderer anywhere in its graph — the+// same reason canExportResume sits outside the resume-pdf barrel. Importing+// it must not pull the renderer into an eagerly-loaded chunk.+export function canExportCoverLetter(+ content: string | null | undefined,+): boolean {+ if (!content || !content.trim()) return false;+ const text = new DOMParser().parseFromString(content, "text/html").body+ .textContent;+ return Boolean(text && text.trim());+}diff --git a/src/components/profile/cover-letter-pdf/CoverLetterTemplate.tsx b/src/components/profile/cover-letter-pdf/CoverLetterTemplate.tsxnew file mode 100644index 0000000..cbf69a6--- /dev/null+++ b/src/components/profile/cover-letter-pdf/CoverLetterTemplate.tsx@@ -0,0 +1,69 @@+import React from "react";+import { Document, Link, Page, Text, View } from "@react-pdf/renderer";+import type { ContactInfo } from "@/models/profile.model";+import { buildContactParts } from "../pdf-contact-parts";+import type { LetterStyles } from "./styles/letter.styles";++type Props = {+ title: string;+ contactInfo: ContactInfo | null;+ dateLabel: string;+ bodyNodes: React.ReactElement[];+ styles: LetterStyles;+};++// The body already carries its own salutation and its "Sincerely," close —+// that comes from the generation prompt and is stored in `content`. This+// template never injects a salutation, a recipient block or a signature.+export function CoverLetterDocument({+ title,+ contactInfo,+ dateLabel,+ bodyNodes,+ styles,+}: Props) {+ const contactParts = buildContactParts(contactInfo);++ return (+ <Document+ author={`${contactInfo?.firstName ?? ""} ${contactInfo?.lastName ?? ""}`.trim()}+ creator="jobsync.ca"+ producer="react-pdf"+ title={title}+ >+ <Page size="A4" style={styles.page} wrap>+ {contactInfo && (+ <View>+ <Text style={styles.name}>+ {contactInfo.firstName} {contactInfo.lastName}+ </Text>+ {contactInfo.headline ? (+ <Text style={styles.headline}>{contactInfo.headline}</Text>+ ) : null}+ {contactParts.length > 0 ? (+ <View style={styles.contactRow}>+ {contactParts.map((part, i) => (+ <Text key={i} style={styles.contactLine}>+ {i > 0 ? " · " : ""}+ {part.href ? (+ <Link src={part.href} style={styles.link}>+ {part.text}+ </Link>+ ) : (+ part.text+ )}+ </Text>+ ))}+ </View>+ ) : null}+ <View style={styles.rule} />+ </View>+ )}++ <Text style={styles.date}>{dateLabel}</Text>++ {bodyNodes}+ </Page>+ </Document>+ );+}diff --git a/src/components/profile/cover-letter-pdf/generateCoverLetterPdf.tsx b/src/components/profile/cover-letter-pdf/generateCoverLetterPdf.tsxnew file mode 100644index 0000000..dfeaf62--- /dev/null+++ b/src/components/profile/cover-letter-pdf/generateCoverLetterPdf.tsx@@ -0,0 +1,44 @@+import React from "react";+import { format } from "date-fns";+import { htmlToPdfNodes } from "@/components/pdf-export/html-to-pdf";+import { sanitizeFilename } from "@/components/pdf-export/download";+import type { ContactInfo } from "@/models/profile.model";+import type { CoverLetterExportSettings } from "@/models/coverLetterExport.model";+import { buildLetterStyles } from "./styles/letter.styles";+import { stripEmptyParagraphs } from "./stripEmptyParagraphs";++export async function generateCoverLetterPdfBlob(+ letter: { title: string; content: string },+ contactInfo: ContactInfo | null,+ settings: CoverLetterExportSettings,+): Promise<{ blob: Blob; filename: string }> {+ const { pdf, Font } = await import("@react-pdf/renderer");+ Font.registerHyphenationCallback((word) => [word]);++ const { styles, htmlStyles } = buildLetterStyles(settings);+ // Parse on the main thread before entering react-pdf's rendering context.+ const bodyNodes = htmlToPdfNodes(+ stripEmptyParagraphs(letter.content),+ htmlStyles,+ );++ // Spelled-out month, the conventional business-letter form — deliberately+ // not the app's "PP", whose abbreviated month reads as UI, not letterhead.+ const dateLabel = format(new Date(), "MMMM d, yyyy");++ const { CoverLetterDocument } = await import("./CoverLetterTemplate");+ const document = (+ <CoverLetterDocument+ title={letter.title}+ contactInfo={contactInfo}+ dateLabel={dateLabel}+ bodyNodes={bodyNodes}+ styles={styles}+ />+ );++ const blob = await pdf(document as any).toBlob();+ // No layout suffix: a letter has exactly one style.+ const filename = `${sanitizeFilename(letter.title, "cover-letter")}.pdf`;+ return { blob, filename };+}diff --git a/src/components/profile/cover-letter-pdf/stripEmptyParagraphs.ts b/src/components/profile/cover-letter-pdf/stripEmptyParagraphs.tsnew file mode 100644index 0000000..0268c41--- /dev/null+++ b/src/components/profile/cover-letter-pdf/stripEmptyParagraphs.ts@@ -0,0 +1,8 @@+// html-to-pdf maps every <p> to a bodyText Text, including an empty one.+// With paragraphSpacing on bodyText.marginBottom, a blank line a user typed+// in Tiptap would print as an empty line plus a full paragraph gap. Dropping+// them here rather than in the shared converter keeps every exported resume+// byte-for-byte what it was.+export function stripEmptyParagraphs(html: string): string {+ return html.replace(/<p>(?:\s| |<br\s*\/?>)*<\/p>/gi, "");+}diff --git a/src/components/profile/pdf-contact-parts.ts b/src/components/profile/pdf-contact-parts.tsnew file mode 100644index 0000000..6962870--- /dev/null+++ b/src/components/profile/pdf-contact-parts.ts@@ -0,0 +1,25 @@+import type { ContactInfo } from "@/models/profile.model";++export type ContactPart = { text: string; href?: string };++// The one-line "email · phone · address · url1 · url2" assembly, shared by+// SimpleTemplate's header and the cover letter's letterhead. Professional's+// header is a different two-column layout and deliberately does not use this.+export function buildContactParts(+ contactInfo: ContactInfo | null | undefined,+): ContactPart[] {+ if (!contactInfo) return [];+ const stripScheme = (url: string) => url.replace(/^https?:\/\/(www\.)?/, "");++ return [+ contactInfo.email ? { text: contactInfo.email } : null,+ contactInfo.phone ? { text: contactInfo.phone } : null,+ contactInfo.address ? { text: contactInfo.address } : null,+ contactInfo.url1+ ? { text: stripScheme(contactInfo.url1), href: contactInfo.url1 }+ : null,+ contactInfo.url2+ ? { text: stripScheme(contactInfo.url2), href: contactInfo.url2 }+ : null,+ ].filter((p): p is ContactPart => p !== null);+}diff --git a/src/components/profile/resume-pdf/SimpleTemplate.tsx b/src/components/profile/resume-pdf/SimpleTemplate.tsxindex fd5e589..9d5f1bc 100644--- a/src/components/profile/resume-pdf/SimpleTemplate.tsx+++ b/src/components/profile/resume-pdf/SimpleTemplate.tsx@@ -2,6 +2,7 @@ import React from "react";import { Document, Link, Page, Text, View } from "@react-pdf/renderer";import { format } from "date-fns";import { Resume, SectionType } from "@/models/profile.model";+import { buildContactParts } from "../pdf-contact-parts";import type { SimpleStyles } from "./styles/simple.styles";import { ResumeHtmlNodes } from "./generateResumePdf";@@ -51,18 +52,7 @@ export function SimpleResumeDocument({ resume, htmlNodes, styles }: Props) {(s) => s.sectionType === SectionType.CERTIFICATION,);- type ContactPart = { text: string; href?: string };- const contactParts: ContactPart[] = [- ContactInfo?.email ? { text: ContactInfo.email } : null,- ContactInfo?.phone ? { text: ContactInfo.phone } : null,- ContactInfo?.address ? { text: ContactInfo.address } : null,- ContactInfo?.url1- ? { text: ContactInfo.url1.replace(/^https?:\/\/(www\.)?/, ""), href: ContactInfo.url1 }- : null,- ContactInfo?.url2- ? { text: ContactInfo.url2.replace(/^https?:\/\/(www\.)?/, ""), href: ContactInfo.url2 }- : null,- ].filter((p): p is ContactPart => p !== null);+ const contactParts = buildContactParts(ContactInfo);return (<Document