mirror of
https://github.com/nextlevelbuilder/ui-ux-pro-max-skill.git
synced 2026-11-18 16:23:38 +00:00
feat(design-system): export the generated design system as design tokens (#577)
This commit is contained in:
parent
efd9822135
commit
b6a79003ad
@ -113,6 +113,24 @@ If `design-system/<project-slug>/MASTER.md` already exists, `--persist` **skips
|
||||
|
||||
Read an existing `MASTER.md` before deciding whether `--force` is justified. Never use `--force` without explicit user authorization.
|
||||
|
||||
### Step 2b-tokens: Export Design Tokens
|
||||
|
||||
`--tokens` is valid only with `--design-system`. It prints a machine-readable token document so hex values and font names do not have to be copied by hand:
|
||||
|
||||
```bash
|
||||
python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py" "<query>" --design-system --tokens dtcg
|
||||
python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py" "<query>" --design-system --tokens css
|
||||
```
|
||||
|
||||
- `dtcg` prints W3C Design Tokens Community Group JSON (`$value` / `$type`, `color`, `font`, and a `semantic` layer such as `color.primary`, `color.on-primary`, `color.background`, `font.heading`).
|
||||
- `css` prints `:root` custom properties using the same names as the bundled design-system token compiler (`--color-primary`, `--font-heading`, …).
|
||||
- Dark-mode results emit the resolved dark values and record the mode in `$description`.
|
||||
- With `--persist`, also write `tokens.json` next to `MASTER.md` (and `tokens.css` when `--tokens css`). Existing files follow the same `--force` / skip-if-exists rules. Token files are master-level only; `--page` overrides do not emit page-specific tokens.
|
||||
|
||||
```bash
|
||||
python "${CLAUDE_PLUGIN_ROOT}/.claude/skills/ui-ux-pro-max/scripts/search.py" "<query>" --design-system --persist --tokens dtcg -p "Project Name" --output-dir "<project-root>"
|
||||
```
|
||||
|
||||
**Retrieval when building a specific page:**
|
||||
1. Read `design-system/<project-slug>/MASTER.md`
|
||||
2. Check if `design-system/<project-slug>/pages/<page-name>.md` exists — if so, its rules override Master
|
||||
@ -201,7 +219,7 @@ Then synthesize the design system + detailed searches and implement.
|
||||
|
||||
## Output Formats
|
||||
|
||||
`--design-system` supports `-f ascii` (default, terminal display), `-f markdown` (documentation), and `--json` (machine-readable, includes the raw design system dict plus persistence status).
|
||||
`--design-system` supports `-f ascii` (default, terminal display), `-f markdown` (documentation), `--json` (machine-readable, includes the raw design system dict plus persistence status), and `--tokens dtcg|css` (W3C Design Tokens JSON or CSS variables; requires `--design-system`).
|
||||
|
||||
## Tips for Better Results
|
||||
|
||||
|
||||
@ -594,7 +594,9 @@ class DesignSystemGenerator:
|
||||
"mood": best_typography.get("Mood/Style Keywords", reasoning.get("typography_mood", "")),
|
||||
"best_for": best_typography.get("Best For", ""),
|
||||
"google_fonts_url": best_typography.get("Google Fonts URL", ""),
|
||||
"css_import": best_typography.get("CSS Import", "")
|
||||
"css_import": best_typography.get("CSS Import", ""),
|
||||
"tailwind_config": best_typography.get("Tailwind Config", ""),
|
||||
"category": best_typography.get("Category", ""),
|
||||
},
|
||||
"key_effects": combined_effects,
|
||||
"anti_patterns": _filter_anti_patterns_for_mode(
|
||||
@ -941,11 +943,172 @@ def format_markdown(design_system: dict) -> str:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ============ DESIGN TOKENS (DTCG / CSS) ============
|
||||
# Token names follow SEMANTIC_COLOR_ENTRIES CSS variables so --tokens css
|
||||
# and cli/assets/skills/design-system/scripts/generate-tokens.cjs agree:
|
||||
# semantic.color.primary -> --color-primary.
|
||||
TOKEN_SCHEMA = "https://design-tokens.org/schema.json"
|
||||
_HEX6 = re.compile(r"^#[0-9A-Fa-f]{6}$")
|
||||
_TW_FONT_PAIR = re.compile(r"\['([^']+)',\s*'([^']+)'\]")
|
||||
|
||||
|
||||
def _css_font_family(font_name: str, tailwind_config: str = "") -> str:
|
||||
"""CSS font-family stack using the pairing's Tailwind Config fallback when present."""
|
||||
name = (font_name or "").strip()
|
||||
if not name:
|
||||
return ""
|
||||
generic = "sans-serif"
|
||||
for listed_name, fallback in _TW_FONT_PAIR.findall(tailwind_config or ""):
|
||||
if listed_name == name and fallback:
|
||||
generic = fallback
|
||||
break
|
||||
quoted = f'"{name}"' if (" " in name or "," in name) else name
|
||||
return f"{quoted}, {generic}"
|
||||
|
||||
|
||||
def _token_color_entries(colors: dict):
|
||||
"""Yield (kebab-name, hex) for 6-digit palette roles the design system actually has."""
|
||||
for _label, key, _css_var in SEMANTIC_COLOR_ENTRIES:
|
||||
hex_val = (colors or {}).get(key, "")
|
||||
if not hex_val:
|
||||
continue
|
||||
value = str(hex_val).strip()
|
||||
if _HEX6.match(value):
|
||||
yield key.replace("_", "-"), value
|
||||
|
||||
|
||||
def _resolve_token_reference(value, tokens):
|
||||
"""Resolve DTCG `{group.token}` references the same way generate-tokens.cjs does."""
|
||||
if not isinstance(value, str) or not value.startswith("{") or not value.endswith("}"):
|
||||
return value
|
||||
node = tokens
|
||||
for key in value[1:-1].split("."):
|
||||
if not isinstance(node, dict):
|
||||
return value
|
||||
node = node.get(key)
|
||||
if isinstance(node, dict) and "$value" in node:
|
||||
return _resolve_token_reference(node["$value"], tokens)
|
||||
return value if node is None else node
|
||||
|
||||
|
||||
def _flatten_tokens(obj, tokens, prefix=None, result=None):
|
||||
"""Flatten a DTCG group into CSS custom properties (generate-tokens.cjs flattenTokens)."""
|
||||
prefix = prefix or []
|
||||
result = {} if result is None else result
|
||||
if not isinstance(obj, dict):
|
||||
return result
|
||||
for key, value in obj.items():
|
||||
if not isinstance(value, dict):
|
||||
continue
|
||||
current = prefix + [key]
|
||||
if "$value" in value:
|
||||
css_var = "--" + "-".join(current).replace(".", "-")
|
||||
result[css_var] = _resolve_token_reference(value["$value"], tokens)
|
||||
else:
|
||||
_flatten_tokens(value, tokens, current, result)
|
||||
return result
|
||||
|
||||
|
||||
def _root_block(mapping: dict) -> str:
|
||||
body = "\n".join(f" {name}: {value};" for name, value in mapping.items())
|
||||
return f":root {{\n{body}\n}}"
|
||||
|
||||
|
||||
def build_design_tokens(design_system: dict) -> dict:
|
||||
"""W3C DTCG document for a generated design system. Invents nothing beyond CSS generic fallbacks."""
|
||||
colors = design_system.get("colors") or {}
|
||||
typography = design_system.get("typography") or {}
|
||||
mode = design_system.get("color_mode") or "light"
|
||||
derivation = (design_system.get("source_derivations") or {}).get("color_mode")
|
||||
project = design_system.get("project_name") or "PROJECT"
|
||||
description = f"Design tokens for {project} ({mode} mode)."
|
||||
if derivation == "derived-dark":
|
||||
description += " Surface colors were derived for dark mode from the product palette."
|
||||
|
||||
color_group = {}
|
||||
semantic_color = {}
|
||||
for name, hex_val in _token_color_entries(colors):
|
||||
color_group[name] = {"$value": hex_val, "$type": "color"}
|
||||
semantic_color[name] = {"$value": f"{{color.{name}}}", "$type": "color"}
|
||||
|
||||
tailwind_config = typography.get("tailwind_config", "")
|
||||
font_group = {}
|
||||
semantic_font = {}
|
||||
for role in ("heading", "body"):
|
||||
stack = _css_font_family(typography.get(role, ""), tailwind_config)
|
||||
if not stack:
|
||||
continue
|
||||
font_group[role] = {"$value": stack, "$type": "fontFamily"}
|
||||
semantic_font[role] = {"$value": f"{{font.{role}}}", "$type": "fontFamily"}
|
||||
|
||||
tokens = {
|
||||
"$schema": TOKEN_SCHEMA,
|
||||
"$description": description,
|
||||
"color": color_group,
|
||||
"font": font_group,
|
||||
"semantic": {},
|
||||
}
|
||||
if semantic_color:
|
||||
tokens["semantic"]["color"] = semantic_color
|
||||
if semantic_font:
|
||||
tokens["semantic"]["font"] = semantic_font
|
||||
|
||||
spacing_scale = design_system.get("spacing_scale")
|
||||
if spacing_scale:
|
||||
space_group = {}
|
||||
semantic_space = {}
|
||||
for token, px_value in spacing_scale.items():
|
||||
if not px_value:
|
||||
continue
|
||||
space_group[token] = {"$value": px_value, "$type": "dimension"}
|
||||
semantic_space[token] = {"$value": f"{{space.{token}}}", "$type": "dimension"}
|
||||
if space_group:
|
||||
tokens["space"] = space_group
|
||||
tokens["semantic"]["space"] = semantic_space
|
||||
|
||||
return tokens
|
||||
|
||||
|
||||
def format_tokens_dtcg(tokens: dict) -> str:
|
||||
"""Pretty-print a DTCG document as JSON."""
|
||||
return json.dumps(tokens, indent=2, ensure_ascii=False) + "\n"
|
||||
|
||||
|
||||
def format_tokens_css(tokens: dict) -> str:
|
||||
"""CSS custom properties matching generate-tokens.cjs generateCSS()."""
|
||||
primitive = _flatten_tokens(tokens.get("primitive") or {}, tokens, ["primitive"])
|
||||
semantic = _flatten_tokens(tokens.get("semantic") or {}, tokens, [])
|
||||
component = _flatten_tokens(tokens.get("component") or {}, tokens, [])
|
||||
dark_semantic = _flatten_tokens(
|
||||
(tokens.get("dark") or {}).get("semantic") or {}, tokens, []
|
||||
)
|
||||
css = (
|
||||
"/* Design Tokens - Auto-generated */\n"
|
||||
"/* Do not edit directly - modify tokens.json instead */\n"
|
||||
"\n"
|
||||
"/* === PRIMITIVES === */\n"
|
||||
f"{_root_block(primitive)}\n"
|
||||
"\n"
|
||||
"/* === SEMANTIC === */\n"
|
||||
f"{_root_block(semantic)}\n"
|
||||
"\n"
|
||||
"/* === COMPONENTS === */\n"
|
||||
f"{_root_block(component)}\n"
|
||||
)
|
||||
if dark_semantic:
|
||||
dark_body = "\n".join(
|
||||
f" {name}: {value};" for name, value in dark_semantic.items()
|
||||
)
|
||||
css += f"\n/* === DARK MODE === */\n.dark {{\n{dark_body}\n}}\n"
|
||||
return css
|
||||
|
||||
|
||||
# ============ MAIN ENTRY POINT ============
|
||||
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, preview: bool = False) -> dict:
|
||||
force: bool = False, preview: bool = False,
|
||||
token_format: str = None) -> dict:
|
||||
"""
|
||||
Main entry point for design system generation.
|
||||
|
||||
@ -962,19 +1125,29 @@ def generate_design_system(query: str, project_name: str = None, output_format:
|
||||
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
|
||||
token_format: Optional "dtcg" or "css". When set, "text" is the token
|
||||
document and persist writes tokens.json (and tokens.css for css)
|
||||
next to MASTER.md. Tokens are master-level only; --page does not
|
||||
emit page-specific token files.
|
||||
|
||||
Returns:
|
||||
dict with keys: "text" (formatted design system string), "design_system"
|
||||
(raw dict, useful for --json callers), "persistence" (result of
|
||||
dict with keys: "text" (formatted design system or token string),
|
||||
"design_system" (raw dict, useful for --json callers), "tokens"
|
||||
(DTCG dict when token_format is set), "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)
|
||||
|
||||
tokens = build_design_tokens(design_system) if token_format else None
|
||||
|
||||
persistence_result = None
|
||||
if persist:
|
||||
persistence_result = persist_design_system(design_system, page, output_dir, query, force=force)
|
||||
persistence_result = persist_design_system(
|
||||
design_system, page, output_dir, query, force=force,
|
||||
token_format=token_format, tokens=tokens,
|
||||
)
|
||||
|
||||
preview_result = None
|
||||
if preview:
|
||||
@ -983,13 +1156,21 @@ def generate_design_system(query: str, project_name: str = None, output_format:
|
||||
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)
|
||||
if token_format == "css":
|
||||
text = format_tokens_css(tokens)
|
||||
elif token_format == "dtcg":
|
||||
text = format_tokens_dtcg(tokens)
|
||||
elif output_format == "markdown":
|
||||
text = format_markdown(design_system)
|
||||
else:
|
||||
text = format_ascii_box(design_system)
|
||||
|
||||
return {
|
||||
"text": text,
|
||||
"design_system": design_system,
|
||||
"persistence": persistence_result,
|
||||
"preview": preview_result,
|
||||
"tokens": tokens,
|
||||
}
|
||||
|
||||
|
||||
@ -1029,7 +1210,8 @@ def _write_persisted_file(path: Path, content: str, force: bool) -> None:
|
||||
|
||||
|
||||
def persist_design_system(design_system: dict, page: str = None, output_dir: str = None,
|
||||
page_query: str = None, force: bool = False) -> dict:
|
||||
page_query: str = None, force: bool = False,
|
||||
token_format: str = None, tokens: dict = None) -> dict:
|
||||
"""
|
||||
Persist design system to design-system/<project>/ folder using Master + Overrides pattern.
|
||||
|
||||
@ -1041,10 +1223,14 @@ def persist_design_system(design_system: dict, page: str = None, output_dir: str
|
||||
force: If True, overwrite an existing MASTER.md. If False (default) and
|
||||
MASTER.md already exists, persistence is skipped so prior design
|
||||
decisions aren't silently discarded.
|
||||
token_format: Optional "dtcg" or "css". When set, also write tokens.json
|
||||
next to MASTER.md (and tokens.css when css). Token files are
|
||||
master-level only; --page does not emit page-specific tokens.
|
||||
tokens: Optional pre-built DTCG dict; built from design_system when omitted.
|
||||
|
||||
Returns:
|
||||
dict with created file paths and status. status is "skipped_exists" if
|
||||
MASTER.md already existed and force was not set.
|
||||
no files were written because they already existed and force was not set.
|
||||
"""
|
||||
base_dir = Path(output_dir) if output_dir else Path.cwd()
|
||||
|
||||
@ -1066,23 +1252,28 @@ def persist_design_system(design_system: dict, page: str = None, output_dir: str
|
||||
|
||||
# Exclusive creation makes the default no-overwrite contract safe when
|
||||
# multiple agents persist the same project concurrently.
|
||||
master_content = format_master_md(design_system)
|
||||
master_content = format_master_md(design_system, token_format=token_format)
|
||||
try:
|
||||
_write_persisted_file(master_file, master_content, force)
|
||||
created_files.append(str(master_file))
|
||||
except FileExistsError:
|
||||
if not page:
|
||||
return {
|
||||
"status": "skipped_exists",
|
||||
"design_system_dir": str(design_system_dir),
|
||||
"master_file": str(master_file),
|
||||
"created_files": [],
|
||||
"message": (
|
||||
f"{master_file} already exists and was not modified. "
|
||||
"Read it first to check for prior design decisions, then "
|
||||
"re-run with force=True / --force to overwrite."
|
||||
),
|
||||
}
|
||||
pass
|
||||
|
||||
if token_format:
|
||||
token_doc = tokens if tokens is not None else build_design_tokens(design_system)
|
||||
json_path = design_system_dir / "tokens.json"
|
||||
try:
|
||||
_write_persisted_file(json_path, format_tokens_dtcg(token_doc), force)
|
||||
created_files.append(str(json_path))
|
||||
except FileExistsError:
|
||||
pass
|
||||
if token_format == "css":
|
||||
css_path = design_system_dir / "tokens.css"
|
||||
try:
|
||||
_write_persisted_file(css_path, format_tokens_css(token_doc), force)
|
||||
created_files.append(str(css_path))
|
||||
except FileExistsError:
|
||||
pass
|
||||
|
||||
# If page is specified, create page override file with intelligent content
|
||||
if page:
|
||||
@ -1092,14 +1283,21 @@ def persist_design_system(design_system: dict, page: str = None, output_dir: str
|
||||
_write_persisted_file(page_file, page_content, force)
|
||||
created_files.append(str(page_file))
|
||||
except FileExistsError:
|
||||
if not created_files:
|
||||
return {
|
||||
"status": "skipped_exists",
|
||||
"design_system_dir": str(design_system_dir),
|
||||
"master_file": str(master_file),
|
||||
"created_files": [],
|
||||
"message": f"{page_file} already exists and was not modified.",
|
||||
}
|
||||
pass
|
||||
|
||||
if not created_files:
|
||||
existing = master_file if master_file.exists() else design_system_dir
|
||||
return {
|
||||
"status": "skipped_exists",
|
||||
"design_system_dir": str(design_system_dir),
|
||||
"master_file": str(master_file),
|
||||
"created_files": [],
|
||||
"message": (
|
||||
f"{existing} already exists and was not modified. "
|
||||
"Read it first to check for prior design decisions, then "
|
||||
"re-run with force=True / --force to overwrite."
|
||||
),
|
||||
}
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
@ -1109,7 +1307,7 @@ def persist_design_system(design_system: dict, page: str = None, output_dir: str
|
||||
}
|
||||
|
||||
|
||||
def format_master_md(design_system: dict) -> str:
|
||||
def format_master_md(design_system: dict, token_format: str = None) -> str:
|
||||
"""Format design system as MASTER.md with hierarchical override logic."""
|
||||
project = design_system.get("project_name", "PROJECT")
|
||||
pattern = design_system.get("pattern", {})
|
||||
@ -1138,6 +1336,11 @@ def format_master_md(design_system: dict) -> str:
|
||||
lines.append(f"**Project:** {project}")
|
||||
lines.append(f"**Generated:** {timestamp}")
|
||||
lines.append(f"**Category:** {design_system.get('category', 'General')}")
|
||||
if token_format:
|
||||
lines.append("**Token files:** `tokens.json` (W3C Design Tokens Community Group JSON).")
|
||||
if token_format == "css":
|
||||
lines.append("**CSS variables:** `tokens.css` (`:root` custom properties).")
|
||||
lines.append("Token files are master-level only; `--page` overrides do not emit tokens.")
|
||||
if any(dials.get(k) is not None for k in ("variance", "motion", "density")):
|
||||
dial_parts = []
|
||||
if dials.get("variance") is not None:
|
||||
|
||||
@ -4,6 +4,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 --tokens dtcg|css
|
||||
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
|
||||
@ -17,13 +18,19 @@ Design dials (1-10, only with --design-system):
|
||||
--motion MOTION_INTENSITY: 1=subtle, 10=complex; attaches a GSAP snippet from motion.csv
|
||||
--density VISUAL_DENSITY: 1=spacious, 10=dense/dashboard; overrides the spacing scale
|
||||
|
||||
Token export (only with --design-system):
|
||||
--tokens dtcg Print W3C Design Tokens JSON (color, font, semantic layers)
|
||||
--tokens css Print :root CSS variables using the same names generate-tokens.cjs emits
|
||||
|
||||
Persistence (Master + Overrides pattern):
|
||||
--persist Save design system to design-system/<project-slug>/MASTER.md
|
||||
--output-dir Directory the design-system/ folder is created under (defaults to cwd --
|
||||
always pass this explicitly, pointed at the project root)
|
||||
--page Also create a page-specific override file in design-system/<project-slug>/pages/
|
||||
Token files are master-level only; --page does not emit page-specific tokens
|
||||
--force Overwrite an existing MASTER.md (without this, persistence is skipped
|
||||
if MASTER.md already exists, so prior design decisions aren't lost)
|
||||
With --tokens, also writes tokens.json (and tokens.css when --tokens css)
|
||||
--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.
|
||||
@ -127,6 +134,8 @@ if __name__ == "__main__":
|
||||
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)")
|
||||
parser.add_argument("--tokens", choices=["dtcg", "css"], default=None,
|
||||
help="Export design tokens as W3C DTCG JSON or CSS variables (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)")
|
||||
@ -136,6 +145,8 @@ if __name__ == "__main__":
|
||||
|
||||
if args.preview and not args.design_system:
|
||||
parser.error("--preview requires --design-system")
|
||||
if args.tokens and not args.design_system:
|
||||
parser.error("--tokens requires --design-system")
|
||||
|
||||
# Design system takes priority
|
||||
if args.design_system:
|
||||
@ -162,6 +173,7 @@ if __name__ == "__main__":
|
||||
density=args.density,
|
||||
force=args.force,
|
||||
preview=args.preview,
|
||||
token_format=args.tokens,
|
||||
)
|
||||
|
||||
if args.json:
|
||||
@ -171,33 +183,48 @@ if __name__ == "__main__":
|
||||
}
|
||||
if args.preview:
|
||||
payload["preview"] = result["preview"]
|
||||
if result.get("tokens") is not None:
|
||||
payload["tokens"] = result["tokens"]
|
||||
print(json_module.dumps(payload, indent=2, ensure_ascii=False))
|
||||
else:
|
||||
print(result["text"])
|
||||
# Token export is meant to be redirected; keep a trailing newline
|
||||
# matching generate-tokens.cjs stdout without doubling print()'s.
|
||||
text = result["text"]
|
||||
if args.tokens:
|
||||
sys.stdout.write(text if text.endswith("\n") else text + "\n")
|
||||
else:
|
||||
print(text)
|
||||
|
||||
if args.persist:
|
||||
persistence = result["persistence"] or {}
|
||||
print("\n" + "=" * 60)
|
||||
persist_stream = sys.stderr if args.tokens else sys.stdout
|
||||
print("\n" + "=" * 60, file=persist_stream)
|
||||
if persistence.get("status") == "skipped_exists":
|
||||
print(f"⚠️ {persistence.get('message', 'MASTER.md already exists; not overwritten.')}")
|
||||
print(f"⚠️ {persistence.get('message', 'MASTER.md already exists; not overwritten.')}",
|
||||
file=persist_stream)
|
||||
else:
|
||||
ds_dir = persistence.get("design_system_dir", "design-system/<project>")
|
||||
print(f"✅ Design system persisted to {ds_dir}/")
|
||||
print(f"✅ Design system persisted to {ds_dir}/", file=persist_stream)
|
||||
for f in persistence.get("created_files", []):
|
||||
print(f" 📄 {f}")
|
||||
print("")
|
||||
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)
|
||||
print(f" 📄 {f}", file=persist_stream)
|
||||
print("", file=persist_stream)
|
||||
print(f"📖 Usage: When building a page, check {ds_dir}/pages/[page].md first.",
|
||||
file=persist_stream)
|
||||
print(" If it exists, its rules override MASTER.md. Otherwise, use MASTER.md.",
|
||||
file=persist_stream)
|
||||
print("=" * 60, file=persist_stream)
|
||||
|
||||
if args.preview:
|
||||
preview = result["preview"] or {}
|
||||
print("\n" + "=" * 60)
|
||||
preview_stream = sys.stderr if args.tokens else sys.stdout
|
||||
print("\n" + "=" * 60, file=preview_stream)
|
||||
if preview.get("status") == "skipped_exists":
|
||||
print(f"⚠️ {preview.get('message', 'preview.html already exists; not overwritten.')}")
|
||||
print(f"⚠️ {preview.get('message', 'preview.html already exists; not overwritten.')}",
|
||||
file=preview_stream)
|
||||
else:
|
||||
print(f"✅ Design system preview: {preview.get('preview_file')}")
|
||||
print("=" * 60)
|
||||
print(f"✅ Design system preview: {preview.get('preview_file')}",
|
||||
file=preview_stream)
|
||||
print("=" * 60, file=preview_stream)
|
||||
# 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": "d0cb5803e094c21dc5262770f4a2dd8cecd20abf702896eea6ec69c357c54648",
|
||||
"runtimeFingerprint": "4f0d12f19a6be7fe7e3faf289244349f80497bac0ddb5563b0511e667953a225",
|
||||
"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,321 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Tests for --tokens dtcg|css export from the design-system generator.
|
||||
|
||||
Stdlib-only (unittest, not pytest) to match test_core.py -- this project ships
|
||||
with zero external dependencies. The generate-tokens.cjs round-trip is skipped
|
||||
when Node is missing; CI has Node.
|
||||
|
||||
Run with:
|
||||
python -m unittest discover -s scripts/tests -v
|
||||
or directly:
|
||||
python scripts/tests/test_design_system_tokens.py
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
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,
|
||||
_HEX6,
|
||||
build_design_tokens,
|
||||
format_tokens_css,
|
||||
format_tokens_dtcg,
|
||||
generate_design_system,
|
||||
)
|
||||
|
||||
ON_COLOR_PAIRS = (
|
||||
("on_primary", "primary"),
|
||||
("on_secondary", "secondary"),
|
||||
("on_accent", "accent"),
|
||||
("foreground", "background"),
|
||||
("card_foreground", "card"),
|
||||
("muted_foreground", "muted"),
|
||||
("on_destructive", "destructive"),
|
||||
)
|
||||
|
||||
SEARCH = SCRIPTS_DIR / "search.py"
|
||||
REPO = next(
|
||||
parent for parent in Path(__file__).resolve().parents
|
||||
if (parent / "cli" / "assets" / "skills" / "design-system" / "scripts"
|
||||
/ "generate-tokens.cjs").is_file()
|
||||
)
|
||||
GENERATE_TOKENS = (
|
||||
REPO / "cli" / "assets" / "skills" / "design-system" / "scripts"
|
||||
/ "generate-tokens.cjs"
|
||||
)
|
||||
HEX_TOKEN = re.compile(r"^#[0-9A-Fa-f]{6}$")
|
||||
CSS_VAR = re.compile(r"^\s+(--[a-z0-9-]+):\s*(.+);\s*$", re.MULTILINE)
|
||||
|
||||
|
||||
def _node_available():
|
||||
return shutil.which("node") is not None
|
||||
|
||||
|
||||
def _parse_css_vars(css: str) -> dict:
|
||||
return {name: value for name, value in CSS_VAR.findall(css)}
|
||||
|
||||
|
||||
class TokenExportTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.result = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", token_format="dtcg"
|
||||
)
|
||||
cls.ds = cls.result["design_system"]
|
||||
cls.tokens = cls.result["tokens"]
|
||||
|
||||
def test_color_mode_is_recorded(self):
|
||||
self.assertIn(self.ds["color_mode"], ("light", "dark"))
|
||||
|
||||
def test_dtcg_shape_matches_starter_conventions(self):
|
||||
tokens = self.tokens
|
||||
self.assertEqual(tokens["$schema"], "https://design-tokens.org/schema.json")
|
||||
self.assertIn("$description", tokens)
|
||||
self.assertIn(self.ds["color_mode"], tokens["$description"])
|
||||
self.assertIn("color", tokens)
|
||||
self.assertIn("font", tokens)
|
||||
self.assertIn("semantic", tokens)
|
||||
semantic_color = tokens["semantic"]["color"]
|
||||
for name in (
|
||||
"primary", "on-primary", "background", "foreground",
|
||||
"card", "muted", "border", "ring", "destructive",
|
||||
):
|
||||
self.assertIn(name, semantic_color)
|
||||
self.assertEqual(semantic_color[name]["$type"], "color")
|
||||
self.assertEqual(semantic_color[name]["$value"], "{color.%s}" % name)
|
||||
self.assertEqual(tokens["color"][name]["$type"], "color")
|
||||
self.assertRegex(tokens["color"][name]["$value"], HEX_TOKEN)
|
||||
for role in ("heading", "body"):
|
||||
self.assertEqual(tokens["font"][role]["$type"], "fontFamily")
|
||||
self.assertTrue(tokens["font"][role]["$value"])
|
||||
self.assertEqual(
|
||||
tokens["semantic"]["font"][role]["$value"], "{font.%s}" % role
|
||||
)
|
||||
|
||||
def test_every_exported_color_is_six_digit_hex(self):
|
||||
for name, token in self.tokens["color"].items():
|
||||
with self.subTest(color=name):
|
||||
self.assertEqual(token["$type"], "color")
|
||||
self.assertRegex(token["$value"], HEX_TOKEN)
|
||||
self.assertTrue(_HEX6.match(token["$value"]))
|
||||
|
||||
def test_on_color_pairs_reuse_generator_contrast(self):
|
||||
colors = self.ds["colors"]
|
||||
for foreground, background in ON_COLOR_PAIRS:
|
||||
with self.subTest(pair=foreground):
|
||||
self.assertGreaterEqual(
|
||||
_contrast_ratio(colors[foreground], colors[background]), 4.5
|
||||
)
|
||||
|
||||
def test_css_uses_generate_tokens_variable_names(self):
|
||||
css = format_tokens_css(self.tokens)
|
||||
variables = _parse_css_vars(css)
|
||||
for _label, key, css_var in SEMANTIC_COLOR_ENTRIES:
|
||||
hex_val = self.ds["colors"].get(key)
|
||||
if not hex_val:
|
||||
continue
|
||||
self.assertEqual(variables[css_var], hex_val)
|
||||
self.assertIn("--font-heading", variables)
|
||||
self.assertIn("--font-body", variables)
|
||||
self.assertTrue(css.strip().startswith("/* Design Tokens"))
|
||||
self.assertIn(":root {", css)
|
||||
|
||||
def test_dtcg_text_is_the_token_document(self):
|
||||
parsed = json.loads(self.result["text"])
|
||||
self.assertEqual(parsed["semantic"]["color"]["primary"]["$type"], "color")
|
||||
self.assertNotIn("TARGET:", self.result["text"])
|
||||
|
||||
def test_css_token_format_prints_css(self):
|
||||
result = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", token_format="css"
|
||||
)
|
||||
self.assertIn("--color-primary:", result["text"])
|
||||
self.assertEqual(result["tokens"]["color"]["primary"]["$value"],
|
||||
_parse_css_vars(result["text"])["--color-primary"])
|
||||
|
||||
def test_spacing_tokens_only_when_density_is_set(self):
|
||||
plain = build_design_tokens(
|
||||
generate_design_system("fintech dashboard", "Ledgerly")["design_system"]
|
||||
)
|
||||
dense = build_design_tokens(
|
||||
generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", density=9
|
||||
)["design_system"]
|
||||
)
|
||||
self.assertNotIn("space", plain)
|
||||
self.assertIn("space", dense)
|
||||
self.assertIn("xs", dense["semantic"]["space"])
|
||||
css_vars = _parse_css_vars(format_tokens_css(dense))
|
||||
self.assertIn("--space-xs", css_vars)
|
||||
|
||||
|
||||
class DarkModeTokenTest(unittest.TestCase):
|
||||
def test_dark_query_marks_mode_and_emits_dark_surfaces(self):
|
||||
result = generate_design_system(
|
||||
"dark mode developer tool", "Nightshift", token_format="dtcg"
|
||||
)
|
||||
ds = result["design_system"]
|
||||
tokens = result["tokens"]
|
||||
self.assertEqual(ds["color_mode"], "dark")
|
||||
self.assertIn("dark", tokens["$description"].lower())
|
||||
background = tokens["color"]["background"]["$value"]
|
||||
foreground = tokens["color"]["foreground"]["$value"]
|
||||
self.assertRegex(background, HEX_TOKEN)
|
||||
self.assertGreater(
|
||||
_contrast_ratio(foreground, background), 4.5
|
||||
)
|
||||
css = format_tokens_css(tokens)
|
||||
self.assertEqual(_parse_css_vars(css)["--color-background"], background)
|
||||
|
||||
|
||||
class PersistTokenTest(unittest.TestCase):
|
||||
def test_persist_dtcg_writes_tokens_json_beside_master(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
result = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", persist=True, output_dir=tmp,
|
||||
token_format="dtcg",
|
||||
)
|
||||
folder = Path(tmp) / "design-system" / "ledgerly"
|
||||
master = folder / "MASTER.md"
|
||||
tokens_json = folder / "tokens.json"
|
||||
self.assertTrue(master.exists())
|
||||
self.assertTrue(tokens_json.exists())
|
||||
self.assertFalse((folder / "tokens.css").exists())
|
||||
self.assertIn(str(tokens_json), result["persistence"]["created_files"])
|
||||
master_text = master.read_text(encoding="utf-8")
|
||||
self.assertIn("tokens.json", master_text)
|
||||
self.assertIn("master-level only", master_text)
|
||||
parsed = json.loads(tokens_json.read_text(encoding="utf-8"))
|
||||
self.assertEqual(parsed["semantic"]["color"]["primary"]["$type"], "color")
|
||||
|
||||
def test_persist_css_writes_json_and_css(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", persist=True, output_dir=tmp,
|
||||
token_format="css",
|
||||
)
|
||||
folder = Path(tmp) / "design-system" / "ledgerly"
|
||||
css_text = (folder / "tokens.css").read_text(encoding="utf-8")
|
||||
self.assertIn("--color-primary:", css_text)
|
||||
master = (folder / "MASTER.md").read_text(encoding="utf-8")
|
||||
self.assertIn("tokens.css", master)
|
||||
|
||||
def test_page_overrides_do_not_write_page_tokens(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
result = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", persist=True, page="dashboard",
|
||||
output_dir=tmp, token_format="dtcg",
|
||||
)
|
||||
folder = Path(tmp) / "design-system" / "ledgerly"
|
||||
page = folder / "pages" / "dashboard.md"
|
||||
self.assertTrue(page.exists())
|
||||
self.assertTrue((folder / "tokens.json").exists())
|
||||
self.assertFalse((folder / "pages" / "tokens.json").exists())
|
||||
created = result["persistence"]["created_files"]
|
||||
self.assertTrue(any(path.endswith("tokens.json") for path in created))
|
||||
self.assertTrue(any(path.endswith("dashboard.md") for path in created))
|
||||
|
||||
def test_skip_if_exists_then_force(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
first = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", persist=True, output_dir=tmp,
|
||||
token_format="dtcg",
|
||||
)
|
||||
tokens_json = Path(first["persistence"]["design_system_dir"]) / "tokens.json"
|
||||
original = tokens_json.read_text(encoding="utf-8")
|
||||
skipped = generate_design_system(
|
||||
"beauty spa", "Ledgerly", persist=True, output_dir=tmp,
|
||||
token_format="dtcg",
|
||||
)
|
||||
self.assertEqual(skipped["persistence"]["status"], "skipped_exists")
|
||||
self.assertEqual(tokens_json.read_text(encoding="utf-8"), original)
|
||||
forced = generate_design_system(
|
||||
"beauty spa", "Ledgerly", persist=True, output_dir=tmp,
|
||||
token_format="dtcg", force=True,
|
||||
)
|
||||
self.assertEqual(forced["persistence"]["status"], "success")
|
||||
self.assertNotEqual(tokens_json.read_text(encoding="utf-8"), original)
|
||||
|
||||
|
||||
class TokenCliTest(unittest.TestCase):
|
||||
def run_search(self, *args):
|
||||
return subprocess.run(
|
||||
[sys.executable, str(SEARCH), *map(str, args)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=False,
|
||||
)
|
||||
|
||||
def test_tokens_without_design_system_is_an_argparse_error(self):
|
||||
proc = self.run_search("fintech dashboard", "--tokens", "dtcg")
|
||||
self.assertNotEqual(proc.returncode, 0)
|
||||
self.assertIn("--tokens", proc.stderr)
|
||||
self.assertIn("--design-system", proc.stderr)
|
||||
|
||||
def test_cli_dtcg_stdout_is_json(self):
|
||||
proc = self.run_search(
|
||||
"fintech dashboard", "--design-system", "--tokens", "dtcg",
|
||||
"-p", "Ledgerly",
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
payload = json.loads(proc.stdout)
|
||||
self.assertEqual(payload["semantic"]["color"]["primary"]["$type"], "color")
|
||||
|
||||
def test_cli_css_stdout_has_root_variables(self):
|
||||
proc = self.run_search(
|
||||
"fintech dashboard", "--design-system", "--tokens", "css",
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
self.assertIn(":root {", proc.stdout)
|
||||
self.assertIn("--color-primary:", proc.stdout)
|
||||
|
||||
def test_json_payload_includes_tokens(self):
|
||||
proc = self.run_search(
|
||||
"fintech dashboard", "--design-system", "--tokens", "dtcg", "--json",
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
payload = json.loads(proc.stdout)
|
||||
self.assertIn("design_system", payload)
|
||||
self.assertIn("tokens", payload)
|
||||
self.assertIn("primary", payload["tokens"]["color"])
|
||||
|
||||
|
||||
@unittest.skipUnless(_node_available(), "Node.js is required to round-trip tokens through generate-tokens.cjs")
|
||||
class GenerateTokensRoundTripTest(unittest.TestCase):
|
||||
def test_cjs_css_matches_tokens_css_output(self):
|
||||
result = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", token_format="css"
|
||||
)
|
||||
python_css = format_tokens_css(result["tokens"])
|
||||
self.assertEqual(python_css, result["text"])
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
json_path = Path(tmp) / "tokens.json"
|
||||
cjs_css_path = Path(tmp) / "from-cjs.css"
|
||||
json_path.write_text(format_tokens_dtcg(result["tokens"]), encoding="utf-8")
|
||||
proc = subprocess.run(
|
||||
["node", str(GENERATE_TOKENS), "--config", str(json_path),
|
||||
"-o", str(cjs_css_path)],
|
||||
capture_output=True, text=True, encoding="utf-8", check=False,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
cjs_css = cjs_css_path.read_text(encoding="utf-8")
|
||||
self.assertEqual(cjs_css, python_css)
|
||||
self.assertEqual(_parse_css_vars(cjs_css), _parse_css_vars(python_css))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
12
README.md
12
README.md
@ -450,6 +450,10 @@ python3 .claude/skills/ui-ux-pro-max/scripts/search.py "beauty spa wellness" --d
|
||||
# Generate with Markdown output
|
||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "fintech banking" --design-system -f markdown
|
||||
|
||||
# Export design tokens (requires --design-system)
|
||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "fintech dashboard" --design-system --tokens dtcg
|
||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "fintech dashboard" --design-system --tokens css
|
||||
|
||||
# Domain-specific search
|
||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "glassmorphism" --domain style
|
||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "elegant serif" --domain typography
|
||||
@ -517,10 +521,16 @@ python3 .claude/skills/ui-ux-pro-max/scripts/search.py "SaaS dashboard" --design
|
||||
|
||||
# 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"
|
||||
|
||||
# Persist machine-readable tokens next to MASTER.md (tokens are master-level only)
|
||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "SaaS dashboard" --design-system --persist --tokens dtcg -p "MyApp"
|
||||
python3 .claude/skills/ui-ux-pro-max/scripts/search.py "SaaS dashboard" --design-system --persist --tokens css -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`.
|
||||
|
||||
`--tokens dtcg` prints W3C Design Tokens JSON; `--tokens css` prints `:root` CSS variables named the same way as `cli/assets/skills/design-system/scripts/generate-tokens.cjs`. Both require `--design-system`. With `--persist`, `tokens.json` is written beside `MASTER.md` (and `tokens.css` when `--tokens css`). `--page` overrides do not emit token files.
|
||||
|
||||
This creates a `design-system/` folder structure:
|
||||
|
||||
```
|
||||
@ -528,6 +538,8 @@ 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
|
||||
├── tokens.json # W3C Design Tokens (when persisted with --tokens)
|
||||
├── tokens.css # CSS variables (when persisted with --tokens css)
|
||||
└── pages/
|
||||
└── dashboard.md # Page-specific overrides (only deviations from Master)
|
||||
```
|
||||
|
||||
@ -594,7 +594,9 @@ class DesignSystemGenerator:
|
||||
"mood": best_typography.get("Mood/Style Keywords", reasoning.get("typography_mood", "")),
|
||||
"best_for": best_typography.get("Best For", ""),
|
||||
"google_fonts_url": best_typography.get("Google Fonts URL", ""),
|
||||
"css_import": best_typography.get("CSS Import", "")
|
||||
"css_import": best_typography.get("CSS Import", ""),
|
||||
"tailwind_config": best_typography.get("Tailwind Config", ""),
|
||||
"category": best_typography.get("Category", ""),
|
||||
},
|
||||
"key_effects": combined_effects,
|
||||
"anti_patterns": _filter_anti_patterns_for_mode(
|
||||
@ -941,11 +943,172 @@ def format_markdown(design_system: dict) -> str:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ============ DESIGN TOKENS (DTCG / CSS) ============
|
||||
# Token names follow SEMANTIC_COLOR_ENTRIES CSS variables so --tokens css
|
||||
# and cli/assets/skills/design-system/scripts/generate-tokens.cjs agree:
|
||||
# semantic.color.primary -> --color-primary.
|
||||
TOKEN_SCHEMA = "https://design-tokens.org/schema.json"
|
||||
_HEX6 = re.compile(r"^#[0-9A-Fa-f]{6}$")
|
||||
_TW_FONT_PAIR = re.compile(r"\['([^']+)',\s*'([^']+)'\]")
|
||||
|
||||
|
||||
def _css_font_family(font_name: str, tailwind_config: str = "") -> str:
|
||||
"""CSS font-family stack using the pairing's Tailwind Config fallback when present."""
|
||||
name = (font_name or "").strip()
|
||||
if not name:
|
||||
return ""
|
||||
generic = "sans-serif"
|
||||
for listed_name, fallback in _TW_FONT_PAIR.findall(tailwind_config or ""):
|
||||
if listed_name == name and fallback:
|
||||
generic = fallback
|
||||
break
|
||||
quoted = f'"{name}"' if (" " in name or "," in name) else name
|
||||
return f"{quoted}, {generic}"
|
||||
|
||||
|
||||
def _token_color_entries(colors: dict):
|
||||
"""Yield (kebab-name, hex) for 6-digit palette roles the design system actually has."""
|
||||
for _label, key, _css_var in SEMANTIC_COLOR_ENTRIES:
|
||||
hex_val = (colors or {}).get(key, "")
|
||||
if not hex_val:
|
||||
continue
|
||||
value = str(hex_val).strip()
|
||||
if _HEX6.match(value):
|
||||
yield key.replace("_", "-"), value
|
||||
|
||||
|
||||
def _resolve_token_reference(value, tokens):
|
||||
"""Resolve DTCG `{group.token}` references the same way generate-tokens.cjs does."""
|
||||
if not isinstance(value, str) or not value.startswith("{") or not value.endswith("}"):
|
||||
return value
|
||||
node = tokens
|
||||
for key in value[1:-1].split("."):
|
||||
if not isinstance(node, dict):
|
||||
return value
|
||||
node = node.get(key)
|
||||
if isinstance(node, dict) and "$value" in node:
|
||||
return _resolve_token_reference(node["$value"], tokens)
|
||||
return value if node is None else node
|
||||
|
||||
|
||||
def _flatten_tokens(obj, tokens, prefix=None, result=None):
|
||||
"""Flatten a DTCG group into CSS custom properties (generate-tokens.cjs flattenTokens)."""
|
||||
prefix = prefix or []
|
||||
result = {} if result is None else result
|
||||
if not isinstance(obj, dict):
|
||||
return result
|
||||
for key, value in obj.items():
|
||||
if not isinstance(value, dict):
|
||||
continue
|
||||
current = prefix + [key]
|
||||
if "$value" in value:
|
||||
css_var = "--" + "-".join(current).replace(".", "-")
|
||||
result[css_var] = _resolve_token_reference(value["$value"], tokens)
|
||||
else:
|
||||
_flatten_tokens(value, tokens, current, result)
|
||||
return result
|
||||
|
||||
|
||||
def _root_block(mapping: dict) -> str:
|
||||
body = "\n".join(f" {name}: {value};" for name, value in mapping.items())
|
||||
return f":root {{\n{body}\n}}"
|
||||
|
||||
|
||||
def build_design_tokens(design_system: dict) -> dict:
|
||||
"""W3C DTCG document for a generated design system. Invents nothing beyond CSS generic fallbacks."""
|
||||
colors = design_system.get("colors") or {}
|
||||
typography = design_system.get("typography") or {}
|
||||
mode = design_system.get("color_mode") or "light"
|
||||
derivation = (design_system.get("source_derivations") or {}).get("color_mode")
|
||||
project = design_system.get("project_name") or "PROJECT"
|
||||
description = f"Design tokens for {project} ({mode} mode)."
|
||||
if derivation == "derived-dark":
|
||||
description += " Surface colors were derived for dark mode from the product palette."
|
||||
|
||||
color_group = {}
|
||||
semantic_color = {}
|
||||
for name, hex_val in _token_color_entries(colors):
|
||||
color_group[name] = {"$value": hex_val, "$type": "color"}
|
||||
semantic_color[name] = {"$value": f"{{color.{name}}}", "$type": "color"}
|
||||
|
||||
tailwind_config = typography.get("tailwind_config", "")
|
||||
font_group = {}
|
||||
semantic_font = {}
|
||||
for role in ("heading", "body"):
|
||||
stack = _css_font_family(typography.get(role, ""), tailwind_config)
|
||||
if not stack:
|
||||
continue
|
||||
font_group[role] = {"$value": stack, "$type": "fontFamily"}
|
||||
semantic_font[role] = {"$value": f"{{font.{role}}}", "$type": "fontFamily"}
|
||||
|
||||
tokens = {
|
||||
"$schema": TOKEN_SCHEMA,
|
||||
"$description": description,
|
||||
"color": color_group,
|
||||
"font": font_group,
|
||||
"semantic": {},
|
||||
}
|
||||
if semantic_color:
|
||||
tokens["semantic"]["color"] = semantic_color
|
||||
if semantic_font:
|
||||
tokens["semantic"]["font"] = semantic_font
|
||||
|
||||
spacing_scale = design_system.get("spacing_scale")
|
||||
if spacing_scale:
|
||||
space_group = {}
|
||||
semantic_space = {}
|
||||
for token, px_value in spacing_scale.items():
|
||||
if not px_value:
|
||||
continue
|
||||
space_group[token] = {"$value": px_value, "$type": "dimension"}
|
||||
semantic_space[token] = {"$value": f"{{space.{token}}}", "$type": "dimension"}
|
||||
if space_group:
|
||||
tokens["space"] = space_group
|
||||
tokens["semantic"]["space"] = semantic_space
|
||||
|
||||
return tokens
|
||||
|
||||
|
||||
def format_tokens_dtcg(tokens: dict) -> str:
|
||||
"""Pretty-print a DTCG document as JSON."""
|
||||
return json.dumps(tokens, indent=2, ensure_ascii=False) + "\n"
|
||||
|
||||
|
||||
def format_tokens_css(tokens: dict) -> str:
|
||||
"""CSS custom properties matching generate-tokens.cjs generateCSS()."""
|
||||
primitive = _flatten_tokens(tokens.get("primitive") or {}, tokens, ["primitive"])
|
||||
semantic = _flatten_tokens(tokens.get("semantic") or {}, tokens, [])
|
||||
component = _flatten_tokens(tokens.get("component") or {}, tokens, [])
|
||||
dark_semantic = _flatten_tokens(
|
||||
(tokens.get("dark") or {}).get("semantic") or {}, tokens, []
|
||||
)
|
||||
css = (
|
||||
"/* Design Tokens - Auto-generated */\n"
|
||||
"/* Do not edit directly - modify tokens.json instead */\n"
|
||||
"\n"
|
||||
"/* === PRIMITIVES === */\n"
|
||||
f"{_root_block(primitive)}\n"
|
||||
"\n"
|
||||
"/* === SEMANTIC === */\n"
|
||||
f"{_root_block(semantic)}\n"
|
||||
"\n"
|
||||
"/* === COMPONENTS === */\n"
|
||||
f"{_root_block(component)}\n"
|
||||
)
|
||||
if dark_semantic:
|
||||
dark_body = "\n".join(
|
||||
f" {name}: {value};" for name, value in dark_semantic.items()
|
||||
)
|
||||
css += f"\n/* === DARK MODE === */\n.dark {{\n{dark_body}\n}}\n"
|
||||
return css
|
||||
|
||||
|
||||
# ============ MAIN ENTRY POINT ============
|
||||
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, preview: bool = False) -> dict:
|
||||
force: bool = False, preview: bool = False,
|
||||
token_format: str = None) -> dict:
|
||||
"""
|
||||
Main entry point for design system generation.
|
||||
|
||||
@ -962,19 +1125,29 @@ def generate_design_system(query: str, project_name: str = None, output_format:
|
||||
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
|
||||
token_format: Optional "dtcg" or "css". When set, "text" is the token
|
||||
document and persist writes tokens.json (and tokens.css for css)
|
||||
next to MASTER.md. Tokens are master-level only; --page does not
|
||||
emit page-specific token files.
|
||||
|
||||
Returns:
|
||||
dict with keys: "text" (formatted design system string), "design_system"
|
||||
(raw dict, useful for --json callers), "persistence" (result of
|
||||
dict with keys: "text" (formatted design system or token string),
|
||||
"design_system" (raw dict, useful for --json callers), "tokens"
|
||||
(DTCG dict when token_format is set), "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)
|
||||
|
||||
tokens = build_design_tokens(design_system) if token_format else None
|
||||
|
||||
persistence_result = None
|
||||
if persist:
|
||||
persistence_result = persist_design_system(design_system, page, output_dir, query, force=force)
|
||||
persistence_result = persist_design_system(
|
||||
design_system, page, output_dir, query, force=force,
|
||||
token_format=token_format, tokens=tokens,
|
||||
)
|
||||
|
||||
preview_result = None
|
||||
if preview:
|
||||
@ -983,13 +1156,21 @@ def generate_design_system(query: str, project_name: str = None, output_format:
|
||||
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)
|
||||
if token_format == "css":
|
||||
text = format_tokens_css(tokens)
|
||||
elif token_format == "dtcg":
|
||||
text = format_tokens_dtcg(tokens)
|
||||
elif output_format == "markdown":
|
||||
text = format_markdown(design_system)
|
||||
else:
|
||||
text = format_ascii_box(design_system)
|
||||
|
||||
return {
|
||||
"text": text,
|
||||
"design_system": design_system,
|
||||
"persistence": persistence_result,
|
||||
"preview": preview_result,
|
||||
"tokens": tokens,
|
||||
}
|
||||
|
||||
|
||||
@ -1029,7 +1210,8 @@ def _write_persisted_file(path: Path, content: str, force: bool) -> None:
|
||||
|
||||
|
||||
def persist_design_system(design_system: dict, page: str = None, output_dir: str = None,
|
||||
page_query: str = None, force: bool = False) -> dict:
|
||||
page_query: str = None, force: bool = False,
|
||||
token_format: str = None, tokens: dict = None) -> dict:
|
||||
"""
|
||||
Persist design system to design-system/<project>/ folder using Master + Overrides pattern.
|
||||
|
||||
@ -1041,10 +1223,14 @@ def persist_design_system(design_system: dict, page: str = None, output_dir: str
|
||||
force: If True, overwrite an existing MASTER.md. If False (default) and
|
||||
MASTER.md already exists, persistence is skipped so prior design
|
||||
decisions aren't silently discarded.
|
||||
token_format: Optional "dtcg" or "css". When set, also write tokens.json
|
||||
next to MASTER.md (and tokens.css when css). Token files are
|
||||
master-level only; --page does not emit page-specific tokens.
|
||||
tokens: Optional pre-built DTCG dict; built from design_system when omitted.
|
||||
|
||||
Returns:
|
||||
dict with created file paths and status. status is "skipped_exists" if
|
||||
MASTER.md already existed and force was not set.
|
||||
no files were written because they already existed and force was not set.
|
||||
"""
|
||||
base_dir = Path(output_dir) if output_dir else Path.cwd()
|
||||
|
||||
@ -1066,23 +1252,28 @@ def persist_design_system(design_system: dict, page: str = None, output_dir: str
|
||||
|
||||
# Exclusive creation makes the default no-overwrite contract safe when
|
||||
# multiple agents persist the same project concurrently.
|
||||
master_content = format_master_md(design_system)
|
||||
master_content = format_master_md(design_system, token_format=token_format)
|
||||
try:
|
||||
_write_persisted_file(master_file, master_content, force)
|
||||
created_files.append(str(master_file))
|
||||
except FileExistsError:
|
||||
if not page:
|
||||
return {
|
||||
"status": "skipped_exists",
|
||||
"design_system_dir": str(design_system_dir),
|
||||
"master_file": str(master_file),
|
||||
"created_files": [],
|
||||
"message": (
|
||||
f"{master_file} already exists and was not modified. "
|
||||
"Read it first to check for prior design decisions, then "
|
||||
"re-run with force=True / --force to overwrite."
|
||||
),
|
||||
}
|
||||
pass
|
||||
|
||||
if token_format:
|
||||
token_doc = tokens if tokens is not None else build_design_tokens(design_system)
|
||||
json_path = design_system_dir / "tokens.json"
|
||||
try:
|
||||
_write_persisted_file(json_path, format_tokens_dtcg(token_doc), force)
|
||||
created_files.append(str(json_path))
|
||||
except FileExistsError:
|
||||
pass
|
||||
if token_format == "css":
|
||||
css_path = design_system_dir / "tokens.css"
|
||||
try:
|
||||
_write_persisted_file(css_path, format_tokens_css(token_doc), force)
|
||||
created_files.append(str(css_path))
|
||||
except FileExistsError:
|
||||
pass
|
||||
|
||||
# If page is specified, create page override file with intelligent content
|
||||
if page:
|
||||
@ -1092,14 +1283,21 @@ def persist_design_system(design_system: dict, page: str = None, output_dir: str
|
||||
_write_persisted_file(page_file, page_content, force)
|
||||
created_files.append(str(page_file))
|
||||
except FileExistsError:
|
||||
if not created_files:
|
||||
return {
|
||||
"status": "skipped_exists",
|
||||
"design_system_dir": str(design_system_dir),
|
||||
"master_file": str(master_file),
|
||||
"created_files": [],
|
||||
"message": f"{page_file} already exists and was not modified.",
|
||||
}
|
||||
pass
|
||||
|
||||
if not created_files:
|
||||
existing = master_file if master_file.exists() else design_system_dir
|
||||
return {
|
||||
"status": "skipped_exists",
|
||||
"design_system_dir": str(design_system_dir),
|
||||
"master_file": str(master_file),
|
||||
"created_files": [],
|
||||
"message": (
|
||||
f"{existing} already exists and was not modified. "
|
||||
"Read it first to check for prior design decisions, then "
|
||||
"re-run with force=True / --force to overwrite."
|
||||
),
|
||||
}
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
@ -1109,7 +1307,7 @@ def persist_design_system(design_system: dict, page: str = None, output_dir: str
|
||||
}
|
||||
|
||||
|
||||
def format_master_md(design_system: dict) -> str:
|
||||
def format_master_md(design_system: dict, token_format: str = None) -> str:
|
||||
"""Format design system as MASTER.md with hierarchical override logic."""
|
||||
project = design_system.get("project_name", "PROJECT")
|
||||
pattern = design_system.get("pattern", {})
|
||||
@ -1138,6 +1336,11 @@ def format_master_md(design_system: dict) -> str:
|
||||
lines.append(f"**Project:** {project}")
|
||||
lines.append(f"**Generated:** {timestamp}")
|
||||
lines.append(f"**Category:** {design_system.get('category', 'General')}")
|
||||
if token_format:
|
||||
lines.append("**Token files:** `tokens.json` (W3C Design Tokens Community Group JSON).")
|
||||
if token_format == "css":
|
||||
lines.append("**CSS variables:** `tokens.css` (`:root` custom properties).")
|
||||
lines.append("Token files are master-level only; `--page` overrides do not emit tokens.")
|
||||
if any(dials.get(k) is not None for k in ("variance", "motion", "density")):
|
||||
dial_parts = []
|
||||
if dials.get("variance") is not None:
|
||||
|
||||
@ -4,6 +4,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 --tokens dtcg|css
|
||||
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
|
||||
@ -17,13 +18,19 @@ Design dials (1-10, only with --design-system):
|
||||
--motion MOTION_INTENSITY: 1=subtle, 10=complex; attaches a GSAP snippet from motion.csv
|
||||
--density VISUAL_DENSITY: 1=spacious, 10=dense/dashboard; overrides the spacing scale
|
||||
|
||||
Token export (only with --design-system):
|
||||
--tokens dtcg Print W3C Design Tokens JSON (color, font, semantic layers)
|
||||
--tokens css Print :root CSS variables using the same names generate-tokens.cjs emits
|
||||
|
||||
Persistence (Master + Overrides pattern):
|
||||
--persist Save design system to design-system/<project-slug>/MASTER.md
|
||||
--output-dir Directory the design-system/ folder is created under (defaults to cwd --
|
||||
always pass this explicitly, pointed at the project root)
|
||||
--page Also create a page-specific override file in design-system/<project-slug>/pages/
|
||||
Token files are master-level only; --page does not emit page-specific tokens
|
||||
--force Overwrite an existing MASTER.md (without this, persistence is skipped
|
||||
if MASTER.md already exists, so prior design decisions aren't lost)
|
||||
With --tokens, also writes tokens.json (and tokens.css when --tokens css)
|
||||
--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.
|
||||
@ -127,6 +134,8 @@ if __name__ == "__main__":
|
||||
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)")
|
||||
parser.add_argument("--tokens", choices=["dtcg", "css"], default=None,
|
||||
help="Export design tokens as W3C DTCG JSON or CSS variables (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)")
|
||||
@ -136,6 +145,8 @@ if __name__ == "__main__":
|
||||
|
||||
if args.preview and not args.design_system:
|
||||
parser.error("--preview requires --design-system")
|
||||
if args.tokens and not args.design_system:
|
||||
parser.error("--tokens requires --design-system")
|
||||
|
||||
# Design system takes priority
|
||||
if args.design_system:
|
||||
@ -162,6 +173,7 @@ if __name__ == "__main__":
|
||||
density=args.density,
|
||||
force=args.force,
|
||||
preview=args.preview,
|
||||
token_format=args.tokens,
|
||||
)
|
||||
|
||||
if args.json:
|
||||
@ -171,33 +183,48 @@ if __name__ == "__main__":
|
||||
}
|
||||
if args.preview:
|
||||
payload["preview"] = result["preview"]
|
||||
if result.get("tokens") is not None:
|
||||
payload["tokens"] = result["tokens"]
|
||||
print(json_module.dumps(payload, indent=2, ensure_ascii=False))
|
||||
else:
|
||||
print(result["text"])
|
||||
# Token export is meant to be redirected; keep a trailing newline
|
||||
# matching generate-tokens.cjs stdout without doubling print()'s.
|
||||
text = result["text"]
|
||||
if args.tokens:
|
||||
sys.stdout.write(text if text.endswith("\n") else text + "\n")
|
||||
else:
|
||||
print(text)
|
||||
|
||||
if args.persist:
|
||||
persistence = result["persistence"] or {}
|
||||
print("\n" + "=" * 60)
|
||||
persist_stream = sys.stderr if args.tokens else sys.stdout
|
||||
print("\n" + "=" * 60, file=persist_stream)
|
||||
if persistence.get("status") == "skipped_exists":
|
||||
print(f"⚠️ {persistence.get('message', 'MASTER.md already exists; not overwritten.')}")
|
||||
print(f"⚠️ {persistence.get('message', 'MASTER.md already exists; not overwritten.')}",
|
||||
file=persist_stream)
|
||||
else:
|
||||
ds_dir = persistence.get("design_system_dir", "design-system/<project>")
|
||||
print(f"✅ Design system persisted to {ds_dir}/")
|
||||
print(f"✅ Design system persisted to {ds_dir}/", file=persist_stream)
|
||||
for f in persistence.get("created_files", []):
|
||||
print(f" 📄 {f}")
|
||||
print("")
|
||||
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)
|
||||
print(f" 📄 {f}", file=persist_stream)
|
||||
print("", file=persist_stream)
|
||||
print(f"📖 Usage: When building a page, check {ds_dir}/pages/[page].md first.",
|
||||
file=persist_stream)
|
||||
print(" If it exists, its rules override MASTER.md. Otherwise, use MASTER.md.",
|
||||
file=persist_stream)
|
||||
print("=" * 60, file=persist_stream)
|
||||
|
||||
if args.preview:
|
||||
preview = result["preview"] or {}
|
||||
print("\n" + "=" * 60)
|
||||
preview_stream = sys.stderr if args.tokens else sys.stdout
|
||||
print("\n" + "=" * 60, file=preview_stream)
|
||||
if preview.get("status") == "skipped_exists":
|
||||
print(f"⚠️ {preview.get('message', 'preview.html already exists; not overwritten.')}")
|
||||
print(f"⚠️ {preview.get('message', 'preview.html already exists; not overwritten.')}",
|
||||
file=preview_stream)
|
||||
else:
|
||||
print(f"✅ Design system preview: {preview.get('preview_file')}")
|
||||
print("=" * 60)
|
||||
print(f"✅ Design system preview: {preview.get('preview_file')}",
|
||||
file=preview_stream)
|
||||
print("=" * 60, file=preview_stream)
|
||||
# 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": "d0cb5803e094c21dc5262770f4a2dd8cecd20abf702896eea6ec69c357c54648",
|
||||
"runtimeFingerprint": "4f0d12f19a6be7fe7e3faf289244349f80497bac0ddb5563b0511e667953a225",
|
||||
"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.",
|
||||
|
||||
321
cli/assets/scripts/tests/test_design_system_tokens.py
Normal file
321
cli/assets/scripts/tests/test_design_system_tokens.py
Normal file
@ -0,0 +1,321 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Tests for --tokens dtcg|css export from the design-system generator.
|
||||
|
||||
Stdlib-only (unittest, not pytest) to match test_core.py -- this project ships
|
||||
with zero external dependencies. The generate-tokens.cjs round-trip is skipped
|
||||
when Node is missing; CI has Node.
|
||||
|
||||
Run with:
|
||||
python -m unittest discover -s scripts/tests -v
|
||||
or directly:
|
||||
python scripts/tests/test_design_system_tokens.py
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
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,
|
||||
_HEX6,
|
||||
build_design_tokens,
|
||||
format_tokens_css,
|
||||
format_tokens_dtcg,
|
||||
generate_design_system,
|
||||
)
|
||||
|
||||
ON_COLOR_PAIRS = (
|
||||
("on_primary", "primary"),
|
||||
("on_secondary", "secondary"),
|
||||
("on_accent", "accent"),
|
||||
("foreground", "background"),
|
||||
("card_foreground", "card"),
|
||||
("muted_foreground", "muted"),
|
||||
("on_destructive", "destructive"),
|
||||
)
|
||||
|
||||
SEARCH = SCRIPTS_DIR / "search.py"
|
||||
REPO = next(
|
||||
parent for parent in Path(__file__).resolve().parents
|
||||
if (parent / "cli" / "assets" / "skills" / "design-system" / "scripts"
|
||||
/ "generate-tokens.cjs").is_file()
|
||||
)
|
||||
GENERATE_TOKENS = (
|
||||
REPO / "cli" / "assets" / "skills" / "design-system" / "scripts"
|
||||
/ "generate-tokens.cjs"
|
||||
)
|
||||
HEX_TOKEN = re.compile(r"^#[0-9A-Fa-f]{6}$")
|
||||
CSS_VAR = re.compile(r"^\s+(--[a-z0-9-]+):\s*(.+);\s*$", re.MULTILINE)
|
||||
|
||||
|
||||
def _node_available():
|
||||
return shutil.which("node") is not None
|
||||
|
||||
|
||||
def _parse_css_vars(css: str) -> dict:
|
||||
return {name: value for name, value in CSS_VAR.findall(css)}
|
||||
|
||||
|
||||
class TokenExportTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.result = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", token_format="dtcg"
|
||||
)
|
||||
cls.ds = cls.result["design_system"]
|
||||
cls.tokens = cls.result["tokens"]
|
||||
|
||||
def test_color_mode_is_recorded(self):
|
||||
self.assertIn(self.ds["color_mode"], ("light", "dark"))
|
||||
|
||||
def test_dtcg_shape_matches_starter_conventions(self):
|
||||
tokens = self.tokens
|
||||
self.assertEqual(tokens["$schema"], "https://design-tokens.org/schema.json")
|
||||
self.assertIn("$description", tokens)
|
||||
self.assertIn(self.ds["color_mode"], tokens["$description"])
|
||||
self.assertIn("color", tokens)
|
||||
self.assertIn("font", tokens)
|
||||
self.assertIn("semantic", tokens)
|
||||
semantic_color = tokens["semantic"]["color"]
|
||||
for name in (
|
||||
"primary", "on-primary", "background", "foreground",
|
||||
"card", "muted", "border", "ring", "destructive",
|
||||
):
|
||||
self.assertIn(name, semantic_color)
|
||||
self.assertEqual(semantic_color[name]["$type"], "color")
|
||||
self.assertEqual(semantic_color[name]["$value"], "{color.%s}" % name)
|
||||
self.assertEqual(tokens["color"][name]["$type"], "color")
|
||||
self.assertRegex(tokens["color"][name]["$value"], HEX_TOKEN)
|
||||
for role in ("heading", "body"):
|
||||
self.assertEqual(tokens["font"][role]["$type"], "fontFamily")
|
||||
self.assertTrue(tokens["font"][role]["$value"])
|
||||
self.assertEqual(
|
||||
tokens["semantic"]["font"][role]["$value"], "{font.%s}" % role
|
||||
)
|
||||
|
||||
def test_every_exported_color_is_six_digit_hex(self):
|
||||
for name, token in self.tokens["color"].items():
|
||||
with self.subTest(color=name):
|
||||
self.assertEqual(token["$type"], "color")
|
||||
self.assertRegex(token["$value"], HEX_TOKEN)
|
||||
self.assertTrue(_HEX6.match(token["$value"]))
|
||||
|
||||
def test_on_color_pairs_reuse_generator_contrast(self):
|
||||
colors = self.ds["colors"]
|
||||
for foreground, background in ON_COLOR_PAIRS:
|
||||
with self.subTest(pair=foreground):
|
||||
self.assertGreaterEqual(
|
||||
_contrast_ratio(colors[foreground], colors[background]), 4.5
|
||||
)
|
||||
|
||||
def test_css_uses_generate_tokens_variable_names(self):
|
||||
css = format_tokens_css(self.tokens)
|
||||
variables = _parse_css_vars(css)
|
||||
for _label, key, css_var in SEMANTIC_COLOR_ENTRIES:
|
||||
hex_val = self.ds["colors"].get(key)
|
||||
if not hex_val:
|
||||
continue
|
||||
self.assertEqual(variables[css_var], hex_val)
|
||||
self.assertIn("--font-heading", variables)
|
||||
self.assertIn("--font-body", variables)
|
||||
self.assertTrue(css.strip().startswith("/* Design Tokens"))
|
||||
self.assertIn(":root {", css)
|
||||
|
||||
def test_dtcg_text_is_the_token_document(self):
|
||||
parsed = json.loads(self.result["text"])
|
||||
self.assertEqual(parsed["semantic"]["color"]["primary"]["$type"], "color")
|
||||
self.assertNotIn("TARGET:", self.result["text"])
|
||||
|
||||
def test_css_token_format_prints_css(self):
|
||||
result = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", token_format="css"
|
||||
)
|
||||
self.assertIn("--color-primary:", result["text"])
|
||||
self.assertEqual(result["tokens"]["color"]["primary"]["$value"],
|
||||
_parse_css_vars(result["text"])["--color-primary"])
|
||||
|
||||
def test_spacing_tokens_only_when_density_is_set(self):
|
||||
plain = build_design_tokens(
|
||||
generate_design_system("fintech dashboard", "Ledgerly")["design_system"]
|
||||
)
|
||||
dense = build_design_tokens(
|
||||
generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", density=9
|
||||
)["design_system"]
|
||||
)
|
||||
self.assertNotIn("space", plain)
|
||||
self.assertIn("space", dense)
|
||||
self.assertIn("xs", dense["semantic"]["space"])
|
||||
css_vars = _parse_css_vars(format_tokens_css(dense))
|
||||
self.assertIn("--space-xs", css_vars)
|
||||
|
||||
|
||||
class DarkModeTokenTest(unittest.TestCase):
|
||||
def test_dark_query_marks_mode_and_emits_dark_surfaces(self):
|
||||
result = generate_design_system(
|
||||
"dark mode developer tool", "Nightshift", token_format="dtcg"
|
||||
)
|
||||
ds = result["design_system"]
|
||||
tokens = result["tokens"]
|
||||
self.assertEqual(ds["color_mode"], "dark")
|
||||
self.assertIn("dark", tokens["$description"].lower())
|
||||
background = tokens["color"]["background"]["$value"]
|
||||
foreground = tokens["color"]["foreground"]["$value"]
|
||||
self.assertRegex(background, HEX_TOKEN)
|
||||
self.assertGreater(
|
||||
_contrast_ratio(foreground, background), 4.5
|
||||
)
|
||||
css = format_tokens_css(tokens)
|
||||
self.assertEqual(_parse_css_vars(css)["--color-background"], background)
|
||||
|
||||
|
||||
class PersistTokenTest(unittest.TestCase):
|
||||
def test_persist_dtcg_writes_tokens_json_beside_master(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
result = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", persist=True, output_dir=tmp,
|
||||
token_format="dtcg",
|
||||
)
|
||||
folder = Path(tmp) / "design-system" / "ledgerly"
|
||||
master = folder / "MASTER.md"
|
||||
tokens_json = folder / "tokens.json"
|
||||
self.assertTrue(master.exists())
|
||||
self.assertTrue(tokens_json.exists())
|
||||
self.assertFalse((folder / "tokens.css").exists())
|
||||
self.assertIn(str(tokens_json), result["persistence"]["created_files"])
|
||||
master_text = master.read_text(encoding="utf-8")
|
||||
self.assertIn("tokens.json", master_text)
|
||||
self.assertIn("master-level only", master_text)
|
||||
parsed = json.loads(tokens_json.read_text(encoding="utf-8"))
|
||||
self.assertEqual(parsed["semantic"]["color"]["primary"]["$type"], "color")
|
||||
|
||||
def test_persist_css_writes_json_and_css(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", persist=True, output_dir=tmp,
|
||||
token_format="css",
|
||||
)
|
||||
folder = Path(tmp) / "design-system" / "ledgerly"
|
||||
css_text = (folder / "tokens.css").read_text(encoding="utf-8")
|
||||
self.assertIn("--color-primary:", css_text)
|
||||
master = (folder / "MASTER.md").read_text(encoding="utf-8")
|
||||
self.assertIn("tokens.css", master)
|
||||
|
||||
def test_page_overrides_do_not_write_page_tokens(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
result = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", persist=True, page="dashboard",
|
||||
output_dir=tmp, token_format="dtcg",
|
||||
)
|
||||
folder = Path(tmp) / "design-system" / "ledgerly"
|
||||
page = folder / "pages" / "dashboard.md"
|
||||
self.assertTrue(page.exists())
|
||||
self.assertTrue((folder / "tokens.json").exists())
|
||||
self.assertFalse((folder / "pages" / "tokens.json").exists())
|
||||
created = result["persistence"]["created_files"]
|
||||
self.assertTrue(any(path.endswith("tokens.json") for path in created))
|
||||
self.assertTrue(any(path.endswith("dashboard.md") for path in created))
|
||||
|
||||
def test_skip_if_exists_then_force(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
first = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", persist=True, output_dir=tmp,
|
||||
token_format="dtcg",
|
||||
)
|
||||
tokens_json = Path(first["persistence"]["design_system_dir"]) / "tokens.json"
|
||||
original = tokens_json.read_text(encoding="utf-8")
|
||||
skipped = generate_design_system(
|
||||
"beauty spa", "Ledgerly", persist=True, output_dir=tmp,
|
||||
token_format="dtcg",
|
||||
)
|
||||
self.assertEqual(skipped["persistence"]["status"], "skipped_exists")
|
||||
self.assertEqual(tokens_json.read_text(encoding="utf-8"), original)
|
||||
forced = generate_design_system(
|
||||
"beauty spa", "Ledgerly", persist=True, output_dir=tmp,
|
||||
token_format="dtcg", force=True,
|
||||
)
|
||||
self.assertEqual(forced["persistence"]["status"], "success")
|
||||
self.assertNotEqual(tokens_json.read_text(encoding="utf-8"), original)
|
||||
|
||||
|
||||
class TokenCliTest(unittest.TestCase):
|
||||
def run_search(self, *args):
|
||||
return subprocess.run(
|
||||
[sys.executable, str(SEARCH), *map(str, args)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=False,
|
||||
)
|
||||
|
||||
def test_tokens_without_design_system_is_an_argparse_error(self):
|
||||
proc = self.run_search("fintech dashboard", "--tokens", "dtcg")
|
||||
self.assertNotEqual(proc.returncode, 0)
|
||||
self.assertIn("--tokens", proc.stderr)
|
||||
self.assertIn("--design-system", proc.stderr)
|
||||
|
||||
def test_cli_dtcg_stdout_is_json(self):
|
||||
proc = self.run_search(
|
||||
"fintech dashboard", "--design-system", "--tokens", "dtcg",
|
||||
"-p", "Ledgerly",
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
payload = json.loads(proc.stdout)
|
||||
self.assertEqual(payload["semantic"]["color"]["primary"]["$type"], "color")
|
||||
|
||||
def test_cli_css_stdout_has_root_variables(self):
|
||||
proc = self.run_search(
|
||||
"fintech dashboard", "--design-system", "--tokens", "css",
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
self.assertIn(":root {", proc.stdout)
|
||||
self.assertIn("--color-primary:", proc.stdout)
|
||||
|
||||
def test_json_payload_includes_tokens(self):
|
||||
proc = self.run_search(
|
||||
"fintech dashboard", "--design-system", "--tokens", "dtcg", "--json",
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
payload = json.loads(proc.stdout)
|
||||
self.assertIn("design_system", payload)
|
||||
self.assertIn("tokens", payload)
|
||||
self.assertIn("primary", payload["tokens"]["color"])
|
||||
|
||||
|
||||
@unittest.skipUnless(_node_available(), "Node.js is required to round-trip tokens through generate-tokens.cjs")
|
||||
class GenerateTokensRoundTripTest(unittest.TestCase):
|
||||
def test_cjs_css_matches_tokens_css_output(self):
|
||||
result = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", token_format="css"
|
||||
)
|
||||
python_css = format_tokens_css(result["tokens"])
|
||||
self.assertEqual(python_css, result["text"])
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
json_path = Path(tmp) / "tokens.json"
|
||||
cjs_css_path = Path(tmp) / "from-cjs.css"
|
||||
json_path.write_text(format_tokens_dtcg(result["tokens"]), encoding="utf-8")
|
||||
proc = subprocess.run(
|
||||
["node", str(GENERATE_TOKENS), "--config", str(json_path),
|
||||
"-o", str(cjs_css_path)],
|
||||
capture_output=True, text=True, encoding="utf-8", check=False,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
cjs_css = cjs_css_path.read_text(encoding="utf-8")
|
||||
self.assertEqual(cjs_css, python_css)
|
||||
self.assertEqual(_parse_css_vars(cjs_css), _parse_css_vars(python_css))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@ -127,6 +127,24 @@ python3 {{SCRIPT_PATH}} "<query>" --design-system --persist --preview -p "Projec
|
||||
|
||||
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.
|
||||
|
||||
### Step 2b-tokens: Export Design Tokens
|
||||
|
||||
`--tokens` is valid only with `--design-system`. It prints a machine-readable token document so hex values and font names do not have to be copied by hand:
|
||||
|
||||
```bash
|
||||
python3 {{SCRIPT_PATH}} "<query>" --design-system --tokens dtcg
|
||||
python3 {{SCRIPT_PATH}} "<query>" --design-system --tokens css
|
||||
```
|
||||
|
||||
- `dtcg` prints W3C Design Tokens Community Group JSON (`$value` / `$type`, `color`, `font`, and a `semantic` layer such as `color.primary`, `color.on-primary`, `color.background`, `font.heading`).
|
||||
- `css` prints `:root` custom properties using the same names `../design-system/scripts/generate-tokens.cjs` emits (`--color-primary`, `--font-heading`, …).
|
||||
- Dark-mode results emit the resolved dark values and record the mode in `$description`.
|
||||
- With `--persist`, also write `tokens.json` next to `MASTER.md` (and `tokens.css` when `--tokens css`). Existing files follow the same `--force` / skip-if-exists rules. Token files are master-level only; `--page` overrides do not emit page-specific tokens.
|
||||
|
||||
```bash
|
||||
python3 {{SCRIPT_PATH}} "<query>" --design-system --persist --tokens dtcg -p "Project Name" --output-dir "<project-root>"
|
||||
```
|
||||
|
||||
**How hierarchical retrieval works:**
|
||||
1. Read `design-system/<project-slug>/MASTER.md`
|
||||
2. When building a specific page (e.g., "Checkout"), check `design-system/<project-slug>/pages/checkout.md`
|
||||
@ -278,7 +296,7 @@ python3 {{SCRIPT_PATH}} "streaming suspense" --stack nextjs
|
||||
|
||||
## Output Formats
|
||||
|
||||
The `--design-system` flag supports two output formats:
|
||||
The `--design-system` flag supports ASCII, Markdown, JSON, and token export:
|
||||
|
||||
```bash
|
||||
# ASCII box (default) - best for terminal display
|
||||
@ -286,6 +304,10 @@ python3 {{SCRIPT_PATH}} "fintech crypto" --design-system
|
||||
|
||||
# Markdown - best for documentation
|
||||
python3 {{SCRIPT_PATH}} "fintech crypto" --design-system -f markdown
|
||||
|
||||
# Design tokens (requires --design-system)
|
||||
python3 {{SCRIPT_PATH}} "fintech crypto" --design-system --tokens dtcg
|
||||
python3 {{SCRIPT_PATH}} "fintech crypto" --design-system --tokens css
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@ -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 = 18;
|
||||
const SEARCH_COMMAND_COUNT = 23;
|
||||
|
||||
function extractSearchScriptPaths(content: string): string[] {
|
||||
return [...content.matchAll(/^python3\s+(\S*search\.py)\b/gm)].map(match => match[1]);
|
||||
|
||||
@ -26,7 +26,8 @@ FLAGS = {
|
||||
"--domain", "-d", "--stack", "-s", "--max-results", "-n", "--json",
|
||||
"--full", "--design-system", "-ds", "--project-name", "-p", "--format",
|
||||
"-f", "--persist", "--page", "--output-dir", "-o", "--force", "--preview",
|
||||
"--variance", "--motion", "--density",
|
||||
"--variance", "--motion", "--density", "--tokens",
|
||||
|
||||
}
|
||||
PLATFORM_COUNT = 25
|
||||
GUIDE_REQUIREMENTS = (
|
||||
|
||||
@ -594,7 +594,9 @@ class DesignSystemGenerator:
|
||||
"mood": best_typography.get("Mood/Style Keywords", reasoning.get("typography_mood", "")),
|
||||
"best_for": best_typography.get("Best For", ""),
|
||||
"google_fonts_url": best_typography.get("Google Fonts URL", ""),
|
||||
"css_import": best_typography.get("CSS Import", "")
|
||||
"css_import": best_typography.get("CSS Import", ""),
|
||||
"tailwind_config": best_typography.get("Tailwind Config", ""),
|
||||
"category": best_typography.get("Category", ""),
|
||||
},
|
||||
"key_effects": combined_effects,
|
||||
"anti_patterns": _filter_anti_patterns_for_mode(
|
||||
@ -941,11 +943,172 @@ def format_markdown(design_system: dict) -> str:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ============ DESIGN TOKENS (DTCG / CSS) ============
|
||||
# Token names follow SEMANTIC_COLOR_ENTRIES CSS variables so --tokens css
|
||||
# and cli/assets/skills/design-system/scripts/generate-tokens.cjs agree:
|
||||
# semantic.color.primary -> --color-primary.
|
||||
TOKEN_SCHEMA = "https://design-tokens.org/schema.json"
|
||||
_HEX6 = re.compile(r"^#[0-9A-Fa-f]{6}$")
|
||||
_TW_FONT_PAIR = re.compile(r"\['([^']+)',\s*'([^']+)'\]")
|
||||
|
||||
|
||||
def _css_font_family(font_name: str, tailwind_config: str = "") -> str:
|
||||
"""CSS font-family stack using the pairing's Tailwind Config fallback when present."""
|
||||
name = (font_name or "").strip()
|
||||
if not name:
|
||||
return ""
|
||||
generic = "sans-serif"
|
||||
for listed_name, fallback in _TW_FONT_PAIR.findall(tailwind_config or ""):
|
||||
if listed_name == name and fallback:
|
||||
generic = fallback
|
||||
break
|
||||
quoted = f'"{name}"' if (" " in name or "," in name) else name
|
||||
return f"{quoted}, {generic}"
|
||||
|
||||
|
||||
def _token_color_entries(colors: dict):
|
||||
"""Yield (kebab-name, hex) for 6-digit palette roles the design system actually has."""
|
||||
for _label, key, _css_var in SEMANTIC_COLOR_ENTRIES:
|
||||
hex_val = (colors or {}).get(key, "")
|
||||
if not hex_val:
|
||||
continue
|
||||
value = str(hex_val).strip()
|
||||
if _HEX6.match(value):
|
||||
yield key.replace("_", "-"), value
|
||||
|
||||
|
||||
def _resolve_token_reference(value, tokens):
|
||||
"""Resolve DTCG `{group.token}` references the same way generate-tokens.cjs does."""
|
||||
if not isinstance(value, str) or not value.startswith("{") or not value.endswith("}"):
|
||||
return value
|
||||
node = tokens
|
||||
for key in value[1:-1].split("."):
|
||||
if not isinstance(node, dict):
|
||||
return value
|
||||
node = node.get(key)
|
||||
if isinstance(node, dict) and "$value" in node:
|
||||
return _resolve_token_reference(node["$value"], tokens)
|
||||
return value if node is None else node
|
||||
|
||||
|
||||
def _flatten_tokens(obj, tokens, prefix=None, result=None):
|
||||
"""Flatten a DTCG group into CSS custom properties (generate-tokens.cjs flattenTokens)."""
|
||||
prefix = prefix or []
|
||||
result = {} if result is None else result
|
||||
if not isinstance(obj, dict):
|
||||
return result
|
||||
for key, value in obj.items():
|
||||
if not isinstance(value, dict):
|
||||
continue
|
||||
current = prefix + [key]
|
||||
if "$value" in value:
|
||||
css_var = "--" + "-".join(current).replace(".", "-")
|
||||
result[css_var] = _resolve_token_reference(value["$value"], tokens)
|
||||
else:
|
||||
_flatten_tokens(value, tokens, current, result)
|
||||
return result
|
||||
|
||||
|
||||
def _root_block(mapping: dict) -> str:
|
||||
body = "\n".join(f" {name}: {value};" for name, value in mapping.items())
|
||||
return f":root {{\n{body}\n}}"
|
||||
|
||||
|
||||
def build_design_tokens(design_system: dict) -> dict:
|
||||
"""W3C DTCG document for a generated design system. Invents nothing beyond CSS generic fallbacks."""
|
||||
colors = design_system.get("colors") or {}
|
||||
typography = design_system.get("typography") or {}
|
||||
mode = design_system.get("color_mode") or "light"
|
||||
derivation = (design_system.get("source_derivations") or {}).get("color_mode")
|
||||
project = design_system.get("project_name") or "PROJECT"
|
||||
description = f"Design tokens for {project} ({mode} mode)."
|
||||
if derivation == "derived-dark":
|
||||
description += " Surface colors were derived for dark mode from the product palette."
|
||||
|
||||
color_group = {}
|
||||
semantic_color = {}
|
||||
for name, hex_val in _token_color_entries(colors):
|
||||
color_group[name] = {"$value": hex_val, "$type": "color"}
|
||||
semantic_color[name] = {"$value": f"{{color.{name}}}", "$type": "color"}
|
||||
|
||||
tailwind_config = typography.get("tailwind_config", "")
|
||||
font_group = {}
|
||||
semantic_font = {}
|
||||
for role in ("heading", "body"):
|
||||
stack = _css_font_family(typography.get(role, ""), tailwind_config)
|
||||
if not stack:
|
||||
continue
|
||||
font_group[role] = {"$value": stack, "$type": "fontFamily"}
|
||||
semantic_font[role] = {"$value": f"{{font.{role}}}", "$type": "fontFamily"}
|
||||
|
||||
tokens = {
|
||||
"$schema": TOKEN_SCHEMA,
|
||||
"$description": description,
|
||||
"color": color_group,
|
||||
"font": font_group,
|
||||
"semantic": {},
|
||||
}
|
||||
if semantic_color:
|
||||
tokens["semantic"]["color"] = semantic_color
|
||||
if semantic_font:
|
||||
tokens["semantic"]["font"] = semantic_font
|
||||
|
||||
spacing_scale = design_system.get("spacing_scale")
|
||||
if spacing_scale:
|
||||
space_group = {}
|
||||
semantic_space = {}
|
||||
for token, px_value in spacing_scale.items():
|
||||
if not px_value:
|
||||
continue
|
||||
space_group[token] = {"$value": px_value, "$type": "dimension"}
|
||||
semantic_space[token] = {"$value": f"{{space.{token}}}", "$type": "dimension"}
|
||||
if space_group:
|
||||
tokens["space"] = space_group
|
||||
tokens["semantic"]["space"] = semantic_space
|
||||
|
||||
return tokens
|
||||
|
||||
|
||||
def format_tokens_dtcg(tokens: dict) -> str:
|
||||
"""Pretty-print a DTCG document as JSON."""
|
||||
return json.dumps(tokens, indent=2, ensure_ascii=False) + "\n"
|
||||
|
||||
|
||||
def format_tokens_css(tokens: dict) -> str:
|
||||
"""CSS custom properties matching generate-tokens.cjs generateCSS()."""
|
||||
primitive = _flatten_tokens(tokens.get("primitive") or {}, tokens, ["primitive"])
|
||||
semantic = _flatten_tokens(tokens.get("semantic") or {}, tokens, [])
|
||||
component = _flatten_tokens(tokens.get("component") or {}, tokens, [])
|
||||
dark_semantic = _flatten_tokens(
|
||||
(tokens.get("dark") or {}).get("semantic") or {}, tokens, []
|
||||
)
|
||||
css = (
|
||||
"/* Design Tokens - Auto-generated */\n"
|
||||
"/* Do not edit directly - modify tokens.json instead */\n"
|
||||
"\n"
|
||||
"/* === PRIMITIVES === */\n"
|
||||
f"{_root_block(primitive)}\n"
|
||||
"\n"
|
||||
"/* === SEMANTIC === */\n"
|
||||
f"{_root_block(semantic)}\n"
|
||||
"\n"
|
||||
"/* === COMPONENTS === */\n"
|
||||
f"{_root_block(component)}\n"
|
||||
)
|
||||
if dark_semantic:
|
||||
dark_body = "\n".join(
|
||||
f" {name}: {value};" for name, value in dark_semantic.items()
|
||||
)
|
||||
css += f"\n/* === DARK MODE === */\n.dark {{\n{dark_body}\n}}\n"
|
||||
return css
|
||||
|
||||
|
||||
# ============ MAIN ENTRY POINT ============
|
||||
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, preview: bool = False) -> dict:
|
||||
force: bool = False, preview: bool = False,
|
||||
token_format: str = None) -> dict:
|
||||
"""
|
||||
Main entry point for design system generation.
|
||||
|
||||
@ -962,19 +1125,29 @@ def generate_design_system(query: str, project_name: str = None, output_format:
|
||||
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
|
||||
token_format: Optional "dtcg" or "css". When set, "text" is the token
|
||||
document and persist writes tokens.json (and tokens.css for css)
|
||||
next to MASTER.md. Tokens are master-level only; --page does not
|
||||
emit page-specific token files.
|
||||
|
||||
Returns:
|
||||
dict with keys: "text" (formatted design system string), "design_system"
|
||||
(raw dict, useful for --json callers), "persistence" (result of
|
||||
dict with keys: "text" (formatted design system or token string),
|
||||
"design_system" (raw dict, useful for --json callers), "tokens"
|
||||
(DTCG dict when token_format is set), "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)
|
||||
|
||||
tokens = build_design_tokens(design_system) if token_format else None
|
||||
|
||||
persistence_result = None
|
||||
if persist:
|
||||
persistence_result = persist_design_system(design_system, page, output_dir, query, force=force)
|
||||
persistence_result = persist_design_system(
|
||||
design_system, page, output_dir, query, force=force,
|
||||
token_format=token_format, tokens=tokens,
|
||||
)
|
||||
|
||||
preview_result = None
|
||||
if preview:
|
||||
@ -983,13 +1156,21 @@ def generate_design_system(query: str, project_name: str = None, output_format:
|
||||
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)
|
||||
if token_format == "css":
|
||||
text = format_tokens_css(tokens)
|
||||
elif token_format == "dtcg":
|
||||
text = format_tokens_dtcg(tokens)
|
||||
elif output_format == "markdown":
|
||||
text = format_markdown(design_system)
|
||||
else:
|
||||
text = format_ascii_box(design_system)
|
||||
|
||||
return {
|
||||
"text": text,
|
||||
"design_system": design_system,
|
||||
"persistence": persistence_result,
|
||||
"preview": preview_result,
|
||||
"tokens": tokens,
|
||||
}
|
||||
|
||||
|
||||
@ -1029,7 +1210,8 @@ def _write_persisted_file(path: Path, content: str, force: bool) -> None:
|
||||
|
||||
|
||||
def persist_design_system(design_system: dict, page: str = None, output_dir: str = None,
|
||||
page_query: str = None, force: bool = False) -> dict:
|
||||
page_query: str = None, force: bool = False,
|
||||
token_format: str = None, tokens: dict = None) -> dict:
|
||||
"""
|
||||
Persist design system to design-system/<project>/ folder using Master + Overrides pattern.
|
||||
|
||||
@ -1041,10 +1223,14 @@ def persist_design_system(design_system: dict, page: str = None, output_dir: str
|
||||
force: If True, overwrite an existing MASTER.md. If False (default) and
|
||||
MASTER.md already exists, persistence is skipped so prior design
|
||||
decisions aren't silently discarded.
|
||||
token_format: Optional "dtcg" or "css". When set, also write tokens.json
|
||||
next to MASTER.md (and tokens.css when css). Token files are
|
||||
master-level only; --page does not emit page-specific tokens.
|
||||
tokens: Optional pre-built DTCG dict; built from design_system when omitted.
|
||||
|
||||
Returns:
|
||||
dict with created file paths and status. status is "skipped_exists" if
|
||||
MASTER.md already existed and force was not set.
|
||||
no files were written because they already existed and force was not set.
|
||||
"""
|
||||
base_dir = Path(output_dir) if output_dir else Path.cwd()
|
||||
|
||||
@ -1066,23 +1252,28 @@ def persist_design_system(design_system: dict, page: str = None, output_dir: str
|
||||
|
||||
# Exclusive creation makes the default no-overwrite contract safe when
|
||||
# multiple agents persist the same project concurrently.
|
||||
master_content = format_master_md(design_system)
|
||||
master_content = format_master_md(design_system, token_format=token_format)
|
||||
try:
|
||||
_write_persisted_file(master_file, master_content, force)
|
||||
created_files.append(str(master_file))
|
||||
except FileExistsError:
|
||||
if not page:
|
||||
return {
|
||||
"status": "skipped_exists",
|
||||
"design_system_dir": str(design_system_dir),
|
||||
"master_file": str(master_file),
|
||||
"created_files": [],
|
||||
"message": (
|
||||
f"{master_file} already exists and was not modified. "
|
||||
"Read it first to check for prior design decisions, then "
|
||||
"re-run with force=True / --force to overwrite."
|
||||
),
|
||||
}
|
||||
pass
|
||||
|
||||
if token_format:
|
||||
token_doc = tokens if tokens is not None else build_design_tokens(design_system)
|
||||
json_path = design_system_dir / "tokens.json"
|
||||
try:
|
||||
_write_persisted_file(json_path, format_tokens_dtcg(token_doc), force)
|
||||
created_files.append(str(json_path))
|
||||
except FileExistsError:
|
||||
pass
|
||||
if token_format == "css":
|
||||
css_path = design_system_dir / "tokens.css"
|
||||
try:
|
||||
_write_persisted_file(css_path, format_tokens_css(token_doc), force)
|
||||
created_files.append(str(css_path))
|
||||
except FileExistsError:
|
||||
pass
|
||||
|
||||
# If page is specified, create page override file with intelligent content
|
||||
if page:
|
||||
@ -1092,14 +1283,21 @@ def persist_design_system(design_system: dict, page: str = None, output_dir: str
|
||||
_write_persisted_file(page_file, page_content, force)
|
||||
created_files.append(str(page_file))
|
||||
except FileExistsError:
|
||||
if not created_files:
|
||||
return {
|
||||
"status": "skipped_exists",
|
||||
"design_system_dir": str(design_system_dir),
|
||||
"master_file": str(master_file),
|
||||
"created_files": [],
|
||||
"message": f"{page_file} already exists and was not modified.",
|
||||
}
|
||||
pass
|
||||
|
||||
if not created_files:
|
||||
existing = master_file if master_file.exists() else design_system_dir
|
||||
return {
|
||||
"status": "skipped_exists",
|
||||
"design_system_dir": str(design_system_dir),
|
||||
"master_file": str(master_file),
|
||||
"created_files": [],
|
||||
"message": (
|
||||
f"{existing} already exists and was not modified. "
|
||||
"Read it first to check for prior design decisions, then "
|
||||
"re-run with force=True / --force to overwrite."
|
||||
),
|
||||
}
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
@ -1109,7 +1307,7 @@ def persist_design_system(design_system: dict, page: str = None, output_dir: str
|
||||
}
|
||||
|
||||
|
||||
def format_master_md(design_system: dict) -> str:
|
||||
def format_master_md(design_system: dict, token_format: str = None) -> str:
|
||||
"""Format design system as MASTER.md with hierarchical override logic."""
|
||||
project = design_system.get("project_name", "PROJECT")
|
||||
pattern = design_system.get("pattern", {})
|
||||
@ -1138,6 +1336,11 @@ def format_master_md(design_system: dict) -> str:
|
||||
lines.append(f"**Project:** {project}")
|
||||
lines.append(f"**Generated:** {timestamp}")
|
||||
lines.append(f"**Category:** {design_system.get('category', 'General')}")
|
||||
if token_format:
|
||||
lines.append("**Token files:** `tokens.json` (W3C Design Tokens Community Group JSON).")
|
||||
if token_format == "css":
|
||||
lines.append("**CSS variables:** `tokens.css` (`:root` custom properties).")
|
||||
lines.append("Token files are master-level only; `--page` overrides do not emit tokens.")
|
||||
if any(dials.get(k) is not None for k in ("variance", "motion", "density")):
|
||||
dial_parts = []
|
||||
if dials.get("variance") is not None:
|
||||
|
||||
@ -4,6 +4,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 --tokens dtcg|css
|
||||
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
|
||||
@ -17,13 +18,19 @@ Design dials (1-10, only with --design-system):
|
||||
--motion MOTION_INTENSITY: 1=subtle, 10=complex; attaches a GSAP snippet from motion.csv
|
||||
--density VISUAL_DENSITY: 1=spacious, 10=dense/dashboard; overrides the spacing scale
|
||||
|
||||
Token export (only with --design-system):
|
||||
--tokens dtcg Print W3C Design Tokens JSON (color, font, semantic layers)
|
||||
--tokens css Print :root CSS variables using the same names generate-tokens.cjs emits
|
||||
|
||||
Persistence (Master + Overrides pattern):
|
||||
--persist Save design system to design-system/<project-slug>/MASTER.md
|
||||
--output-dir Directory the design-system/ folder is created under (defaults to cwd --
|
||||
always pass this explicitly, pointed at the project root)
|
||||
--page Also create a page-specific override file in design-system/<project-slug>/pages/
|
||||
Token files are master-level only; --page does not emit page-specific tokens
|
||||
--force Overwrite an existing MASTER.md (without this, persistence is skipped
|
||||
if MASTER.md already exists, so prior design decisions aren't lost)
|
||||
With --tokens, also writes tokens.json (and tokens.css when --tokens css)
|
||||
--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.
|
||||
@ -127,6 +134,8 @@ if __name__ == "__main__":
|
||||
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)")
|
||||
parser.add_argument("--tokens", choices=["dtcg", "css"], default=None,
|
||||
help="Export design tokens as W3C DTCG JSON or CSS variables (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)")
|
||||
@ -136,6 +145,8 @@ if __name__ == "__main__":
|
||||
|
||||
if args.preview and not args.design_system:
|
||||
parser.error("--preview requires --design-system")
|
||||
if args.tokens and not args.design_system:
|
||||
parser.error("--tokens requires --design-system")
|
||||
|
||||
# Design system takes priority
|
||||
if args.design_system:
|
||||
@ -162,6 +173,7 @@ if __name__ == "__main__":
|
||||
density=args.density,
|
||||
force=args.force,
|
||||
preview=args.preview,
|
||||
token_format=args.tokens,
|
||||
)
|
||||
|
||||
if args.json:
|
||||
@ -171,33 +183,48 @@ if __name__ == "__main__":
|
||||
}
|
||||
if args.preview:
|
||||
payload["preview"] = result["preview"]
|
||||
if result.get("tokens") is not None:
|
||||
payload["tokens"] = result["tokens"]
|
||||
print(json_module.dumps(payload, indent=2, ensure_ascii=False))
|
||||
else:
|
||||
print(result["text"])
|
||||
# Token export is meant to be redirected; keep a trailing newline
|
||||
# matching generate-tokens.cjs stdout without doubling print()'s.
|
||||
text = result["text"]
|
||||
if args.tokens:
|
||||
sys.stdout.write(text if text.endswith("\n") else text + "\n")
|
||||
else:
|
||||
print(text)
|
||||
|
||||
if args.persist:
|
||||
persistence = result["persistence"] or {}
|
||||
print("\n" + "=" * 60)
|
||||
persist_stream = sys.stderr if args.tokens else sys.stdout
|
||||
print("\n" + "=" * 60, file=persist_stream)
|
||||
if persistence.get("status") == "skipped_exists":
|
||||
print(f"⚠️ {persistence.get('message', 'MASTER.md already exists; not overwritten.')}")
|
||||
print(f"⚠️ {persistence.get('message', 'MASTER.md already exists; not overwritten.')}",
|
||||
file=persist_stream)
|
||||
else:
|
||||
ds_dir = persistence.get("design_system_dir", "design-system/<project>")
|
||||
print(f"✅ Design system persisted to {ds_dir}/")
|
||||
print(f"✅ Design system persisted to {ds_dir}/", file=persist_stream)
|
||||
for f in persistence.get("created_files", []):
|
||||
print(f" 📄 {f}")
|
||||
print("")
|
||||
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)
|
||||
print(f" 📄 {f}", file=persist_stream)
|
||||
print("", file=persist_stream)
|
||||
print(f"📖 Usage: When building a page, check {ds_dir}/pages/[page].md first.",
|
||||
file=persist_stream)
|
||||
print(" If it exists, its rules override MASTER.md. Otherwise, use MASTER.md.",
|
||||
file=persist_stream)
|
||||
print("=" * 60, file=persist_stream)
|
||||
|
||||
if args.preview:
|
||||
preview = result["preview"] or {}
|
||||
print("\n" + "=" * 60)
|
||||
preview_stream = sys.stderr if args.tokens else sys.stdout
|
||||
print("\n" + "=" * 60, file=preview_stream)
|
||||
if preview.get("status") == "skipped_exists":
|
||||
print(f"⚠️ {preview.get('message', 'preview.html already exists; not overwritten.')}")
|
||||
print(f"⚠️ {preview.get('message', 'preview.html already exists; not overwritten.')}",
|
||||
file=preview_stream)
|
||||
else:
|
||||
print(f"✅ Design system preview: {preview.get('preview_file')}")
|
||||
print("=" * 60)
|
||||
print(f"✅ Design system preview: {preview.get('preview_file')}",
|
||||
file=preview_stream)
|
||||
print("=" * 60, file=preview_stream)
|
||||
# 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": "d0cb5803e094c21dc5262770f4a2dd8cecd20abf702896eea6ec69c357c54648",
|
||||
"runtimeFingerprint": "4f0d12f19a6be7fe7e3faf289244349f80497bac0ddb5563b0511e667953a225",
|
||||
"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.",
|
||||
|
||||
321
src/ui-ux-pro-max/scripts/tests/test_design_system_tokens.py
Normal file
321
src/ui-ux-pro-max/scripts/tests/test_design_system_tokens.py
Normal file
@ -0,0 +1,321 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Tests for --tokens dtcg|css export from the design-system generator.
|
||||
|
||||
Stdlib-only (unittest, not pytest) to match test_core.py -- this project ships
|
||||
with zero external dependencies. The generate-tokens.cjs round-trip is skipped
|
||||
when Node is missing; CI has Node.
|
||||
|
||||
Run with:
|
||||
python -m unittest discover -s scripts/tests -v
|
||||
or directly:
|
||||
python scripts/tests/test_design_system_tokens.py
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
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,
|
||||
_HEX6,
|
||||
build_design_tokens,
|
||||
format_tokens_css,
|
||||
format_tokens_dtcg,
|
||||
generate_design_system,
|
||||
)
|
||||
|
||||
ON_COLOR_PAIRS = (
|
||||
("on_primary", "primary"),
|
||||
("on_secondary", "secondary"),
|
||||
("on_accent", "accent"),
|
||||
("foreground", "background"),
|
||||
("card_foreground", "card"),
|
||||
("muted_foreground", "muted"),
|
||||
("on_destructive", "destructive"),
|
||||
)
|
||||
|
||||
SEARCH = SCRIPTS_DIR / "search.py"
|
||||
REPO = next(
|
||||
parent for parent in Path(__file__).resolve().parents
|
||||
if (parent / "cli" / "assets" / "skills" / "design-system" / "scripts"
|
||||
/ "generate-tokens.cjs").is_file()
|
||||
)
|
||||
GENERATE_TOKENS = (
|
||||
REPO / "cli" / "assets" / "skills" / "design-system" / "scripts"
|
||||
/ "generate-tokens.cjs"
|
||||
)
|
||||
HEX_TOKEN = re.compile(r"^#[0-9A-Fa-f]{6}$")
|
||||
CSS_VAR = re.compile(r"^\s+(--[a-z0-9-]+):\s*(.+);\s*$", re.MULTILINE)
|
||||
|
||||
|
||||
def _node_available():
|
||||
return shutil.which("node") is not None
|
||||
|
||||
|
||||
def _parse_css_vars(css: str) -> dict:
|
||||
return {name: value for name, value in CSS_VAR.findall(css)}
|
||||
|
||||
|
||||
class TokenExportTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.result = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", token_format="dtcg"
|
||||
)
|
||||
cls.ds = cls.result["design_system"]
|
||||
cls.tokens = cls.result["tokens"]
|
||||
|
||||
def test_color_mode_is_recorded(self):
|
||||
self.assertIn(self.ds["color_mode"], ("light", "dark"))
|
||||
|
||||
def test_dtcg_shape_matches_starter_conventions(self):
|
||||
tokens = self.tokens
|
||||
self.assertEqual(tokens["$schema"], "https://design-tokens.org/schema.json")
|
||||
self.assertIn("$description", tokens)
|
||||
self.assertIn(self.ds["color_mode"], tokens["$description"])
|
||||
self.assertIn("color", tokens)
|
||||
self.assertIn("font", tokens)
|
||||
self.assertIn("semantic", tokens)
|
||||
semantic_color = tokens["semantic"]["color"]
|
||||
for name in (
|
||||
"primary", "on-primary", "background", "foreground",
|
||||
"card", "muted", "border", "ring", "destructive",
|
||||
):
|
||||
self.assertIn(name, semantic_color)
|
||||
self.assertEqual(semantic_color[name]["$type"], "color")
|
||||
self.assertEqual(semantic_color[name]["$value"], "{color.%s}" % name)
|
||||
self.assertEqual(tokens["color"][name]["$type"], "color")
|
||||
self.assertRegex(tokens["color"][name]["$value"], HEX_TOKEN)
|
||||
for role in ("heading", "body"):
|
||||
self.assertEqual(tokens["font"][role]["$type"], "fontFamily")
|
||||
self.assertTrue(tokens["font"][role]["$value"])
|
||||
self.assertEqual(
|
||||
tokens["semantic"]["font"][role]["$value"], "{font.%s}" % role
|
||||
)
|
||||
|
||||
def test_every_exported_color_is_six_digit_hex(self):
|
||||
for name, token in self.tokens["color"].items():
|
||||
with self.subTest(color=name):
|
||||
self.assertEqual(token["$type"], "color")
|
||||
self.assertRegex(token["$value"], HEX_TOKEN)
|
||||
self.assertTrue(_HEX6.match(token["$value"]))
|
||||
|
||||
def test_on_color_pairs_reuse_generator_contrast(self):
|
||||
colors = self.ds["colors"]
|
||||
for foreground, background in ON_COLOR_PAIRS:
|
||||
with self.subTest(pair=foreground):
|
||||
self.assertGreaterEqual(
|
||||
_contrast_ratio(colors[foreground], colors[background]), 4.5
|
||||
)
|
||||
|
||||
def test_css_uses_generate_tokens_variable_names(self):
|
||||
css = format_tokens_css(self.tokens)
|
||||
variables = _parse_css_vars(css)
|
||||
for _label, key, css_var in SEMANTIC_COLOR_ENTRIES:
|
||||
hex_val = self.ds["colors"].get(key)
|
||||
if not hex_val:
|
||||
continue
|
||||
self.assertEqual(variables[css_var], hex_val)
|
||||
self.assertIn("--font-heading", variables)
|
||||
self.assertIn("--font-body", variables)
|
||||
self.assertTrue(css.strip().startswith("/* Design Tokens"))
|
||||
self.assertIn(":root {", css)
|
||||
|
||||
def test_dtcg_text_is_the_token_document(self):
|
||||
parsed = json.loads(self.result["text"])
|
||||
self.assertEqual(parsed["semantic"]["color"]["primary"]["$type"], "color")
|
||||
self.assertNotIn("TARGET:", self.result["text"])
|
||||
|
||||
def test_css_token_format_prints_css(self):
|
||||
result = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", token_format="css"
|
||||
)
|
||||
self.assertIn("--color-primary:", result["text"])
|
||||
self.assertEqual(result["tokens"]["color"]["primary"]["$value"],
|
||||
_parse_css_vars(result["text"])["--color-primary"])
|
||||
|
||||
def test_spacing_tokens_only_when_density_is_set(self):
|
||||
plain = build_design_tokens(
|
||||
generate_design_system("fintech dashboard", "Ledgerly")["design_system"]
|
||||
)
|
||||
dense = build_design_tokens(
|
||||
generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", density=9
|
||||
)["design_system"]
|
||||
)
|
||||
self.assertNotIn("space", plain)
|
||||
self.assertIn("space", dense)
|
||||
self.assertIn("xs", dense["semantic"]["space"])
|
||||
css_vars = _parse_css_vars(format_tokens_css(dense))
|
||||
self.assertIn("--space-xs", css_vars)
|
||||
|
||||
|
||||
class DarkModeTokenTest(unittest.TestCase):
|
||||
def test_dark_query_marks_mode_and_emits_dark_surfaces(self):
|
||||
result = generate_design_system(
|
||||
"dark mode developer tool", "Nightshift", token_format="dtcg"
|
||||
)
|
||||
ds = result["design_system"]
|
||||
tokens = result["tokens"]
|
||||
self.assertEqual(ds["color_mode"], "dark")
|
||||
self.assertIn("dark", tokens["$description"].lower())
|
||||
background = tokens["color"]["background"]["$value"]
|
||||
foreground = tokens["color"]["foreground"]["$value"]
|
||||
self.assertRegex(background, HEX_TOKEN)
|
||||
self.assertGreater(
|
||||
_contrast_ratio(foreground, background), 4.5
|
||||
)
|
||||
css = format_tokens_css(tokens)
|
||||
self.assertEqual(_parse_css_vars(css)["--color-background"], background)
|
||||
|
||||
|
||||
class PersistTokenTest(unittest.TestCase):
|
||||
def test_persist_dtcg_writes_tokens_json_beside_master(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
result = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", persist=True, output_dir=tmp,
|
||||
token_format="dtcg",
|
||||
)
|
||||
folder = Path(tmp) / "design-system" / "ledgerly"
|
||||
master = folder / "MASTER.md"
|
||||
tokens_json = folder / "tokens.json"
|
||||
self.assertTrue(master.exists())
|
||||
self.assertTrue(tokens_json.exists())
|
||||
self.assertFalse((folder / "tokens.css").exists())
|
||||
self.assertIn(str(tokens_json), result["persistence"]["created_files"])
|
||||
master_text = master.read_text(encoding="utf-8")
|
||||
self.assertIn("tokens.json", master_text)
|
||||
self.assertIn("master-level only", master_text)
|
||||
parsed = json.loads(tokens_json.read_text(encoding="utf-8"))
|
||||
self.assertEqual(parsed["semantic"]["color"]["primary"]["$type"], "color")
|
||||
|
||||
def test_persist_css_writes_json_and_css(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", persist=True, output_dir=tmp,
|
||||
token_format="css",
|
||||
)
|
||||
folder = Path(tmp) / "design-system" / "ledgerly"
|
||||
css_text = (folder / "tokens.css").read_text(encoding="utf-8")
|
||||
self.assertIn("--color-primary:", css_text)
|
||||
master = (folder / "MASTER.md").read_text(encoding="utf-8")
|
||||
self.assertIn("tokens.css", master)
|
||||
|
||||
def test_page_overrides_do_not_write_page_tokens(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
result = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", persist=True, page="dashboard",
|
||||
output_dir=tmp, token_format="dtcg",
|
||||
)
|
||||
folder = Path(tmp) / "design-system" / "ledgerly"
|
||||
page = folder / "pages" / "dashboard.md"
|
||||
self.assertTrue(page.exists())
|
||||
self.assertTrue((folder / "tokens.json").exists())
|
||||
self.assertFalse((folder / "pages" / "tokens.json").exists())
|
||||
created = result["persistence"]["created_files"]
|
||||
self.assertTrue(any(path.endswith("tokens.json") for path in created))
|
||||
self.assertTrue(any(path.endswith("dashboard.md") for path in created))
|
||||
|
||||
def test_skip_if_exists_then_force(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
first = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", persist=True, output_dir=tmp,
|
||||
token_format="dtcg",
|
||||
)
|
||||
tokens_json = Path(first["persistence"]["design_system_dir"]) / "tokens.json"
|
||||
original = tokens_json.read_text(encoding="utf-8")
|
||||
skipped = generate_design_system(
|
||||
"beauty spa", "Ledgerly", persist=True, output_dir=tmp,
|
||||
token_format="dtcg",
|
||||
)
|
||||
self.assertEqual(skipped["persistence"]["status"], "skipped_exists")
|
||||
self.assertEqual(tokens_json.read_text(encoding="utf-8"), original)
|
||||
forced = generate_design_system(
|
||||
"beauty spa", "Ledgerly", persist=True, output_dir=tmp,
|
||||
token_format="dtcg", force=True,
|
||||
)
|
||||
self.assertEqual(forced["persistence"]["status"], "success")
|
||||
self.assertNotEqual(tokens_json.read_text(encoding="utf-8"), original)
|
||||
|
||||
|
||||
class TokenCliTest(unittest.TestCase):
|
||||
def run_search(self, *args):
|
||||
return subprocess.run(
|
||||
[sys.executable, str(SEARCH), *map(str, args)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=False,
|
||||
)
|
||||
|
||||
def test_tokens_without_design_system_is_an_argparse_error(self):
|
||||
proc = self.run_search("fintech dashboard", "--tokens", "dtcg")
|
||||
self.assertNotEqual(proc.returncode, 0)
|
||||
self.assertIn("--tokens", proc.stderr)
|
||||
self.assertIn("--design-system", proc.stderr)
|
||||
|
||||
def test_cli_dtcg_stdout_is_json(self):
|
||||
proc = self.run_search(
|
||||
"fintech dashboard", "--design-system", "--tokens", "dtcg",
|
||||
"-p", "Ledgerly",
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
payload = json.loads(proc.stdout)
|
||||
self.assertEqual(payload["semantic"]["color"]["primary"]["$type"], "color")
|
||||
|
||||
def test_cli_css_stdout_has_root_variables(self):
|
||||
proc = self.run_search(
|
||||
"fintech dashboard", "--design-system", "--tokens", "css",
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
self.assertIn(":root {", proc.stdout)
|
||||
self.assertIn("--color-primary:", proc.stdout)
|
||||
|
||||
def test_json_payload_includes_tokens(self):
|
||||
proc = self.run_search(
|
||||
"fintech dashboard", "--design-system", "--tokens", "dtcg", "--json",
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
payload = json.loads(proc.stdout)
|
||||
self.assertIn("design_system", payload)
|
||||
self.assertIn("tokens", payload)
|
||||
self.assertIn("primary", payload["tokens"]["color"])
|
||||
|
||||
|
||||
@unittest.skipUnless(_node_available(), "Node.js is required to round-trip tokens through generate-tokens.cjs")
|
||||
class GenerateTokensRoundTripTest(unittest.TestCase):
|
||||
def test_cjs_css_matches_tokens_css_output(self):
|
||||
result = generate_design_system(
|
||||
"fintech dashboard", "Ledgerly", token_format="css"
|
||||
)
|
||||
python_css = format_tokens_css(result["tokens"])
|
||||
self.assertEqual(python_css, result["text"])
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
json_path = Path(tmp) / "tokens.json"
|
||||
cjs_css_path = Path(tmp) / "from-cjs.css"
|
||||
json_path.write_text(format_tokens_dtcg(result["tokens"]), encoding="utf-8")
|
||||
proc = subprocess.run(
|
||||
["node", str(GENERATE_TOKENS), "--config", str(json_path),
|
||||
"-o", str(cjs_css_path)],
|
||||
capture_output=True, text=True, encoding="utf-8", check=False,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
cjs_css = cjs_css_path.read_text(encoding="utf-8")
|
||||
self.assertEqual(cjs_css, python_css)
|
||||
self.assertEqual(_parse_css_vars(cjs_css), _parse_css_vars(python_css))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@ -127,6 +127,24 @@ python3 {{SCRIPT_PATH}} "<query>" --design-system --persist --preview -p "Projec
|
||||
|
||||
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.
|
||||
|
||||
### Step 2b-tokens: Export Design Tokens
|
||||
|
||||
`--tokens` is valid only with `--design-system`. It prints a machine-readable token document so hex values and font names do not have to be copied by hand:
|
||||
|
||||
```bash
|
||||
python3 {{SCRIPT_PATH}} "<query>" --design-system --tokens dtcg
|
||||
python3 {{SCRIPT_PATH}} "<query>" --design-system --tokens css
|
||||
```
|
||||
|
||||
- `dtcg` prints W3C Design Tokens Community Group JSON (`$value` / `$type`, `color`, `font`, and a `semantic` layer such as `color.primary`, `color.on-primary`, `color.background`, `font.heading`).
|
||||
- `css` prints `:root` custom properties using the same names `../design-system/scripts/generate-tokens.cjs` emits (`--color-primary`, `--font-heading`, …).
|
||||
- Dark-mode results emit the resolved dark values and record the mode in `$description`.
|
||||
- With `--persist`, also write `tokens.json` next to `MASTER.md` (and `tokens.css` when `--tokens css`). Existing files follow the same `--force` / skip-if-exists rules. Token files are master-level only; `--page` overrides do not emit page-specific tokens.
|
||||
|
||||
```bash
|
||||
python3 {{SCRIPT_PATH}} "<query>" --design-system --persist --tokens dtcg -p "Project Name" --output-dir "<project-root>"
|
||||
```
|
||||
|
||||
**How hierarchical retrieval works:**
|
||||
1. Read `design-system/<project-slug>/MASTER.md`
|
||||
2. When building a specific page (e.g., "Checkout"), check `design-system/<project-slug>/pages/checkout.md`
|
||||
@ -278,7 +296,7 @@ python3 {{SCRIPT_PATH}} "streaming suspense" --stack nextjs
|
||||
|
||||
## Output Formats
|
||||
|
||||
The `--design-system` flag supports two output formats:
|
||||
The `--design-system` flag supports ASCII, Markdown, JSON, and token export:
|
||||
|
||||
```bash
|
||||
# ASCII box (default) - best for terminal display
|
||||
@ -286,6 +304,10 @@ python3 {{SCRIPT_PATH}} "fintech crypto" --design-system
|
||||
|
||||
# Markdown - best for documentation
|
||||
python3 {{SCRIPT_PATH}} "fintech crypto" --design-system -f markdown
|
||||
|
||||
# Design tokens (requires --design-system)
|
||||
python3 {{SCRIPT_PATH}} "fintech crypto" --design-system --tokens dtcg
|
||||
python3 {{SCRIPT_PATH}} "fintech crypto" --design-system --tokens css
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user