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