From efd98221354918762b54a5079b39554c3f546f7a Mon Sep 17 00:00:00 2001 From: Matt Van Horn Date: Sun, 15 Nov 2026 11:05:27 -0800 Subject: [PATCH] feat(design-system): write a self-contained preview page for the generated system (#576) --- .claude/skills/ui-ux-pro-max/SKILL.md | 8 + .../ui-ux-pro-max/scripts/design_system.py | 17 +- .../skills/ui-ux-pro-max/scripts/preview.py | 543 ++++++++++++++++++ .../skills/ui-ux-pro-max/scripts/search.py | 29 +- .../tests/fixtures/relevance-thresholds.json | 2 +- .../tests/test_design_system_preview.py | 274 +++++++++ CLAUDE.md | 1 + README.md | 6 + cli/assets/scripts/design_system.py | 17 +- cli/assets/scripts/preview.py | 543 ++++++++++++++++++ cli/assets/scripts/search.py | 29 +- .../tests/fixtures/relevance-thresholds.json | 2 +- .../tests/test_design_system_preview.py | 274 +++++++++ cli/assets/templates/base/skill-content.md | 8 + cli/tests/e2e/template-script-paths.spec.ts | 2 +- scripts/validate-agent-guide.py | 2 +- src/ui-ux-pro-max/scripts/design_system.py | 17 +- src/ui-ux-pro-max/scripts/preview.py | 543 ++++++++++++++++++ src/ui-ux-pro-max/scripts/search.py | 29 +- .../tests/fixtures/relevance-thresholds.json | 2 +- .../tests/test_design_system_preview.py | 274 +++++++++ .../templates/base/skill-content.md | 8 + 22 files changed, 2604 insertions(+), 26 deletions(-) create mode 100644 .claude/skills/ui-ux-pro-max/scripts/preview.py create mode 100644 .claude/skills/ui-ux-pro-max/scripts/tests/test_design_system_preview.py create mode 100644 cli/assets/scripts/preview.py create mode 100644 cli/assets/scripts/tests/test_design_system_preview.py create mode 100644 src/ui-ux-pro-max/scripts/preview.py create mode 100644 src/ui-ux-pro-max/scripts/tests/test_design_system_preview.py diff --git a/.claude/skills/ui-ux-pro-max/SKILL.md b/.claude/skills/ui-ux-pro-max/SKILL.md index 2cacc87..253dba6 100644 --- a/.claude/skills/ui-ux-pro-max/SKILL.md +++ b/.claude/skills/ui-ux-pro-max/SKILL.md @@ -101,6 +101,14 @@ This creates: With a page-specific override, add `--page "dashboard"` to also create `design-system//pages/dashboard.md`. If Master already exists, a new page file is created without changing Master; an existing page file is skipped unless `--force` is explicitly authorized. +To render the generated system as a static page, add `--preview` (only valid with `--design-system`): + +```bash +python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py" "" --design-system --persist --preview -p "Project Name" --output-dir "" +``` + +With `--persist`, this writes `design-system//preview.html` next to Master. Without `--persist`, pass `--output-dir` to write `preview.html` there, or omit it to get a temp file whose path is printed. Existing `preview.html` files are skipped unless `--force` is set. + If `design-system//MASTER.md` already exists, `--persist` **skips writing and leaves it untouched** unless you also pass `--force` — check whether it exists first (and read it) before regenerating, so you don't silently discard prior decisions the user or a teammate made. Read an existing `MASTER.md` before deciding whether `--force` is justified. Never use `--force` without explicit user authorization. diff --git a/.claude/skills/ui-ux-pro-max/scripts/design_system.py b/.claude/skills/ui-ux-pro-max/scripts/design_system.py index d5fe157..e923c3f 100644 --- a/.claude/skills/ui-ux-pro-max/scripts/design_system.py +++ b/.claude/skills/ui-ux-pro-max/scripts/design_system.py @@ -612,6 +612,7 @@ class DesignSystemGenerator: "typography": best_typography.get("Font Pairing Name"), "landing": best_landing.get("Pattern Name"), }, + "color_mode": color_mode, "source_derivations": { "color_mode": best_color.get("_mode_derivation"), }, @@ -944,7 +945,7 @@ def format_markdown(design_system: dict) -> str: def generate_design_system(query: str, project_name: str = None, output_format: str = "ascii", persist: bool = False, page: str = None, output_dir: str = None, variance: int = None, motion: int = None, density: int = None, - force: bool = False) -> dict: + force: bool = False, preview: bool = False) -> dict: """ Main entry point for design system generation. @@ -960,11 +961,13 @@ def generate_design_system(query: str, project_name: str = None, output_format: density: Optional 1-10 VISUAL_DENSITY dial, overrides the spacing scale (1=spacious, 10=dense) force: If True, overwrite an existing MASTER.md; otherwise persistence is skipped (with a status message) when one already exists + preview: If True, write a self-contained preview.html of this system Returns: dict with keys: "text" (formatted design system string), "design_system" - (raw dict, useful for --json callers), and "persistence" (result of - persist_design_system(), or None if persist=False) + (raw dict, useful for --json callers), "persistence" (result of + persist_design_system(), or None if persist=False), and "preview" + (result of write_preview_html(), or None if preview=False) """ generator = DesignSystemGenerator() design_system = generator.generate(query, project_name, variance=variance, motion=motion, density=density) @@ -973,12 +976,20 @@ def generate_design_system(query: str, project_name: str = None, output_format: if persist: persistence_result = persist_design_system(design_system, page, output_dir, query, force=force) + preview_result = None + if preview: + from preview import write_preview_html + preview_result = write_preview_html( + design_system, persist=persist, output_dir=output_dir, force=force + ) + text = format_markdown(design_system) if output_format == "markdown" else format_ascii_box(design_system) return { "text": text, "design_system": design_system, "persistence": persistence_result, + "preview": preview_result, } diff --git a/.claude/skills/ui-ux-pro-max/scripts/preview.py b/.claude/skills/ui-ux-pro-max/scripts/preview.py new file mode 100644 index 0000000..9f61882 --- /dev/null +++ b/.claude/skills/ui-ux-pro-max/scripts/preview.py @@ -0,0 +1,543 @@ +#!/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} +
      + {swatches_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

    +
      + {anti_html} +
    +
    +
    + + +""" + + +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)], + } diff --git a/.claude/skills/ui-ux-pro-max/scripts/search.py b/.claude/skills/ui-ux-pro-max/scripts/search.py index 9ce5e40..9036ff6 100644 --- a/.claude/skills/ui-ux-pro-max/scripts/search.py +++ b/.claude/skills/ui-ux-pro-max/scripts/search.py @@ -5,6 +5,7 @@ UI/UX Pro Max Search - BM25 search engine for UI/UX style guides Usage: python search.py "" [--domain ] [--stack ] [--max-results 3] python search.py "" --design-system [-p "Project Name"] python search.py "" --design-system --persist [-p "Project Name"] --output-dir "" [--page "dashboard"] + python search.py "" --design-system --persist --preview [-p "Project Name"] --output-dir "" python search.py "" --design-system --variance 8 --motion 9 --density 7 Domains: style, color, chart, landing, product, ux, typography, google-fonts, icons, gsap, react, web @@ -23,6 +24,9 @@ Persistence (Master + Overrides pattern): --page Also create a page-specific override file in design-system//pages/ --force Overwrite an existing MASTER.md (without this, persistence is skipped if MASTER.md already exists, so prior design decisions aren't lost) + --preview Write preview.html for the generated system (requires --design-system). + With --persist, the file is written next to MASTER.md. Without --persist, + it is written to --output-dir or to a temp file whose path is printed. """ import argparse @@ -122,6 +126,7 @@ if __name__ == "__main__": parser.add_argument("--page", type=str, default=None, help="Create page-specific override file in design-system//pages/") parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory -- pass this explicitly, pointed at the project root)") parser.add_argument("--force", action="store_true", help="Overwrite an existing MASTER.md when persisting (default: skip if it already exists)") + parser.add_argument("--preview", action="store_true", help="Write a self-contained preview.html of the generated design system (requires --design-system)") # Design dials (1-10), only applied with --design-system parser.add_argument("--variance", type=int, choices=range(1, 11), metavar="1-10", help="DESIGN_VARIANCE dial: 1=centered/minimal, 10=bold/asymmetric (only with --design-system)") parser.add_argument("--motion", type=int, choices=range(1, 11), metavar="1-10", help="MOTION_INTENSITY dial: 1=subtle, 10=complex; pulls a matching GSAP snippet from motion.csv (only with --design-system)") @@ -129,6 +134,9 @@ if __name__ == "__main__": args = parser.parse_args() + if args.preview and not args.design_system: + parser.error("--preview requires --design-system") + # Design system takes priority if args.design_system: if args.rtl is not None: @@ -153,13 +161,17 @@ if __name__ == "__main__": motion=args.motion, density=args.density, force=args.force, + preview=args.preview, ) if args.json: - print(json_module.dumps( - {"design_system": result["design_system"], "persistence": result["persistence"]}, - indent=2, ensure_ascii=False, - )) + payload = { + "design_system": result["design_system"], + "persistence": result["persistence"], + } + if args.preview: + payload["preview"] = result["preview"] + print(json_module.dumps(payload, indent=2, ensure_ascii=False)) else: print(result["text"]) @@ -177,6 +189,15 @@ if __name__ == "__main__": print(f"📖 Usage: When building a page, check {ds_dir}/pages/[page].md first.") print(" If it exists, its rules override MASTER.md. Otherwise, use MASTER.md.") print("=" * 60) + + if args.preview: + preview = result["preview"] or {} + print("\n" + "=" * 60) + if preview.get("status") == "skipped_exists": + print(f"⚠️ {preview.get('message', 'preview.html already exists; not overwritten.')}") + else: + print(f"✅ Design system preview: {preview.get('preview_file')}") + print("=" * 60) # Stack search elif args.stack: if args.rtl is not None: diff --git a/.claude/skills/ui-ux-pro-max/scripts/tests/fixtures/relevance-thresholds.json b/.claude/skills/ui-ux-pro-max/scripts/tests/fixtures/relevance-thresholds.json index c4ded1a..bdbeb02 100644 --- a/.claude/skills/ui-ux-pro-max/scripts/tests/fixtures/relevance-thresholds.json +++ b/.claude/skills/ui-ux-pro-max/scripts/tests/fixtures/relevance-thresholds.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "status": "provisional-baseline-regression-gate", "baselineRevision": "97eb2a2", - "runtimeFingerprint": "b5d3f2964bf5e55edafb253387b468e69a5ad0ee4c456ed295850819429d6168", + "runtimeFingerprint": "d0cb5803e094c21dc5262770f4a2dd8cecd20abf702896eea6ec69c357c54648", "oracleFingerprint": "02e7226428c64a995ec24ae104ce4d186f5f91bf0f062556e90ef9b0fcb6d67a", "approvingMaintainer": "repository maintainer approved Phase 1 testing checkpoint; second judgment review remains required before final-target promotion", "units": "All metrics are ratios in [0,1]. Precision treats missing ranks as non-relevant. Negative abstention is measured across the hard-negative by domain/stack cross-product.", diff --git a/.claude/skills/ui-ux-pro-max/scripts/tests/test_design_system_preview.py b/.claude/skills/ui-ux-pro-max/scripts/tests/test_design_system_preview.py new file mode 100644 index 0000000..219dddc --- /dev/null +++ b/.claude/skills/ui-ux-pro-max/scripts/tests/test_design_system_preview.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Tests for --preview HTML output of the design system generator. + +Stdlib-only (unittest, not pytest) to match test_core.py. + +Run with: + python -m unittest discover -s scripts/tests -v +or directly: + python scripts/tests/test_design_system_preview.py +""" + +import json +import subprocess +import sys +import tempfile +import unittest +from html import escape +from html.parser import HTMLParser +from pathlib import Path + +SCRIPTS_DIR = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(SCRIPTS_DIR)) + +from design_system import ( # noqa: E402 + SEMANTIC_COLOR_ENTRIES, + _contrast_ratio, + _palette_is_dark, + generate_design_system, +) +from preview import format_preview_html, write_preview_html # noqa: E402 + +SEARCH = SCRIPTS_DIR / "search.py" +HOSTILE_NAME = '' +DARK_QUERY = "SaaS invoicing fintech B2B professional dark mode" + + +class _TagCollector(HTMLParser): + def __init__(self): + super().__init__() + self.tags = [] + self.text = [] + + def handle_starttag(self, tag, attrs): + self.tags.append((tag, dict(attrs))) + + def handle_data(self, data): + self.text.append(data) + + +def _parse(html): + parser = _TagCollector() + parser.feed(html) + return parser + + +def _run_search(*args): + return subprocess.run( + [sys.executable, str(SEARCH), *map(str, args)], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + ) + + +class TestPreviewStructure(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.result = generate_design_system("fintech dashboard", "Ledger") + cls.ds = cls.result["design_system"] + cls.html = format_preview_html(cls.ds) + cls.parsed = _parse(cls.html) + + def test_lang_landmark_and_labels(self): + html_tag = next(attrs for tag, attrs in self.parsed.tags if tag == "html") + self.assertEqual(html_tag.get("lang"), "en") + tags = [tag for tag, _attrs in self.parsed.tags] + self.assertIn("main", tags) + self.assertIn("header", tags) + labels = [attrs for tag, attrs in self.parsed.tags if tag == "label"] + inputs = [attrs for tag, attrs in self.parsed.tags if tag == "input"] + self.assertGreaterEqual(len(labels), 2) + self.assertGreaterEqual(len(inputs), 2) + for attrs in inputs: + self.assertTrue(attrs.get("id"), attrs) + matching = [label for label in labels if label.get("for") == attrs["id"]] + self.assertTrue(matching, attrs) + + def test_palette_swatches_cover_every_present_role(self): + for label, key, _css_var in SEMANTIC_COLOR_ENTRIES: + hex_val = self.ds["colors"].get(key, "") + if hex_val: + self.assertIn(hex_val, self.html) + self.assertIn(label, self.html) + + def test_type_buttons_card_form_style_and_anti_patterns(self): + self.assertIn(self.ds["typography"]["heading"], self.html) + self.assertIn(self.ds["typography"]["body"], self.html) + self.assertIn("btn-primary", self.html) + self.assertIn("btn-secondary", self.html) + self.assertIn("btn-accent", self.html) + self.assertIn("btn-destructive", self.html) + self.assertIn("is-hover", self.html) + self.assertIn("is-focus", self.html) + self.assertIn("disabled", self.html) + self.assertIn("preview-card", self.html) + self.assertIn("aria-invalid", self.html) + self.assertIn(self.ds["style"]["name"], self.html) + self.assertIn("prefers-reduced-motion", self.html) + self.assertIn(":focus-visible", self.html) + if self.ds["key_effects"]: + self.assertIn(self.ds["key_effects"].split("+")[0].strip()[:20], self.html) + for clause in self.ds["anti_patterns"].split("+"): + clause = clause.strip() + if clause: + self.assertIn(clause, self.html) + + def test_google_fonts_link_when_pairing_has_a_url(self): + url = self.ds["typography"].get("google_fonts_url") or "" + if url: + self.assertIn(escape(url, quote=True), self.html) + self.assertIn('rel="stylesheet"', self.html) + self.assertIn("system-ui", self.html) + + +class TestPreviewEscaping(unittest.TestCase): + def test_hostile_project_name_is_escaped(self): + ds = generate_design_system("kids education app", HOSTILE_NAME)["design_system"] + html = format_preview_html(ds) + self.assertNotIn("", html) + self.assertIn("<script>alert(1)</script>", html) + self.assertIn("alert(1)", html) + self.assertIn("<script>alert(1)</script>", html) + + +class TestPreviewContrast(unittest.TestCase): + def test_printed_ratios_match_generator(self): + ds = generate_design_system("fintech dashboard", "Ledger")["design_system"] + html = format_preview_html(ds) + pairs = ( + ("primary", "on_primary"), + ("secondary", "on_secondary"), + ("accent", "on_accent"), + ("background", "foreground"), + ("card", "card_foreground"), + ("muted", "muted_foreground"), + ("destructive", "on_destructive"), + ) + for surface, on in pairs: + ratio = _contrast_ratio(ds["colors"][surface], ds["colors"][on]) + self.assertIsNotNone(ratio) + self.assertIn(f"{ratio:.2f}:1", html) + level = "AAA" if ratio >= 7 else "AA" if ratio >= 4.5 else "Fail" + self.assertIn(level, html) + + +class TestPreviewDarkMode(unittest.TestCase): + def test_dark_system_renders_on_its_dark_surfaces(self): + ds = generate_design_system(DARK_QUERY, "Night Ledger")["design_system"] + self.assertEqual(ds["color_mode"], "dark") + self.assertTrue(_palette_is_dark({"Background": ds["colors"]["background"]})) + html = format_preview_html(ds) + self.assertIn(f'background: {ds["colors"]["background"]}', html) + self.assertIn(f'color: {ds["colors"]["foreground"]}', html) + self.assertIn('content="dark"', html) + + +class TestPreviewCli(unittest.TestCase): + def test_preview_without_design_system_errors(self): + proc = _run_search("fintech dashboard", "--preview") + self.assertNotEqual(proc.returncode, 0) + self.assertIn("--design-system", proc.stderr) + + def test_preview_with_persist_writes_next_to_master(self): + with tempfile.TemporaryDirectory() as tmp: + proc = _run_search( + "fintech dashboard", "--design-system", "--persist", "--preview", + "--project-name", "Ledger", "--output-dir", tmp, "--json", + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + payload = json.loads(proc.stdout) + preview = Path(payload["preview"]["preview_file"]) + master = Path(payload["persistence"]["master_file"]) + self.assertEqual(preview.parent, master.parent) + self.assertEqual(preview.name, "preview.html") + self.assertTrue(preview.exists()) + self.assertTrue(master.exists()) + + def test_preview_without_persist_uses_output_dir(self): + with tempfile.TemporaryDirectory() as tmp: + proc = _run_search( + "fintech dashboard", "--design-system", "--preview", + "--project-name", "Ledger", "--output-dir", tmp, "--json", + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + payload = json.loads(proc.stdout) + preview = Path(payload["preview"]["preview_file"]) + self.assertEqual(preview, Path(tmp) / "preview.html") + self.assertTrue(preview.exists()) + self.assertFalse((Path(tmp) / "design-system").exists()) + + def test_preview_without_output_dir_uses_temp_file(self): + proc = _run_search( + "fintech dashboard", "--design-system", "--preview", + "--project-name", "Temp Ledger", "--json", + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + payload = json.loads(proc.stdout) + preview = Path(payload["preview"]["preview_file"]) + self.assertTrue(preview.exists()) + self.assertTrue(preview.name.startswith("design-system-preview-")) + preview.unlink() + + def test_preview_respects_force(self): + with tempfile.TemporaryDirectory() as tmp: + first = write_preview_html( + generate_design_system("fintech dashboard", "Ledger")["design_system"], + output_dir=tmp, + ) + path = Path(first["preview_file"]) + path.write_text("stale", encoding="utf-8") + skipped = write_preview_html( + generate_design_system("fintech dashboard", "Ledger")["design_system"], + output_dir=tmp, + ) + self.assertEqual(skipped["status"], "skipped_exists") + self.assertEqual(path.read_text(encoding="utf-8"), "stale") + overwritten = write_preview_html( + generate_design_system("fintech dashboard", "Ledger")["design_system"], + output_dir=tmp, force=True, + ) + self.assertEqual(overwritten["status"], "success") + self.assertIn("" --domain [-n " --design-system --variance <1-10> --motion <1-10> --density <1-10> ``` +`--preview` (only with `--design-system`) writes a self-contained `preview.html` of the generated system. With `--persist` it lands next to `MASTER.md`; without `--persist` it writes to `--output-dir` or a temp file. `--variance` biases style selection (centered/minimal → bold/asymmetric), `--motion` attaches a matching GSAP snippet from `motion.csv`, `--density` overrides the spacing-scale tokens (spacious → dense/dashboard). Any dial left unset behaves exactly as before. **RTL filter (optional, `style` and `product` only):** diff --git a/README.md b/README.md index abfcb74..98a06ee 100755 --- a/README.md +++ b/README.md @@ -514,14 +514,20 @@ python3 .claude/skills/ui-ux-pro-max/scripts/search.py "SaaS dashboard" --design # Also create a page-specific override file python3 .claude/skills/ui-ux-pro-max/scripts/search.py "SaaS dashboard" --design-system --persist -p "MyApp" --page "dashboard" + +# Also write a self-contained preview.html next to MASTER.md +python3 .claude/skills/ui-ux-pro-max/scripts/search.py "SaaS dashboard" --design-system --persist --preview -p "MyApp" ``` +`--preview` requires `--design-system`. With `--persist` it writes `preview.html` next to `MASTER.md`. Without `--persist`, pass `--output-dir` to write `preview.html` there, or omit it to get a temp file whose path is printed. Existing files are skipped unless you also pass `--force`. + This creates a `design-system/` folder structure: ``` design-system/ └── myapp/ # One folder per project (slug of -p "MyApp") ├── MASTER.md # Global Source of Truth (colors, typography, spacing, components) + ├── preview.html # Static preview of the generated palette, type, and components └── pages/ └── dashboard.md # Page-specific overrides (only deviations from Master) ``` diff --git a/cli/assets/scripts/design_system.py b/cli/assets/scripts/design_system.py index d5fe157..e923c3f 100644 --- a/cli/assets/scripts/design_system.py +++ b/cli/assets/scripts/design_system.py @@ -612,6 +612,7 @@ class DesignSystemGenerator: "typography": best_typography.get("Font Pairing Name"), "landing": best_landing.get("Pattern Name"), }, + "color_mode": color_mode, "source_derivations": { "color_mode": best_color.get("_mode_derivation"), }, @@ -944,7 +945,7 @@ def format_markdown(design_system: dict) -> str: def generate_design_system(query: str, project_name: str = None, output_format: str = "ascii", persist: bool = False, page: str = None, output_dir: str = None, variance: int = None, motion: int = None, density: int = None, - force: bool = False) -> dict: + force: bool = False, preview: bool = False) -> dict: """ Main entry point for design system generation. @@ -960,11 +961,13 @@ def generate_design_system(query: str, project_name: str = None, output_format: density: Optional 1-10 VISUAL_DENSITY dial, overrides the spacing scale (1=spacious, 10=dense) force: If True, overwrite an existing MASTER.md; otherwise persistence is skipped (with a status message) when one already exists + preview: If True, write a self-contained preview.html of this system Returns: dict with keys: "text" (formatted design system string), "design_system" - (raw dict, useful for --json callers), and "persistence" (result of - persist_design_system(), or None if persist=False) + (raw dict, useful for --json callers), "persistence" (result of + persist_design_system(), or None if persist=False), and "preview" + (result of write_preview_html(), or None if preview=False) """ generator = DesignSystemGenerator() design_system = generator.generate(query, project_name, variance=variance, motion=motion, density=density) @@ -973,12 +976,20 @@ def generate_design_system(query: str, project_name: str = None, output_format: if persist: persistence_result = persist_design_system(design_system, page, output_dir, query, force=force) + preview_result = None + if preview: + from preview import write_preview_html + preview_result = write_preview_html( + design_system, persist=persist, output_dir=output_dir, force=force + ) + text = format_markdown(design_system) if output_format == "markdown" else format_ascii_box(design_system) return { "text": text, "design_system": design_system, "persistence": persistence_result, + "preview": preview_result, } diff --git a/cli/assets/scripts/preview.py b/cli/assets/scripts/preview.py new file mode 100644 index 0000000..9f61882 --- /dev/null +++ b/cli/assets/scripts/preview.py @@ -0,0 +1,543 @@ +#!/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} +
      + {swatches_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

    +
      + {anti_html} +
    +
    +
    + + +""" + + +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)], + } diff --git a/cli/assets/scripts/search.py b/cli/assets/scripts/search.py index 9ce5e40..9036ff6 100644 --- a/cli/assets/scripts/search.py +++ b/cli/assets/scripts/search.py @@ -5,6 +5,7 @@ UI/UX Pro Max Search - BM25 search engine for UI/UX style guides Usage: python search.py "" [--domain ] [--stack ] [--max-results 3] python search.py "" --design-system [-p "Project Name"] python search.py "" --design-system --persist [-p "Project Name"] --output-dir "" [--page "dashboard"] + python search.py "" --design-system --persist --preview [-p "Project Name"] --output-dir "" python search.py "" --design-system --variance 8 --motion 9 --density 7 Domains: style, color, chart, landing, product, ux, typography, google-fonts, icons, gsap, react, web @@ -23,6 +24,9 @@ Persistence (Master + Overrides pattern): --page Also create a page-specific override file in design-system//pages/ --force Overwrite an existing MASTER.md (without this, persistence is skipped if MASTER.md already exists, so prior design decisions aren't lost) + --preview Write preview.html for the generated system (requires --design-system). + With --persist, the file is written next to MASTER.md. Without --persist, + it is written to --output-dir or to a temp file whose path is printed. """ import argparse @@ -122,6 +126,7 @@ if __name__ == "__main__": parser.add_argument("--page", type=str, default=None, help="Create page-specific override file in design-system//pages/") parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory -- pass this explicitly, pointed at the project root)") parser.add_argument("--force", action="store_true", help="Overwrite an existing MASTER.md when persisting (default: skip if it already exists)") + parser.add_argument("--preview", action="store_true", help="Write a self-contained preview.html of the generated design system (requires --design-system)") # Design dials (1-10), only applied with --design-system parser.add_argument("--variance", type=int, choices=range(1, 11), metavar="1-10", help="DESIGN_VARIANCE dial: 1=centered/minimal, 10=bold/asymmetric (only with --design-system)") parser.add_argument("--motion", type=int, choices=range(1, 11), metavar="1-10", help="MOTION_INTENSITY dial: 1=subtle, 10=complex; pulls a matching GSAP snippet from motion.csv (only with --design-system)") @@ -129,6 +134,9 @@ if __name__ == "__main__": args = parser.parse_args() + if args.preview and not args.design_system: + parser.error("--preview requires --design-system") + # Design system takes priority if args.design_system: if args.rtl is not None: @@ -153,13 +161,17 @@ if __name__ == "__main__": motion=args.motion, density=args.density, force=args.force, + preview=args.preview, ) if args.json: - print(json_module.dumps( - {"design_system": result["design_system"], "persistence": result["persistence"]}, - indent=2, ensure_ascii=False, - )) + payload = { + "design_system": result["design_system"], + "persistence": result["persistence"], + } + if args.preview: + payload["preview"] = result["preview"] + print(json_module.dumps(payload, indent=2, ensure_ascii=False)) else: print(result["text"]) @@ -177,6 +189,15 @@ if __name__ == "__main__": print(f"📖 Usage: When building a page, check {ds_dir}/pages/[page].md first.") print(" If it exists, its rules override MASTER.md. Otherwise, use MASTER.md.") print("=" * 60) + + if args.preview: + preview = result["preview"] or {} + print("\n" + "=" * 60) + if preview.get("status") == "skipped_exists": + print(f"⚠️ {preview.get('message', 'preview.html already exists; not overwritten.')}") + else: + print(f"✅ Design system preview: {preview.get('preview_file')}") + print("=" * 60) # Stack search elif args.stack: if args.rtl is not None: diff --git a/cli/assets/scripts/tests/fixtures/relevance-thresholds.json b/cli/assets/scripts/tests/fixtures/relevance-thresholds.json index c4ded1a..bdbeb02 100644 --- a/cli/assets/scripts/tests/fixtures/relevance-thresholds.json +++ b/cli/assets/scripts/tests/fixtures/relevance-thresholds.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "status": "provisional-baseline-regression-gate", "baselineRevision": "97eb2a2", - "runtimeFingerprint": "b5d3f2964bf5e55edafb253387b468e69a5ad0ee4c456ed295850819429d6168", + "runtimeFingerprint": "d0cb5803e094c21dc5262770f4a2dd8cecd20abf702896eea6ec69c357c54648", "oracleFingerprint": "02e7226428c64a995ec24ae104ce4d186f5f91bf0f062556e90ef9b0fcb6d67a", "approvingMaintainer": "repository maintainer approved Phase 1 testing checkpoint; second judgment review remains required before final-target promotion", "units": "All metrics are ratios in [0,1]. Precision treats missing ranks as non-relevant. Negative abstention is measured across the hard-negative by domain/stack cross-product.", diff --git a/cli/assets/scripts/tests/test_design_system_preview.py b/cli/assets/scripts/tests/test_design_system_preview.py new file mode 100644 index 0000000..219dddc --- /dev/null +++ b/cli/assets/scripts/tests/test_design_system_preview.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Tests for --preview HTML output of the design system generator. + +Stdlib-only (unittest, not pytest) to match test_core.py. + +Run with: + python -m unittest discover -s scripts/tests -v +or directly: + python scripts/tests/test_design_system_preview.py +""" + +import json +import subprocess +import sys +import tempfile +import unittest +from html import escape +from html.parser import HTMLParser +from pathlib import Path + +SCRIPTS_DIR = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(SCRIPTS_DIR)) + +from design_system import ( # noqa: E402 + SEMANTIC_COLOR_ENTRIES, + _contrast_ratio, + _palette_is_dark, + generate_design_system, +) +from preview import format_preview_html, write_preview_html # noqa: E402 + +SEARCH = SCRIPTS_DIR / "search.py" +HOSTILE_NAME = '' +DARK_QUERY = "SaaS invoicing fintech B2B professional dark mode" + + +class _TagCollector(HTMLParser): + def __init__(self): + super().__init__() + self.tags = [] + self.text = [] + + def handle_starttag(self, tag, attrs): + self.tags.append((tag, dict(attrs))) + + def handle_data(self, data): + self.text.append(data) + + +def _parse(html): + parser = _TagCollector() + parser.feed(html) + return parser + + +def _run_search(*args): + return subprocess.run( + [sys.executable, str(SEARCH), *map(str, args)], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + ) + + +class TestPreviewStructure(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.result = generate_design_system("fintech dashboard", "Ledger") + cls.ds = cls.result["design_system"] + cls.html = format_preview_html(cls.ds) + cls.parsed = _parse(cls.html) + + def test_lang_landmark_and_labels(self): + html_tag = next(attrs for tag, attrs in self.parsed.tags if tag == "html") + self.assertEqual(html_tag.get("lang"), "en") + tags = [tag for tag, _attrs in self.parsed.tags] + self.assertIn("main", tags) + self.assertIn("header", tags) + labels = [attrs for tag, attrs in self.parsed.tags if tag == "label"] + inputs = [attrs for tag, attrs in self.parsed.tags if tag == "input"] + self.assertGreaterEqual(len(labels), 2) + self.assertGreaterEqual(len(inputs), 2) + for attrs in inputs: + self.assertTrue(attrs.get("id"), attrs) + matching = [label for label in labels if label.get("for") == attrs["id"]] + self.assertTrue(matching, attrs) + + def test_palette_swatches_cover_every_present_role(self): + for label, key, _css_var in SEMANTIC_COLOR_ENTRIES: + hex_val = self.ds["colors"].get(key, "") + if hex_val: + self.assertIn(hex_val, self.html) + self.assertIn(label, self.html) + + def test_type_buttons_card_form_style_and_anti_patterns(self): + self.assertIn(self.ds["typography"]["heading"], self.html) + self.assertIn(self.ds["typography"]["body"], self.html) + self.assertIn("btn-primary", self.html) + self.assertIn("btn-secondary", self.html) + self.assertIn("btn-accent", self.html) + self.assertIn("btn-destructive", self.html) + self.assertIn("is-hover", self.html) + self.assertIn("is-focus", self.html) + self.assertIn("disabled", self.html) + self.assertIn("preview-card", self.html) + self.assertIn("aria-invalid", self.html) + self.assertIn(self.ds["style"]["name"], self.html) + self.assertIn("prefers-reduced-motion", self.html) + self.assertIn(":focus-visible", self.html) + if self.ds["key_effects"]: + self.assertIn(self.ds["key_effects"].split("+")[0].strip()[:20], self.html) + for clause in self.ds["anti_patterns"].split("+"): + clause = clause.strip() + if clause: + self.assertIn(clause, self.html) + + def test_google_fonts_link_when_pairing_has_a_url(self): + url = self.ds["typography"].get("google_fonts_url") or "" + if url: + self.assertIn(escape(url, quote=True), self.html) + self.assertIn('rel="stylesheet"', self.html) + self.assertIn("system-ui", self.html) + + +class TestPreviewEscaping(unittest.TestCase): + def test_hostile_project_name_is_escaped(self): + ds = generate_design_system("kids education app", HOSTILE_NAME)["design_system"] + html = format_preview_html(ds) + self.assertNotIn("", html) + self.assertIn("<script>alert(1)</script>", html) + self.assertIn("alert(1)", html) + self.assertIn("<script>alert(1)</script>", html) + + +class TestPreviewContrast(unittest.TestCase): + def test_printed_ratios_match_generator(self): + ds = generate_design_system("fintech dashboard", "Ledger")["design_system"] + html = format_preview_html(ds) + pairs = ( + ("primary", "on_primary"), + ("secondary", "on_secondary"), + ("accent", "on_accent"), + ("background", "foreground"), + ("card", "card_foreground"), + ("muted", "muted_foreground"), + ("destructive", "on_destructive"), + ) + for surface, on in pairs: + ratio = _contrast_ratio(ds["colors"][surface], ds["colors"][on]) + self.assertIsNotNone(ratio) + self.assertIn(f"{ratio:.2f}:1", html) + level = "AAA" if ratio >= 7 else "AA" if ratio >= 4.5 else "Fail" + self.assertIn(level, html) + + +class TestPreviewDarkMode(unittest.TestCase): + def test_dark_system_renders_on_its_dark_surfaces(self): + ds = generate_design_system(DARK_QUERY, "Night Ledger")["design_system"] + self.assertEqual(ds["color_mode"], "dark") + self.assertTrue(_palette_is_dark({"Background": ds["colors"]["background"]})) + html = format_preview_html(ds) + self.assertIn(f'background: {ds["colors"]["background"]}', html) + self.assertIn(f'color: {ds["colors"]["foreground"]}', html) + self.assertIn('content="dark"', html) + + +class TestPreviewCli(unittest.TestCase): + def test_preview_without_design_system_errors(self): + proc = _run_search("fintech dashboard", "--preview") + self.assertNotEqual(proc.returncode, 0) + self.assertIn("--design-system", proc.stderr) + + def test_preview_with_persist_writes_next_to_master(self): + with tempfile.TemporaryDirectory() as tmp: + proc = _run_search( + "fintech dashboard", "--design-system", "--persist", "--preview", + "--project-name", "Ledger", "--output-dir", tmp, "--json", + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + payload = json.loads(proc.stdout) + preview = Path(payload["preview"]["preview_file"]) + master = Path(payload["persistence"]["master_file"]) + self.assertEqual(preview.parent, master.parent) + self.assertEqual(preview.name, "preview.html") + self.assertTrue(preview.exists()) + self.assertTrue(master.exists()) + + def test_preview_without_persist_uses_output_dir(self): + with tempfile.TemporaryDirectory() as tmp: + proc = _run_search( + "fintech dashboard", "--design-system", "--preview", + "--project-name", "Ledger", "--output-dir", tmp, "--json", + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + payload = json.loads(proc.stdout) + preview = Path(payload["preview"]["preview_file"]) + self.assertEqual(preview, Path(tmp) / "preview.html") + self.assertTrue(preview.exists()) + self.assertFalse((Path(tmp) / "design-system").exists()) + + def test_preview_without_output_dir_uses_temp_file(self): + proc = _run_search( + "fintech dashboard", "--design-system", "--preview", + "--project-name", "Temp Ledger", "--json", + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + payload = json.loads(proc.stdout) + preview = Path(payload["preview"]["preview_file"]) + self.assertTrue(preview.exists()) + self.assertTrue(preview.name.startswith("design-system-preview-")) + preview.unlink() + + def test_preview_respects_force(self): + with tempfile.TemporaryDirectory() as tmp: + first = write_preview_html( + generate_design_system("fintech dashboard", "Ledger")["design_system"], + output_dir=tmp, + ) + path = Path(first["preview_file"]) + path.write_text("stale", encoding="utf-8") + skipped = write_preview_html( + generate_design_system("fintech dashboard", "Ledger")["design_system"], + output_dir=tmp, + ) + self.assertEqual(skipped["status"], "skipped_exists") + self.assertEqual(path.read_text(encoding="utf-8"), "stale") + overwritten = write_preview_html( + generate_design_system("fintech dashboard", "Ledger")["design_system"], + output_dir=tmp, force=True, + ) + self.assertEqual(overwritten["status"], "success") + self.assertIn("" --design-system --persist -p "Project Name" -- This also creates: - `design-system//pages/dashboard.md` — Page-specific deviations from Master +**Preview the generated system as a static page:** + +```bash +python3 {{SCRIPT_PATH}} "" --design-system --persist --preview -p "Project Name" --output-dir "" +``` + +`--preview` is valid only with `--design-system`. With `--persist` it writes `design-system//preview.html` next to `MASTER.md`. Without `--persist`, pass `--output-dir` to write `preview.html` there, or omit it to get a temp file whose path is printed. Existing `preview.html` files are skipped unless `--force` is set, same as Master. + If Master already exists, a new page file is created without changing Master. Existing Master and page files are skipped by default. Read an existing `MASTER.md` before deciding whether `--force` is justified; without explicit user authorization, keep existing files unchanged. **How hierarchical retrieval works:** diff --git a/cli/tests/e2e/template-script-paths.spec.ts b/cli/tests/e2e/template-script-paths.spec.ts index 7156153..1b4157f 100644 --- a/cli/tests/e2e/template-script-paths.spec.ts +++ b/cli/tests/e2e/template-script-paths.spec.ts @@ -11,7 +11,7 @@ const cases = [ ['amazonq', '.amazonq/skills/ui-ux-pro-max/scripts/search.py'], ['openclaw', '.agents/skills/ui-ux-pro-max/scripts/search.py'], ] as const; -const SEARCH_COMMAND_COUNT = 17; +const SEARCH_COMMAND_COUNT = 18; function extractSearchScriptPaths(content: string): string[] { return [...content.matchAll(/^python3\s+(\S*search\.py)\b/gm)].map(match => match[1]); diff --git a/scripts/validate-agent-guide.py b/scripts/validate-agent-guide.py index aaa51ff..49baf8f 100644 --- a/scripts/validate-agent-guide.py +++ b/scripts/validate-agent-guide.py @@ -25,7 +25,7 @@ DOMAINS = { FLAGS = { "--domain", "-d", "--stack", "-s", "--max-results", "-n", "--json", "--full", "--design-system", "-ds", "--project-name", "-p", "--format", - "-f", "--persist", "--page", "--output-dir", "-o", "--force", + "-f", "--persist", "--page", "--output-dir", "-o", "--force", "--preview", "--variance", "--motion", "--density", } PLATFORM_COUNT = 25 diff --git a/src/ui-ux-pro-max/scripts/design_system.py b/src/ui-ux-pro-max/scripts/design_system.py index d5fe157..e923c3f 100644 --- a/src/ui-ux-pro-max/scripts/design_system.py +++ b/src/ui-ux-pro-max/scripts/design_system.py @@ -612,6 +612,7 @@ class DesignSystemGenerator: "typography": best_typography.get("Font Pairing Name"), "landing": best_landing.get("Pattern Name"), }, + "color_mode": color_mode, "source_derivations": { "color_mode": best_color.get("_mode_derivation"), }, @@ -944,7 +945,7 @@ def format_markdown(design_system: dict) -> str: def generate_design_system(query: str, project_name: str = None, output_format: str = "ascii", persist: bool = False, page: str = None, output_dir: str = None, variance: int = None, motion: int = None, density: int = None, - force: bool = False) -> dict: + force: bool = False, preview: bool = False) -> dict: """ Main entry point for design system generation. @@ -960,11 +961,13 @@ def generate_design_system(query: str, project_name: str = None, output_format: density: Optional 1-10 VISUAL_DENSITY dial, overrides the spacing scale (1=spacious, 10=dense) force: If True, overwrite an existing MASTER.md; otherwise persistence is skipped (with a status message) when one already exists + preview: If True, write a self-contained preview.html of this system Returns: dict with keys: "text" (formatted design system string), "design_system" - (raw dict, useful for --json callers), and "persistence" (result of - persist_design_system(), or None if persist=False) + (raw dict, useful for --json callers), "persistence" (result of + persist_design_system(), or None if persist=False), and "preview" + (result of write_preview_html(), or None if preview=False) """ generator = DesignSystemGenerator() design_system = generator.generate(query, project_name, variance=variance, motion=motion, density=density) @@ -973,12 +976,20 @@ def generate_design_system(query: str, project_name: str = None, output_format: if persist: persistence_result = persist_design_system(design_system, page, output_dir, query, force=force) + preview_result = None + if preview: + from preview import write_preview_html + preview_result = write_preview_html( + design_system, persist=persist, output_dir=output_dir, force=force + ) + text = format_markdown(design_system) if output_format == "markdown" else format_ascii_box(design_system) return { "text": text, "design_system": design_system, "persistence": persistence_result, + "preview": preview_result, } diff --git a/src/ui-ux-pro-max/scripts/preview.py b/src/ui-ux-pro-max/scripts/preview.py new file mode 100644 index 0000000..9f61882 --- /dev/null +++ b/src/ui-ux-pro-max/scripts/preview.py @@ -0,0 +1,543 @@ +#!/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} +
      + {swatches_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

    +
      + {anti_html} +
    +
    +
    + + +""" + + +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)], + } diff --git a/src/ui-ux-pro-max/scripts/search.py b/src/ui-ux-pro-max/scripts/search.py index 9ce5e40..9036ff6 100644 --- a/src/ui-ux-pro-max/scripts/search.py +++ b/src/ui-ux-pro-max/scripts/search.py @@ -5,6 +5,7 @@ UI/UX Pro Max Search - BM25 search engine for UI/UX style guides Usage: python search.py "" [--domain ] [--stack ] [--max-results 3] python search.py "" --design-system [-p "Project Name"] python search.py "" --design-system --persist [-p "Project Name"] --output-dir "" [--page "dashboard"] + python search.py "" --design-system --persist --preview [-p "Project Name"] --output-dir "" python search.py "" --design-system --variance 8 --motion 9 --density 7 Domains: style, color, chart, landing, product, ux, typography, google-fonts, icons, gsap, react, web @@ -23,6 +24,9 @@ Persistence (Master + Overrides pattern): --page Also create a page-specific override file in design-system//pages/ --force Overwrite an existing MASTER.md (without this, persistence is skipped if MASTER.md already exists, so prior design decisions aren't lost) + --preview Write preview.html for the generated system (requires --design-system). + With --persist, the file is written next to MASTER.md. Without --persist, + it is written to --output-dir or to a temp file whose path is printed. """ import argparse @@ -122,6 +126,7 @@ if __name__ == "__main__": parser.add_argument("--page", type=str, default=None, help="Create page-specific override file in design-system//pages/") parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory -- pass this explicitly, pointed at the project root)") parser.add_argument("--force", action="store_true", help="Overwrite an existing MASTER.md when persisting (default: skip if it already exists)") + parser.add_argument("--preview", action="store_true", help="Write a self-contained preview.html of the generated design system (requires --design-system)") # Design dials (1-10), only applied with --design-system parser.add_argument("--variance", type=int, choices=range(1, 11), metavar="1-10", help="DESIGN_VARIANCE dial: 1=centered/minimal, 10=bold/asymmetric (only with --design-system)") parser.add_argument("--motion", type=int, choices=range(1, 11), metavar="1-10", help="MOTION_INTENSITY dial: 1=subtle, 10=complex; pulls a matching GSAP snippet from motion.csv (only with --design-system)") @@ -129,6 +134,9 @@ if __name__ == "__main__": args = parser.parse_args() + if args.preview and not args.design_system: + parser.error("--preview requires --design-system") + # Design system takes priority if args.design_system: if args.rtl is not None: @@ -153,13 +161,17 @@ if __name__ == "__main__": motion=args.motion, density=args.density, force=args.force, + preview=args.preview, ) if args.json: - print(json_module.dumps( - {"design_system": result["design_system"], "persistence": result["persistence"]}, - indent=2, ensure_ascii=False, - )) + payload = { + "design_system": result["design_system"], + "persistence": result["persistence"], + } + if args.preview: + payload["preview"] = result["preview"] + print(json_module.dumps(payload, indent=2, ensure_ascii=False)) else: print(result["text"]) @@ -177,6 +189,15 @@ if __name__ == "__main__": print(f"📖 Usage: When building a page, check {ds_dir}/pages/[page].md first.") print(" If it exists, its rules override MASTER.md. Otherwise, use MASTER.md.") print("=" * 60) + + if args.preview: + preview = result["preview"] or {} + print("\n" + "=" * 60) + if preview.get("status") == "skipped_exists": + print(f"⚠️ {preview.get('message', 'preview.html already exists; not overwritten.')}") + else: + print(f"✅ Design system preview: {preview.get('preview_file')}") + print("=" * 60) # Stack search elif args.stack: if args.rtl is not None: diff --git a/src/ui-ux-pro-max/scripts/tests/fixtures/relevance-thresholds.json b/src/ui-ux-pro-max/scripts/tests/fixtures/relevance-thresholds.json index c4ded1a..bdbeb02 100644 --- a/src/ui-ux-pro-max/scripts/tests/fixtures/relevance-thresholds.json +++ b/src/ui-ux-pro-max/scripts/tests/fixtures/relevance-thresholds.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "status": "provisional-baseline-regression-gate", "baselineRevision": "97eb2a2", - "runtimeFingerprint": "b5d3f2964bf5e55edafb253387b468e69a5ad0ee4c456ed295850819429d6168", + "runtimeFingerprint": "d0cb5803e094c21dc5262770f4a2dd8cecd20abf702896eea6ec69c357c54648", "oracleFingerprint": "02e7226428c64a995ec24ae104ce4d186f5f91bf0f062556e90ef9b0fcb6d67a", "approvingMaintainer": "repository maintainer approved Phase 1 testing checkpoint; second judgment review remains required before final-target promotion", "units": "All metrics are ratios in [0,1]. Precision treats missing ranks as non-relevant. Negative abstention is measured across the hard-negative by domain/stack cross-product.", diff --git a/src/ui-ux-pro-max/scripts/tests/test_design_system_preview.py b/src/ui-ux-pro-max/scripts/tests/test_design_system_preview.py new file mode 100644 index 0000000..219dddc --- /dev/null +++ b/src/ui-ux-pro-max/scripts/tests/test_design_system_preview.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Tests for --preview HTML output of the design system generator. + +Stdlib-only (unittest, not pytest) to match test_core.py. + +Run with: + python -m unittest discover -s scripts/tests -v +or directly: + python scripts/tests/test_design_system_preview.py +""" + +import json +import subprocess +import sys +import tempfile +import unittest +from html import escape +from html.parser import HTMLParser +from pathlib import Path + +SCRIPTS_DIR = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(SCRIPTS_DIR)) + +from design_system import ( # noqa: E402 + SEMANTIC_COLOR_ENTRIES, + _contrast_ratio, + _palette_is_dark, + generate_design_system, +) +from preview import format_preview_html, write_preview_html # noqa: E402 + +SEARCH = SCRIPTS_DIR / "search.py" +HOSTILE_NAME = '' +DARK_QUERY = "SaaS invoicing fintech B2B professional dark mode" + + +class _TagCollector(HTMLParser): + def __init__(self): + super().__init__() + self.tags = [] + self.text = [] + + def handle_starttag(self, tag, attrs): + self.tags.append((tag, dict(attrs))) + + def handle_data(self, data): + self.text.append(data) + + +def _parse(html): + parser = _TagCollector() + parser.feed(html) + return parser + + +def _run_search(*args): + return subprocess.run( + [sys.executable, str(SEARCH), *map(str, args)], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + ) + + +class TestPreviewStructure(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.result = generate_design_system("fintech dashboard", "Ledger") + cls.ds = cls.result["design_system"] + cls.html = format_preview_html(cls.ds) + cls.parsed = _parse(cls.html) + + def test_lang_landmark_and_labels(self): + html_tag = next(attrs for tag, attrs in self.parsed.tags if tag == "html") + self.assertEqual(html_tag.get("lang"), "en") + tags = [tag for tag, _attrs in self.parsed.tags] + self.assertIn("main", tags) + self.assertIn("header", tags) + labels = [attrs for tag, attrs in self.parsed.tags if tag == "label"] + inputs = [attrs for tag, attrs in self.parsed.tags if tag == "input"] + self.assertGreaterEqual(len(labels), 2) + self.assertGreaterEqual(len(inputs), 2) + for attrs in inputs: + self.assertTrue(attrs.get("id"), attrs) + matching = [label for label in labels if label.get("for") == attrs["id"]] + self.assertTrue(matching, attrs) + + def test_palette_swatches_cover_every_present_role(self): + for label, key, _css_var in SEMANTIC_COLOR_ENTRIES: + hex_val = self.ds["colors"].get(key, "") + if hex_val: + self.assertIn(hex_val, self.html) + self.assertIn(label, self.html) + + def test_type_buttons_card_form_style_and_anti_patterns(self): + self.assertIn(self.ds["typography"]["heading"], self.html) + self.assertIn(self.ds["typography"]["body"], self.html) + self.assertIn("btn-primary", self.html) + self.assertIn("btn-secondary", self.html) + self.assertIn("btn-accent", self.html) + self.assertIn("btn-destructive", self.html) + self.assertIn("is-hover", self.html) + self.assertIn("is-focus", self.html) + self.assertIn("disabled", self.html) + self.assertIn("preview-card", self.html) + self.assertIn("aria-invalid", self.html) + self.assertIn(self.ds["style"]["name"], self.html) + self.assertIn("prefers-reduced-motion", self.html) + self.assertIn(":focus-visible", self.html) + if self.ds["key_effects"]: + self.assertIn(self.ds["key_effects"].split("+")[0].strip()[:20], self.html) + for clause in self.ds["anti_patterns"].split("+"): + clause = clause.strip() + if clause: + self.assertIn(clause, self.html) + + def test_google_fonts_link_when_pairing_has_a_url(self): + url = self.ds["typography"].get("google_fonts_url") or "" + if url: + self.assertIn(escape(url, quote=True), self.html) + self.assertIn('rel="stylesheet"', self.html) + self.assertIn("system-ui", self.html) + + +class TestPreviewEscaping(unittest.TestCase): + def test_hostile_project_name_is_escaped(self): + ds = generate_design_system("kids education app", HOSTILE_NAME)["design_system"] + html = format_preview_html(ds) + self.assertNotIn("", html) + self.assertIn("<script>alert(1)</script>", html) + self.assertIn("alert(1)", html) + self.assertIn("<script>alert(1)</script>", html) + + +class TestPreviewContrast(unittest.TestCase): + def test_printed_ratios_match_generator(self): + ds = generate_design_system("fintech dashboard", "Ledger")["design_system"] + html = format_preview_html(ds) + pairs = ( + ("primary", "on_primary"), + ("secondary", "on_secondary"), + ("accent", "on_accent"), + ("background", "foreground"), + ("card", "card_foreground"), + ("muted", "muted_foreground"), + ("destructive", "on_destructive"), + ) + for surface, on in pairs: + ratio = _contrast_ratio(ds["colors"][surface], ds["colors"][on]) + self.assertIsNotNone(ratio) + self.assertIn(f"{ratio:.2f}:1", html) + level = "AAA" if ratio >= 7 else "AA" if ratio >= 4.5 else "Fail" + self.assertIn(level, html) + + +class TestPreviewDarkMode(unittest.TestCase): + def test_dark_system_renders_on_its_dark_surfaces(self): + ds = generate_design_system(DARK_QUERY, "Night Ledger")["design_system"] + self.assertEqual(ds["color_mode"], "dark") + self.assertTrue(_palette_is_dark({"Background": ds["colors"]["background"]})) + html = format_preview_html(ds) + self.assertIn(f'background: {ds["colors"]["background"]}', html) + self.assertIn(f'color: {ds["colors"]["foreground"]}', html) + self.assertIn('content="dark"', html) + + +class TestPreviewCli(unittest.TestCase): + def test_preview_without_design_system_errors(self): + proc = _run_search("fintech dashboard", "--preview") + self.assertNotEqual(proc.returncode, 0) + self.assertIn("--design-system", proc.stderr) + + def test_preview_with_persist_writes_next_to_master(self): + with tempfile.TemporaryDirectory() as tmp: + proc = _run_search( + "fintech dashboard", "--design-system", "--persist", "--preview", + "--project-name", "Ledger", "--output-dir", tmp, "--json", + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + payload = json.loads(proc.stdout) + preview = Path(payload["preview"]["preview_file"]) + master = Path(payload["persistence"]["master_file"]) + self.assertEqual(preview.parent, master.parent) + self.assertEqual(preview.name, "preview.html") + self.assertTrue(preview.exists()) + self.assertTrue(master.exists()) + + def test_preview_without_persist_uses_output_dir(self): + with tempfile.TemporaryDirectory() as tmp: + proc = _run_search( + "fintech dashboard", "--design-system", "--preview", + "--project-name", "Ledger", "--output-dir", tmp, "--json", + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + payload = json.loads(proc.stdout) + preview = Path(payload["preview"]["preview_file"]) + self.assertEqual(preview, Path(tmp) / "preview.html") + self.assertTrue(preview.exists()) + self.assertFalse((Path(tmp) / "design-system").exists()) + + def test_preview_without_output_dir_uses_temp_file(self): + proc = _run_search( + "fintech dashboard", "--design-system", "--preview", + "--project-name", "Temp Ledger", "--json", + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + payload = json.loads(proc.stdout) + preview = Path(payload["preview"]["preview_file"]) + self.assertTrue(preview.exists()) + self.assertTrue(preview.name.startswith("design-system-preview-")) + preview.unlink() + + def test_preview_respects_force(self): + with tempfile.TemporaryDirectory() as tmp: + first = write_preview_html( + generate_design_system("fintech dashboard", "Ledger")["design_system"], + output_dir=tmp, + ) + path = Path(first["preview_file"]) + path.write_text("stale", encoding="utf-8") + skipped = write_preview_html( + generate_design_system("fintech dashboard", "Ledger")["design_system"], + output_dir=tmp, + ) + self.assertEqual(skipped["status"], "skipped_exists") + self.assertEqual(path.read_text(encoding="utf-8"), "stale") + overwritten = write_preview_html( + generate_design_system("fintech dashboard", "Ledger")["design_system"], + output_dir=tmp, force=True, + ) + self.assertEqual(overwritten["status"], "success") + self.assertIn("" --design-system --persist -p "Project Name" -- This also creates: - `design-system//pages/dashboard.md` — Page-specific deviations from Master +**Preview the generated system as a static page:** + +```bash +python3 {{SCRIPT_PATH}} "" --design-system --persist --preview -p "Project Name" --output-dir "" +``` + +`--preview` is valid only with `--design-system`. With `--persist` it writes `design-system//preview.html` next to `MASTER.md`. Without `--persist`, pass `--output-dir` to write `preview.html` there, or omit it to get a temp file whose path is printed. Existing `preview.html` files are skipped unless `--force` is set, same as Master. + If Master already exists, a new page file is created without changing Master. Existing Master and page files are skipped by default. Read an existing `MASTER.md` before deciding whether `--force` is justified; without explicit user authorization, keep existing files unchanged. **How hierarchical retrieval works:**