Add PDF HTML template with typography, themes and TOC
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildCleanHtml, safePdfFilename } from "@/lib/clean-pdf/template";
|
||||
|
||||
const base = {
|
||||
title: "Заголовок статьи",
|
||||
url: "https://example.com/article",
|
||||
theme: "light" as const,
|
||||
};
|
||||
|
||||
describe("buildCleanHtml", () => {
|
||||
it("экранирует HTML в метаполях", () => {
|
||||
const html = buildCleanHtml({ ...base, title: `<script>alert(1)</script>`, contentHtml: "<p>ок</p>" });
|
||||
expect(html).not.toContain("<script>alert(1)</script>");
|
||||
expect(html).toContain("<script>");
|
||||
});
|
||||
|
||||
it("вставляет контент и шапку", () => {
|
||||
const html = buildCleanHtml({ ...base, author: "Автор", site: "Example", contentHtml: "<p>Текст статьи</p>" });
|
||||
expect(html).toContain("<p>Текст статьи</p>");
|
||||
expect(html).toContain("Заголовок статьи");
|
||||
expect(html).toContain("Автор");
|
||||
expect(html).toContain("https://example.com/article");
|
||||
});
|
||||
|
||||
it("строит оглавление при 3+ заголовках и проставляет якоря", () => {
|
||||
const content = "<h2>Один</h2><p>a</p><h2>Два</h2><p>b</p><h3>Три</h3><p>c</p>";
|
||||
const html = buildCleanHtml({ ...base, contentHtml: content });
|
||||
expect(html).toContain("Содержание");
|
||||
expect(html).toMatch(/<h2 id="[^"]+">Один<\/h2>/);
|
||||
expect((html.match(/class="toc-item/g) ?? []).length).toBe(3);
|
||||
});
|
||||
|
||||
it("не строит оглавление при <3 заголовках", () => {
|
||||
const html = buildCleanHtml({ ...base, contentHtml: "<h2>Один</h2><p>a</p>" });
|
||||
expect(html).not.toContain("Содержание");
|
||||
});
|
||||
|
||||
it("уникализирует одинаковые якоря", () => {
|
||||
const content = "<h2>Раздел</h2><h2>Раздел</h2><h2>Раздел</h2>";
|
||||
const html = buildCleanHtml({ ...base, contentHtml: content });
|
||||
const ids = [...html.matchAll(/<h2 id="([^"]+)"/g)].map((m) => m[1]);
|
||||
expect(new Set(ids).size).toBe(3);
|
||||
});
|
||||
|
||||
it("переключает тёмную тему", () => {
|
||||
const light = buildCleanHtml({ ...base, contentHtml: "<p>x</p>" });
|
||||
const dark = buildCleanHtml({ ...base, theme: "dark", contentHtml: "<p>x</p>" });
|
||||
expect(light).toContain('data-theme="light"');
|
||||
expect(dark).toContain('data-theme="dark"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("safePdfFilename", () => {
|
||||
it("убирает опасные символы и ограничивает длину", () => {
|
||||
expect(safePdfFilename('Статья: как/не\\надо "делать"?')).toBe("Статья_ как_не_надо _делать_");
|
||||
expect(safePdfFilename("")).toBe("document");
|
||||
expect(safePdfFilename("a".repeat(300)).length).toBeLessThanOrEqual(140);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import { JSDOM } from "jsdom";
|
||||
|
||||
export interface CleanArticle {
|
||||
title: string;
|
||||
author?: string;
|
||||
site?: string;
|
||||
url: string;
|
||||
contentHtml: string;
|
||||
theme: "light" | "dark";
|
||||
}
|
||||
|
||||
function escapeHtml(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
export function safePdfFilename(title: string): string {
|
||||
const cleaned = title.replace(/[\\/:"*?<>|\n\r]+/g, "_").trim().slice(0, 140);
|
||||
return cleaned || "document";
|
||||
}
|
||||
|
||||
interface TocEntry { id: string; text: string; level: 2 | 3 }
|
||||
|
||||
/** Проставляет id заголовкам h2/h3 и возвращает контент + записи оглавления. */
|
||||
function prepareContent(contentHtml: string): { html: string; toc: TocEntry[] } {
|
||||
const dom = new JSDOM(`<body>${contentHtml}</body>`);
|
||||
const doc = dom.window.document;
|
||||
const used = new Set<string>();
|
||||
const toc: TocEntry[] = [];
|
||||
|
||||
doc.querySelectorAll("h2, h3").forEach((h) => {
|
||||
const text = (h.textContent ?? "").trim();
|
||||
if (!text) return;
|
||||
let id = text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "") || "section";
|
||||
let i = 2;
|
||||
while (used.has(id)) id = `${id}-${i++}`;
|
||||
used.add(id);
|
||||
h.id = id;
|
||||
toc.push({ id, text, level: h.tagName === "H2" ? 2 : 3 });
|
||||
});
|
||||
|
||||
return { html: doc.body.innerHTML, toc };
|
||||
}
|
||||
|
||||
const CSS = `
|
||||
:root[data-theme="light"] { --bg: #faf7f0; --fg: #1f1d1a; --muted: #6b6459; --line: #d8d2c4; --accent: #7a2e2e; }
|
||||
:root[data-theme="dark"] { --bg: #201e1b; --fg: #e8e4dc; --muted: #a39b8d; --line: #3d3a34; --accent: #d4a0a0; }
|
||||
* { box-sizing: border-box; }
|
||||
body { background: var(--bg); color: var(--fg); font-family: Georgia, "Times New Roman", serif;
|
||||
font-size: 12.5pt; line-height: 1.65; margin: 0; }
|
||||
main { max-width: 100%; }
|
||||
h1 { font-size: 22pt; line-height: 1.25; margin: 0 0 6pt; }
|
||||
h2 { font-size: 16pt; margin: 20pt 0 8pt; }
|
||||
h3 { font-size: 13.5pt; margin: 16pt 0 6pt; }
|
||||
p { margin: 0 0 9pt; }
|
||||
a { color: var(--accent); text-decoration: none; }
|
||||
img, video, iframe { max-width: 100%; height: auto; }
|
||||
pre { background: rgba(127,127,127,.08); border: 1px solid var(--line); padding: 8pt;
|
||||
overflow-x: hidden; white-space: pre-wrap; word-wrap: break-word;
|
||||
font-family: "SF Mono", Menlo, Consolas, monospace; font-size: 9.5pt; }
|
||||
code { font-family: "SF Mono", Menlo, Consolas, monospace; font-size: 0.9em; }
|
||||
blockquote { border-left: 3px solid var(--line); margin: 0 0 9pt; padding: 2pt 0 2pt 12pt; color: var(--muted); }
|
||||
table { border-collapse: collapse; width: 100%; font-size: 10.5pt; }
|
||||
th, td { border: 1px solid var(--line); padding: 4pt 6pt; text-align: left; }
|
||||
figure { margin: 0 0 9pt; } figcaption { color: var(--muted); font-size: 9.5pt; }
|
||||
.meta { color: var(--muted); font-size: 10pt; margin-bottom: 4pt; }
|
||||
.meta a { color: var(--muted); }
|
||||
.head-rule { border: 0; border-top: 1px solid var(--line); margin: 12pt 0 16pt; }
|
||||
.toc { border: 1px solid var(--line); padding: 10pt 14pt; margin: 0 0 16pt; }
|
||||
.toc-title { font-weight: bold; margin-bottom: 6pt; }
|
||||
.toc-item { display: block; margin: 2pt 0; }
|
||||
.toc-item.lvl3 { padding-left: 14pt; font-size: 0.92em; }
|
||||
h2, h3 { break-after: avoid; } pre, blockquote, figure, table { break-inside: avoid; }
|
||||
`;
|
||||
|
||||
export function buildCleanHtml(article: CleanArticle): string {
|
||||
const { html, toc } = prepareContent(article.contentHtml);
|
||||
const metaParts = [article.site, article.author].filter(Boolean).map((s) => escapeHtml(s!));
|
||||
|
||||
const tocHtml = toc.length >= 3
|
||||
? `<nav class="toc"><div class="toc-title">Содержание</div>${toc
|
||||
.map((t) => `<a class="toc-item lvl${t.level}" href="#${t.id}">${escapeHtml(t.text)}</a>`)
|
||||
.join("")}</nav>`
|
||||
: "";
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="ru" data-theme="${article.theme}">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>${escapeHtml(article.title)}</title>
|
||||
<style>${CSS}</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>${escapeHtml(article.title)}</h1>
|
||||
${metaParts.length ? `<div class="meta">${metaParts.join(" · ")}</div>` : ""}
|
||||
<div class="meta"><a href="${escapeHtml(article.url)}">${escapeHtml(article.url)}</a></div>
|
||||
<hr class="head-rule">
|
||||
${tocHtml}
|
||||
${html}
|
||||
</main>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
Reference in New Issue
Block a user