fix: strip images from toc labels (#749)

Signed-off-by: Timothée Mazzucotelli <dev@pawamoy.fr>
This commit is contained in:
Timothée Mazzucotelli
2026-06-13 10:24:19 +00:00
committed by GitHub
parent 0f11c7fe99
commit e6b55fe6c6
3 changed files with 58 additions and 1 deletions
+38
View File
@@ -104,3 +104,41 @@ class TestTocCleanup:
# The child heading must preserve the abbreviation text.
child = result["toc"][0]["children"][0]
assert child["content"] == "Using CSS"
def test_images_stripped_from_toc_content(self) -> None:
"""Images defined in the page must not appear as <img> in TOC."""
result = render(
content="# ![icon](../../images/system-32.png) System\n",
path="index.md",
url="/",
)
# Sanity-check: the rendered page body must contain <img>.
assert "<img" in result["content"]
# The TOC must contain exactly one top-level entry.
assert len(result["toc"]) == 1
heading = result["toc"][0]
# The TOC content must be plain text no <img> tags.
assert "<img" not in heading["content"]
assert heading["content"].strip() == "System"
def test_images_stripped_from_nested_toc(self) -> None:
"""Image stripping must apply at every nesting level."""
result = render(
content=(
"# Top level\n\n## ![icon](../../images/system-32.png) System\n"
),
path="index.md",
url="/",
)
# The rendered page body must contain <img>.
assert "<img" in result["content"]
# Collect content from all TOC levels.
all_contents = _toc_contents(result["toc"])
# No level should contain <img>.
assert all("<img" not in c for c in all_contents)
+18 -1
View File
@@ -80,13 +80,30 @@ class TestCleanupTocLabel:
"\nAbbr\n",
id="multiline_abbr",
),
# Images ------------------------------------------------------
pytest.param(
'<img src="image.png" alt="Image">',
"",
id="img_tag",
),
pytest.param(
'<img src="image.png" alt="Image">Text',
"Text",
id="img_tag_with_text_after",
),
pytest.param(
'Text<img src="image.png" alt="Image">',
"Text",
id="img_tag_with_text_before",
),
# Combined and passthrough ------------------------------------
pytest.param(
'<a href="#x">Intro to '
'<abbr title="HyperText Markup Language">HTML</abbr>'
'<img src="image.png" alt="Image">'
"</a>",
"Intro to HTML",
id="links_and_abbreviations",
id="combined_and_passthrough",
),
pytest.param(
"Just plain text",
+2
View File
@@ -180,4 +180,6 @@ def _cleanup_toc_label(html: str) -> str:
html = re.sub(r"<a\s+[^>]+>(.*?)</a>", r"\1", html, flags=re.DOTALL)
# Remove abbreviations
html = re.sub(r"<abbr\s+[^>]+>(.*?)</abbr>", r"\1", html, flags=re.DOTALL)
# Remove images
html = re.sub(r"<img\s+[^>]+>", "", html, flags=re.DOTALL)
return html # noqa: RET504