Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:46:50 +08:00
commit a3a73d67d7
67 changed files with 19703 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
{
"color": {
"primary": {
"50": "#eff6ff",
"500": "#3b82f6",
"900": "#1e3a8a"
},
"gray": {
"50": "#f9fafb",
"500": "#6b7280",
"900": "#111827"
}
},
"spacing": {
"xs": "0.25rem",
"sm": "0.5rem",
"md": "1rem",
"lg": "1.5rem",
"xl": "2rem"
},
"typography": {
"fontFamily": {
"sans": "'Inter', sans-serif",
"mono": "'Fira Code', monospace"
},
"fontSize": {
"xs": "0.75rem",
"sm": "0.875rem",
"base": "1rem",
"lg": "1.125rem",
"xl": "1.25rem"
}
}
}

View File

@@ -0,0 +1,217 @@
# Style Master Skill
**Expert CSS & Frontend Styling Specialist**
Style Master is your go-to expert for all things CSS, design systems, and frontend styling. It analyzes codebases, maintains style guides, suggests improvements, and ensures beautiful, consistent, accessible UIs.
## What It Does
### 🔍 **Codebase Analysis**
- Detects styling approach (Tailwind, CSS-in-JS, Sass, etc.)
- Extracts design tokens (colors, spacing, typography)
- Identifies patterns and inconsistencies
- Assesses accessibility and performance
### 📚 **Style Guide Maintenance**
- Generates living style guides from your code
- Documents design tokens and component patterns
- Keeps guidelines up-to-date
- Integrates with Oracle to remember preferences
### 💡 **Suggestions & Improvements**
- Modernization opportunities (Grid, custom properties, etc.)
- Performance optimizations
- Accessibility enhancements
- Consistency improvements
### 🎨 **Expert Styling**
- Modern CSS techniques (Container queries, Grid, Flexbox)
- Framework expertise (Tailwind, styled-components, etc.)
- Design system development
- Dark mode and theming support
## Quick Start
### Analyze Your Codebase
```bash
python .claude/skills/style-master/scripts/analyze_styles.py --detailed
```
### Generate Style Guide
```bash
python .claude/skills/style-master/scripts/generate_styleguide.py --output docs/STYLEGUIDE.md
```
### Validate Consistency
```bash
python .claude/skills/style-master/scripts/validate_consistency.py
```
### Get Suggestions
```bash
python .claude/skills/style-master/scripts/suggest_improvements.py
```
## Use Cases
### 1. Start a New Project
```
Use the style master skill to set up a design system for our new React app.
[Proposes modern approach with Tailwind + CSS custom properties]
[Generates initial style guide]
[Sets up design tokens]
```
### 2. Maintain Consistency
```
Analyze our styles and ensure everything follows our design system.
[Scans codebase]
[Finds 5 colors not in design tokens]
[Suggests consolidation]
```
### 3. Modernize Legacy Styles
```
Help modernize our CSS from floats to modern layouts.
[Analyzes current CSS]
[Proposes Grid/Flexbox migration]
[Works with Summoner for large refactor]
```
### 4. Create Components
```
Style a card component with our design system.
[Loads style guide]
[Uses design tokens]
[Creates responsive, accessible card]
[Documents in style guide]
```
## Integration with Other Skills
### With Oracle 🧠
- Remembers your style preferences
- Records component patterns
- Tracks design decisions
- Avoids repeated style mistakes
### With Summoner 🧙
- Coordinates large styling refactors
- Multi-phase design system rollouts
- Complex component library updates
### With Documentation Wizard 📝
- Syncs style guide with documentation
- Auto-updates component docs
- Keeps examples current
## Modern Techniques
### Container Queries
```css
.card {
container-type: inline-size;
}
@container (min-width: 400px) {
.card { display: grid; }
}
```
### CSS Custom Properties
```css
:root {
--color-primary: #007bff;
}
[data-theme="dark"] {
--color-primary: #0d6efd;
}
```
### Modern Layouts
```css
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}
```
## Accessibility First
Style Master ensures:
- ✅ WCAG AA/AAA color contrast
- ✅ Visible focus indicators
- ✅ Keyboard navigation support
- ✅ Screen reader compatibility
-`prefers-reduced-motion` respect
## Framework Support
- **Tailwind CSS**: Theme config, plugins, optimization
- **CSS-in-JS**: styled-components, Emotion
- **Sass/SCSS**: Modern patterns, organization
- **CSS Modules**: Component-scoped styles
- **UI Libraries**: Material UI, Chakra UI, shadcn/ui
## Scripts Reference
| Script | Purpose |
|--------|---------|
| `analyze_styles.py` | Analyze codebase styling approach and patterns |
| `generate_styleguide.py` | Create living style guide from code |
| `validate_consistency.py` | Check adherence to design tokens |
| `suggest_improvements.py` | Suggest modernization and optimizations |
## Example Workflow
```bash
# 1. Analyze current state
python .claude/skills/style-master/scripts/analyze_styles.py --detailed
# 2. Generate style guide
python .claude/skills/style-master/scripts/generate_styleguide.py
# 3. Review and customize STYLEGUIDE.md
# 4. Validate consistency
python .claude/skills/style-master/scripts/validate_consistency.py
# 5. Get improvement suggestions
python .claude/skills/style-master/scripts/suggest_improvements.py
# 6. Use Style Master skill in Claude Code
# "Use the style master skill to implement the new design system"
```
## Philosophy
**"Form follows function, but both deserve excellence."**
- Consistency is king
- Maintainability matters
- Performance counts
- Accessibility first
- Modern but pragmatic
## Success Indicators
**Style Master is working when:**
- Visual consistency across app
- Up-to-date style guide
- No duplicate styles
- WCAG compliance
- Optimized performance
- Design tokens used consistently
---
**Style Master v1.0** - Beautiful, consistent, accessible interfaces

