"""Shared visual theme — the "Spectrum" design system.
Loads ``app/assets/design_system.css`` (the full token + component CSS from
the design file), injects it once per render, and provides helper functions
for emitting the correct HTML markup so the CSS classes actually match.
Key architecture: Streamlit generates its own HTML, so Spectrum's component
classes (.card, .screen-head, .verdict, .proposal-doc, etc.) only take effect
when we explicitly emit matching HTML via st.markdown(unsafe_allow_html=True).
Streamlit's functional widgets (buttons, file_uploader, text_input) are kept
for interactivity but restyled via the CSS widget-override section.
"""
from __future__ import annotations
from functools import lru_cache
import streamlit as st
import streamlit.components.v1 as components
from app.paths import resource_path
# Status-chip kinds → CSS class (legacy, used by a few callers).
_CHIP_KINDS = {
"ready": "ups-chip-ready",
"info": "ups-chip-info",
"missing": "ups-chip-missing",
"neutral": "ups-chip-neutral",
}
# Per-step signature color: (H, C, H2) in oklch. Light default.
STEP_COLORS: dict[str, tuple[float, float, float]] = {
# Aurora keeps ONE dominant violet, so the six steps sit inside a narrow
# band: the room warms or cools very slightly as the user moves forward,
# it never changes colour. At the "setup" values --accent resolves to
# #8B5CF6 — the Aurora primary.
"setup": (293.5, 0.213, 304.0),
"dossier": (290.0, 0.213, 301.0),
"screenshot": (297.0, 0.207, 308.0),
"confirmation": (287.0, 0.216, 299.0),
"analysis": (287.0, 0.216, 299.0),
"proposal": (300.0, 0.200, 310.0),
}
_DEFAULT_ACCENT = STEP_COLORS["setup"]
STEP_EYEBROWS = {
"setup": "Step 01 — Setup",
"dossier": "Step 02 — Dossier",
"screenshot": "Step 03 — Job Screenshot",
"analysis": "Step 04 — Analysis",
"proposal": "Step 05 — Proposal",
}
_FONTS_LINK = (
''
''
''
)
# Extra CSS layered on top of design_system.css to bridge Streamlit's DOM
# with the design's component classes.
_BRIDGE_CSS = """
"""
@lru_cache(maxsize=1)
def _design_css() -> str:
"""Read the Spectrum design system CSS once (cached), stripping stray style tags."""
try:
path = resource_path("app", "assets", "design_system.css")
css = path.read_text(encoding="utf-8")
except Exception:
return ""
return css.replace("", "").replace("" % (
rows,
_mask_url("arrow"),
)
def inject_css() -> None:
"""Inject fonts + the Spectrum design system + Streamlit bridge CSS."""
st.markdown(_FONTS_LINK, unsafe_allow_html=True)
css = _design_css()
if css:
st.markdown(f"", unsafe_allow_html=True)
st.markdown(_BRIDGE_CSS, unsafe_allow_html=True)
st.markdown(_nav_icon_css(), unsafe_allow_html=True)
def apply_step_accent(step_key: str, *, dark: bool = False) -> None:
"""Re-tint the whole screen to the current step's signature hue + theme.
The design tokens live under ``[data-theme]`` on the parent ````, so
this bridges from the component iframe to set it. It is hardened against the
two things that made dark mode feel flaky: the parent DOM not being ready
when the iframe first runs (so it retries briefly), and a write throwing in
some embedding contexts (so it is wrapped in try/catch). It also sets
``color-scheme`` so native widgets (uploader, inputs) adopt the dark look.
"""
h, c, h2 = STEP_COLORS.get(step_key, _DEFAULT_ACCENT)
theme_val = "dark" if dark else "light"
components.html(
f"""""",
height=0,
)
# ── Screen header ──────────────────────────────────────────────────────────
def screen_head(step_key: str, title: str, subtitle: str) -> None:
"""Render the screen's title and standfirst, as on the design canvas.
The artboards put the step indicator in the top bar rather than above the
headline, so this no longer emits the eyebrow pill — ``top_bar`` carries
the breadcrumb, the segmented rail and "Step N of M". ``step_key`` stays in
the signature (every screen passes it) and still selects the eyebrow text
for callers that want it via :data:`STEP_EYEBROWS`.
``subtitle`` is trusted markup written in the screen modules — it carries
emphasis. Never pass model output or file contents through it.
"""
st.markdown(
f"""
{title}
{subtitle}
""",
unsafe_allow_html=True,
)
# ── Verdict banner ─────────────────────────────────────────────────────────
_VERDICT_TONE = {
"Apply Confidently": ("go", "Apply confidently"),
"Proceed With Caution": ("warn", "Proceed with caution"),
"Do Not Proceed": ("stop", "Do not proceed"),
}
def verdict_banner(beginner_result: str, headline: str, body: str) -> None:
"""Render the full-bleed coloured verdict banner from the prototype."""
tone, badge_label = _VERDICT_TONE.get(beginner_result, ("warn", beginner_result))
st.markdown(
f"""
{badge_label}
{headline}
{body}
""",
unsafe_allow_html=True,
)
# ── Proposal document ──────────────────────────────────────────────────────
def _proposal_doc_html(text: str, word_count: int, file_count: int = 0) -> str:
"""Build the proposal card HTML as a single line (see :func:`proposal_doc`).
Returned as one line with no leading indentation and no whitespace-only
gaps so Streamlit's markdown parser renders it as pure HTML — a blank line
(e.g. when ``grounded`` is empty) would otherwise terminate the HTML block
and turn the trailing ```` into a literal code block.
"""
import html as _html
import re as _re
from app.services.proposal_generator import strip_stray_html
# 1. Strip any stray HTML tags the model may have emitted (e.g. a trailing
# ) so leaked markup never shows as text. Only real layout tags
# go: code such as "" or "Map" is content, and the
# escaping below shows it as written.
text = strip_stray_html(text or "")
# 2. Put each "Step N:" / "Step N -" marker on its own paragraph so numbered
# steps always render on separate lines. We ONLY split on the explicit
# "Step N" marker — never on bare numbers like "Day 2" or "$2.5".
text = _re.sub(r"\s*(? for readable line breaks.
def _para_html(p: str) -> str:
escaped = _html.escape(p)
escaped = escaped.replace("\n", " ")
return f"
{escaped}
"
paras_html = "".join(_para_html(p) for p in paragraphs)
grounded = (
f'
'
f'Grounded in {file_count} file{"s" if file_count != 1 else ""} from your dossier'
f"
"
if file_count
else ""
)
wc_label = f"{word_count} words" if word_count else ""
# Build as ONE line with no leading indentation and no whitespace-only
# gaps. Streamlit runs this through a markdown parser: a blank/whitespace
# line (e.g. when ``grounded`` is empty) would terminate the HTML block and
# the next indented ```` would render as a literal code block. Keeping
# it single-line avoids that entirely.
return (
f'
'
f'{wc_label}'
f''
f"
"
f'
{paras_html}{grounded}
'
)
def proposal_doc(text: str, word_count: int, file_count: int = 0) -> None:
"""Render the styled proposal document card from the prototype."""
st.markdown(
_proposal_doc_html(text, word_count, file_count),
unsafe_allow_html=True,
)
# ── Legacy helpers (kept for backward compat with existing screen code) ────
def status_chip(label: str, kind: str = "neutral") -> str:
css_class = _CHIP_KINDS.get(kind, _CHIP_KINDS["neutral"])
return f'{label}'
def render_app_header(
title: str,
subtitle: str,
*,
chip_label: str | None = None,
chip_kind: str = "neutral",
step_label: str | None = None,
) -> None:
"""Minimal top-of-page header (app title line only — screens use screen_head)."""
right_bits = []
if step_label:
right_bits.append(
f'{step_label}'
)
if chip_label:
right_bits.append(status_chip(chip_label, chip_kind))
right_html = (
'
', unsafe_allow_html=True)
# ══════════════════════════════════════════════════════════════════════════
# Aurora components
#
# One Python helper per component on the design canvas, emitting exactly the
# markup the artboards use (classes defined under "Aurora components" in
# design_system.css). Everything is escaped on the way in — these render app
# data, and none of them accept markup from a model or a file.
#
# Every helper here is presentational. None of them wrap, replace or stand in
# for a Streamlit control: real controls stay real controls and are matched to
# this same language by the widget layer in _BRIDGE_CSS.
# ══════════════════════════════════════════════════════════════════════════
import html as _html_mod
from app.ui.icons import ICONS, icon # noqa: F401 (re-exported for screens)
def _e(value: object) -> str:
"""Escape anything on its way into markup."""
return _html_mod.escape("" if value is None else str(value))
def _ico(name: str | None, size: int | None = None) -> str:
return icon(name, size=size) if name else ""
# ── chrome ────────────────────────────────────────────────────────────────
def top_bar(
*,
crumb_a: str,
crumb_b: str,
step_index: int | None,
step_total: int,
right_html: str = "",
) -> None:
"""The artboard's top bar: breadcrumb, segmented step rail, step caption.
``step_index`` is 1-based; ``None`` draws the rail with nothing lit (used
when the current screen is not one of the numbered steps).
"""
now = step_index or 0
segs = "".join(
f''
for i in range(step_total)
)
cap = (
f'Step {now} of {step_total}'
if step_index
else ""
)
st.markdown(
f'
",
unsafe_allow_html=True,
)
def sidebar_brand(title: str, tagline: str = "") -> None:
"""Brand lockup at the head of the rail: mark, wordmark, and the tagline.
The canvas puts a short tracked descriptor under the wordmark. This app's
descriptor is a real two-sentence tagline, so it is set as wrapping copy
below the lockup rather than squeezed onto one tracked line — the words
are the product's own and none of them are dropped.
"""
tag_html = (
f'
{_e(tagline)}
' if tagline else ""
)
st.markdown(
f'
'
f'{_ico("compass")}'
f'{_e(title)}'
f"
{tag_html}",
unsafe_allow_html=True,
)
def rail_cap(text: str) -> None:
"""The small uppercase caption that labels a group in the rail."""
st.markdown(f'
{_e(text)}
', unsafe_allow_html=True)
def engine_card(label: str, value: str, status: str, kind: str = "ok") -> None:
"""The rail's footer card — which AI service this session is running on."""
dot = "ups-dot" if kind == "ok" else f"ups-dot {_e(kind)}"
st.markdown(
f'
'
f'
{_e(label)}
'
f'
{_e(value)}
'
f'
{_e(status)}
'
f"
",
unsafe_allow_html=True,
)
# ── surfaces ──────────────────────────────────────────────────────────────
def panel(body_html: str, *, title: str = "", right_html: str = "") -> None:
"""A glass panel built from markup only.
For a panel that must CONTAIN Streamlit widgets, use
``st.container(border=True)`` instead — the widget layer styles it to
match this exactly. Wrapping widgets in raw HTML does not work.
"""
head = (
f'
{_e(title)}'
f'{right_html}
'
if title or right_html
else ""
)
st.markdown(
f'
{head}{body_html}
',
unsafe_allow_html=True,
)
def panel_header(title: str, right_html: str = "") -> None:
"""The panel head on its own, for use inside a st.container(border=True)."""
st.markdown(
f'
{_e(title)}'
f'{right_html}
',
unsafe_allow_html=True,
)
def kpis(items: list[dict], *, columns: int | None = None) -> None:
"""A row of KPI tiles.
Each item: ``{"lab", "val", "icon" | "initial", "delta", "delta_kind"}``.
Only ever call this with numbers the app actually has — a KPI that has to
be invented is a KPI that should not be on the screen.
"""
if not items:
return
n = columns or len(items)
cls = {1: "ups-kpis one", 2: "ups-kpis two", 3: "ups-kpis three"}.get(n, "ups-kpis")
tiles = []
for it in items:
badge = _ico(it["icon"]) if it.get("icon") else _e(it.get("initial", ""))
delta = (
f'{_e(it["delta"])}'
if it.get("delta")
else ""
)
tiles.append(
f'
', unsafe_allow_html=True)
def rows_table(columns: list[str], widths: str, rows: list[list[str]]) -> None:
"""A header row plus data rows on the artboard's grid.
``widths`` is a ``grid-template-columns`` value; every row uses it, so the
header and the body always line up. Cells are pre-built HTML fragments
from the caller (use ``cell`` / ``tile`` / ``tag`` below) — escape any raw
text with the helpers rather than passing it through.
"""
head = "".join(f"{_e(c)}" for c in columns)
body = "".join(
f'
'
+ "".join(cells)
+ "
"
for cells in rows
)
st.markdown(
f'
{head}
'
f"{body}",
unsafe_allow_html=True,
)
def cell(main: str, sub: str = "") -> str:
"""One two-line row cell: a bold primary line over a muted second line."""
sub_html = f'{_e(sub)}' if sub else ""
return f"{_e(main)}{sub_html}"
def plain(text: str, cls: str = "ups-cap") -> str:
"""One single-line row cell."""
return f'{_e(text)}'
def tile(label: str = "", icon_name: str | None = None) -> str:
"""The small square badge at the head of a row."""
return f'{_ico(icon_name) if icon_name else _e(label)}'
def kv_grid(pairs: list[tuple[str, str]], *, columns: int = 4) -> None:
"""The extracted-facts grid: a label over a value, in equal cells."""
if not pairs:
return
# Values are often the user's own words: "$10 or $20" must not turn
# into maths, so they get the Markdown-safe escaping, not just HTML's.
cells = "".join(
f'
{_text_block(k)}
'
f'
{_text_block(v) if v else "not stated"}
'
for k, v in pairs
)
cls = "ups-kv two" if columns == 2 else "ups-kv"
st.markdown(f'
{cells}
', unsafe_allow_html=True)
def log_block(lines: list[tuple[str, str]]) -> None:
"""A console transcript: ``(text, kind)`` where kind is ``""``/``ac``/``ok``."""
body = "".join(f'
{_e(t)}
' for t, k in lines)
st.markdown(f'
{body}
', unsafe_allow_html=True)
# Characters Markdown would act on even inside an HTML block: "$" starts
# maths, "*" and "_" emphasis, a backtick code. As entities they display as
# themselves. Newlines become , because a blank line would end the HTML
# block and turn an indented line into a code box.
_MD_ENTITIES = {
"$": "$", "*": "*", "_": "_", "`": "`", "~": "~",
"\\": "\", "[": "[", "]": "]", "#": "#", "|": "|",
}
_HTML_ENTITIES = {"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}
def _text_block(value: object) -> str:
"""Escape free text for an HTML block rendered through Markdown.
One pass, one entity per character: escaping HTML first and Markdown
after would rewrite the "#" inside the apostrophe's own entity.
"""
text = "" if value is None else str(value)
escaped = "".join(_HTML_ENTITIES.get(ch) or _MD_ENTITIES.get(ch, ch) for ch in text)
return " ".join(line.strip() for line in escaped.splitlines())
def evidence_list(items: list[dict]) -> None:
"""Evidence entries: a claim, the sentence behind it, and its source file."""
body = "".join(
f'
'
)
def flow(*fragments: str, gap: int = 12, top: int = 0) -> None:
"""Lay inline fragments (tags, captions) out in a row."""
style = f"gap:{gap}px" + (f";margin-top:{top}px" if top else "")
st.markdown(
f'
{"".join(f for f in fragments if f)}
',
unsafe_allow_html=True,
)
def html(markup: str) -> None:
"""Emit a composed fragment. The caller owns escaping."""
st.markdown(markup, unsafe_allow_html=True)