From d8afd95c1b96eda29fa5cba7449e5f70c08484cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E4=B8=80=E4=B8=81?= <1769123563@qq.com> Date: Wed, 19 Nov 2025 19:13:03 +0800 Subject: [PATCH] Optimize the Binding of the Catalog --- ReportEngine/core/stitcher.py | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/ReportEngine/core/stitcher.py b/ReportEngine/core/stitcher.py index 463a093..cf75212 100644 --- a/ReportEngine/core/stitcher.py +++ b/ReportEngine/core/stitcher.py @@ -45,10 +45,20 @@ class DocumentComposer: 返回: dict: 满足渲染器需求的Document IR。 """ + # 构建从chapterId到toc anchor的映射 + toc_anchor_map = self._build_toc_anchor_map(metadata) + ordered = sorted(chapters, key=lambda c: c.get("order", 0)) for idx, chapter in enumerate(ordered, start=1): chapter.setdefault("chapterId", f"S{idx}") - anchor = chapter.get("anchor") or f"section-{idx}" + + # 优先级:1. 目录配置的anchor 2. 章节自带的anchor 3. 默认anchor + chapter_id = chapter.get("chapterId") + anchor = ( + toc_anchor_map.get(chapter_id) or + chapter.get("anchor") or + f"section-{idx}" + ) chapter["anchor"] = self._ensure_unique_anchor(anchor) chapter.setdefault("order", idx * 10) if chapter.get("errorPlaceholder"): @@ -78,6 +88,29 @@ class DocumentComposer: self._seen_anchors.add(anchor) return anchor + def _build_toc_anchor_map(self, metadata: Dict[str, object]) -> Dict[str, str]: + """ + 从metadata.toc.customEntries构建chapterId到anchor的映射。 + + 参数: + metadata: 文档元信息。 + + 返回: + dict: chapterId -> anchor 的映射。 + """ + toc_config = metadata.get("toc") or {} + custom_entries = toc_config.get("customEntries") or [] + anchor_map = {} + + for entry in custom_entries: + if isinstance(entry, dict): + chapter_id = entry.get("chapterId") + anchor = entry.get("anchor") + if chapter_id and anchor: + anchor_map[chapter_id] = anchor + + return anchor_map + def _ensure_heading_block(self, chapter: Dict[str, object]) -> None: """保证占位章节仍然拥有可用于目录的heading block。""" blocks = chapter.get("blocks")