Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

61.1 KB
Raw Blame
import {hideMessage, showMessage} from "../../dialog/message";
import {Constants} from "../../constants";
/// #if !BROWSER
import {ipcRenderer} from "electron";
import * as fs from "fs";
import * as path from "path";
import {afterExport} from "./util";
/// #endif
import {confirmDialog} from "../../dialog/confirmDialog";
import {getThemeMode, setInlineStyle} from "../../util/assets";
import {getCustomFontStyle} from "../../util/customFont";
import {fetchPost, fetchSyncPost} from "../../util/fetch";
import {Dialog} from "../../dialog";
import {replaceLocalPath} from "../../editor/rename";
import {getScreenWidth, isInMobileApp, saveExportFile, setStorageVal} from "../util/compatibility";
import {getFrontend, isBrowser} from "../../util/functions";
import {isEncryptedBox} from "../../util/pathName";
import {getHostCapabilities} from "../../util/hostCapabilities";
import {getLastExportPath, setLastExportPath} from "./path";
import {normalizeHeadingPageBreakLevels} from "./headingPageBreaks";
import {headingPageBreakControls} from "./headingPageBreaksUI";
import type {APICallbackResponse, APIPOSTRoutes} from "../../types/api";

const getExportLanguages = () => {
    const keys = new Set([
        "copy", "mindmap", "fontSize", "bold", "italic", "colorFont", "color", "undo", "redo", "fold", "collapse", "expand",
        "fullscreen", "exitFullscreen", "zoomIn", "zoomOut", "delete", "close", "connect", "text",
        "task", "taskStatusTodo", "taskStatusInProgress", "taskStatusDone", "taskStatusCanceled", "customTaskStatus",
        "expandLevel", "expandAll", "foldAll",
    ]);
    const languages = Object.fromEntries(Object.entries(window.siyuan.languages)
        .filter(([key]) => keys.has(key) || key.startsWith("listMindmap")));
    // 转义脚本边界和行分隔符,保留各语言文案中的引号与换行。
    return JSON.stringify(languages).replace(/</g, "\\u003c")
        .replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
};

const getPluginStyle = async () => {
    const response = await fetchSyncPost("/api/petal/loadPetals", {frontend: getFrontend()});
    let css = "";
    // 为加快启动速度,不进行 await
    (response.code === 0 && Array.isArray(response.data) ? response.data : []).forEach(item => {
        css += item.css || "";
    });
    return css;
};

const getIconScript = (servePath: string) => {
    const isBuiltInIcon = ["litheness"].includes(window.siyuan.config.appearance.icon);
    const html = isBuiltInIcon ? "" : `<script src="${servePath}appearance/icons/litheness/icon.js?v=${Constants.SIYUAN_VERSION}"></script>`;
    return html + `<script src="${servePath}appearance/icons/${window.siyuan.config.appearance.icon}/icon.js?v=${Constants.SIYUAN_VERSION}"></script>`;
};

export const saveExport = (option: IExportOptions) => {
    if (!getHostCapabilities().documentImportExport) {
        return;
    }
    if ((isBrowser() || getHostCapabilities().remoteKernel) && ["html", "htmlmd"].includes(option.type)) {
        const startExport = () => {
            const msgId = showMessage(window.siyuan.languages.exporting, -1);
            // 浏览器和远程连接先生成资源与完整 HTML,再下载服务器打包的导出物。
            const onExportHTML = async (exportResponse: APICallbackResponse<APIPOSTRoutes["/api/export/exportHTML"]["response"]>) => {
                const html = await onExport(exportResponse, undefined, "", option);
                fetchPost("/api/export/exportBrowserHTML", {
                    folder: exportResponse.data.folder,
                    html: html,
                    name: exportResponse.data.name
                }, zipResponse => {
                    saveExportFile(zipResponse.data.zip, msgId);
                });
            };
            if (option.type === "htmlmd") {
                fetchPost("/api/export/exportMdHTML", {id: option.id, savePath: ""}, onExportHTML);
            } else {
                fetchPost("/api/export/exportHTML", {id: option.id, pdf: false, merge: true, savePath: ""}, onExportHTML);
            }
        };
        fetchPost("/api/block/getBlockInfo", {id: option.id}, (response) => {
            if (response.code === 0 && isEncryptedBox(response.data.box)) {
                confirmDialog("⚠️ " + window.siyuan.languages.export, window.siyuan.languages.encryptedExportRiskTip, startExport);
                return;
            }
            startExport();
        });
        return;
    }
    if (!getHostCapabilities().importExport) {
        return;
    }
    /// #if !BROWSER
    if (option.type === "pdf") {
        if (window.siyuan.config.appearance.mode === 1) {
            confirmDialog(window.siyuan.languages.pdfTip, window.siyuan.languages.pdfConfirm, () => {
                renderPDF(option.id);
            });
        } else {
            renderPDF(option.id);
        }
    } else if (option.type === "word") {
        const localData = window.siyuan.storage[Constants.LOCAL_EXPORTWORD];
        const wordDialog = new Dialog({
            title: "Word " + window.siyuan.languages.config,
            content: `<div class="b3-dialog__content">
    <label class="fn__flex b3-label">
        <div class="fn__flex-1">
            ${window.siyuan.languages.removeAssetsFolder}
        </div>
        <span class="fn__space"></span>
        <input id="removeAssets" class="b3-switch" type="checkbox" ${localData.removeAssets ? "checked" : ""}>
    </label>
    <label class="fn__flex b3-label">
        <div class="fn__flex-1">
            ${window.siyuan.languages.mergeSubdocs}
        </div>
        <span class="fn__space"></span>
        <input id="mergeSubdocs" class="b3-switch" type="checkbox" ${localData.mergeSubdocs ? "checked" : ""}>
    </label>
    <label class="fn__flex b3-label merge-heading-option${localData.mergeSubdocs ? "" : " fn__none"}">
        <div class="fn__flex-1">
            ${window.siyuan.languages.mergeDocHeadingMode}
        </div>
        <span class="fn__space"></span>
        <select id="mergeDocHeadingMode" class="b3-select">
            <option value="flat" ${localData.mergeDocHeadingMode === "flat" ? "selected" : ""}>${window.siyuan.languages.mergeDocHeadingFlat}</option>
            <option value="tree" ${localData.mergeDocHeadingMode === "tree" ? "selected" : ""}>${window.siyuan.languages.mergeDocHeadingTree}</option>
        </select>
    </label>
    <label class="fn__flex b3-label merge-heading-option${localData.mergeSubdocs ? "" : " fn__none"}">
        <div class="fn__flex-1">
            ${window.siyuan.languages.mergeContentHeadingMode}
        </div>
        <span class="fn__space"></span>
        <select id="mergeContentHeadingMode" class="b3-select">
            <option value="preserve" ${localData.mergeContentHeadingMode === "preserve" ? "selected" : ""}>${window.siyuan.languages.mergeContentHeadingPreserve}</option>
            <option value="demote" ${localData.mergeContentHeadingMode === "demote" ? "selected" : ""}>${window.siyuan.languages.mergeContentHeadingDemote}</option>
        </select>
    </label>
</div>
<div class="b3-dialog__action">
    <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>
    <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>
</div>`,
            width: "520px",
        });
        wordDialog.element.setAttribute("data-key", Constants.DIALOG_EXPORTWORD);
        const mergeSubdocsElement = wordDialog.element.querySelector("#mergeSubdocs") as HTMLInputElement;
        mergeSubdocsElement.addEventListener("change", () => {
            wordDialog.element.querySelectorAll(".merge-heading-option").forEach((item) => {
                item.classList.toggle("fn__none", !mergeSubdocsElement.checked);
            });
        });
        const btnsElement = wordDialog.element.querySelectorAll(".b3-button");
        btnsElement[0].addEventListener("click", () => {
            wordDialog.destroy();
        });
        btnsElement[1].addEventListener("click", () => {
            const removeAssets = (wordDialog.element.querySelector("#removeAssets") as HTMLInputElement).checked;
            const mergeSubdocs = mergeSubdocsElement.checked;
            const mergeDocHeadingMode = (wordDialog.element.querySelector("#mergeDocHeadingMode") as HTMLSelectElement).value;
            const mergeContentHeadingMode = (wordDialog.element.querySelector("#mergeContentHeadingMode") as HTMLSelectElement).value;
            window.siyuan.storage[Constants.LOCAL_EXPORTWORD] = {
                removeAssets,
                mergeSubdocs,
                mergeDocHeadingMode,
                mergeContentHeadingMode,
            };
            setStorageVal(Constants.LOCAL_EXPORTWORD, window.siyuan.storage[Constants.LOCAL_EXPORTWORD]);
            getExportPath(option, removeAssets, mergeSubdocs, mergeDocHeadingMode, mergeContentHeadingMode);
            wordDialog.destroy();
        });
    } else {
        getExportPath(option, false, true);
    }
    /// #endif
};

