mirror of
https://github.com/nextlevelbuilder/ui-ux-pro-max-skill.git
synced 2026-11-19 09:00:32 +00:00
feat(design-system): write a self-contained preview page for the generated system (#576)
This commit is contained in:
parent
0e8d408204
commit
efd9822135
@ -101,6 +101,14 @@ This creates:
|
||||
|
||||
With a page-specific override, add `--page "dashboard"` to also create `design-system/<project-slug>/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" "<query>" --design-system --persist --preview -p "Project Name" --output-dir "<project-root>"
|
||||
```
|
||||
|
||||
With `--persist`, this writes `design-system/<project-slug>/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/<project-slug>/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.
|
||||
|
||||
@ -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,
|
||||
}
|
||||
|
||||
|
||||
|
||||
543
.claude/skills/ui-ux-pro-max/scripts/preview.py
Normal file
543
.claude/skills/ui-ux-pro-max/scripts/preview.py
Normal file
@ -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'<p class="swatch-contrast">vs {_text(pair_label)} '
|
||||
f'<code>{_text(pair_hex)}</code>: {_text(_format_ratio(ratio))} '
|
||||
f'<span class="badge {badge_class}">{_text(level)}</span></p>'
|
||||
)
|
||||
swatches.append(
|
||||
f'<li class="swatch">'
|
||||
f'<div class="swatch-chip" style="background:{hex_val}" aria-hidden="true"></div>'
|
||||
f'<div class="swatch-meta">'
|
||||
f'<p class="swatch-role">{_text(label)}</p>'
|
||||
f'<p><code>{_text(hex_val)}</code> <code>{_text(css_var)}</code></p>'
|
||||
f'{ratio_html}'
|
||||
f'</div></li>'
|
||||
)
|
||||
|
||||
anti_items = []
|
||||
for clause in (anti_patterns.split("+") if anti_patterns else []):
|
||||
clause = clause.strip()
|
||||
if clause:
|
||||
anti_items.append(f"<li>{_text(clause)}</li>")
|
||||
if not anti_items:
|
||||
anti_items.append("<li>None listed for this system.</li>")
|
||||
|
||||
font_links = ""
|
||||
if google_href:
|
||||
font_links = (
|
||||
' <link rel="preconnect" href="https://fonts.googleapis.com">\n'
|
||||
' <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>\n'
|
||||
f' <link rel="stylesheet" href="{google_href}">\n'
|
||||
)
|
||||
|
||||
color_scheme = "dark" if dark else "light"
|
||||
notes_html = (
|
||||
f'<p class="notes">{_text(notes)}</p>' 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"""<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="{color_scheme}">
|
||||
<title>{_attr(project)} design system preview</title>
|
||||
{font_links} <style>
|
||||
:root {{
|
||||
{css_vars_block}
|
||||
--font-heading: {heading_stack};
|
||||
--font-body: {body_stack};
|
||||
}}
|
||||
*, *::before, *::after {{ box-sizing: border-box; }}
|
||||
html {{ font-size: 16px; }}
|
||||
body {{
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
font-family: var(--font-body);
|
||||
background: {background};
|
||||
color: {foreground};
|
||||
line-height: 1.5;
|
||||
}}
|
||||
a:focus-visible,
|
||||
button:focus-visible,
|
||||
input:focus-visible {{
|
||||
outline: 3px solid {ring};
|
||||
outline-offset: 2px;
|
||||
}}
|
||||
header, main {{
|
||||
width: min(1100px, calc(100% - 2rem));
|
||||
margin-inline: auto;
|
||||
}}
|
||||
header {{
|
||||
padding: 2.5rem 0 1.5rem;
|
||||
border-bottom: 1px solid {border};
|
||||
}}
|
||||
.eyebrow {{
|
||||
margin: 0 0 0.35rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
font-size: 0.75rem;
|
||||
color: {muted_fg};
|
||||
}}
|
||||
h1, h2, h3, .specimen-heading {{
|
||||
font-family: var(--font-heading);
|
||||
line-height: 1.2;
|
||||
margin: 0 0 0.5rem;
|
||||
}}
|
||||
h1 {{ font-size: 2.25rem; }}
|
||||
h2 {{ font-size: 1.5rem; }}
|
||||
h3 {{ font-size: 1.2rem; }}
|
||||
main {{ padding: 2rem 0 4rem; display: grid; gap: 2.5rem; }}
|
||||
section {{
|
||||
background: {card};
|
||||
color: {card_fg};
|
||||
border: 1px solid {border};
|
||||
border-radius: 12px;
|
||||
padding: 1.5rem;
|
||||
}}
|
||||
.swatches {{
|
||||
list-style: none;
|
||||
margin: 1rem 0 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
||||
}}
|
||||
.swatch {{
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
align-items: flex-start;
|
||||
}}
|
||||
.swatch-chip {{
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid {border};
|
||||
flex-shrink: 0;
|
||||
}}
|
||||
.swatch-meta p {{ margin: 0; font-size: 0.9rem; }}
|
||||
.swatch-role {{ font-weight: 600; }}
|
||||
.swatch-contrast {{ color: {muted_fg}; }}
|
||||
code {{ font-size: 0.85em; }}
|
||||
.badge {{
|
||||
display: inline-block;
|
||||
margin-left: 0.35rem;
|
||||
padding: 0.05rem 0.4rem;
|
||||
border-radius: 999px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
}}
|
||||
.badge-aaa {{ background: {primary}; color: {on_primary}; }}
|
||||
.badge-aa {{ background: {muted}; color: {muted_fg}; }}
|
||||
.badge-fail {{ background: {destructive}; color: {on_destructive}; }}
|
||||
.type-scale {{ display: grid; gap: 0.75rem; }}
|
||||
.type-scale p {{ margin: 0; max-width: 42rem; }}
|
||||
.btn-row {{
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
margin: 0.75rem 0;
|
||||
}}
|
||||
.btn {{
|
||||
font-family: var(--font-body);
|
||||
font-weight: 600;
|
||||
font-size: 1rem;
|
||||
padding: 12px 24px;
|
||||
border-radius: 8px;
|
||||
border: 2px solid transparent;
|
||||
cursor: pointer;
|
||||
transition: opacity 200ms ease, transform 200ms ease, box-shadow 200ms ease;
|
||||
}}
|
||||
.btn-primary {{ background: {primary}; color: {on_primary}; }}
|
||||
.btn-secondary {{
|
||||
background: transparent;
|
||||
color: {secondary_text};
|
||||
border-color: {secondary};
|
||||
}}
|
||||
.btn-accent {{ background: {accent}; color: {on_accent}; }}
|
||||
.btn-destructive {{ background: {destructive}; color: {on_destructive}; }}
|
||||
.btn:hover, .btn.is-hover {{
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.18);
|
||||
transform: translateY(-1px);
|
||||
}}
|
||||
.btn:focus-visible, .btn.is-focus {{
|
||||
outline: 3px solid {ring};
|
||||
outline-offset: 2px;
|
||||
}}
|
||||
.btn:disabled, .btn.is-disabled {{
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}}
|
||||
.state-label {{
|
||||
font-size: 0.8rem;
|
||||
color: {muted_fg};
|
||||
margin: 0.25rem 0 0;
|
||||
}}
|
||||
.preview-card {{
|
||||
background: {card};
|
||||
color: {card_fg};
|
||||
border: 1px solid {border};
|
||||
border-radius: 12px;
|
||||
padding: 1.5rem;
|
||||
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
|
||||
max-width: 28rem;
|
||||
}}
|
||||
.field {{ display: grid; gap: 0.35rem; max-width: 28rem; }}
|
||||
.field + .field {{ margin-top: 1rem; }}
|
||||
label {{ font-weight: 600; }}
|
||||
input[type="text"], input[type="email"] {{
|
||||
font: inherit;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid {border};
|
||||
border-radius: 8px;
|
||||
background: {background};
|
||||
color: {foreground};
|
||||
}}
|
||||
input[aria-invalid="true"] {{
|
||||
border-color: {destructive};
|
||||
}}
|
||||
.help {{ margin: 0; color: {muted_fg}; font-size: 0.9rem; }}
|
||||
.error {{
|
||||
margin: 0;
|
||||
color: {on_destructive};
|
||||
background: {destructive};
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
padding: 0.4rem 0.6rem;
|
||||
border-radius: 6px;
|
||||
}}
|
||||
.notes {{ color: {muted_fg}; }}
|
||||
@media (prefers-reduced-motion: reduce) {{
|
||||
*, *::before, *::after {{
|
||||
animation: none !important;
|
||||
transition: none !important;
|
||||
scroll-behavior: auto !important;
|
||||
}}
|
||||
.btn:hover, .btn.is-hover {{ transform: none; }}
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<p class="eyebrow">Design system preview</p>
|
||||
<h1>{_text(project)}</h1>
|
||||
<p>{_text(style.get("name") or "Unspecified style")}{_text(" · " + category if category else "")}</p>
|
||||
</header>
|
||||
<main>
|
||||
<section aria-labelledby="palette-heading">
|
||||
<h2 id="palette-heading">Palette</h2>
|
||||
{notes_html}
|
||||
<ul class="swatches">
|
||||
{swatches_html}
|
||||
</ul>
|
||||
</section>
|
||||
<section aria-labelledby="type-heading">
|
||||
<h2 id="type-heading">Typography</h2>
|
||||
<p class="help">Heading: {_text(heading_font)} · Body: {_text(body_font)}</p>
|
||||
<div class="type-scale">
|
||||
<p class="specimen-heading" style="font-size:2.5rem">Display · {_text(heading_font)}</p>
|
||||
<h3>Heading 2 · {_text(heading_font)}</h3>
|
||||
<p>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.</p>
|
||||
</div>
|
||||
</section>
|
||||
<section aria-labelledby="buttons-heading">
|
||||
<h2 id="buttons-heading">Buttons</h2>
|
||||
<p class="state-label">Default</p>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary" type="button">Primary</button>
|
||||
<button class="btn btn-secondary" type="button">Secondary</button>
|
||||
<button class="btn btn-accent" type="button">Accent</button>
|
||||
<button class="btn btn-destructive" type="button">Destructive</button>
|
||||
</div>
|
||||
<p class="state-label">Hover</p>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary is-hover" type="button">Primary</button>
|
||||
<button class="btn btn-secondary is-hover" type="button">Secondary</button>
|
||||
<button class="btn btn-accent is-hover" type="button">Accent</button>
|
||||
<button class="btn btn-destructive is-hover" type="button">Destructive</button>
|
||||
</div>
|
||||
<p class="state-label">Focus-visible</p>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary is-focus" type="button">Primary</button>
|
||||
<button class="btn btn-secondary is-focus" type="button">Secondary</button>
|
||||
<button class="btn btn-accent is-focus" type="button">Accent</button>
|
||||
<button class="btn btn-destructive is-focus" type="button">Destructive</button>
|
||||
</div>
|
||||
<p class="state-label">Disabled</p>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary" type="button" disabled>Primary</button>
|
||||
<button class="btn btn-secondary" type="button" disabled>Secondary</button>
|
||||
<button class="btn btn-accent" type="button" disabled>Accent</button>
|
||||
<button class="btn btn-destructive" type="button" disabled>Destructive</button>
|
||||
</div>
|
||||
</section>
|
||||
<section aria-labelledby="card-heading">
|
||||
<h2 id="card-heading">Card</h2>
|
||||
<article class="preview-card">
|
||||
<h3>{_text(project)}</h3>
|
||||
<p>A sample card using the generated card surface, border, and type pairing.</p>
|
||||
<button class="btn btn-primary" type="button">Continue</button>
|
||||
</article>
|
||||
</section>
|
||||
<section aria-labelledby="form-heading">
|
||||
<h2 id="form-heading">Form</h2>
|
||||
<form>
|
||||
<div class="field">
|
||||
<label for="preview-email">Email</label>
|
||||
<input id="preview-email" name="email" type="email" autocomplete="email" aria-describedby="preview-email-help">
|
||||
<p id="preview-email-help" class="help">Use your work address.</p>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="preview-name">Display name</label>
|
||||
<input id="preview-name" name="name" type="text" value="Not a valid value" aria-invalid="true" aria-describedby="preview-name-error">
|
||||
<p id="preview-name-error" class="error">Enter a display name of at least two characters.</p>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
<section aria-labelledby="style-heading">
|
||||
<h2 id="style-heading">Style, effects, anti-patterns</h2>
|
||||
<p><strong>Style:</strong> {_text(style.get("name") or "")}</p>
|
||||
<p><strong>Key effects:</strong> {effects_html}</p>
|
||||
<h3>Anti-patterns</h3>
|
||||
<ul>
|
||||
{anti_html}
|
||||
</ul>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</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/<slug>/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)],
|
||||
}
|
||||
@ -5,6 +5,7 @@ UI/UX Pro Max Search - BM25 search engine for UI/UX style guides
|
||||
Usage: python search.py "<query>" [--domain <domain>] [--stack <stack>] [--max-results 3]
|
||||
python search.py "<query>" --design-system [-p "Project Name"]
|
||||
python search.py "<query>" --design-system --persist [-p "Project Name"] --output-dir "<project-root>" [--page "dashboard"]
|
||||
python search.py "<query>" --design-system --persist --preview [-p "Project Name"] --output-dir "<project-root>"
|
||||
python search.py "<query>" --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/<project-slug>/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/<project-slug>/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:
|
||||
|
||||
@ -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.",
|
||||
|
||||
@ -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 = '<script>alert(1)</script>'
|
||||
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("<script>alert(1)</script>", html)
|
||||
self.assertIn("<script>alert(1)</script>", html)
|
||||
self.assertIn("<html lang=", html)
|
||||
|
||||
def test_cli_hostile_project_name_is_escaped(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
proc = _run_search(
|
||||
"kids education app", "--design-system", "--preview",
|
||||
"--project-name", HOSTILE_NAME, "--output-dir", tmp, "--json",
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
payload = json.loads(proc.stdout)
|
||||
path = Path(payload["preview"]["preview_file"])
|
||||
html = path.read_text(encoding="utf-8")
|
||||
self.assertNotIn("<script>alert(1)</script>", 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("<html lang=", path.read_text(encoding="utf-8"))
|
||||
|
||||
def test_preview_still_writes_when_master_already_exists(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
generate_design_system(
|
||||
"fintech dashboard", "Ledger", persist=True, output_dir=tmp
|
||||
)
|
||||
result = generate_design_system(
|
||||
"fintech dashboard", "Ledger", persist=True, preview=True, output_dir=tmp
|
||||
)
|
||||
self.assertEqual(result["persistence"]["status"], "skipped_exists")
|
||||
self.assertEqual(result["preview"]["status"], "success")
|
||||
self.assertTrue(Path(result["preview"]["preview_file"]).exists())
|
||||
|
||||
|
||||
class TestPreviewNoScriptInjectionInCss(unittest.TestCase):
|
||||
def test_invalid_hex_is_not_emitted_as_css_color(self):
|
||||
ds = generate_design_system("fintech dashboard", "Ledger")["design_system"]
|
||||
ds = dict(ds)
|
||||
ds["colors"] = dict(ds["colors"])
|
||||
ds["colors"]["primary"] = "red; } body { background: url(javascript:alert(1))"
|
||||
html = format_preview_html(ds)
|
||||
self.assertNotIn("javascript:alert", html)
|
||||
self.assertNotIn("red; } body", html)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@ -30,6 +30,7 @@ python3 src/ui-ux-pro-max/scripts/search.py "<query>" --domain <domain> [-n <max
|
||||
```bash
|
||||
python3 src/ui-ux-pro-max/scripts/search.py "<query>" --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):**
|
||||
|
||||
@ -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)
|
||||
```
|
||||
|
||||
@ -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,
|
||||
}
|
||||
|
||||
|
||||
|
||||
543
cli/assets/scripts/preview.py
Normal file
543
cli/assets/scripts/preview.py
Normal file
@ -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'<p class="swatch-contrast">vs {_text(pair_label)} '
|
||||
f'<code>{_text(pair_hex)}</code>: {_text(_format_ratio(ratio))} '
|
||||
f'<span class="badge {badge_class}">{_text(level)}</span></p>'
|
||||
)
|
||||
swatches.append(
|
||||
f'<li class="swatch">'
|
||||
f'<div class="swatch-chip" style="background:{hex_val}" aria-hidden="true"></div>'
|
||||
f'<div class="swatch-meta">'
|
||||
f'<p class="swatch-role">{_text(label)}</p>'
|
||||
f'<p><code>{_text(hex_val)}</code> <code>{_text(css_var)}</code></p>'
|
||||
f'{ratio_html}'
|
||||
f'</div></li>'
|
||||
)
|
||||
|
||||
anti_items = []
|
||||
for clause in (anti_patterns.split("+") if anti_patterns else []):
|
||||
clause = clause.strip()
|
||||
if clause:
|
||||
anti_items.append(f"<li>{_text(clause)}</li>")
|
||||
if not anti_items:
|
||||
anti_items.append("<li>None listed for this system.</li>")
|
||||
|
||||
font_links = ""
|
||||
if google_href:
|
||||
font_links = (
|
||||
' <link rel="preconnect" href="https://fonts.googleapis.com">\n'
|
||||
' <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>\n'
|
||||
f' <link rel="stylesheet" href="{google_href}">\n'
|
||||
)
|
||||
|
||||
color_scheme = "dark" if dark else "light"
|
||||
notes_html = (
|
||||
f'<p class="notes">{_text(notes)}</p>' 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"""<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="{color_scheme}">
|
||||
<title>{_attr(project)} design system preview</title>
|
||||
{font_links} <style>
|
||||
:root {{
|
||||
{css_vars_block}
|
||||
--font-heading: {heading_stack};
|
||||
--font-body: {body_stack};
|
||||
}}
|
||||
*, *::before, *::after {{ box-sizing: border-box; }}
|
||||
html {{ font-size: 16px; }}
|
||||
body {{
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
font-family: var(--font-body);
|
||||
background: {background};
|
||||
color: {foreground};
|
||||
line-height: 1.5;
|
||||
}}
|
||||
a:focus-visible,
|
||||
button:focus-visible,
|
||||
input:focus-visible {{
|
||||
outline: 3px solid {ring};
|
||||
outline-offset: 2px;
|
||||
}}
|
||||
header, main {{
|
||||
width: min(1100px, calc(100% - 2rem));
|
||||
margin-inline: auto;
|
||||
}}
|
||||
header {{
|
||||
padding: 2.5rem 0 1.5rem;
|
||||
border-bottom: 1px solid {border};
|
||||
}}
|
||||
.eyebrow {{
|
||||
margin: 0 0 0.35rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
font-size: 0.75rem;
|
||||
color: {muted_fg};
|
||||
}}
|
||||
h1, h2, h3, .specimen-heading {{
|
||||
font-family: var(--font-heading);
|
||||
line-height: 1.2;
|
||||
margin: 0 0 0.5rem;
|
||||
}}
|
||||
h1 {{ font-size: 2.25rem; }}
|
||||
h2 {{ font-size: 1.5rem; }}
|
||||
h3 {{ font-size: 1.2rem; }}
|
||||
main {{ padding: 2rem 0 4rem; display: grid; gap: 2.5rem; }}
|
||||
section {{
|
||||
background: {card};
|
||||
color: {card_fg};
|
||||
border: 1px solid {border};
|
||||
border-radius: 12px;
|
||||
padding: 1.5rem;
|
||||
}}
|
||||
.swatches {{
|
||||
list-style: none;
|
||||
margin: 1rem 0 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
||||
}}
|
||||
.swatch {{
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
align-items: flex-start;
|
||||
}}
|
||||
.swatch-chip {{
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid {border};
|
||||
flex-shrink: 0;
|
||||
}}
|
||||
.swatch-meta p {{ margin: 0; font-size: 0.9rem; }}
|
||||
.swatch-role {{ font-weight: 600; }}
|
||||
.swatch-contrast {{ color: {muted_fg}; }}
|
||||
code {{ font-size: 0.85em; }}
|
||||
.badge {{
|
||||
display: inline-block;
|
||||
margin-left: 0.35rem;
|
||||
padding: 0.05rem 0.4rem;
|
||||
border-radius: 999px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
}}
|
||||
.badge-aaa {{ background: {primary}; color: {on_primary}; }}
|
||||
.badge-aa {{ background: {muted}; color: {muted_fg}; }}
|
||||
.badge-fail {{ background: {destructive}; color: {on_destructive}; }}
|
||||
.type-scale {{ display: grid; gap: 0.75rem; }}
|
||||
.type-scale p {{ margin: 0; max-width: 42rem; }}
|
||||
.btn-row {{
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
margin: 0.75rem 0;
|
||||
}}
|
||||
.btn {{
|
||||
font-family: var(--font-body);
|
||||
font-weight: 600;
|
||||
font-size: 1rem;
|
||||
padding: 12px 24px;
|
||||
border-radius: 8px;
|
||||
border: 2px solid transparent;
|
||||
cursor: pointer;
|
||||
transition: opacity 200ms ease, transform 200ms ease, box-shadow 200ms ease;
|
||||
}}
|
||||
.btn-primary {{ background: {primary}; color: {on_primary}; }}
|
||||
.btn-secondary {{
|
||||
background: transparent;
|
||||
color: {secondary_text};
|
||||
border-color: {secondary};
|
||||
}}
|
||||
.btn-accent {{ background: {accent}; color: {on_accent}; }}
|
||||
.btn-destructive {{ background: {destructive}; color: {on_destructive}; }}
|
||||
.btn:hover, .btn.is-hover {{
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.18);
|
||||
transform: translateY(-1px);
|
||||
}}
|
||||
.btn:focus-visible, .btn.is-focus {{
|
||||
outline: 3px solid {ring};
|
||||
outline-offset: 2px;
|
||||
}}
|
||||
.btn:disabled, .btn.is-disabled {{
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}}
|
||||
.state-label {{
|
||||
font-size: 0.8rem;
|
||||
color: {muted_fg};
|
||||
margin: 0.25rem 0 0;
|
||||
}}
|
||||
.preview-card {{
|
||||
background: {card};
|
||||
color: {card_fg};
|
||||
border: 1px solid {border};
|
||||
border-radius: 12px;
|
||||
padding: 1.5rem;
|
||||
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
|
||||
max-width: 28rem;
|
||||
}}
|
||||
.field {{ display: grid; gap: 0.35rem; max-width: 28rem; }}
|
||||
.field + .field {{ margin-top: 1rem; }}
|
||||
label {{ font-weight: 600; }}
|
||||
input[type="text"], input[type="email"] {{
|
||||
font: inherit;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid {border};
|
||||
border-radius: 8px;
|
||||
background: {background};
|
||||
color: {foreground};
|
||||
}}
|
||||
input[aria-invalid="true"] {{
|
||||
border-color: {destructive};
|
||||
}}
|
||||
.help {{ margin: 0; color: {muted_fg}; font-size: 0.9rem; }}
|
||||
.error {{
|
||||
margin: 0;
|
||||
color: {on_destructive};
|
||||
background: {destructive};
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
padding: 0.4rem 0.6rem;
|
||||
border-radius: 6px;
|
||||
}}
|
||||
.notes {{ color: {muted_fg}; }}
|
||||
@media (prefers-reduced-motion: reduce) {{
|
||||
*, *::before, *::after {{
|
||||
animation: none !important;
|
||||
transition: none !important;
|
||||
scroll-behavior: auto !important;
|
||||
}}
|
||||
.btn:hover, .btn.is-hover {{ transform: none; }}
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<p class="eyebrow">Design system preview</p>
|
||||
<h1>{_text(project)}</h1>
|
||||
<p>{_text(style.get("name") or "Unspecified style")}{_text(" · " + category if category else "")}</p>
|
||||
</header>
|
||||
<main>
|
||||
<section aria-labelledby="palette-heading">
|
||||
<h2 id="palette-heading">Palette</h2>
|
||||
{notes_html}
|
||||
<ul class="swatches">
|
||||
{swatches_html}
|
||||
</ul>
|
||||
</section>
|
||||
<section aria-labelledby="type-heading">
|
||||
<h2 id="type-heading">Typography</h2>
|
||||
<p class="help">Heading: {_text(heading_font)} · Body: {_text(body_font)}</p>
|
||||
<div class="type-scale">
|
||||
<p class="specimen-heading" style="font-size:2.5rem">Display · {_text(heading_font)}</p>
|
||||
<h3>Heading 2 · {_text(heading_font)}</h3>
|
||||
<p>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.</p>
|
||||
</div>
|
||||
</section>
|
||||
<section aria-labelledby="buttons-heading">
|
||||
<h2 id="buttons-heading">Buttons</h2>
|
||||
<p class="state-label">Default</p>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary" type="button">Primary</button>
|
||||
<button class="btn btn-secondary" type="button">Secondary</button>
|
||||
<button class="btn btn-accent" type="button">Accent</button>
|
||||
<button class="btn btn-destructive" type="button">Destructive</button>
|
||||
</div>
|
||||
<p class="state-label">Hover</p>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary is-hover" type="button">Primary</button>
|
||||
<button class="btn btn-secondary is-hover" type="button">Secondary</button>
|
||||
<button class="btn btn-accent is-hover" type="button">Accent</button>
|
||||
<button class="btn btn-destructive is-hover" type="button">Destructive</button>
|
||||
</div>
|
||||
<p class="state-label">Focus-visible</p>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary is-focus" type="button">Primary</button>
|
||||
<button class="btn btn-secondary is-focus" type="button">Secondary</button>
|
||||
<button class="btn btn-accent is-focus" type="button">Accent</button>
|
||||
<button class="btn btn-destructive is-focus" type="button">Destructive</button>
|
||||
</div>
|
||||
<p class="state-label">Disabled</p>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary" type="button" disabled>Primary</button>
|
||||
<button class="btn btn-secondary" type="button" disabled>Secondary</button>
|
||||
<button class="btn btn-accent" type="button" disabled>Accent</button>
|
||||
<button class="btn btn-destructive" type="button" disabled>Destructive</button>
|
||||
</div>
|
||||
</section>
|
||||
<section aria-labelledby="card-heading">
|
||||
<h2 id="card-heading">Card</h2>
|
||||
<article class="preview-card">
|
||||
<h3>{_text(project)}</h3>
|
||||
<p>A sample card using the generated card surface, border, and type pairing.</p>
|
||||
<button class="btn btn-primary" type="button">Continue</button>
|
||||
</article>
|
||||
</section>
|
||||
<section aria-labelledby="form-heading">
|
||||
<h2 id="form-heading">Form</h2>
|
||||
<form>
|
||||
<div class="field">
|
||||
<label for="preview-email">Email</label>
|
||||
<input id="preview-email" name="email" type="email" autocomplete="email" aria-describedby="preview-email-help">
|
||||
<p id="preview-email-help" class="help">Use your work address.</p>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="preview-name">Display name</label>
|
||||
<input id="preview-name" name="name" type="text" value="Not a valid value" aria-invalid="true" aria-describedby="preview-name-error">
|
||||
<p id="preview-name-error" class="error">Enter a display name of at least two characters.</p>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
<section aria-labelledby="style-heading">
|
||||
<h2 id="style-heading">Style, effects, anti-patterns</h2>
|
||||
<p><strong>Style:</strong> {_text(style.get("name") or "")}</p>
|
||||
<p><strong>Key effects:</strong> {effects_html}</p>
|
||||
<h3>Anti-patterns</h3>
|
||||
<ul>
|
||||
{anti_html}
|
||||
</ul>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</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/<slug>/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)],
|
||||
}
|
||||
@ -5,6 +5,7 @@ UI/UX Pro Max Search - BM25 search engine for UI/UX style guides
|
||||
Usage: python search.py "<query>" [--domain <domain>] [--stack <stack>] [--max-results 3]
|
||||
python search.py "<query>" --design-system [-p "Project Name"]
|
||||
python search.py "<query>" --design-system --persist [-p "Project Name"] --output-dir "<project-root>" [--page "dashboard"]
|
||||
python search.py "<query>" --design-system --persist --preview [-p "Project Name"] --output-dir "<project-root>"
|
||||
python search.py "<query>" --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/<project-slug>/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/<project-slug>/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:
|
||||
|
||||
@ -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.",
|
||||
|
||||
274
cli/assets/scripts/tests/test_design_system_preview.py
Normal file
274
cli/assets/scripts/tests/test_design_system_preview.py
Normal file
@ -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 = '<script>alert(1)</script>'
|
||||
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("<script>alert(1)</script>", html)
|
||||
self.assertIn("<script>alert(1)</script>", html)
|
||||
self.assertIn("<html lang=", html)
|
||||
|
||||
def test_cli_hostile_project_name_is_escaped(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
proc = _run_search(
|
||||
"kids education app", "--design-system", "--preview",
|
||||
"--project-name", HOSTILE_NAME, "--output-dir", tmp, "--json",
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
payload = json.loads(proc.stdout)
|
||||
path = Path(payload["preview"]["preview_file"])
|
||||
html = path.read_text(encoding="utf-8")
|
||||
self.assertNotIn("<script>alert(1)</script>", 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("<html lang=", path.read_text(encoding="utf-8"))
|
||||
|
||||
def test_preview_still_writes_when_master_already_exists(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
generate_design_system(
|
||||
"fintech dashboard", "Ledger", persist=True, output_dir=tmp
|
||||
)
|
||||
result = generate_design_system(
|
||||
"fintech dashboard", "Ledger", persist=True, preview=True, output_dir=tmp
|
||||
)
|
||||
self.assertEqual(result["persistence"]["status"], "skipped_exists")
|
||||
self.assertEqual(result["preview"]["status"], "success")
|
||||
self.assertTrue(Path(result["preview"]["preview_file"]).exists())
|
||||
|
||||
|
||||
class TestPreviewNoScriptInjectionInCss(unittest.TestCase):
|
||||
def test_invalid_hex_is_not_emitted_as_css_color(self):
|
||||
ds = generate_design_system("fintech dashboard", "Ledger")["design_system"]
|
||||
ds = dict(ds)
|
||||
ds["colors"] = dict(ds["colors"])
|
||||
ds["colors"]["primary"] = "red; } body { background: url(javascript:alert(1))"
|
||||
html = format_preview_html(ds)
|
||||
self.assertNotIn("javascript:alert", html)
|
||||
self.assertNotIn("red; } body", html)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@ -117,6 +117,14 @@ python3 {{SCRIPT_PATH}} "<query>" --design-system --persist -p "Project Name" --
|
||||
This also creates:
|
||||
- `design-system/<project-slug>/pages/dashboard.md` — Page-specific deviations from Master
|
||||
|
||||
**Preview the generated system as a static page:**
|
||||
|
||||
```bash
|
||||
python3 {{SCRIPT_PATH}} "<query>" --design-system --persist --preview -p "Project Name" --output-dir "<project-root>"
|
||||
```
|
||||
|
||||
`--preview` is valid only with `--design-system`. With `--persist` it writes `design-system/<project-slug>/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:**
|
||||
|
||||
@ -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]);
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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,
|
||||
}
|
||||
|
||||
|
||||
|
||||
543
src/ui-ux-pro-max/scripts/preview.py
Normal file
543
src/ui-ux-pro-max/scripts/preview.py
Normal file
@ -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'<p class="swatch-contrast">vs {_text(pair_label)} '
|
||||
f'<code>{_text(pair_hex)}</code>: {_text(_format_ratio(ratio))} '
|
||||
f'<span class="badge {badge_class}">{_text(level)}</span></p>'
|
||||
)
|
||||
swatches.append(
|
||||
f'<li class="swatch">'
|
||||
f'<div class="swatch-chip" style="background:{hex_val}" aria-hidden="true"></div>'
|
||||
f'<div class="swatch-meta">'
|
||||
f'<p class="swatch-role">{_text(label)}</p>'
|
||||
f'<p><code>{_text(hex_val)}</code> <code>{_text(css_var)}</code></p>'
|
||||
f'{ratio_html}'
|
||||
f'</div></li>'
|
||||
)
|
||||
|
||||
anti_items = []
|
||||
for clause in (anti_patterns.split("+") if anti_patterns else []):
|
||||
clause = clause.strip()
|
||||
if clause:
|
||||
anti_items.append(f"<li>{_text(clause)}</li>")
|
||||
if not anti_items:
|
||||
anti_items.append("<li>None listed for this system.</li>")
|
||||
|
||||
font_links = ""
|
||||
if google_href:
|
||||
font_links = (
|
||||
' <link rel="preconnect" href="https://fonts.googleapis.com">\n'
|
||||
' <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>\n'
|
||||
f' <link rel="stylesheet" href="{google_href}">\n'
|
||||
)
|
||||
|
||||
color_scheme = "dark" if dark else "light"
|
||||
notes_html = (
|
||||
f'<p class="notes">{_text(notes)}</p>' 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"""<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="{color_scheme}">
|
||||
<title>{_attr(project)} design system preview</title>
|
||||
{font_links} <style>
|
||||
:root {{
|
||||
{css_vars_block}
|
||||
--font-heading: {heading_stack};
|
||||
--font-body: {body_stack};
|
||||
}}
|
||||
*, *::before, *::after {{ box-sizing: border-box; }}
|
||||
html {{ font-size: 16px; }}
|
||||
body {{
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
font-family: var(--font-body);
|
||||
background: {background};
|
||||
color: {foreground};
|
||||
line-height: 1.5;
|
||||
}}
|
||||
a:focus-visible,
|
||||
button:focus-visible,
|
||||
input:focus-visible {{
|
||||
outline: 3px solid {ring};
|
||||
outline-offset: 2px;
|
||||
}}
|
||||
header, main {{
|
||||
width: min(1100px, calc(100% - 2rem));
|
||||
margin-inline: auto;
|
||||
}}
|
||||
header {{
|
||||
padding: 2.5rem 0 1.5rem;
|
||||
border-bottom: 1px solid {border};
|
||||
}}
|
||||
.eyebrow {{
|
||||
margin: 0 0 0.35rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
font-size: 0.75rem;
|
||||
color: {muted_fg};
|
||||
}}
|
||||
h1, h2, h3, .specimen-heading {{
|
||||
font-family: var(--font-heading);
|
||||
line-height: 1.2;
|
||||
margin: 0 0 0.5rem;
|
||||
}}
|
||||
h1 {{ font-size: 2.25rem; }}
|
||||
h2 {{ font-size: 1.5rem; }}
|
||||
h3 {{ font-size: 1.2rem; }}
|
||||
main {{ padding: 2rem 0 4rem; display: grid; gap: 2.5rem; }}
|
||||
section {{
|
||||
background: {card};
|
||||
color: {card_fg};
|
||||
border: 1px solid {border};
|
||||
border-radius: 12px;
|
||||
padding: 1.5rem;
|
||||
}}
|
||||
.swatches {{
|
||||
list-style: none;
|
||||
margin: 1rem 0 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
||||
}}
|
||||
.swatch {{
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
align-items: flex-start;
|
||||
}}
|
||||
.swatch-chip {{
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
border-radius: 8px;
|
||||
border: 1px solid {border};
|
||||
flex-shrink: 0;
|
||||
}}
|
||||
.swatch-meta p {{ margin: 0; font-size: 0.9rem; }}
|
||||
.swatch-role {{ font-weight: 600; }}
|
||||
.swatch-contrast {{ color: {muted_fg}; }}
|
||||
code {{ font-size: 0.85em; }}
|
||||
.badge {{
|
||||
display: inline-block;
|
||||
margin-left: 0.35rem;
|
||||
padding: 0.05rem 0.4rem;
|
||||
border-radius: 999px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
}}
|
||||
.badge-aaa {{ background: {primary}; color: {on_primary}; }}
|
||||
.badge-aa {{ background: {muted}; color: {muted_fg}; }}
|
||||
.badge-fail {{ background: {destructive}; color: {on_destructive}; }}
|
||||
.type-scale {{ display: grid; gap: 0.75rem; }}
|
||||
.type-scale p {{ margin: 0; max-width: 42rem; }}
|
||||
.btn-row {{
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
margin: 0.75rem 0;
|
||||
}}
|
||||
.btn {{
|
||||
font-family: var(--font-body);
|
||||
font-weight: 600;
|
||||
font-size: 1rem;
|
||||
padding: 12px 24px;
|
||||
border-radius: 8px;
|
||||
border: 2px solid transparent;
|
||||
cursor: pointer;
|
||||
transition: opacity 200ms ease, transform 200ms ease, box-shadow 200ms ease;
|
||||
}}
|
||||
.btn-primary {{ background: {primary}; color: {on_primary}; }}
|
||||
.btn-secondary {{
|
||||
background: transparent;
|
||||
color: {secondary_text};
|
||||
border-color: {secondary};
|
||||
}}
|
||||
.btn-accent {{ background: {accent}; color: {on_accent}; }}
|
||||
.btn-destructive {{ background: {destructive}; color: {on_destructive}; }}
|
||||
.btn:hover, .btn.is-hover {{
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.18);
|
||||
transform: translateY(-1px);
|
||||
}}
|
||||
.btn:focus-visible, .btn.is-focus {{
|
||||
outline: 3px solid {ring};
|
||||
outline-offset: 2px;
|
||||
}}
|
||||
.btn:disabled, .btn.is-disabled {{
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}}
|
||||
.state-label {{
|
||||
font-size: 0.8rem;
|
||||
color: {muted_fg};
|
||||
margin: 0.25rem 0 0;
|
||||
}}
|
||||
.preview-card {{
|
||||
background: {card};
|
||||
color: {card_fg};
|
||||
border: 1px solid {border};
|
||||
border-radius: 12px;
|
||||
padding: 1.5rem;
|
||||
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
|
||||
max-width: 28rem;
|
||||
}}
|
||||
.field {{ display: grid; gap: 0.35rem; max-width: 28rem; }}
|
||||
.field + .field {{ margin-top: 1rem; }}
|
||||
label {{ font-weight: 600; }}
|
||||
input[type="text"], input[type="email"] {{
|
||||
font: inherit;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid {border};
|
||||
border-radius: 8px;
|
||||
background: {background};
|
||||
color: {foreground};
|
||||
}}
|
||||
input[aria-invalid="true"] {{
|
||||
border-color: {destructive};
|
||||
}}
|
||||
.help {{ margin: 0; color: {muted_fg}; font-size: 0.9rem; }}
|
||||
.error {{
|
||||
margin: 0;
|
||||
color: {on_destructive};
|
||||
background: {destructive};
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
padding: 0.4rem 0.6rem;
|
||||
border-radius: 6px;
|
||||
}}
|
||||
.notes {{ color: {muted_fg}; }}
|
||||
@media (prefers-reduced-motion: reduce) {{
|
||||
*, *::before, *::after {{
|
||||
animation: none !important;
|
||||
transition: none !important;
|
||||
scroll-behavior: auto !important;
|
||||
}}
|
||||
.btn:hover, .btn.is-hover {{ transform: none; }}
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<p class="eyebrow">Design system preview</p>
|
||||
<h1>{_text(project)}</h1>
|
||||
<p>{_text(style.get("name") or "Unspecified style")}{_text(" · " + category if category else "")}</p>
|
||||
</header>
|
||||
<main>
|
||||
<section aria-labelledby="palette-heading">
|
||||
<h2 id="palette-heading">Palette</h2>
|
||||
{notes_html}
|
||||
<ul class="swatches">
|
||||
{swatches_html}
|
||||
</ul>
|
||||
</section>
|
||||
<section aria-labelledby="type-heading">
|
||||
<h2 id="type-heading">Typography</h2>
|
||||
<p class="help">Heading: {_text(heading_font)} · Body: {_text(body_font)}</p>
|
||||
<div class="type-scale">
|
||||
<p class="specimen-heading" style="font-size:2.5rem">Display · {_text(heading_font)}</p>
|
||||
<h3>Heading 2 · {_text(heading_font)}</h3>
|
||||
<p>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.</p>
|
||||
</div>
|
||||
</section>
|
||||
<section aria-labelledby="buttons-heading">
|
||||
<h2 id="buttons-heading">Buttons</h2>
|
||||
<p class="state-label">Default</p>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary" type="button">Primary</button>
|
||||
<button class="btn btn-secondary" type="button">Secondary</button>
|
||||
<button class="btn btn-accent" type="button">Accent</button>
|
||||
<button class="btn btn-destructive" type="button">Destructive</button>
|
||||
</div>
|
||||
<p class="state-label">Hover</p>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary is-hover" type="button">Primary</button>
|
||||
<button class="btn btn-secondary is-hover" type="button">Secondary</button>
|
||||
<button class="btn btn-accent is-hover" type="button">Accent</button>
|
||||
<button class="btn btn-destructive is-hover" type="button">Destructive</button>
|
||||
</div>
|
||||
<p class="state-label">Focus-visible</p>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary is-focus" type="button">Primary</button>
|
||||
<button class="btn btn-secondary is-focus" type="button">Secondary</button>
|
||||
<button class="btn btn-accent is-focus" type="button">Accent</button>
|
||||
<button class="btn btn-destructive is-focus" type="button">Destructive</button>
|
||||
</div>
|
||||
<p class="state-label">Disabled</p>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-primary" type="button" disabled>Primary</button>
|
||||
<button class="btn btn-secondary" type="button" disabled>Secondary</button>
|
||||
<button class="btn btn-accent" type="button" disabled>Accent</button>
|
||||
<button class="btn btn-destructive" type="button" disabled>Destructive</button>
|
||||
</div>
|
||||
</section>
|
||||
<section aria-labelledby="card-heading">
|
||||
<h2 id="card-heading">Card</h2>
|
||||
<article class="preview-card">
|
||||
<h3>{_text(project)}</h3>
|
||||
<p>A sample card using the generated card surface, border, and type pairing.</p>
|
||||
<button class="btn btn-primary" type="button">Continue</button>
|
||||
</article>
|
||||
</section>
|
||||
<section aria-labelledby="form-heading">
|
||||
<h2 id="form-heading">Form</h2>
|
||||
<form>
|
||||
<div class="field">
|
||||
<label for="preview-email">Email</label>
|
||||
<input id="preview-email" name="email" type="email" autocomplete="email" aria-describedby="preview-email-help">
|
||||
<p id="preview-email-help" class="help">Use your work address.</p>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="preview-name">Display name</label>
|
||||
<input id="preview-name" name="name" type="text" value="Not a valid value" aria-invalid="true" aria-describedby="preview-name-error">
|
||||
<p id="preview-name-error" class="error">Enter a display name of at least two characters.</p>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
<section aria-labelledby="style-heading">
|
||||
<h2 id="style-heading">Style, effects, anti-patterns</h2>
|
||||
<p><strong>Style:</strong> {_text(style.get("name") or "")}</p>
|
||||
<p><strong>Key effects:</strong> {effects_html}</p>
|
||||
<h3>Anti-patterns</h3>
|
||||
<ul>
|
||||
{anti_html}
|
||||
</ul>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</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/<slug>/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)],
|
||||
}
|
||||
@ -5,6 +5,7 @@ UI/UX Pro Max Search - BM25 search engine for UI/UX style guides
|
||||
Usage: python search.py "<query>" [--domain <domain>] [--stack <stack>] [--max-results 3]
|
||||
python search.py "<query>" --design-system [-p "Project Name"]
|
||||
python search.py "<query>" --design-system --persist [-p "Project Name"] --output-dir "<project-root>" [--page "dashboard"]
|
||||
python search.py "<query>" --design-system --persist --preview [-p "Project Name"] --output-dir "<project-root>"
|
||||
python search.py "<query>" --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/<project-slug>/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/<project-slug>/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:
|
||||
|
||||
@ -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.",
|
||||
|
||||
274
src/ui-ux-pro-max/scripts/tests/test_design_system_preview.py
Normal file
274
src/ui-ux-pro-max/scripts/tests/test_design_system_preview.py
Normal file
@ -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 = '<script>alert(1)</script>'
|
||||
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("<script>alert(1)</script>", html)
|
||||
self.assertIn("<script>alert(1)</script>", html)
|
||||
self.assertIn("<html lang=", html)
|
||||
|
||||
def test_cli_hostile_project_name_is_escaped(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
proc = _run_search(
|
||||
"kids education app", "--design-system", "--preview",
|
||||
"--project-name", HOSTILE_NAME, "--output-dir", tmp, "--json",
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
payload = json.loads(proc.stdout)
|
||||
path = Path(payload["preview"]["preview_file"])
|
||||
html = path.read_text(encoding="utf-8")
|
||||
self.assertNotIn("<script>alert(1)</script>", 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("<html lang=", path.read_text(encoding="utf-8"))
|
||||
|
||||
def test_preview_still_writes_when_master_already_exists(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
generate_design_system(
|
||||
"fintech dashboard", "Ledger", persist=True, output_dir=tmp
|
||||
)
|
||||
result = generate_design_system(
|
||||
"fintech dashboard", "Ledger", persist=True, preview=True, output_dir=tmp
|
||||
)
|
||||
self.assertEqual(result["persistence"]["status"], "skipped_exists")
|
||||
self.assertEqual(result["preview"]["status"], "success")
|
||||
self.assertTrue(Path(result["preview"]["preview_file"]).exists())
|
||||
|
||||
|
||||
class TestPreviewNoScriptInjectionInCss(unittest.TestCase):
|
||||
def test_invalid_hex_is_not_emitted_as_css_color(self):
|
||||
ds = generate_design_system("fintech dashboard", "Ledger")["design_system"]
|
||||
ds = dict(ds)
|
||||
ds["colors"] = dict(ds["colors"])
|
||||
ds["colors"]["primary"] = "red; } body { background: url(javascript:alert(1))"
|
||||
html = format_preview_html(ds)
|
||||
self.assertNotIn("javascript:alert", html)
|
||||
self.assertNotIn("red; } body", html)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@ -117,6 +117,14 @@ python3 {{SCRIPT_PATH}} "<query>" --design-system --persist -p "Project Name" --
|
||||
This also creates:
|
||||
- `design-system/<project-slug>/pages/dashboard.md` — Page-specific deviations from Master
|
||||
|
||||
**Preview the generated system as a static page:**
|
||||
|
||||
```bash
|
||||
python3 {{SCRIPT_PATH}} "<query>" --design-system --persist --preview -p "Project Name" --output-dir "<project-root>"
|
||||
```
|
||||
|
||||
`--preview` is valid only with `--design-system`. With `--persist` it writes `design-system/<project-slug>/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:**
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user