design_system.py 46 KB

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