Add PDF HTML template with typography, themes and TOC

This commit is contained in:
2026-07-06 11:40:24 +05:00
parent 9a74339087
commit 6316c09993
2 changed files with 166 additions and 0 deletions
@@ -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("&lt;script&gt;");
});
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);
});
});