Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Design intelligence for professional web and mobile interfaces: styles, palettes, typography, UX checks, and design-system guidance.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
design_system.py
1#!/usr/bin/env python32# -*- coding: utf-8 -*-3"""4Design System Generator - Aggregates search results and applies reasoning5to generate comprehensive design system recommendations.67Usage:8from design_system import generate_design_system9result = generate_design_system("SaaS dashboard", "My Project")1011# With persistence (Master + Overrides pattern)12result = generate_design_system("SaaS dashboard", "My Project", persist=True)13result = generate_design_system("SaaS dashboard", "My Project", persist=True, page="dashboard")14"""1516import csv17import json18import os19from datetime import datetime20from pathlib import Path21from core import search, DATA_DIR222324# ============ CONFIGURATION ============25REASONING_FILE = "ui-reasoning.csv"2627SEARCH_CONFIG = {28"product": {"max_results": 1},29"style": {"max_results": 3},30"color": {"max_results": 2},31"landing": {"max_results": 2},32"typography": {"max_results": 2}33}343536# ============ DESIGN SYSTEM GENERATOR ============37class DesignSystemGenerator:38"""Generates design system recommendations from aggregated searches."""3940def __init__(self):41self.reasoning_data = self._load_reasoning()4243def _load_reasoning(self) -> list:44"""Load reasoning rules from CSV."""45filepath = DATA_DIR / REASONING_FILE46if not filepath.exists():47return []48with open(filepath, 'r', encoding='utf-8') as f:49return list(csv.DictReader(f))5051def _multi_domain_search(self, query: str, style_priority: list = None) -> dict:52"""Execute searches across multiple domains."""53results = {}54for domain, config in SEARCH_CONFIG.items():55if domain == "style" and style_priority:56# For style, also search with priority keywords57priority_query = " ".join(style_priority[:2]) if style_priority else query58combined_query = f"{query} {priority_query}"59results[domain] = search(combined_query, domain, config["max_results"])60else:61results[domain] = search(query, domain, config["max_results"])62return results6364def _find_reasoning_rule(self, category: str) -> dict:65"""Find matching reasoning rule for a category."""66category_lower = category.lower()6768# Try exact match first69for rule in self.reasoning_data:70if rule.get("UI_Category", "").lower() == category_lower:71return rule7273# Try partial match74for rule in self.reasoning_data:75ui_cat = rule.get("UI_Category", "").lower()76if ui_cat in category_lower or category_lower in ui_cat:77return rule7879# Try keyword match80for rule in self.reasoning_data:81ui_cat = rule.get("UI_Category", "").lower()82keywords = ui_cat.replace("/", " ").replace("-", " ").split()83if any(kw in category_lower for kw in keywords):84return rule8586return {}8788def _apply_reasoning(self, category: str, search_results: dict) -> dict:89"""Apply reasoning rules to search results."""90rule = self._find_reasoning_rule(category)9192if not rule:93return {94"pattern": "Hero + Features + CTA",95"style_priority": ["Minimalism", "Flat Design"],96"color_mood": "Professional",97"typography_mood": "Clean",98"key_effects": "Subtle hover transitions",99"anti_patterns": "",100"decision_rules": {},101"severity": "MEDIUM"102}103104# Parse decision rules JSON105decision_rules = {}106try:107decision_rules = json.loads(rule.get("Decision_Rules", "{}"))108except json.JSONDecodeError:109pass110111return {112"pattern": rule.get("Recommended_Pattern", ""),113"style_priority": [s.strip() for s in rule.get("Style_Priority", "").split("+")],114"color_mood": rule.get("Color_Mood", ""),115"typography_mood": rule.get("Typography_Mood", ""),116"key_effects": rule.get("Key_Effects", ""),117"anti_patterns": rule.get("Anti_Patterns", ""),118"decision_rules": decision_rules,119"severity": rule.get("Severity", "MEDIUM")120}121122def _select_best_match(self, results: list, priority_keywords: list) -> dict:123"""Select best matching result based on priority keywords."""124if not results:125return {}126127if not priority_keywords:128return results[0]129130# First: try exact style name match131for priority in priority_keywords:132priority_lower = priority.lower().strip()133for result in results:134style_name = result.get("Style Category", "").lower()135if priority_lower in style_name or style_name in priority_lower:136return result137138# Second: score by keyword match in all fields139scored = []140for result in results:141result_str = str(result).lower()142score = 0143for kw in priority_keywords:144kw_lower = kw.lower().strip()145# Higher score for style name match146if kw_lower in result.get("Style Category", "").lower():147score += 10148# Lower score for keyword field match149elif kw_lower in result.get("Keywords", "").lower():150score += 3151# Even lower for other field matches152elif kw_lower in result_str:153score += 1154scored.append((score, result))155156scored.sort(key=lambda x: x[0], reverse=True)157return scored[0][1] if scored and scored[0][0] > 0 else results[0]158159def _extract_results(self, search_result: dict) -> list:160"""Extract results list from search result dict."""161return search_result.get("results", [])162163def generate(self, query: str, project_name: str = None) -> dict:164"""Generate complete design system recommendation."""165# Step 1: First search product to get category166product_result = search(query, "product", 1)167product_results = product_result.get("results", [])168category = "General"169if product_results:170category = product_results[0].get("Product Type", "General")171172# Step 2: Get reasoning rules for this category173reasoning = self._apply_reasoning(category, {})174style_priority = reasoning.get("style_priority", [])175176# Step 3: Multi-domain search with style priority hints177search_results = self._multi_domain_search(query, style_priority)178search_results["product"] = product_result # Reuse product search179180# Step 4: Select best matches from each domain using priority181style_results = self._extract_results(search_results.get("style", {}))182color_results = self._extract_results(search_results.get("color", {}))183typography_results = self._extract_results(search_results.get("typography", {}))184landing_results = self._extract_results(search_results.get("landing", {}))185186best_style = self._select_best_match(style_results, reasoning.get("style_priority", []))187best_color = color_results[0] if color_results else {}188best_typography = typography_results[0] if typography_results else {}189best_landing = landing_results[0] if landing_results else {}190191# Step 5: Build final recommendation192# Combine effects from both reasoning and style search193style_effects = best_style.get("Effects & Animation", "")194reasoning_effects = reasoning.get("key_effects", "")195combined_effects = style_effects if style_effects else reasoning_effects196197return {198"project_name": project_name or query.upper(),199"category": category,200"pattern": {201"name": best_landing.get("Pattern Name", reasoning.get("pattern", "Hero + Features + CTA")),202"sections": best_landing.get("Section Order", "Hero > Features > CTA"),203"cta_placement": best_landing.get("Primary CTA Placement", "Above fold"),204"color_strategy": best_landing.get("Color Strategy", ""),205"conversion": best_landing.get("Conversion Optimization", "")206},207"style": {208"name": best_style.get("Style Category", "Minimalism"),209"type": best_style.get("Type", "General"),210"effects": style_effects,211"keywords": best_style.get("Keywords", ""),212"best_for": best_style.get("Best For", ""),213"performance": best_style.get("Performance", ""),214"accessibility": best_style.get("Accessibility", "")215},216"colors": {217"primary": best_color.get("Primary (Hex)", "#2563EB"),218"secondary": best_color.get("Secondary (Hex)", "#3B82F6"),219"cta": best_color.get("CTA (Hex)", "#F97316"),220"background": best_color.get("Background (Hex)", "#F8FAFC"),221"text": best_color.get("Text (Hex)", "#1E293B"),222"notes": best_color.get("Notes", "")223},224"typography": {225"heading": best_typography.get("Heading Font", "Inter"),226"body": best_typography.get("Body Font", "Inter"),227"mood": best_typography.get("Mood/Style Keywords", reasoning.get("typography_mood", "")),228"best_for": best_typography.get("Best For", ""),229"google_fonts_url": best_typography.get("Google Fonts URL", ""),230"css_import": best_typography.get("CSS Import", "")231},232"key_effects": combined_effects,233"anti_patterns": reasoning.get("anti_patterns", ""),234"decision_rules": reasoning.get("decision_rules", {}),235"severity": reasoning.get("severity", "MEDIUM")236}237238239# ============ OUTPUT FORMATTERS ============240BOX_WIDTH = 90 # Wider box for more content241242def format_ascii_box(design_system: dict) -> str:243"""Format design system as ASCII box with emojis (MCP-style)."""244project = design_system.get("project_name", "PROJECT")245pattern = design_system.get("pattern", {})246style = design_system.get("style", {})247colors = design_system.get("colors", {})248typography = design_system.get("typography", {})249effects = design_system.get("key_effects", "")250anti_patterns = design_system.get("anti_patterns", "")251252def wrap_text(text: str, prefix: str, width: int) -> list:253"""Wrap long text into multiple lines."""254if not text:255return []256words = text.split()257lines = []258current_line = prefix259for word in words:260if len(current_line) + len(word) + 1 <= width - 2:261current_line += (" " if current_line != prefix else "") + word262else:263if current_line != prefix:264lines.append(current_line)265current_line = prefix + word266if current_line != prefix:267lines.append(current_line)268return lines269270# Build sections from pattern271sections = pattern.get("sections", "").split(">")272sections = [s.strip() for s in sections if s.strip()]273274# Build output lines275lines = []276w = BOX_WIDTH - 1277278lines.append("+" + "-" * w + "+")279lines.append(f"| TARGET: {project} - RECOMMENDED DESIGN SYSTEM".ljust(BOX_WIDTH) + "|")280lines.append("+" + "-" * w + "+")281lines.append("|" + " " * BOX_WIDTH + "|")282283# Pattern section284lines.append(f"| PATTERN: {pattern.get('name', '')}".ljust(BOX_WIDTH) + "|")285if pattern.get('conversion'):286lines.append(f"| Conversion: {pattern.get('conversion', '')}".ljust(BOX_WIDTH) + "|")287if pattern.get('cta_placement'):288lines.append(f"| CTA: {pattern.get('cta_placement', '')}".ljust(BOX_WIDTH) + "|")289lines.append("| Sections:".ljust(BOX_WIDTH) + "|")290for i, section in enumerate(sections, 1):291lines.append(f"| {i}. {section}".ljust(BOX_WIDTH) + "|")292lines.append("|" + " " * BOX_WIDTH + "|")293294# Style section295lines.append(f"| STYLE: {style.get('name', '')}".ljust(BOX_WIDTH) + "|")296if style.get("keywords"):297for line in wrap_text(f"Keywords: {style.get('keywords', '')}", "| ", BOX_WIDTH):298lines.append(line.ljust(BOX_WIDTH) + "|")299if style.get("best_for"):300for line in wrap_text(f"Best For: {style.get('best_for', '')}", "| ", BOX_WIDTH):301lines.append(line.ljust(BOX_WIDTH) + "|")302if style.get("performance") or style.get("accessibility"):303perf_a11y = f"Performance: {style.get('performance', '')} | Accessibility: {style.get('accessibility', '')}"304lines.append(f"| {perf_a11y}".ljust(BOX_WIDTH) + "|")305lines.append("|" + " " * BOX_WIDTH + "|")306307# Colors section308lines.append("| COLORS:".ljust(BOX_WIDTH) + "|")309lines.append(f"| Primary: {colors.get('primary', '')}".ljust(BOX_WIDTH) + "|")310lines.append(f"| Secondary: {colors.get('secondary', '')}".ljust(BOX_WIDTH) + "|")311lines.append(f"| CTA: {colors.get('cta', '')}".ljust(BOX_WIDTH) + "|")312lines.append(f"| Background: {colors.get('background', '')}".ljust(BOX_WIDTH) + "|")313lines.append(f"| Text: {colors.get('text', '')}".ljust(BOX_WIDTH) + "|")314if colors.get("notes"):315for line in wrap_text(f"Notes: {colors.get('notes', '')}", "| ", BOX_WIDTH):316lines.append(line.ljust(BOX_WIDTH) + "|")317lines.append("|" + " " * BOX_WIDTH + "|")318319# Typography section320lines.append(f"| TYPOGRAPHY: {typography.get('heading', '')} / {typography.get('body', '')}".ljust(BOX_WIDTH) + "|")321if typography.get("mood"):322for line in wrap_text(f"Mood: {typography.get('mood', '')}", "| ", BOX_WIDTH):323lines.append(line.ljust(BOX_WIDTH) + "|")324if typography.get("best_for"):325for line in wrap_text(f"Best For: {typography.get('best_for', '')}", "| ", BOX_WIDTH):326lines.append(line.ljust(BOX_WIDTH) + "|")327if typography.get("google_fonts_url"):328lines.append(f"| Google Fonts: {typography.get('google_fonts_url', '')}".ljust(BOX_WIDTH) + "|")329if typography.get("css_import"):330lines.append(f"| CSS Import: {typography.get('css_import', '')[:70]}...".ljust(BOX_WIDTH) + "|")331lines.append("|" + " " * BOX_WIDTH + "|")332333# Key Effects section334if effects:335lines.append("| KEY EFFECTS:".ljust(BOX_WIDTH) + "|")336for line in wrap_text(effects, "| ", BOX_WIDTH):337lines.append(line.ljust(BOX_WIDTH) + "|")338lines.append("|" + " " * BOX_WIDTH + "|")339340# Anti-patterns section341if anti_patterns:342lines.append("| AVOID (Anti-patterns):".ljust(BOX_WIDTH) + "|")343for line in wrap_text(anti_patterns, "| ", BOX_WIDTH):344lines.append(line.ljust(BOX_WIDTH) + "|")345lines.append("|" + " " * BOX_WIDTH + "|")346347# Pre-Delivery Checklist section348lines.append("| PRE-DELIVERY CHECKLIST:".ljust(BOX_WIDTH) + "|")349checklist_items = [350"[ ] No emojis as icons (use SVG: Heroicons/Lucide)",351"[ ] cursor-pointer on all clickable elements",352"[ ] Hover states with smooth transitions (150-300ms)",353"[ ] Light mode: text contrast 4.5:1 minimum",354"[ ] Focus states visible for keyboard nav",355"[ ] prefers-reduced-motion respected",356"[ ] Responsive: 375px, 768px, 1024px, 1440px"357]358for item in checklist_items:359lines.append(f"| {item}".ljust(BOX_WIDTH) + "|")360lines.append("|" + " " * BOX_WIDTH + "|")361362lines.append("+" + "-" * w + "+")363364