-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy path.cursorrules
More file actions
1652 lines (1287 loc) · 41.6 KB
/
.cursorrules
File metadata and controls
1652 lines (1287 loc) · 41.6 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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# YCode Cursor AI Rules
## 🎯 Project Context
**YCode** is a self-hosted visual website builder built with Next.js 15, TypeScript, Tailwind CSS, and Supabase. This is a **fast-moving team project** where multiple developers use Cursor simultaneously. Code consistency and abstraction are critical.
---
## 🧠 Core Philosophy: ALWAYS Think About Abstraction
Before writing any code, ask yourself:
1. **Can this logic be extracted into a reusable hook?**
2. **Does a ShadCN component already exist for this UI element?**
3. **Is this component doing too many things? Should it be split?**
4. **Can this be a pure utility function instead of component logic?**
5. **Will another team member be able to reuse this easily?**
**Golden Rule**: If you're writing the same code twice, abstract it.
---
## 🎨 1. ShadCN Components (MANDATORY)
### ALWAYS Use ShadCN for UI Primitives
**Available ShadCN Components** (in `/components/ui/`):
- `Button` - All button interactions
- `Input` - Text inputs
- `Textarea` - Multi-line text
- `Label` - Form labels
- `Select` - Dropdowns
- `Tabs` - Tab navigation
- `Dropdown Menu` - Context menus
- `Popover` - Overlays
- `Tooltip` - Hover hints
- `Slider` - Range inputs
- `Badge` - Status indicators
- `Spinner` - Loading states
- `Icon` - Lucide icons (via icon.tsx)
### ✅ CORRECT Usage
```typescript
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Icon } from '@/components/ui/icon';
export function SearchBar({ onSearch }: SearchBarProps) {
const [query, setQuery] = useState('');
return (
<div className="flex gap-2">
<Input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search pages..."
/>
<Button size="sm" onClick={() => onSearch(query)}>
<Icon name="search" />
Search
</Button>
</div>
);
}
```
### ❌ FORBIDDEN - Never Do This
```typescript
// ❌ WRONG: Custom button instead of ShadCN
export function SearchBar({ onSearch }: SearchBarProps) {
return (
<button className="px-4 py-2 bg-blue-500 rounded hover:bg-blue-600">
Search
</button>
);
}
// ❌ WRONG: Custom input instead of ShadCN
<input className="border rounded px-2 py-1" />
```
### Extending ShadCN Components
If you need custom behavior, **compose** ShadCN components:
```typescript
// ✅ CORRECT: Composition
import { Button } from '@/components/ui/button';
import { Icon } from '@/components/ui/icon';
interface IconButtonProps {
icon: string;
label: string;
onClick: () => void;
}
export function IconButton({ icon, label, onClick }: IconButtonProps) {
return (
<Button size="sm" variant="secondary" onClick={onClick}>
<Icon name={icon} />
{label}
</Button>
);
}
```
---
## 🏗️ 2. Component Architecture & Abstraction
### Single Responsibility Principle
Each component should do ONE thing well:
```typescript
// ✅ GOOD: Small, focused components
function PageListItem({ page, onSelect, isActive }: PageListItemProps) {
return (
<button
onClick={() => onSelect(page.id)}
className={cn(
'w-full text-left px-3 py-2 rounded',
isActive ? 'bg-zinc-700' : 'hover:bg-zinc-800'
)}
>
<Icon name="file" />
{page.title}
</button>
);
}
function PageList({ pages, selectedId, onSelect }: PageListProps) {
return (
<div className="flex flex-col gap-1">
{pages.map(page => (
<PageListItem
key={page.id}
page={page}
isActive={selectedId === page.id}
onSelect={onSelect}
/>
))}
</div>
);
}
// ❌ BAD: Monolithic component doing everything
function PageManagement() {
// 500 lines of code managing pages, settings, modals, etc.
}
```
### Extract Custom Hooks
Move reusable logic into custom hooks:
```typescript
// ✅ GOOD: Reusable hook
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(handler);
}, [value, delay]);
return debouncedValue;
}
// Usage in component
function SearchInput() {
const [query, setQuery] = useState('');
const debouncedQuery = useDebounce(query, 500);
useEffect(() => {
if (debouncedQuery) {
performSearch(debouncedQuery);
}
}, [debouncedQuery]);
}
```
### Extract Utility Functions
Keep components clean by moving pure functions to `/lib`:
```typescript
// ✅ GOOD: Utility in /lib/layer-utils.ts
export function findLayerById(layers: Layer[], id: string): Layer | null {
for (const layer of layers) {
if (layer.id === id) return layer;
if (layer.children) {
const found = findLayerById(layer.children, id);
if (found) return found;
}
}
return null;
}
// Usage in component
import { findLayerById } from '@/lib/layer-utils';
function LayerEditor({ layers, selectedId }: LayerEditorProps) {
const selectedLayer = findLayerById(layers, selectedId);
// ...
}
```
---
## 📁 3. File & Naming Conventions
### File Names
- **All files**: `kebab-case.tsx` (e.g., `page-settings.tsx`, `user-profile.tsx`)
- **Components**: PascalCase export matching filename
- File: `layer-renderer.tsx` → Export: `LayerRenderer`
- **Utilities**: camelCase functions
- File: `layer-utils.ts` → Export: `findLayerById`
- **Hooks**: camelCase with `use` prefix
- File: `use-debounce.ts` → Export: `useDebounce`
### Variable & Function Names
```typescript
// Components & Types: PascalCase
const UserProfile: React.FC<UserProfileProps> = () => {};
interface LayerProps {}
type PageStatus = 'draft' | 'published';
// Functions & Variables: camelCase
const handleClick = () => {};
const userData = fetchUser();
function formatDate(date: Date) {}
// Event Handlers: handleX pattern
const handleSubmit = () => {};
const handlePageSelect = (id: string) => {};
const handleInputChange = (e: ChangeEvent) => {};
// Boolean: isX, hasX, shouldX
const isLoading = false;
const hasChildren = layers.length > 0;
const shouldRender = isVisible && hasData;
// Constants: SCREAMING_SNAKE_CASE
const MAX_PAGE_SIZE = 100;
const API_BASE_URL = 'https://api.example.com';
const DEFAULT_LAYER_CLASSES = 'flex gap-4';
```
---
## 📦 4. Import Organization
**ALWAYS order imports consistently** to prevent merge conflicts:
```typescript
// 1. React/Next.js core
import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import Image from 'next/image';
// 2. External libraries (alphabetical)
import { create } from 'zustand';
import debounce from 'lodash.debounce';
import { DndContext } from '@dnd-kit/core';
// 3. ShadCN UI components (alphabetical)
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
// 4. Internal components (alphabetical)
import { LayerRenderer } from '@/components/layers/LayerRenderer';
import { PageSettings } from './PageSettings';
import ElementLibrary from './ElementLibrary';
// 5. Stores (alphabetical)
import { useEditorStore } from '@/stores/useEditorStore';
import { usePagesStore } from '@/stores/usePagesStore';
// 6. Utils, APIs, lib (alphabetical)
import { pagesApi } from '@/lib/api';
import { cn } from '@/lib/utils';
import { findLayerById } from '@/lib/layer-utils';
// 7. Types (always last, alphabetical)
import type { Layer, Page, PageLayers, Asset } from '@/types';
```
---
## 🛣️ 5. Path Aliases - When to Use What
### Rules:
- Use `@/` for **everything outside current directory**
- Use `./` **ONLY** for files in the **same directory**
- Use `../` **sparingly** (max 1 level up, prefer `@/`)
- **NEVER** use deep relative paths like `../../../../`
```typescript
// ✅ CORRECT
import { Button } from '@/components/ui/button';
import { useEditorStore } from '@/stores/useEditorStore';
import { PageSettings } from './PageSettings'; // Same directory
import { findLayerById } from '@/lib/layer-utils';
// ❌ WRONG
import { Button } from '../../../components/ui/button';
import { useEditorStore } from '../../stores/useEditorStore';
```
---
## ⚛️ 6. Server vs Client Components (Next.js 15)
### Default: Server Components
**Don't add any directive** - components are Server Components by default.
### Add `'use client'` ONLY When:
- Using React hooks (`useState`, `useEffect`, `useCallback`, etc.)
- Using event handlers (`onClick`, `onChange`, `onSubmit`)
- Using browser APIs (`window`, `localStorage`, `document`)
- Using Zustand stores
- Using client-only libraries
```typescript
// ✅ Server Component (no directive)
// app/[slug]/page.tsx
export default async function Page({ params }: { params: { slug: string } }) {
const page = await fetchPageBySlug(params.slug);
return <LayerRenderer layers={page.layers} />;
}
// ✅ Client Component (with directive)
// app/ycode/components/LayersTree.tsx
'use client';
import { useState } from 'react';
export default function LayersTree({ layers }: LayersTreeProps) {
const [expanded, setExpanded] = useState<Set<string>>(new Set());
// Component using hooks and state
}
```
### Keep `'use client'` Close to Leaves
Push client boundaries down the tree:
```typescript
// ✅ GOOD: Server component wraps client component
// app/page.tsx (Server Component)
export default function Page() {
return (
<div>
<Header /> {/* Server */}
<InteractiveWidget /> {/* Client */}
<Footer /> {/* Server */}
</div>
);
}
// ❌ BAD: Everything is client-side unnecessarily
'use client';
export default function Page() {
return (
<div>
<Header /> {/* Unnecessarily client-side */}
<InteractiveWidget />
<Footer /> {/* Unnecessarily client-side */}
</div>
);
}
```
---
## 🗄️ 7. Repository Pattern (Backend/API)
### NEVER Use Supabase Directly in API Routes
**Architecture**: `API Route → Repository → Supabase Client`
```typescript
// ✅ CORRECT: Use repository pattern
// app/api/pages/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { getPageById, updatePage } from '@/lib/repositories/pageRepository';
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const page = await getPageById(params.id);
if (!page) {
return NextResponse.json({ error: 'Page not found' }, { status: 404 });
}
return NextResponse.json({ data: page });
} catch (error) {
console.error('Error fetching page:', error);
return NextResponse.json(
{ error: 'Failed to fetch page' },
{ status: 500 }
);
}
}
// ❌ WRONG: Direct Supabase in API route
import { getSupabaseAdmin } from '@/lib/supabase-server';
export async function GET(request: NextRequest, { params }) {
const supabase = await getSupabaseAdmin();
const { data } = await supabase.from('pages').select('*').eq('id', params.id);
// WRONG! Use repository instead
}
```
### Create Repositories for All Data Entities
**IMPORTANT**: Always use alias imports (`@/lib/...`) for all lib modules including `supabase-server` and repositories. Never use relative imports like `../supabase-server` or `../repositories/settingsRepository`. This ensures consistent behavior and allows overlays to work correctly in multi-tenant deployments.
Example structure in `/lib/repositories/pageRepository.ts`:
```typescript
import { getSupabaseAdmin } from '@/lib/supabase-server';
import type { Page } from '@/types';
export async function getAllPages(): Promise<Page[]> {
const client = await getSupabaseAdmin();
const { data, error } = await client
.from('pages')
.select('*')
.order('created_at', { ascending: false });
if (error) throw new Error(`Failed to fetch pages: ${error.message}`);
return data || [];
}
export async function getPageById(id: string): Promise<Page | null> {
const client = await getSupabaseAdmin();
const { data, error } = await client
.from('pages')
.select('*')
.eq('id', id)
.single();
if (error && error.code !== 'PGRST116') {
throw new Error(`Failed to fetch page: ${error.message}`);
}
return data;
}
export async function createPage(pageData: Omit<Page, 'id' | 'created_at' | 'updated_at'>): Promise<Page> {
const client = await getSupabaseAdmin();
const { data, error } = await client
.from('pages')
.insert(pageData)
.select()
.single();
if (error) throw new Error(`Failed to create page: ${error.message}`);
return data;
}
```
### ALWAYS Use Upsert for Database Operations
**NEVER execute queries in loops or use Promise.all for individual database operations.**
Use batch operations with `upsert` instead of separate insert/update operations.
```typescript
// ✅ CORRECT: Batch upsert operation
const itemsToUpsert = items.map(item => ({
id: item.id,
name: item.name,
is_published: true,
updated_at: new Date().toISOString(),
}));
await client
.from('table_name')
.upsert(itemsToUpsert, {
onConflict: 'id,is_published', // Composite key
});
// ❌ WRONG: Queries in loops
for (const item of items) {
const existing = await getItemById(item.id);
if (existing) {
await client.from('table_name').update(item).eq('id', item.id);
} else {
await client.from('table_name').insert(item);
}
}
// ❌ WRONG: Promise.all with individual queries
const updates = items.map(item =>
client.from('table_name').update(item).eq('id', item.id)
);
await Promise.all(updates);
```
### Rules
1. **ALWAYS** use `upsert` for insert/update operations
2. **NEVER** execute queries inside loops
3. **NEVER** use `Promise.all` with individual update queries
4. **ALWAYS** batch operations when possible
5. Use `onConflict` parameter to specify composite keys for upsert operations
---
## 🔄 8. API Response Format (Consistency)
### All API Routes MUST Return Consistent Format
Use the `ApiResponse<T>` type from `/types/index.ts`:
```typescript
// ✅ Success response
return NextResponse.json({
data: result
}, { status: 200 });
// ✅ Error response
return NextResponse.json({
error: 'Descriptive error message'
}, { status: 400 });
// ✅ With optional message
return NextResponse.json({
data: result,
message: 'Page published successfully'
}, { status: 200 });
```
### Status Codes
- `200` - Success (GET, PUT)
- `201` - Created (POST)
- `204` - No Content (DELETE)
- `400` - Bad Request (validation errors)
- `404` - Not Found
- `500` - Internal Server Error
---
## ⚠️ 9. Error Handling & Async Operations
### ALWAYS Follow This Pattern
```typescript
// ✅ REQUIRED pattern for ALL async operations
const handleAction = async () => {
try {
setLoading(true);
setError(null); // Clear previous errors
const result = await apiCall();
// Success handling
setData(result);
} catch (error) {
console.error('Context-specific message:', error);
setError(error instanceof Error ? error.message : 'Unknown error occurred');
} finally {
setLoading(false); // Always runs
}
};
```
### In Components with UI State
```typescript
function PageEditor({ pageId }: PageEditorProps) {
const [page, setPage] = useState<Page | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const loadPage = async () => {
try {
setLoading(true);
const result = await pagesApi.getById(pageId);
setPage(result.data);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load page');
} finally {
setLoading(false);
}
};
loadPage();
}, [pageId]);
if (loading) return <Spinner />;
if (error) return <ErrorMessage error={error} />;
if (!page) return null;
return <div>{/* Render page */}</div>;
}
```
---
## ⏳ 10. Loading States (MANDATORY)
### Always Show Loading for Async Operations
```typescript
// ✅ CORRECT: Loading state shown
function PageList() {
const [pages, setPages] = useState<Page[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchPages().then(setPages).finally(() => setLoading(false));
}, []);
if (loading) {
return <Spinner />;
}
return <div>{/* Render pages */}</div>;
}
// ❌ WRONG: No loading state
function PageList() {
const [pages, setPages] = useState<Page[]>([]);
useEffect(() => {
fetchPages().then(setPages);
}, []);
return <div>{/* Flashes empty state, then content */}</div>;
}
```
### Use ShadCN Spinner
```typescript
import { Spinner } from '@/components/ui/spinner';
if (loading) return <Spinner />;
if (loading) return (
<div className="flex items-center justify-center p-8">
<Spinner />
</div>
);
```
---
## 🔀 11. Conditional Rendering - Early Returns
### Prefer Early Returns Over Nested Ternaries
```typescript
// ✅ GOOD: Early returns (clean, readable)
function PageEditor({ pageId }: PageEditorProps) {
const { page, loading, error } = usePageData(pageId);
if (loading) {
return <Spinner />;
}
if (error) {
return <ErrorMessage error={error} />;
}
if (!page) {
return <EmptyState message="Page not found" />;
}
return (
<div>
<h1>{page.title}</h1>
{/* Main content */}
</div>
);
}
// ❌ BAD: Nested ternaries (hard to read, hard to maintain)
function PageEditor({ pageId }: PageEditorProps) {
const { page, loading, error } = usePageData(pageId);
return loading ? (
<Spinner />
) : error ? (
<ErrorMessage error={error} />
) : !page ? (
<EmptyState message="Page not found" />
) : (
<div>
<h1>{page.title}</h1>
{/* Main content */}
</div>
);
}
```
### For Simple Conditions
Use inline ternaries for simple show/hide:
```typescript
// ✅ GOOD: Simple inline conditional
<div>
{isVisible && <Notice message="Page is published" />}
{count > 0 ? <Badge>{count}</Badge> : null}
</div>
```
---
## 🎭 12. State Management with Zustand
### Keep Stores Focused and Domain-Specific
```typescript
// ✅ GOOD: Focused store
// stores/useEditorStore.ts
import { create } from 'zustand';
interface EditorState {
selectedLayerId: string | null;
currentPageId: string | null;
isLoading: boolean;
isSaving: boolean;
}
interface EditorActions {
setSelectedLayerId: (id: string | null) => void;
setCurrentPageId: (id: string | null) => void;
setLoading: (value: boolean) => void;
setSaving: (value: boolean) => void;
}
type EditorStore = EditorState & EditorActions;
export const useEditorStore = create<EditorStore>((set) => ({
selectedLayerId: null,
currentPageId: null,
isLoading: false,
isSaving: false,
setSelectedLayerId: (id) => set({ selectedLayerId: id }),
setCurrentPageId: (id) => set({ currentPageId: id }),
setLoading: (value) => set({ isLoading: value }),
setSaving: (value) => set({ isSaving: value }),
}));
```
### Use TypeScript Interfaces for Store Types
Always define separate interfaces for state and actions, then combine them.
---
## ⚡ 13. Performance Optimization
### When to Optimize
1. **Profile First** - Don't optimize prematurely
2. **Use React DevTools Profiler** to identify slow components
3. **Optimize when you see actual performance issues**
### React.memo for Expensive Pure Components
```typescript
// ✅ Use React.memo for pure components that render often
import React, { memo } from 'react';
interface LayerItemProps {
layer: Layer;
onSelect: (id: string) => void;
}
const LayerItem: React.FC<LayerItemProps> = memo(({ layer, onSelect }) => {
return (
<div onClick={() => onSelect(layer.id)}>
{layer.name}
</div>
);
});
```
### useCallback for Functions Passed as Props
```typescript
// ✅ useCallback prevents unnecessary re-renders
function LayersList({ layers }: LayersListProps) {
const handleSelect = useCallback((id: string) => {
console.log('Selected:', id);
}, []); // Empty deps - function never changes
return (
<>
{layers.map(layer => (
<LayerItem key={layer.id} layer={layer} onSelect={handleSelect} />
))}
</>
);
}
```
### useMemo for Expensive Calculations
```typescript
// ✅ useMemo caches expensive computations
function PageEditor({ pageId }: PageEditorProps) {
const { draftsByPageId } = usePagesStore();
// Expensive: traverse tree structure
const layersForCurrentPage = useMemo(() => {
if (!pageId) return [];
const draft = draftsByPageId[pageId];
return draft ? draft.layers : [];
}, [pageId, draftsByPageId]);
return <LayerRenderer layers={layersForCurrentPage} />;
}
```
---
## ♿ 14. Accessibility (A11y)
### Required for All Interactive Elements
```typescript
// ✅ GOOD: Accessible button
<Button
onClick={handleDelete}
aria-label="Delete page"
aria-describedby="delete-hint"
>
<Icon name="trash" />
</Button>
<span id="delete-hint" className="sr-only">
This action cannot be undone
</span>
// ❌ BAD: Not accessible
<div onClick={handleDelete}>
<Icon name="trash" />
</div>
```
### Checklist
- ✅ Use semantic HTML (`<button>` not `<div onClick>`)
- ✅ Include ARIA labels for icon-only buttons
- ✅ Maintain proper heading hierarchy (h1 → h2 → h3)
- ✅ Add alt text for images
- ✅ Ensure keyboard navigation works (Tab, Enter, Esc)
- ✅ Test with screen reader when possible
- ✅ Maintain sufficient color contrast
---
## 📝 15. Comments & Documentation
### When to Comment
```typescript
// ✅ GOOD: Explain WHY, not WHAT
// Use debounce to prevent excessive API calls during typing
const debouncedSearch = useDebounce(searchQuery, 500);
// Edge case: Supabase returns error code PGRST116 for "not found"
if (error && error.code !== 'PGRST116') {
throw error;
}
// TODO: Add pagination after 100 pages - performance degrades with large lists
const pages = await getAllPages();
// ❌ BAD: Obvious comments that repeat the code
// Set loading to true
setLoading(true);
// Loop through pages
pages.forEach(page => {
// ...
});
```
### JSDoc for Public APIs
```typescript
/**
* Recursively finds a layer by ID in a tree structure
* @param layers - Array of layers to search
* @param id - Unique layer ID to find
* @returns The found layer or null if not found
*/
export function findLayerById(layers: Layer[], id: string): Layer | null {
for (const layer of layers) {
if (layer.id === id) return layer;
if (layer.children) {
const found = findLayerById(layer.children, id);
if (found) return found;
}
}
return null;
}
```
---
## 🧹 16. Input Sanitization (MANDATORY for Design Properties)
### ALWAYS Sanitize User Input for Tailwind Classes
Design property inputs (fontSize, width, padding, etc.) MUST be sanitized to prevent invalid Tailwind classes. Spaces break Tailwind syntax.
### Use Centralized Utilities
**Location**: `/lib/utils.ts`
```typescript
import { removeSpaces, sanitizeInput } from '@/lib/utils';
// ✅ CORRECT: Use removeSpaces for Tailwind values
const handleFontSizeChange = (value: string) => {
const sanitized = removeSpaces(value); // "10 rem" → "10rem"
updateDesignProperty('typography', 'fontSize', sanitized || null);
};
// ✅ CORRECT: Use controlled input hook (auto-sanitizes)
const [fontSizeInput, setFontSizeInput] = useControlledInput(fontSize);
// Spaces automatically stripped at input level - never appear in the field
// ❌ WRONG: No sanitization
const handleChange = (value: string) => {
updateDesignProperty('typography', 'fontSize', value); // "10 rem" creates invalid class!
};
```
### useControlledInput Hook
The `useControlledInput` hook automatically sanitizes input values by default:
```typescript
import { useControlledInput } from '@/hooks/use-controlled-input';
// Auto-sanitizes by default (removes spaces)
const [fontSizeInput, setFontSizeInput] = useControlledInput(fontSize);
// Opt-out of sanitization if needed (rare)
const [customInput, setCustomInput] = useControlledInput(value, undefined, false);
```
### Available Sanitization Functions
```typescript
// Quick helper: Remove all spaces
removeSpaces('10 rem') // '10rem'
// Advanced: Custom sanitization
sanitizeInput(' 100px ', {
removeSpaces: false,
trim: true // '100px'
})
sanitizeInput('#FF 00 00', {
removeSpaces: true // '#FF0000'
})
```
### Rules
1. **ALWAYS** use `removeSpaces()` from `@/lib/utils` for design property handlers
2. **NEVER** create duplicate `const sanitize =` helpers in components
3. **USE** `useControlledInput` hook for design property inputs (auto-sanitizes)
4. **IMPORT** from `@/lib/utils`, not inline implementations
### Defense in Depth
We use **two layers** of protection:
1. **Hook Level**: `useControlledInput` strips spaces before they appear in the input field
2. **Handler Level**: `removeSpaces()` ensures spaces don't get saved
### Example: Complete Implementation
```typescript
import { useControlledInput } from '@/hooks/use-controlled-input';
import { removeSpaces } from '@/lib/utils';
import { extractMeasurementValue } from '@/lib/measurement-utils';
export default function TypographyControls({ layer, onLayerUpdate }) {
const { updateDesignProperty, getDesignProperty } = useDesignSync({
layer,
onLayerUpdate,