design_system.py 43 KB

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