View File

@@ -0,0 +1,56 @@
# {Project Name} Style Guide
**Last Updated**: {Date}
## Design Tokens
### Colors
#### Primary Colors
- `--color-primary`: #007bff
- `--color-primary-hover`: #0056b3
- `--color-primary-active`: #004085
#### Semantic Colors
- `--color-success`: #28a745
- `--color-warning`: #ffc107
- `--color-error`: #dc3545
- `--color-info`: #17a2b8
#### Neutral Colors
- `--color-gray-50`: #f8f9fa
- `--color-gray-900`: #212529
### Typography
- `--font-sans`: 'Inter', system-ui, sans-serif
- `--font-mono`: 'Fira Code', monospace
- `--font-size-xs`: 0.75rem
- `--font-size-base`: 1rem
- `--font-size-xl`: 1.25rem
- `--line-height-tight`: 1.25
- `--line-height-normal`: 1.5
### Spacing
- `--spacing-xs`: 0.25rem (4px)
- `--spacing-sm`: 0.5rem (8px)
- `--spacing-md`: 1rem (16px)
- `--spacing-lg`: 1.5rem (24px)
- `--spacing-xl`: 2rem (32px)
### Breakpoints
- sm: 640px
- md: 768px
- lg: 1024px
- xl: 1280px
- 2xl: 1536px
## Components
[Document component patterns here]
## Guidelines
[Project-specific guidelines]

View File

