# React Component Analyzer

A powerful static analysis tool for React components that helps you understand dependencies, optimize state management, and automatically refactor prop drilling into React Context. Now with **folder-wide analysis** capabilities!

## 🚀 What's New in v2.0

- **📁 Folder Analysis**: Analyze entire component folders for comprehensive insights
- **🔍 Auto-Detection**: Automatically detects whether you're analyzing a component or folder
- **📊 Enhanced Metrics**: Folder-wide state management metrics and distribution analysis
- **🎯 Organization Suggestions**: Get recommendations for better folder structure and component organization
- **🔧 Cross-Component Patterns**: Identify prop drilling chains and shared state opportunities across multiple components
- **📈 Health Scoring**: Get an overall health score for your component folders

## Features

- **Dependency Analysis**: Visualize component dependencies and import relationships
- **State Management Analysis**: Analyze how state is managed across components and folders
- **Folder-Wide Insights**: Understand state patterns across entire component directories
- **Automatic Context Generation**: Convert prop drilling to Context API with one command
- **Advanced State Metrics**: Calculate cohesion, coupling, and other state quality metrics
- **Performance Recommendations**: Identify memoization opportunities and other optimizations
- **Refactoring Suggestions**: Get actionable advice for improving component architecture
- **Organization Analysis**: Get suggestions for better folder structure and component grouping

## Installation

```bash
# Install globally
npm install -g react-component-analyzer

# Or install as a development dependency in your project
npm install --save-dev react-component-analyzer

# Or use directly with npx (no installation required)
npx react-component-analyzer MyComponent
```

## Usage

### 🔍 Component Analysis

Analyze individual React components:

```bash
# Basic component analysis
react-analyzer ComponentName

# Advanced component analysis with metrics
react-analyzer ComponentName --advanced-state

# Full component analysis (all features)
react-analyzer ComponentName --full

# Generate HTML dependency report
react-analyzer ComponentName --html

# Create Context and Provider
react-analyzer ComponentName --create-context
```

### 📁 Folder Analysis (NEW)

Analyze entire folders containing React components:

```bash
# Basic folder analysis (auto-detected)
react-analyzer ./src/components

# Advanced folder analysis with metrics
react-analyzer ./src/components --folder-state --metrics

# Full folder analysis with all features
react-analyzer ./src/components --full

# Analyze specific feature folders
react-analyzer ./src/features/dashboard --advanced-state

# Console-only analysis (great for CI/CD)
react-analyzer ./src/components --console-only --metrics
```

### 🎛️ Advanced Options

```bash
# Force analysis type (when auto-detection is unclear)
react-analyzer ./src --type folder
react-analyzer MyComponent --type component

# Non-recursive folder analysis (only direct children)
react-analyzer ./src/components --no-recursive

# Include test files in folder analysis
react-analyzer ./src/components --include-tests

# Custom output directory
react-analyzer ./src/components --output-dir ./analysis-reports

# Generate runtime instrumentation for performance tracking
react-analyzer ./src/components --runtime-capture

# Get refactoring suggestions
react-analyzer ./src/components --refactor
```

## 📊 What You Get

### Component Analysis Output
- `ComponentName-dependencies.html` - Interactive dependency visualization
- `ComponentName-state-analysis.html` - State management analysis
- `ComponentName-refactoring-plan.html` - Suggested refactorings
- `generated-context/ComponentNameContext.js` - Generated context provider

### Folder Analysis Output  
- `folder-name-state-analysis.html` - Comprehensive folder analysis with:
  - **📁 Folder Structure Analysis**: File organization, naming consistency, co-location patterns
  - **📊 State Distribution**: Component complexity categorization and pattern usage
  - **🔗 Component Relationships**: Prop drilling chains and shared state opportunities
  - **🎯 Organization Suggestions**: Folder structure improvements and component grouping
  - **⚡ Performance Insights**: Memoization opportunities and optimization recommendations
  - **📈 Health Score**: Overall folder health assessment

## Configuration

By default, the analyzer looks for React components in the `src` directory of your project. You can modify this and other settings by creating a `.react-analyzer.json` file in your project root:

```json
{
  "rootDir": "src",
  "testDir": "tests",
  "fileExtensions": ["tsx", "jsx", "ts", "js"],
  "aliasPatterns": {
    "@/components": "src/components",
    "@/": "src/"
  },
  "folderAnalysis": {
    "includeTests": false,
    "recursive": true,
    "maxDepth": 5,
    "healthThresholds": {
      "excellent": 90,
      "good": 80,
      "fair": 70,
      "poor": 60
    }
  }
}
```

## CLI Options

