#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Self-contained HTML preview of a generated design system. Writes preview.html with inline CSS (no JS framework, no Tailwind CDN). Google Fonts are linked when the pairing provides a URL; system-font fallbacks keep the page readable offline. """ from html import escape import os import re import tempfile from pathlib import Path from design_system import ( SEMANTIC_COLOR_ENTRIES, _button_outline_text_color, _contrast_ratio, _palette_is_dark, _write_persisted_file, safe_slug, ) _SAFE_HEX = re.compile(r"^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$") _GOOGLE_FONTS_PREFIXES = ( "https://fonts.googleapis.com/", "https://fonts.gstatic.com/", ) # Surface / on-surface pairs used for WCAG contrast badges. _CONTRAST_PAIRS = ( ("primary", "on_primary"), ("secondary", "on_secondary"), ("accent", "on_accent"), ("background", "foreground"), ("card", "card_foreground"), ("muted", "muted_foreground"), ("destructive", "on_destructive"), ) _ON_ROLE = {surface: on for surface, on in _CONTRAST_PAIRS} _ON_ROLE.update({on: surface for surface, on in _CONTRAST_PAIRS}) def _text(value) -> str: if value is None: return "" return escape(str(value), quote=False) def _attr(value) -> str: if value is None: return "" return escape(str(value), quote=True) def _css_color(value, fallback=None) -> str: raw = (value or "").strip() if _SAFE_HEX.match(raw): return raw if fallback and _SAFE_HEX.match(fallback.strip()): return fallback.strip() return "" def _css_font(name: str) -> str: cleaned = re.sub(r'["\\]', "", (name or "").strip()) return cleaned or "sans-serif" def _google_fonts_href(url: str) -> str: raw = (url or "").strip() if any(raw.startswith(prefix) for prefix in _GOOGLE_FONTS_PREFIXES): return _attr(raw) return "" def _wcag_level(ratio) -> str: if ratio is None: return "" if ratio >= 7: return "AAA" if ratio >= 4.5: return "AA" return "Fail" def _format_ratio(ratio) -> str: if ratio is None: return "" return f"{ratio:.2f}:1" def _is_dark(design_system: dict) -> bool: if design_system.get("color_mode") == "dark": return True colors = design_system.get("colors") or {} return _palette_is_dark({"Background": colors.get("background", "")}) def _role_contrast(colors: dict, key: str): pair_key = _ON_ROLE.get(key) if not pair_key: return None return _contrast_ratio(colors.get(key, ""), colors.get(pair_key, "")) def format_preview_html(design_system: dict) -> str: """Render a dependency-free HTML page for the generated design system.""" project = design_system.get("project_name") or "Design system" category = design_system.get("category") or "" style = design_system.get("style") or {} colors = design_system.get("colors") or {} typography = design_system.get("typography") or {} effects = design_system.get("key_effects") or "" anti_patterns = design_system.get("anti_patterns") or "" notes = colors.get("notes") or "" heading_font = typography.get("heading") or "sans-serif" body_font = typography.get("body") or "sans-serif" google_href = _google_fonts_href(typography.get("google_fonts_url") or "") dark = _is_dark(design_system) css_vars = [] for _label, key, css_var in SEMANTIC_COLOR_ENTRIES: hex_val = _css_color(colors.get(key, "")) if hex_val: css_vars.append(f" {css_var}: {hex_val};") background = _css_color(colors.get("background"), "#FFFFFF") or "#FFFFFF" foreground = _css_color(colors.get("foreground"), "#111111") or "#111111" card = _css_color(colors.get("card"), background) or background card_fg = _css_color(colors.get("card_foreground"), foreground) or foreground primary = _css_color(colors.get("primary"), "#2563EB") or "#2563EB" on_primary = _css_color(colors.get("on_primary")) or _css_color( colors.get("foreground"), "#FFFFFF" ) or "#FFFFFF" secondary = _css_color(colors.get("secondary"), primary) or primary on_secondary = _css_color(colors.get("on_secondary")) or on_primary accent = _css_color(colors.get("accent") or colors.get("cta"), primary) or primary on_accent = _css_color(colors.get("on_accent") or colors.get("on_cta")) or on_primary destructive = _css_color(colors.get("destructive"), "#DC2626") or "#DC2626" on_destructive = _css_color(colors.get("on_destructive")) or "#FFFFFF" muted = _css_color(colors.get("muted"), card) or card muted_fg = _css_color(colors.get("muted_foreground"), foreground) or foreground border = _css_color(colors.get("border"), foreground) or foreground ring = _css_color(colors.get("ring"), primary) or primary secondary_text = _css_color(_button_outline_text_color(colors), foreground) or foreground heading_stack = f'"{_css_font(heading_font)}", system-ui, -apple-system, "Segoe UI", sans-serif' body_stack = f'"{_css_font(body_font)}", system-ui, -apple-system, "Segoe UI", sans-serif' swatches = [] for label, key, css_var in SEMANTIC_COLOR_ENTRIES: hex_val = _css_color(colors.get(key, "")) if not hex_val: continue ratio = _role_contrast(colors, key) pair_key = _ON_ROLE.get(key) pair_hex = _css_color(colors.get(pair_key, "")) if pair_key else "" level = _wcag_level(ratio) ratio_html = "" if ratio is not None: badge_class = "badge-aaa" if level == "AAA" else "badge-aa" if level == "AA" else "badge-fail" pair_label = next( (entry[0] for entry in SEMANTIC_COLOR_ENTRIES if entry[1] == pair_key), pair_key, ) ratio_html = ( f'

