Coverage for lode / helpers / html_utils.py: 100%
12 statements
« prev ^ index » next coverage.py v7.13.0, created at 2026-10-05 16:02 +0000
« prev ^ index » next coverage.py v7.13.0, created at 2026-10-05 16:02 +0000
1# lode/helpers/html_utils.py
2"""HTML post-processing utilities.
4Shared by api.py (HTTP responses) and builder.py (static site generation).
5No dependency on FastAPI or any HTTP layer.
6"""
7import re
8import minify_html
11def minify(html: str) -> str:
12 """Minify HTML preserving render-markdown blocks (newline-sensitive).
14 render-markdown blocks contain Markdown text rendered client-side:
15 stripping their newlines would break the Markdown parser. They are
16 stashed before minification and restored verbatim afterwards.
17 """
18 stash: list[str] = []
20 def _hold(m: re.Match) -> str:
21 stash.append(m.group(0))
22 return f"\x00MD{len(stash)-1}\x00"
24 protected = re.sub(
25 r'<(span|div|a|p)\b[^>]*\brender-markdown\b[^>]*>.*?</\1>',
26 _hold, html, flags=re.S,
27 )
28 out = minify_html.minify(protected, minify_css=False, minify_js=False)
29 for i, block in enumerate(stash):
30 out = out.replace(f"\x00MD{i}\x00", block)
31 return out