Coverage for lode / helpers / html_utils.py: 100%

12 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2026-11-22 15:54 +0000

1# lode/helpers/html_utils.py 

2"""HTML post-processing utilities. 

3 

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 

9 

10 

11def minify(html: str) -> str: 

12 """Minify HTML preserving render-markdown blocks (newline-sensitive). 

13 

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] = [] 

19 

20 def _hold(m: re.Match) -> str: 

21 """Replace a protected block with a numbered placeholder and remember the block.""" 

22 stash.append(m.group(0)) 

23 return f"\x00MD{len(stash)-1}\x00" 

24 

25 protected = re.sub( 

26 r'<(span|div|a|p)\b[^>]*\brender-markdown\b[^>]*>.*?</\1>', 

27 _hold, html, flags=re.S, 

28 ) 

29 

30 def _restore(m: re.Match) -> str: 

31 """Return the protected block that a placeholder stands for.""" 

32 return stash[int(m.group(1))] 

33 

34 out = minify_html.minify(protected, minify_css=False, minify_js=False) 

35 # One pass: replacing block by block rescanned the whole page once per block. 

36 return re.sub(r"\x00MD(\d+)\x00", _restore, out)