release: 发布 v0.5.1

新增能力:内置 4 套红头、3 套正式文档和 3 套标书主题,支持主题推荐页边距、页面装饰、页眉页脚和页码;增加结构化公文、项目报告及标书 Front Matter,内置 Fandol 中文字体、两份教程和 14 份主题示例。

桌面工作流:重组更多菜单,增加新建、保存、另存为快捷键和未保存确认;另存为后跟随新路径,主题示例自动切换主题,Desktop 发行包完整携带教程、示例与字体。

问题修复:修正红头标题居中与正式文档字体;围栏代码按正文宽度自动换行,长内容安全断行,至少两行即可在当前页分页,并统一保留 8px 左侧内容留白;Docker Web 镜像正确打包 samples。

兼容与部署:未声明主题推荐设置时继续使用 16mm 默认页边距;Web 隐藏不适用的另存为。正式镜像 yixiong/md-to-pdf:v0.5.1 内容 ID 为 sha256:72f519a69bfd6cb2f6df30c2be938e58ceb6f20e4748a32551874de3d436b276,Compose 健康运行。

验证结果:最终修复前 65 个测试文件、286 项测试通过,最终代码块与主题定向测试 27 项通过;全项目类型检查、生产构建和 git diff --check 通过。容器检出 14 套主题、17 份 Markdown,代码块回归 PDF 为 2 页且无越界。NSIS SHA-256 为 676CCE73D782B0B15AC6BC68F253CFBC4740383583E4DAA98F746EDF9999C5CC,ZIP SHA-256 为 82BF6ADF1200604F145CC86FA3ED193955CF6741EBEE3DF8953483515CFF621F。
This commit is contained in:
SkyJourney
2026-07-29 16:58:17 +08:00
parent 58087d0c7e
commit 83e6559c2c
111 changed files with 8274 additions and 173 deletions
@@ -0,0 +1,134 @@
const PREPARED_ATTRIBUTE = "data-code-pagination-prepared";
const CHUNK_CLASS = "md-code-pagination-chunk";
const CHUNK_POSITION_ATTRIBUTE = "data-code-pagination-position";
const LINE_GROUP_CLASS = "md-code-line-group";
const LINE_CLASS = "md-code-line";
function splitNodeIntoLines(node: Node): Node[][] {
const documentRef = node.ownerDocument;
if (!documentRef) {
throw new Error("代码块分页节点缺少 ownerDocument");
}
if (node.nodeType === node.TEXT_NODE) {
return (node.textContent ?? "").split("\n").map((text) => [
documentRef.createTextNode(text)
]);
}
if (node.nodeType !== node.ELEMENT_NODE) {
return [[node.cloneNode(true)]];
}
const lineChildren = splitNodesIntoLines(
Array.from(node.childNodes)
);
return lineChildren.map((children) => {
const clone = node.cloneNode(false) as Element;
clone.append(...children);
return [clone];
});
}
function splitNodesIntoLines(nodes: Node[]): Node[][] {
const lines: Node[][] = [[]];
for (const node of nodes) {
const nodeLines = splitNodeIntoLines(node);
lines.at(-1)?.push(...(nodeLines[0] ?? []));
for (const line of nodeLines.slice(1)) {
lines.push([...line]);
}
}
return lines;
}
function lineHasContent(nodes: Node[]) {
return nodes.some((node) => (node.textContent ?? "").length > 0);
}
function createLineGroups(
documentRef: Document,
lines: Node[][]
) {
const groups: HTMLElement[] = [];
let lineIndex = 0;
while (lineIndex < lines.length) {
const remaining = lines.length - lineIndex;
const groupSize =
remaining === 1 ? 1 : remaining === 3 ? 3 : 2;
const group = documentRef.createElement("span");
group.className = LINE_GROUP_CLASS;
for (
let offset = 0;
offset < groupSize && lineIndex < lines.length;
offset += 1, lineIndex += 1
) {
const line = documentRef.createElement("span");
line.className = LINE_CLASS;
line.append(...(lines[lineIndex] ?? []));
group.append(line);
}
groups.push(group);
}
return groups;
}
export function prepareCodeBlockPagination(root: ParentNode) {
const codeBlocks = Array.from(
root.querySelectorAll<HTMLElement>(
`pre.md-fences:not([${PREPARED_ATTRIBUTE}])`
)
);
for (const codeBlock of codeBlocks) {
const code = codeBlock.querySelector<HTMLElement>(
":scope > code"
);
if (!code) {
continue;
}
const sourceEndsWithNewline =
code.textContent?.endsWith("\n") ?? false;
const lines = splitNodesIntoLines(Array.from(code.childNodes));
if (
sourceEndsWithNewline &&
lines.length > 1 &&
!lineHasContent(lines.at(-1) ?? [])
) {
lines.pop();
}
const groups = createLineGroups(code.ownerDocument, lines);
const chunks = groups.map((group, index) => {
const chunk = code.ownerDocument.createElement("div");
for (const attribute of Array.from(codeBlock.attributes)) {
chunk.setAttribute(attribute.name, attribute.value);
}
chunk.classList.add(CHUNK_CLASS);
chunk.setAttribute(PREPARED_ATTRIBUTE, "true");
chunk.setAttribute(
CHUNK_POSITION_ATTRIBUTE,
groups.length === 1
? "only"
: index === 0
? "first"
: index === groups.length - 1
? "last"
: "middle"
);
const chunkCode = code.cloneNode(false) as HTMLElement;
chunkCode.append(group);
chunk.append(chunkCode);
return chunk;
});
codeBlock.replaceWith(...chunks);
}
}
@@ -11,6 +11,7 @@ import {
findCommonPrefixLength,
mountContinuousRenderStage
} from "./continuous-preview.js";
import { prepareCodeBlockPagination } from "./code-block-pagination.js";
import { fitOversizedEChartsToPage } from "./echarts-page-fit.js";
import {
fitDocumentImagesToPage,
@@ -44,6 +45,8 @@ import {
documentGeometryCss,
documentInteractionCss,
formatPageNumber,
resolvePageNumberAlignment,
shouldRenderPageNumber,
type PagedPreviewPayload
} from "./paged-preview.js";
import type { PagedRenderTarget } from "./paged-render-target.js";
@@ -156,12 +159,23 @@ function applyPageNumbers(
return;
}
const alignment = payload.exportConfig.footer.alignment;
const pages = Array.from(
container.querySelectorAll<HTMLElement>(".pagedjs_page")
);
for (const [pageIndex, page] of pages.entries()) {
if (
!shouldRenderPageNumber(
payload.exportConfig.footer,
pageIndex
)
) {
continue;
}
const alignment = resolvePageNumberAlignment(
payload.exportConfig.footer,
pageIndex
);
const content = page.querySelector<HTMLElement>(
`.pagedjs_margin-bottom-${alignment} .pagedjs_margin-content`
);
@@ -640,6 +654,7 @@ export class PagedDocumentRuntime {
this.resetPagedState();
this.root.replaceChildren();
}
prepareCodeBlockPagination(nextArticle);
const setupMs = performance.now() - setupStartedAt;
const mermaidStartedAt = performance.now();
+81 -2
View File
@@ -75,10 +75,22 @@ svg {
max-width: 100%;
}
#write pre.md-fences > code {
#write pre.md-fences,
#write .md-code-pagination-chunk {
min-width: 0;
max-width: 100%;
white-space: pre-wrap;
overflow-wrap: anywhere;
word-break: break-word;
}
#write pre.md-fences > code,
#write .md-code-pagination-chunk > code {
display: block;
min-width: 0;
max-width: 100%;
padding: 0;
padding-left: 8px;
border: 0;
border-radius: 0;
background: transparent;
@@ -87,6 +99,9 @@ svg {
font-size: inherit;
font-weight: inherit;
line-height: inherit;
white-space: inherit;
overflow-wrap: inherit;
word-break: inherit;
}
.md-document-image-block {
@@ -250,6 +265,9 @@ export function formatPageNumber(
if (config.format === "dash-page") {
return `- ${page} -`;
}
if (config.format === "official-page") {
return `${page}`;
}
return (config.template || "${page} / ${pages}")
.replace(/\$\{page\}/g, String(page))
@@ -262,6 +280,7 @@ function marginBox(
content: string,
options: {
color: string;
fontFamily: string;
fontSize: string;
height: string;
showDivider: boolean;
@@ -280,7 +299,7 @@ function marginBox(
content: ${content};
height: ${options.height};
color: ${options.color};
font-family: inherit;
font-family: ${options.fontFamily};
font-size: ${options.fontSize};
font-weight: 400;
line-height: 1.25;
@@ -300,6 +319,7 @@ function buildHeaderCss(
const options = {
color: config.header.color,
fontFamily: config.header.fontFamily,
fontSize: config.header.fontSize,
height: config.header.height,
showDivider: config.header.showDivider
@@ -328,6 +348,7 @@ function buildFooterCss(config: ExportConfig) {
const options = {
color: config.footer.color,
fontFamily: config.footer.fontFamily,
fontSize: config.footer.fontSize,
height: config.footer.height,
showDivider: config.footer.showDivider
@@ -347,6 +368,23 @@ function buildFooterCss(config: ExportConfig) {
.join("\n");
}
export function resolvePageNumberAlignment(
config: ExportConfig["footer"],
pageIndex: number
): "left" | "center" | "right" {
if (config.alignment !== "outer") {
return config.alignment;
}
return pageIndex % 2 === 0 ? "right" : "left";
}
export function shouldRenderPageNumber(
config: ExportConfig["footer"],
pageIndex: number
) {
return config.showOnFirstPage || pageIndex !== 0;
}
export function buildPagedMediaCss(
config: ExportConfig,
payload: Pick<PagedPreviewPayload, "fileName" | "metadata">
@@ -398,6 +436,47 @@ ${buildFooterCss(config)}
break-inside: avoid;
}
#write .md-code-pagination-chunk {
break-inside: avoid;
page-break-inside: avoid;
}
#write .md-code-pagination-chunk > code {
display: block;
}
#write .md-code-pagination-chunk:not(
[data-code-pagination-position="first"]
):not([data-code-pagination-position="only"]) {
margin-top: 0 !important;
padding-top: 0 !important;
border-top: 0 !important;
border-top-left-radius: 0 !important;
border-top-right-radius: 0 !important;
}
#write .md-code-pagination-chunk:not(
[data-code-pagination-position="last"]
):not([data-code-pagination-position="only"]) {
margin-bottom: 0 !important;
padding-bottom: 0 !important;
border-bottom: 0 !important;
border-bottom-left-radius: 0 !important;
border-bottom-right-radius: 0 !important;
}
#write .md-code-line-group {
display: block;
}
#write .md-code-line {
display: block;
min-height: 1lh;
white-space: inherit;
overflow-wrap: inherit;
word-break: inherit;
}
#write table[data-empty-split-table="true"] {
display: none;
}
@@ -0,0 +1,141 @@
// @vitest-environment happy-dom
import { describe, expect, it } from "vitest";
import { prepareCodeBlockPagination } from "../src/code-block-pagination.js";
function createRoot(codeHtml: string) {
const root = document.createElement("article");
root.innerHTML = `<pre class="md-fences"><code>${codeHtml}</code></pre>`;
return root;
}
function getGroups(root: ParentNode) {
return Array.from(
root.querySelectorAll<HTMLElement>(".md-code-line-group")
);
}
function getLines(root: ParentNode) {
return Array.from(
root.querySelectorAll<HTMLElement>(".md-code-line")
);
}
function getChunks(root: ParentNode) {
return Array.from(
root.querySelectorAll<HTMLElement>(".md-code-pagination-chunk")
);
}
describe("代码块分页预处理", () => {
it("偶数行按两行分组", () => {
const root = createRoot("line-1\nline-2\nline-3\nline-4\n");
prepareCodeBlockPagination(root);
expect(getGroups(root).map((group) => group.children.length)).toEqual([
2,
2
]);
expect(getLines(root).map((line) => line.textContent)).toEqual([
"line-1",
"line-2",
"line-3",
"line-4"
]);
expect(
getChunks(root).map((chunk) =>
chunk.getAttribute("data-code-pagination-position")
)
).toEqual(["first", "last"]);
});
it("奇数行将最后三行合组并保留单行代码块", () => {
const oddRoot = createRoot(
"line-1\nline-2\nline-3\nline-4\nline-5\n"
);
const singleRoot = createRoot("only-line\n");
prepareCodeBlockPagination(oddRoot);
prepareCodeBlockPagination(singleRoot);
expect(
getGroups(oddRoot).map((group) => group.children.length)
).toEqual([2, 3]);
expect(
getGroups(singleRoot).map((group) => group.children.length)
).toEqual([1]);
expect(
getChunks(singleRoot)[0]?.getAttribute(
"data-code-pagination-position"
)
).toBe("only");
});
it("跨行克隆语法高亮结构并保留空行", () => {
const root = createRoot(
'<span class="hljs-string">first\nsecond</span>\n\n' +
'<span class="hljs-keyword">return</span> value;\n'
);
prepareCodeBlockPagination(root);
const lines = getLines(root);
expect(lines.map((line) => line.textContent)).toEqual([
"first",
"second",
"",
"return value;"
]);
expect(
lines[0]?.querySelector(".hljs-string")?.textContent
).toBe("first");
expect(
lines[1]?.querySelector(".hljs-string")?.textContent
).toBe("second");
expect(
lines[3]?.querySelector(".hljs-keyword")?.textContent
).toBe("return");
});
it("重复调用不会再次包装已经准备的代码块", () => {
const root = createRoot("line-1\nline-2\n");
prepareCodeBlockPagination(root);
const firstHtml = root.innerHTML;
prepareCodeBlockPagination(root);
expect(root.innerHTML).toBe(firstHtml);
expect(root.querySelector("pre.md-fences")).toBeNull();
const paginationChunks = getChunks(root);
expect(paginationChunks).toHaveLength(1);
expect(
paginationChunks[0]?.classList.contains("md-fences")
).toBe(true);
expect(
paginationChunks[0]?.getAttribute(
"data-code-pagination-prepared"
)
).toBe("true");
});
it("复制代码元素属性并把每个双行组拆成同级分页片段", () => {
const root = document.createElement("article");
root.innerHTML =
'<pre class="md-fences custom" data-source="demo">' +
'<code class="hljs language-js" data-language="js">' +
"line-1\nline-2\nline-3\nline-4\n" +
"</code></pre>";
prepareCodeBlockPagination(root);
const chunks = getChunks(root);
expect(chunks).toHaveLength(2);
expect(Array.from(root.children)).toEqual(chunks);
expect(chunks[0]?.classList.contains("custom")).toBe(true);
expect(chunks[1]?.getAttribute("data-source")).toBe("demo");
expect(
chunks[1]?.querySelector("code")?.getAttribute("data-language")
).toBe("js");
});
});
@@ -11,6 +11,8 @@ import {
isPagedPreviewFrameMessage,
isPagedPreviewRenderRequest,
PAGED_PREVIEW_MESSAGE_SCOPE,
resolvePageNumberAlignment,
shouldRenderPageNumber,
type PagedPreviewPayload
} from "../src/paged-preview.js";
@@ -36,6 +38,9 @@ describe("分页预览协议", () => {
expect(css).toContain("size: 210mm 297mm");
expect(css).toContain("margin: 16mm 16mm");
expect(css).toContain("@bottom-center");
expect(css).toContain(
'font-family: "Segoe UI", "Microsoft YaHei", sans-serif'
);
expect(css).not.toContain("counter-reset: page");
expect(css).toContain("#write thead");
expect(css).toContain("display: table-header-group");
@@ -149,6 +154,36 @@ describe("分页预览协议", () => {
5
)
).toBe("- 5 -");
expect(
formatPageNumber(
{
...defaultExportConfig.footer,
format: "official-page"
},
4,
5
)
).toBe("— 5 —");
});
it("将公文页码放在奇偶页外侧并支持首页隐藏", () => {
const officialFooter = {
...defaultExportConfig.footer,
alignment: "outer" as const,
showOnFirstPage: false
};
expect(resolvePageNumberAlignment(officialFooter, 0)).toBe(
"right"
);
expect(resolvePageNumberAlignment(officialFooter, 1)).toBe(
"left"
);
expect(resolvePageNumberAlignment(officialFooter, 2)).toBe(
"right"
);
expect(shouldRenderPageNumber(officialFooter, 0)).toBe(false);
expect(shouldRenderPageNumber(officialFooter, 1)).toBe(true);
});
it("在主题 CSS 之后强制分页画布保持透明", () => {
@@ -168,6 +203,39 @@ describe("分页预览协议", () => {
);
});
it("只在至少两行的代码组之间分页", () => {
const css = buildPagedMediaCss(defaultExportConfig, payload);
expect(css).toContain("#write .md-code-pagination-chunk");
expect(css).toContain("#write .md-code-line-group");
expect(css).toContain("page-break-inside: avoid;");
expect(css).toContain(
'[data-code-pagination-position="first"]'
);
expect(css).toContain(
'[data-code-pagination-position="last"]'
);
expect(css).toContain("#write .md-code-line");
expect(css).toContain("min-height: 1lh;");
});
it("代码围栏按正文宽度保留缩进并自动折行", () => {
expect(documentBaseCss).toContain("#write pre.md-fences,");
expect(documentBaseCss).toContain(
"#write .md-code-pagination-chunk"
);
expect(documentBaseCss).toContain("max-width: 100%;");
expect(documentBaseCss).toContain("padding-left: 8px;");
expect(documentBaseCss).toContain("white-space: pre-wrap;");
expect(documentBaseCss).toContain("overflow-wrap: anywhere;");
expect(documentBaseCss).toContain("word-break: break-word;");
const css = buildPagedMediaCss(defaultExportConfig, payload);
expect(css).toContain("#write .md-code-line");
expect(css).toContain("overflow-wrap: inherit;");
expect(css).toContain("word-break: inherit;");
});
it("以低优先级兜底样式保留链接识别和焦点反馈", () => {
expect(documentInteractionCss).toContain(":where(#write a[href])");
expect(documentInteractionCss).toContain(