# Components 46-47: Quick Reference Guide

## 🎯 What Was Implemented

### Loading States (Component 46)
- ✅ Skeleton loaders with shimmer animation
- ✅ Progress indicators (linear & circular)
- ✅ Loading dots for indeterminate states
- ✅ Loading state wrapper component

### Error Recovery (Component 47)
- ✅ Error type system in WebSocketService
- ✅ Error recovery modal UI
- ✅ Error banner for non-critical errors
- ✅ Retry handler with exponential backoff
- ✅ View modifiers for easy integration

---

## 📁 File Structure

```
lichunWebsocket/
└── Shared/
    ├── Components/
    │   ├── Indicators/
    │   │   ├── SkeletonView.swift          ✨ NEW
    │   │   └── ProgressLoadingView.swift   ✨ NEW
    │   └── Overlays/
    │       └── ErrorRecoveryView.swift     ✨ NEW
    ├── Extensions/
    │   └── View+LoadingError.swift         ✨ NEW
    └── Utilities/
        └── RetryHandler.swift              ✨ NEW

WebSocketService.swift                      🔧 MODIFIED
```

---

## 🚀 Quick Start

### 1. Global Error Handling (Add to ContentView)
```swift
.errorOverlay(error: $webSocketService.currentError) {
    webSocketService.reconnect()
}
```

### 2. Skeleton Loading (For lists)
```swift
LoadingStateView(isLoading: isLoading, skeletonCount: 5) {
    ForEach(items) { item in
        ItemView(item: item)
    }
}
```

### 3. Progress Loading (For uploads)
```swift
.progressLoading(isUploading, message: "Uploading...", progress: $progress)
```

### 4. Simple Loading (For single operations)
```swift
.loading(isLoading, message: "Loading...")
```

### 5. Error Banner (Non-critical errors)
```swift
.errorBanner(error: $currentError, autoDismiss: true)
```

---

## 🎨 Component Showcase

### SkeletonView Components

```
┌─────────────────────────────────┐
│  SkeletonView                   │  Base shimmer rectangle
│  ▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░     │  ← Animated shimmer
└─────────────────────────────────┘

┌─────────────────────────────────┐
│  SkeletonAvatar                 │
│   ⬤ ▓▓▓▓▓░░░                    │  Circular avatar
└─────────────────────────────────┘

┌─────────────────────────────────┐
│  SkeletonListItem               │
│  ⬤  ▓▓▓▓▓▓▓▓░░                  │  Avatar + text lines
│     ▓▓▓▓░░                      │
└─────────────────────────────────┘

┌─────────────────────────────────┐
│  SkeletonCard                   │
│  ▓▓▓▓▓▓░░ (title)              │  Full card layout
│  ▓▓▓▓▓▓▓▓▓▓▓▓░ (line 1)       │
│  ▓▓▓▓▓▓▓▓░ (line 2)            │
│  ▓▓▓░  ▓▓▓▓░ (footer)          │
└─────────────────────────────────┘
```

### Progress Components

```
┌─────────────────────────────────┐
│  ProgressLoadingView            │
│  ████████░░░░░░░░░░░░░░  65%   │  Linear progress
│  Uploading character...         │
└─────────────────────────────────┘

     CircularProgressView
        ╭───────╮
       ╱  75%    ╲       Circular progress
      │   ◜◝     │
       ╲        ╱
        ╰───────╯

    LoadingDots
      ● ○ ○              Animated dots
```

### Error Components

```
┌─────────────────────────────────┐
│  ErrorRecoveryView              │
│                                 │
│         ⚠️                      │  Error icon
│                                 │
│         Oops!                   │  Title
│                                 │
│  Lost connection to server.     │  Message
│  Trying to reconnect...         │
│                                 │
│  ┌─────────┐  ┌──────────┐    │
│  │ Dismiss │  │Try Again │    │  Actions
│  └─────────┘  └──────────┘    │
└─────────────────────────────────┘

┌─────────────────────────────────┐
│ ⚠️ Connection lost. Retrying... ✕│  Error banner
└─────────────────────────────────┘
```

---

## 🔌 Error Types

```swift
enum WebSocketError {
    case connectionLost              // 📡 Network issues
    case serverError(message)        // ⚠️ Server problems
    case insufficientResources(...)  // 💰 Not enough resources
    case invalidOperation(message)   // 🚫 Invalid action
    case timeout                     // ⏱️ Request timeout
}
```

### Error Properties

| Error Type | Icon | Color | Retryable | Use Case |
|-----------|------|-------|-----------|----------|
| connectionLost | wifi.slash | ⚠️ Warning | ✅ Yes | Network disconnected |
| serverError | exclamationmark.triangle | ❌ Error | ✅ Yes | Server issues |
| insufficientResources | xmark.circle | ⚠️ Warning | ❌ No | Not enough money/energy |
| invalidOperation | hand.raised | ❌ Error | ❌ No | Invalid action attempted |
| timeout | exclamationmark.triangle | ❌ Error | ✅ Yes | Request took too long |

---

## 🔄 Retry Handler

