feat: 实现网页实时预览

This commit is contained in:
SkyJourney
2026-07-25 21:52:45 +08:00
parent 7224dfdf60
commit fa07472428
16 changed files with 2860 additions and 218 deletions
+1
View File
@@ -3,6 +3,7 @@ dist/
coverage/
.env
.env.local
.local/
*.log
.DS_Store
Thumbs.db
+192
View File
@@ -0,0 +1,192 @@
# AGENTS.md
本文件适用于仓库根目录及其所有子目录。进入本项目的新会话必须先完整阅读本文件与 `docs/PROGRESS.md`
## 1. 语言与沟通
- 所有解释、询问、进度汇报、提交说明和项目文档必须使用简体中文,代码及必要的技术标识除外。
- 涉及架构调整、新功能模块或明显改变现有实现方向时,先用文字或 Mermaid 对齐设计,等待用户确认后再编码。
- 开始实质性任务前列出任务清单,等待用户明确确认。
- 修改、新建或删除文件前,简要说明具体变更范围,等待用户确认。
- 代码量较大或逻辑复杂时分步执行;每完成一个阶段,汇报结果并等待用户确认是否继续。
- Mermaid 中的中文标题和节点文字必须使用英文双引号包裹。
## 2. 会话启动检查
新会话、上下文压缩后或对当前目录不确定时,在执行其他 Shell 命令前先运行:
```powershell
Get-Location
```
确认目录为:
```text
C:\Projects\md-to-pdf
```
随后依次执行只读检查:
```powershell
git status --short
git log --oneline -5
Get-Content -LiteralPath 'docs\PROGRESS.md' -Encoding UTF8
```
当前工作区可能包含用户或上一个会话留下的未提交修改。禁止使用 `git reset --hard``git checkout --``git clean` 等方式丢弃修改,除非用户明确要求。
## 3. Shell 与文件操作
- 当前默认 Shell 为 PowerShell,使用 PowerShell 语法。
- 不要通过绝对路径 `cd` 前缀拼接命令;工具支持时优先使用 `workdir`
- 子目录操作使用相对路径或直接设置 `workdir`
- PowerShell 读取、写入、追加或替换文本时显式指定 UTF-8 编码。
- 本地文件修改优先使用补丁工具,避免使用不透明的大段覆盖命令。
- 不执行破坏性删除;如确需删除,先确认精确目标并向用户说明。
## 4. 项目目标
本项目是一个可在内网部署的 Markdown 排版与 PDF 导出工具,目标包括:
- 浏览器选择或编辑 Markdown;
- 使用服务端统一渲染 Markdown;
- 网页预览和 PDF 使用同一份 HTML、主题 CSS 与资源;
- 使用固定版本 Chromium 生成真实、可搜索的 PDF 文件;
- 支持纸张尺寸、方向、页边距、页眉、页脚和多种页码样式;
- 支持主题清单与 CSS 主题扩展;
- 支持 Front Matter、表格、任务列表、脚注、代码高亮、KaTeX 和 Mermaid
- 使用 Docker Compose 在内网部署;
- 文档只在当前请求中临时处理,不建立文档历史数据库。
核心渲染链路:
```mermaid
flowchart LR
A["Markdown 与资源"] --> B["安全 Markdown 渲染"]
B --> C["统一 HTML 结构"]
D["主题 CSS"] --> C
E["导出配置"] --> C
C --> F["网页预览"]
C --> G["Playwright Chromium"]
G --> H["真实 PDF 文件"]
```
## 5. 技术架构
- 前端:React、TypeScript、Vite。
- 后端:Node.js、TypeScript、Fastify。
- 共享模型:`packages/core`
- Markdown 渲染:`packages/renderer`
- PDF 引擎:计划使用 Playwright Chromium。
- Markdownmarkdown-it 及 `@mdit/plugin-*` 插件。
- 元数据:gray-matter。
- 安全过滤:sanitize-html。
- 代码高亮:highlight.js。
- 数学公式:KaTeX。
- 图表:Mermaid。
- 校验:Zod。
- 测试:Vitest。
- 部署:Docker、Docker Compose。
主要目录职责:
```text
apps/web/ 前端编辑、配置与预览界面
apps/server/ HTTP API、主题读取及未来 PDF 服务
packages/core/ 导出配置和主题清单等共享模型
packages/renderer/ Markdown 到安全 HTML 的渲染管线
themes/ 内置主题及未来可安装主题
docker/ 容器化配置
tests/ 跨包和端到端测试
docs/ 进度、架构和部署文档
```
## 6. 必须保持的实现约束
### 6.1 预览与 PDF 一致性
- 预览和 PDF 必须复用 Markdown 渲染结果、`#write` DOM、主题 CSS 和打印 CSS。
- 不允许前端和 PDF 服务分别维护两套 Markdown 解析逻辑。
- PDF 使用容器中固定版本的 Chromium,确保不同部署环境结果可复现。
- Mermaid、字体、图片和公式完成渲染后,才能调用 PDF 输出。
### 6.2 主题扩展
- 主题通过版本化 `theme.json` 清单接入,不在业务代码中写死主题行为。
- 主题负责字体、颜色、标题、表格、引用、代码块等视觉样式。
- 纸张、页边距、页眉页脚、页码和 PDF 元数据属于导出配置,不属于主题。
- 主题需要声明作者、版本、许可证、DOM 预设和支持能力。
- Typora 官方默认主题仓库目前没有明确许可证,不得直接复制并打包。
- 可以自行实现视觉接近的主题,或使用许可证明确允许的第三方主题。
### 6.3 安全与隐私
- 默认不保存用户 Markdown、图片或生成历史。
- 资源上传和 PDF 生成使用每请求独立临时目录,并在 `finally` 中清理。
- 阻止 `../` 路径穿越、任意本地文件读取和符号链接越界。
- Markdown 原始 HTML 默认不执行;渲染结果必须经过安全过滤。
- Mermaid 使用严格安全模式。
- 自定义 CSS、远程图片和远程字体需要限制网络访问,避免信息泄漏和 SSRF。
- 对 Markdown、资源数量、单文件大小、总大小、渲染时间和 Chromium 并发设置上限。
### 6.4 页眉页脚与页码
- 普通页眉页脚优先使用 Chromium 的 header/footer template。
- 模板样式必须内联,不假设继承正文 CSS。
- 基础页码支持当前页、总页数、中英文组合及左右中位置。
- 罗马数字、章节页码、封面不计页码等复杂能力放在 PDF 后处理扩展层,不阻塞首版。
## 7. 开发和验证
要求 Node.js 22 或更高版本。
安装依赖:
```powershell
npm install
```
本地开发:
```powershell
npm run dev
```
完整验证:
```powershell
npm test
npm run typecheck
npm run build
```
任何功能提交前至少满足:
- 相关单元测试通过;
- 全项目类型检查通过;
- 生产构建通过;
- `git diff --check` 无空白错误;
- 未意外纳入 `node_modules``dist`、临时文件或用户文档。
如涉及 PDF 输出,还必须使用包含中文、长表格、代码块、公式、Mermaid、图片和分页边界的样例进行端到端验证,并对生成 PDF 做页面渲染检查。
## 8. Git 规范
- 默认分支为 `main`
- 提交前先检查 `git status --short``git diff`
- 不覆盖或混入与当前任务无关的用户修改。
- 一个提交只表达一个清晰阶段。
- 提交信息前缀使用标准英文,正文使用简体中文,例如:
```text
feat: 实现网页实时预览
fix: 修复表格跨页断裂
docs: 更新内网部署说明
chore: 初始化项目骨架
```
- 不修改或重写已有提交,除非用户明确要求。
## 9. 当前交接入口
项目的实时状态、已完成内容、未提交修改和下一步顺序以 `docs/PROGRESS.md` 为准。新会话不得仅凭 Git 提交标题判断进度。
+28 -9
View File
@@ -4,17 +4,19 @@
## 当前状态
项目处于骨架阶段,已经建立
已经实现
- React 前端
- Fastify 后端
- React Markdown 编辑与本地文件读取
- Fastify 预览接口
- 共享导出配置模型;
- 版本化主题清单接口;
- 动态主题清单、CSS 和静态资源接口;
- Markdown、Front Matter、安全过滤和扩展语法渲染核心;
- 内置 Typora 风格主题目录
- Docker 与测试目录预留。
- 表格、任务列表、脚注、代码高亮、KaTeX 和 Mermaid
- iframe 隔离的 A4 页面预览与主题切换;
- 内置 Typora 风格主题,以及仅供本机使用的 Typora 默认主题导入工具;
- Docker 与 PDF 渲染目录预留。
网页预览和 PDF 生成将在后续阶段实现。
Chromium PDF 下载、完整导出配置面板和本地资源文件处理将在后续阶段实现。
## 本地开发
@@ -31,12 +33,29 @@ npm run dev
- 后端:http://localhost:3001
- 健康检查:http://localhost:3001/api/health
## 构建
页面支持直接编辑 Markdown,或选择本地 `.md` 文件。文件内容将读取到当前浏览器页面并发送给内网转换服务,不写入数据库。
## 本地导入 Typora 默认主题
项目不会打包或提交 Typora 官方默认主题。如本机已安装 Typora,可以将其 GitHub 默认主题复制到 Git 忽略的本地主题目录:
```powershell
npm run theme:import-typora
```
默认读取 `%APPDATA%\Typora\themes`,写入 `.local\themes\typora-github`。启动开发服务后,该主题会出现在预览页面的主题选择器中。导入工具不会覆盖已存在的目标目录;如需重新导入,请先自行确认并移走旧目录。
本地主题由动态主题注册器加载,CSS 中的相对字体和图片会通过受限资源接口提供。外部 URL、越界路径和符号链接逃逸会被拒绝。
## 测试与构建
```powershell
npm test
npm run typecheck
npm run build
git diff --check
```
## 隐私原则
文档和资源文件仅用于当前转换请求。正式实现将为每次请求创建隔离的临时目录,并在成功或失败后统一清理,不接入数据库或文档历史存储。
文档和资源文件仅用于当前转换请求。PDF 阶段将为每次请求创建隔离的临时目录,并在成功或失败后统一清理,不接入数据库或文档历史存储。
+3 -1
View File
@@ -7,6 +7,7 @@
"dev": "tsx watch src/index.ts",
"build": "tsc -p tsconfig.json",
"start": "node dist/index.js",
"test": "vitest run",
"typecheck": "tsc -p tsconfig.json --noEmit --pretty false"
},
"dependencies": {
@@ -16,6 +17,7 @@
},
"devDependencies": {
"@types/node": "^24.10.1",
"tsx": "^4.21.0"
"tsx": "^4.21.0",
"vitest": "^4.1.10"
}
}
+149
View File
@@ -0,0 +1,149 @@
import { fileURLToPath } from "node:url";
import { resolve } from "node:path";
import Fastify from "fastify";
import {
EXPORT_CONFIG_VERSION,
defaultExportConfig,
supportedPaperFormats
} from "@md-to-pdf/core";
import { RENDERER_VERSION, renderMarkdown } from "@md-to-pdf/renderer";
import { createThemeRegistry } from "./theme-registry.js";
interface RenderRequestBody {
markdown?: unknown;
language?: unknown;
}
const projectRoot = fileURLToPath(new URL("../../../", import.meta.url));
export interface BuildAppOptions {
localThemeRoot?: string;
logger?: boolean;
}
export function buildApp(options: BuildAppOptions = {}) {
const app = Fastify({
logger: options.logger ?? true,
bodyLimit: 2 * 1024 * 1024
});
const themes = createThemeRegistry({
bundledRoot: resolve(projectRoot, "themes"),
localRoot:
options.localThemeRoot ?? resolve(projectRoot, ".local", "themes")
});
app.get("/api/health", async () => ({
status: "ok",
service: "md-to-pdf",
configVersion: EXPORT_CONFIG_VERSION,
rendererVersion: RENDERER_VERSION
}));
app.get("/api/capabilities", async () => ({
defaultExportConfig,
supportedPaperFormats,
implemented: [
"project-skeleton",
"export-config",
"theme-manifest",
"markdown-render",
"html-preview"
],
planned: ["pdf-export"]
}));
app.get("/api/themes", async () => ({
themes: (await themes.list()).map(({ manifest, source }) => ({
id: manifest.id,
name: manifest.name,
version: manifest.version,
description: manifest.description,
bundled: manifest.bundled,
source
}))
}));
app.get<{ Params: { themeId: string } }>(
"/api/themes/:themeId/css",
async (request, reply) => {
const { themeId } = request.params;
const css = await themes.getCss(themeId);
if (css === undefined) {
return reply.code(404).send({
error: "THEME_NOT_FOUND",
message: "未找到指定主题"
});
}
return reply
.header("content-type", "text/css; charset=utf-8")
.header("cache-control", "public, max-age=300")
.send(css);
}
);
app.get<{ Params: { themeId: string; "*": string } }>(
"/api/themes/:themeId/assets/*",
async (request, reply) => {
try {
const asset = await themes.getAsset(
request.params.themeId,
request.params["*"]
);
if (!asset) {
return reply.code(404).send({
error: "THEME_NOT_FOUND",
message: "未找到指定主题"
});
}
return reply
.header("content-type", asset.contentType)
.header("cache-control", "public, max-age=300")
.header("content-security-policy", "default-src 'none'; sandbox")
.header("x-content-type-options", "nosniff")
.send(asset.content);
} catch {
return reply.code(404).send({
error: "THEME_ASSET_NOT_FOUND",
message: "未找到指定主题资源"
});
}
}
);
app.post<{ Body: RenderRequestBody }>(
"/api/render",
async (request, reply) => {
const { markdown, language } = request.body ?? {};
if (typeof markdown !== "string") {
return reply.code(400).send({
error: "INVALID_MARKDOWN",
message: "markdown 必须是字符串"
});
}
if (markdown.length > 1_500_000) {
return reply.code(413).send({
error: "MARKDOWN_TOO_LARGE",
message: "Markdown 内容不能超过 1.5 MB"
});
}
if (language !== undefined && typeof language !== "string") {
return reply.code(400).send({
error: "INVALID_LANGUAGE",
message: "language 必须是字符串"
});
}
return renderMarkdown(markdown, {
...(typeof language === "string" ? { language } : {})
});
}
);
return app;
}
+2 -30
View File
@@ -1,36 +1,8 @@
import Fastify from "fastify";
import {
EXPORT_CONFIG_VERSION,
defaultExportConfig,
supportedPaperFormats
} from "@md-to-pdf/core";
import { RENDERER_VERSION } from "@md-to-pdf/renderer";
import { buildApp } from "./app.js";
const port = Number.parseInt(process.env.PORT ?? "3001", 10);
const host = process.env.HOST ?? "0.0.0.0";
const app = Fastify({
logger: true
});
app.get("/api/health", async () => ({
status: "ok",
service: "md-to-pdf",
configVersion: EXPORT_CONFIG_VERSION,
rendererVersion: RENDERER_VERSION
}));
app.get("/api/capabilities", async () => ({
defaultExportConfig,
supportedPaperFormats,
implemented: [
"project-skeleton",
"export-config",
"theme-manifest",
"markdown-render"
],
planned: ["html-preview", "pdf-export"]
}));
const app = buildApp();
async function start() {
try {
+246
View File
@@ -0,0 +1,246 @@
import {
readdir,
readFile,
realpath,
stat
} from "node:fs/promises";
import {
extname,
isAbsolute,
relative,
resolve,
sep
} from "node:path";
import {
themeManifestSchema,
type ThemeManifest
} from "@md-to-pdf/core";
export interface ThemeRecord {
manifest: ThemeManifest;
directory: string;
source: "bundled" | "local";
}
export interface ThemeRegistryOptions {
bundledRoot: string;
localRoot: string;
}
const assetContentTypes: Record<string, string> = {
".gif": "image/gif",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".png": "image/png",
".svg": "image/svg+xml",
".ttf": "font/ttf",
".webp": "image/webp",
".woff": "font/woff",
".woff2": "font/woff2"
};
function isMissingFileError(error: unknown) {
return (
error instanceof Error &&
"code" in error &&
(error as NodeJS.ErrnoException).code === "ENOENT"
);
}
function isInsideDirectory(directory: string, path: string) {
const pathFromDirectory = relative(directory, path);
return (
pathFromDirectory === "" ||
(!pathFromDirectory.startsWith(`..${sep}`) &&
pathFromDirectory !== ".." &&
!isAbsolute(pathFromDirectory))
);
}
async function resolveThemeFile(directory: string, relativePath: string) {
if (
isAbsolute(relativePath) ||
relativePath.includes("\0") ||
relativePath.split(/[\\/]/).includes("..")
) {
throw new Error("主题资源路径不安全");
}
const realDirectory = await realpath(directory);
const candidate = resolve(realDirectory, relativePath);
if (!isInsideDirectory(realDirectory, candidate)) {
throw new Error("主题资源路径越界");
}
const realCandidate = await realpath(candidate);
if (!isInsideDirectory(realDirectory, realCandidate)) {
throw new Error("主题资源符号链接越界");
}
const fileStat = await stat(realCandidate);
if (!fileStat.isFile()) {
throw new Error("主题资源不是文件");
}
return realCandidate;
}
async function readThemeRoot(
root: string,
source: ThemeRecord["source"]
): Promise<ThemeRecord[]> {
let entries;
try {
entries = await readdir(root, { withFileTypes: true });
} catch (error) {
if (isMissingFileError(error) && source === "local") {
return [];
}
throw error;
}
const records: ThemeRecord[] = [];
for (const entry of entries) {
if (!entry.isDirectory()) {
continue;
}
const directory = resolve(root, entry.name);
try {
const manifestPath = await resolveThemeFile(directory, "theme.json");
const manifest = themeManifestSchema.parse(
JSON.parse(await readFile(manifestPath, "utf8"))
);
if (manifest.id !== entry.name) {
throw new Error("主题目录名必须与主题 ID 一致");
}
if (manifest.bundled !== (source === "bundled")) {
throw new Error("主题 bundled 标记与来源不一致");
}
await resolveThemeFile(directory, manifest.entry);
if (manifest.print) {
await resolveThemeFile(directory, manifest.print);
}
records.push({
manifest,
directory,
source
});
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`主题 ${entry.name} 无效:${message}`);
}
}
return records;
}
function encodeAssetPath(path: string) {
return path
.split("/")
.map((segment) => encodeURIComponent(segment))
.join("/");
}
function prepareThemeCss(css: string, themeId: string) {
const withoutTyporaExportIncludes = css.replace(
/^\s*@include-when-export\s+url\([^;\r\n]+;\s*$/gim,
""
);
return withoutTyporaExportIncludes.replace(
/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi,
(match, _quote: string, rawValue: string) => {
const value = rawValue.trim();
if (value.startsWith("data:") || value.startsWith("#")) {
return match;
}
if (
value.startsWith("/") ||
value.startsWith("//") ||
/^[a-z][a-z0-9+.-]*:/i.test(value)
) {
throw new Error(`主题包含不允许的外部资源:${value}`);
}
const normalized = value.replaceAll("\\", "/").replace(/^\.\//, "");
if (normalized.split("/").includes("..")) {
throw new Error(`主题资源路径不安全:${value}`);
}
return `url("/api/themes/${encodeURIComponent(themeId)}/assets/${encodeAssetPath(normalized)}")`;
}
);
}
export function createThemeRegistry(options: ThemeRegistryOptions) {
async function list() {
const [bundledThemes, localThemes] = await Promise.all([
readThemeRoot(options.bundledRoot, "bundled"),
readThemeRoot(options.localRoot, "local")
]);
const themes = [...bundledThemes, ...localThemes];
const themeIds = new Set<string>();
for (const theme of themes) {
if (themeIds.has(theme.manifest.id)) {
throw new Error(`主题 ID 重复:${theme.manifest.id}`);
}
themeIds.add(theme.manifest.id);
}
return themes;
}
async function get(themeId: string) {
return (await list()).find((theme) => theme.manifest.id === themeId);
}
async function getCss(themeId: string) {
const theme = await get(themeId);
if (!theme) {
return undefined;
}
const cssFiles = [
await resolveThemeFile(theme.directory, theme.manifest.entry),
...(theme.manifest.print
? [await resolveThemeFile(theme.directory, theme.manifest.print)]
: [])
];
const css = (
await Promise.all(cssFiles.map((path) => readFile(path, "utf8")))
).join("\n");
return prepareThemeCss(css, themeId);
}
async function getAsset(themeId: string, assetPath: string) {
const theme = await get(themeId);
if (!theme) {
return undefined;
}
const extension = extname(assetPath).toLowerCase();
const contentType = assetContentTypes[extension];
if (!contentType) {
throw new Error("不支持的主题资源类型");
}
const path = await resolveThemeFile(theme.directory, assetPath);
return {
contentType,
content: await readFile(path)
};
}
return {
get,
getAsset,
getCss,
list
};
}
+137
View File
@@ -0,0 +1,137 @@
import { afterEach, describe, expect, it } from "vitest";
import type { FastifyInstance } from "fastify";
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { buildApp } from "../src/app.js";
let app: FastifyInstance | undefined;
let temporaryDirectory: string | undefined;
afterEach(async () => {
await app?.close();
if (temporaryDirectory) {
await rm(temporaryDirectory, { recursive: true, force: true });
}
app = undefined;
temporaryDirectory = undefined;
});
describe("预览 API", () => {
it("渲染 Markdown 并返回安全文章结构", async () => {
app = buildApp();
const response = await app.inject({
method: "POST",
url: "/api/render",
payload: {
markdown: "# 文档\n\n<script>alert('xss')</script>"
}
});
expect(response.statusCode).toBe(200);
const result = response.json();
expect(result.articleHtml).toContain('id="write"');
expect(result.articleHtml).not.toContain("<script");
expect(result.metadata.title).toBe("文档");
});
it("拒绝非字符串 Markdown", async () => {
app = buildApp();
const response = await app.inject({
method: "POST",
url: "/api/render",
payload: {
markdown: 42
}
});
expect(response.statusCode).toBe(400);
expect(response.json().error).toBe("INVALID_MARKDOWN");
});
it("返回内置主题 CSS", async () => {
app = buildApp();
const response = await app.inject({
method: "GET",
url: "/api/themes/typora-like/css"
});
expect(response.statusCode).toBe(200);
expect(response.headers["content-type"]).toContain("text/css");
expect(response.body).toContain("#write");
});
it("发现本地主题并安全提供相对字体资源", async () => {
temporaryDirectory = await mkdtemp(join(tmpdir(), "md-to-pdf-theme-"));
const themeDirectory = join(temporaryDirectory, "local-test");
await mkdir(join(themeDirectory, "fonts"), { recursive: true });
await writeFile(
join(themeDirectory, "theme.json"),
JSON.stringify({
manifestVersion: 1,
id: "local-test",
name: "本地测试主题",
version: "local",
description: "本地主题测试",
author: "test",
license: "local-only",
entry: "theme.css",
domPreset: "typora",
defaultFontSize: "16px",
supportedFeatures: ["code", "table"],
bundled: false
}),
"utf8"
);
await writeFile(
join(themeDirectory, "theme.css"),
[
"@include-when-export url(https://example.com/font.css);",
"@font-face { src: url('./fonts/test.woff2') format('woff2'); }",
"#write { font-family: LocalTest; }"
].join("\n"),
"utf8"
);
await writeFile(
join(themeDirectory, "fonts", "test.woff2"),
Buffer.from([0, 1, 2, 3])
);
app = buildApp({
localThemeRoot: temporaryDirectory,
logger: false
});
const themesResponse = await app.inject({
method: "GET",
url: "/api/themes"
});
expect(themesResponse.statusCode).toBe(200);
expect(themesResponse.json().themes).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: "local-test",
bundled: false,
source: "local"
})
])
);
const cssResponse = await app.inject({
method: "GET",
url: "/api/themes/local-test/css"
});
expect(cssResponse.statusCode).toBe(200);
expect(cssResponse.body).not.toContain("@include-when-export");
expect(cssResponse.body).toContain(
"/api/themes/local-test/assets/fonts/test.woff2"
);
const assetResponse = await app.inject({
method: "GET",
url: "/api/themes/local-test/assets/fonts/test.woff2"
});
expect(assetResponse.statusCode).toBe(200);
expect(assetResponse.headers["content-type"]).toContain("font/woff2");
expect(assetResponse.rawPayload).toEqual(Buffer.from([0, 1, 2, 3]));
});
});
+3
View File
@@ -10,6 +10,9 @@
},
"dependencies": {
"@md-to-pdf/core": "0.1.0",
"highlight.js": "^11.11.1",
"katex": "^0.16.28",
"mermaid": "^11.12.3",
"react": "^19.2.0",
"react-dom": "^19.2.0"
},
+431 -50
View File
@@ -1,60 +1,441 @@
import { defaultExportConfig, paperFormatLabels } from "@md-to-pdf/core";
import {
type ChangeEvent,
useEffect,
useMemo,
useRef,
useState
} from "react";
import highlightCss from "highlight.js/styles/github.css?inline";
import katexCss from "katex/dist/katex.min.css?inline";
const capabilities = [
"Markdown 本地预览",
"Chromium PDF 下载",
"纸张与页边距",
"页眉、页脚与页码",
"可扩展 CSS 主题"
];
interface RenderedMarkdown {
articleHtml: string;
metadata: {
title: string;
author: string;
subject: string;
keywords: string[];
language: string;
};
features: string[];
warnings: string[];
}
interface ThemeSummary {
id: string;
name: string;
version: string;
description: string;
bundled: boolean;
source: "bundled" | "local";
}
const sampleMarkdown = `---
title: Markdown PDF 示例
author: 内网文档团队
keywords:
- Markdown
- PDF
---
# Markdown PDF 示例
这是一份使用 **Typora 风格主题** 渲染的预览文档。
## 常用内容
- [x] Markdown 实时预览
- [x] 表格与任务列表
- [x] 数学公式与 Mermaid
- [ ] Chromium PDF 导出
| 功能 | 当前状态 |
| --- | --- |
| HTML 预览 | 已实现 |
| PDF 下载 | 下一阶段 |
行内公式:$E = mc^2$
\`\`\`mermaid
flowchart LR
A["Markdown"] --> B["统一 HTML"]
B --> C["主题 CSS"]
C --> D["网页预览"]
C --> E["PDF 导出"]
\`\`\`
> 预览和 PDF 将共用同一份 HTML 与 CSS。
`;
const previewBaseCss = `
:root {
color-scheme: light;
background: #fff;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-width: 0;
background: #fff;
}
img,
svg {
max-width: 100%;
}
.mermaid {
display: flex;
justify-content: center;
margin: 1.5em 0;
overflow: auto;
}
`;
let mermaidPromise: Promise<(typeof import("mermaid"))["default"]> | undefined;
let mermaidRenderSequence = 0;
async function loadMermaid() {
if (!mermaidPromise) {
mermaidPromise = import("mermaid").then(({ default: mermaid }) => {
mermaid.initialize({
startOnLoad: false,
securityLevel: "strict",
theme: "neutral",
fontFamily: "Segoe UI, Microsoft YaHei, sans-serif"
});
return mermaid;
});
}
return mermaidPromise;
}
function escapeHtml(value: string) {
return value
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;");
}
function escapeStyleContent(value: string) {
return value.replace(/<\/style/gi, "<\\/style");
}
function buildPreviewDocument(
result: RenderedMarkdown,
themeCss: string
) {
return `<!doctype html>
<html lang="${escapeHtml(result.metadata.language || "zh-CN")}">
<head>
<meta charset="UTF-8" />
<meta
http-equiv="Content-Security-Policy"
content="default-src 'none'; style-src 'unsafe-inline'; font-src 'self' data:; img-src 'self' data:;"
/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>${escapeHtml(result.metadata.title || "Markdown 预览")}</title>
<style>${escapeStyleContent(previewBaseCss)}</style>
<style>${escapeStyleContent(highlightCss)}</style>
<style>${escapeStyleContent(katexCss)}</style>
<style>${escapeStyleContent(themeCss)}</style>
</head>
<body>
${result.articleHtml}
</body>
</html>`;
}
export function App() {
const [markdown, setMarkdown] = useState(sampleMarkdown);
const [fileName, setFileName] = useState("示例文档.md");
const [result, setResult] = useState<RenderedMarkdown | null>(null);
const [themes, setThemes] = useState<ThemeSummary[]>([]);
const [themeId, setThemeId] = useState("typora-like");
const [themeCss, setThemeCss] = useState("");
const [status, setStatus] = useState("正在准备预览…");
const [renderError, setRenderError] = useState("");
const [themeError, setThemeError] = useState("");
const [mermaidError, setMermaidError] = useState("");
const previewFrameRef = useRef<HTMLIFrameElement>(null);
const error = renderError || themeError || mermaidError;
const selectedTheme = themes.find((theme) => theme.id === themeId);
const previewDocument = useMemo(
() =>
result && themeCss ? buildPreviewDocument(result, themeCss) : undefined,
[result, themeCss]
);
useEffect(() => {
const controller = new AbortController();
void fetch("/api/themes", {
signal: controller.signal
})
.then(async (response) => {
if (!response.ok) {
throw new Error("无法加载主题清单");
}
return response.json() as Promise<{ themes: ThemeSummary[] }>;
})
.then(({ themes: availableThemes }) => {
setThemes(availableThemes);
const preferredTheme =
availableThemes.find((theme) => theme.id === "typora-github") ??
availableThemes.find((theme) => theme.id === "typora-like") ??
availableThemes[0];
if (preferredTheme) {
setThemeId(preferredTheme.id);
}
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) {
setThemeError(
reason instanceof Error ? reason.message : "无法加载主题清单"
);
}
});
return () => controller.abort();
}, []);
useEffect(() => {
const controller = new AbortController();
setThemeCss("");
setThemeError("");
void fetch(`/api/themes/${encodeURIComponent(themeId)}/css`, {
signal: controller.signal
})
.then(async (response) => {
if (!response.ok) {
throw new Error("无法加载主题");
}
return response.text();
})
.then(setThemeCss)
.catch((reason: unknown) => {
if (!controller.signal.aborted) {
setThemeError(
reason instanceof Error ? reason.message : "无法加载主题"
);
}
});
return () => controller.abort();
}, [themeId]);
useEffect(() => {
const controller = new AbortController();
const timer = window.setTimeout(() => {
setStatus("正在渲染…");
setRenderError("");
setMermaidError("");
void fetch("/api/render", {
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify({
markdown,
language: "zh-CN"
}),
signal: controller.signal
})
.then(async (response) => {
const payload = await response.json();
if (!response.ok) {
throw new Error(payload.message ?? "渲染失败");
}
return payload as RenderedMarkdown;
})
.then((payload) => {
setResult(payload);
setStatus("预览已更新");
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) {
setRenderError(
reason instanceof Error ? reason.message : "渲染失败"
);
setStatus("预览失败");
}
});
}, 250);
return () => {
window.clearTimeout(timer);
controller.abort();
};
}, [markdown]);
async function handlePreviewLoad() {
const frame = previewFrameRef.current;
const document = frame?.contentDocument;
if (!frame || !document || !result) {
return;
}
const resizeFrame = () => {
frame.style.height = `${Math.max(
document.documentElement.scrollHeight,
document.body.scrollHeight,
500
)}px`;
};
resizeFrame();
await document.fonts.ready;
if (result.features.includes("mermaid")) {
const nodes = Array.from(
document.querySelectorAll<HTMLElement>(
".mermaid[data-mermaid-pending]"
)
);
if (nodes.length > 0) {
try {
const mermaid = await loadMermaid();
for (const node of nodes) {
const definition = node.textContent ?? "";
mermaidRenderSequence += 1;
const { svg, bindFunctions } = await mermaid.render(
`mermaid-preview-${mermaidRenderSequence}`,
definition
);
node.innerHTML = svg;
node.removeAttribute("data-mermaid-pending");
bindFunctions?.(node);
}
} catch (reason: unknown) {
setMermaidError(
reason instanceof Error
? `Mermaid${reason.message}`
: "Mermaid 渲染失败"
);
}
}
}
resizeFrame();
}
async function handleFileChange(event: ChangeEvent<HTMLInputElement>) {
const file = event.target.files?.[0];
if (!file) {
return;
}
try {
setMarkdown(await file.text());
setFileName(file.name);
} catch {
setRenderError("无法读取所选 Markdown 文件");
} finally {
event.target.value = "";
}
}
return (
<main className="shell">
<section className="intro" aria-labelledby="page-title">
<p className="eyebrow"></p>
<h1 id="page-title">Markdown PDF </h1>
<p className="summary">
使 HTML CSS Chromium PDF
</p>
<div className="status">
<span className="status-dot" aria-hidden="true" />
</div>
</section>
<section className="panel" aria-labelledby="config-title">
<main className="workspace">
<header className="topbar">
<div>
<p className="panel-label"></p>
<h2 id="config-title">{defaultExportConfig.name}</h2>
<p className="eyebrow"></p>
<h1>Markdown PDF </h1>
</div>
<dl className="facts">
<div>
<dt></dt>
<dd>{paperFormatLabels[defaultExportConfig.paper.format]}</dd>
</div>
<div>
<dt></dt>
<dd>
{defaultExportConfig.paper.orientation === "portrait"
? "纵向"
: "横向"}
</dd>
</div>
<div>
<dt></dt>
<dd>{defaultExportConfig.themeId}</dd>
</div>
</dl>
</section>
<div className="topbar-actions">
<label className="file-button">
Markdown
<input
type="file"
accept=".md,.markdown,text/markdown,text/plain"
onChange={handleFileChange}
/>
</label>
<button type="button" disabled title="下一阶段实现">
PDF
</button>
</div>
</header>
<section className="capabilities" aria-label="规划能力">
{capabilities.map((item, index) => (
<article key={item}>
<span>{String(index + 1).padStart(2, "0")}</span>
<p>{item}</p>
</article>
))}
<section className="editor-layout">
<aside className="editor-panel" aria-label="Markdown 编辑区">
<div className="panel-heading">
<div>
<span className="panel-kicker"></span>
<strong>{fileName}</strong>
</div>
<span className={`render-status${error ? " is-error" : ""}`}>
{error || status}
</span>
</div>
<textarea
aria-label="Markdown 内容"
value={markdown}
spellCheck={false}
onChange={(event) => setMarkdown(event.target.value)}
/>
</aside>
<section className="preview-panel" aria-label="文档预览">
<div className="panel-heading">
<div>
<span className="panel-kicker"></span>
<strong>{result?.metadata.title || "未命名文档"}</strong>
</div>
<label className="theme-control">
<span className="sr-only"></span>
<select
aria-label="预览主题"
value={themeId}
onChange={(event) => setThemeId(event.target.value)}
>
{themes.length === 0 ? (
<option value={themeId}></option>
) : (
themes.map((theme) => (
<option key={theme.id} value={theme.id}>
{theme.name}
</option>
))
)}
</select>
{selectedTheme?.source === "local" ? (
<span className="local-theme-mark"></span>
) : null}
</label>
</div>
<div className="preview-scroll">
<div
className={`paper${
selectedTheme?.source === "local" ? " is-local-theme" : ""
}`}
>
{previewDocument ? (
<iframe
ref={previewFrameRef}
className="preview-frame"
title="文档内容预览"
sandbox="allow-same-origin"
srcDoc={previewDocument}
onLoad={() => void handlePreviewLoad()}
/>
) : (
<div className="preview-loading"></div>
)}
</div>
</div>
</section>
</section>
</main>
);
+254 -125
View File
@@ -1,8 +1,6 @@
:root {
color: #1d2522;
background:
radial-gradient(circle at 12% 10%, rgb(197 225 210 / 45%), transparent 30rem),
#f2f0e9;
color: #1e2925;
background: #e9ece8;
font-family:
Inter, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
font-synthesis: none;
@@ -26,169 +24,300 @@ textarea {
font: inherit;
}
.shell {
width: min(1120px, calc(100% - 40px));
margin: 0 auto;
padding: 88px 0;
}
.intro {
max-width: 760px;
}
.eyebrow,
.panel-label {
margin: 0 0 14px;
color: #34705a;
font-size: 0.75rem;
button,
.file-button {
min-height: 40px;
padding: 0 16px;
border: 1px solid #b8c2bd;
border-radius: 9px;
background: #fff;
color: #263a32;
font-size: 0.86rem;
font-weight: 700;
cursor: pointer;
}
button:disabled {
border-color: #d5d9d7;
background: #dfe3e1;
color: #8a938f;
cursor: not-allowed;
}
.workspace {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 28px;
min-height: 92px;
padding: 18px 28px;
border-bottom: 1px solid #cbd2ce;
background: rgb(247 248 246 / 92%);
}
.eyebrow {
margin: 0 0 4px;
color: #3b755d;
font-size: 0.66rem;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1,
h2,
p {
margin-top: 0;
}
h1 {
max-width: 700px;
margin-bottom: 22px;
margin: 0;
font-family: Georgia, "Songti SC", serif;
font-size: clamp(3rem, 8vw, 6.4rem);
font-size: clamp(1.45rem, 3vw, 2rem);
font-weight: 500;
letter-spacing: -0.055em;
line-height: 0.94;
letter-spacing: -0.025em;
}
.summary {
max-width: 610px;
margin-bottom: 28px;
color: #56615d;
font-size: 1.15rem;
line-height: 1.7;
.topbar-actions {
display: flex;
gap: 10px;
}
.status {
.file-button {
display: inline-flex;
align-items: center;
gap: 10px;
color: #315a4b;
}
.file-button input {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
}
.editor-layout {
display: grid;
grid-template-columns: minmax(360px, 0.8fr) minmax(520px, 1.2fr);
flex: 1;
min-height: 0;
}
.editor-panel,
.preview-panel {
display: flex;
flex-direction: column;
min-width: 0;
min-height: calc(100vh - 92px);
}
.editor-panel {
border-right: 1px solid #cbd2ce;
background: #f6f7f5;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
min-height: 66px;
padding: 12px 20px;
border-bottom: 1px solid #d9dedb;
background: rgb(255 255 255 / 70%);
}
.panel-heading > div {
display: flex;
flex-direction: column;
min-width: 0;
}
.panel-heading strong {
overflow: hidden;
font-size: 0.9rem;
font-weight: 650;
text-overflow: ellipsis;
white-space: nowrap;
}
.status-dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: #3da073;
box-shadow: 0 0 0 5px rgb(61 160 115 / 13%);
.panel-kicker {
margin-bottom: 3px;
color: #7a8580;
font-size: 0.65rem;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.panel {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(420px, 1.25fr);
gap: 48px;
align-items: end;
margin-top: 80px;
padding: 34px;
border: 1px solid rgb(41 64 55 / 14%);
border-radius: 20px;
background: rgb(255 255 255 / 58%);
box-shadow: 0 24px 60px rgb(49 67 59 / 8%);
backdrop-filter: blur(18px);
.render-status {
flex: none;
max-width: 48%;
overflow: hidden;
color: #4f695e;
font-size: 0.72rem;
text-overflow: ellipsis;
white-space: nowrap;
}
.panel h2 {
margin-bottom: 0;
font-family: Georgia, "Songti SC", serif;
font-size: clamp(1.8rem, 4vw, 3rem);
font-weight: 500;
.render-status.is-error {
color: #a23d3d;
}
.facts {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
margin: 0;
.theme-control {
display: flex;
flex: none;
align-items: center;
gap: 6px;
max-width: 56%;
}
.facts div {
padding: 18px;
border-radius: 13px;
background: #e6ebe6;
}
.facts dt {
margin-bottom: 7px;
color: #6b756f;
font-size: 0.75rem;
}
.facts dd {
margin: 0;
.theme-control select {
min-width: 0;
max-width: 220px;
height: 34px;
padding: 0 28px 0 10px;
overflow: hidden;
border: 1px solid #c9d4ce;
border-radius: 8px;
outline: 0;
background: #f8fbf9;
color: #356c55;
font-size: 0.74rem;
font-weight: 700;
text-overflow: ellipsis;
}
.capabilities {
.theme-control select:focus {
border-color: #74a88f;
box-shadow: 0 0 0 3px rgb(116 168 143 / 16%);
}
.local-theme-mark {
padding: 4px 7px;
border-radius: 999px;
background: #e3eee8;
color: #356c55;
font-size: 0.65rem;
font-weight: 800;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
textarea {
flex: 1;
width: 100%;
min-height: 560px;
padding: 24px;
border: 0;
outline: 0;
resize: none;
background: #f6f7f5;
color: #26312d;
font-family: "Cascadia Code", "SFMono-Regular", Consolas, monospace;
font-size: 0.86rem;
line-height: 1.72;
tab-size: 2;
}
textarea:focus {
box-shadow: inset 3px 0 #74a88f;
}
.preview-panel {
background:
linear-gradient(90deg, rgb(37 52 45 / 4%) 1px, transparent 1px),
linear-gradient(rgb(37 52 45 / 4%) 1px, transparent 1px),
#e6e9e5;
background-size: 22px 22px;
}
.preview-scroll {
flex: 1;
overflow: auto;
padding: 34px;
}
.paper {
width: 210mm;
min-width: 210mm;
min-height: 297mm;
margin: 0 auto;
padding: 20mm 18mm;
background: #fff;
box-shadow: 0 18px 48px rgb(37 49 43 / 16%);
}
.paper.is-local-theme {
padding: 8mm;
}
.preview-frame {
display: block;
width: 100%;
min-height: 500px;
border: 0;
background: #fff;
}
.preview-loading {
display: grid;
grid-template-columns: repeat(5, 1fr);
margin-top: 20px;
border-top: 1px solid rgb(41 64 55 / 16%);
min-height: 500px;
place-items: center;
color: #7a8580;
font-size: 0.9rem;
}
.capabilities article {
min-height: 132px;
padding: 20px 16px;
border-right: 1px solid rgb(41 64 55 / 16%);
}
.capabilities article:last-child {
border-right: 0;
}
.capabilities span {
color: #7e8983;
font-family: Georgia, serif;
font-size: 0.75rem;
}
.capabilities p {
margin: 42px 0 0;
font-size: 0.92rem;
font-weight: 650;
line-height: 1.45;
}
@media (max-width: 760px) {
.shell {
width: min(100% - 28px, 1120px);
padding: 48px 0;
@media (max-width: 900px) {
.topbar {
align-items: flex-start;
padding: 16px;
}
.panel {
grid-template-columns: 1fr;
margin-top: 56px;
padding: 24px;
.topbar-actions {
flex-direction: column;
}
.facts {
.editor-layout {
grid-template-columns: 1fr;
}
.capabilities {
grid-template-columns: 1fr;
.editor-panel,
.preview-panel {
min-height: 650px;
}
.capabilities article {
min-height: auto;
.editor-panel {
border-right: 0;
border-bottom: 1px solid rgb(41 64 55 / 16%);
border-bottom: 1px solid #cbd2ce;
}
.capabilities p {
margin-top: 16px;
.preview-scroll {
padding: 18px 10px;
}
.paper {
min-height: auto;
padding: 14mm 10mm;
}
.paper.is-local-theme {
padding: 8mm;
}
.theme-control {
max-width: 62%;
}
.theme-control select {
max-width: 150px;
}
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+240
View File
@@ -0,0 +1,240 @@
# Markdown PDF 导出器进度
最后更新:2026-07-25
## 1. 当前概况
项目目录:
```text
C:\Projects\md-to-pdf
```
当前分支:
```text
main
```
已有提交:
```text
7224dfd feat: 实现 Markdown 渲染核心
ec48bce chore: 初始化项目骨架
```
当前工作区存在未提交修改,主要是网页实时预览、预览 API、动态主题注册和本地 Typora 主题导入。接手时必须保留并审查这些修改,不要重置工作区。
## 2. 已完成
### 2.1 项目骨架
- 建立 npm workspaces。
- 建立 React + Vite 前端。
- 建立 Fastify 后端。
- 建立 `packages/core` 共享包。
- 建立主题、测试和 Docker 目录。
- 初始化本地 Git 仓库。
### 2.2 导出配置模型
`packages/core/src/export-config.ts` 已包含:
- 配置版本号;
- A3、A4、A5、Letter、Legal、Tabloid 和自定义纸张;
- 横向、纵向;
- 四边页边距;
- 页眉和页脚左右中区域;
- 页码位置和格式;
- PDF 元数据;
- 打印背景、缩放和一级标题分页选项;
- Zod 数据校验;
- 默认 A4 技术文档预设。
### 2.3 主题接口
`packages/core/src/theme.ts``themes/typora-like` 和动态主题注册器已包含:
- 版本化主题清单;
- 主题 ID、名称、版本、作者、许可证;
- DOM 预设;
- 支持能力声明;
- 主体 CSS 和打印 CSS
- 自制 Typora 风格主题;
- `#write` 兼容文档结构;
- 内置主题和 `.local/themes` 本地主题动态扫描;
- 主题 CSS 相对资源重写与受限资源接口;
- 目录匹配、真实路径包含关系和外部 URL 安全检查。
内置主题为项目自有实现,没有复制 Typora 官方默认主题。用户可以通过导入工具将本机已安装的 Typora GitHub 默认主题复制到 Git 忽略的 `.local/themes/typora-github`,该副本仅供本机使用,不进入仓库或发布包。
### 2.4 Markdown 渲染核心
提交 `7224dfd` 已完成:
- `packages/renderer` 独立工作区;
- Front Matter 解析;
- Markdown 到安全 HTML
- 标题锚点;
- 表格;
- 任务列表;
- 脚注;
- highlight.js 代码高亮;
- KaTeX 数学公式;
- Mermaid 安全占位;
- sanitize-html 安全过滤;
- 元数据规范化;
- 功能检测;
- 统一 `<article id="write">` 输出;
- 5 项渲染单元测试。
## 3. 当前未提交工作
以下内容已写入工作区,但尚未提交:
### 3.1 后端预览 API
- 将 Fastify 应用拆分为可测试的 `buildApp()`
- `POST /api/render`:接收 Markdown 并返回安全渲染结果。
- `GET /api/themes`:动态返回内置和本地可用主题。
- `GET /api/themes/:themeId/css`:返回主题 CSS 和打印 CSS。
- `GET /api/themes/:themeId/assets/*`:返回经过路径校验的主题字体和图片。
- 增加请求体积和参数类型检查。
- 增加 4 项后端 API 测试。
### 3.2 网页预览
- Markdown 文本编辑区;
- 本地 `.md` 文件读取;
- 250ms 防抖实时预览;
- 固定 210mm 宽度的 A4 纸张效果;
- 内置和本地主题选择;
- iframe 隔离主题 CSS,避免主题影响应用界面;
- KaTeX 样式;
- highlight.js 样式;
- Mermaid 浏览器渲染;
- Mermaid 改为按需加载;
- Mermaid 使用逐个 `render()` 后注入安全 SVG
- 桌面双栏与移动端上下布局;
- PDF 按钮保留为下一阶段入口。
### 3.3 文档及依赖
- README 已更新为预览阶段状态。
- 增加 `npm run theme:import-typora` 本地主题导入命令。
- `.local/` 已加入 Git 忽略规则。
- 增加 Mermaid、KaTeX、highlight.js 和后端测试依赖。
- `package-lock.json` 已更新。
## 4. 已执行验证
2026-07-25 在当前完整工作区成功执行:
```text
npm test
npm run typecheck
npm run build
git diff --check
```
结果:
- 渲染器测试:5 项通过;
- 后端测试:4 项通过;
- 全项目类型检查通过;
- 生产构建通过;
- `git diff --check` 通过,仅出现工作区 LF 将来可能转为 CRLF 的提示。
已使用浏览器插件完成视觉验证:
- 导入并打开 `tmp/数据中台项目周报_2026_W30.md`
- 参考 `tmp/数据中台项目周报_2026_W30.pdf` 的 Typora 输出;
- A4 纸张宽度、标题、长表格和滚动布局正常;
- 本地 Typora GitHub 主题及 Open Sans 字体加载正常;
- 内置主题与本地主题切换正常;
- KaTeX、代码高亮和 Mermaid 正常显示;
- 浏览器控制台无警告或错误。
视觉验证所启动的开发服务进程树已清理,3001 和 5173 端口无残留监听。
## 5. 当前注意事项
- 工作区不是干净状态,禁止重置。
- `apps/web/src/App.tsx` 是当前预览实现的主要文件。
- `apps/server/src/app.ts` 是新增的可测试 Fastify 应用。
- `apps/server/src/theme-registry.ts` 负责内置和本地主题发现、CSS 处理及资源安全。
- `.local/themes/typora-github` 是用户本机副本,已被 Git 忽略,不得提交。
- Mermaid 已按需加载,但生产构建仍提示 `mermaid.core``cynefin` 两个分块超过 500 kB;这不影响功能,可后续优化。
- PDF 生成尚未实现。
- 资源目录上传、本地相对图片、临时目录和路径安全尚未实现。
- Dockerfile 和 Compose 尚未实现。
## 6. 推荐接手顺序
### 阶段一:提交网页预览
网页预览、动态主题、本地 Typora 主题导入、全量验证和视觉检查均已完成。用户确认后创建独立提交:
```text
feat: 实现网页实时预览
```
### 阶段二:实现真实 PDF
开始编码前必须先给出具体设计和详细任务清单,等待用户确认。设计至少覆盖:
1. 增加 Playwright 和固定版本 Chromium。
2. 抽取可复用的完整 HTML 文档组装器。
3. 预览和 PDF 共用文章 HTML、主题 CSS、打印 CSS及资源。
4. 等待字体、图片、KaTeX 和 Mermaid 完成。
5. 实现 `POST /api/pdf`,响应 `application/pdf`
6. 前端启用“导出 PDF”按钮并下载文件。
7. 增加 PDF 接口与端到端测试。
### 阶段三:导出配置界面
- 纸张尺寸;
- 横向或纵向;
- 四边页边距;
- 页眉页脚开关;
- 左中右内容区域;
- 当前页和总页数;
- 多种页码预设;
- Front Matter 元数据覆盖;
- 浏览器本地配置预设;
- 配置 JSON 导入和导出。
### 阶段四:资源与安全
- Markdown 文件夹或 ZIP
- 相对图片解析;
- 每请求独立临时目录;
- 路径穿越防护;
- 文件数量、大小和超时限制;
- Chromium 并发和网络访问限制;
- 请求结束可靠清理。
### 阶段五:容器化与交付
- Dockerfile
- Docker Compose
- Chromium 字体与中文字体;
- 非 root 用户;
- 健康检查;
- 临时目录容量限制;
- 内网部署说明;
- 完整 PDF 样例和视觉回归验证。
## 7. 首版验收目标
- 可以选择或粘贴 Markdown
- 网页正确预览常用 Markdown、公式和 Mermaid
- 可以下载真实 PDF
- PDF 文本可搜索;
- 预览与 PDF 基本一致;
- 支持 A4、Letter、方向和边距;
- 支持基础页眉、页脚和页码;
- 支持主题切换扩展;
- 相对图片可用;
- 转换后不保留用户文档;
- Docker Compose 可在内网启动。
+1093 -2
View File
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -14,7 +14,8 @@
"dev:renderer": "npm run dev -w @md-to-pdf/renderer",
"dev:server": "npm run dev -w @md-to-pdf/server",
"dev:web": "npm run dev -w @md-to-pdf/web",
"test": "npm run test -w @md-to-pdf/renderer",
"theme:import-typora": "node scripts/import-typora-theme.mjs",
"test": "npm run test -w @md-to-pdf/renderer && npm run test -w @md-to-pdf/server",
"typecheck": "npm run typecheck -w @md-to-pdf/core && npm run build -w @md-to-pdf/core && npm run typecheck -w @md-to-pdf/renderer && npm run build -w @md-to-pdf/renderer && npm run typecheck -w @md-to-pdf/web && npm run typecheck -w @md-to-pdf/server"
},
"engines": {
+78
View File
@@ -0,0 +1,78 @@
import { cp, mkdir, readFile, writeFile } from "node:fs/promises";
import { constants } from "node:fs";
import { access } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const projectRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const sourceRoot =
process.env.TYPORA_THEME_DIR ??
join(process.env.APPDATA ?? "", "Typora", "themes");
const sourceCss = join(sourceRoot, "github.css");
const sourceAssets = join(sourceRoot, "github");
const targetRoot = join(projectRoot, ".local", "themes", "typora-github");
async function assertReadable(path, label) {
try {
await access(path, constants.R_OK);
} catch {
throw new Error(`${label}不存在或不可读取:${path}`);
}
}
await assertReadable(sourceCss, "Typora GitHub 主题");
await assertReadable(sourceAssets, "Typora GitHub 主题资源目录");
try {
await access(targetRoot, constants.F_OK);
throw new Error(
`目标目录已存在:${targetRoot}\n请先人工确认并移走旧目录,再重新导入。`
);
} catch (error) {
if (error instanceof Error && error.message.startsWith("目标目录已存在")) {
throw error;
}
}
await mkdir(targetRoot, { recursive: true });
await cp(sourceAssets, join(targetRoot, "github"), {
recursive: true,
errorOnExist: true,
force: false
});
await writeFile(
join(targetRoot, "github.css"),
await readFile(sourceCss, "utf8"),
"utf8"
);
const manifest = {
manifestVersion: 1,
id: "typora-github",
name: "Typora 默认(GitHub,本地)",
version: "local",
description:
"从本机 Typora 安装导入,仅供当前设备个人使用,不进入 Git、容器或发布包。",
author: "Typora",
license: "本地个人使用,未随项目分发",
entry: "github.css",
domPreset: "typora",
defaultFontSize: "16px",
supportedFeatures: [
"code",
"table",
"task-list",
"footnote",
"katex",
"mermaid"
],
bundled: false
};
await writeFile(
join(targetRoot, "theme.json"),
`${JSON.stringify(manifest, null, 2)}\n`,
"utf8"
);
console.log(`已导入本地 Typora 主题:${targetRoot}`);