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
+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" />