-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path.cursorrules
More file actions
575 lines (479 loc) · 15.8 KB
/
Copy path.cursorrules
File metadata and controls
575 lines (479 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# Workout Tracker - Cursor Rules
## Project Overview
This is a workout and nutrition tracking application following the architecture and patterns from the Yumi codebase and Auctor dashboard styling. The application uses a monorepo structure with:
- **Web Frontend**: Next.js 15 with React 19, TypeScript, Tailwind CSS v4
- **Mobile App**: SwiftUI (iOS)
- **Backend**: Python FastAPI
- **Database**: Supabase (PostgreSQL)
---
## Design System (Auctor-Inspired)
### Color Palette
Use these CSS variables for consistent theming:
```css
:root {
/* Surfaces */
--background: 0 0% 98%; /* #FAFAFA */
--foreground: 0 0% 3.9%; /* #0A0A0A */
--card: 0 0% 100%; /* White */
/* Primary - Professional Purple */
--primary: 251 59% 52%; /* #573DCD */
--primary-light: 251 59% 94%; /* #EDEBFA */
--primary-foreground: 0 0% 100%;
/* Neutrals */
--muted: 0 0% 95%; /* #F5F5F5 */
--muted-foreground: 0 0% 45%; /* #737373 */
--border: 0 0% 90%; /* #E5E5E5 */
/* Semantic Status (Stoplight Pattern) */
--success: 142 76% 36%; /* Green */
--warning: 38 92% 50%; /* Yellow/Amber */
--destructive: 0 70% 50%; /* Red */
--info: 200 75% 55%; /* Blue */
/* Radius - Subtle rounding */
--radius: 0.625rem; /* 10px */
}
```
### Typography
- **Font**: Geist Sans (primary), fallback to system fonts
- **Base size**: 14px
- **Text hierarchy**:
- Primary text: `text-foreground`
- Secondary text: `text-muted-foreground`
- Labels: `text-xs font-medium`
- **No bold headers**: Use `font-medium` for emphasis
### Component Styling Rules
1. **Cards**: `rounded-md border bg-white` (not bg-card)
2. **Buttons**: `h-9 px-4` default, subtle hover states
3. **Inputs**: `h-9` height, `border-input` border
4. **Icons**: `size-4` (16px) standard, `stroke-[1.75]`
5. **Spacing**: Use p-2, p-4, p-6 consistently
6. **Transitions**: `transition-colors` (not `transition-all`)
7. **Focus rings**: `focus-visible:ring-2`
### Sidebar Guidelines
- Width: 16rem default, 3rem collapsed
- Background: Same as page background (#FAFAFA)
- Menu items: h-8, hover:bg-muted
- Collapsible with Cmd+B keyboard shortcut
- Use Zustand for sidebar state management
### Scrollbar Styling
```css
::-webkit-scrollbar { width: 2px; height: 2px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: hsl(var(--muted-foreground) / 0.15); }
```
### Empty States
```tsx
<div className="flex flex-col items-center justify-center gap-3 text-center">
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-muted text-muted-foreground">
<Icon className="h-6 w-6" />
</div>
<div className="text-base font-medium">{title}</div>
<div className="text-sm text-muted-foreground max-w-md">{description}</div>
</div>
```
---
## Architecture Rules
### Data Flow (CRITICAL)
1. Frontend MUST make API calls to backend for ALL data mutations
2. Frontend NEVER directly writes to Supabase database
3. Backend validates JWT tokens before any database operation
4. Frontend can use Supabase client ONLY for:
- Authentication (sign in/up/out)
- Real-time subscriptions (listening to changes)
- Storage (image uploads with proper RLS)
### File Structure
```
workout-tracker/
├── web/ # Next.js Web App
│ ├── app/ # App router pages
│ │ ├── (dashboard)/ # Protected dashboard routes
│ │ ├── api/ # Next.js API routes (proxies to backend)
│ │ └── auth/ # Auth callback routes
│ ├── components/ # React components
│ │ └── ui/ # Reusable UI primitives (shadcn/ui style)
│ ├── hooks/ # Custom React hooks
│ ├── lib/ # Utilities
│ │ ├── api-config.ts # Backend API configuration
│ │ ├── auth-context.tsx # Auth provider
│ │ ├── supabase/ # Supabase clients
│ │ └── utils.ts # Utility functions
│ └── public/ # Static assets
│
├── mobile/ # SwiftUI iOS App
│ └── WorkoutTracker/
│ ├── Models/ # Codable data models
│ ├── Views/ # SwiftUI views
│ ├── ViewModels/ # ObservableObject view models
│ ├── Services/ # Network, Auth, Cache services
│ └── Extensions/ # Swift extensions
│
├── backend/ # FastAPI Backend
│ ├── main.py # App entry point
│ ├── routers/ # API route handlers
│ ├── services/ # Business logic
│ ├── utils/ # Utilities (auth, helpers)
│ └── requirements.txt # Python dependencies
│
└── .cursor/ # Cursor AI context
└── context.md # Project documentation
```
---
## Code Style Rules
### TypeScript/React (Web Frontend)
1. **Use TypeScript strictly** - No `any` types unless absolutely necessary
2. **Prefer functional components** with hooks
3. **Use `'use client'`** directive for client components
4. **API calls pattern**:
```typescript
// lib/api-config.ts
export async function apiRequest<T>(endpoint: string, options?: RequestInit): Promise<T> {
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
...options,
headers: {
'Content-Type': 'application/json',
...options?.headers,
},
});
if (!response.ok) throw new Error('Request failed');
return response.json();
}
```
5. **Component file naming**: PascalCase (e.g., `WorkoutCard.tsx`)
6. **Hook naming**: camelCase with `use` prefix (e.g., `useWorkoutData.ts`)
### CSS/Styling (Auctor Pattern)
1. **Use Tailwind CSS** for all styling
2. **Follow Auctor color system** (see Design System section above)
3. **Component variants** with class-variance-authority (CVA):
```typescript
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-normal transition-colors disabled:opacity-50 [&_svg]:size-4",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
outline: "border border-input bg-background hover:bg-muted",
ghost: "text-foreground hover:text-primary",
icon: "bg-white hover:bg-white text-muted-foreground hover:text-primary",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 px-3",
icon: "h-9 w-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
);
```
4. **Auctor styling principles**:
- Use Geist font (or system fonts) - NOT Inter
- Subtle hover states (bg-muted, not dramatic colors)
- Minimal shadows, prefer borders
- 2px scrollbars, transparent track
- Icons at size-4 (16px) standard
- Text hierarchy: foreground > muted-foreground
- Consistent p-2, p-4, p-6 spacing
### Python (Backend)
1. **FastAPI router pattern**:
```python
router = APIRouter(prefix="/workouts", tags=["workouts"])
@router.post("/create")
async def create_workout(
user_id: str = Depends(get_user_id_from_token),
name: str = Form(...),
exercises: str = Form(...)
) -> dict:
"""Docstring explaining the endpoint."""
# Implementation
```
2. **Service pattern**:
```python
class WorkoutService:
_instance = None
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
async def create_workout(self, user_id: str, data: dict) -> dict:
# Business logic here
def get_workout_service() -> WorkoutService:
return WorkoutService.get_instance()
```
3. **Auth dependency**:
```python
async def get_user_id_from_token(
authorization: str = Header(...)
) -> str:
"""Extract and validate user ID from JWT token."""
token = authorization.replace("Bearer ", "")
# Validate with Supabase
return user_id
```
4. **Use type hints** everywhere
5. **Async/await** for all IO operations
### Swift (iOS)
1. **MVVM pattern**:
```swift
// ViewModel
@MainActor
class WorkoutViewModel: ObservableObject {
@Published var workouts: [Workout] = []
@Published var isLoading = false
@Published var error: String?
func loadWorkouts() async {
isLoading = true
defer { isLoading = false }
// Load data
}
}
```
2. **Singleton services**:
```swift
class NetworkService {
static let shared = NetworkService()
private let baseURL = "..."
private init() {}
func fetch<T: Codable>(endpoint: String, authToken: String) async throws -> T {
// Implementation
}
}
```
3. **Codable models**:
```swift
struct Workout: Codable, Identifiable {
let id: UUID
let name: String
let exercises: [Exercise]
let createdAt: Date
enum CodingKeys: String, CodingKey {
case id, name, exercises
case createdAt = "created_at"
}
}
```
4. **⚠️ CRITICAL: Adding Swift Files to Xcode Project**
When creating new Swift files for the mobile app, you MUST manually add them to `mobile/FitTrack.xcodeproj/project.pbxproj`. Without this, Xcode will show "Cannot find X in scope" errors even if the file exists on disk.
Steps to add a new Swift file:
1. **PBXFileReference section** - Add file reference with unique ID
2. **PBXBuildFile section** - Add build file linking to reference
3. **PBXGroup section** - Add file to appropriate folder group
4. **PBXSourcesBuildPhase section** - Add to compilation sources
Example for a new `MyView.swift`:
```pbxproj
/* PBXFileReference */
MYVIEWREF123456789AB /* MyView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MyView.swift; sourceTree = "<group>"; };
/* PBXBuildFile */
MYVIEWBLD987654321AB /* MyView.swift in Sources */ = {isa = PBXBuildFile; fileRef = MYVIEWREF123456789AB /* MyView.swift */; };
/* Add to appropriate PBXGroup's children array */
/* Add MYVIEWBLD987654321AB to PBXSourcesBuildPhase files array */
```
---
## UI/UX Guidelines
### Design Principles (Fitness App Best Practices)
1. **Minimalist interface** - Show only essential information
2. **Quick logging** - Reduce friction for common actions
3. **Visual progress** - Charts, graphs, streaks
4. **Personalization** - Customizable goals and preferences
5. **Bottom navigation** - Thumb-friendly on mobile
### Component Patterns
1. **Cards** for grouping related content:
```tsx
<Card className="p-4 rounded-2xl shadow-soft">
<CardHeader>
<CardTitle>Today's Workout</CardTitle>
</CardHeader>
<CardContent>
{/* Content */}
</CardContent>
</Card>
```
2. **Loading states** always:
```tsx
{isLoading ? (
<Skeleton className="h-32 w-full" />
) : (
<WorkoutList workouts={workouts} />
)}
```
3. **Empty states** with clear CTAs:
```tsx
{workouts.length === 0 && (
<EmptyState
icon={<Dumbbell />}
title="No workouts yet"
description="Start your fitness journey"
action={<Button>Create Workout</Button>}
/>
)}
```
### Animations
1. Use Framer Motion for React:
```tsx
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
{content}
</motion.div>
```
2. Use spring animations for natural feel:
```tsx
transition={{ type: "spring", stiffness: 300, damping: 30 }}
```
3. Stagger children for list animations:
```tsx
<motion.ul variants={container}>
{items.map((item, i) => (
<motion.li key={i} variants={child}>
{item}
</motion.li>
))}
</motion.ul>
```
---
## Security Rules
1. **Never expose secrets** in frontend code
2. **Validate all inputs** on backend
3. **Use Row Level Security (RLS)** in Supabase
4. **JWT tokens** must be validated on every API request
5. **Rate limiting** on API endpoints
6. **CORS configuration** - whitelist specific origins in production
---
## Database Guidelines
### Supabase Table Naming
- Use snake_case for table and column names
- Use plural for table names (e.g., `workouts`, `exercises`)
- Include `created_at` and `updated_at` timestamps
- Include `user_id` foreign key for user-owned data
### Example Schema
```sql
CREATE TABLE workouts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES auth.users(id) NOT NULL,
name TEXT NOT NULL,
description TEXT,
duration_minutes INTEGER,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
-- Enable RLS
ALTER TABLE workouts ENABLE ROW LEVEL SECURITY;
-- RLS Policy
CREATE POLICY "Users can only access their own workouts"
ON workouts FOR ALL
USING (auth.uid() = user_id);
```
---
## Testing Guidelines
1. **Backend**: Use pytest with async support
2. **Frontend**: Use Jest and React Testing Library
3. **E2E**: Consider Playwright for critical flows
4. **API testing**: Test files in `backend/test_*.py`
---
## Environment Variables
### Web Frontend (.env.local)
```
NEXT_PUBLIC_SUPABASE_URL=
NEXT_PUBLIC_SUPABASE_ANON_KEY=
NEXT_PUBLIC_API_BASE_URL=http://localhost:8000
```
### Backend (.env)
```
SUPABASE_URL=
SUPABASE_KEY=
ENVIRONMENT=development
API_HOST=0.0.0.0
API_PORT=8000
```
---
## Common Patterns to Follow
### API Response Format
```typescript
// Success
{ status: "success", data: {...} }
// Error
{ status: "error", message: "Error description", detail: "..." }
```
### Error Handling
```typescript
try {
const data = await apiRequest('/endpoint');
setData(data);
} catch (error) {
setError(error.message);
toast.error('Failed to load data');
}
```
### Form Handling
Use multipart/form-data for backend compatibility:
```typescript
const formData = new FormData();
formData.append('name', name);
formData.append('duration', duration.toString());
await fetch('/api/workouts', {
method: 'POST',
body: formData,
});
```
---
## Required Fitness Features
### Weight Management
- Daily weight logging with trend smoothing (7-day moving average)
- Goal weight with target date and weekly rate
- TDEE/BMR calculations
- Weight projection to goal
### Body Measurements
- Circumference tracking: chest, waist, hips, arms, thighs, neck
- Body fat percentage (manual entry)
- Waist-to-hip ratio
- Progress photos with date stamps
### Strength Training
- Progressive overload tracking
- 1RM calculator (Brzycki, Epley formulas)
- Volume tracking (sets × reps × weight)
- Exercise history with PR highlights
- Muscle group weekly volume
- RPE logging (1-10 scale)
- Rest timer with notifications
- Superset/circuit support
### Nutrition
- Macro goals: Protein, Carbs, Fat, Calories
- Timeline-based food log (not rigid meals)
- Food database search
- Quick-add manual entry
- Recipe builder
- Copy meals from previous days
### Gym Split Management
- Pre-built templates: PPL, Upper/Lower, Bro Split, Full Body
- Custom split creator
- Day assignment with rest day marking
- Active split indicator
### Analytics
- Weight trend charts with moving average
- Calorie/macro trend charts
- Exercise progress over time
- Workout frequency heat map
- Personal records list
- Weekly/monthly summaries
---
## Remember
1. ✅ Keep UI clean and minimal (Auctor style)
2. ✅ Frontend calls backend, backend calls database
3. ✅ Use TypeScript types everywhere
4. ✅ Handle loading and error states
5. ✅ Validate inputs on backend
6. ✅ Use async/await patterns
7. ✅ Follow Auctor styling patterns
8. ✅ Use Zustand for client state (sidebar, preferences)
9. ✅ **Test mobile builds in Simulator before finishing** - Run `xcodebuild` or open Xcode
10. ✅ **Add Swift files to project.pbxproj** - See Swift section above
11. ❌ Don't use inline styles
12. ❌ Don't skip error handling
13. ❌ Don't expose API keys in frontend
14. ❌ Don't use bold fonts - prefer font-medium
15. ❌ Don't use heavy shadows - prefer subtle borders
16. ❌ Don't create Swift files without adding to project.pbxproj