Files
rengine/reports/render/css.py
T
Yogesh OjhaandClaude Fable 5.1 068f14bbfb feat(reports): the document says its answer before you open it
A design pass over the rendered documents, on the six themes, the print
stylesheet, the charts and the cover artwork. The brief was a baseline that
looked templated; the bar was a client deliverable someone would be proud to
hand over.

The structural failure was the severity chart. On a real scan, 589 informational
findings swamped 20 criticals into an invisible sliver, on the one page everyone
reads. Severity counts are now stat tiles, so the number is always legible, and
the ring and bar draw only the actionable set with the informational total
stated in the caption. That is the dataviz rule that a dominant neutral bucket
is a KPI, not a slice.

The executive page now opens with a verdict band: the gauge, the headline, the
severity tiles, then five surface figures in one row, and only then the prose at
a readable measure. Every cover carries a grade mark, so the report tells you
its answer on the front; on blueprint the reticle artwork is drawn around it.
Findings are a card with a hierarchy and a facts row where a table used to be,
control mapping is a line of text per framework rather than a wall of chips,
tables have a settled rhythm, and the section number sits in the accent.

The warning collector from the previous commit found every WeasyPrint defect
here. font-weight accepts only the hundreds, so two themes had been rendering
headings in a silent bold. content(text) drops the whitespace between an inline
span and its neighbour, so the running header read "1Executive summary" and the
bookmark with it; both now read a precomputed attribute. break-after: avoid on a
div is not honoured, so labels were orphaning from their content. A dark-paper
theme needs its background on @page as well as html, or the margins print white,
which is why noir had a white frame. word-break: break-word is invalid, and the
hostname column in the asset table was being crushed to a sliver by auto layout.

Two string edits in this pass silently missed because ruff had reformatted the
target; reading the function back after each edit is now written down.

Verified on the gov.cy scan: all 26 sections in all six themes, 57 to 60 pages
each, zero renderer warnings.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017f2Mf2HGwFaTRnui4UxpRd
2026-09-06 13:59:44 +05:30

130 lines
4.1 KiB
Python

"""Assemble one stylesheet: faces, theme tokens, page setup, then the theme's own CSS."""
from __future__ import annotations
import re
from functools import lru_cache
from pathlib import Path
from reports.theme import css_variables
from shared.definitions.report_theme import ThemeTokens
from shared.definitions.reports import (
PAGE_SIZE_CSS,
SLOT_TOKEN_VALUES,
Orientation,
ReportStyle,
)
ASSETS = Path(__file__).resolve().parent.parent / "assets"
TEMPLATES = Path(__file__).resolve().parent.parent / "templates"
_TOKEN_RE = re.compile("(" + "|".join(re.escape(t) for t in SLOT_TOKEN_VALUES) + ")")
_COUNTER_SLOTS = {
"{page}": "counter(page)",
"{pages}": "counter(pages)",
"{section}": "string(section)",
}
@lru_cache(maxsize=1)
def base_css() -> str:
return (TEMPLATES / "base.css").read_text(encoding="utf-8")
def _escape(value: str) -> str:
return value.replace("\\", "\\\\").replace('"', '\\"')
def slot_content(template: str, values: dict[str, str]) -> str:
"""A header or footer slot as a CSS content value."""
if not template.strip():
return "none"
parts: list[str] = []
for piece in _TOKEN_RE.split(template):
if not piece:
continue
if piece in _COUNTER_SLOTS:
parts.append(_COUNTER_SLOTS[piece])
elif piece.startswith("{") and piece.endswith("}"):
literal = values.get(piece[1:-1], "")
if literal:
parts.append(f'"{_escape(literal)}"')
else:
parts.append(f'"{_escape(piece)}"')
return " ".join(parts) if parts else "none"
def page_css(style: ReportStyle, values: dict[str, str]) -> str:
size = PAGE_SIZE_CSS.get(style.page_size, "A4")
orientation = (
"landscape" if style.orientation == Orientation.LANDSCAPE.value else "portrait"
)
margins = (
f"{style.margin_top}mm {style.margin_right}mm "
f"{style.margin_bottom}mm {style.margin_left}mm"
)
boxes: list[str] = []
slots = (
("top-left", style.header_left if style.show_header else ""),
("top-center", style.header_center if style.show_header else ""),
("top-right", style.header_right if style.show_header else ""),
("bottom-left", style.footer_left if style.show_footer else ""),
("bottom-center", style.footer_center if style.show_footer else ""),
("bottom-right", style.footer_right if style.show_footer else ""),
)
for box, template in slots:
content = slot_content(template, values)
if content == "none":
continue
edge = "top" if box.startswith("top") else "bottom"
boxes.append(
f"@{box}{{content:{content};font-family:var(--r-font-mono);"
f"font-size:var(--r-micro);letter-spacing:var(--r-label-track);"
f"color:var(--r-ink-faint);"
f"padding-{'bottom' if edge == 'top' else 'top'}:3mm;"
f"vertical-align:{edge}}}"
)
blank = "".join(
f"@{box}{{content:none}}"
for box in (
"top-left",
"top-center",
"top-right",
"bottom-left",
"bottom-center",
"bottom-right",
)
)
return (
f"@page{{size:{size} {orientation};margin:{margins};background:var(--r-page);{''.join(boxes)}}}"
f"@page cover{{margin:0;background:var(--r-page);{blank}}}"
f"@page appendix{{{''.join(boxes)}}}"
"h1{bookmark-level:1;bookmark-label:content(text)}"
".section__title{string-set:section attr(data-run);bookmark-level:1;bookmark-label:attr(data-run)}"
".sub__title{bookmark-level:2;bookmark-label:content(text)}"
".finding__title{bookmark-level:3;bookmark-label:content(text)}"
)
def stylesheet(
tokens: ThemeTokens,
style: ReportStyle,
values: dict[str, str],
*,
faces: str = "",
families: dict[str, str] | None = None,
) -> str:
return "\n".join(
(
faces,
css_variables(tokens, style, families=families),
base_css(),
page_css(style, values),
tokens.css or "",
)
)