refactor: 收敛渲染链路共享抽象
This commit is contained in:
+52
-144
@@ -10,6 +10,7 @@ import {
|
||||
useState
|
||||
} from "react";
|
||||
import {
|
||||
createPagedDocumentPayload,
|
||||
getPaperDimensionsMm,
|
||||
millimetersToCssPixels,
|
||||
type ExportConfig
|
||||
@@ -43,6 +44,11 @@ import {
|
||||
loadPreviewZoom,
|
||||
savePreviewZoom
|
||||
} from "./preview-zoom";
|
||||
import { useMarkdownRender } from "./use-markdown-render";
|
||||
import {
|
||||
type ThemeSummary,
|
||||
useThemeResources
|
||||
} from "./use-theme-resources";
|
||||
|
||||
const PrecisePdfPreview = lazy(async () => {
|
||||
const module = await import("./PrecisePdfPreview");
|
||||
@@ -51,28 +57,6 @@ const PrecisePdfPreview = lazy(async () => {
|
||||
|
||||
type PreviewMode = "quick" | "precise";
|
||||
|
||||
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: 内网文档团队
|
||||
@@ -113,15 +97,11 @@ flowchart LR
|
||||
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 [exportConfig, setExportConfig] =
|
||||
useState<ExportConfig>(loadExportConfig);
|
||||
const [themeCss, setThemeCss] = useState("");
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [status, setStatus] = useState("正在准备预览…");
|
||||
const [renderError, setRenderError] = useState("");
|
||||
const [themeError, setThemeError] = useState("");
|
||||
const [appError, setAppError] = useState("");
|
||||
const [mermaidError, setMermaidError] = useState("");
|
||||
const [paginationError, setPaginationError] = useState("");
|
||||
const [pdfError, setPdfError] = useState("");
|
||||
@@ -146,9 +126,47 @@ export function App() {
|
||||
"editor" | "preview" | undefined
|
||||
>(undefined);
|
||||
|
||||
const handleThemesLoaded = useCallback(
|
||||
(availableThemes: ThemeSummary[]) => {
|
||||
setExportConfig((currentConfig) => {
|
||||
if (
|
||||
availableThemes.some(
|
||||
(theme) => theme.id === currentConfig.themeId
|
||||
)
|
||||
) {
|
||||
return currentConfig;
|
||||
}
|
||||
const preferredTheme =
|
||||
availableThemes.find((theme) => theme.id === "typora-github") ??
|
||||
availableThemes.find((theme) => theme.id === "typora-like") ??
|
||||
availableThemes[0];
|
||||
return preferredTheme
|
||||
? { ...currentConfig, themeId: preferredTheme.id }
|
||||
: currentConfig;
|
||||
});
|
||||
},
|
||||
[]
|
||||
);
|
||||
const handleRenderStart = useCallback(() => {
|
||||
setMermaidError("");
|
||||
}, []);
|
||||
const { error: renderError, result } = useMarkdownRender(
|
||||
markdown,
|
||||
"zh-CN",
|
||||
{
|
||||
onRenderStart: handleRenderStart,
|
||||
onStatusChange: setStatus
|
||||
}
|
||||
);
|
||||
const {
|
||||
error: themeError,
|
||||
themeCss,
|
||||
themes
|
||||
} = useThemeResources(exportConfig.themeId, handleThemesLoaded);
|
||||
const error =
|
||||
renderError ||
|
||||
themeError ||
|
||||
appError ||
|
||||
mermaidError ||
|
||||
paginationError ||
|
||||
pdfError;
|
||||
@@ -176,14 +194,12 @@ export function App() {
|
||||
const previewPayload = useMemo<PagedPreviewPayload | undefined>(
|
||||
() =>
|
||||
result && themeCss
|
||||
? {
|
||||
articleHtml: result.articleHtml,
|
||||
? createPagedDocumentPayload({
|
||||
document: result,
|
||||
fileName,
|
||||
metadata: result.metadata,
|
||||
features: result.features,
|
||||
themeCss,
|
||||
exportConfig
|
||||
}
|
||||
})
|
||||
: undefined,
|
||||
[exportConfig, fileName, result, themeCss]
|
||||
);
|
||||
@@ -204,53 +220,12 @@ export function App() {
|
||||
previewModeRef.current = previewMode;
|
||||
pdfRequestKeyRef.current = pdfCacheKey;
|
||||
|
||||
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);
|
||||
setExportConfig((currentConfig) => {
|
||||
if (
|
||||
availableThemes.some(
|
||||
(theme) => theme.id === currentConfig.themeId
|
||||
)
|
||||
) {
|
||||
return currentConfig;
|
||||
}
|
||||
const preferredTheme =
|
||||
availableThemes.find((theme) => theme.id === "typora-github") ??
|
||||
availableThemes.find((theme) => theme.id === "typora-like") ??
|
||||
availableThemes[0];
|
||||
return preferredTheme
|
||||
? { ...currentConfig, themeId: preferredTheme.id }
|
||||
: currentConfig;
|
||||
});
|
||||
})
|
||||
.catch((reason: unknown) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setThemeError(
|
||||
reason instanceof Error ? reason.message : "无法加载主题清单"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return () => controller.abort();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
saveExportConfig(exportConfig);
|
||||
setAppError("");
|
||||
} catch {
|
||||
setRenderError("无法保存导出设置,当前设置仅在本次页面中有效");
|
||||
setAppError("无法保存导出设置,当前设置仅在本次页面中有效");
|
||||
}
|
||||
}, [exportConfig]);
|
||||
|
||||
@@ -271,77 +246,9 @@ export function App() {
|
||||
}, [pdfCache, pdfCacheKey]);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setPreviewFrameReady(false);
|
||||
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]);
|
||||
|
||||
useEffect(() => {
|
||||
function handlePreviewFrameMessage(event: MessageEvent<unknown>) {
|
||||
const frame = previewFrameRef.current;
|
||||
@@ -552,10 +459,11 @@ export function App() {
|
||||
}
|
||||
|
||||
try {
|
||||
setAppError("");
|
||||
setMarkdown(await file.text());
|
||||
setFileName(file.name);
|
||||
} catch {
|
||||
setRenderError("无法读取所选 Markdown 文件");
|
||||
setAppError("无法读取所选 Markdown 文件");
|
||||
} finally {
|
||||
event.target.value = "";
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import highlightCss from "highlight.js/styles/github.css?inline";
|
||||
import katexCss from "katex/dist/katex.min.css?inline";
|
||||
import type {
|
||||
PagedDocumentRenderResult,
|
||||
PagedDocumentTimings
|
||||
} from "@md-to-pdf/core";
|
||||
import { Previewer } from "pagedjs";
|
||||
import { createMermaidSiteConfig } from "./mermaid-config";
|
||||
import {
|
||||
@@ -20,23 +24,10 @@ import {
|
||||
} from "./paged-preview";
|
||||
import type { PagedRenderTarget } from "./paged-render-target";
|
||||
|
||||
export interface PagedDocumentRenderResult {
|
||||
pageCount: number;
|
||||
contentHeight: number;
|
||||
mermaidErrors: string[];
|
||||
timings: PagedDocumentTimings;
|
||||
}
|
||||
|
||||
export interface PagedDocumentTimings {
|
||||
setupMs: number;
|
||||
mermaidMs: number;
|
||||
mermaidFitMs: number;
|
||||
mermaidConversionMs: number;
|
||||
resourceWaitMs: number;
|
||||
paginationMs: number;
|
||||
finalizeMs: number;
|
||||
totalMs: number;
|
||||
}
|
||||
export type {
|
||||
PagedDocumentRenderResult,
|
||||
PagedDocumentTimings
|
||||
} from "@md-to-pdf/core";
|
||||
|
||||
export interface PagedDocumentRenderOptions {
|
||||
target: PagedRenderTarget;
|
||||
@@ -364,13 +355,6 @@ export class PagedDocumentRuntime {
|
||||
|
||||
return {
|
||||
pageCount: flow.total,
|
||||
contentHeight: Math.ceil(
|
||||
Math.max(
|
||||
documentRef.documentElement.scrollHeight,
|
||||
documentRef.body.scrollHeight,
|
||||
this.root.scrollHeight
|
||||
)
|
||||
),
|
||||
mermaidErrors,
|
||||
timings: {
|
||||
setupMs,
|
||||
|
||||
@@ -1,27 +1,15 @@
|
||||
import {
|
||||
getPaperDimensionsMm,
|
||||
type ExportConfig
|
||||
type ExportConfig,
|
||||
type MarkdownDocumentMetadata,
|
||||
type PagedDocumentPayload
|
||||
} from "@md-to-pdf/core";
|
||||
import { PREVIEW_SCROLLBAR_WIDTH_PX } from "./preview-page";
|
||||
|
||||
export const PAGED_PREVIEW_MESSAGE_SCOPE = "md-to-pdf:paged-preview";
|
||||
|
||||
export interface PreviewMetadata {
|
||||
title: string;
|
||||
author: string;
|
||||
subject: string;
|
||||
keywords: string[];
|
||||
language: string;
|
||||
}
|
||||
|
||||
export interface PagedPreviewPayload {
|
||||
articleHtml: string;
|
||||
fileName: string;
|
||||
metadata: PreviewMetadata;
|
||||
features: string[];
|
||||
themeCss: string;
|
||||
exportConfig: ExportConfig;
|
||||
}
|
||||
export type PreviewMetadata = MarkdownDocumentMetadata;
|
||||
export type PagedPreviewPayload = PagedDocumentPayload;
|
||||
|
||||
export interface PagedPreviewRenderRequest {
|
||||
scope: typeof PAGED_PREVIEW_MESSAGE_SCOPE;
|
||||
@@ -45,7 +33,6 @@ export type PagedPreviewFrameMessage =
|
||||
type: "rendered";
|
||||
requestId: number;
|
||||
pageCount: number;
|
||||
contentHeight: number;
|
||||
mermaidErrors: string[];
|
||||
}
|
||||
| {
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
export const PDF_POINTS_PER_INCH = 72;
|
||||
export const CSS_PIXELS_PER_INCH = 96;
|
||||
import {
|
||||
CSS_PIXELS_PER_INCH,
|
||||
PDF_POINTS_PER_INCH
|
||||
} from "@md-to-pdf/core";
|
||||
|
||||
export const PDF_PAGE_CSS_SCALE =
|
||||
CSS_PIXELS_PER_INCH / PDF_POINTS_PER_INCH;
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { RenderedMarkdownDocument } from "@md-to-pdf/core";
|
||||
|
||||
export interface MarkdownRenderCallbacks {
|
||||
onRenderStart?: () => void;
|
||||
onStatusChange?: (status: string) => void;
|
||||
}
|
||||
|
||||
export function useMarkdownRender(
|
||||
markdown: string,
|
||||
language: string,
|
||||
callbacks: MarkdownRenderCallbacks = {}
|
||||
) {
|
||||
const [result, setResult] =
|
||||
useState<RenderedMarkdownDocument | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
const { onRenderStart, onStatusChange } = callbacks;
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
const timer = window.setTimeout(() => {
|
||||
onStatusChange?.("正在渲染…");
|
||||
onRenderStart?.();
|
||||
setError("");
|
||||
|
||||
void fetch("/api/render", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({ markdown, language }),
|
||||
signal: controller.signal
|
||||
})
|
||||
.then(async (response) => {
|
||||
const payload = (await response.json()) as
|
||||
| RenderedMarkdownDocument
|
||||
| { message?: string };
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
"message" in payload
|
||||
? payload.message ?? "渲染失败"
|
||||
: "渲染失败"
|
||||
);
|
||||
}
|
||||
return payload as RenderedMarkdownDocument;
|
||||
})
|
||||
.then((payload) => {
|
||||
setResult(payload);
|
||||
onStatusChange?.("预览已更新");
|
||||
})
|
||||
.catch((reason: unknown) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(
|
||||
reason instanceof Error ? reason.message : "渲染失败"
|
||||
);
|
||||
onStatusChange?.("预览失败");
|
||||
}
|
||||
});
|
||||
}, 250);
|
||||
|
||||
return () => {
|
||||
window.clearTimeout(timer);
|
||||
controller.abort();
|
||||
};
|
||||
}, [language, markdown, onRenderStart, onStatusChange]);
|
||||
|
||||
return { error, result };
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export interface ThemeSummary {
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
description: string;
|
||||
bundled: boolean;
|
||||
source: "bundled" | "local";
|
||||
}
|
||||
|
||||
export function useThemeResources(
|
||||
themeId: string,
|
||||
onThemesLoaded: (themes: ThemeSummary[]) => void
|
||||
) {
|
||||
const [themes, setThemes] = useState<ThemeSummary[]>([]);
|
||||
const [themeCss, setThemeCss] = useState("");
|
||||
const [catalogError, setCatalogError] = useState("");
|
||||
const [cssError, setCssError] = useState("");
|
||||
|
||||
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);
|
||||
setCatalogError("");
|
||||
onThemesLoaded(availableThemes);
|
||||
})
|
||||
.catch((reason: unknown) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setCatalogError(
|
||||
reason instanceof Error ? reason.message : "无法加载主题清单"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return () => controller.abort();
|
||||
}, [onThemesLoaded]);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setThemeCss("");
|
||||
setCssError("");
|
||||
|
||||
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) {
|
||||
setCssError(
|
||||
reason instanceof Error ? reason.message : "无法加载主题"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return () => controller.abort();
|
||||
}, [themeId]);
|
||||
|
||||
return {
|
||||
error: catalogError || cssError,
|
||||
themeCss,
|
||||
themes
|
||||
};
|
||||
}
|
||||
@@ -178,7 +178,6 @@ describe("分页预览协议", () => {
|
||||
type: "rendered",
|
||||
requestId: 3,
|
||||
pageCount: 2,
|
||||
contentHeight: 2300,
|
||||
mermaidErrors: []
|
||||
})
|
||||
).toBe(true);
|
||||
|
||||
Reference in New Issue
Block a user