-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtoss-frontend-rules.mdc
More file actions
757 lines (586 loc) · 20.4 KB
/
Copy pathtoss-frontend-rules.mdc
File metadata and controls
757 lines (586 loc) · 20.4 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
---
description:
globs:
alwaysApply: true
---
# Frontend Design Guideline
This document summarizes key frontend design principles and rules, showcasing
recommended patterns. Follow these guidelines when writing frontend code.
# Readability
Improving the clarity and ease of understanding code.
## Naming Magic Numbers
**Rule:** Replace magic numbers with named constants for clarity.
**Reasoning:**
- Improves clarity by giving semantic meaning to unexplained values.
- Enhances maintainability.
#### Recommended Pattern:
```typescript
const ANIMATION_DELAY_MS = 300;
async function onLikeClick() {
await postLike(url);
await delay(ANIMATION_DELAY_MS); // Clearly indicates waiting for animation
await refetchPostLike();
}
```
## Abstracting Implementation Details
**Rule:** Abstract complex logic/interactions into dedicated components/HOCs.
**Reasoning:**
- Reduces cognitive load by separating concerns.
- Improves readability, testability, and maintainability of components.
#### Recommended Pattern 1: Auth Guard
(Login check abstracted to a wrapper/guard component)
```tsx
// App structure
function App() {
return (
<AuthGuard>
{" "}
{/* Wrapper handles auth check */}
<LoginStartPage />
</AuthGuard>
);
}
// AuthGuard component encapsulates the check/redirect logic
function AuthGuard({ children }) {
const status = useCheckLoginStatus();
useEffect(() => {
if (status === "LOGGED_IN") {
location.href = "/home";
}
}, [status]);
// Render children only if not logged in, otherwise render null (or loading)
return status !== "LOGGED_IN" ? children : null;
}
// LoginStartPage is now simpler, focused only on login UI/logic
function LoginStartPage() {
// ... login related logic ONLY ...
return <>{/* ... login related components ... */}</>;
}
```
## Separating Code Paths for Conditional Rendering
**Rule:** Separate significantly different conditional UI/logic into distinct
components.
**Reasoning:**
- Improves readability by avoiding complex conditionals within one component.
- Ensures each specialized component has a clear, single responsibility.
#### Recommended Pattern:
(Separate components for each role)
```tsx
function SubmitButton() {
const isViewer = useRole() === "viewer";
// Delegate rendering to specialized components
return isViewer ? <ViewerSubmitButton /> : <AdminSubmitButton />;
}
// Component specifically for the 'viewer' role
function ViewerSubmitButton() {
return <TextButton disabled>Submit</TextButton>;
}
// Component specifically for the 'admin' (or non-viewer) role
function AdminSubmitButton() {
useEffect(() => {
showAnimation(); // Animation logic isolated here
}, []);
return <Button type="submit">Submit</Button>;
}
```
## Simplifying Complex Ternary Operators
**Rule:** Replace complex/nested ternaries with `if`/`else` or IIFEs for
readability.
**Reasoning:**
- Makes conditional logic easier to follow quickly.
- Improves overall code maintainability.
#### Recommended Pattern:
(Using an IIFE with `if` statements)
```typescript
const status = (() => {
if (ACondition && BCondition) return "BOTH";
if (ACondition) return "A";
if (BCondition) return "B";
return "NONE";
})();
```
## Reducing Eye Movement (Colocating Simple Logic)
**Rule:** Colocate simple, localized logic or use inline definitions to reduce
context switching.
**Reasoning:**
- Allows top-to-bottom reading and faster comprehension.
- Reduces cognitive load from context switching (eye movement).
#### Recommended Pattern A: Inline `switch`
```tsx
function Page() {
const user = useUser();
// Logic is directly visible here
switch (user.role) {
case "admin":
return (
<div>
<Button disabled={false}>Invite</Button>
<Button disabled={false}>View</Button>
</div>
);
case "viewer":
return (
<div>
<Button disabled={true}>Invite</Button> {/* Example for viewer */}
<Button disabled={false}>View</Button>
</div>
);
default:
return null;
}
}
```
#### Recommended Pattern B: Colocated simple policy object
```tsx
function Page() {
const user = useUser();
// Simple policy defined right here, easy to see
const policy = {
admin: { canInvite: true, canView: true },
viewer: { canInvite: false, canView: true },
}[user.role];
// Ensure policy exists before accessing properties if role might not match
if (!policy) return null;
return (
<div>
<Button disabled={!policy.canInvite}>Invite</Button>
<Button disabled={!policy.canView}>View</Button>
</div>
);
}
```
## Naming Complex Conditions
**Rule:** Assign complex boolean conditions to named variables.
**Reasoning:**
- Makes the _meaning_ of the condition explicit.
- Improves readability and self-documentation by reducing cognitive load.
#### Recommended Pattern:
(Conditions assigned to named variables)
```typescript
const matchedProducts = products.filter((product) => {
// Check if product belongs to the target category
const isSameCategory = product.categories.some(
(category) => category.id === targetCategory.id
);
// Check if any product price falls within the desired range
const isPriceInRange = product.prices.some(
(price) => price >= minPrice && price <= maxPrice
);
// The overall condition is now much clearer
return isSameCategory && isPriceInRange;
});
```
**Guidance:** Name conditions when the logic is complex, reused, or needs unit
testing. Avoid naming very simple, single-use conditions.
# Predictability
Ensuring code behaves as expected based on its name, parameters, and context.
## Standardizing Return Types
**Rule:** Use consistent return types for similar functions/hooks.
**Reasoning:**
- Improves code predictability; developers can anticipate return value shapes.
- Reduces confusion and potential errors from inconsistent types.
#### Recommended Pattern 1: API Hooks (React Query)
```typescript
// Always return the Query object
import { useQuery, UseQueryResult } from "@tanstack/react-query";
// Assuming fetchUser returns Promise<UserType>
function useUser(): UseQueryResult<UserType, Error> {
const query = useQuery({ queryKey: ["user"], queryFn: fetchUser });
return query;
}
// Assuming fetchServerTime returns Promise<Date>
function useServerTime(): UseQueryResult<Date, Error> {
const query = useQuery({
queryKey: ["serverTime"],
queryFn: fetchServerTime,
});
return query;
}
```
#### Recommended Pattern 2: Validation Functions
(Using a consistent type, ideally a Discriminated Union)
```typescript
type ValidationResult = { ok: true } | { ok: false; reason: string };
function checkIsNameValid(name: string): ValidationResult {
if (name.length === 0) return { ok: false, reason: "Name cannot be empty." };
if (name.length >= 20)
return { ok: false, reason: "Name cannot be longer than 20 characters." };
return { ok: true };
}
function checkIsAgeValid(age: number): ValidationResult {
if (!Number.isInteger(age))
return { ok: false, reason: "Age must be an integer." };
if (age < 18) return { ok: false, reason: "Age must be 18 or older." };
if (age > 99) return { ok: false, reason: "Age must be 99 or younger." };
return { ok: true };
}
// Usage allows safe access to 'reason' only when ok is false
const nameValidation = checkIsNameValid(name);
if (!nameValidation.ok) {
console.error(nameValidation.reason);
}
```
## Revealing Hidden Logic (Single Responsibility)
**Rule:** Avoid hidden side effects; functions should only perform actions
implied by their signature (SRP).
**Reasoning:**
- Leads to predictable behavior without unintended side effects.
- Creates more robust, testable code through separation of concerns (SRP).
#### Recommended Pattern:
```typescript
// Function *only* fetches balance
async function fetchBalance(): Promise<number> {
const balance = await http.get<number>("...");
return balance;
}
// Caller explicitly performs logging where needed
async function handleUpdateClick() {
const balance = await fetchBalance(); // Fetch
logging.log("balance_fetched"); // Log (explicit action)
await syncBalance(balance); // Another action
}
```
## Using Unique and Descriptive Names (Avoiding Ambiguity)
**Rule:** Use unique, descriptive names for custom wrappers/functions to avoid
ambiguity.
**Reasoning:**
- Avoids ambiguity and enhances predictability.
- Allows developers to understand specific actions (e.g., adding auth) directly
from the name.
#### Recommended Pattern:
```typescript
// In httpService.ts - Clearer module name
import { http as httpLibrary } from "@some-library/http";
export const httpService = {
// Unique module name
async getWithAuth(url: string) {
// Descriptive function name
const token = await fetchToken();
return httpLibrary.get(url, {
headers: { Authorization: `Bearer ${token}` },
});
},
};
// In fetchUser.ts - Usage clearly indicates auth
import { httpService } from "./httpService";
export async function fetchUser() {
// Name 'getWithAuth' makes the behavior explicit
return await httpService.getWithAuth("...");
}
```
# Cohesion
Keeping related code together and ensuring modules have a well-defined, single
purpose.
## Considering Form Cohesion
**Rule:** Choose field-level or form-level cohesion based on form requirements.
**Reasoning:**
- Balances field independence (field-level) vs. form unity (form-level).
- Ensures related form logic is appropriately grouped based on requirements.
#### Recommended Pattern (Field-Level Example):
```tsx
// Each field uses its own `validate` function
import { useForm } from "react-hook-form";
export function Form() {
const {
register,
formState: { errors },
handleSubmit,
} = useForm({
/* defaultValues etc. */
});
const onSubmit = handleSubmit((formData) => {
console.log("Form submitted:", formData);
});
return (
<form onSubmit={onSubmit}>
<div>
<input
{...register("name", {
validate: (value) =>
value.trim() === "" ? "Please enter your name." : true, // Example validation
})}
placeholder="Name"
/>
{errors.name && <p>{errors.name.message}</p>}
</div>
<div>
<input
{...register("email", {
validate: (value) =>
/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(value)
? true
: "Invalid email address.", // Example validation
})}
placeholder="Email"
/>
{errors.email && <p>{errors.email.message}</p>}
</div>
<button type="submit">Submit</button>
</form>
);
}
```
#### Recommended Pattern (Form-Level Example):
```tsx
// A single schema defines validation for the whole form
import * as z from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
const schema = z.object({
name: z.string().min(1, "Please enter your name."),
email: z.string().min(1, "Please enter your email.").email("Invalid email."),
});
export function Form() {
const {
register,
formState: { errors },
handleSubmit,
} = useForm({
resolver: zodResolver(schema),
defaultValues: { name: "", email: "" },
});
const onSubmit = handleSubmit((formData) => {
console.log("Form submitted:", formData);
});
return (
<form onSubmit={onSubmit}>
<div>
<input {...register("name")} placeholder="Name" />
{errors.name && <p>{errors.name.message}</p>}
</div>
<div>
<input {...register("email")} placeholder="Email" />
{errors.email && <p>{errors.email.message}</p>}
</div>
<button type="submit">Submit</button>
</form>
);
}
```
**Guidance:** Choose **field-level** for independent validation, async checks,
or reusable fields. Choose **form-level** for related fields, wizard forms, or
interdependent validation.
## Organizing Code by Feature/Domain
**Rule:** Organize directories by feature/domain, not just by code type.
**Reasoning:**
- Increases cohesion by keeping related files together.
- Simplifies feature understanding, development, maintenance, and deletion.
#### Recommended Pattern:
(Organized by feature/domain)
```
src/
├── components/ # Shared/common components
├── hooks/ # Shared/common hooks
├── utils/ # Shared/common utils
├── domains/
│ ├── user/
│ │ ├── components/
│ │ │ └── UserProfileCard.tsx
│ │ ├── hooks/
│ │ │ └── useUser.ts
│ │ └── index.ts # Optional barrel file
│ ├── product/
│ │ ├── components/
│ │ │ └── ProductList.tsx
│ │ ├── hooks/
│ │ │ └── useProducts.ts
│ │ └── ...
│ └── order/
│ ├── components/
│ │ └── OrderSummary.tsx
│ ├── hooks/
│ │ └── useOrder.ts
│ └── ...
└── App.tsx
```
## Relating Magic Numbers to Logic
**Rule:** Define constants near related logic or ensure names link them clearly.
**Reasoning:**
- Improves cohesion by linking constants to the logic they represent.
- Prevents silent failures caused by updating logic without updating related
constants.
#### Recommended Pattern:
```typescript
// Constant clearly named and potentially defined near animation logic
const ANIMATION_DELAY_MS = 300;
async function onLikeClick() {
await postLike(url);
// Delay uses the constant, maintaining the link to the animation
await delay(ANIMATION_DELAY_MS);
await refetchPostLike();
}
```
_Ensure constants are maintained alongside the logic they depend on or clearly
named to show the relationship._
# Coupling
Minimizing dependencies between different parts of the codebase.
## Balancing Abstraction and Coupling (Avoiding Premature Abstraction)
**Rule:** Avoid premature abstraction of duplicates if use cases might diverge;
prefer lower coupling.
**Reasoning:**
- Avoids tight coupling from forcing potentially diverging logic into one
abstraction.
- Allowing some duplication can improve decoupling and maintainability when
future needs are uncertain.
#### Guidance:
Before abstracting, consider if the logic is truly identical and likely to
_stay_ identical across all use cases. If divergence is possible (e.g.,
different pages needing slightly different behavior from a shared hook like
`useOpenMaintenanceBottomSheet`), keeping the logic separate initially (allowing
duplication) can lead to more maintainable, decoupled code. Discuss trade-offs
with the team. _[No specific 'good' code example here, as the recommendation is
situational awareness rather than a single pattern]._
## Scoping State Management (Avoiding Overly Broad Hooks)
**Rule:** Break down broad state management into smaller, focused
hooks/contexts.
**Reasoning:**
- Reduces coupling by ensuring components only depend on necessary state slices.
- Improves performance by preventing unnecessary re-renders from unrelated state
changes.
#### Recommended Pattern:
(Focused hooks, low coupling)
```typescript
// Hook specifically for cardId query param
import { useQueryParam, NumberParam } from "use-query-params";
import { useCallback } from "react";
export function useCardIdQueryParam() {
// Assuming 'query' provides the raw param value
const [cardIdParam, setCardIdParam] = useQueryParam("cardId", NumberParam);
const setCardId = useCallback(
(newCardId: number | undefined) => {
setCardIdParam(newCardId, "replaceIn"); // Or 'push' depending on desired history behavior
},
[setCardIdParam]
);
// Provide a stable return tuple
return [cardIdParam ?? undefined, setCardId] as const;
}
// Separate hook for date range, etc.
// export function useDateRangeQueryParam() { /* ... */ }
```
Components now only import and use `useCardIdQueryParam` if they need `cardId`,
decoupling them from date range state, etc.
## Eliminating Props Drilling with Composition
**Rule:** Use Component Composition instead of Props Drilling.
**Reasoning:**
- Significantly reduces coupling by eliminating unnecessary intermediate
dependencies.
- Makes refactoring easier and clarifies data flow in flatter component trees.
#### Recommended Pattern:
```tsx
import React, { useState } from "react";
// Assume Modal, Input, Button, ItemEditList components exist
function ItemEditModal({ open, items, recommendedItems, onConfirm, onClose }) {
const [keyword, setKeyword] = useState("");
// Render children directly within Modal, passing props only where needed
return (
<Modal open={open} onClose={onClose}>
{/* Input and Button rendered directly */}
<div
style={{
display: "flex",
justifyContent: "space-between",
marginBottom: "1rem",
}}
>
<Input
value={keyword}
onChange={(e) => setKeyword(e.target.value)} // State managed here
placeholder="Search items..."
/>
<Button onClick={onClose}>Close</Button>
</div>
{/* ItemEditList rendered directly, gets props it needs */}
<ItemEditList
keyword={keyword} // Passed directly
items={items} // Passed directly
recommendedItems={recommendedItems} // Passed directly
onConfirm={onConfirm} // Passed directly
/>
</Modal>
);
}
// The intermediate ItemEditBody component is eliminated, reducing coupling.
```
# Documentation and Language
## English-Only Codebase
**Rule:** All documentation, comments, and variable/function names must be written in English.
**Reasoning:**
- Ensures global collaboration and understanding
- Maintains coding standard consistency
- Improves maintainability for future developers
- Reduces context switching between languages
- Makes code more accessible to international contributors
#### Implementation Guidelines:
- All variable and function names must use English terms
- All comments must be written in English
- All documentation files must be in English
- Commit messages must be in English
- Even temporary development notes should be in English
- API documentation must be in English
- Code reviews and pull request discussions must be in English
- Issue descriptions and discussions must be in English
#### Examples:
✅ Good:
```typescript
// Calculate the total price including tax
const calculateTotalPrice = (price: number, taxRate: number): number => {
return price * (1 + taxRate);
};
```
❌ Bad:
```typescript
// 세금을 포함한 총 가격 계산
const 총가격계산 = (가격: number, 세율: number): number => {
return 가격 * (1 + 세율);
};
```
**Note:** Non-English content should only appear in user-facing text that will be localized, and even then, it should be properly organized in localization files, not hardcoded in the application.
## Code Documentation Guidelines
**Rule:** Only add comments for historical context or complex logic that cannot be easily understood from the code itself.
**Reasoning:**
- Reduces noise and maintenance overhead
- Encourages self-documenting code through clear naming and structure
- Focuses documentation on truly necessary context
- Makes code reviews more efficient by highlighting only important context
#### Implementation Guidelines:
- Avoid commenting on obvious code that can be understood from the code itself
- Use comments only for:
- Historical context (why a decision was made)
- Complex business logic that isn't immediately obvious
- Workarounds or temporary solutions
- Important edge cases or limitations
- Prefer self-documenting code through:
- Clear variable and function names
- Small, focused functions
- Consistent patterns and structure
- Type definitions and interfaces
#### Examples:
✅ Good:
```typescript
// Historical: This timeout was increased from 300ms to 500ms due to
// intermittent network latency issues in production
const API_TIMEOUT_MS = 500;
// Complex business logic: Calculate prorated refund amount based on
// subscription period and usage
function calculateRefundAmount(subscription: Subscription): number {
// ... complex calculation logic ...
}
// Workaround: Using setTimeout to ensure DOM is ready before
// initializing the chart due to SSR hydration timing
useEffect(() => {
setTimeout(() => initializeChart(), 0);
}, []);
```
❌ Bad:
```typescript
// This is a function that adds two numbers
function add(a: number, b: number): number {
return a + b;
}
// Loop through the array
for (const item of items) {
// Process each item
processItem(item);
}
```