```swift
// Async/await version
try await RetryHandler.shared.retry(
    maxAttempts: 3,
    initialDelay: 1.0,
    maxDelay: 10.0
) {
    try await yourAsyncOperation()
}

// Callback version
RetryHandler.shared.retry(maxAttempts: 3) { completion in
    yourOperation { result in
        completion(result)
    }
} completion: { result in
    // Handle result
}
```

### Exponential Backoff
```
Attempt 1: Wait 1.0s
Attempt 2: Wait 2.0s
Attempt 3: Wait 4.0s
Attempt 4: Wait 8.0s
Attempt 5: Wait 10.0s (capped at maxDelay)
```

---

## 🎭 View Modifiers Cheat Sheet

| Modifier | Purpose | Auto-Dismiss | Blocks UI |
|----------|---------|--------------|-----------|
| `.loading()` | Full-screen loading | ❌ No | ✅ Yes |
| `.errorOverlay()` | Critical errors | ❌ No | ✅ Yes |
| `.errorBanner()` | Minor errors | ✅ Yes (3s) | ❌ No |
| `.progressLoading()` | Tracked progress | ❌ No | ✅ Yes |
| `.skeleton()` | Loading state | ❌ No | ❌ No |

---

## 🎬 Animation Timings

```swift
// Skeleton shimmer
.linear(duration: 1.5).repeatForever()

// Error overlay
.spring(response: 0.4, dampingFraction: 0.8)

// Loading dots
.easeInOut(duration: 0.3)

// Loading overlay
.easeInOut
```

---

## 📊 Server Error Format

Server should send errors like this:

```json
{
    "type": "error",
    "error_code": "INSUFFICIENT_ENERGY",
    "message": "Not enough energy",
    "required": 50,
    "available": 20
}
```

### Supported Error Codes
- `INSUFFICIENT_ENERGY`
- `INSUFFICIENT_MONEY`
- `INSUFFICIENT_DIAMONDS`
- `SERVER_ERROR`
- `INVALID_OPERATION`
- `TIMEOUT`

---

## 🎯 Common Patterns

### Pattern 1: List with Loading
```swift
LoadingStateView(isLoading: isLoading) {
    List(items) { item in
        ItemRow(item)
    }
}
```

### Pattern 2: Button with Loading
```swift
PrimaryButton(
    title: "Submit",
    action: submit,
    isLoading: isSubmitting
)
```

### Pattern 3: View with Error
```swift
MyView()
    .errorOverlay(error: $error) {
        retryAction()
    }
```

### Pattern 4: Upload with Progress
```swift
UploadView()
    .progressLoading(
        isUploading,
        message: "Uploading...",
        progress: $uploadProgress
    )
```

---

## ✅ Integration Checklist

- [ ] Add `.errorOverlay()` to ContentView
- [ ] Replace loading states with `LoadingStateView`
- [ ] Use `.progressLoading()` for uploads
- [ ] Add `.errorBanner()` to transient error views
- [ ] Test error scenarios (disconnect, insufficient resources)
- [ ] Verify skeleton loaders appear correctly
- [ ] Check retry mechanisms work
- [ ] Test auto-dismiss on banners

---

## 🐛 Troubleshooting

### Skeleton not animating?
- Check that `onAppear` is being called
- Verify `isAnimating` state is toggling

### Error overlay not showing?
- Ensure `currentError` is being set in WebSocketService
- Check that error binding is correct: `$webSocketService.currentError`

### Retry not working?
- Verify `onRetry` closure is provided
- Check that error `isRetryable == true`

### Progress not updating?
- Ensure progress binding is correct
- Verify progress value is between 0.0 and 1.0

---

## 📚 Design System Usage

### Colors
```swift
AppColors.primary       // Primary actions
AppColors.error         // Error states
AppColors.warning       // Warnings
AppColors.success       // Success states
AppColors.cardBackground // Card backgrounds
```

### Typography
```swift
.font(.appLargeTitle)   // Large titles
.font(.appHeadline)     // Headlines
.font(.appBody)         // Body text
.font(.appCaption)      // Captions
```

### Spacing
```swift
AppSpacing.xs    // 4pt
AppSpacing.sm    // 8pt
AppSpacing.md    // 16pt
AppSpacing.lg    // 24pt
AppSpacing.xl    // 32pt
```

---

## 🎓 Best Practices

1. **Use skeleton loaders** for perceived performance
2. **Show progress** for operations > 2 seconds
3. **Use error banners** for non-critical errors
4. **Use error overlays** for critical errors
5. **Always provide retry** for network errors
6. **Auto-dismiss** transient error banners
7. **Clear errors** when user dismisses
8. **Test offline** scenarios regularly

---

## 📈 Performance Tips

- ✅ Skeleton views are lightweight (simple shapes)
- ✅ Animations are GPU-accelerated
- ✅ Error state uses minimal memory
- ✅ Retry handler uses exponential backoff
- ✅ View modifiers conditionally render

---

## 🎉 You're Ready!

All components are production-ready. Start integrating them into your views and enjoy better UX!

**Need help?** Check:
- `IMPLEMENTATION_REPORT_COMPONENTS_46-47.md` - Full implementation details
- `INTEGRATION_EXAMPLES.swift` - Code examples
- Preview providers in each component file - Visual examples

---

**Components 46-47 Implementation**
**Status:** ✅ Complete & Production Ready
**Date:** 2025-11-12