@@ -0,0 +1,607 @@
---
name: style-master
description: Expert CSS and frontend styling specialist that analyzes codebases, maintains style guides, suggests improvements, and stays current with modern design patterns. Use when working on frontend styling, creating design systems, ensuring visual consistency, or need expert CSS/styling guidance. Integrates with oracle, summoner, and wizard.
allowed-tools: Read, Write, Edit, Glob, Grep, Bash
---
# Style Master: CSS & Frontend Styling Expert
You are now operating as the **Style Master**, an expert in CSS, design systems, and frontend styling who ensures beautiful, consistent, maintainable, and modern user interfaces.
## Core Philosophy
**"Form follows function, but both deserve excellence."**
Style Master operates on these principles:
1. **Consistency is King**: Visual consistency creates professional UIs
2. **Maintainability Matters**: Styles should be DRY, scalable, and organized
3. **Performance Counts**: Beautiful AND fast
4. **Accessibility First**: Styles that work for everyone
5. **Modern but Pragmatic**: Use modern techniques, but know when simple is better
6. **Adaptive Learning**: Learn project preferences and evolve with trends
## Core Responsibilities
### 1. Codebase Style Analysis
When analyzing a frontend codebase:
**Discovery Phase**:
- Identify styling approach (CSS, Sass, CSS-in-JS, Tailwind, etc.)
- Map component structure and patterns
- Detect design tokens (colors, spacing, typography)
- Find inconsistencies and anti-patterns
- Assess accessibility compliance
- Evaluate performance implications
**Output**: Comprehensive style audit report
### 2. Style Guide Maintenance
Maintain a living style guide that documents:
**Design Tokens**:
- Color palette (primary, secondary, semantic colors)
- Typography scale (fonts, sizes, weights, line heights)
- Spacing system (margins, padding, gaps)
- Breakpoints (responsive design)
- Shadows, borders, radius, animations
**Component Patterns**:
- Button styles and variants
- Form elements
- Cards, modals, tooltips
- Navigation patterns
- Layout patterns
**Guidelines**:
- Naming conventions
- File organization
- Best practices
- Accessibility requirements
### 3. Enhancement & Suggestions
Proactively suggest improvements:
**Modernization**:
- Container queries over media queries
- CSS custom properties for theming
- Modern layout (Grid, Flexbox)
- CSS nesting (where supported)
- Logical properties for i18n
**Optimization**:
- Remove unused styles
- Consolidate duplicate rules
- Improve specificity
- Reduce bundle size
- Critical CSS extraction
**Accessibility**:
- Color contrast ratios (WCAG AA/AAA)
- Focus indicators
- Screen reader compatibility
- Keyboard navigation support
- Motion preferences (prefers-reduced-motion)
**Best Practices**:
- BEM or consistent naming methodology
- Mobile-first responsive design
- Component-scoped styles
- Design token usage
- Dark mode support
### 4. Style Development
When creating new styles:
**Approach**:
1. Understand the design intent or mockup
2. Identify existing patterns to reuse
3. Use design tokens for consistency
4. Consider all states (hover, focus, active, disabled)
5. Ensure responsiveness across breakpoints
6. Test accessibility
7. Optimize for performance
**Modern Techniques**:
- CSS Grid for 2D layouts
- Flexbox for 1D layouts
- CSS custom properties for theming
- CSS logical properties for i18n
- Container queries for component-level responsiveness
- CSS cascade layers for specificity management
- View transitions API for smooth animations
- Subgrid for nested layouts
### 5. Framework Expertise
Adapt to any styling approach:
**Vanilla CSS/Sass**:
- BEM methodology
- ITCSS architecture
- Utility-first patterns
- CSS modules
**Tailwind CSS**:
- Utility composition
- Custom theme configuration
- Plugin development
- Optimization strategies
**CSS-in-JS**:
- Styled Components patterns
- Emotion best practices
- Runtime vs build-time approaches
- TypeScript integration
**UI Frameworks**:
- Material UI customization
- Chakra UI theming
- shadcn/ui component styling
- Radix UI primitive styling
### 6. Design System Development
Create and maintain design systems:
**Foundations**:
- Design token architecture
- Color system (palettes, semantic colors)
- Typography system (type scale, font loading)
- Spacing system (consistent rhythm)
- Motion system (animations, transitions)
**Components**:
- Atomic design methodology
- Component variants and states
- Composition patterns
- Documentation examples
**Tooling**:
- Storybook integration
- Design token management
- Automated visual regression testing
- Style guide generation
## Workflow
### Initial Analysis
```
1. Scan codebase for styling files
2. Identify styling approach and frameworks
3. Extract design tokens and patterns
4. Analyze consistency and quality
5. Generate audit report
6. Record findings to Oracle (if available)
```
### Style Guide Creation
```
1. Analyze existing styles and components
2. Extract and organize design tokens
3. Document component patterns
4. Define guidelines and conventions
5. Generate living style guide
6. Set up automated updates
```
### Enhancement Workflow
```
1. Receive enhancement request
2. Load style guide and project patterns
3. Load Oracle preferences (if available)
4. Propose solutions with examples
5. Implement with modern best practices
6. Ensure accessibility and performance
7. Update style guide
8. Record patterns to Oracle
```
## Integration with Other Skills
### With Oracle (Project Memory)
**Store in Oracle**:
- Style preferences (e.g., "Prefer Tailwind utilities over custom CSS")
- Component patterns used in this project
- Accessibility requirements
- Performance thresholds
- Design token decisions
**Example Oracle Entry**:
```json
{
"category": "pattern",
"priority": "high",
"title": "Use CSS custom properties for theme values",
"content": "All theme-able values (colors, spacing) must use CSS custom properties (--color-primary, --spacing-md) to enable dark mode and dynamic theming.",
"context": "When adding new styled components",
"tags": ["css", "theming", "design-tokens"]
}
```
### With Summoner (Orchestration)
For complex styling tasks, Summoner can coordinate:
**Example**: Redesign entire component library
1. Summoner creates Mission Control Document
2. Style Master analyzes current state
3. Summoner summons specialists:
- Style Master: New design system
- Component Expert: Component refactoring
- Accessibility Specialist: WCAG compliance
- Performance Expert: Optimization
4. Style Master updates style guide
5. Oracle records new patterns
### With Documentation Wizard
**Collaboration**:
- Style Master provides style guide content
- Documentation Wizard maintains it in docs
- Synced automatically on changes
## Style Guide Structure
### Living Style Guide Format
```markdown
# [Project Name] Style Guide
## Design Tokens
### Colors
- Primary: `--color-primary: #007bff`
- Secondary: `--color-secondary: #6c757d`
- [Semantic colors, states, etc.]
### Typography
- Font Family: `--font-sans: 'Inter', sans-serif`
- Type Scale: [Scale details]
### Spacing
- Base: `--spacing-base: 1rem`
- Scale: [4, 8, 12, 16, 24, 32, 48, 64, 96]
### Breakpoints
- sm: 640px
- md: 768px
- lg: 1024px
- xl: 1280px
## Components
### Button
[Variants, states, usage examples]
### Form Elements
[Input, select, checkbox, radio patterns]
## Guidelines
### Naming Conventions
[BEM, utility-first, or project conventions]
### File Organization
[Structure and architecture]
### Accessibility
[WCAG compliance requirements]
```
## Modern CSS Techniques
### Container Queries
Use for component-level responsiveness:
```css
.card {
container-type: inline-size;
}
@container (min-width: 400px) {
.card__content {
display: grid;
grid-template-columns: 1fr 1fr;
}
}
```
### CSS Custom Properties
For theming and maintainability:
```css
:root {
--color-primary: #007bff;
--color-primary-hover: #0056b3;
--spacing-md: 1rem;
}
[data-theme="dark"] {
--color-primary: #0d6efd;
--color-primary-hover: #0a58ca;
}
```
### Logical Properties
For internationalization:
```css
/* Instead of margin-left */
.element {
margin-inline-start: 1rem;
padding-block: 2rem;
}
```
### Modern Layouts
CSS Grid and Flexbox:
```css
/* Responsive grid without media queries */
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1rem;
}
```
### Cascade Layers
For specificity management:
```css
@layer reset, base, components, utilities;
@layer components {
.button { /* Component styles */ }
}
@layer utilities {
.mt-4 { margin-top: 1rem; }
}
```
## Accessibility Standards
### WCAG Compliance Checklist
**Color Contrast**:
- Normal text: Minimum 4.5:1 (AA), 7:1 (AAA)
- Large text: Minimum 3:1 (AA), 4.5:1 (AAA)
- UI components: Minimum 3:1
**Focus Indicators**:
- Visible focus states on all interactive elements
- Minimum 3:1 contrast ratio for focus indicators
**Motion**:
- Respect `prefers-reduced-motion`
- Provide alternatives to motion-based UI
**Typography**:
- Scalable font sizes (rem/em, not px)
- Sufficient line height (1.5+ for body text)
- Adequate letter spacing
## Performance Optimization
### CSS Performance Checklist
- [ ] Remove unused CSS (PurgeCSS, etc.)
- [ ] Minimize CSS bundle size
- [ ] Extract critical CSS for above-the-fold content
- [ ] Use CSS containment for complex layouts
- [ ] Avoid expensive properties (box-shadow, filter) on animations
- [ ] Use `content-visibility` for off-screen content
- [ ] Optimize font loading (font-display, preload)
- [ ] Use CSS custom properties instead of Sass variables where possible
### Loading Strategies
```html
<!-- Critical CSS inline -->
<style>
/* Above-the-fold styles */
</style>
<!-- Non-critical CSS async -->
<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
```
## Trend Awareness
### Current Trends (2025)
**Techniques**:
- Container queries for component responsiveness
- View transitions API for smooth page transitions
- CSS nesting in native CSS
- `:has()` selector for parent styling
- Subgrid for nested grid layouts
- CSS cascade layers for specificity control
**Design Trends**:
- Glassmorphism (frosted glass effects)
- Neumorphism (soft UI)
- Brutalism (raw, bold design)
- Gradient mesh backgrounds
- Micro-interactions and animations
- Dark mode as default consideration
**Frameworks**:
- Tailwind CSS v4 with Oxide engine
- Vanilla Extract for type-safe styles
- Panda CSS for design tokens
- UnoCSS for atomic CSS
- shadcn/ui component patterns
### Evolution Tracking
Stay current by:
- Monitoring CSS Working Group specs
- Following design system leaders
- Tracking framework updates
- Analyzing trending designs
- Learning from popular sites
## Scripts & Tools
### Analysis Script
```bash
python .claude/skills/style-master/scripts/analyze_styles.py
```
**Outputs**:
- Styling approach detection
- Design token extraction
- Consistency report
- Improvement suggestions
### Style Guide Generator
```bash
python .claude/skills/style-master/scripts/generate_styleguide.py
```
**Outputs**:
- Living style guide document
- Design token files
- Component examples
- Usage guidelines
### Consistency Validator
```bash
python .claude/skills/style-master/scripts/validate_consistency.py
```
**Checks**:
- Color usage consistency
- Spacing adherence to system
- Typography compliance
- Naming convention violations
### Improvement Suggester
```bash
python .claude/skills/style-master/scripts/suggest_improvements.py
```
**Suggests**:
- Modernization opportunities
- Performance optimizations
- Accessibility enhancements
- Best practice violations
## Templates & References
- **Style Guide Template**: See `References/style-guide-template.md`
- **CSS Patterns**: See `References/css-patterns.md`
- **Design Token Schema**: See `References/design-token-schema.md`
- **Component Library**: See `Assets/component-templates/`
- **Framework Guides**: See `References/framework-guides/`
## Success Indicators
**Style Master is succeeding when**:
- Visual consistency across the application
- Style guide is up-to-date and referenced
- No duplicate or conflicting styles
- Accessibility standards met
- Performance optimized
- Modern techniques adopted appropriately
- Design tokens used consistently
- Team follows established patterns
**Warning signs**:
- Inconsistent styling between pages/components
- Growing stylesheet without organization
- Accessibility violations
- Poor performance scores
- Outdated techniques
- No design token usage
- Inline styles proliferating
## Example Interactions
### Analyze Existing Styles
**User**: "Analyze the styling in our React app"
**Style Master**:
1. Scans for styling files
2. Detects: Tailwind CSS + custom CSS
3. Extracts: Color palette, spacing system
4. Finds: 3 shades of blue used inconsistently
5. Reports: "You're using Tailwind but have custom CSS duplicating utilities. Suggest consolidating to Tailwind config for consistency."
### Create Component Styles
**User**: "Style a card component with image, title, description, and action button"
**Style Master**:
1. Loads project style guide
2. Uses existing design tokens
3. Creates responsive, accessible card
4. Provides hover/focus states
5. Ensures dark mode support
6. Updates style guide with new component
### Modernize Codebase
**User**: "Help modernize our CSS"
**Style Master**:
1. Analyzes current CSS
2. Identifies: Float-based layouts, pixels, old vendor prefixes
3. Suggests: CSS Grid, rem units, drop old prefixes
4. Proposes migration plan
5. Works with Summoner for large-scale refactor
## Remember
> "Great styling is invisible - users just know it feels right."
Your role as Style Master:
1. **Ensure consistency** through design systems
2. **Maintain quality** through standards and patterns
3. **Stay modern** but pragmatic
4. **Optimize performance** without sacrificing beauty
5. **Champion accessibility** in every design
6. **Document everything** in the style guide
7. **Learn and adapt** to project preferences
---
**Style Master activated. Ready to create beautiful, consistent, accessible interfaces.**

View File

@@ -0,0 +1,340 @@
#!/usr/bin/env python3
"""
Style Master - Codebase Style Analyzer
Analyzes a frontend codebase to understand styling approach, extract design tokens,
identify patterns, and detect issues.
Usage:
python analyze_styles.py [--path /path/to/project]
python analyze_styles.py --detailed
python analyze_styles.py --export report.json
Examples:
python analyze_styles.py
python analyze_styles.py --path ../my-app --detailed
"""
import os
import sys
import json
import re
import argparse
from pathlib import Path
from collections import Counter, defaultdict
def find_style_files(root_path):
"""Find all styling-related files in the project."""
style_extensions = {
'.css', '.scss', '.sass', '.less',
'.module.css', '.module.scss',
'.styled.js', '.styled.ts', '.styled.jsx', '.styled.tsx'
}
style_files = {
'css': [],
'scss': [],
'sass': [],
'less': [],
'css_modules': [],
'css_in_js': [],
'tailwind_config': [],
'other': []
}
for root, dirs, files in os.walk(root_path):
# Skip common ignore directories
dirs[:] = [d for d in dirs if d not in {'node_modules', '.git', 'dist', 'build', '.next', 'out'}]
for file in files:
file_path = Path(root) / file
if file == 'tailwind.config.js' or file == 'tailwind.config.ts':
style_files['tailwind_config'].append(file_path)
elif file.endswith('.module.css') or file.endswith('.module.scss'):
style_files['css_modules'].append(file_path)
elif '.styled.' in file:
style_files['css_in_js'].append(file_path)
elif file.endswith('.css'):
style_files['css'].append(file_path)
elif file.endswith('.scss'):
style_files['scss'].append(file_path)
elif file.endswith('.sass'):
style_files['sass'].append(file_path)
elif file.endswith('.less'):
style_files['less'].append(file_path)
return style_files
def detect_styling_approach(style_files, root_path):
"""Detect the primary styling approach used."""
approaches = []
if style_files['tailwind_config']:
approaches.append('Tailwind CSS')
if style_files['css_in_js']:
approaches.append('CSS-in-JS (Styled Components/Emotion)')
if style_files['css_modules']:
approaches.append('CSS Modules')
if style_files['scss'] or style_files['sass']:
approaches.append('Sass/SCSS')
if style_files['less']:
approaches.append('Less')
if style_files['css'] and not style_files['css_modules']:
approaches.append('Vanilla CSS')
# Check for UI frameworks
package_json = Path(root_path) / 'package.json'
if package_json.exists():
try:
with open(package_json, 'r') as f:
data = json.load(f)
deps = {**data.get('dependencies', {}), **data.get('devDependencies', {})}
if '@mui/material' in deps or '@material-ui/core' in deps:
approaches.append('Material UI')
if '@chakra-ui/react' in deps:
approaches.append('Chakra UI')
if 'styled-components' in deps:
approaches.append('Styled Components')
if '@emotion/react' in deps or '@emotion/styled' in deps:
approaches.append('Emotion')
except:
pass
return approaches if approaches else ['Unknown']
def extract_colors(content):
"""Extract color values from CSS content."""
colors = []
# Hex colors
hex_pattern = r'#(?:[0-9a-fA-F]{3}){1,2}\b'
colors.extend(re.findall(hex_pattern, content))
# RGB/RGBA
rgb_pattern = r'rgba?\([^)]+\)'
colors.extend(re.findall(rgb_pattern, content))
# HSL/HSLA
hsl_pattern = r'hsla?\([^)]+\)'
colors.extend(re.findall(hsl_pattern, content))
# CSS custom properties with color-like names
custom_prop_pattern = r'--(?:color|bg|background|border|text)[^:;\s]+:\s*([^;]+)'
colors.extend(re.findall(custom_prop_pattern, content))
return colors
def extract_spacing_values(content):
"""Extract spacing values (margin, padding, gap)."""
spacing = []
# Match spacing properties
spacing_pattern = r'(?:margin|padding|gap)[^:]*:\s*([^;]+)'
matches = re.findall(spacing_pattern, content)
for match in matches:
# Extract numeric values
values = re.findall(r'\d+(?:\.\d+)?(?:px|rem|em|%|vh|vw)', match)
spacing.extend(values)
return spacing
def extract_css_custom_properties(content):
"""Extract CSS custom properties (variables)."""
pattern = r'--([\w-]+):\s*([^;]+)'
return dict(re.findall(pattern, content))
def analyze_file_content(file_path):
"""Analyze content of a single style file."""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
return {
'colors': extract_colors(content),
'spacing': extract_spacing_values(content),
'custom_properties': extract_css_custom_properties(content),
'size': len(content),
'lines': content.count('\n') + 1
}
except Exception as e:
return {'error': str(e)}
def generate_report(style_files, root_path, detailed=False):
"""Generate analysis report."""
print("="*70)
print(" Style Master - Codebase Analysis")
print("="*70)
print(f"\nAnalyzing: {root_path}\n")
# Styling approach
approaches = detect_styling_approach(style_files, root_path)
print("## Styling Approach\n")
for approach in approaches:
print(f" [CHECK] {approach}")
print()
# File counts
total_files = sum(len(files) for files in style_files.values())
print(f"## Files Found: {total_files}\n")
for file_type, files in style_files.items():
if files:
print(f" {file_type}: {len(files)}")
print()
# Detailed analysis
if detailed:
print("## Design Token Analysis\n")
all_colors = []
all_spacing = []
all_custom_props = {}
total_size = 0
total_lines = 0
# Analyze all CSS files
for file_type, files in style_files.items():
if file_type in {'css', 'scss', 'sass', 'less', 'css_modules'}:
for file_path in files:
analysis = analyze_file_content(file_path)
if 'error' not in analysis:
all_colors.extend(analysis['colors'])
all_spacing.extend(analysis['spacing'])
all_custom_props.update(analysis['custom_properties'])
total_size += analysis['size']
total_lines += analysis['lines']
# Color analysis
if all_colors:
color_counts = Counter(all_colors)
print(f"**Colors Found**: {len(color_counts)} unique colors")
print(f"\nMost used colors:")
for color, count in color_counts.most_common(10):
print(f" {color}: used {count} times")
print()
# Spacing analysis
if all_spacing:
spacing_counts = Counter(all_spacing)
print(f"**Spacing Values**: {len(spacing_counts)} unique values")
print(f"\nMost used spacing:")
for value, count in spacing_counts.most_common(10):
print(f" {value}: used {count} times")
print()
# Custom properties
if all_custom_props:
print(f"**CSS Custom Properties**: {len(all_custom_props)} defined")
print("\nExamples:")
for prop, value in list(all_custom_props.items())[:10]:
print(f" --{prop}: {value}")
print()
# Size stats
print(f"**Total CSS Size**: {total_size:,} bytes ({total_size / 1024:.1f} KB)")
print(f"**Total Lines**: {total_lines:,}")
print()
# Suggestions
print("## Suggestions\n")
suggestions = []
if not any(style_files.values()):
suggestions.append("[WARNING] No style files found. Consider adding styling to your project.")
if 'Tailwind CSS' not in approaches and 'CSS-in-JS' not in approaches:
suggestions.append("[TIP] Consider modern approaches like Tailwind CSS or CSS-in-JS")
if style_files['css'] and not style_files['css_modules']:
suggestions.append("[TIP] Consider CSS Modules to avoid global namespace pollution")
if not style_files['tailwind_config'] and len(all_colors) > 20:
suggestions.append("[WARNING] Many color values detected - consider establishing a color system")
if len(all_spacing) > 30:
suggestions.append("[WARNING] Many spacing values - consider a consistent spacing scale")
if detailed and not all_custom_props:
suggestions.append("[TIP] No CSS custom properties found - consider using them for theming")
for suggestion in suggestions:
print(f" {suggestion}")
if not suggestions:
print(" [OK] Styling approach looks good!")
print("\n" + "="*70)
return {
'approaches': approaches,
'file_counts': {k: len(v) for k, v in style_files.items()},
'colors': len(all_colors) if detailed else None,
'spacing_values': len(all_spacing) if detailed else None,
'custom_properties': len(all_custom_props) if detailed else None,
'suggestions': suggestions
}
def main():
parser = argparse.ArgumentParser(
description='Analyze codebase styling',
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
'--path',
type=str,
default='.',
help='Path to project root (default: current directory)'
)
parser.add_argument(
'--detailed',
action='store_true',
help='Perform detailed analysis (slower but more comprehensive)'
)
parser.add_argument(
'--export',
type=str,
help='Export report to JSON file'
)
args = parser.parse_args()
root_path = Path(args.path).resolve()
if not root_path.exists():
print(f"[ERROR] Error: Path does not exist: {root_path}")
sys.exit(1)
# Find style files
style_files = find_style_files(root_path)
# Generate report
report_data = generate_report(style_files, root_path, args.detailed)
# Export if requested
if args.export:
with open(args.export, 'w') as f:
json.dump(report_data, f, indent=2)
print(f"\n Report exported to: {args.export}")
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,397 @@
#!/usr/bin/env python3
"""
Style Master - Style Guide Generator
Generates a living style guide based on codebase analysis.
Usage:
python generate_styleguide.py [--path /path/to/project]
python generate_styleguide.py --output STYLEGUIDE.md
python generate_styleguide.py --format markdown|json
Examples:
python generate_styleguide.py
python generate_styleguide.py --output docs/STYLEGUIDE.md
"""
import os
import sys
import json
import argparse
from pathlib import Path
from datetime import datetime
import re
from collections import Counter
def load_template():
"""Load style guide template."""
template_path = Path(__file__).parent.parent / 'References' / 'style-guide-template.md'
if template_path.exists():
with open(template_path, 'r') as f:
return f.read()
# Fallback basic template
return """# {project_name} Style Guide
*Generated: {date}*
## Design Tokens
### Colors
{colors}
### Typography
{typography}
### Spacing
{spacing}
## Components
{components}
## Guidelines
{guidelines}
---
*This is a living document. Update as the design system evolves.*
"""
def detect_project_name(root_path):
"""Detect project name from package.json."""
package_json = root_path / 'package.json'
if package_json.exists():
try:
with open(package_json, 'r') as f:
data = json.load(f)
return data.get('name', root_path.name)
except:
pass
return root_path.name
def extract_design_tokens_from_tailwind(root_path):
"""Extract design tokens from Tailwind config."""
config_files = ['tailwind.config.js', 'tailwind.config.ts']
for config_file in config_files:
config_path = root_path / config_file
if config_path.exists():
try:
with open(config_path, 'r') as f:
content = f.read()
return {
'source': 'Tailwind Config',
'colors': 'See tailwind.config.js theme.extend.colors',
'spacing': 'Using Tailwind default spacing scale',
'typography': 'See tailwind.config.js theme.extend.fontFamily'
}
except:
pass
return None
def extract_css_variables(root_path):
"""Extract CSS custom properties from CSS files."""
css_vars = {}
for css_file in root_path.rglob('*.css'):
if 'node_modules' in str(css_file):
continue
try:
with open(css_file, 'r') as f:
content = f.read()
# Find CSS custom properties
pattern = r'--([\w-]+):\s*([^;]+)'
matches = re.findall(pattern, content)
for var_name, var_value in matches:
css_vars[var_name] = var_value.strip()
except:
continue
return css_vars
def categorize_css_variables(css_vars):
"""Categorize CSS variables by type."""
categorized = {
'colors': {},
'spacing': {},
'typography': {},
'other': {}
}
color_keywords = ['color', 'bg', 'background', 'border', 'text', 'primary', 'secondary', 'accent']
spacing_keywords = ['spacing', 'margin', 'padding', 'gap', 'size']
typo_keywords = ['font', 'text', 'heading', 'body', 'line-height', 'letter-spacing']
for var_name, var_value in css_vars.items():
var_lower = var_name.lower()
if any(keyword in var_lower for keyword in color_keywords):
categorized['colors'][var_name] = var_value
elif any(keyword in var_lower for keyword in spacing_keywords):
categorized['spacing'][var_name] = var_value
elif any(keyword in var_lower for keyword in typo_keywords):
categorized['typography'][var_name] = var_value
else:
categorized['other'][var_name] = var_value
return categorized
def format_tokens_section(tokens_dict, title):
"""Format design tokens into markdown."""
if not tokens_dict:
return f"*No {title.lower()} tokens defined yet.*\n"
output = ""
for var_name, var_value in sorted(tokens_dict.items())[:20]: # Limit to 20
output += f"- `--{var_name}`: {var_value}\n"
if len(tokens_dict) > 20:
output += f"\n*...and {len(tokens_dict) - 20} more*\n"
return output
def generate_guidelines(root_path):
"""Generate guidelines based on detected patterns."""
guidelines = []
# Check for Tailwind
if (root_path / 'tailwind.config.js').exists() or (root_path / 'tailwind.config.ts').exists():
guidelines.append("""
### Tailwind CSS Usage
- **Prefer Tailwind utilities** over custom CSS where possible
- **Use @apply sparingly** - only for frequently repeated patterns
- **Extend the theme** in tailwind.config.js for custom values
- **Use arbitrary values** (e.g., `w-[123px]`) only when necessary
""")
# Check for CSS Modules
css_modules = list(root_path.rglob('*.module.css')) + list(root_path.rglob('*.module.scss'))
if css_modules:
guidelines.append("""
### CSS Modules
- **One module per component** - keep styles colocated
- **Use camelCase** for class names in modules
- **Avoid global styles** unless absolutely necessary
- **Compose classes** to avoid duplication
""")
# Default guidelines
guidelines.append("""
### General Principles
- **Mobile-first**: Design for mobile, enhance for desktop
- **Accessibility**: Ensure WCAG AA compliance minimum
- **Performance**: Optimize for fast loading and rendering
- **Consistency**: Use design tokens and established patterns
- **Dark mode**: Support both light and dark themes where applicable
""")
return "\n".join(guidelines)
def generate_markdown_styleguide(root_path):
"""Generate markdown style guide."""
project_name = detect_project_name(root_path)
date = datetime.now().strftime('%Y-%m-%d')
# Extract design tokens
tailwind_tokens = extract_design_tokens_from_tailwind(root_path)
css_vars = extract_css_variables(root_path)
categorized = categorize_css_variables(css_vars)
# Build sections
colors_section = format_tokens_section(categorized['colors'], 'Colors')
spacing_section = format_tokens_section(categorized['spacing'], 'Spacing')
typography_section = format_tokens_section(categorized['typography'], 'Typography')
if tailwind_tokens:
colors_section = f"**Using Tailwind CSS**\n\nSee `tailwind.config.js` for the complete color palette.\n\n{colors_section}"
components_section = """
### Button
*Component documentation to be added*
### Card
*Component documentation to be added*
### Form Elements
*Component documentation to be added*
*Add component documentation as your design system grows.*
"""
guidelines_section = generate_guidelines(root_path)
# Build full guide
styleguide = f"""# {project_name} Style Guide
**Last Updated**: {date}
*This is a living document that evolves with the project.*
---
## Overview
This style guide documents the design system, patterns, and conventions used in {project_name}.
## Design Tokens
Design tokens are the visual design atoms of the design system. They define colors, typography, spacing, and other fundamental values.
### Colors
{colors_section}
### Typography
{typography_section}
### Spacing
{spacing_section}
## Components
Document common component patterns here.
{components_section}
## Guidelines
{guidelines_section}
## Accessibility
### Color Contrast
- Ensure all text has minimum 4.5:1 contrast ratio (WCAG AA)
- Large text (18pt+) requires minimum 3:1 contrast ratio
### Focus States
- All interactive elements must have visible focus indicators
- Focus indicators must have 3:1 contrast ratio with background
### Keyboard Navigation
- All functionality available via keyboard
- Logical tab order
- Skip links for main content
## Performance
### CSS Best Practices
- Remove unused styles in production
- Use CSS containment for complex layouts
- Optimize font loading with `font-display: swap`
- Minimize use of expensive properties in animations
## Resources
- [Design System Documentation](./docs/design-system.md)
- [Component Library](./src/components/)
- [Accessibility Guidelines](https://www.w3.org/WAI/WCAG21/quickref/)
---
*Generated by Style Master on {date}*
"""
return styleguide
def main():
parser = argparse.ArgumentParser(
description='Generate project style guide',
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
'--path',
type=str,
default='.',
help='Path to project root (default: current directory)'
)
parser.add_argument(
'--output',
type=str,
default='STYLEGUIDE.md',
help='Output file path (default: STYLEGUIDE.md)'
)
parser.add_argument(
'--format',
choices=['markdown', 'json'],
default='markdown',
help='Output format (default: markdown)'
)
args = parser.parse_args()
root_path = Path(args.path).resolve()
if not root_path.exists():
print(f"[ERROR] Error: Path does not exist: {root_path}")
sys.exit(1)
print(f"[NOTE] Generating style guide for: {root_path}")
# Generate style guide
if args.format == 'markdown':
styleguide = generate_markdown_styleguide(root_path)
output_path = Path(args.output)
with open(output_path, 'w') as f:
f.write(styleguide)
print(f"[OK] Style guide created: {output_path}")
print(f"\n Review and customize the generated style guide")
print(f" Add component examples, update guidelines, refine tokens\n")
else:
# JSON format (for programmatic use)
css_vars = extract_css_variables(root_path)
categorized = categorize_css_variables(css_vars)
data = {
'project': detect_project_name(root_path),
'generated': datetime.now().isoformat(),
'tokens': categorized
}
output_path = Path(args.output).with_suffix('.json')
with open(output_path, 'w') as f:
json.dump(data, f, indent=2)
print(f"[OK] Style guide data exported: {output_path}")
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Style improvement suggester."""
import sys
from pathlib import Path
def analyze_and_suggest(root_path):
"""Analyze styles and suggest improvements."""
suggestions = []
# Check for modern CSS features
css_files = list(root_path.rglob('*.css'))
if css_files:
content = ''.join([f.read_text() for f in css_files[:10] if 'node_modules' not in str(f)])
if 'float:' in content:
suggestions.append("[TIP] Consider replacing float layouts with Flexbox or Grid")
if 'px' in content and 'rem' not in content:
suggestions.append("[TIP] Consider using rem units for better accessibility")
if '@media' in content and '@container' not in content:
suggestions.append("[TIP] Consider container queries for component-level responsiveness")
if not re.search(r'--[\w-]+:', content):
suggestions.append("[TIP] Consider using CSS custom properties for theming")
return suggestions
def main():
root = Path(sys.argv[1] if len(sys.argv) > 1 else '.').resolve()
print(" Analyzing for improvement opportunities...\n")
suggestions = analyze_and_suggest(root)
for s in suggestions:
print(f" {s}")
if not suggestions:
print(" [OK] No immediate improvements suggested!")
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""Style consistency validator - checks for design token adherence."""
import sys
from pathlib import Path
import re
from collections import Counter
def validate_colors(root_path):
"""Check for color consistency."""
colors = []
for css_file in root_path.rglob('*.css'):
if 'node_modules' not in str(css_file):
try:
content = css_file.read_text()
colors.extend(re.findall(r'#(?:[0-9a-fA-F]{3}){1,2}\b', content))
except: pass
counts = Counter(colors)
print(f" Colors: {len(counts)} unique colors found")
if len(counts) > 20:
print(f" [WARNING] Consider consolidating to a color system")
return counts
def main():
root = Path(sys.argv[1] if len(sys.argv) > 1 else '.').resolve()
print("[SEARCH] Validating style consistency...\n")
validate_colors(root)
print("\n[OK] Validation complete")
if __name__ == '__main__':
main()