fix: remove abbreviations from table of contents (#669)

Signed-off-by: Timothée Mazzucotelli <dev@pawamoy.fr>
This commit is contained in:
Timothée Mazzucotelli
2026-05-14 11:30:12 +00:00
committed by GitHub
parent 6eb2f4d942
commit 17c67a2f62
8 changed files with 343 additions and 5 deletions
+22
View File
@@ -0,0 +1,22 @@
# Copyright (c) 2025-2026 Zensical and contributors
# SPDX-License-Identifier: MIT
# All contributions are certified under the DCO
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
+63
View File
@@ -0,0 +1,63 @@
# Copyright (c) 2025-2026 Zensical and contributors
# SPDX-License-Identifier: MIT
# All contributions are certified under the DCO
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from __future__ import annotations
import copy
from typing import Any
import pytest
from zensical import config
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture(name="base_config", scope="session")
def _fixture_base_config(
tmp_path_factory: pytest.TempPathFactory,
) -> dict[str, Any]:
"""Build a fully-processed config once per session."""
root = tmp_path_factory.mktemp("integration_base")
(root / "docs").mkdir()
return config._apply_defaults(
{
"site_name": "Test",
"markdown_extensions": config.DEFAULT_MARKDOWN_EXTENSIONS,
},
str(root / "zensical.toml"),
)
@pytest.fixture(autouse=True)
def _fixture_set_config(base_config: dict[str, Any]) -> Any:
"""Give each test a fresh copy of the config and restore state after.
render() mutates the global config (it appends/updates ContextExtension),
so every test must start from an isolated copy.
"""
config._CONFIG = copy.deepcopy(base_config)
yield
config._CONFIG = None
@@ -0,0 +1,22 @@
# Copyright (c) 2025-2026 Zensical and contributors
# SPDX-License-Identifier: MIT
# All contributions are certified under the DCO
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
@@ -0,0 +1,106 @@
# Copyright (c) 2025-2026 Zensical and contributors
# SPDX-License-Identifier: MIT
# All contributions are certified under the DCO
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from __future__ import annotations
from zensical.markdown.render import render
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _toc_contents(toc: list[dict]) -> list[str]:
"""Recursively collect the `content` field of every TOC item."""
result = []
for item in toc:
result.append(item["content"])
result.extend(_toc_contents(item["children"]))
return result
# ---------------------------------------------------------------------------
# TOC cleanup
# ---------------------------------------------------------------------------
class TestTocCleanup:
def test_abbreviations_stripped_from_toc_content(self) -> None:
"""Abbreviations defined in the page must not appear as <abbr> in TOC.
The abbr Markdown extension runs before the TOC tree processor, so
heading HTML stored in toc_tokens already contains <abbr> elements.
_cleanup_toc_label must remove them, keeping only the plain text.
"""
result = render(
content=(
"# Working with HTML\n"
"\n"
"Some content here.\n"
"\n"
"*[HTML]: HyperText Markup Language\n"
),
path="index.md",
url="/",
)
# Sanity-check: the rendered page body must contain <abbr> to confirm
# the extension is actually active and expanding abbreviations.
assert "<abbr" 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 <abbr> tags.
assert "<abbr" not in heading["content"]
assert heading["content"] == "Working with HTML"
def test_abbreviations_stripped_from_nested_toc(self) -> None:
"""Abbreviation stripping must apply at every nesting level."""
result = render(
content=(
"# Top level\n"
"\n"
"## Using CSS\n"
"\n"
"Some content here.\n"
"\n"
"*[CSS]: Cascading Style Sheets\n"
),
path="index.md",
url="/",
)
# The rendered page body must contain <abbr>.
assert "<abbr" in result["content"]
# Collect content from all TOC levels.
all_contents = _toc_contents(result["toc"])
# No level should contain <abbr>.
assert all("<abbr" not in c for c in all_contents)
# The child heading must preserve the abbreviation text.
child = result["toc"][0]["children"][0]
assert child["content"] == "Using CSS"
+22
View File
@@ -0,0 +1,22 @@
# Copyright (c) 2025-2026 Zensical and contributors
# SPDX-License-Identifier: MIT
# All contributions are certified under the DCO
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
+99
View File
@@ -0,0 +1,99 @@
# Copyright (c) 2025-2026 Zensical and contributors
# SPDX-License-Identifier: MIT
# All contributions are certified under the DCO
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from __future__ import annotations
import pytest
from zensical.markdown.render import _cleanup_toc_label
# ---------------------------------------------------------------------------
# Cleaning up TOC
# ---------------------------------------------------------------------------
class TestCleanupTocLabel:
@pytest.mark.parametrize(
("html", "expected"),
[
# Links --------------------------------------------------------
pytest.param(
'<a href="#foo" id="foo">Heading</a>',
"Heading",
id="anchor_with_id_attr", # id= is stripped before <a>
),
pytest.param(
'<a href="#x">Hello <em>world</em></a>',
"Hello <em>world</em>",
id="anchor_preserves_inner_content",
),
pytest.param(
'<a href="#x">\nLine one\nLine two\n</a>',
"\nLine one\nLine two\n",
id="multiline_anchor",
),
pytest.param(
'<a href="#a">First</a> and <a href="#b">Second</a>',
"First and Second",
id="multiple_anchors",
),
# Abbreviations -----------------------------------------------
pytest.param(
'<abbr title="HyperText Markup Language">HTML</abbr>',
"HTML",
id="abbr_tag",
),
pytest.param(
'Use <abbr title="Cascading Style Sheets">CSS</abbr> for style',
"Use CSS for style",
id="abbr_preserves_surrounding_text",
),
pytest.param(
'<abbr title="HyperText Markup Language">HTML</abbr>'
" and "
'<abbr title="Cascading Style Sheets">CSS</abbr>',
"HTML and CSS",
id="multiple_abbreviations",
),
pytest.param(
'<abbr title="foo">\nAbbr\n</abbr>',
"\nAbbr\n",
id="multiline_abbr",
),
# Combined and passthrough ------------------------------------
pytest.param(
'<a href="#x">Intro to '
'<abbr title="HyperText Markup Language">HTML</abbr>'
"</a>",
"Intro to HTML",
id="links_and_abbreviations",
),
pytest.param(
"Just plain text",
"Just plain text",
id="plain_text_unchanged",
),
],
)
def test_cleans(self, html: str, expected: str) -> None:
assert _cleanup_toc_label(html) == expected
+1 -1
View File
@@ -56,7 +56,7 @@ if TYPE_CHECKING:
# ----------------------------------------------------------------------------
_CONFIG = None
_CONFIG: dict[str, Any] | None = None
"""
Global configuration to pick up later for parsing Markdown.
+8 -4
View File
@@ -158,7 +158,7 @@ def _convert_toc(item: Any) -> dict:
"""Convert a table of contents item to navigation item format."""
toc_item = {
"title": item["data-toc-label"] or item["name"],
"content": item["data-toc-label"] or _remove_links(item["html"]),
"content": item["data-toc-label"] or _cleanup_toc_label(item["html"]),
"id": item["id"],
"url": f"#{item['id']}",
"children": [],
@@ -173,7 +173,11 @@ def _convert_toc(item: Any) -> dict:
return toc_item
def _remove_links(html: str) -> str:
"""Remove links from HTML string."""
def _cleanup_toc_label(html: str) -> str:
"""Clean up a TOC label."""
# Remove links
html = re.sub(r"id=\"?[^\">]+\"?", "", html)
return re.sub(r"<a\s+[^>]+>(.*?)</a>", r"\1", html, flags=re.DOTALL)
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)
return html # noqa: RET504