const getSnippetCSS = () => {
    let snippetCSS = "";
    document.querySelectorAll("style").forEach((item) => {
        if (item.id.startsWith("snippetCSS")) {
            snippetCSS += item.outerHTML;
        }
    });
    return snippetCSS;
};

const getSnippetJS = () => {
    let snippetScript = "";
    document.querySelectorAll("script").forEach((item) => {
        if (item.id.startsWith("snippetJS")) {
            snippetScript += item.outerHTML;
        }
    });
    return snippetScript;
};

/// #if !BROWSER
const getAvailableExportPath = async () => {
    const exportPath = getLastExportPath();
    if (!exportPath) {
        return "";
    }
    try {
        return (await fs.promises.stat(exportPath)).isDirectory() ? exportPath : "";
    } catch (e) {
        return "";
    }
};

const renderPDF = async (id: string) => {
    const localData = window.siyuan.storage[Constants.LOCAL_EXPORTPDF];
    if (typeof localData.paged === "undefined") {
        localData.paged = true;
    }
    // 导出预览临时页可能由不同于主窗口的内核端口提供,使用相对路径可确保资源和接口保持同源。
    const servePathWithoutTrailingSlash = "";
    const servePath = "/";
    const isDefault = window.siyuan.config.appearance.themeLight === "daylight";
    let themeStyle = "";
    if (!isDefault) {
        themeStyle = `<link rel="stylesheet" type="text/css" id="themeStyle" href="${servePath}appearance/themes/${window.siyuan.config.appearance.themeLight}/theme.css?${Constants.SIYUAN_VERSION}"/>`;
    }
    const currentWindowId = await ipcRenderer.invoke(Constants.SIYUAN_GET, {
        cmd: "getContentsId",
    });
    const defaultExportPath = await getAvailableExportPath();
    // 开发编译不会改变版本号,预览页需刷新导出样式和渲染脚本,避免沿用编译前的缓存。
    const exportResourceVersion = Constants.NODE_ENV === "development" ?
        `${Constants.SIYUAN_VERSION}-${Date.now()}` : Constants.SIYUAN_VERSION;
    // data-theme-mode="light" https://github.com/siyuan-note/siyuan/issues/7379
    const html = `<!DOCTYPE html>
<html lang="${window.siyuan.config.appearance.lang}" data-theme-mode="light" data-light-theme="${window.siyuan.config.appearance.themeLight}" data-dark-theme="${window.siyuan.config.appearance.themeDark}">
<head>
    <base href="${servePath}">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
    <meta name="mobile-web-app-capable" content="yes"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="stylesheet" type="text/css" id="baseStyle" href="${servePath}stage/build/export/base.css?v=${exportResourceVersion}"/>
    <link rel="stylesheet" type="text/css" id="themeDefaultStyle" href="${servePath}appearance/themes/daylight/theme.css?v=${Constants.SIYUAN_VERSION}"/>
    <script src="${servePath}stage/protyle/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}"></script>
    ${themeStyle}
    <title>${window.siyuan.languages.export} PDF</title>
    <style>
        body {
          margin: 0;
          font-family: var(--b3-font-family);
          background-color: var(--b3-body-background);
        }
        
        #action {
          width: 280px;
          background-color: var(--b3-theme-background);
          padding: 12px 0;
          position: fixed;
          right: 0;
          top: 0;
          overflow-y: auto;
          bottom: 0;
          overflow-x: hidden;
          z-index: 1;
          display: flex;
          flex-direction: column;
          border-left: 1px solid var(--b3-body-background);
        }
        
        .b3-switch {
            margin-left: 14px;
        }

        #action .b3-select:focus {
            outline: none;
        }
        
        #previewContainer {
          position: fixed;
          top: 0;
          right: 280px;
          bottom: 0;
          left: 0;
          overflow: auto;
        }

        #preview {
          max-width: 800px;
          margin: 24px auto;
          position: relative;
          min-height: calc(100% - 48px);
          box-sizing: border-box;
          background-color: var(--b3-theme-background);
          box-shadow: var(--b3-dialog-shadow);
        }

        .exporting #previewContainer {
          position: inherit;
          overflow: visible;
        }
        
        .exporting #preview {
          position: inherit;
          max-width: none;
          box-shadow: none;
        }
        
        .exporting {
            background-color: var(--b3-theme-background);
        }
        
        .exporting #preview::-webkit-scrollbar {
          width: 0;
          height: 0;
        }
        
        .protyle-wysiwyg {
          height: 100%;
          overflow: auto;
          box-sizing: border-box;
        }
        
        .b3-label {
          border-bottom: 1px solid var(--b3-theme-surface-lighter);
          display: block;
          color: var(--b3-theme-on-surface);
          padding-bottom: 12px;
          margin: 0 12px 12px 12px;
        }
        
        .b3-label:last-child {
            border-bottom: none;
        }

        #mergeHeadingOptions .b3-label:last-child {
            border-bottom: 1px solid var(--b3-theme-surface-lighter);
        }
        
        #preview .render-node[data-subtype="plantuml"] object {
            max-width: 100%;
        }

        #preview .mindmap-view__toolbar {
            display: none !important;
        }

        #preview .mindmap-view {
            height: var(--mindmap-view-print-height, 420px);
            min-height: 0;
        }

        #preview a.pdf-embedded-asset {
            position: relative;
            padding-right: 1em !important;
        }

        #preview .pdf-embedded-asset__icon {
            position: absolute;
            right: 0;
            bottom: 0;
            width: 1em;
            height: 1em;
            color: currentColor;
            pointer-events: none;
        }

        .exporting #preview .pdf-embedded-asset__icon {
            visibility: hidden;
        }
        ${await setInlineStyle(false, servePath)}
        ${getHostCapabilities().customAppearance ? await getCustomFontStyle() : ""}
        ${await getPluginStyle()}
    </style>
    ${getSnippetCSS()}
</head>
<body data-export-pdf="true" style="-webkit-print-color-adjust: exact;">
<div id="action">
    <div style="flex: 1;overflow-y:auto;overflow-x:hidden">
        <div class="b3-label">
            <div>
                ${window.siyuan.languages.exportPDF0}
            </div>
            <span class="fn__hr"></span>
            <select class="b3-select" id="pageSize">
                <option ${localData.pageSize === "A3" ? "selected" : ""} value="A3">A3</option>
                <option ${localData.pageSize === "A4" ? "selected" : ""} value="A4">A4</option>
                <option ${localData.pageSize === "A5" ? "selected" : ""} value="A5">A5</option>
                <option ${localData.pageSize === "Legal" ? "selected" : ""} value="Legal">Legal</option>
                <option ${localData.pageSize === "Letter" ? "selected" : ""} value="Letter">Letter</option>
                <option ${localData.pageSize === "Tabloid" ? "selected" : ""} value="Tabloid">Tabloid</option>
            </select>
        </div>
        <div class="b3-label">
            <div>
                ${window.siyuan.languages.exportPDF2}
            </div>
            <span class="fn__hr"></span>
            <select class="b3-select" id="marginsType">
                <option ${localData.marginType === "default" ? "selected" : ""} value="default">${window.siyuan.languages.defaultMargin}</option>
                <option ${localData.marginType === "none" ? "selected" : ""} value="none">${window.siyuan.languages.noneMargin}</option>
                <option ${localData.marginType === "printableArea" ? "selected" : ""} value="printableArea">${window.siyuan.languages.minimalMargin}</option>
                <option ${localData.marginType === "custom" ? "selected" : ""} value="custom">${window.siyuan.languages.customMargin}</option>
            </select>
            <div class="${localData.marginType === "custom" ? "" : "fn__none"}">
                <span class="fn__hr"></span>
                <small>${window.siyuan.languages.marginTop}</small>
                <div class="fn__hr--small"></div>
                <div class="fn__flex">
                    <input id="marginsTop" class="b3-text-field fn__block" value="${localData.marginTop || 0}" type="number" min="0" step="0.01">
                    <span class="fn__space"></span>
                    <small class="fn__flex-center" style="white-space: nowrap;">${window.siyuan.languages.unitInches}</small>
                </div>
                <div class="fn__hr"></div>
                <small>${window.siyuan.languages.marginRight}</small>
                <div class="fn__hr--small"></div>
                <div class="fn__flex">
                    <input id="marginsRight" class="b3-text-field fn__block" value="${localData.marginRight || 0}" type="number" min="0" step="0.01">
                    <span class="fn__space"></span>
                    <small class="fn__flex-center" style="white-space: nowrap;">${window.siyuan.languages.unitInches}</small>
                </div>
                <div class="fn__hr"></div>
                <small>${window.siyuan.languages.marginBottom}</small>
                <div class="fn__hr--small"></div>
                <div class="fn__flex">
                    <input id="marginsBottom" class="b3-text-field fn__block" value="${localData.marginBottom || 0}" type="number" min="0" step="0.01">
                    <span class="fn__space"></span>
                    <small class="fn__flex-center" style="white-space: nowrap;">${window.siyuan.languages.unitInches}</small>
                </div>
                <div class="fn__hr"></div>
                <small>${window.siyuan.languages.marginLeft}</small>
                <div class="fn__hr--small"></div>
                <div class="fn__flex">
                    <input id="marginsLeft" class="b3-text-field fn__block" value="${localData.marginLeft || 0}" type="number" min="0" step="0.01">
                    <span class="fn__space"></span>
                    <small class="fn__flex-center" style="white-space: nowrap;">${window.siyuan.languages.unitInches}</small>
                </div>
            </div>
        </div>
        <div class="b3-label">
            <div>
                ${window.siyuan.languages.exportPDF3}
                <span id="scaleTip" style="float: right;color: var(--b3-theme-on-background);">${localData.scale || 1}</span>
            </div>
            <span class="fn__hr"></span>
            <input style="width: 189px" value="${localData.scale || 1}" id="scale" step="0.1" class="b3-slider" type="range" min="0.1" max="2">
        </div>
        <label class="b3-label">
            <div>
                ${window.siyuan.languages.exportPDF1}
            </div>
            <span class="fn__hr"></span>
          <input id="landscape" class="b3-switch" type="checkbox" ${localData.landscape ? "checked" : ""}>
        </label>
        <label class="b3-label">
            <div>
                ${window.siyuan.languages.exportPDF4}
            </div>
            <span class="fn__hr"></span>
            <input id="removeAssets" class="b3-switch" type="checkbox" ${localData.removeAssets ? "checked" : ""}>
        </label>
        <label class="b3-label">
            <div>
                ${window.siyuan.languages.exportPDF5}
            </div>
            <span class="fn__hr"></span>
            <input id="keepFold" class="b3-switch" type="checkbox" ${localData.keepFold ? "checked" : ""}>
        </label>
        <label class="b3-label">
            <div>
                ${window.siyuan.languages.export17}
            </div>
            <span class="fn__hr"></span>
            <input id="addTitle" class="b3-switch" type="checkbox" ${window.siyuan.config.export.addTitle ? "checked" : ""}>
        </label>
        <label class="b3-label">
            <div>
                ${window.siyuan.languages.exportTitleImage}
            </div>
            <span class="fn__hr"></span>
            <input id="titleImage" class="b3-switch" type="checkbox" ${localData.titleImage !== false ? "checked" : ""}>
        </label>
        <label id="customTitlePanel" class="b3-label${window.siyuan.config.export.addTitle ? "" : " fn__none"}">
            <div>
                ${window.siyuan.languages.title}
            </div>
            <span class="fn__hr"></span>
            <input aria-label="${window.siyuan.languages.title}" id="customTitle" class="b3-text-field fn__block" placeholder="${window.siyuan.languages.title}">
        </label>
        <label class="b3-label">
            <div>
                ${window.siyuan.languages.mergeSubdocs}
            </div>
            <span class="fn__hr"></span>
            <input id="mergeSubdocs" class="b3-switch" type="checkbox" ${localData.mergeSubdocs ? "checked" : ""}>
        </label>
        <div id="mergeHeadingOptions" class="${localData.mergeSubdocs ? "" : "fn__none"}">
            <label class="b3-label">
                <div>
                    ${window.siyuan.languages.mergeDocHeadingMode}
                </div>
                <span class="fn__hr"></span>
                <select class="b3-select" id="mergeDocHeadingMode">
                    <option value="flat" ${localData.mergeDocHeadingMode === "flat" ? "selected" : ""}>${window.siyuan.languages.mergeDocHeadingFlat}</option>
                    <option value="tree" ${localData.mergeDocHeadingMode === "tree" ? "selected" : ""}>${window.siyuan.languages.mergeDocHeadingTree}</option>
                </select>
            </label>
            <label class="b3-label">
                <div>
                    ${window.siyuan.languages.mergeContentHeadingMode}
                </div>
                <span class="fn__hr"></span>
                <select class="b3-select" id="mergeContentHeadingMode">
                    <option value="preserve" ${localData.mergeContentHeadingMode === "preserve" ? "selected" : ""}>${window.siyuan.languages.mergeContentHeadingPreserve}</option>
                    <option value="demote" ${localData.mergeContentHeadingMode === "demote" ? "selected" : ""}>${window.siyuan.languages.mergeContentHeadingDemote}</option>
                </select>
            </label>
        </div>
        <label class="b3-label">
            <div>
                ${window.siyuan.languages.export27}
            </div>
            <span class="fn__hr"></span>
            <input id="watermark" class="b3-switch" type="checkbox" ${localData.watermark ? "checked" : ""}>
        </label>
        <label class="b3-label">
            <div>
                ${window.siyuan.languages.paged}
            </div>
            <span class="fn__hr"></span>
            <input id="paged" class="b3-switch" type="checkbox" ${localData.paged ? "checked" : ""}>
        </label>
        <div id="headingPageBreakOptions" class="b3-label${localData.paged ? "" : " fn__none"}">
            <div>${window.siyuan.languages.pdfHeadingPageBreaks}</div>
            <div class="ft__smaller ft__on-surface">${window.siyuan.languages.pdfHeadingPageBreaksTip}</div>
            <div class="fn__hr"></div>
            <div id="headingPageBreaks">${headingPageBreakControls(localData.headingPageBreakLevels)}</div>
        </div>
    </div>
    <div class="fn__flex" style="padding: 0 12px">
      <div class="fn__flex-1"></div>
      <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button>
      <div class="fn__space"></div>
      <button disabled class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>
    </div>
</div>
<div id="previewContainer">
    <div style="zoom:${localData.scale || 1}" id="preview">
        <div class="fn__loading" style="left:0;height:100vh"><span class="b3-loading b3-loading--large" aria-hidden="true"></span></div>
    </div>
</div>
${getIconScript(servePath)}
<script src="${servePath}stage/build/export/protyle-method.js?${exportResourceVersion}"></script>
<script src="${servePath}stage/protyle/js/lute/lute.min.js?${Constants.SIYUAN_VERSION}"></script>    
<script>
    const previewElement = document.getElementById('preview');
    const getHeadingPageBreakLevels = () => Array.from(document.querySelectorAll("#headingPageBreaks input:checked"))
        .map(input => Number(input.value));
    const updateHeadingPageBreaks = () => {
        const enabled = document.getElementById("paged").checked;
        document.getElementById("headingPageBreakOptions").classList.toggle("fn__none", !enabled);
        document.querySelectorAll("#headingPageBreaks input").forEach(input => {
            input.disabled = !enabled;
        });
        Protyle.applyExportHeadingPageBreaks(previewElement, getHeadingPageBreakLevels(), enabled);
    };
    document.getElementById("headingPageBreaks").addEventListener("change", updateHeadingPageBreaks);
    document.getElementById("paged").addEventListener("change", updateHeadingPageBreaks);
    updateHeadingPageBreaks();
    const fixBlockWidth = async (printableWidth = false) => {
        const isLandscape = document.querySelector("#landscape").checked;
        let width = 800
        let height = 1131
        switch (document.querySelector("#action #pageSize").value) {
            case "A3":
              width = isLandscape ? 1587.84 : 1122.24
              height = isLandscape ? 1122.24 : 1587.84
              break;
            case "A4":
              width = isLandscape ? 1122.24 : 793.92
              height = isLandscape ? 793.92 : 1122.24
              break;
            case "A5":
              width = isLandscape ? 793.92 : 559.68
              height = isLandscape ? 559.68 : 793.92
              break;
            case "Legal":
              width = isLandscape ? 1344: 816
              height = isLandscape ? 816 : 1344
              break;
            case "Letter":
              width = isLandscape ? 1056 : 816
              height = isLandscape ? 816 : 1056
              break;
            case "Tabloid":
              width = isLandscape ? 1632 : 1056
              height = isLandscape ? 1056 : 1632
              break;
        }
        const scale = parseFloat(document.querySelector("#scale").value);
        if (printableWidth) {
            width -= ((parseFloat(document.querySelector("#marginsLeft").value) || 0) +
                (parseFloat(document.querySelector("#marginsRight").value) || 0)) * 96;
        }
        width = width / scale;
        height = (height -
            (parseFloat(document.querySelector("#marginsTop").value) +
                parseFloat(document.querySelector("#marginsBottom").value)) * 96) / scale;
        previewElement.style.width = width + "px";
        width = width - parseFloat(previewElement.style.paddingLeft) * 96 * 2;
        // 为保持代码块宽度一致,全部都进行宽度设定 https://github.com/siyuan-note/siyuan/issues/7692 
        previewElement.querySelectorAll('.hljs').forEach((item) => {
            // 强制换行 https://ld246.com/article/1679228783553
            item.parentElement.setAttribute("linewrap", "true");
            item.parentElement.style.width = "";
            item.parentElement.style.boxSizing = "border-box";
            item.parentElement.style.width = Math.min(item.parentElement.clientWidth, width) + "px";
            item.removeAttribute('data-render');
        })
        Protyle.highlightRender(previewElement, "${servePath}stage/protyle", document.querySelector("#scale").value);
        previewElement.querySelectorAll('[data-type="NodeMathBlock"]').forEach((item) => {
            // 超级块内不能移除 width https://github.com/siyuan-note/siyuan/issues/14318
            item.removeAttribute('data-render');
        })
        previewElement.querySelectorAll('[data-type="NodeCodeBlock"][data-subtype="mermaid"] svg').forEach((item) => {
            item.style.maxHeight = height + "px";
        })
        await Protyle.mathRender(previewElement, "${servePath}stage/protyle", true);
        previewElement.querySelectorAll("table").forEach(item => {
            if (item.clientWidth > item.parentElement.clientWidth) {
                item.style.zoom = (item.parentElement.clientWidth / item.clientWidth).toFixed(2) - 0.01;
                item.parentElement.style.overflow = "hidden";
            }
        })
        const images = Array.from(previewElement.querySelectorAll(".img img"));
        // 先恢复用户设置的尺寸,再按当前纸张、边距和缩放计算,避免重复调整时只能缩小。
        images.forEach(image => image.removeAttribute("data-export-image-fit"));
        if (document.querySelector("#paged").checked) {
            images.forEach(image => {
                const block = image.closest("[data-node-id]") || image.parentElement;
                const style = getComputedStyle(block);
                const blockSpacing = [style.paddingTop, style.paddingBottom, style.marginTop, style.marginBottom]
                    .reduce((sum, value) => sum + (parseFloat(value) || 0), 0);
                let maxHeight = height;
                // 图片缩窄后说明文字可能增加行数,逐步收紧高度以保留说明、段落间距和行盒的空间。
                while (true) {
                    const extraHeight = Math.max(0, image.parentElement.offsetHeight - image.offsetHeight) +
                        (parseFloat(style.lineHeight) || parseFloat(style.fontSize) * 1.625) + blockSpacing;
                    const nextHeight = Math.max(1, Math.floor(height - extraHeight - 1));
                    if (image.clientHeight <= nextHeight || nextHeight >= maxHeight) {
                        break;
                    }
                    maxHeight = nextHeight;
                    image.style.setProperty("--export-image-max-height", maxHeight + "px");
                    image.setAttribute("data-export-image-fit", "true");
                }
            });
        }
    }
    const setPadding = () => {
        const isLandscape = document.querySelector("#landscape").checked;
        const topElement = document.querySelector("#marginsTop")
        const rightElement = document.querySelector("#marginsRight")
        const bottomElement = document.querySelector("#marginsBottom")
        const leftElement = document.querySelector("#marginsLeft")
        switch (document.querySelector("#marginsType").value) {
            case "default":
                if (isLandscape) {
                    topElement.value = "0.42";
                    rightElement.value = "0.42";
                    bottomElement.value = "0.42";
                    leftElement.value = "0.42";
                } else {
                    topElement.value = "1";
                    rightElement.value = "0.54";
                    bottomElement.value = "1";
                    leftElement.value = "0.54";
                }
                break;
            case "none": // none
                topElement.value = "0";
                rightElement.value = "0";
                bottomElement.value = "0";
                leftElement.value = "0";
                break;
            case "printableArea": // minimal
                if (isLandscape) {
                    topElement.value = ".07";
                    rightElement.value = ".07";
                    bottomElement.value = ".07";
                    leftElement.value = ".07";
                } else {
                    topElement.value = "0.58";
                    rightElement.value = "0.1";
                    bottomElement.value = "0.58";
                    leftElement.value = "0.1";
                }
                break;
        }
        document.getElementById('preview').style.padding = topElement.value + "in " 
                             + rightElement.value + "in "
                             + bottomElement.value + "in "
                             + leftElement.value + "in";
        setTimeout(() => {
            fixBlockWidth();
        }, 300);
    }
    const fetchPost = (url, data, cb) => {
        fetch("${servePathWithoutTrailingSlash}" + url, {
            method: "POST",
            body: JSON.stringify(data)
        }).then((response) => {
            if (!response.ok) {
                cb({ code: -response.status, msg: response.statusText, data: null });
                return;
            }
            return response.json();
        }).then((response) => {
            if (response) {
                cb(response);
            }
        })
    }
    const waitForImages = () => Promise.all(Array.from(previewElement.querySelectorAll("img")).map((image) => {
        image.loading = "eager";
        if (image.complete) {
            return Promise.resolve();
        }
        return new Promise((resolve) => {
            const finish = () => {
                clearTimeout(timeout);
                image.removeEventListener("load", finish);
                image.removeEventListener("error", finish);
                resolve();
            };
            const timeout = setTimeout(finish, 30000);
            image.addEventListener("load", finish, {once: true});
            image.addEventListener("error", finish, {once: true});
        });
    }));
    let previewReady = Promise.resolve();
    let previewRevision = 0;
    const renderPreview = async (data) => {
        previewElement.innerHTML = '<div style="padding:8px 0 0 0" class="protyle-wysiwyg${window.siyuan.config.editor.displayBookmarkIcon ? " protyle-wysiwyg--attr" : ""}">' + data.content + '</div>';
        const wysElement = previewElement.querySelector(".protyle-wysiwyg");
        wysElement.setAttribute("data-doc-type", data.type || "NodeDocument");
        Object.keys(data.attrs).forEach(key => {
            wysElement.setAttribute(key, data.attrs[key]);
        })
        Protyle.setAutoDirection(previewElement, ${!!window.siyuan.config.editor.autoDirection});
        await Protyle.renderExportJSEmbeds(wysElement, {
            disabled: ${window.siyuan.config.system.safeMode || getHostCapabilities().remoteKernel},
            disabledTip: decodeURIComponent(${JSON.stringify(encodeURIComponent(window.siyuan.languages.safeModeJSTip))}),
            rootID: "${id}",
            headingMode: ${window.siyuan.config.editor.headingEmbedMode},
        }, async (url, data) => {
            const response = await fetch("${servePathWithoutTrailingSlash}" + url, {
                method: "POST", body: JSON.stringify(data),
            });
            if (!response.ok) {
                throw new Error(response.statusText);
            }
            return response.json();
        });
        // https://github.com/siyuan-note/siyuan/issues/13669
        wysElement.querySelectorAll('[data-node-id]').forEach((item) => {
            if (item.querySelector(".img")) {
                item.insertAdjacentHTML("beforeend", "<hr style='margin:0;border:0'>");
            }
        })
        Protyle.mermaidRender(wysElement, "${servePath}stage/protyle");
        Protyle.flowchartRender(wysElement, "${servePath}stage/protyle");
        Protyle.graphvizRender(wysElement, "${servePath}stage/protyle");
        Protyle.chartRender(wysElement, "${servePath}stage/protyle");
        Protyle.mindmapRender(wysElement, "${servePath}stage/protyle");
        Protyle.abcRender(wysElement, "${servePath}stage/protyle");
        Protyle.htmlRender(wysElement);
        Protyle.plantumlRender(wysElement, "${servePath}stage/protyle");
        updateHeadingPageBreaks();
        await waitForImages();
    }
    fetchPost("/api/export/exportPreviewHTML", {
        id: "${id}",
        keepJSEmbed: true,
        keepFold: ${localData.keepFold},
        pdf: true,
        excludeTitleImage: ${localData.titleImage === false},
        addTitle: ${window.siyuan.config.export.addTitle},
        customTitle: "",
        merge: ${localData.mergeSubdocs},
        mergeDocHeadingMode: "${localData.mergeDocHeadingMode}",
        mergeContentHeadingMode: "${localData.mergeContentHeadingMode}",
    }, response => {
        if (response.code !== 0) {
            alert(response.msg)
            return;
        }
        document.title = response.data.name
        window.siyuan = {
          config: {
            appearance: { mode: 0, codeBlockThemeDark: "${window.siyuan.config.appearance.codeBlockThemeDark}", codeBlockThemeLight: "${window.siyuan.config.appearance.codeBlockThemeLight}" },
            editor: { 
              allowSVGScriptTip: ${window.siyuan.config.editor.allowSVGScript},
              allowHTMLBLockScript: ${window.siyuan.config.editor.allowHTMLBLockScript},
              fontSize: ${window.siyuan.config.editor.fontSize},
              codeLineWrap: true,
              codeLigatures: ${window.siyuan.config.editor.codeLigatures},
              plantUMLServePath: "${window.siyuan.config.editor.plantUMLServePath}",
              codeSyntaxHighlightLineNum: ${window.siyuan.config.editor.codeSyntaxHighlightLineNum},
              katexMacros: decodeURI(\`${encodeURI(window.siyuan.config.editor.katexMacros)}\`),
            }
          },
          languages: ${getExportLanguages()}
        };
        previewElement.addEventListener("click", (event) => {
            let target = event.target;
            while (target && !target.isEqualNode(previewElement)) {
                if (target.tagName === "A") {
                    const linkAddress = target.getAttribute("href");
                    if (linkAddress.startsWith("#")) {
                        // 导出预览模式点击块引转换后的脚注跳转不正确 https://github.com/siyuan-note/siyuan/issues/5700
                        const hash = linkAddress.substring(1);
                        previewElement.querySelector('[data-node-id="' + hash + '"], [id="' + hash + '"]').scrollIntoView();
                        event.stopPropagation();
                        event.preventDefault();
                        return;
                    }
                } else if (target.classList.contains("protyle-action__copy")) {
                    navigator.clipboard.writeText(target.parentElement.nextElementSibling.textContent.trimEnd().replace(/\u00A0/g, " ").replace(/\u200D\`\`\`/g, "\`\`\`"));
                    event.preventDefault();
                    event.stopPropagation();
                    break;
                }
                target = target.parentElement;
            }
        });
        const actionElement = document.getElementById('action');
        const keepFoldElement = actionElement.querySelector('#keepFold');
        keepFoldElement.addEventListener('change', () => {
            refreshPreview();
        });
        const addTitleElement = actionElement.querySelector('#addTitle');
        const titleImageElement = actionElement.querySelector('#titleImage');
        titleImageElement.addEventListener('change', () => {
            refreshPreview();
        });
        const customTitleElement = actionElement.querySelector('#customTitle');
        const customTitlePanelElement = actionElement.querySelector('#customTitlePanel');
        let titleRefreshTimer;
        let titleComposing = false;
        addTitleElement.addEventListener('change', () => {
            customTitlePanelElement.classList.toggle('fn__none', !addTitleElement.checked);
            refreshPreview();
        });
        const scheduleTitleRefresh = () => {
            window.clearTimeout(titleRefreshTimer);
            titleRefreshTimer = window.setTimeout(refreshPreview, 300);
        };
        customTitleElement.addEventListener('compositionstart', () => {
            titleComposing = true;
            window.clearTimeout(titleRefreshTimer);
        });
        customTitleElement.addEventListener('compositionend', () => {
            titleComposing = false;
            scheduleTitleRefresh();
        });
        customTitleElement.addEventListener('input', () => {
            if (!titleComposing) {
                scheduleTitleRefresh();
            }
        });
        const mergeSubdocsElement = actionElement.querySelector('#mergeSubdocs');
        const mergeHeadingOptionsElement = actionElement.querySelector('#mergeHeadingOptions');
        const mergeDocHeadingModeElement = actionElement.querySelector('#mergeDocHeadingMode');
        const mergeContentHeadingModeElement = actionElement.querySelector('#mergeContentHeadingMode');
        mergeSubdocsElement.addEventListener('change', () => {
            mergeHeadingOptionsElement.classList.toggle('fn__none', !mergeSubdocsElement.checked);
            refreshPreview();
        });
        mergeDocHeadingModeElement.addEventListener('change', () => {
            refreshPreview();
        });
        mergeContentHeadingModeElement.addEventListener('change', () => {
            refreshPreview();
        });
        const removeAssetsElement = actionElement.querySelector("#removeAssets");
        const  watermarkElement = actionElement.querySelector('#watermark');
        const refreshPreview = () => {
            const revision = ++previewRevision;
            actionElement.querySelector('.b3-button--text').disabled = true;
            previewElement.innerHTML = '<div class="fn__loading" style="left:0;height: 100vh"><span class="b3-loading b3-loading--large" aria-hidden="true"></span></div>'
            fetchPost("/api/export/exportPreviewHTML", {
                id: "${id}",
                keepJSEmbed: true,
                keepFold: keepFoldElement.checked,
                pdf: true,
                excludeTitleImage: !titleImageElement.checked,
                addTitle: addTitleElement.checked,
                customTitle: customTitleElement.value,
                merge: mergeSubdocsElement.checked,
                mergeDocHeadingMode: mergeDocHeadingModeElement.value,
                mergeContentHeadingMode: mergeContentHeadingModeElement.value,
            }, response2 => {
                if (revision !== previewRevision) {
                    return;
                }
                if (response2.code !== 0) {
                    alert(response2.msg)
                    return;
                }
                setPadding();
                previewReady = renderPreview(response2.data).then(() => {
                    if (revision !== previewRevision) {
                        return;
                    }
                    reserveEmbeddedAssetSpace(removeAssetsElement.checked);
                    fixBlockWidth();
                    actionElement.querySelector('.b3-button--text').disabled = false;
                });
            })
        };

        actionElement.querySelector("#scale").addEventListener("input", () => {
            const scale = actionElement.querySelector("#scale").value;
            actionElement.querySelector("#scaleTip").innerText = scale;
            previewElement.style.zoom = scale;
            fixBlockWidth();
        })
        actionElement.querySelector("#pageSize").addEventListener('change', () => {
            fixBlockWidth();
        });
        actionElement.querySelector("#marginsType").addEventListener('change', (event) => {
            setPadding();
            if (event.target.value === "custom") {
                event.target.nextElementSibling.classList.remove("fn__none");
            } else {
                event.target.nextElementSibling.classList.add("fn__none");
            }
        });
        actionElement.querySelector("#marginsTop").addEventListener('change', () => {
            setPadding();
        });
        actionElement.querySelector("#marginsRight").addEventListener('change', () => {
            setPadding();
        });
        actionElement.querySelector("#marginsBottom").addEventListener('change', () => {
            setPadding();
        });
        actionElement.querySelector("#marginsLeft").addEventListener('change', () => {
            setPadding();
        });
        actionElement.querySelector("#landscape").addEventListener('change', (e) => {
            setPadding();
        });
        actionElement.querySelector("#paged").addEventListener('change', () => {
            fixBlockWidth();
        });
        actionElement.querySelector('.b3-button--cancel').addEventListener('click', () => {
            const {ipcRenderer}  = require("electron");
            ipcRenderer.send("${Constants.SIYUAN_CMD}", "destroy")
        });
        const buildExportConfig = (unPagedPageSize) => {
            const pageSize = actionElement.querySelector("#pageSize").value;
            // https://www.electronjs.org/docs/latest/api/web-contents#contentsprinttopdfoptions
            // https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF
            return {
                title: "${window.siyuan.languages.export} PDF",
                pdfOptions: {
                    printBackground: true,
                    landscape: actionElement.querySelector("#landscape").checked,
                    marginType: actionElement.querySelector("#marginsType").value,
                    margins: {
                        top: parseFloat(document.querySelector("#marginsTop").value) || 0,
                        bottom: parseFloat(document.querySelector("#marginsBottom").value) || 0,
                        left: parseFloat(document.querySelector("#marginsLeft").value) || 0,
                        right: parseFloat(document.querySelector("#marginsRight").value) || 0,
                    },
                    scale: parseFloat(actionElement.querySelector("#scale").value),
                    pageSize: unPagedPageSize || pageSize,
                },
                pageSize,
                titleImage: titleImageElement.checked,
                keepFold: keepFoldElement.checked,
                addTitle: addTitleElement.checked,
                customTitle: customTitleElement.value,
                mergeSubdocs: mergeSubdocsElement.checked,
                mergeDocHeadingMode: mergeDocHeadingModeElement.value,
                mergeContentHeadingMode: mergeContentHeadingModeElement.value,
                watermark: watermarkElement.checked,
                removeAssets: removeAssetsElement.checked,
                paged: !unPagedPageSize,
                headingPageBreakLevels: getHeadingPageBreakLevels(),
                rootId: "${id}",
                rootTitle: response.data.name,
                parentWindowId: ${currentWindowId},
            };
        };
        const reserveEmbeddedAssetSpace = (enabled) => {
            // 为内嵌附件注解预留空间,避免覆盖后续文本。
            previewElement.querySelectorAll("a[href]").forEach((item) => {
                const url = new URL(item.href);
                const embedded = enabled && url.hostname === "127.0.0.1" && url.pathname.includes("/assets/");
                item.classList.toggle("pdf-embedded-asset", embedded);
                const iconElement = item.querySelector(".pdf-embedded-asset__icon");
                if (embedded && !iconElement) {
                    item.insertAdjacentHTML("beforeend", '<svg aria-hidden="true" class="pdf-embedded-asset__icon"><use xlink:href="#iconPaperclip"></use></svg>');
                } else if (!embedded) {
                    iconElement?.remove();
                }
            });
        };
        removeAssetsElement.addEventListener("change", () => {
            reserveEmbeddedAssetSpace(removeAssetsElement.checked);
        });
        actionElement.querySelector('.b3-button--text').addEventListener('click', async () => {
            await previewReady;
            const {ipcRenderer}  = require("electron");
            const defaultPath = decodeURIComponent(${JSON.stringify(encodeURIComponent(defaultExportPath))});
            const dialogOptions = {
                cmd: "showOpenDialog",
                title: "${window.siyuan.languages.export} PDF",
                buttonLabel: ${JSON.stringify(window.siyuan.languages.save)},
                properties: ["createDirectory", "openDirectory"],
            };
            if (defaultPath) {
                dialogOptions.defaultPath = defaultPath;
            }
            const result = await ipcRenderer.invoke("${Constants.SIYUAN_GET}", dialogOptions);
            if (result.canceled || result.filePaths.length === 0) {
                return;
            }
            reserveEmbeddedAssetSpace(removeAssetsElement.checked);
            await waitForImages();
            const isPaged = actionElement.querySelector("#paged").checked;
            updateHeadingPageBreaks();
            document.body.classList.add("exporting");
            previewElement.style.zoom = "";
            previewElement.style.padding = "6px 0 0 0";
            if (!isPaged) {
                // 按打印可用宽度完成排版后测量,避免预览边距、缩放和列表布局影响长页高度。
                previewElement.style.margin = "0";
                previewElement.style.minHeight = "0";
            }
            await fixBlockWidth(true);
            await document.fonts.ready;
            await waitForImages();
            let exportConfig;
            if (!isPaged) {
                const getPageSizeDimensions = () => {
                    // https://github.com/electron/electron/blob/3df3a6a736b93e0d69fa3b0c403b33f201287780/lib/browser/api/web-contents.ts#L89-L101
                    const pageSizes = {
                        "A3": { width: 11.7, height: 16.54 },
                        "A4": { width: 8.27, height: 11.7 },
                        "A5": { width: 5.83, height: 8.27 },
                        "Legal": { width: 8.5, height: 14 },
                        "Letter": { width: 8.5, height: 11 },
                        "Tabloid": { width: 11, height: 17 },
                    };
                    return pageSizes[actionElement.querySelector("#pageSize").value];
                };
                const dimensions = getPageSizeDimensions();
                const landscape = actionElement.querySelector("#landscape").checked;
                const scale = parseFloat(actionElement.querySelector("#scale").value);
                const margins = (parseFloat(document.querySelector("#marginsTop").value) || 0) +
                    (parseFloat(document.querySelector("#marginsBottom").value) || 0);
                // 纸张高度包含缩放后的正文和打印边距,并预留一个像素以容纳单位换算误差。
                const previewHeight = Math.max((previewElement.scrollHeight * scale + 1) / 96 + margins,
                    landscape ? dimensions.width : dimensions.height);
                exportConfig = buildExportConfig(landscape ? {
                    height: dimensions.height,
                    width: previewHeight,
                } : {
                    width: dimensions.width,
                    height: previewHeight,
                });
            } else {
                exportConfig = buildExportConfig();
            }
            exportConfig.filePaths = result.filePaths;
            actionElement.remove();
            ipcRenderer.send("${Constants.SIYUAN_EXPORT_PDF}", exportConfig);
        });
        setPadding();
        previewReady = renderPreview(response.data).then(() => {
            if (previewRevision !== 0) {
                return;
            }
            reserveEmbeddedAssetSpace(removeAssetsElement.checked);
            fixBlockWidth();
            actionElement.querySelector('.b3-button--text').disabled = false;
        });
        window.addEventListener("keydown", (event) => {
            if (event.key === "Escape") {
                const {ipcRenderer}  = require("electron");
                ipcRenderer.send("${Constants.SIYUAN_CMD}", "destroy")
                event.preventDefault();
            }
        })
    });
</script>
${getSnippetJS()}
</body></html>`;
    fetchPost("/api/export/exportTempContent", {content: html, id}, (response) => {
        if (response.code === 0) {
            ipcRenderer.send(Constants.SIYUAN_EXPORT_NEWWINDOW, response.data.url);
        }
    });
};