| Option | Alias | Description |
|--------|-------|-------------|
| `--html` | `-h` | Generate HTML dependency report (components only) |
| `--cruiser` | `-c` | Generate dependency-cruiser report (components only) |
| `--state` | `-s` | Analyze state management (basic) |
| `--advanced-state` | `-as` | Run advanced state analysis with metrics |
| `--folder-state` | `-fs` | Run folder-wide state analysis (auto-detected for folders) |
| `--create-context` | `-cc` | Create Context and Provider (components only) |
| `--full` | `-f` | Run all analyses |
| `--type` | | Force analysis type: `component`, `folder`, `auto` (default: auto) |
| `--output` | `-o` | Specify output path for reports |
| `--output-dir` | | Specify output directory for all reports |
| `--console-only` | | Output to console only, no HTML reports |
| `--no-recursive` | | Don't analyze folders recursively |
| `--include-tests` | | Include test files in folder analysis |
| `--metrics` | | Calculate advanced state metrics |
| `--refactor` | | Generate refactoring suggestions |
| `--runtime-capture` | | Generate runtime state capture instrumentation |

## Examples

### 🔍 Component Analysis Examples

#### Creating Context for a Component with Prop Drilling

```bash
react-analyzer ProductList --create-context
```

This will generate:
- `./generated-context/ProductListContext.js` - The context and provider implementation
- `./generated-context/ProductListWithContext.example.js` - Example usage of the context

#### Analyzing State Management in a Complex Component

```bash
react-analyzer Dashboard --advanced-state --metrics --refactor
```

This will generate detailed metrics and suggestions for state management optimization.

### 📁 Folder Analysis Examples

#### Analyzing Your Components Folder

```bash
react-analyzer ./src/components --full
```

This will:
- ✅ Analyze all React components in the folder
- 📊 Generate folder-wide state management insights
- 🎯 Provide organization suggestions
- 📈 Calculate a health score for the folder
- 🔧 Suggest refactoring opportunities

#### Feature-Specific Analysis

```bash
react-analyzer ./src/features/authentication --folder-state --metrics
```

Perfect for:
- 🔍 Feature health checks before releases
- 📊 Understanding state complexity in specific features
- 🎯 Identifying cross-component optimization opportunities

#### Quick Health Check (Great for CI/CD)

```bash
react-analyzer ./src/components --console-only --metrics
```

Output example:
```
📊 STATE MANAGEMENT SUMMARY:
   - Analysis scope: folder
   - Files analyzed: 12
   - Components analyzed: 12
   - Components using local state (useState): 8
   - Components using reducers (useReducer): 2

📁 FOLDER-SPECIFIC INSIGHTS:
   - Complex stateful components: 2
   - Moderate complexity components: 4
   - Simple components: 6
   - Folder health score: 85% (Good)

🔍 RECOMMENDATIONS:
   1. Consider consolidating related state across components
   2. 3 components have memoization opportunities
```

### 🏢 Real-World Scenarios

#### Pre-Refactoring Analysis
```bash
# Before refactoring - establish baseline
react-analyzer ./src/legacy-components --full --output-dir ./pre-refactor

# After refactoring - compare improvements
react-analyzer ./src/components --full --output-dir ./post-refactor
```

#### Code Review Preparation
```bash
# Analyze new feature before PR
react-analyzer ./src/features/new-feature --console-only --metrics

# Include analysis in PR description
```

#### CI/CD Integration
```bash
# GitHub Actions / CI pipeline
react-analyzer ./src --console-only --metrics
if [ $? -ne 0 ]; then
  echo "❌ State management issues found!"
  exit 1
fi
```

## 📈 Understanding the Results

### Folder Health Score Guide
- **90-100%**: 🟢 Excellent - Well organized, minimal issues
- **80-89%**: 🟡 Good - Minor improvements needed  
- **70-79%**: 🟠 Fair - Some refactoring recommended
- **60-69%**: 🔴 Needs Improvement - Multiple issues found
- **<60%**: 🚨 Critical - Significant refactoring needed

### Component Complexity Categories
- **Simple (0-2 state vars)**: 🟢 Lightweight, easy to maintain
- **Moderate (3-5 state vars)**: 🟡 Well-structured, watch complexity
- **Complex (6+ state vars)**: 🟠 Consider splitting or using reducers

### Key Metrics to Monitor
- **Naming Consistency**: Aim for 80%+ consistency across files
- **State Distribution**: Avoid heavy concentration in few components  
- **Prop Drilling Depth**: Keep under 3 levels deep
- **Cross-Component Patterns**: Look for opportunities to share state

## 🔄 Migration from v1.x

All existing commands continue to work! v2.0 is fully backward compatible:

```bash
# v1.x commands still work exactly the same
react-analyzer MyComponent --full
react-analyzer Header --html  
react-analyzer Dashboard --create-context

# Plus new v2.0 folder analysis capabilities
react-analyzer ./src/components --folder-state
```

## 🚀 Use Cases

- **🔍 Code Reviews**: Analyze new features before merging
- **📊 Health Monitoring**: Regular checks of component folder health
- **🔧 Refactoring**: Identify improvement opportunities before major refactors
- **📈 Performance**: Find memoization and optimization opportunities
- **🎯 Architecture**: Get suggestions for better component organization
- **🏢 Team Standards**: Ensure consistent state management patterns across teams

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

**Ready to analyze your React codebase?** 🚀

```bash
npx react-component-analyzer ./src/components --full
```