vs {_text(pair_label)} ' f'{_text(pair_hex)}: {_text(_format_ratio(ratio))} ' f'{_text(level)}

' ) swatches.append( f'
  • ' f'' f'
    ' f'

    {_text(label)}

    ' f'

    {_text(hex_val)} {_text(css_var)}

    ' f'{ratio_html}' f'
  • ' ) anti_items = [] for clause in (anti_patterns.split("+") if anti_patterns else []): clause = clause.strip() if clause: anti_items.append(f"
  • {_text(clause)}
  • ") if not anti_items: anti_items.append("
  • None listed for this system.
  • ") font_links = "" if google_href: font_links = ( ' \n' ' \n' f' \n' ) color_scheme = "dark" if dark else "light" notes_html = ( f'

    {_text(notes)}

    ' if notes else "" ) effects_html = _text(effects) if effects else "None listed for this system." css_vars_block = "\n".join(css_vars) swatches_html = "".join(swatches) anti_html = "".join(anti_items) return f""" {_attr(project)} design system preview {font_links}

    Design system preview

    {_text(project)}

    {_text(style.get("name") or "Unspecified style")}{_text(" · " + category if category else "")}

    Palette

    {notes_html}

    Typography

    Heading: {_text(heading_font)} · Body: {_text(body_font)}

    Display · {_text(heading_font)}

    Heading 2 · {_text(heading_font)}

    Body copy in {_text(body_font)}. The generated pairing is shown at a readable scale so you can judge hierarchy, weight, and line length before building components. Pack my box with five dozen liquor jugs.

    Buttons

    Default

    Hover

    Focus-visible

    Disabled

    Card

    {_text(project)}

    A sample card using the generated card surface, border, and type pairing.

    Form

    Use your work address.

    Enter a display name of at least two characters.

    Style, effects, anti-patterns

    Style: {_text(style.get("name") or "")}

    Key effects: {effects_html}

    Anti-patterns

    """ def preview_destination(design_system: dict, persist: bool = False, output_dir: str = None) -> Path: """Resolve where preview.html should be written (not used for temp files).""" project_name = design_system.get("project_name") or "default" slug = safe_slug(project_name) if persist: base_dir = Path(output_dir) if output_dir else Path.cwd() return base_dir / "design-system" / slug / "preview.html" if output_dir: return Path(output_dir) / "preview.html" raise ValueError("preview_destination requires persist or output_dir") def write_preview_html(design_system: dict, persist: bool = False, output_dir: str = None, force: bool = False) -> dict: """Write preview.html. Follows persist path rules and --force semantics. With persist: design-system//preview.html under output_dir or cwd. Without persist: --output-dir/preview.html, or a temp file when output_dir is omitted. Existing files are left untouched unless force is True. """ html = format_preview_html(design_system) if not persist and not output_dir: handle = tempfile.NamedTemporaryFile( mode="w", encoding="utf-8", suffix=".html", prefix="design-system-preview-", delete=False, ) try: handle.write(html) handle.flush() os.fsync(handle.fileno()) finally: handle.close() return { "status": "success", "preview_file": handle.name, "created_files": [handle.name], } path = preview_destination(design_system, persist=persist, output_dir=output_dir) path.parent.mkdir(parents=True, exist_ok=True) try: _write_persisted_file(path, html, force) except FileExistsError: return { "status": "skipped_exists", "preview_file": str(path), "created_files": [], "message": ( f"{path} already exists and was not modified. " "Re-run with force=True / --force to overwrite." ), } return { "status": "success", "preview_file": str(path), "created_files": [str(path)], }