const getExportPath = (
    option: IExportOptions,
    removeAssets?: boolean,
    mergeSubdocs?: boolean,
    mergeDocHeadingMode?: string,
    mergeContentHeadingMode?: string,
    confirmed = false,
) => {
    fetchPost("/api/block/getBlockInfo", {
        id: option.id
    }, async (response) => {
        if (response.code === 3) {
            showMessage(response.msg);
            return;
        }
        if (!confirmed && isEncryptedBox(response.data.box)) {
            confirmDialog("⚠️ " + window.siyuan.languages.export, window.siyuan.languages.encryptedExportRiskTip, () => {
                getExportPath(option, removeAssets, mergeSubdocs, mergeDocHeadingMode, mergeContentHeadingMode, true);
            });
            return;
        }
        let exportType = "HTML (SiYuan)";
        switch (option.type) {
            case "htmlmd":
                exportType = "HTML (Markdown)";
                break;
            case "word":
                exportType = "Word .docx";
                break;
            case "pdf":
                exportType = "PDF";
                break;
        }

        const defaultPath = await getAvailableExportPath();
        const result = await ipcRenderer.invoke(Constants.SIYUAN_GET, {
            cmd: "showOpenDialog",
            title: window.siyuan.languages.export + " " + exportType,
            properties: ["createDirectory", "openDirectory"],
            ...(defaultPath ? {defaultPath} : {}),
        });
        if (!result.canceled) {
            setLastExportPath(result.filePaths[0]);
            const msgId = showMessage(window.siyuan.languages.exporting, -1);
            let url = "/api/export/exportHTML";
            if (option.type === "htmlmd") {
                url = "/api/export/exportMdHTML";
            } else if (option.type === "word") {
                url = "/api/export/exportDocx";
            }
            let savePath = result.filePaths[0];
            if (option.type !== "word" && !savePath.endsWith(response.data.rootTitle)) {
                savePath = path.join(savePath, replaceLocalPath(response.data.rootTitle));
            }
            savePath = savePath.trim();
            fetchPost(url, {
                id: option.id,
                pdf: option.type === "pdf",
                removeAssets: removeAssets,
                merge: mergeSubdocs,
                mergeDocHeadingMode,
                mergeContentHeadingMode,
                savePath
            }, exportResponse => {
                if (option.type === "word") {
                    if (exportResponse.code === 1) {
                        hideMessage(msgId);
                        showMessage(exportResponse.msg, 0, "error");
                        return;
                    }
                    afterExport(exportResponse.data.path, msgId);
                } else {
                    onExport(exportResponse, savePath, "", option, msgId);
                }
            });
        }
    });
};
/// #endif

