design_system.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Design System Generator - Aggregates search results and applies reasoning
  5. to generate comprehensive design system recommendations.
  6. Usage:
  7. from .design_system import generate_design_system
  8. result = generate_design_system("SaaS dashboard", "My Project")
  9. # With persistence (Master + Overrides pattern)
  10. result = generate_design_system("SaaS dashboard", "My Project", persist=True)
  11. result = generate_design_system("SaaS dashboard", "My Project", persist=True, page="dashboard")
  12. """
  13. import csv
  14. import json
  15. import os
  16. from datetime import datetime
  17. from pathlib import Path
  18. # Allow both `python design_system.py ...` and `python -m ...` execution.
  19. try:
  20. from core import search, DATA_DIR
  21. except ImportError: # pragma: no cover
  22. from .core import search, DATA_DIR
  23. # ============ CONFIGURATION ============
  24. REASONING_FILE = "ui-reasoning.csv"
  25. SEARCH_CONFIG = {
  26. "product": {"max_results": 1},
  27. "style": {"max_results": 3},
  28. "color": {"max_results": 2},
  29. "landing": {"max_results": 2},
  30. "typography": {"max_results": 2}
  31. }
  32. # ============ DESIGN SYSTEM GENERATOR ============
  33. class DesignSystemGenerator:
  34. """Generates design system recommendations from aggregated searches."""
  35. def __init__(self):
  36. self.reasoning_data = self._load_reasoning()
  37. def _load_reasoning(self) -> list:
  38. """Load reasoning rules from CSV."""
  39. filepath = DATA_DIR / REASONING_FILE
  40. if not filepath.exists():
  41. return []
  42. with open(filepath, 'r', encoding='utf-8') as f:
  43. return list(csv.DictReader(f))
  44. def _multi_domain_search(self, query: str, style_priority: list = None) -> dict:
  45. """Execute searches across multiple domains."""
  46. results = {}
  47. for domain, config in SEARCH_CONFIG.items():
  48. if domain == "style" and style_priority:
  49. # For style, also search with priority keywords
  50. priority_query = " ".join(style_priority[:2]) if style_priority else query
  51. combined_query = f"{query} {priority_query}"
  52. results[domain] = search(combined_query, domain, config["max_results"])
  53. else:
  54. results[domain] = search(query, domain, config["max_results"])
  55. return results
  56. def _find_reasoning_rule(self, category: str) -> dict:
  57. """Find matching reasoning rule for a category."""
  58. category_lower = category.lower()
  59. # Try exact match first
  60. for rule in self.reasoning_data:
  61. if rule.get("UI_Category", "").lower() == category_lower:
  62. return rule
  63. # Try partial match
  64. for rule in self.reasoning_data:
  65. ui_cat = rule.get("UI_Category", "").lower()
  66. if ui_cat in category_lower or category_lower in ui_cat:
  67. return rule
  68. # Try keyword match
  69. for rule in self.reasoning_data:
  70. ui_cat = rule.get("UI_Category", "").lower()
  71. keywords = ui_cat.replace("/", " ").replace("-", " ").split()
  72. if any(kw in category_lower for kw in keywords):
  73. return rule
  74. return {}
  75. def _apply_reasoning(self, category: str, search_results: dict) -> dict:
  76. """Apply reasoning rules to search results."""
  77. rule = self._find_reasoning_rule(category)
  78. if not rule:
  79. return {
  80. "pattern": "Hero + Features + CTA",
  81. "style_priority": ["Minimalism", "Flat Design"],
  82. "color_mood": "Professional",
  83. "typography_mood": "Clean",
  84. "key_effects": "Subtle hover transitions",
  85. "anti_patterns": "",
  86. "decision_rules": {},
  87. "severity": "MEDIUM"
  88. }
  89. # Parse decision rules JSON
  90. decision_rules = {}
  91. try:
  92. decision_rules = json.loads(rule.get("Decision_Rules", "{}"))
  93. except json.JSONDecodeError:
  94. pass
  95. return {
  96. "pattern": rule.get("Recommended_Pattern", ""),
  97. "style_priority": [s.strip() for s in rule.get("Style_Priority", "").split("+")],
  98. "color_mood": rule.get("Color_Mood", ""),
  99. "typography_mood": rule.get("Typography_Mood", ""),
  100. "key_effects": rule.get("Key_Effects", ""),
  101. "anti_patterns": rule.get("Anti_Patterns", ""),
  102. "decision_rules": decision_rules,
  103. "severity": rule.get("Severity", "MEDIUM")
  104. }
  105. def _select_best_match(self, results: list, priority_keywords: list) -> dict:
  106. """Select best matching result based on priority keywords."""
  107. if not results:
  108. return {}
  109. if not priority_keywords:
  110. return results[0]
  111. # First: try exact style name match
  112. for priority in priority_keywords:
  113. priority_lower = priority.lower().strip()
  114. for result in results:
  115. style_name = result.get("Style Category", "").lower()
  116. if priority_lower in style_name or style_name in priority_lower:
  117. return result
  118. # Second: score by keyword match in all fields
  119. scored = []
  120. for result in results:
  121. result_str = str(result).lower()
  122. score = 0
  123. for kw in priority_keywords:
  124. kw_lower = kw.lower().strip()
  125. # Higher score for style name match
  126. if kw_lower in result.get("Style Category", "").lower():
  127. score += 10
  128. # Lower score for keyword field match
  129. elif kw_lower in result.get("Keywords", "").lower():
  130. score += 3
  131. # Even lower for other field matches
  132. elif kw_lower in result_str:
  133. score += 1
  134. scored.append((score, result))
  135. scored.sort(key=lambda x: x[0], reverse=True)
  136. return scored[0][1] if scored and scored[0][0] > 0 else results[0]
  137. def _extract_results(self, search_result: dict) -> list:
  138. """Extract results list from search result dict."""
  139. return search_result.get("results", [])
  140. def generate(self, query: str, project_name: str = None) -> dict:
  141. """Generate complete design system recommendation."""
  142. # Step 1: First search product to get category
  143. product_result = search(query, "product", 1)
  144. product_results = product_result.get("results", [])
  145. category = "General"
  146. if product_results:
  147. category = product_results[0].get("Product Type", "General")
  148. # Step 2: Get reasoning rules for this category
  149. reasoning = self._apply_reasoning(category, {})
  150. style_priority = reasoning.get("style_priority", [])
  151. # Step 3: Multi-domain search with style priority hints
  152. search_results = self._multi_domain_search(query, style_priority)
  153. search_results["product"] = product_result # Reuse product search
  154. # Step 4: Select best matches from each domain using priority
  155. style_results = self._extract_results(search_results.get("style", {}))
  156. color_results = self._extract_results(search_results.get("color", {}))
  157. typography_results = self._extract_results(search_results.get("typography", {}))
  158. landing_results = self._extract_results(search_results.get("landing", {}))
  159. best_style = self._select_best_match(style_results, reasoning.get("style_priority", []))
  160. best_color = color_results[0] if color_results else {}
  161. best_typography = typography_results[0] if typography_results else {}
  162. best_landing = landing_results[0] if landing_results else {}
  163. # Step 5: Build final recommendation
  164. # Combine effects from both reasoning and style search
  165. style_effects = best_style.get("Effects & Animation", "")
  166. reasoning_effects = reasoning.get("key_effects", "")
  167. combined_effects = style_effects if style_effects else reasoning_effects
  168. return {
  169. "project_name": project_name or query.upper(),
  170. "category": category,
  171. "pattern": {
  172. "name": best_landing.get("Pattern Name", reasoning.get("pattern", "Hero + Features + CTA")),
  173. "sections": best_landing.get("Section Order", "Hero > Features > CTA"),
  174. "cta_placement": best_landing.get("Primary CTA Placement", "Above fold"),
  175. "color_strategy": best_landing.get("Color Strategy", ""),
  176. "conversion": best_landing.get("Conversion Optimization", "")
  177. },
  178. "style": {
  179. "name": best_style.get("Style Category", "Minimalism"),
  180. "type": best_style.get("Type", "General"),
  181. "effects": style_effects,
  182. "keywords": best_style.get("Keywords", ""),
  183. "best_for": best_style.get("Best For", ""),
  184. "performance": best_style.get("Performance", ""),
  185. "accessibility": best_style.get("Accessibility", "")
  186. },
  187. "colors": {
  188. "primary": best_color.get("Primary (Hex)", "#2563EB"),
  189. "secondary": best_color.get("Secondary (Hex)", "#3B82F6"),
  190. "cta": best_color.get("CTA (Hex)", "#F97316"),
  191. "background": best_color.get("Background (Hex)", "#F8FAFC"),
  192. "text": best_color.get("Text (Hex)", "#1E293B"),
  193. "notes": best_color.get("Notes", "")
  194. },
  195. "typography": {
  196. "heading": best_typography.get("Heading Font", "Inter"),
  197. "body": best_typography.get("Body Font", "Inter"),
  198. "mood": best_typography.get("Mood/Style Keywords", reasoning.get("typography_mood", "")),
  199. "best_for": best_typography.get("Best For", ""),
  200. "google_fonts_url": best_typography.get("Google Fonts URL", ""),
  201. "css_import": best_typography.get("CSS Import", "")
  202. },
  203. "key_effects": combined_effects,
  204. "anti_patterns": reasoning.get("anti_patterns", ""),
  205. "decision_rules": reasoning.get("decision_rules", {}),
  206. "severity": reasoning.get("severity", "MEDIUM")
  207. }
  208. # ============ OUTPUT FORMATTERS ============
  209. BOX_WIDTH = 90 # Wider box for more content
  210. def format_ascii_box(design_system: dict) -> str:
  211. """Format design system as ASCII box with emojis (MCP-style)."""
  212. project = design_system.get("project_name", "PROJECT")
  213. pattern = design_system.get("pattern", {})
  214. style = design_system.get("style", {})
  215. colors = design_system.get("colors", {})
  216. typography = design_system.get("typography", {})
  217. effects = design_system.get("key_effects", "")
  218. anti_patterns = design_system.get("anti_patterns", "")
  219. def wrap_text(text: str, prefix: str, width: int) -> list:
  220. """Wrap long text into multiple lines."""
  221. if not text:
  222. return []
  223. words = text.split()
  224. lines = []
  225. current_line = prefix
  226. for word in words:
  227. if len(current_line) + len(word) + 1 <= width - 2:
  228. current_line += (" " if current_line != prefix else "") + word
  229. else:
  230. if current_line != prefix:
  231. lines.append(current_line)
  232. current_line = prefix + word
  233. if current_line != prefix:
  234. lines.append(current_line)
  235. return lines
  236. # Build sections from pattern
  237. sections = pattern.get("sections", "").split(">")
  238. sections = [s.strip() for s in sections if s.strip()]
  239. # Build output lines
  240. lines = []
  241. w = BOX_WIDTH - 1
  242. lines.append("+" + "-" * w + "+")
  243. lines.append(f"| TARGET: {project} - RECOMMENDED DESIGN SYSTEM".ljust(BOX_WIDTH) + "|")
  244. lines.append("+" + "-" * w + "+")
  245. lines.append("|" + " " * BOX_WIDTH + "|")
  246. # Pattern section
  247. lines.append(f"| PATTERN: {pattern.get('name', '')}".ljust(BOX_WIDTH) + "|")
  248. if pattern.get('conversion'):
  249. lines.append(f"| Conversion: {pattern.get('conversion', '')}".ljust(BOX_WIDTH) + "|")
  250. if pattern.get('cta_placement'):
  251. lines.append(f"| CTA: {pattern.get('cta_placement', '')}".ljust(BOX_WIDTH) + "|")
  252. lines.append("| Sections:".ljust(BOX_WIDTH) + "|")
  253. for i, section in enumerate(sections, 1):
  254. lines.append(f"| {i}. {section}".ljust(BOX_WIDTH) + "|")
  255. lines.append("|" + " " * BOX_WIDTH + "|")
  256. # Style section
  257. lines.append(f"| STYLE: {style.get('name', '')}".ljust(BOX_WIDTH) + "|")
  258. if style.get("keywords"):
  259. for line in wrap_text(f"Keywords: {style.get('keywords', '')}", "| ", BOX_WIDTH):
  260. lines.append(line.ljust(BOX_WIDTH) + "|")
  261. if style.get("best_for"):
  262. for line in wrap_text(f"Best For: {style.get('best_for', '')}", "| ", BOX_WIDTH):
  263. lines.append(line.ljust(BOX_WIDTH) + "|")
  264. if style.get("performance") or style.get("accessibility"):
  265. perf_a11y = f"Performance: {style.get('performance', '')} | Accessibility: {style.get('accessibility', '')}"
  266. lines.append(f"| {perf_a11y}".ljust(BOX_WIDTH) + "|")
  267. lines.append("|" + " " * BOX_WIDTH + "|")
  268. # Colors section
  269. lines.append("| COLORS:".ljust(BOX_WIDTH) + "|")
  270. lines.append(f"| Primary: {colors.get('primary', '')}".ljust(BOX_WIDTH) + "|")
  271. lines.append(f"| Secondary: {colors.get('secondary', '')}".ljust(BOX_WIDTH) + "|")
  272. lines.append(f"| CTA: {colors.get('cta', '')}".ljust(BOX_WIDTH) + "|")
  273. lines.append(f"| Background: {colors.get('background', '')}".ljust(BOX_WIDTH) + "|")
  274. lines.append(f"| Text: {colors.get('text', '')}".ljust(BOX_WIDTH) + "|")
  275. if colors.get("notes"):
  276. for line in wrap_text(f"Notes: {colors.get('notes', '')}", "| ", BOX_WIDTH):
  277. lines.append(line.ljust(BOX_WIDTH) + "|")
  278. lines.append("|" + " " * BOX_WIDTH + "|")
  279. # Typography section
  280. lines.append(f"| TYPOGRAPHY: {typography.get('heading', '')} / {typography.get('body', '')}".ljust(BOX_WIDTH) + "|")
  281. if typography.get("mood"):
  282. for line in wrap_text(f"Mood: {typography.get('mood', '')}", "| ", BOX_WIDTH):
  283. lines.append(line.ljust(BOX_WIDTH) + "|")
  284. if typography.get("best_for"):
  285. for line in wrap_text(f"Best For: {typography.get('best_for', '')}", "| ", BOX_WIDTH):
  286. lines.append(line.ljust(BOX_WIDTH) + "|")
  287. if typography.get("google_fonts_url"):
  288. lines.append(f"| Google Fonts: {typography.get('google_fonts_url', '')}".ljust(BOX_WIDTH) + "|")
  289. if typography.get("css_import"):
  290. lines.append(f"| CSS Import: {typography.get('css_import', '')[:70]}...".ljust(BOX_WIDTH) + "|")
  291. lines.append("|" + " " * BOX_WIDTH + "|")
  292. # Key Effects section
  293. if effects:
  294. lines.append("| KEY EFFECTS:".ljust(BOX_WIDTH) + "|")
  295. for line in wrap_text(effects, "| ", BOX_WIDTH):
  296. lines.append(line.ljust(BOX_WIDTH) + "|")
  297. lines.append("|" + " " * BOX_WIDTH + "|")
  298. # Anti-patterns section
  299. if anti_patterns:
  300. lines.append("| AVOID (Anti-patterns):".ljust(BOX_WIDTH) + "|")
  301. for line in wrap_text(anti_patterns, "| ", BOX_WIDTH):
  302. lines.append(line.ljust(BOX_WIDTH) + "|")
  303. lines.append("|" + " " * BOX_WIDTH + "|")
  304. # Pre-Delivery Checklist section
  305. lines.append("| PRE-DELIVERY CHECKLIST:".ljust(BOX_WIDTH) + "|")
  306. checklist_items = [
  307. "[ ] No emojis as icons (use SVG: Heroicons/Lucide)",
  308. "[ ] cursor-pointer on all clickable elements",
  309. "[ ] Hover states with smooth transitions (150-300ms)",
  310. "[ ] Light mode: text contrast 4.5:1 minimum",
  311. "[ ] Focus states visible for keyboard nav",
  312. "[ ] prefers-reduced-motion respected",
  313. "[ ] Responsive: 375px, 768px, 1024px, 1440px"
  314. ]
  315. for item in checklist_items:
  316. lines.append(f"| {item}".ljust(BOX_WIDTH) + "|")
  317. lines.append("|" + " " * BOX_WIDTH + "|")
  318. lines.append("+" + "-" * w + "+")
  319. return "\n".join(lines)
  320. def format_markdown(design_system: dict) -> str:
  321. """Format design system as markdown."""
  322. project = design_system.get("project_name", "PROJECT")
  323. pattern = design_system.get("pattern", {})
  324. style = design_system.get("style", {})
  325. colors = design_system.get("colors", {})
  326. typography = design_system.get("typography", {})
  327. effects = design_system.get("key_effects", "")
  328. anti_patterns = design_system.get("anti_patterns", "")
  329. lines = []
  330. lines.append(f"## Design System: {project}")
  331. lines.append("")
  332. # Pattern section
  333. lines.append("### Pattern")
  334. lines.append(f"- **Name:** {pattern.get('name', '')}")
  335. if pattern.get('conversion'):
  336. lines.append(f"- **Conversion Focus:** {pattern.get('conversion', '')}")
  337. if pattern.get('cta_placement'):
  338. lines.append(f"- **CTA Placement:** {pattern.get('cta_placement', '')}")
  339. if pattern.get('color_strategy'):
  340. lines.append(f"- **Color Strategy:** {pattern.get('color_strategy', '')}")
  341. lines.append(f"- **Sections:** {pattern.get('sections', '')}")
  342. lines.append("")
  343. # Style section
  344. lines.append("### Style")
  345. lines.append(f"- **Name:** {style.get('name', '')}")
  346. if style.get('keywords'):
  347. lines.append(f"- **Keywords:** {style.get('keywords', '')}")
  348. if style.get('best_for'):
  349. lines.append(f"- **Best For:** {style.get('best_for', '')}")
  350. if style.get('performance') or style.get('accessibility'):
  351. lines.append(f"- **Performance:** {style.get('performance', '')} | **Accessibility:** {style.get('accessibility', '')}")
  352. lines.append("")
  353. # Colors section
  354. lines.append("### Colors")
  355. lines.append(f"| Role | Hex |")
  356. lines.append(f"|------|-----|")
  357. lines.append(f"| Primary | {colors.get('primary', '')} |")
  358. lines.append(f"| Secondary | {colors.get('secondary', '')} |")
  359. lines.append(f"| CTA | {colors.get('cta', '')} |")
  360. lines.append(f"| Background | {colors.get('background', '')} |")
  361. lines.append(f"| Text | {colors.get('text', '')} |")
  362. if colors.get("notes"):
  363. lines.append(f"\n*Notes: {colors.get('notes', '')}*")
  364. lines.append("")
  365. # Typography section
  366. lines.append("### Typography")
  367. lines.append(f"- **Heading:** {typography.get('heading', '')}")
  368. lines.append(f"- **Body:** {typography.get('body', '')}")
  369. if typography.get("mood"):
  370. lines.append(f"- **Mood:** {typography.get('mood', '')}")
  371. if typography.get("best_for"):
  372. lines.append(f"- **Best For:** {typography.get('best_for', '')}")
  373. if typography.get("google_fonts_url"):
  374. lines.append(f"- **Google Fonts:** {typography.get('google_fonts_url', '')}")
  375. if typography.get("css_import"):
  376. lines.append(f"- **CSS Import:**")
  377. lines.append(f"```css")
  378. lines.append(f"{typography.get('css_import', '')}")
  379. lines.append(f"```")
  380. lines.append("")
  381. # Key Effects section
  382. if effects:
  383. lines.append("### Key Effects")
  384. lines.append(f"{effects}")
  385. lines.append("")
  386. # Anti-patterns section
  387. if anti_patterns:
  388. lines.append("### Avoid (Anti-patterns)")
  389. newline_bullet = '\n- '
  390. lines.append(f"- {anti_patterns.replace(' + ', newline_bullet)}")
  391. lines.append("")
  392. # Pre-Delivery Checklist section
  393. lines.append("### Pre-Delivery Checklist")
  394. lines.append("- [ ] No emojis as icons (use SVG: Heroicons/Lucide)")
  395. lines.append("- [ ] cursor-pointer on all clickable elements")
  396. lines.append("- [ ] Hover states with smooth transitions (150-300ms)")
  397. lines.append("- [ ] Light mode: text contrast 4.5:1 minimum")
  398. lines.append("- [ ] Focus states visible for keyboard nav")
  399. lines.append("- [ ] prefers-reduced-motion respected")
  400. lines.append("- [ ] Responsive: 375px, 768px, 1024px, 1440px")
  401. lines.append("")
  402. return "\n".join(lines)
  403. # ============ MAIN ENTRY POINT ============
  404. def generate_design_system(query: str, project_name: str = None, output_format: str = "ascii",
  405. persist: bool = False, page: str = None, output_dir: str = None) -> str:
  406. """
  407. Main entry point for design system generation.
  408. Args:
  409. query: Search query (e.g., "SaaS dashboard", "e-commerce luxury")
  410. project_name: Optional project name for output header
  411. output_format: "ascii" (default) or "markdown"
  412. persist: If True, save design system to design-system/ folder
  413. page: Optional page name for page-specific override file
  414. output_dir: Optional output directory (defaults to current working directory)
  415. Returns:
  416. Formatted design system string
  417. """
  418. generator = DesignSystemGenerator()
  419. design_system = generator.generate(query, project_name)
  420. # Persist to files if requested
  421. if persist:
  422. persist_design_system(design_system, page, output_dir, query)
  423. if output_format == "markdown":
  424. return format_markdown(design_system)
  425. return format_ascii_box(design_system)
  426. # ============ PERSISTENCE FUNCTIONS ============
  427. def persist_design_system(design_system: dict, page: str = None, output_dir: str = None, page_query: str = None) -> dict:
  428. """
  429. Persist design system to design-system/<project>/ folder using Master + Overrides pattern.
  430. Args:
  431. design_system: The generated design system dictionary
  432. page: Optional page name for page-specific override file
  433. output_dir: Optional output directory (defaults to current working directory)
  434. page_query: Optional query string for intelligent page override generation
  435. Returns:
  436. dict with created file paths and status
  437. """
  438. base_dir = Path(output_dir) if output_dir else Path.cwd()
  439. # Use project name for project-specific folder
  440. project_name = design_system.get("project_name", "default")
  441. project_slug = project_name.lower().replace(' ', '-')
  442. design_system_dir = base_dir / "design-system" / project_slug
  443. pages_dir = design_system_dir / "pages"
  444. created_files = []
  445. # Create directories
  446. design_system_dir.mkdir(parents=True, exist_ok=True)
  447. pages_dir.mkdir(parents=True, exist_ok=True)
  448. master_file = design_system_dir / "MASTER.md"
  449. # Generate and write MASTER.md
  450. master_content = format_master_md(design_system)
  451. with open(master_file, 'w', encoding='utf-8') as f:
  452. f.write(master_content)
  453. created_files.append(str(master_file))
  454. # If page is specified, create page override file with intelligent content
  455. if page:
  456. page_file = pages_dir / f"{page.lower().replace(' ', '-')}.md"
  457. page_content = format_page_override_md(design_system, page, page_query)
  458. with open(page_file, 'w', encoding='utf-8') as f:
  459. f.write(page_content)
  460. created_files.append(str(page_file))
  461. return {
  462. "status": "success",
  463. "design_system_dir": str(design_system_dir),
  464. "created_files": created_files
  465. }
  466. def format_master_md(design_system: dict) -> str:
  467. """Format design system as MASTER.md with hierarchical override logic."""
  468. project = design_system.get("project_name", "PROJECT")
  469. pattern = design_system.get("pattern", {})
  470. style = design_system.get("style", {})
  471. colors = design_system.get("colors", {})
  472. typography = design_system.get("typography", {})
  473. effects = design_system.get("key_effects", "")
  474. anti_patterns = design_system.get("anti_patterns", "")
  475. timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  476. lines = []
  477. # Logic header
  478. lines.append("# Design System Master File")
  479. lines.append("")
  480. lines.append("> **LOGIC:** When building a specific page, first check `design-system/pages/[page-name].md`.")
  481. lines.append("> If that file exists, its rules **override** this Master file.")
  482. lines.append("> If not, strictly follow the rules below.")
  483. lines.append("")
  484. lines.append("---")
  485. lines.append("")
  486. lines.append(f"**Project:** {project}")
  487. lines.append(f"**Generated:** {timestamp}")
  488. lines.append(f"**Category:** {design_system.get('category', 'General')}")
  489. lines.append("")
  490. lines.append("---")
  491. lines.append("")
  492. # Global Rules section
  493. lines.append("## Global Rules")
  494. lines.append("")
  495. # Color Palette
  496. lines.append("### Color Palette")
  497. lines.append("")
  498. lines.append("| Role | Hex | CSS Variable |")
  499. lines.append("|------|-----|--------------|")
  500. lines.append(f"| Primary | `{colors.get('primary', '#2563EB')}` | `--color-primary` |")
  501. lines.append(f"| Secondary | `{colors.get('secondary', '#3B82F6')}` | `--color-secondary` |")
  502. lines.append(f"| CTA/Accent | `{colors.get('cta', '#F97316')}` | `--color-cta` |")
  503. lines.append(f"| Background | `{colors.get('background', '#F8FAFC')}` | `--color-background` |")
  504. lines.append(f"| Text | `{colors.get('text', '#1E293B')}` | `--color-text` |")
  505. lines.append("")
  506. if colors.get("notes"):
  507. lines.append(f"**Color Notes:** {colors.get('notes', '')}")
  508. lines.append("")
  509. # Typography
  510. lines.append("### Typography")
  511. lines.append("")
  512. lines.append(f"- **Heading Font:** {typography.get('heading', 'Inter')}")
  513. lines.append(f"- **Body Font:** {typography.get('body', 'Inter')}")
  514. if typography.get("mood"):
  515. lines.append(f"- **Mood:** {typography.get('mood', '')}")
  516. if typography.get("google_fonts_url"):
  517. lines.append(f"- **Google Fonts:** [{typography.get('heading', '')} + {typography.get('body', '')}]({typography.get('google_fonts_url', '')})")
  518. lines.append("")
  519. if typography.get("css_import"):
  520. lines.append("**CSS Import:**")
  521. lines.append("```css")
  522. lines.append(typography.get("css_import", ""))
  523. lines.append("```")
  524. lines.append("")
  525. # Spacing Variables
  526. lines.append("### Spacing Variables")
  527. lines.append("")
  528. lines.append("| Token | Value | Usage |")
  529. lines.append("|-------|-------|-------|")
  530. lines.append("| `--space-xs` | `4px` / `0.25rem` | Tight gaps |")
  531. lines.append("| `--space-sm` | `8px` / `0.5rem` | Icon gaps, inline spacing |")
  532. lines.append("| `--space-md` | `16px` / `1rem` | Standard padding |")
  533. lines.append("| `--space-lg` | `24px` / `1.5rem` | Section padding |")
  534. lines.append("| `--space-xl` | `32px` / `2rem` | Large gaps |")
  535. lines.append("| `--space-2xl` | `48px` / `3rem` | Section margins |")
  536. lines.append("| `--space-3xl` | `64px` / `4rem` | Hero padding |")
  537. lines.append("")
  538. # Shadow Depths
  539. lines.append("### Shadow Depths")
  540. lines.append("")
  541. lines.append("| Level | Value | Usage |")
  542. lines.append("|-------|-------|-------|")
  543. lines.append("| `--shadow-sm` | `0 1px 2px rgba(0,0,0,0.05)` | Subtle lift |")
  544. lines.append("| `--shadow-md` | `0 4px 6px rgba(0,0,0,0.1)` | Cards, buttons |")
  545. lines.append("| `--shadow-lg` | `0 10px 15px rgba(0,0,0,0.1)` | Modals, dropdowns |")
  546. lines.append("| `--shadow-xl` | `0 20px 25px rgba(0,0,0,0.15)` | Hero images, featured cards |")
  547. lines.append("")
  548. # Component Specs section
  549. lines.append("---")
  550. lines.append("")
  551. lines.append("## Component Specs")
  552. lines.append("")
  553. # Buttons
  554. lines.append("### Buttons")
  555. lines.append("")
  556. lines.append("```css")
  557. lines.append("/* Primary Button */")
  558. lines.append(".btn-primary {")
  559. lines.append(f" background: {colors.get('cta', '#F97316')};")
  560. lines.append(" color: white;")
  561. lines.append(" padding: 12px 24px;")
  562. lines.append(" border-radius: 8px;")
  563. lines.append(" font-weight: 600;")
  564. lines.append(" transition: all 200ms ease;")
  565. lines.append(" cursor: pointer;")
  566. lines.append("}")
  567. lines.append("")
  568. lines.append(".btn-primary:hover {")
  569. lines.append(" opacity: 0.9;")
  570. lines.append(" transform: translateY(-1px);")
  571. lines.append("}")
  572. lines.append("")
  573. lines.append("/* Secondary Button */")
  574. lines.append(".btn-secondary {")
  575. lines.append(f" background: transparent;")
  576. lines.append(f" color: {colors.get('primary', '#2563EB')};")
  577. lines.append(f" border: 2px solid {colors.get('primary', '#2563EB')};")
  578. lines.append(" padding: 12px 24px;")
  579. lines.append(" border-radius: 8px;")
  580. lines.append(" font-weight: 600;")
  581. lines.append(" transition: all 200ms ease;")
  582. lines.append(" cursor: pointer;")
  583. lines.append("}")
  584. lines.append("```")
  585. lines.append("")
  586. # Cards
  587. lines.append("### Cards")
  588. lines.append("")
  589. lines.append("```css")
  590. lines.append(".card {")
  591. lines.append(f" background: {colors.get('background', '#FFFFFF')};")
  592. lines.append(" border-radius: 12px;")
  593. lines.append(" padding: 24px;")
  594. lines.append(" box-shadow: var(--shadow-md);")
  595. lines.append(" transition: all 200ms ease;")
  596. lines.append(" cursor: pointer;")
  597. lines.append("}")
  598. lines.append("")
  599. lines.append(".card:hover {")
  600. lines.append(" box-shadow: var(--shadow-lg);")
  601. lines.append(" transform: translateY(-2px);")
  602. lines.append("}")
  603. lines.append("```")
  604. lines.append("")
  605. # Inputs
  606. lines.append("### Inputs")
  607. lines.append("")
  608. lines.append("```css")
  609. lines.append(".input {")
  610. lines.append(" padding: 12px 16px;")
  611. lines.append(" border: 1px solid #E2E8F0;")
  612. lines.append(" border-radius: 8px;")
  613. lines.append(" font-size: 16px;")
  614. lines.append(" transition: border-color 200ms ease;")
  615. lines.append("}")
  616. lines.append("")
  617. lines.append(".input:focus {")
  618. lines.append(f" border-color: {colors.get('primary', '#2563EB')};")
  619. lines.append(" outline: none;")
  620. lines.append(f" box-shadow: 0 0 0 3px {colors.get('primary', '#2563EB')}20;")
  621. lines.append("}")
  622. lines.append("```")
  623. lines.append("")
  624. # Modals
  625. lines.append("### Modals")
  626. lines.append("")
  627. lines.append("```css")
  628. lines.append(".modal-overlay {")
  629. lines.append(" background: rgba(0, 0, 0, 0.5);")
  630. lines.append(" backdrop-filter: blur(4px);")
  631. lines.append("}")
  632. lines.append("")
  633. lines.append(".modal {")
  634. lines.append(" background: white;")
  635. lines.append(" border-radius: 16px;")
  636. lines.append(" padding: 32px;")
  637. lines.append(" box-shadow: var(--shadow-xl);")
  638. lines.append(" max-width: 500px;")
  639. lines.append(" width: 90%;")
  640. lines.append("}")
  641. lines.append("```")
  642. lines.append("")
  643. # Style section
  644. lines.append("---")
  645. lines.append("")
  646. lines.append("## Style Guidelines")
  647. lines.append("")
  648. lines.append(f"**Style:** {style.get('name', 'Minimalism')}")
  649. lines.append("")
  650. if style.get("keywords"):
  651. lines.append(f"**Keywords:** {style.get('keywords', '')}")
  652. lines.append("")
  653. if style.get("best_for"):
  654. lines.append(f"**Best For:** {style.get('best_for', '')}")
  655. lines.append("")
  656. if effects:
  657. lines.append(f"**Key Effects:** {effects}")
  658. lines.append("")
  659. # Layout Pattern
  660. lines.append("### Page Pattern")
  661. lines.append("")
  662. lines.append(f"**Pattern Name:** {pattern.get('name', '')}")
  663. lines.append("")
  664. if pattern.get('conversion'):
  665. lines.append(f"- **Conversion Strategy:** {pattern.get('conversion', '')}")
  666. if pattern.get('cta_placement'):
  667. lines.append(f"- **CTA Placement:** {pattern.get('cta_placement', '')}")
  668. lines.append(f"- **Section Order:** {pattern.get('sections', '')}")
  669. lines.append("")
  670. # Anti-Patterns section
  671. lines.append("---")
  672. lines.append("")
  673. lines.append("## Anti-Patterns (Do NOT Use)")
  674. lines.append("")
  675. if anti_patterns:
  676. anti_list = [a.strip() for a in anti_patterns.split("+")]
  677. for anti in anti_list:
  678. if anti:
  679. lines.append(f"- ❌ {anti}")
  680. lines.append("")
  681. lines.append("### Additional Forbidden Patterns")
  682. lines.append("")
  683. lines.append("- ❌ **Emojis as icons** — Use SVG icons (Heroicons, Lucide, Simple Icons)")
  684. lines.append("- ❌ **Missing cursor:pointer** — All clickable elements must have cursor:pointer")
  685. lines.append("- ❌ **Layout-shifting hovers** — Avoid scale transforms that shift layout")
  686. lines.append("- ❌ **Low contrast text** — Maintain 4.5:1 minimum contrast ratio")
  687. lines.append("- ❌ **Instant state changes** — Always use transitions (150-300ms)")
  688. lines.append("- ❌ **Invisible focus states** — Focus states must be visible for a11y")
  689. lines.append("")
  690. # Pre-Delivery Checklist
  691. lines.append("---")
  692. lines.append("")
  693. lines.append("## Pre-Delivery Checklist")
  694. lines.append("")
  695. lines.append("Before delivering any UI code, verify:")
  696. lines.append("")
  697. lines.append("- [ ] No emojis used as icons (use SVG instead)")
  698. lines.append("- [ ] All icons from consistent icon set (Heroicons/Lucide)")
  699. lines.append("- [ ] `cursor-pointer` on all clickable elements")
  700. lines.append("- [ ] Hover states with smooth transitions (150-300ms)")
  701. lines.append("- [ ] Light mode: text contrast 4.5:1 minimum")
  702. lines.append("- [ ] Focus states visible for keyboard navigation")
  703. lines.append("- [ ] `prefers-reduced-motion` respected")
  704. lines.append("- [ ] Responsive: 375px, 768px, 1024px, 1440px")
  705. lines.append("- [ ] No content hidden behind fixed navbars")
  706. lines.append("- [ ] No horizontal scroll on mobile")
  707. lines.append("")
  708. return "\n".join(lines)
  709. def format_page_override_md(design_system: dict, page_name: str, page_query: str = None) -> str:
  710. """Format a page-specific override file with intelligent AI-generated content."""
  711. project = design_system.get("project_name", "PROJECT")
  712. timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  713. page_title = page_name.replace("-", " ").replace("_", " ").title()
  714. # Detect page type and generate intelligent overrides
  715. page_overrides = _generate_intelligent_overrides(page_name, page_query, design_system)
  716. lines = []
  717. lines.append(f"# {page_title} Page Overrides")
  718. lines.append("")
  719. lines.append(f"> **PROJECT:** {project}")
  720. lines.append(f"> **Generated:** {timestamp}")
  721. lines.append(f"> **Page Type:** {page_overrides.get('page_type', 'General')}")
  722. lines.append("")
  723. lines.append("> ⚠️ **IMPORTANT:** Rules in this file **override** the Master file (`design-system/MASTER.md`).")
  724. lines.append("> Only deviations from the Master are documented here. For all other rules, refer to the Master.")
  725. lines.append("")
  726. lines.append("---")
  727. lines.append("")
  728. # Page-specific rules with actual content
  729. lines.append("## Page-Specific Rules")
  730. lines.append("")
  731. # Layout Overrides
  732. lines.append("### Layout Overrides")
  733. lines.append("")
  734. layout = page_overrides.get("layout", {})
  735. if layout:
  736. for key, value in layout.items():
  737. lines.append(f"- **{key}:** {value}")
  738. else:
  739. lines.append("- No overrides — use Master layout")
  740. lines.append("")
  741. # Spacing Overrides
  742. lines.append("### Spacing Overrides")
  743. lines.append("")
  744. spacing = page_overrides.get("spacing", {})
  745. if spacing:
  746. for key, value in spacing.items():
  747. lines.append(f"- **{key}:** {value}")
  748. else:
  749. lines.append("- No overrides — use Master spacing")
  750. lines.append("")
  751. # Typography Overrides
  752. lines.append("### Typography Overrides")
  753. lines.append("")
  754. typography = page_overrides.get("typography", {})
  755. if typography:
  756. for key, value in typography.items():
  757. lines.append(f"- **{key}:** {value}")
  758. else:
  759. lines.append("- No overrides — use Master typography")
  760. lines.append("")
  761. # Color Overrides
  762. lines.append("### Color Overrides")
  763. lines.append("")
  764. colors = page_overrides.get("colors", {})
  765. if colors:
  766. for key, value in colors.items():
  767. lines.append(f"- **{key}:** {value}")
  768. else:
  769. lines.append("- No overrides — use Master colors")
  770. lines.append("")
  771. # Component Overrides
  772. lines.append("### Component Overrides")
  773. lines.append("")
  774. components = page_overrides.get("components", [])
  775. if components:
  776. for comp in components:
  777. lines.append(f"- {comp}")
  778. else:
  779. lines.append("- No overrides — use Master component specs")
  780. lines.append("")
  781. # Page-Specific Components
  782. lines.append("---")
  783. lines.append("")
  784. lines.append("## Page-Specific Components")
  785. lines.append("")
  786. unique_components = page_overrides.get("unique_components", [])
  787. if unique_components:
  788. for comp in unique_components:
  789. lines.append(f"- {comp}")
  790. else:
  791. lines.append("- No unique components for this page")
  792. lines.append("")
  793. # Recommendations
  794. lines.append("---")
  795. lines.append("")
  796. lines.append("## Recommendations")
  797. lines.append("")
  798. recommendations = page_overrides.get("recommendations", [])
  799. if recommendations:
  800. for rec in recommendations:
  801. lines.append(f"- {rec}")
  802. lines.append("")
  803. return "\n".join(lines)
  804. def _generate_intelligent_overrides(page_name: str, page_query: str, design_system: dict) -> dict:
  805. """
  806. Generate intelligent overrides based on page type using layered search.
  807. Uses the existing search infrastructure to find relevant style, UX, and layout
  808. data instead of hardcoded page types.
  809. """
  810. from .core import search
  811. page_lower = page_name.lower()
  812. query_lower = (page_query or "").lower()
  813. combined_context = f"{page_lower} {query_lower}"
  814. # Search across multiple domains for page-specific guidance
  815. style_search = search(combined_context, "style", max_results=1)
  816. ux_search = search(combined_context, "ux", max_results=3)
  817. landing_search = search(combined_context, "landing", max_results=1)
  818. # Extract results from search response
  819. style_results = style_search.get("results", [])
  820. ux_results = ux_search.get("results", [])
  821. landing_results = landing_search.get("results", [])
  822. # Detect page type from search results or context
  823. page_type = _detect_page_type(combined_context, style_results)
  824. # Build overrides from search results
  825. layout = {}
  826. spacing = {}
  827. typography = {}
  828. colors = {}
  829. components = []
  830. unique_components = []
  831. recommendations = []
  832. # Extract style-based overrides
  833. if style_results:
  834. style = style_results[0]
  835. style_name = style.get("Style Category", "")
  836. keywords = style.get("Keywords", "")
  837. best_for = style.get("Best For", "")
  838. effects = style.get("Effects & Animation", "")
  839. # Infer layout from style keywords
  840. if any(kw in keywords.lower() for kw in ["data", "dense", "dashboard", "grid"]):
  841. layout["Max Width"] = "1400px or full-width"
  842. layout["Grid"] = "12-column grid for data flexibility"
  843. spacing["Content Density"] = "High — optimize for information display"
  844. elif any(kw in keywords.lower() for kw in ["minimal", "simple", "clean", "single"]):
  845. layout["Max Width"] = "800px (narrow, focused)"
  846. layout["Layout"] = "Single column, centered"
  847. spacing["Content Density"] = "Low — focus on clarity"
  848. else:
  849. layout["Max Width"] = "1200px (standard)"
  850. layout["Layout"] = "Full-width sections, centered content"
  851. if effects:
  852. recommendations.append(f"Effects: {effects}")
  853. # Extract UX guidelines as recommendations
  854. for ux in ux_results:
  855. category = ux.get("Category", "")
  856. do_text = ux.get("Do", "")
  857. dont_text = ux.get("Don't", "")
  858. if do_text:
  859. recommendations.append(f"{category}: {do_text}")
  860. if dont_text:
  861. components.append(f"Avoid: {dont_text}")
  862. # Extract landing pattern info for section structure
  863. if landing_results:
  864. landing = landing_results[0]
  865. sections = landing.get("Section Order", "")
  866. cta_placement = landing.get("Primary CTA Placement", "")
  867. color_strategy = landing.get("Color Strategy", "")
  868. if sections:
  869. layout["Sections"] = sections
  870. if cta_placement:
  871. recommendations.append(f"CTA Placement: {cta_placement}")
  872. if color_strategy:
  873. colors["Strategy"] = color_strategy
  874. # Add page-type specific defaults if no search results
  875. if not layout:
  876. layout["Max Width"] = "1200px"
  877. layout["Layout"] = "Responsive grid"
  878. if not recommendations:
  879. recommendations = [
  880. "Refer to MASTER.md for all design rules",
  881. "Add specific overrides as needed for this page"
  882. ]
  883. return {
  884. "page_type": page_type,
  885. "layout": layout,
  886. "spacing": spacing,
  887. "typography": typography,
  888. "colors": colors,
  889. "components": components,
  890. "unique_components": unique_components,
  891. "recommendations": recommendations
  892. }
  893. def _detect_page_type(context: str, style_results: list) -> str:
  894. """Detect page type from context and search results."""
  895. context_lower = context.lower()
  896. # Check for common page type patterns
  897. page_patterns = [
  898. (["dashboard", "admin", "analytics", "data", "metrics", "stats", "monitor", "overview"], "Dashboard / Data View"),
  899. (["checkout", "payment", "cart", "purchase", "order", "billing"], "Checkout / Payment"),
  900. (["settings", "profile", "account", "preferences", "config"], "Settings / Profile"),
  901. (["landing", "marketing", "homepage", "hero", "home", "promo"], "Landing / Marketing"),
  902. (["login", "signin", "signup", "register", "auth", "password"], "Authentication"),
  903. (["pricing", "plans", "subscription", "tiers", "packages"], "Pricing / Plans"),
  904. (["blog", "article", "post", "news", "content", "story"], "Blog / Article"),
  905. (["product", "item", "detail", "pdp", "shop", "store"], "Product Detail"),
  906. (["search", "results", "browse", "filter", "catalog", "list"], "Search Results"),
  907. (["empty", "404", "error", "not found", "zero"], "Empty State"),
  908. ]
  909. for keywords, page_type in page_patterns:
  910. if any(kw in context_lower for kw in keywords):
  911. return page_type
  912. # Fallback: try to infer from style results
  913. if style_results:
  914. style_name = style_results[0].get("Style Category", "").lower()
  915. best_for = style_results[0].get("Best For", "").lower()
  916. if "dashboard" in best_for or "data" in best_for:
  917. return "Dashboard / Data View"
  918. elif "landing" in best_for or "marketing" in best_for:
  919. return "Landing / Marketing"
  920. return "General"
  921. # ============ CLI SUPPORT ============
  922. if __name__ == "__main__":
  923. import argparse
  924. parser = argparse.ArgumentParser(description="Generate Design System")
  925. parser.add_argument("query", help="Search query (e.g., 'SaaS dashboard')")
  926. parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name")
  927. parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format")
  928. args = parser.parse_args()
  929. result = generate_design_system(args.query, args.project_name, args.format)
  930. print(result)