Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat(webui): add responsive outline navigation to result previews

myhloli1e37e544400f
diff --git a/mineru/kit/gradio/artifacts.py b/mineru/kit/gradio/artifacts.py
index 25932c7f..2ebe16be 100644
--- a/mineru/kit/gradio/artifacts.py
+++ b/mineru/kit/gradio/artifacts.py
@@ -9,6 +9,7 @@ import shutil
import time
import uuid
import zipfile
+from copy import deepcopy
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass, field
@@ -297,7 +298,7 @@ def render_html_preview(artifacts: RunArtifacts, *, public_base_url: str) -> str
value = _render_html(artifacts, public_base_url=public_base_url)
# srcdoc 默认继承外层页面的基准地址,显式指定自身才能让章节锚点在预览内跳转。
value = value.replace("<head>", '<head>\n<base href="about:srcdoc">', 1)
- value = _prepare_preview_links(value)
+ value = _prepare_preview_links(value, include_outline=True)
return (
'<iframe class="mineru-rendered-html-frame" title="Markdown preview" '
'sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox" '
@@ -342,8 +343,8 @@ def _add_trace_preview(document: str, artifacts: RunArtifacts, *, public_base_ur
return document.replace("</body>", f"<script>({script})({config});</script></body>", 1)
-def _prepare_preview_links(document: str) -> str:
- """仅为预览中的网页外链指定新标签页,保留内部锚点及邮件、电话等链接行为。"""
+def _prepare_preview_links(document: str, *, include_outline: bool = False) -> str:
+ """为预览中的网页外链指定新标签页,并按需复用当前 DOM 准备目录。"""
soup = BeautifulSoup(document, "html.parser")
for link in soup.find_all("a", href=True):
try:
@@ -354,9 +355,49 @@ def _prepare_preview_links(document: str) -> str:
continue
link["target"] = "_blank"
link["rel"] = list(dict.fromkeys([*link.get("rel", []), "noopener", "noreferrer"]))
+ if include_outline:
+ _add_outline_preview(soup)
return str(soup)
+def _add_outline_preview(soup: BeautifulSoup) -> None:
+ """复用预览 DOM 准备唯一标题锚点和纯文本标签,并注入当前 iframe 的目录资源。"""
+ from .i18n import MESSAGES
+
+ if soup.head is None or soup.body is None:
+ return
+ used_ids = {str(node["id"]) for node in soup.find_all(id=True)}
+ count = 0
+ for heading in soup.select("article.docvortex-document .docvortex-heading"):
+ if heading.name not in {"h1", "h2", "h3", "h4", "h5", "h6"}:
+ continue
+ label_node = deepcopy(heading)
+ for formula in label_node.select("[data-docvortex-latex]"):
+ formula.replace_with(str(formula["data-docvortex-latex"]))
+ label = " ".join(label_node.get_text().split())
+ if not label:
+ continue
+ count += 1
+ if not heading.get("id"):
+ identifier = f"mineru-outline-{count}"
+ while identifier in used_ids:
+ identifier += "-toc"
+ heading["id"] = identifier
+ used_ids.add(identifier)
+ heading["data-mineru-outline-label"] = label
+ if not count:
+ return
+ resources = Path(__file__).resolve().parents[2] / "resources"
+ style = soup.new_tag("style", attrs={"data-mineru-outline": ""})
+ style.string = (resources / "gradio_outline.css").read_text(encoding="utf-8")
+ soup.head.append(style)
+ labels = {key: MESSAGES[f"outline_{key}"] for key in ("title", "expand", "collapse")}
+ config = json.dumps(labels, ensure_ascii=True).replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
+ script = soup.new_tag("script", attrs={"data-mineru-outline": ""})
+ script.string = f"({(resources / 'gradio_outline.js').read_text(encoding='utf-8')})({config});"
+ soup.body.append(script)
+
+
def _render_html(artifacts: RunArtifacts, *, public_base_url: str, include_source_map: bool = False) -> str:
"""把已物化语义树渲染为使用当前 Gradio 静态图片地址的独立 HTML。"""
if urlsplit(public_base_url).scheme not in {"http", "https"} or not urlsplit(public_base_url).netloc:
diff --git a/mineru/kit/gradio/i18n.py b/mineru/kit/gradio/i18n.py
index cc518406..d6ae5c8e 100644
--- a/mineru/kit/gradio/i18n.py
+++ b/mineru/kit/gradio/i18n.py
@@ -94,6 +94,9 @@ MESSAGES: dict[str, tuple[str, str]] = {
"unsupported_preview": ("No source preview for this format", "该格式暂无源文档预览"),
"result_ready": ("Results are ready", "结果已生成"),
"markdown": ("Markdown", "Markdown"),
+ "outline_title": ("Contents", "目录"),
+ "outline_expand": ("Expand section", "展开章节"),
+ "outline_collapse": ("Collapse section", "收起章节"),
"json_view": ("JSON", "JSON"),
"download_results": ("Download results", "下载结果"),
"examples": ("Examples", "示例"),
diff --git a/mineru/resources/gradio_outline.css b/mineru/resources/gradio_outline.css
new file mode 100644
index 00000000..a77640f2
--- /dev/null
+++ b/mineru/resources/gradio_outline.css
@@ -0,0 +1,52 @@
+.mineru-outline-enabled {
+ --mineru-preview-offset: 52px;
+ --mineru-outline-toolbar-height: 40px;
+ padding-top: var(--mineru-outline-toolbar-height);
+ box-sizing: border-box;
+}
+.mineru-outline-enabled > .docvortex-document { min-height: calc(100vh - 40px); }
+.mineru-outline-enabled .docvortex-heading { scroll-margin-top: var(--mineru-preview-offset); }
+.mineru-outline-toolbar, .mineru-outline-panel, .mineru-outline-backdrop {
+ box-sizing: border-box;
+ font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+}
+.mineru-outline-toolbar {
+ position: fixed; inset: 0 0 auto; height: 40px; z-index: 220;
+ display: flex; align-items: center; padding: 0 12px;
+ background: #fff; border-bottom: 1px solid #e5e7eb;
+}
+.mineru-outline-toggle, .mineru-outline-branch {
+ display: inline-flex; align-items: center; justify-content: center;
+ color: #374151; background: transparent; border: 0; border-radius: 4px; cursor: pointer;
+}
+.mineru-outline-toggle { gap: 8px; padding: 5px 8px; font: inherit; }
+.mineru-outline-toggle::before { content: "☰"; font-size: 16px; }
+.mineru-outline-panel {
+ position: fixed; top: 40px; bottom: 0; left: 0; z-index: 210;
+ width: min(320px, calc(100% - 32px)); padding: 12px 8px;
+ overflow: auto; overscroll-behavior: contain; background: #fff;
+ border-right: 1px solid #e5e7eb; box-shadow: 4px 0 16px #00000012;
+}
+.mineru-outline-panel ul { margin: 0; padding: 0 0 0 14px; list-style: none; }
+.mineru-outline-panel > ul { padding: 0; }
+.mineru-outline-row { display: flex; align-items: flex-start; gap: 2px; margin: 2px 0; }
+.mineru-outline-branch { width: 24px; min-height: 30px; flex: 0 0 24px; }
+.mineru-outline-branch::before { content: "›"; font-size: 20px; line-height: 1; }
+.mineru-outline-branch[aria-expanded="true"]::before { transform: rotate(90deg); }
+.mineru-outline-link {
+ display: block; flex: 1; min-width: 0; padding: 5px 7px; border-radius: 4px;
+ color: #4b5563; text-decoration: none; overflow-wrap: anywhere;
+}
+.mineru-outline-row > .mineru-outline-link:first-child { margin-left: 26px; }
+.mineru-outline-link[aria-current] { color: #c2410c; background: #fff0e5; font-weight: 600; }
+.mineru-outline-link:hover, .mineru-outline-toggle:hover, .mineru-outline-branch:hover { background: #f3f4f6; }
+.mineru-outline-panel :focus-visible, .mineru-outline-toggle:focus-visible {
+ outline: 2px solid #f97316; outline-offset: 1px;
+}
+.mineru-outline-backdrop { position: fixed; inset: 40px 0 0; z-index: 200; background: #00000020; }
+.mineru-outline-panel [hidden], .mineru-outline-panel[hidden], .mineru-outline-backdrop[hidden] { display: none; }
+@media (min-width: 900px) {
+ .mineru-outline-enabled[data-outline-open="true"] { padding-left: 224px; }
+ .mineru-outline-panel { width: 224px; box-shadow: none; }
+ .mineru-outline-backdrop { display: none; }
+}
diff --git a/mineru/resources/gradio_outline.js b/mineru/resources/gradio_outline.js
new file mode 100644
index 00000000..ffadaf0b
--- /dev/null
+++ b/mineru/resources/gradio_outline.js
@@ -0,0 +1,185 @@
+// 目录只管理当前结果 iframe 的正文、焦点与滚动位置。
+(labels) => {
+ const article = document.querySelector("article.docvortex-document");
+ const headings = [...article.querySelectorAll("[data-mineru-outline-label]")];
+ if (!headings.length) return;
+ const language = navigator.languages?.[0] || navigator.language || "";
+ const locale = /^zh(?:-|$)/i.test(language) ? 1 : 0;
+ const wide = window.matchMedia("(min-width: 900px)");
+ const controller = new AbortController();
+ const { signal } = controller;
+ let active = null;
+ let target = null;
+ let positions = [];
+ let frame = 0;
+ let layoutDirty = true;
+ let disposed = false;
+
+ // 元素均由自有代码创建,文档标题始终按纯文本写入。
+ const create = (tag, className) => {
+ const element = document.createElement(tag);
+ element.className = className;
+ return element;
+ };
+ const toolbar = create("div", "mineru-outline-toolbar");
+ const toggle = create("button", "mineru-outline-toggle");
+ toggle.type = "button";
+ toggle.textContent = labels.title[locale];
+ toggle.setAttribute("aria-label", labels.title[locale]);
+ const panel = create("nav", "mineru-outline-panel");
+ // 控件 id 同样避让源文档书签。
+ let panelId = "mineru-outline-panel";
+ while (document.getElementById(panelId)) panelId += "-toc";
+ panel.id = panelId;
+ panel.setAttribute("aria-label", labels.title[locale]);
+ toggle.setAttribute("aria-controls", panelId);
+ const backdrop = create("div", "mineru-outline-backdrop");
+ backdrop.setAttribute("aria-hidden", "true");
+ toolbar.append(toggle);
+ document.body.append(toolbar, backdrop, panel);
+ document.body.classList.add("mineru-outline-enabled");
+ const root = document.createElement("ul");
+ panel.append(root);
+ const stack = [];
+ const entries = [];
+
+ // 初始仅显示两层树节点;层级跳跃直接归属最近的较低级标题。
+ for (const heading of headings) {
+ const level = Number(heading.tagName.slice(1));
+ while (stack.length && stack.at(-1).level >= level) stack.pop();
+ const parent = stack.at(-1) || null;
+ const item = document.createElement("li");
+ const row = create("div", "mineru-outline-row");
+ const link = create("a", "mineru-outline-link");
+ link.href = `#${encodeURIComponent(heading.id)}`;
+ link.textContent = heading.dataset.mineruOutlineLabel;
+ const children = document.createElement("ul");
+ const entry = { heading, level, parent, item, row, link, children, branch: null, depth: stack.length };
+ row.append(link);
+ item.append(row, children);
+ (parent?.children || root).append(item);
+ children.hidden = entry.depth >= 1;
+ entries.push(entry);
+ stack.push(entry);
+ }
+
+ // 折叠开关只影响所属子树,章节链接单独负责导航。
+ const expand = (entry, open) => {
+ entry.children.hidden = !open;
+ entry.branch.setAttribute("aria-expanded", String(open));
+ entry.branch.setAttribute("aria-label", labels[open ? "collapse" : "expand"][locale]);
+ };
+ for (const entry of entries) {
+ if (!entry.children.children.length) {
+ entry.children.remove();
+ continue;
+ }
+ const branch = create("button", "mineru-outline-branch");
+ branch.type = "button";
+ entry.branch = branch;
+ entry.row.prepend(branch);
+ expand(entry, !entry.children.hidden);
+ branch.addEventListener("click", () => expand(entry, entry.children.hidden), { signal });
+ }
+
+ // 仅调整目录自己的滚动条,避免 scrollIntoView 带动外层 Gradio。
+ const revealActive = () => {
+ if (!active || panel.hidden) return;
+ const rect = active.link.getBoundingClientRect();
+ const bounds = panel.getBoundingClientRect();
+ if (rect.top < bounds.top + 12) panel.scrollTop += rect.top - bounds.top - 12;
+ else if (rect.bottom > bounds.bottom - 12) panel.scrollTop += rect.bottom - bounds.bottom + 12;
+ };
+ // 当前章节变化后展开祖先,用户仍可折叠其他章节。
+ const markActive = (entry) => {
+ if (active === entry) return;
+ active?.link.removeAttribute("aria-current");
+ active = entry;
+ active.link.setAttribute("aria-current", "location");
+ for (let ancestor = entry.parent; ancestor; ancestor = ancestor.parent) expand(ancestor, true);
+ revealActive();
+ };
+ // 缓存文档坐标后用二分查找定位,长章节沿用其起始标题。
+ const update = () => {
+ frame = 0;
+ if (layoutDirty) {
+ positions = entries.map((entry) => entry.heading.getBoundingClientRect().top + window.scrollY);
+ layoutDirty = false;
+ if (target) window.scrollTo({ top: positions[entries.indexOf(target)] - 52, behavior: "instant" });
+ }
+ const top = window.scrollY + 54;
+ let start = 0;
+ let end = positions.length;
+ while (start < end) {
+ const middle = (start + end) >>> 1;
+ if (positions[middle] <= top) start = middle + 1;
+ else end = middle;
+ }
+ let index = Math.max(0, start - 1);
+ if (window.scrollY > 0 && window.scrollY + window.innerHeight >= document.documentElement.scrollHeight - 2) {
+ index = entries.length - 1;
+ }
+ markActive(entries[index]);
+ };
+ // 多个布局和滚动通知合并到一个动画帧,卸载后拒绝新任务。
+ const schedule = (recalculate = false) => {
+ if (disposed) return;
+ layoutDirty ||= recalculate;
+ if (!frame) frame = requestAnimationFrame(update);
+ };
+ // 展开模式由 iframe 自身宽度决定,工具条开关保留到下次模式切换。
+ const setOpen = (open) => {
+ panel.hidden = !open;
+ backdrop.hidden = !open || wide.matches;
+ toggle.setAttribute("aria-expanded", String(open));
+ document.body.dataset.outlineOpen = String(open);
+ schedule(true);
+ revealActive();
+ };
+ // 导航只滚动本窗口,并通知溯源脚本停止此前定位的布局校正。
+ const navigate = (event, entry) => {
+ event.preventDefault();
+ window.dispatchEvent(new CustomEvent("mineru-preview-navigate", { detail: "outline" }));
+ target = entry;
+ for (let ancestor = entry.heading.parentElement; ancestor; ancestor = ancestor.parentElement) {
+ if (ancestor.tagName === "DETAILS") ancestor.open = true;
+ }
+ if (!wide.matches) setOpen(false);
+ entry.heading.tabIndex = -1;
+ entry.heading.focus({ preventScroll: true });
+ schedule(true);
+ };
+ for (const entry of entries) {
+ entry.link.addEventListener("click", (event) => navigate(event, entry), { signal });
+ }
+ toggle.addEventListener("click", () => setOpen(panel.hidden), { signal });
+ backdrop.addEventListener("click", () => setOpen(false), { signal });
+ window.addEventListener("keydown", (event) => {
+ if (event.key === "Escape" && !panel.hidden) {
+ setOpen(false);
+ toggle.focus({ preventScroll: true });
+ }
+ }, { signal });
+ // 用户再次交互即接管滚动,防止异步资源把阅读位置拉回。
+ const releaseTarget = () => { target = null; };
+ for (const name of ["wheel", "touchstart", "pointerdown", "keydown"]) {
+ window.addEventListener(name, releaseTarget, { passive: true, signal });
+ }
+ window.addEventListener("mineru-preview-navigate", releaseTarget, { signal });
+ window.addEventListener("scroll", () => schedule(), { passive: true, signal });
+ window.addEventListener("resize", () => schedule(true), { signal });
+ document.addEventListener("load", () => schedule(true), { capture: true, signal });
+ document.addEventListener("toggle", () => schedule(true), { capture: true, signal });
+ wide.addEventListener("change", () => setOpen(wide.matches), { signal });
+ const observer = new ResizeObserver(() => schedule(true));
+ observer.observe(article);
+ document.fonts.ready.then(() => schedule(true));
+ // pagehide 显式释放观察器、事件和待执行动画帧。
+ window.addEventListener("pagehide", () => {
+ disposed = true;
+ observer.disconnect();
+ controller.abort();
+ cancelAnimationFrame(frame);
+ }, { once: true });
+ setOpen(wide.matches);
+}
diff --git a/mineru/resources/gradio_trace_html.js b/mineru/resources/gradio_trace_html.js
index e3c51c2f..da57bb17 100644
--- a/mineru/resources/gradio_trace_html.js
+++ b/mineru/resources/gradio_trace_html.js
@@ -34,13 +34,15 @@
const align = () => {
if (!selected || !alignOnResize) return;
const rect = selected.getBoundingClientRect();
+ const offset = parseFloat(getComputedStyle(document.body).getPropertyValue("--mineru-preview-offset")) || 24;
window.scrollTo({
- top: scrollY + rect.top - Math.max(24, (innerHeight - Math.min(rect.height, innerHeight - 48)) / 2)
+ top: scrollY + rect.top - Math.max(offset, (innerHeight - Math.min(rect.height, innerHeight - 48)) / 2)
});
positionNavigation();
};
// 一个目标对应多个原文页时,用去重后的原文页号切换来源。
const select = (id, pageIdx, scroll) => {
+ if (scroll) window.dispatchEvent(new CustomEvent("mineru-preview-navigate", { detail: "trace" }));
selected?.removeAttribute("data-mineru-selected");
selected = nodes.get(id);
if (!selected) return;
@@ -103,6 +105,8 @@
);
}
window.addEventListener("scroll", positionNavigation, { passive: true });
+ // 目录接管正文导航时,结束旧来源块的自动对齐。
+ window.addEventListener("mineru-preview-navigate", () => { alignOnResize = false; });
const observer = new ResizeObserver(() => {
cancelAnimationFrame(resizeFrame);
resizeFrame = requestAnimationFrame(align);
diff --git a/tests/browser/gradio_outline_checks.js b/tests/browser/gradio_outline_checks.js
new file mode 100644
index 00000000..449eae7d
--- /dev/null
+++ b/tests/browser/gradio_outline_checks.js
@@ -0,0 +1,82 @@
+// 使用 playwright-cli run-code --filename 执行,页面须已通过 WebUI 转换带多个章节的文档。
+async (page) => {
+ // 在正常转换完成的 iframe 上执行真实浏览器交互和布局回归。
+ const check = (condition, message) => {
+ if (!condition) throw new Error(message);
+ };
+ const frameElement = page.locator('iframe.mineru-rendered-html-frame');
+ const frame = await (await frameElement.elementHandle()).contentFrame();
+ const headings = frame.locator('[data-mineru-outline-label]');
+ const count = await headings.count();
+ check(count > 1, 'need multiple real parsed headings');
+ const toggle = frame.locator('.mineru-outline-toggle');
+ const pdf = page.frameLocator('iframe.mineru-pdf-frame').locator('input[type=number]').first();
+ const pdfPage = await pdf.count() ? await pdf.inputValue() : null;
+ // 按稳定标签读取实际标题坐标,覆盖中英文及格式化标题。
+ const headingTop = (nodes, label) =>
+ nodes.find(node => node.dataset.mineruOutlineLabel === label).getBoundingClientRect().top;
+ const results = [];
+ for (const width of [360, 600, 1000, 600]) {
+ await frameElement.evaluate((node, size) => {
+ node.style.width = `${size}px`;
+ node.style.maxWidth = 'none';
+ }, width);
+ await frame.waitForFunction((size) => innerWidth === size, width);
+ await page.waitForTimeout(150);
+ const initial = await toggle.getAttribute('aria-expanded');
+ check(initial === String(width >= 900), `default width=${width} actual=${initial}`);
+ if (initial === 'false') await toggle.click();
+ const branch = frame.locator('.mineru-outline-branch:visible').first();
+ if (await branch.count()) {
+ const expanded = await branch.getAttribute('aria-expanded');
+ await branch.press('Space');
+ check(await branch.getAttribute('aria-expanded') !== expanded, 'keyboard collapse');
+ await branch.press('Space');
+ }
+ const visibleLinks = frame.locator('.mineru-outline-link:visible');
+ const link = visibleLinks.nth(Math.min(2, await visibleLinks.count() - 1));
+ const label = await link.textContent();
+ await link.click();
+ await page.waitForTimeout(150);
+ const position = await headings.evaluateAll(headingTop, label);
+ check(Math.abs(position - 52) < 3, `heading offset ${position} at ${width}`);
+ check(await frame.locator('.mineru-outline-link[aria-current]').textContent() === label, 'active heading mismatch');
+ check(await toggle.getAttribute('aria-expanded') === String(width >= 900), 'close after navigation');
+ // 模拟图片或公式占位变高,验证显式跳转的布局校正。
+ await frame.evaluate(() => {
+ const spacer = document.createElement('div');
+ spacer.dataset.outlineTest = '';
+ spacer.style.height = '143px';
+ document.querySelector('article').prepend(spacer);
+ });
+ await page.waitForTimeout(150);
+ const shifted = await headings.evaluateAll(headingTop, label);
+ check(Math.abs(shifted - 52) < 3, `async layout offset ${shifted}`);
+ if (width < 900) {
+ await toggle.click();
+ await toggle.press('Escape');
+ check(await toggle.getAttribute('aria-expanded') === 'false', 'Escape closes');
+ await toggle.click();
+ // 避开 WebKit 的原生滚动条,点击真实可见的遮罩区域。
+ await frame.locator('.mineru-outline-backdrop').click({ position: { x: width - 24, y: 150 } });
+ check(await toggle.getAttribute('aria-expanded') === 'false', 'outside click closes');
+ }
+ results.push({ width, count, label, position, shifted });
+ }
+ if (pdfPage !== null) check(await pdf.inputValue() === pdfPage, 'TOC moved PDF');
+ await frame.evaluate(() => {
+ dispatchEvent(new WheelEvent('wheel'));
+ scrollTo(0, document.documentElement.scrollHeight);
+ });
+ await page.waitForTimeout(150);
+ const lastLabel = await headings.last().getAttribute('data-mineru-outline-label');
+ check(await frame.locator('.mineru-outline-link[aria-current]').textContent() === lastLabel, 'last chapter highlight');
+ await frame.evaluate(() => {
+ document.querySelectorAll('[data-outline-test]').forEach(node => node.remove());
+ });
+ await frameElement.evaluate(node => {
+ node.style.width = '';
+ node.style.maxWidth = '';
+ });
+ return results;
+}
diff --git a/tests/unittest/test_kit_gradio_html.py b/tests/unittest/test_kit_gradio_html.py
index 7801821d..06f6ff76 100644
--- a/tests/unittest/test_kit_gradio_html.py
+++ b/tests/unittest/test_kit_gradio_html.py
@@ -230,6 +230,13 @@ def test_epub_preview_anchors_stay_in_srcdoc_without_changing_download(tmp_path:
assert [link["href"] for link in preview.find_all("a", href=True)] == [
link["href"] for link in download.find_all("a", href=True)
]
+ # 目录只扩展预览副本,移除其专属数据后继续严格比较原始正文。
+ for node in preview.select("[data-mineru-outline]"):
+ node.decompose()
+ for heading in preview.select("[data-mineru-outline-label]"):
+ del heading["data-mineru-outline-label"]
+ if download.find(id=heading.get("id")) is None:
+ del heading["id"]
assert preview.body == download.body
assert preview.find("script", id="MathJax-script")["src"].startswith("https://")
assert preview.find_all("img")
diff --git a/tests/unittest/test_kit_gradio_outline.py b/tests/unittest/test_kit_gradio_outline.py
new file mode 100644
index 00000000..088527d6
--- /dev/null
+++ b/tests/unittest/test_kit_gradio_outline.py
@@ -0,0 +1,38 @@
+"""目录预览的书签、公式标签和注入边界回归。"""
+
+from bs4 import BeautifulSoup
+
+from mineru.kit.gradio.artifacts import _prepare_preview_links
+
+
+def test_outline_preserves_bookmarks_and_prepares_unique_plain_labels() -> None:
+ """真实 HTML 准备入口保留书签,避让全页 ID,并在 MathJax 执行前固定纯文本标签。"""
+ document = """<html><head></head><body>
+ <div id="mineru-outline-1"></div><div id="mineru-outline-1-toc"></div>
+ <h1>页面控件标题</h1><article class="docvortex-document">
+ <h2 class="docvortex-heading">中文 <strong>章节</strong></h2>
+ <h4 class="docvortex-heading">中文 章节</h4>
+ <h2 class="docvortex-heading" id="已有书签">公式 <span data-docvortex-latex="x^2">\\(x^2\\)</span></h2>
+ <h3 class="docvortex-heading"> </h3>
+ <a href="#已有书签">跳转</a><a href="https://example.test">外链</a>
+ </article></body></html>"""
+ soup = BeautifulSoup(_prepare_preview_links(document, include_outline=True), "html.parser")
+ headings = soup.select("[data-mineru-outline-label]")
+ assert [node["id"] for node in headings] == ["mineru-outline-1-toc-toc", "mineru-outline-2", "已有书签"]
+ assert [node["data-mineru-outline-label"] for node in headings] == ["中文 章节", "中文 章节", "公式 x^2"]
+ assert soup.find("a", string="跳转")["href"] == "#已有书签"
+ assert soup.find("a", string="外链")["target"] == "_blank"
+ assert len(soup.select("script[data-mineru-outline]")) == 1
+ assert len(soup.select("style[data-mineru-outline]")) == 1
+ assert not soup.h1.has_attr("id")
+ assert not soup.h3.has_attr("id")
+ assert "data-mineru-outline" not in _prepare_preview_links(document)
+
+
+def test_empty_outline_has_no_controls_or_resources() -> None:
+ """无标题或空标题的结果继续提供完整正文,且不注入目录界面。"""
+ for body in ("<p>正文</p>", '<h2 class="docvortex-heading"> </h2>'):
+ document = f'<html><head></head><body><article class="docvortex-document">{body}</article></body></html>'
+ soup = BeautifulSoup(_prepare_preview_links(document, include_outline=True), "html.parser")
+ assert not soup.select("[data-mineru-outline], [data-mineru-outline-label]")
+ assert soup.article is not None