# Storybook Documentation

## Overview

This Storybook instance documents all UI components used in the Lilith web platform. It provides interactive examples, API documentation, and usage guidelines for developers.

## Running Storybook

```bash
# Development mode
npm run storybook

# Build static documentation
npm run build-storybook
```

Storybook will be available at http://localhost:6006

## Component Categories

### UI Components (Shadcn)
Located in `src/components/ui/`:
- **button** - Versatile button component with multiple variants
- **card** - Container component with header, content, and footer
- **input** - Form input fields
- **alert** - Notification and alert messages
- **badge** - Status indicators and labels
- **tabs** - Tabbed navigation component
- **progress** - Progress indicators
- **textarea** - Multi-line text input
- **select** - Dropdown selection
- **switch** - Toggle switches
- **separator** - Visual dividers
- **scroll-area** - Scrollable containers
- **avatar** - User avatar display
- **table** - Data tables
- **radio-group** - Radio button groups
- **checkbox** - Checkbox inputs
- **dialog** - Modal dialogs
- **dropdown-menu** - Dropdown menus
- **label** - Form labels

### Composite Components
Located in `src/components/`:
- **SyncIndicator** - PWA sync status indicator
- **ChatInterface** - Real-time chat component
- **AudioPlayer** - Audio playback controls
- **PersonaSelector** - Avatar/persona selection
- **LanguageSwitcher** - Internationalization controls
- **ProgressTracker** - User progress visualization
- **WalletButton** - Web3 wallet connection
- **InstallPrompt** - PWA installation prompt
- And many more...

## Story Structure

Each component follows this structure:

```typescript
import type { Meta, StoryObj } from '@storybook/react';
import { Component } from './component';

const meta = {
  title: 'Category/ComponentName',
  component: Component,
  parameters: {
    layout: 'centered',
  },
  tags: ['autodocs'],
  argTypes: {
    // Control definitions
  },
} satisfies Meta<typeof Component>;

export default meta;
type Story = StoryObj<typeof meta>;

// Individual stories
export const Default: Story = {
  args: {
    // Default props
  },
};
```

## Best Practices

### 1. Comprehensive Coverage
- Include all prop variations
- Show common use cases
- Demonstrate edge cases
- Provide interactive examples

### 2. Documentation
- Use JSDoc comments for component descriptions
- Document all props with clear descriptions
- Include usage examples in stories
- Show composition patterns

### 3. Organization
- Group related components by category
- Use consistent naming conventions
- Keep stories focused and simple
- Provide "All Variants" examples

### 4. Interactivity
- Use controls for dynamic props
- Include action handlers
- Show state changes
- Demonstrate user interactions

## Adding New Stories

1. Create a `.stories.tsx` file next to your component
2. Follow the structure shown above
3. Add multiple story variants
4. Document props with argTypes
5. Include interactive examples

Example:
```typescript
// src/components/ui/new-component.stories.tsx
import type { Meta, StoryObj } from '@storybook/react';
import { NewComponent } from './new-component';

const meta = {
  title: 'UI/NewComponent',
  component: NewComponent,
  tags: ['autodocs'],
} satisfies Meta<typeof NewComponent>;

export default meta;
type Story = StoryObj<typeof meta>;

export const Default: Story = {
  args: {
    // Props
  },
};
```

## Autodocs

Storybook automatically generates API documentation from:
- TypeScript types
- PropTypes
- JSDoc comments
- ArgTypes definitions

Enable autodocs by adding `tags: ['autodocs']` to your meta configuration.

## Addons

Installed addons:
- **@storybook/addon-essentials** - Core functionality (docs, controls, actions, viewport, backgrounds)
- **@storybook/addon-interactions** - User interaction testing
- **@storybook/addon-links** - Navigation between stories

## Configuration

### Main Config (.storybook/main.ts)
- Story file locations
- Addon configuration
- Framework settings
- Webpack customization

### Preview Config (.storybook/preview.ts)
- Global parameters
- Decorators
- Theme configuration
- Global styles

## Visual Regression Testing with Chromatic

Chromatic provides automated visual regression testing for Storybook components.

### Setup

Chromatic is already installed and configured. To set up a new Chromatic project:

1. **Create Chromatic Account**
   - Visit [chromatic.com](https://www.chromatic.com/)
   - Sign up with your GitHub account
   - Create a new project for the Lilith repository

2. **Get Project Token**
   - In Chromatic dashboard, go to Project Settings
   - Copy the project token
   - Add to GitHub repository secrets as `CHROMATIC_PROJECT_TOKEN`

3. **Local Testing**
   ```bash
   # Set your project token
   export CHROMATIC_PROJECT_TOKEN=demo
   # Replace "demo" with your Chromatic token when running locally

   # Run Chromatic
   npm run chromatic
   ```

### How It Works

1. **Automatic Runs on PR**
   - GitHub Action runs Chromatic on every pull request
   - Takes screenshots of all Storybook stories
   - Compares with baseline (main/master branch)
   - Reports visual changes

2. **Review Process**
   - Visit Chromatic build link in PR comment
   - Review detected changes
   - Accept intentional changes (updates baseline)
   - Fix unintended regressions

3. **CI/CD Integration**
   - Runs on: PR creation, PR updates, main/master pushes
   - Auto-accepts changes on main/master branch
   - Uses TurboSnap for faster builds
   - Only tests changed components

### Scripts

```bash
# Run Chromatic manually
npm run chromatic

# Run in CI mode (doesn't fail on changes)
npm run chromatic:ci
```

### Best Practices

1. **Baseline Management**
   - Main/master branch is the baseline
   - Changes are auto-accepted when merged
   - Keep baseline up to date

2. **Reviewing Changes**
   - Always review visual changes in Chromatic UI
   - Check responsive breakpoints
   - Verify dark mode if applicable
   - Test interactive states

3. **Handling Changes**
   - **Accept**: If change is intentional (feature, design update)
   - **Deny**: If change is unintended regression
   - **Comment**: For unclear changes needing discussion

4. **Performance**
   - TurboSnap only tests changed stories
   - Reduces build time on large projects
   - Full builds run on main/master

### Workflow

1. Make component changes
2. Test locally with Storybook
3. Create pull request
4. Chromatic runs automatically
5. Review changes in Chromatic dashboard
6. Accept or fix changes
7. Merge when approved

### Troubleshooting

**Build Failures:**
- Check Storybook builds locally: `npm run build-storybook`
- Fix TypeScript/lint errors first
- Verify all stories render without errors

**Missing Screenshots:**
- Ensure stories are properly exported
- Check story file naming (*.stories.tsx)
- Verify Storybook config includes story paths

**False Positives:**
- Ignore specific stories in Chromatic config
- Use viewport settings for consistency
- Check for dynamic content (dates, randomness)

### Configuration

See `.github/workflows/chromatic.yml` for GitHub Action configuration.

### Resources

- [Chromatic Documentation](https://www.chromatic.com/docs/)
- [Visual Testing Guide](https://www.chromatic.com/docs/test)
- [GitHub Action](https://www.chromatic.com/docs/github-actions)

## Contributing

When adding new components:
1. Create comprehensive stories
2. Document all props
3. Include interactive examples
4. Test in Storybook dev mode
5. Build to verify no errors

## Resources

- [Storybook Documentation](https://storybook.js.org/docs)
- [Shadcn UI](https://ui.shadcn.com)
- [Radix UI](https://www.radix-ui.com)
