-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.cursorrules
More file actions
481 lines (381 loc) · 11.2 KB
/
Copy pathexample.cursorrules
File metadata and controls
481 lines (381 loc) · 11.2 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
# AI-Assisted Development Guidelines
# Copy this to your project root as .cursorrules
## Core Principles
This project is built with AI assistance. These rules ensure consistent, maintainable code across all contributions.
---
## ARCHITECTURE RULES
### 1. Folder Organization
Code is organized by **business feature**, not technical layer:
```
src/
├── pages/ # Full page components (one per route)
├── components/ # Reusable UI components
│ ├── student/ # Student-specific components
│ ├── trainer/ # Trainer-specific components
│ ├── admin/ # Admin-specific components
│ └── ui/ # Base UI components (shadcn/ui)
├── hooks/ # Custom React hooks (business logic only)
│ ├── student/ # Student-specific hooks
│ ├── trainer/ # Trainer-specific hooks
│ └── admin/ # Admin-specific hooks
├── services/ # Non-React utilities and helpers
├── types/ # TypeScript type definitions
├── contexts/ # React Context for global state
└── App.tsx # Main app component
```
### 2. Layer Responsibilities
**Pages (src/pages/)**
- One component per route
- Orchestrates child components
- Calls hooks to fetch data
- Provides data to components
**Components (src/components/)**
- Renders JSX ONLY
- No business logic
- No Supabase calls
- No data fetching
- Receives data via props
- Emits events via callbacks
- Keep under 150 lines
**Hooks (src/hooks/)**
- Manages state and side effects
- Fetches data via services
- Returns { data, loading, error }
- Never calls components
- Never imports UI components
- Keep under 100 lines
- ALWAYS starts with "use" prefix
**Services (src/services/)**
- Wraps Supabase calls
- Contains utilities and calculations
- No React imports
- Export plain functions
- Handle all error checking
**Types (src/types/)**
- All TypeScript definitions
- Organized by feature
- Include documentation
- Export all shared types
**Contexts (src/contexts/)**
- Global state ONLY (auth, user, settings)
- Max 3-4 contexts total
- No feature-specific data
- Provide custom hooks to access (e.g., useAuth)
---
## NAMING CONVENTIONS
### Components
- PascalCase: `StudentDashboard.tsx`
- Descriptive name matching purpose
- One component per file
### Hooks
- camelCase starting with "use": `useStudentCourses.ts`
- Describe what data/logic they manage
- One hook per file
### Services
- camelCase: `courseService.ts`
- Descriptive of domain
- Can have multiple functions in one file
### Types/Interfaces
- PascalCase: `Student.types.ts`
- Descriptive of data model
- Export all types from one file per domain
### Variables & Functions
- camelCase: `getStudentCourses()`, `studentName`
- Descriptive of content
- Constants in UPPER_SNAKE_CASE: `MAX_RETRIES = 3`
---
## REACT COMPONENT GUIDELINES
### Component Structure
```typescript
import { useEffect, useState } from 'react';
import type { ComponentProps } from '@/types/Component.types';
import { useCustomHook } from '@/hooks/useCustomHook';
import { ChildComponent } from '@/components/ChildComponent';
interface MyComponentProps {
title: string;
count: number;
onAction: (id: string) => void;
}
export function MyComponent({ title, count, onAction }: MyComponentProps) {
const [localState, setLocalState] = useState(false);
const handleClick = () => {
setLocalState(!localState);
onAction('id');
};
return (
<div className="flex gap-4">
<h1>{title}</h1>
<button onClick={handleClick}>Click me</button>
<ChildComponent data={count} />
</div>
);
}
```
### Rules
- ✅ Always define props interface
- ✅ Keep components small (50-150 lines max)
- ✅ Use destructuring for props
- ✅ Extract complex logic to hooks
- ✅ Use TypeScript types everywhere
- ❌ Never call Supabase directly
- ❌ Never put business logic in components
- ❌ Never import hooks in other hooks
- ❌ Never use `any` type
---
## CUSTOM HOOKS GUIDELINES
### Hook Structure
```typescript
import { useEffect, useState } from 'react';
import type { MyData } from '@/types/MyData.types';
import { myService } from '@/services/myService';
interface UseMyDataReturn {
data: MyData[] | null;
loading: boolean;
error: string | null;
refetch: () => Promise<void>;
}
/**
* Fetches user's data from the database
* @returns Object with data, loading, error, and refetch function
*/
export function useMyData(): UseMyDataReturn {
const [data, setData] = useState<MyData[] | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchData = async () => {
try {
setLoading(true);
setError(null);
const result = await myService.getData();
setData(result);
} catch (err) {
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData();
}, []);
return { data, loading, error, refetch: fetchData };
}
```
### Rules
- ✅ Always return { data, loading, error }
- ✅ Always include refetch function
- ✅ Always handle errors
- ✅ Add JSDoc comments
- ✅ Keep under 100 lines
- ✅ Use TypeScript for return type
- ❌ Never import components
- ❌ Never import other hooks
- ❌ Never call Supabase directly (use services)
---
## SERVICE LAYER GUIDELINES
### Service Structure
```typescript
import { supabase } from '@/lib/supabase';
import type { Course } from '@/types/Course.types';
export const courseService = {
async getCourses(): Promise<Course[]> {
const { data, error } = await supabase
.from('courses')
.select('*');
if (error) throw new Error(error.message);
return data || [];
},
async createCourse(course: Omit<Course, 'id' | 'created_at'>): Promise<Course> {
const { data, error } = await supabase
.from('courses')
.insert([course])
.select()
.single();
if (error) throw new Error(error.message);
return data;
},
};
```
### Rules
- ✅ Export object with named functions
- ✅ Always handle Supabase errors
- ✅ Always use typed return values
- ✅ All Supabase calls go here
- ❌ No React imports
- ❌ No component imports
- ❌ No logic that belongs in hooks
---
## TYPE SAFETY RULES
### Always Define Types
```typescript
// ❌ WRONG
function getData(data: any): any {
return data.value;
}
// ✅ CORRECT
interface DataInput {
value: string;
count: number;
}
interface DataOutput {
result: string;
}
function getData(data: DataInput): DataOutput {
return { result: data.value };
}
```
### Rules
- ✅ Every parameter has a type
- ✅ Every return value has a type
- ✅ Every prop has an interface
- ✅ Never use `any`
- ✅ Use `unknown` if truly unknown
- ✅ Export types for reuse
---
## ERROR HANDLING RULES
### Always Handle Errors
```typescript
// ❌ WRONG - No error handling
const [data, setData] = useState();
useEffect(() => {
supabase.from('table').select().then(data => setData(data));
}, []);
// ✅ CORRECT - Full error handling
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const fetch = async () => {
try {
const result = await myService.getData();
setData(result);
} catch (err) {
setError(err.message);
}
};
fetch();
}, []);
```
### Rules
- ✅ Try/catch in all async operations
- ✅ Return error state from hooks
- ✅ Show user-friendly messages
- ✅ Log errors for debugging
- ✅ Never silently fail
---
## IMPORT ORGANIZATION
### Import Order
```typescript
// 1. React and external libraries
import { useEffect, useState } from 'react';
// 2. Types
import type { Student } from '@/types/Student.types';
// 3. Hooks
import { useStudentData } from '@/hooks/student/useStudentData';
// 4. Services
import { studentService } from '@/services/studentService';
// 5. Components
import { StudentCard } from '@/components/student/StudentCard';
// 6. UI components
import { Button } from '@/components/ui/button';
```
### Rules
- ✅ Use absolute imports (@/...)
- ✅ Never use relative imports (../../../)
- ✅ Group by category
- ✅ Use `type` keyword for types
- ✅ Organize alphabetically within groups
---
## CODE STYLE RULES
### General
- Use `const` by default, `let` if reassigned, never `var`
- Use arrow functions: `() => {}`
- Use template literals: `` `Hello ${name}` ``
- Use object destructuring: `{ name, email } = user`
- Use array destructuring: `const [count, setCount] = useState(0)`
### React Specific
- Use functional components only
- Use hooks for state management
- Use React.memo for expensive components
- Use useCallback for stable function references
- Never use inline functions in JSX (unless simple handler)
### TypeScript Specific
- Use `interface` for object shapes
- Use `type` for unions and primitives
- Use `satisfies` for type safety without casting
- Always add return types to functions
- Use `Omit` and `Pick` for derived types
---
## FILE SIZE LIMITS
Keep files small and focused:
- Components: 50-150 lines max
- Hooks: 30-100 lines max
- Services: 50-200 lines max
- Pages: 100-300 lines max (they orchestrate)
If file exceeds limit → split into smaller pieces
---
## TESTING GUIDELINES
When writing tests:
- Test hooks independently
- Mock services
- Don't mock components unless necessary
- Test user interactions, not implementation
- Use `screen.getByRole()` not `querySelector()`
---
## PERFORMANCE RULES
- Use `React.memo()` for expensive components
- Use `useCallback()` for stable callbacks
- Use `useMemo()` only for expensive calculations
- Don't fetch in useEffect without dependencies
- Don't create objects/arrays in render
---
## ANTI-PATTERNS TO AVOID
❌ Logic in components
❌ Hooks calling hooks
❌ Multiple contexts (max 3-4)
❌ Using `any` type
❌ Direct Supabase calls in components
❌ Large files (>200 lines)
❌ Silent error handling
❌ Relative imports
❌ Inline complex logic
❌ Passing unnecessary props
---
## CHECKLIST BEFORE COMMITTING
- [ ] All components are under 150 lines
- [ ] All hooks are under 100 lines
- [ ] No Supabase calls in components
- [ ] All error cases handled
- [ ] All types are defined
- [ ] No `any` types
- [ ] Props interfaces defined
- [ ] No console.log statements
- [ ] Imports organized correctly
- [ ] File names follow conventions
- [ ] Updated relevant .md files
---
## PROMPT TEMPLATE FOR AI ASSISTANT
When asking Cursor to build features, use this template:
```
I want to add [FEATURE]. Here are the requirements:
## Requirements
- [Req 1]
- [Req 2]
## Tech Details
- Component: src/components/[role]/[Feature].tsx
- Hook: src/hooks/[role]/use[Feature].ts
- Service: src/services/[feature]Service.ts
- Types: src/types/[Feature].types.ts
## Steps
1. Create types in src/types/
2. Create service in src/services/
3. Create hook in src/hooks/
4. Create component in src/components/
5. Add to page
Follow our ARCHITECTURE.md and .cursorrules guidelines.
```
---
## Questions?
See ARCHITECTURE.md for detailed explanations.
See coding examples in existing feature folders.
When in doubt, ask the AI: "Is this following .cursorrules?"
---
Last Updated: January 2025