export const onExport = async (data: IWebSocketData, filePath: string, servePath: string, exportOption: IExportOptions, msgId?: string) => {
    let themeName = window.siyuan.config.appearance.themeLight;
    let mode = 0;
    if (["html", "htmlmd"].includes(exportOption.type) && window.siyuan.config.appearance.mode === 1) {
        themeName = window.siyuan.config.appearance.themeDark;
        mode = 1;
    }
    const isDefault = (window.siyuan.config.appearance.mode === 1 && window.siyuan.config.appearance.themeDark === "midnight") || (window.siyuan.config.appearance.mode === 0 && window.siyuan.config.appearance.themeLight === "daylight");
    let themeStyle = "";
    if (!isDefault) {
        themeStyle = `<link rel="stylesheet" type="text/css" id="themeStyle" href="${servePath}appearance/themes/${themeName}/theme.css?${Constants.SIYUAN_VERSION}"/>`;
    }
    const isInMobile = isInMobileApp();
    const mobileHtml = isInMobile ? {
        js: exportOption.type === "pdf" ? "" : `document.body.style.minWidth = "${getScreenWidth()}px";`,
        css: `@page { size: A4; margin: 10mm; background-color: var(--b3-theme-background); }
@media print {
    body { margin: 0; }
    .protyle-wysiwyg { display: block; }
    #preview .img img { max-height: calc(277mm - 32px); object-fit: contain; }
}
.protyle-wysiwyg {padding: 0; margin: 0;}`
    } : {js: "", css: ""};
    const html = `<!DOCTYPE html>
<html lang="${window.siyuan.config.appearance.lang}" data-theme-mode="${isInMobile ? "light" : getThemeMode()}" data-light-theme="${window.siyuan.config.appearance.themeLight}" data-dark-theme="${window.siyuan.config.appearance.themeDark}">
<head>
    <base href="${servePath}">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
    <meta name="mobile-web-app-capable" content="yes"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="stylesheet" type="text/css" id="baseStyle" href="${servePath}stage/build/export/base.css?v=${Constants.SIYUAN_VERSION}"/>
    <link rel="stylesheet" type="text/css" id="themeDefaultStyle" href="${servePath}appearance/themes/${themeName}/theme.css?v=${Constants.SIYUAN_VERSION}"/>
    <script src="${servePath}stage/protyle/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}"></script>
    ${themeStyle}
    <title>${data.data.name}</title>
    <!-- Exported by SiYuan v${Constants.SIYUAN_VERSION} -->
    <style>
        body {font-family: var(--b3-font-family);background-color: var(--b3-theme-background);color: var(--b3-theme-on-background)}
        ${await setInlineStyle(false, servePath, data.data.content)}
        ${await getPluginStyle()}
        ${mobileHtml.css}
    </style>
    ${getSnippetCSS()}
</head>
<body>
<div class="${["htmlmd", "word"].includes(exportOption.type) ? "b3-typography" : "protyle-wysiwyg" + (window.siyuan.config.editor.displayBookmarkIcon ? " protyle-wysiwyg--attr" : "")}" 
style="max-width: 800px;margin: 0 auto;" id="preview">${data.data.content}</div>
${getIconScript(servePath)}
<script src="${servePath}stage/build/export/protyle-method.js?v=${Constants.SIYUAN_VERSION}"></script>
<script src="${servePath}stage/protyle/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}"></script>  
<script>
    ${mobileHtml.js}
    window.siyuan = {
      config: {
        appearance: { mode: ${mode}, codeBlockThemeDark: "${window.siyuan.config.appearance.codeBlockThemeDark}", codeBlockThemeLight: "${window.siyuan.config.appearance.codeBlockThemeLight}" },
        editor: { 
          codeLineWrap: true,
          fontSize: ${window.siyuan.config.editor.fontSize},
          codeLigatures: ${window.siyuan.config.editor.codeLigatures},
          plantUMLServePath: "${window.siyuan.config.editor.plantUMLServePath}",
          codeSyntaxHighlightLineNum: ${window.siyuan.config.editor.codeSyntaxHighlightLineNum},
          katexMacros: decodeURI(\`${encodeURI(window.siyuan.config.editor.katexMacros)}\`),
        }
      },
      languages: ${getExportLanguages()}
    };
    const previewElement = document.getElementById('preview');
    Protyle.highlightRender(previewElement, "stage/protyle");
    Protyle.setAutoDirection(previewElement, ${!!window.siyuan.config.editor.autoDirection});
    Protyle.mathRender(previewElement, "stage/protyle", ${exportOption.type === "pdf"});
    Protyle.mermaidRender(previewElement, "stage/protyle");
    Protyle.flowchartRender(previewElement, "stage/protyle");
    Protyle.graphvizRender(previewElement, "stage/protyle");
    Protyle.chartRender(previewElement, "stage/protyle");
    Protyle.mindmapRender(previewElement, "stage/protyle");
    Protyle.abcRender(previewElement, "stage/protyle");
    Protyle.htmlRender(previewElement);
    if (${exportOption.type !== "pdf"}) {
        Protyle.tabsRender(previewElement);
    }
    Protyle.plantumlRender(previewElement, "stage/protyle");
    ${exportOption.type === "pdf" ? `Protyle.applyExportHeadingPageBreaks(previewElement, ${JSON.stringify(
        normalizeHeadingPageBreakLevels(window.siyuan.storage[Constants.LOCAL_EXPORTPDF].headingPageBreakLevels))});` : ""}
    document.querySelectorAll(".protyle-action__copy").forEach((item) => {
      item.addEventListener("click", (event) => {
            navigator.clipboard.writeText(item.parentElement.nextElementSibling.textContent.trimEnd().replace(/\u00A0/g, " ").replace(/\u200D\`\`\`/g, "\`\`\`"));
            event.preventDefault();
            event.stopPropagation();
      })
    });
</script>
${getSnippetJS()}</body></html>`;
    // 移动端导出 pdf、浏览器导出 HTML
    if (typeof filePath === "undefined") {
        return html;
    }
    /// #if !BROWSER
    const htmlPath = path.join(filePath, "index.html");
    fs.writeFileSync(htmlPath, html);
    afterExport(htmlPath, msgId);
    /// #endif
};