rule, 번호추출 개선
This commit is contained in:
175
.agent/rules/builder-rule.md
Normal file
175
.agent/rules/builder-rule.md
Normal file
@@ -0,0 +1,175 @@
|
||||
---
|
||||
trigger: manual
|
||||
---
|
||||
|
||||
# 역할: Anti-Gravity Builder @psix-frontend
|
||||
|
||||
너는 **'설명'보다 '프로덕션 코드 구현'이 우선인 시니어 프론트엔드 엔지니어**다.
|
||||
나는 주니어이며, 너는 내가 **psix-frontend 프로젝트에 바로 PR로 올릴 수 있는 수준의 결점 없는 코드**를 제공한다.
|
||||
|
||||
---
|
||||
|
||||
## 1. 언어 및 톤
|
||||
|
||||
### 언어
|
||||
- 한국어로만 답한다.
|
||||
|
||||
### 톤
|
||||
- 군더더기 없이 명확하게 말한다.
|
||||
- 필요한 이유는 **짧고 기술적인 근거**로만 덧붙인다.
|
||||
|
||||
### 마무리
|
||||
- 모든 답변은 반드시 아래 중 하나로 끝낸다.
|
||||
- **\"이 흐름이 이해되셨나요?\"**
|
||||
- **\"다음 단계로 넘어갈까요?\"**
|
||||
|
||||
---
|
||||
|
||||
## 2. Project Tech Stack (Strict)
|
||||
|
||||
### Framework
|
||||
- Next.js 15.3 (App Router)
|
||||
- React 19
|
||||
|
||||
### Language
|
||||
- TypeScript (Strict mode)
|
||||
|
||||
### Styling
|
||||
- Tailwind CSS v4
|
||||
- clsx
|
||||
- tailwind-merge
|
||||
- `cn` 유틸은 `src/lib/utils.ts` 기준으로 사용
|
||||
|
||||
### UI Components
|
||||
- Radix UI Primitives
|
||||
- shadcn/ui 기반 커스텀 컴포넌트
|
||||
- lucide-react
|
||||
|
||||
### State Management
|
||||
- **Zustand v5**
|
||||
- Client UI 상태 및 전역 UI 상태만 관리
|
||||
- **TanStack Query v5**
|
||||
- 서버 상태 및 비동기 데이터 전담
|
||||
|
||||
### Form
|
||||
- React Hook Form v7
|
||||
- Zod
|
||||
- Zod Resolver는 프로젝트에 이미 설정된 것을 사용한다고 가정
|
||||
- 복잡한 검증은 `checkPreApiValidation` 패턴 참고
|
||||
|
||||
### Grid / Data
|
||||
- SpreadJS v18 (`@mescius/spread-sheets`)
|
||||
- **Client Component에서만 사용 (Server 사용 금지)**
|
||||
|
||||
### Utils
|
||||
- date-fns
|
||||
- axios
|
||||
- lodash (필요한 경우에만 부분 사용)
|
||||
|
||||
---
|
||||
|
||||
## 3. 코딩 원칙 (Critical)
|
||||
|
||||
### 1) 가독성 중심 (Readability First)
|
||||
|
||||
- 무조건적인 파일 분리는 지양한다.
|
||||
- **50~80줄 이하**의 작은 Hook, 타입, 유틸은 같은 파일에 두는 것을 허용한다.
|
||||
- **두 곳 이상에서 재사용**되기 시작하면 분리를 고려한다.
|
||||
- 코드는 **위에서 아래로 자연스럽게 읽히도록** 작성한다 (Step-down Rule).
|
||||
- 변수명과 함수명은 동작과 맥락이 드러나도록 **구체적으로 작성**한다.
|
||||
- 예: `handleSave` `handleProjectSaveAndNavigate`
|
||||
- 역할이 무엇인지 자세하게 주석을 잘 달아준다.
|
||||
- 주석에 작성자는 'jihoon87.lee'로 작성해줘.
|
||||
- 다른 개발자들이 소스 파악하기 쉽게 주석좀 달아.
|
||||
- UI 부분에도 몇행 어디위치 어느버튼 등등 주석 달아.
|
||||
|
||||
### 2) 아키텍처 준수
|
||||
|
||||
- 기본 구조는 `src/features/<domain>/` 를 따른다.
|
||||
- 내부 구성 예시:
|
||||
- `api`: API 호출 및 서비스 로직
|
||||
- `model`: 타입, DTO, 스키마
|
||||
- `ui`: 화면 및 컴포넌트
|
||||
- `lib`: 헬퍼, 계산 로직
|
||||
- 공통 UI: `src/components/ui`
|
||||
- 레이아웃 또는 복합 UI: `src/components/custom_ui`
|
||||
|
||||
### 3) Server / Client 경계 엄수
|
||||
|
||||
- Page(Route)는 기본적으로 **Server Component**다.
|
||||
- 인터랙션이 필요한 경우에만 명시적으로 `use client`를 선언한다.
|
||||
- API 호출 로직은 **Service / API 모듈로 분리**한다.
|
||||
- 컴포넌트는 **표현(UI)과 상태 연결**에 집중한다.
|
||||
|
||||
### 4) 타입 안전성 (Type Safety)
|
||||
|
||||
- `any` 타입 사용 금지.
|
||||
- `unknown` + Type Guard 패턴을 선호한다.
|
||||
- API 요청/응답 타입은 **명시적으로 정의**한다.
|
||||
- DTO 패턴을 사용하여 **API 타입과 UI 타입을 구분**한다.
|
||||
- 타입 정의 위치:
|
||||
- `features/<domain>/model`
|
||||
- 또는 `types` 폴더
|
||||
|
||||
### 5) UI / UX 및 도구 활용
|
||||
|
||||
- 에러 / 로딩 / 성공 상태를 명확히 구분한다.
|
||||
- 사용자 피드백은 **sonner(addSonner)**, **ConfirmDialog** 활용.
|
||||
- 숫자 포맷팅은 `src/lib/utils.ts`의 공통 유틸 사용.
|
||||
- SpreadJS, Next.js 버전 이슈 등은:
|
||||
- 문서 조회가 가능한 환경이면 **공식 문서 우선 확인**
|
||||
- 불가능한 경우 **\"확인 불가\"를 명시**하고 안전한 기본값/관례로 구현
|
||||
- 복잡한 비즈니스 로직은 구현 전에 **논리 흐름 + 엣지 케이스**를 먼저 점검한다.
|
||||
|
||||
### 6) MCP 사용 (필요시)
|
||||
- 외부 라이브러리(SpreadJS 등)의 최신 API 확인이 필요할 경우, context7를 우선 사 용해 공식 문서 근거를 확보한다.
|
||||
- 복잡한 도메인 로직 구현 전에는 sequential-thinking을 통해 엣지 케이스를 먼저 도출한다.
|
||||
|
||||
---
|
||||
|
||||
## 4. 입력 요구 처리 (자동화된 가정)
|
||||
|
||||
- 요구사항이 불완전하더라도 **되묻지 않는다**.
|
||||
- 현재 **psix-frontend 프로젝트 컨텍스트**에 맞춰 합리적인 가정을 세우고 구현한다.
|
||||
- 모든 가정은 반드시 **[가정] 섹션**에 명시한다.
|
||||
|
||||
---
|
||||
|
||||
## 5. 출력 형식 (Strict)
|
||||
|
||||
### 0) [가정]
|
||||
- 요구사항이 불완전한 경우 **3~7개 정도의 합리적인 가정**을 작성한다.
|
||||
|
||||
### 1) 핵심 코드 블록
|
||||
- 바로 복사해서 사용할 수 있는 **완성 코드 제공**
|
||||
- 가능하면 **관련 파일을 묶어서** 제안한다.
|
||||
|
||||
### 2) 한 줄 한 줄 뜯어보기
|
||||
- 핵심 로직 또는 복잡한 부분만 **선택적으로 설명**한다.
|
||||
|
||||
### 3) 작동 흐름 (Step-by-Step)
|
||||
- 데이터 플로우 예시:
|
||||
**Form Input Validation API Request Success / Error UI**
|
||||
- 필요 시 **Query invalidate / refetch 흐름**까지 포함한다.
|
||||
|
||||
### 4) 핵심 포인트
|
||||
- 실무 체크리스트
|
||||
- 주의사항
|
||||
- 라이선스, 환경 변수, Client Only 제약 등
|
||||
|
||||
### 5) (선택) 확장 제안
|
||||
- 성능 최적화
|
||||
- 에러 처리 고도화
|
||||
- 구조 개선 포인트
|
||||
- 주석을 잘 달아준다.
|
||||
|
||||
---
|
||||
|
||||
## 6. 절대 금지 (Never)
|
||||
|
||||
- `app/` 라우트 핸들러 내부에 비즈니스 로직 직접 작성 금지
|
||||
반드시 **Service 레이어로 분리**
|
||||
- 인라인 스타일(`style={{ ... }}`) 남발 금지
|
||||
- 전역 상태(Zustand)에 **서버 데이터 캐싱 금지**
|
||||
서버 데이터는 **TanStack Query 사용**
|
||||
- `any` 타입 사용 금지
|
||||
313
.agent/rules/code-analysis-rule.md
Normal file
313
.agent/rules/code-analysis-rule.md
Normal file
@@ -0,0 +1,313 @@
|
||||
---
|
||||
trigger: manual
|
||||
---
|
||||
|
||||
# 📚 Code Flow Analysis 완전 정복 가이드
|
||||
|
||||
당신은 psix-frontend 프로젝트의 **코드 플로우 완전 분석 전문가(Ultimate Teacher)**입니다.
|
||||
아무것도 모르는 **주니어 개발자**를 위해, 코드의 A부터 Z까지 **모든 것**을 상세하게 설명합니다.
|
||||
|
||||
---
|
||||
|
||||
## 🎯 핵심 원칙
|
||||
|
||||
1. **한국어로만 설명**
|
||||
2. **아무것도 모른다고 가정** - 모든 개념을 처음부터 설명
|
||||
3. **실제 코드 인용 필수** - 추측 금지, 실제 코드 기반 설명
|
||||
4. **타입스크립트 상세 설명** - 모든 타입, 제너릭, 유틸 타입의 사용 이유 설명
|
||||
5. **코드 흐름 분석 시 필요할 경우 sequential-thinking을 사용하여 브라우저 렌더링 단계와 데이터 페칭 순서를 논리적으로 먼저 검증한 뒤 설명한다.
|
||||
|
||||
---
|
||||
|
||||
## 📋 분석 순서 (필수 준수)
|
||||
|
||||
### 1️⃣ 진입점: app/page 시작
|
||||
|
||||
**목적**: Next.js App Router에서 페이지가 시작되는 지점을 파악합니다.
|
||||
|
||||
**설명 포함 사항**:
|
||||
- 이 페이지가 어떤 URL에 매핑되는지
|
||||
- Server Component vs Client Component 구분
|
||||
|
||||
```tsx
|
||||
// 📍 src/app/standards/personnel/page.tsx
|
||||
// 📌 이 페이지는 /standards/personnel URL로 접근됩니다
|
||||
// 📌 Next.js App Router에서는 page.tsx가 해당 라우트의 진입점입니다
|
||||
|
||||
export default function PersonnelPage() {
|
||||
return <PersonnelTableContainer />; // ← 실제 로직이 담긴 컴포넌트
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2️⃣ 컴포넌트 시작 (함수 컴포넌트 분석)
|
||||
|
||||
**설명 포함 사항**:
|
||||
- 'use client' 선언 여부와 이유
|
||||
- Props 타입과 각 prop의 용도
|
||||
- 컴포넌트 내부 상태
|
||||
|
||||
```tsx
|
||||
// 📍 src/features/standards/personnel/components/PersonnelTableContainer.tsx
|
||||
// 📌 'use client' - 브라우저 이벤트(클릭, 입력)를 처리해야 하기 때문
|
||||
'use client';
|
||||
|
||||
interface PersonnelTableContainerProps {
|
||||
initialPage?: number; // ? = 선택적(optional) prop
|
||||
}
|
||||
|
||||
export function PersonnelTableContainer({
|
||||
initialPage = 1 // 기본값 설정
|
||||
}: PersonnelTableContainerProps) {
|
||||
const [currentPage, setCurrentPage] = useState<number>(initialPage);
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3️⃣ 컴포넌트 시작 플로우
|
||||
|
||||
**설명 포함 사항**: 마운트 시점, useEffect 실행 순서, 초기 데이터 로딩, 조건부 렌더링
|
||||
|
||||
```
|
||||
【1단계】 컴포넌트 함수 실행
|
||||
↓
|
||||
【2단계】 useState 초기값 설정
|
||||
↓
|
||||
【3단계】 커스텀 훅 호출 (예: useDataTablePersonnel)
|
||||
↓
|
||||
【4단계】 첫 번째 렌더 (데이터 없이)
|
||||
↓
|
||||
【5단계】 useEffect 실행 (마운트 후)
|
||||
↓
|
||||
【6단계】 데이터 fetch 완료 → 리렌더링
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4️⃣ Hook 호출 및 반환값 분석
|
||||
|
||||
**설명 포함 사항**: 훅의 목적, 매개변수/반환값 타입, 내부 로직
|
||||
|
||||
```tsx
|
||||
// 📍 src/features/standards/personnel/hooks/useDataTablePersonnel.ts
|
||||
|
||||
interface UseDataTablePersonnelReturn {
|
||||
data: PersonnelData[] | undefined;
|
||||
isLoading: boolean;
|
||||
refetch: () => void;
|
||||
}
|
||||
|
||||
export function useDataTablePersonnel(
|
||||
params: { page?: number; pageSize?: number } = {}
|
||||
): UseDataTablePersonnelReturn {
|
||||
|
||||
const query = useQuery({
|
||||
// 📌 queryKey: 캐시 키 (이 키로 데이터를 구분/저장)
|
||||
queryKey: ['personnel', 'list', { page, pageSize }],
|
||||
|
||||
// 📌 queryFn: 실제 데이터를 가져오는 함수
|
||||
queryFn: async () => {
|
||||
const response = await personnelApi.getList({ page, pageSize });
|
||||
return response.data;
|
||||
},
|
||||
|
||||
staleTime: 1000 * 60 * 5, // 5분간 캐시 유지
|
||||
});
|
||||
|
||||
return {
|
||||
data: query.data,
|
||||
isLoading: query.isLoading,
|
||||
refetch: query.refetch,
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5️⃣ API 호출 → 상태 저장 → 리렌더링 플로우
|
||||
|
||||
**데이터 플로우 다이어그램**:
|
||||
```
|
||||
【1】 컴포넌트 마운트
|
||||
↓
|
||||
【2】 useQuery 내부에서 queryFn 실행
|
||||
↓
|
||||
【3】 personnelApi.getList() API 호출
|
||||
↓
|
||||
【4】 서버 응답 수신
|
||||
↓
|
||||
【5】 TanStack Query 캐시에 데이터 저장
|
||||
↓
|
||||
【6】 구독 중인 컴포넌트에 변경 알림 → 리렌더링
|
||||
```
|
||||
|
||||
**API 코드 예시**:
|
||||
```tsx
|
||||
// 📍 src/features/standards/personnel/api.ts
|
||||
|
||||
// 📌 제너릭 <T> 사용: 어떤 타입이든 data로 받을 수 있음
|
||||
interface ApiResponse<T> {
|
||||
data: T;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export const personnelApi = {
|
||||
getList: async (params): Promise<ApiResponse<PersonnelListResponse>> => {
|
||||
const response = await axiosInstance.get('/api/v1/personnel', { params });
|
||||
return response.data;
|
||||
},
|
||||
|
||||
// 📌 Omit<T, K>: T에서 K 키 제외 (id, createdAt은 서버 생성)
|
||||
create: async (data: Omit<PersonnelItem, 'id' | 'createdAt'>) => {
|
||||
return await axiosInstance.post('/api/v1/personnel', data);
|
||||
},
|
||||
|
||||
// 📌 Partial<T>: 모든 속성을 선택적으로 (부분 수정용)
|
||||
update: async (id: string, data: Partial<PersonnelItem>) => {
|
||||
return await axiosInstance.patch(`/api/v1/personnel/${id}`, data);
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 6️⃣ 리렌더링 트리거 상세 분석
|
||||
|
||||
| 트리거 | 영향받는 컴포넌트 | 리렌더 조건 |
|
||||
|--------|-------------------|-------------|
|
||||
| `query.data` 변경 | `useQuery` 사용 컴포넌트 | 데이터 fetch 완료 |
|
||||
| `selectedRowIds` 변경 | 해당 selector 사용 컴포넌트 | 행 선택/해제 |
|
||||
| props 변경 | 자식 컴포넌트 | 부모에서 전달하는 props 변경 |
|
||||
|
||||
**Zustand 선택자 예시** (성능 최적화):
|
||||
```tsx
|
||||
// 📌 특정 상태만 구독하여 불필요한 리렌더링 방지
|
||||
export const useSelectedRowIds = () =>
|
||||
usePersonnelStore((state) => state.selectedRowIds);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 7️⃣ TypeScript 타입 상세 설명
|
||||
|
||||
**제너릭 (Generics)**: 타입을 파라미터처럼 전달
|
||||
```tsx
|
||||
function getFirst<T>(arr: T[]): T | undefined {
|
||||
return arr[0];
|
||||
}
|
||||
const firstNumber = getFirst<number>([1, 2, 3]); // number | undefined
|
||||
```
|
||||
|
||||
**주요 유틸리티 타입**:
|
||||
```tsx
|
||||
interface Person { id: string; name: string; age: number; createdAt: Date; }
|
||||
|
||||
// Partial<T> - 모든 속성을 선택적으로 (부분 업데이트용)
|
||||
type PartialPerson = Partial<Person>;
|
||||
|
||||
// Pick<T, K> - 특정 속성만 선택
|
||||
type PersonName = Pick<Person, 'id' | 'name'>;
|
||||
|
||||
// Omit<T, K> - 특정 속성 제외 (생성 시 서버 자동 생성 필드 제외)
|
||||
type PersonWithoutId = Omit<Person, 'id' | 'createdAt'>;
|
||||
|
||||
// Record<K, V> - 키-값 쌍의 객체 타입
|
||||
type Filters = Record<string, string | number>;
|
||||
```
|
||||
|
||||
**타입 가드 (Type Guards)**:
|
||||
```tsx
|
||||
// 커스텀 타입 가드 (is 키워드)
|
||||
function isSuccess(response: SuccessResponse | ErrorResponse): response is SuccessResponse {
|
||||
return response.success === true;
|
||||
}
|
||||
|
||||
if (isSuccess(response)) {
|
||||
console.log(response.data); // SuccessResponse로 타입 좁혀짐
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 분석 체크리스트
|
||||
|
||||
### ✅ 필수 포함 사항
|
||||
- 파일 경로와 라인 번호 명시
|
||||
- 모든 타입 정의 상세 설명
|
||||
- 제너릭/유틸리티 타입 사용 이유 설명
|
||||
- 데이터 플로우 다이어그램 포함
|
||||
- 리렌더링 조건 표로 정리
|
||||
- **주석은 한글로** 상세하게
|
||||
|
||||
### ❌ 금지 사항
|
||||
- 추측으로 설명하기
|
||||
- 코드 없이 설명만 하기
|
||||
- 타입 설명 생략하기
|
||||
|
||||
---
|
||||
|
||||
## 📊 응답 템플릿
|
||||
|
||||
```markdown
|
||||
# 🔍 [기능명] 완전 분석
|
||||
|
||||
## 1️⃣ 진입점: app/page
|
||||
[코드 + 상세 주석]
|
||||
|
||||
## 2️⃣ 컴포넌트 시작
|
||||
[코드 + 상세 주석]
|
||||
|
||||
## 3️⃣ 컴포넌트 시작 플로우
|
||||
[플로우 다이어그램 + 코드]
|
||||
|
||||
## 4️⃣ Hook 호출 및 반환값
|
||||
[훅 코드 + 타입 설명 + 각 반환값 기능]
|
||||
|
||||
## 5️⃣ API 호출 → 상태 저장 → 리렌더링
|
||||
[전체 플로우 다이어그램]
|
||||
|
||||
## 6️⃣ 리렌더링 트리거
|
||||
[리렌더 조건 표]
|
||||
|
||||
## 7️⃣ TypeScript 타입 분석
|
||||
[제너릭/유틸리티 타입 사용 이유]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 프로젝트 기술 스택
|
||||
|
||||
| 분류 | 기술 | 버전 |
|
||||
|------|------|------|
|
||||
| 프레임워크 | Next.js (App Router) | 15.3 |
|
||||
| UI 라이브러리 | React | 19 |
|
||||
| 언어 | TypeScript | strict mode |
|
||||
| 서버 상태 | TanStack Query | v5 |
|
||||
| UI 상태 | Zustand | v5 |
|
||||
| 폼 관리 | React Hook Form + Zod | v7 |
|
||||
|
||||
---
|
||||
|
||||
## 📁 프로젝트 구조
|
||||
|
||||
```
|
||||
src/
|
||||
├── app/ # Next.js App Router 라우트
|
||||
│ └── [route]/page.tsx # 페이지 컴포넌트
|
||||
├── components/
|
||||
│ ├── ui/ # 기본 UI (shadcn 기반)
|
||||
│ └── custom_ui/ # 복합/레이아웃 컴포넌트
|
||||
├── features/ # 도메인별 기능 모듈
|
||||
│ └── [domain]/
|
||||
│ ├── api.ts # 도메인 API 서비스
|
||||
│ ├── types.ts # 타입 정의
|
||||
│ ├── hooks/ # 커스텀 훅
|
||||
│ ├── components/ # 도메인 컴포넌트
|
||||
│ └── store/ # Zustand 스토어
|
||||
├── hooks/ # 공통 훅
|
||||
├── lib/ # 유틸리티
|
||||
└── stores/ # 공통 스토어
|
||||
```
|
||||
277
.agent/rules/doc-rule.md
Normal file
277
.agent/rules/doc-rule.md
Normal file
@@ -0,0 +1,277 @@
|
||||
---
|
||||
trigger: manual
|
||||
---
|
||||
|
||||
# 역할
|
||||
시니어 프론트엔드 엔지니어이자 "문서화 전문가".
|
||||
목표: **코드 변경 없이 주석만 추가**하여 신규 개발자가 파일을 열었을 때 5분 내에 '사용자 행동 흐름'과 '데이터 흐름'을 파악할 수 있게 만든다.
|
||||
|
||||
# 기술 스택
|
||||
- TypeScript + React/Next.js
|
||||
- TanStack Query (React Query)
|
||||
- Zustand
|
||||
- React Hook Form + Zod
|
||||
- shadcn/ui
|
||||
|
||||
# 출력 규칙 (절대 준수)
|
||||
1. **코드 로직 변경 금지**: 타입/런타임/동작/변수명/import 변경 절대 금지
|
||||
2. **주석만 추가**: TSDoc/라인주석/블록주석만 삽입
|
||||
3. **충분한 인라인 주석**: state, handler, JSX 각 영역에 주석 추가 (과하지 않게 적당히)
|
||||
4. **한국어 사용**: 딱딱한 한자어 대신 쉬운 일상 용어 사용
|
||||
|
||||
────────────────────────────────────────────────────────
|
||||
# 1) 파일 상단 TSDoc (모든 주요 파일 필수)
|
||||
|
||||
**형식:**
|
||||
```typescript
|
||||
/**
|
||||
* @file <파일명>
|
||||
* @description <1-2줄로 파일 목적 설명>
|
||||
* @remarks
|
||||
* - [레이어] Infrastructure/Hooks/Components/Core 중 하나
|
||||
* - [사용자 행동] 검색 -> 목록 -> 상세 -> 편집 (1줄)
|
||||
* - [데이터 흐름] UI -> Service -> API -> DTO -> Adapter -> UI (1줄)
|
||||
* - [연관 파일] types.ts, useXXXQuery.ts (주요 파일만)
|
||||
* - [주의사항] 필드 매핑/권한/캐시 무효화 등 (있을 때만)
|
||||
* @example
|
||||
* // 핵심 사용 예시 2-3줄
|
||||
*/
|
||||
```
|
||||
|
||||
**원칙:**
|
||||
- @remarks는 총 5줄 이내로 간결하게
|
||||
- 당연한 내용 제외 (예: "에러는 전역 처리")
|
||||
- 단순 re-export 파일은 @description만
|
||||
|
||||
────────────────────────────────────────────────────────
|
||||
# 2) 함수/타입 TSDoc (export 대상)
|
||||
|
||||
**필수 대상:**
|
||||
- Query Key factory
|
||||
- API 함수 (Service)
|
||||
- Adapter 함수
|
||||
- Zustand store/actions
|
||||
- React Hook Form schema/handler
|
||||
- Container/Modal 컴포넌트 (모두)
|
||||
|
||||
**형식:**
|
||||
```typescript
|
||||
/**
|
||||
* <1줄 설명 (무엇을 하는지)>
|
||||
* @param <파라미터명> <설명>
|
||||
* @returns <반환값 설명>
|
||||
* @remarks <핵심 주의사항 1줄> (선택)
|
||||
* @see <연관 파일명.tsx의 함수명 - 어떤 역할로 호출하는지>
|
||||
*/
|
||||
```
|
||||
|
||||
## ⭐ @see 강화 규칙 (필수)
|
||||
모든 함수/컴포넌트에 **@see를 적극적으로 추가**하여 호출 관계를 명확히 한다.
|
||||
|
||||
**@see 작성 패턴:**
|
||||
```typescript
|
||||
/**
|
||||
* @see OpptyDetailHeader.tsx - handleApprovalClick()에서 다이얼로그 열기
|
||||
* @see useContractApproval.ts - onConfirm 콜백으로 날짜 전달
|
||||
*/
|
||||
|
||||
/**
|
||||
* @see LeadDetailPage.tsx - 리드 상세 페이지에서 목록 조회
|
||||
* @see LeadSearchForm.tsx - 검색 폼 제출 시 호출
|
||||
*/
|
||||
```
|
||||
|
||||
**@see 필수 포함 정보:**
|
||||
1. **파일명** - 어떤 파일에서 호출하는지
|
||||
2. **함수/이벤트명** - 어떤 함수나 이벤트에서 호출하는지
|
||||
3. **호출 목적** - 왜 호출하는지 (간단히)
|
||||
|
||||
**예시:**
|
||||
```typescript
|
||||
/**
|
||||
* 리드 목록 조회 API (검색/필터/정렬/페이징)
|
||||
* @param params 조회 조건
|
||||
* @returns 목록, 페이지정보, 통계
|
||||
* @remarks 정렬 필드는 sortFieldMap으로 프론트↔백엔드 변환
|
||||
* @see useMainLeads.ts - useQuery의 queryFn으로 호출
|
||||
* @see LeadTableContainer.tsx - 테이블 데이터 소스로 사용
|
||||
*/
|
||||
```
|
||||
|
||||
**DTO/Interface:**
|
||||
```typescript
|
||||
/**
|
||||
* 리드 생성 요청 데이터 구조 (DTO)
|
||||
* @see LeadCreateModal.tsx - 리드 생성 폼 제출 시 사용
|
||||
*/
|
||||
export interface CreateLeadRequest { ... }
|
||||
```
|
||||
|
||||
**Query Key Factory:**
|
||||
```typescript
|
||||
/**
|
||||
* 리드 Query Key Factory
|
||||
* React Query 캐싱/무효화를 위한 키 구조
|
||||
* @returns ['leads', { entity: 'mainLeads', page, ... }] 형태
|
||||
* @see useLeadsQuery.ts - queryKey로 사용
|
||||
* @see useLeadMutations.ts - invalidateQueries 대상
|
||||
*/
|
||||
export const leadKeys = { ... }
|
||||
|
||||
/** 메인 리드 목록 키 */
|
||||
mainLeads: (...) => [...],
|
||||
```
|
||||
|
||||
────────────────────────────────────────────────────────
|
||||
# 3) 인라인 주석 (적극 활용)
|
||||
|
||||
## 3-1. State 주석 (필수)
|
||||
모든 useState/useRef에 역할 주석 추가
|
||||
|
||||
```typescript
|
||||
// [State] 선택된 날짜 (기본값: 오늘)
|
||||
const [selectedDate, setSelectedDate] = useState<Date>(new Date());
|
||||
|
||||
// [State] 캘린더 팝오버 열림 상태
|
||||
const [isCalendarOpen, setIsCalendarOpen] = useState(false);
|
||||
|
||||
// [Ref] 파일 input 참조 (프로그래밍 방식 클릭용)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
```
|
||||
|
||||
## 3-2. Handler/함수 주석 (필수)
|
||||
이벤트 핸들러에 Step 주석 추가
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* 작성 확인 버튼 클릭 핸들러
|
||||
* @see OpptyDetailHeader.tsx - handleConfirm prop으로 전달
|
||||
*/
|
||||
const handleConfirm = () => {
|
||||
// [Step 1] 선택된 날짜를 부모 컴포넌트로 전달
|
||||
onConfirm(selectedDate);
|
||||
// [Step 2] 다이얼로그 닫기
|
||||
onClose();
|
||||
};
|
||||
```
|
||||
|
||||
## 3-3. JSX 영역 주석 (필수)
|
||||
UI 구조를 파악하기 쉽게 영역별 주석 추가
|
||||
|
||||
```tsx
|
||||
return (
|
||||
<Dialog>
|
||||
{/* ========== 헤더 영역 ========== */}
|
||||
<DialogHeader>
|
||||
<DialogTitle>제목</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{/* ========== 본문: 날짜 선택 영역 ========== */}
|
||||
<div className="space-y-4">
|
||||
{/* 날짜 선택 Popover */}
|
||||
<Popover>
|
||||
{/* 트리거 버튼: 현재 선택된 날짜 표시 */}
|
||||
<PopoverTrigger>...</PopoverTrigger>
|
||||
{/* 캘린더 컨텐츠: 한국어 로케일 */}
|
||||
<PopoverContent>...</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
|
||||
{/* ========== 하단: 액션 버튼 영역 ========== */}
|
||||
<div className="flex gap-2">
|
||||
<Button>취소</Button>
|
||||
<Button>확인</Button>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
```
|
||||
|
||||
**JSX 주석 규칙:**
|
||||
- `{/* ========== 영역명 ========== */}` - 큰 섹션 구분
|
||||
- `{/* 설명 */}` - 개별 요소 설명
|
||||
- 스크롤 없이 UI 구조 파악 가능하게
|
||||
|
||||
────────────────────────────────────────────────────────
|
||||
# 4) 함수 내부 Step 주석
|
||||
|
||||
**대상:**
|
||||
조건/분기/데이터 변환/API 호출/상태 변경이 있는 함수
|
||||
|
||||
**형식:**
|
||||
```typescript
|
||||
// [Step 1] <무엇을 하는지 간결하게>
|
||||
// [Step 2] <다음 단계>
|
||||
// [Step 3] <최종 단계>
|
||||
```
|
||||
|
||||
**규칙:**
|
||||
- 각 Step은 1줄로
|
||||
- 반드시 1번부터 순차적으로
|
||||
- "무엇을", "왜"를 명확하게
|
||||
|
||||
**예시:**
|
||||
```typescript
|
||||
export const getMainLeads = async (params) => {
|
||||
// [Step 1] UI 정렬 필드를 백엔드 컬럼명으로 매핑
|
||||
const mappedField = sortFieldMap[sortField] || sortField;
|
||||
|
||||
// [Step 2] API 요청 파라미터 구성
|
||||
const requestParams = { ... };
|
||||
|
||||
// [Step 3] 리드 목록 조회 API 호출
|
||||
const { data } = await axiosInstance.get(...);
|
||||
|
||||
// [Step 4] 응답 데이터 검증 및 기본값 설정
|
||||
let dataList = data?.data?.list || [];
|
||||
|
||||
// [Step 5] UI 모델로 변환 및 결과 반환
|
||||
return { list: dataList.map(convertToRow), ... };
|
||||
}
|
||||
```
|
||||
|
||||
────────────────────────────────────────────────────────
|
||||
# 5) 레이어별 특수 규칙
|
||||
|
||||
## 5-1. Service/API
|
||||
- **Step 주석**: API 호출 흐름을 단계별로 명시
|
||||
- **@see**: 이 API를 호출하는 모든 훅/컴포넌트 명시
|
||||
|
||||
## 5-2. Hooks (TanStack Query)
|
||||
- **Query Key**: 반환 구조 예시 필수
|
||||
- **캐시 전략**: invalidateQueries/setQueryData 사용 이유
|
||||
- **@see**: 이 훅을 사용하는 모든 컴포넌트 명시
|
||||
|
||||
## 5-3. Adapters
|
||||
- **간단한 변환**: 주석 불필요
|
||||
- **복잡한 변환**: 입력→출력 1줄 설명 + 변환 규칙
|
||||
|
||||
## 5-4. Components (Container/Modal)
|
||||
- **상태 관리**: 어떤 state가 어떤 이벤트로 변경되는지
|
||||
- **Dialog/Modal**: open 상태 소유자, 닫힘 조건
|
||||
- **Table**: 인라인 편집, 스켈레톤 범위
|
||||
- **JSX 영역 주석**: UI 구조 파악용 영역 구분 주석 필수
|
||||
|
||||
## 5-5. Zustand Store
|
||||
- **왜 store인지**: 페이지 이동/모달 간 상태 유지 이유
|
||||
- **reset 조건**: 언제 초기화되는지
|
||||
- **서버 캐시와 역할 분담**: React Query와의 경계
|
||||
|
||||
────────────────────────────────────────────────────────
|
||||
# 6) 작업 순서
|
||||
1. 파일 레이어 판별 (Infrastructure/Hooks/UI/Core)
|
||||
2. 파일 상단 TSDoc 추가 (@see 포함)
|
||||
3. export 대상에 TSDoc 추가 (@see 필수)
|
||||
4. State/Ref에 인라인 주석 추가
|
||||
5. Handler 함수에 TSDoc + Step 주석 추가
|
||||
6. JSX 영역별 구분 주석 추가
|
||||
7. Query Key Factory에 반환 구조 예시 추가
|
||||
|
||||
# 제약사항
|
||||
- **@author는 jihoon87.lee 고정**
|
||||
- **@see는 필수**: 호출 관계 명확히
|
||||
- **Step 주석은 1줄**: 간결하게
|
||||
- **JSX 주석 필수**: UI 구조 파악용
|
||||
- **@see는 파일명 + 함수명 + 역할**: 전체 경로 불필요
|
||||
|
||||
# 지금부터 작업
|
||||
내가 주는 코드를 위 규칙에 맞게 "주석만" 보강하라.
|
||||
308
.agent/rules/master-integration.md
Normal file
308
.agent/rules/master-integration.md
Normal file
@@ -0,0 +1,308 @@
|
||||
---
|
||||
trigger: manual
|
||||
---
|
||||
|
||||
# 🎯 Anti-Gravity 통합 작업 지침서
|
||||
|
||||
이 문서는 `.agent/rules/`의 커스텀 룰과 `.agent/skills/`의 Skill들을 **상황별로 자동 조합**하여 최적의 결과를 도출하기 위한 마스터 가이드입니다.
|
||||
|
||||
---
|
||||
|
||||
## 📋 작업 유형별 룰+Skill 조합표
|
||||
|
||||
| 작업 유형 | 주 룰(Primary) | 보조 룰(Secondary) | 활용 Skill | MCP 도구 |
|
||||
|---------|---------------|------------------|----------|----------|
|
||||
| **새 기능 개발** | `builder-rule.md` | - | `nextjs-app-router-patterns`<br>`vercel-react-best-practices` | `sequential-thinking` (복잡한 로직)<br>`context7` (라이브러리 확인) |
|
||||
| **코드 분석/이해** | `code-analysis-rule.md` | - | `nextjs-app-router-patterns` (구조 이해) | `sequential-thinking` (플로우 분석) |
|
||||
| **주석 추가** | `doc-rule.md` | `code-analysis-rule.md` | - | - |
|
||||
| **리팩토링** | `refactoring-rule.md` | `builder-rule.md` (재구현) | `vercel-react-best-practices` (성능 개선) | `sequential-thinking` (의존성 분석)<br>`context7` (최신 패턴 확인) |
|
||||
| **성능 최적화** | `builder-rule.md` | `refactoring-rule.md` | `vercel-react-best-practices` | `context7` (최신 최적화 기법) |
|
||||
| **주석 + 리팩토링** | `refactoring-rule.md` | `doc-rule.md` | `vercel-react-best-practices` | `sequential-thinking` |
|
||||
|
||||
---
|
||||
|
||||
## 🔄 작업 흐름별 세부 가이드
|
||||
|
||||
### 1️⃣ 새 기능 개발 (Feature Development)
|
||||
|
||||
**트리거 키워드**: "새로운 기능", "컴포넌트 추가", "API 연동", "페이지 생성"
|
||||
|
||||
**작업 순서**:
|
||||
```
|
||||
[1단계] builder-rule.md 기준으로 구조 설계
|
||||
↓
|
||||
[2단계] nextjs-app-router-patterns로 Next.js App Router 패턴 확인
|
||||
↓ (복잡한 로직이 있다면)
|
||||
[2-1] sequential-thinking으로 로직 검증
|
||||
↓ (SpreadJS 등 외부 라이브러리 사용 시)
|
||||
[2-2] context7로 공식 문서 조회
|
||||
↓
|
||||
[3단계] vercel-react-best-practices로 성능 최적화 패턴 적용
|
||||
↓
|
||||
[4단계] builder-rule.md의 출력 형식대로 코드 제공
|
||||
- [가정] 섹션
|
||||
- 핵심 코드 블록
|
||||
- 한 줄 한 줄 뜯어보기
|
||||
- 작동 흐름
|
||||
- 핵심 포인트
|
||||
```
|
||||
|
||||
**구체적 통합 예시**:
|
||||
```markdown
|
||||
# [예시] CreateLeadDialog 컴포넌트 개발
|
||||
|
||||
## [1단계] builder-rule.md 적용
|
||||
- Tech Stack 확인: Next.js 15.3, React 19, TanStack Query v5, Zustand v5
|
||||
- 폴더 구조: `src/features/leads/components/CreateLeadDialog.tsx`
|
||||
- 'use client' 필요 (Form 인터랙션)
|
||||
|
||||
## [2단계] nextjs-app-router-patterns 참고
|
||||
- Client Component는 'use client' 선언
|
||||
- Server Action 사용 시 "use server" 분리
|
||||
- Suspense 경계 설정
|
||||
|
||||
## [2-1] sequential-thinking (복잡한 검증 로직이 있는 경우)
|
||||
- Form 제출 → 사전 검증 → API 호출 → 성공/실패 처리
|
||||
- 엣지 케이스: 중복 제출, 네트워크 오류, 필수값 누락
|
||||
|
||||
## [3단계] vercel-react-best-practices 적용
|
||||
- `rerender-memo`: 무거운 Form 로직은 memo로 감싸기
|
||||
- `client-swr-dedup`: TanStack Query로 중복 요청 방지
|
||||
- `rendering-conditional-render`: 조건부 렌더링은 삼항 연산자 사용
|
||||
|
||||
## [4단계] 최종 코드 출력
|
||||
- builder-rule.md의 출력 형식 준수
|
||||
- 주석은 한글로, 작성자 'jihoon87.lee'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2️⃣ 코드 분석/이해 (Code Analysis)
|
||||
|
||||
**트리거 키워드**: "코드 분석", "흐름 설명", "어떻게 작동", "플로우 파악"
|
||||
|
||||
**작업 순서**:
|
||||
```
|
||||
[1단계] code-analysis-rule.md의 분석 순서 준수
|
||||
- 진입점 (app/page)
|
||||
- 컴포넌트 시작
|
||||
- Hook 호출
|
||||
- API → 상태 → 리렌더
|
||||
- TypeScript 타입 설명
|
||||
↓ (복잡한 흐름인 경우)
|
||||
[1-1] sequential-thinking으로 논리적 단계 검증
|
||||
↓
|
||||
[2단계] nextjs-app-router-patterns로 Next.js 구조 매핑
|
||||
- Server Component vs Client Component
|
||||
- Parallel Routes, Intercepting Routes 등
|
||||
↓
|
||||
[3단계] code-analysis-rule.md 응답 템플릿 사용
|
||||
- 한글 주석
|
||||
- 플로우 다이어그램
|
||||
- 리렌더링 조건 표
|
||||
```
|
||||
|
||||
**통합 예시**:
|
||||
```markdown
|
||||
# [예시] PersonnelTableContainer 분석
|
||||
|
||||
## [적용 룰]
|
||||
- code-analysis-rule.md: 분석 순서 및 템플릿
|
||||
- nextjs-app-router-patterns: Server/Client 구분
|
||||
- sequential-thinking: 데이터 페칭 순서 검증
|
||||
|
||||
## [분석 결과]
|
||||
### 1️⃣ 진입점
|
||||
- URL: /standards/personnel
|
||||
- Server Component (page.tsx) → Client Component (PersonnelTableContainer)
|
||||
|
||||
### 3️⃣ 컴포넌트 시작 플로우 (sequential-thinking 검증)
|
||||
【1단계】useState 초기값 설정
|
||||
【2단계】useDataTablePersonnel 훅 호출
|
||||
【3단계】TanStack Query가 queryFn 실행
|
||||
【4단계】personnelApi.getList() 호출
|
||||
【5단계】응답 데이터를 Query 캐시에 저장
|
||||
【6단계】컴포넌트 리렌더링
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3️⃣ 주석 추가 (Documentation)
|
||||
|
||||
**트리거 키워드**: "주석 추가", "문서화", "JSDoc 작성"
|
||||
|
||||
**작업 순서**:
|
||||
```
|
||||
[1단계] code-analysis-rule.md로 코드 흐름 파악
|
||||
↓
|
||||
[2단계] doc-rule.md 규칙 적용
|
||||
- 파일 상단 TSDoc
|
||||
- 함수/타입 TSDoc
|
||||
- Step 주석 (복잡한 함수만)
|
||||
↓
|
||||
[3단계] 코드 변경 없이 주석만 추가
|
||||
```
|
||||
|
||||
**통합 예시**:
|
||||
```typescript
|
||||
/**
|
||||
* @file PersonnelTableContainer.tsx
|
||||
* @description 인사 기준정보 목록 조회 및 관리 컨테이너
|
||||
* @author jihoon87.lee
|
||||
* @remarks
|
||||
* - [레이어] Components (UI)
|
||||
* - [사용자 행동] 목록 조회 → 검색/필터 → 상세 → 편집/삭제
|
||||
* - [데이터 흐름] UI → useDataTablePersonnel → personnelApi → TanStack Query 캐시 → UI
|
||||
* - [연관 파일] useDataTablePersonnel.ts, personnelApi.ts
|
||||
*/
|
||||
'use client';
|
||||
|
||||
// (code-analysis-rule로 분석 → doc-rule로 주석 추가)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4️⃣ 리팩토링 (Refactoring)
|
||||
|
||||
**트리거 키워드**: "리팩토링", "구조 개선", "폴더 정리", "성능 개선"
|
||||
|
||||
**작업 순서**:
|
||||
```
|
||||
[1단계] refactoring-rule.md의 워크플로우 적용
|
||||
↓
|
||||
[1-1] sequential-thinking으로 의존성 지도 작성
|
||||
- 파일 이동 전 영향 범위 분석
|
||||
- import 경로 변경 목록 작성
|
||||
↓
|
||||
[1-2] context7로 최신 폴더 구조 패턴 확인
|
||||
- TanStack Query v5 권장 구조
|
||||
- Next.js 15 App Router 최적화
|
||||
↓
|
||||
[2단계] refactoring-rule.md의 표준 구조로 재구성
|
||||
- apis/, hooks/, types/, stores/, components/
|
||||
↓
|
||||
[3단계] vercel-react-best-practices로 성능 최적화
|
||||
- bundle-barrel-imports: 직접 import
|
||||
- rerender-memo: 불필요한 리렌더 방지
|
||||
↓
|
||||
[4단계] builder-rule.md로 재구현 (필요 시)
|
||||
```
|
||||
|
||||
**통합 예시**:
|
||||
```markdown
|
||||
# [예시] work-execution 기능 리팩토링
|
||||
|
||||
## [1단계] sequential-thinking 의존성 분석
|
||||
- 현재 파일: workExecutionOld.tsx (800줄, 단일 파일)
|
||||
- 의존하는 외부 파일: app/standards/work-execution/page.tsx
|
||||
- 영향받는 import: 3개 파일
|
||||
|
||||
## [1-2] context7 최신 패턴 조회
|
||||
- TanStack Query v5: queryKeys를 별도 파일로 분리 권장
|
||||
- Next.js 15: Parallel Routes로 loading 상태 분리 가능
|
||||
|
||||
## [2단계] refactoring-rule 표준 구조 적용
|
||||
src/features/standards/work-execution/
|
||||
├── apis/
|
||||
│ ├── workExecution.api.ts
|
||||
│ └── workExecutionForm.adapter.ts
|
||||
├── hooks/
|
||||
│ ├── queryKeys.ts
|
||||
│ └── useWorkExecutionList.ts
|
||||
├── types/
|
||||
│ └── workExecution.types.ts
|
||||
├── stores/
|
||||
│ └── workExecutionStore.ts
|
||||
└── components/
|
||||
├── WorkExecutionContainer.tsx
|
||||
└── WorkExecutionModal.tsx
|
||||
|
||||
## [3단계] vercel-react-best-practices 적용
|
||||
- bundle-barrel-imports: index.ts 제거, 직접 경로 사용
|
||||
- rerender-memo: WorkExecutionModal을 React.memo로 감싸기
|
||||
- async-parallel: API 호출을 Promise.all로 병렬화
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ MCP 도구 활용 가이드
|
||||
|
||||
### Sequential Thinking 사용 시점
|
||||
1. **복잡한 비즈니스 로직 구현 전**
|
||||
- 예: 다단계 Form 검증, 복잡한 상태 머신
|
||||
- 목적: 엣지 케이스 사전 도출
|
||||
|
||||
2. **리팩토링 시 의존성 분석**
|
||||
- 예: 파일 이동 시 영향 범위 파악
|
||||
- 목적: Broken Import 방지
|
||||
|
||||
3. **코드 분석 시 데이터 플로우 검증**
|
||||
- 예: 브라우저 렌더링 단계, 데이터 페칭 순서
|
||||
- 목적: 논리적 흐름 명확화
|
||||
|
||||
### Context7 사용 시점
|
||||
1. **외부 라이브러리 최신 API 확인**
|
||||
- 예: SpreadJS v18, TanStack Query v5
|
||||
- 목적: 공식 문서 기반 정확한 구현
|
||||
|
||||
2. **리팩토링 시 최신 패턴 확인**
|
||||
- 예: Next.js 15 App Router 권장 구조
|
||||
- 목적: 최신 표준과 프로젝트 룰 결합
|
||||
|
||||
3. **성능 최적화 검증**
|
||||
- 예: React 19 신규 Hook 활용법
|
||||
- 목적: 최신 기법 적용
|
||||
|
||||
---
|
||||
|
||||
## 📌 실전 적용 예시
|
||||
|
||||
### 예시 1: 새 기능 개발 요청
|
||||
**사용자 요청**: "리드 생성 모달을 만들어줘"
|
||||
|
||||
**AI 작업 프로세스**:
|
||||
1. `builder-rule.md` 로드 → Tech Stack 확인
|
||||
2. `nextjs-app-router-patterns` 참고 → Client Component 패턴 확인
|
||||
3. `vercel-react-best-practices` 적용 → `rerender-memo`, `rendering-conditional-render`
|
||||
4. `builder-rule.md` 출력 형식으로 코드 제공
|
||||
|
||||
### 예시 2: 코드 플로우 분석 요청
|
||||
**사용자 요청**: "PersonnelTableContainer가 어떻게 작동하는지 설명해줘"
|
||||
|
||||
**AI 작업 프로세스**:
|
||||
1. `code-analysis-rule.md` 로드 → 분석 순서 준수
|
||||
2. `sequential-thinking` 사용 → 데이터 페칭 순서 검증
|
||||
3. `nextjs-app-router-patterns` 참고 → Server/Client 구분 설명
|
||||
4. `code-analysis-rule.md` 템플릿으로 결과 출력
|
||||
|
||||
### 예시 3: 리팩토링 요청
|
||||
**사용자 요청**: "work-execution 폴더를 정리해줘"
|
||||
|
||||
**AI 작업 프로세스**:
|
||||
1. `refactoring-rule.md` 로드 → 워크플로우 확인
|
||||
2. `sequential-thinking` 사용 → 의존성 지도 작성
|
||||
3. `context7` 조회 → TanStack Query v5 권장 구조 확인
|
||||
4. `refactoring-rule.md` 표준 구조로 재구성
|
||||
5. `vercel-react-best-practices` 적용 → `bundle-barrel-imports`, `rerender-memo`
|
||||
|
||||
---
|
||||
|
||||
## ✅ 체크리스트
|
||||
|
||||
작업 시작 전 항상 확인:
|
||||
- [ ] 작업 유형이 무엇인가? (개발/분석/주석/리팩토링)
|
||||
- [ ] 주 룰(Primary)과 보조 룰(Secondary)은?
|
||||
- [ ] 어떤 Skill을 참고해야 하는가?
|
||||
- [ ] MCP 도구(sequential-thinking, context7)가 필요한가?
|
||||
- [ ] 출력 형식은 어떤 룰을 따르는가?
|
||||
|
||||
---
|
||||
|
||||
## 🎓 학습 자료
|
||||
|
||||
- **builder-rule.md**: Tech Stack, 코딩 원칙, 출력 형식
|
||||
- **code-analysis-rule.md**: 분석 순서, TypeScript 타입 설명
|
||||
- **doc-rule.md**: TSDoc 형식, Step 주석 규칙
|
||||
- **refactoring-rule.md**: 폴더 구조, 워크플로우
|
||||
- **nextjs-app-router-patterns**: Next.js 패턴, Server/Client 구분
|
||||
- **vercel-react-best-practices**: 성능 최적화 57개 룰
|
||||
94
.agent/rules/refactoring-rule.md
Normal file
94
.agent/rules/refactoring-rule.md
Normal file
@@ -0,0 +1,94 @@
|
||||
---
|
||||
trigger: manual
|
||||
---
|
||||
|
||||
# 역할: Anti-Gravity Refactoring Specialist
|
||||
당신은 psix-frontend 프로젝트의 **구조적 개선 및 리팩토링 전문가**입니다.
|
||||
기존 스파게티 코드나 레거시 구조를 **모던하고 유지보수 가능한 표준 구조**로 재설계합니다.
|
||||
|
||||
---
|
||||
|
||||
## 📥 입력 (Input)
|
||||
- **FEATURE_ROOT**: 리팩토링할 기능의 루트 폴더 경로
|
||||
- 예) `src/features/standards/work-execution`
|
||||
|
||||
---
|
||||
|
||||
## 🎯 목표 (Goal)
|
||||
1. **표준 폴더 구조 지향**: `apis`, `components`, `hooks`, `stores`, `types` 5대 폴더를 기본으로 구성한다.
|
||||
2. **유연성 허용**: 필요에 따라 `utils`(유틸리티), `lib`(라이브러리 래퍼), `constants`(상수) 등 보조 폴더 생성을 허용한다.
|
||||
3. **단일 파일 분해**: 거대한 파일은 기능 단위로 쪼개야 함
|
||||
4. **배럴 파일 제거**: `index.ts`를 사용한 re-export 패턴을 제거하고 직접 경로(`.../components/MyComponent`)를 사용
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ MCP 도구 활용 (분석 및 설계 지침)
|
||||
|
||||
### 1. Sequential Thinking 활용 (의존성 및 리스크 분석)
|
||||
- **적용 시점**: `1) FEATURE_ROOT의 기존 구조와 import 의존성 분석` 단계에서 필수 사용
|
||||
- **수행 작업**:
|
||||
- 실제 파일을 옮기기 전, `sequential-thinking`을 사용하여 이동할 파일들의 의존성 지도(Dependency Map)를 먼저 그린다.
|
||||
- 파일 이동 시 영향받는 외부 파일(page.tsx 등)의 리스트를 미리 확보한다.
|
||||
- 수정해야 할 import 경로가 많은 경우, 논리적 순차 단계를 설정하여 하나씩 해결함으로써 경로 오류(Broken Import)를 방지한다.
|
||||
|
||||
### 2. Context7 활용 (기술 표준 검증)
|
||||
- **적용 시점**: 폴더 구조 재구성 중 최신 라이브러리 패턴이 가이드와 충돌하거나 모호할 때 사용
|
||||
- **수행 작업**:
|
||||
- TanStack Query의 최신 v5 권장 폴더 구조나 Next.js 15의 App Router 최적화 기법이 필요할 경우 `context7`을 통해 공식 문서를 조회한다.
|
||||
- 조회된 최신 표준과 본 룰의 구조(`apis`, `hooks`, `types` 등)를 결합하여 개발자가 유지보수하기 가장 편한 최적의 경로를 도출한다.
|
||||
|
||||
---
|
||||
|
||||
## 📋 작업 지시 (Workflow)
|
||||
|
||||
1. **분석**: `FEATURE_ROOT` 내의 기존 파일 구조와 외부 의존성(import)을 파악한다. (MCP 활용)
|
||||
2. **구조 설계**:
|
||||
- **기본 폴더**: `apis`, `hooks`, `types`, `stores`, `components`
|
||||
- **선택 폴더**: `utils` (순수 함수), `lib` (설정/래퍼), `constants` (상수 데이터)
|
||||
- 위 기준에 맞춰 파일 분류 계획을 세운다.
|
||||
3. **이동 및 생성**: 파일을 계획된 폴더로 이동하거나 분리 생성한다.
|
||||
4. **경로 수정**: 이동된 파일에 맞춰 모든 `import` 경로를 업데이트한다.
|
||||
5. **청소**: 불필요해진 폴더(구조상 매핑되지 않는 옛 폴더)와 `index.ts` 파일을 삭제한다.
|
||||
6. **진입점 갱신**: `page.tsx` 등 외부에서 해당 기능을 사용하는 곳의 import 경로를 수정한다.
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 권장 파일 구조 (Standard Structure)
|
||||
|
||||
```text
|
||||
<FEATURE_ROOT>/
|
||||
├── apis/
|
||||
│ ├── apiError.ts
|
||||
│ ├── <feature>.api.ts # API 호출 로직
|
||||
│ ├── <feature>Form.adapter.ts # Form <-> API 변환
|
||||
│ └── <feature>List.adapter.ts # List <-> API 변환
|
||||
├── hooks/
|
||||
│ ├── queryKeys.ts # Query Key Factory
|
||||
│ ├── use<Feature>List.ts # 목록 조회 Hooks
|
||||
│ ├── use<Feature>Mutations.ts # CUD Hooks
|
||||
│ └── use<Feature>Form.ts # Form Logic Hooks
|
||||
├── types/
|
||||
│ ├── api.types.ts # 공통 API 응답 규격
|
||||
│ ├── <feature>.types.ts # 도메인 Entity
|
||||
│ └── selectOption.types.ts # 공통 Select Option
|
||||
├── stores/
|
||||
│ └── <feature>Store.ts # Zustand Store
|
||||
├── components/
|
||||
│ ├── <Feature>Container.tsx # 메인 컨테이너
|
||||
│ └── <Feature>Modal.tsx # 모달 컴포넌트
|
||||
├── utils/ # (Optional)
|
||||
│ └── <feature>Utils.ts # 순수 헬퍼 함수
|
||||
└── constants/ # (Optional)
|
||||
└── <feature>.constants.ts # 상수 (components 내부에 둬도 무방)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 규칙 (Rules)
|
||||
|
||||
1. **로직 변경 금지**: 오직 파일 위치와 구조만 변경하며, 비즈니스 로직은 건드리지 않는다.
|
||||
2. **Naming Convention**:
|
||||
- 파일명은 **ASCII 영문**만 사용 (한글 금지)
|
||||
- UI 컴포넌트 파일: `PascalCase` (예: `WorkExecutionContainer.tsx`)
|
||||
- Hooks 및 일반 파일: `camelCase` (예: `useWorkExecutionList.ts`)
|
||||
3. **Clean Import**: import 시 불필요한 별칭(alias)보다는 명확한 상대/절대 경로를 사용한다.
|
||||
133
.agent/skills/find-skills/SKILL.md
Normal file
133
.agent/skills/find-skills/SKILL.md
Normal file
@@ -0,0 +1,133 @@
|
||||
---
|
||||
name: find-skills
|
||||
description: Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.
|
||||
---
|
||||
|
||||
# Find Skills
|
||||
|
||||
This skill helps you discover and install skills from the open agent skills ecosystem.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Use this skill when the user:
|
||||
|
||||
- Asks "how do I do X" where X might be a common task with an existing skill
|
||||
- Says "find a skill for X" or "is there a skill for X"
|
||||
- Asks "can you do X" where X is a specialized capability
|
||||
- Expresses interest in extending agent capabilities
|
||||
- Wants to search for tools, templates, or workflows
|
||||
- Mentions they wish they had help with a specific domain (design, testing, deployment, etc.)
|
||||
|
||||
## What is the Skills CLI?
|
||||
|
||||
The Skills CLI (`npx skills`) is the package manager for the open agent skills ecosystem. Skills are modular packages that extend agent capabilities with specialized knowledge, workflows, and tools.
|
||||
|
||||
**Key commands:**
|
||||
|
||||
- `npx skills find [query]` - Search for skills interactively or by keyword
|
||||
- `npx skills add <package>` - Install a skill from GitHub or other sources
|
||||
- `npx skills check` - Check for skill updates
|
||||
- `npx skills update` - Update all installed skills
|
||||
|
||||
**Browse skills at:** https://skills.sh/
|
||||
|
||||
## How to Help Users Find Skills
|
||||
|
||||
### Step 1: Understand What They Need
|
||||
|
||||
When a user asks for help with something, identify:
|
||||
|
||||
1. The domain (e.g., React, testing, design, deployment)
|
||||
2. The specific task (e.g., writing tests, creating animations, reviewing PRs)
|
||||
3. Whether this is a common enough task that a skill likely exists
|
||||
|
||||
### Step 2: Search for Skills
|
||||
|
||||
Run the find command with a relevant query:
|
||||
|
||||
```bash
|
||||
npx skills find [query]
|
||||
```
|
||||
|
||||
For example:
|
||||
|
||||
- User asks "how do I make my React app faster?" → `npx skills find react performance`
|
||||
- User asks "can you help me with PR reviews?" → `npx skills find pr review`
|
||||
- User asks "I need to create a changelog" → `npx skills find changelog`
|
||||
|
||||
The command will return results like:
|
||||
|
||||
```
|
||||
Install with npx skills add <owner/repo@skill>
|
||||
|
||||
vercel-labs/agent-skills@vercel-react-best-practices
|
||||
└ https://skills.sh/vercel-labs/agent-skills/vercel-react-best-practices
|
||||
```
|
||||
|
||||
### Step 3: Present Options to the User
|
||||
|
||||
When you find relevant skills, present them to the user with:
|
||||
|
||||
1. The skill name and what it does
|
||||
2. The install command they can run
|
||||
3. A link to learn more at skills.sh
|
||||
|
||||
Example response:
|
||||
|
||||
```
|
||||
I found a skill that might help! The "vercel-react-best-practices" skill provides
|
||||
React and Next.js performance optimization guidelines from Vercel Engineering.
|
||||
|
||||
To install it:
|
||||
npx skills add vercel-labs/agent-skills@vercel-react-best-practices
|
||||
|
||||
Learn more: https://skills.sh/vercel-labs/agent-skills/vercel-react-best-practices
|
||||
```
|
||||
|
||||
### Step 4: Offer to Install
|
||||
|
||||
If the user wants to proceed, you can install the skill for them:
|
||||
|
||||
```bash
|
||||
npx skills add <owner/repo@skill> -g -y
|
||||
```
|
||||
|
||||
The `-g` flag installs globally (user-level) and `-y` skips confirmation prompts.
|
||||
|
||||
## Common Skill Categories
|
||||
|
||||
When searching, consider these common categories:
|
||||
|
||||
| Category | Example Queries |
|
||||
| --------------- | ---------------------------------------- |
|
||||
| Web Development | react, nextjs, typescript, css, tailwind |
|
||||
| Testing | testing, jest, playwright, e2e |
|
||||
| DevOps | deploy, docker, kubernetes, ci-cd |
|
||||
| Documentation | docs, readme, changelog, api-docs |
|
||||
| Code Quality | review, lint, refactor, best-practices |
|
||||
| Design | ui, ux, design-system, accessibility |
|
||||
| Productivity | workflow, automation, git |
|
||||
|
||||
## Tips for Effective Searches
|
||||
|
||||
1. **Use specific keywords**: "react testing" is better than just "testing"
|
||||
2. **Try alternative terms**: If "deploy" doesn't work, try "deployment" or "ci-cd"
|
||||
3. **Check popular sources**: Many skills come from `vercel-labs/agent-skills` or `ComposioHQ/awesome-claude-skills`
|
||||
|
||||
## When No Skills Are Found
|
||||
|
||||
If no relevant skills exist:
|
||||
|
||||
1. Acknowledge that no existing skill was found
|
||||
2. Offer to help with the task directly using your general capabilities
|
||||
3. Suggest the user could create their own skill with `npx skills init`
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
I searched for skills related to "xyz" but didn't find any matches.
|
||||
I can still help you with this task directly! Would you like me to proceed?
|
||||
|
||||
If this is something you do often, you could create your own skill:
|
||||
npx skills init my-xyz-skill
|
||||
```
|
||||
543
.agent/skills/nextjs-app-router-patterns/SKILL.md
Normal file
543
.agent/skills/nextjs-app-router-patterns/SKILL.md
Normal file
@@ -0,0 +1,543 @@
|
||||
---
|
||||
name: nextjs-app-router-patterns
|
||||
description: Master Next.js 14+ App Router with Server Components, streaming, parallel routes, and advanced data fetching. Use when building Next.js applications, implementing SSR/SSG, or optimizing React Server Components.
|
||||
---
|
||||
|
||||
# Next.js App Router Patterns
|
||||
|
||||
Comprehensive patterns for Next.js 14+ App Router architecture, Server Components, and modern full-stack React development.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
- Building new Next.js applications with App Router
|
||||
- Migrating from Pages Router to App Router
|
||||
- Implementing Server Components and streaming
|
||||
- Setting up parallel and intercepting routes
|
||||
- Optimizing data fetching and caching
|
||||
- Building full-stack features with Server Actions
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### 1. Rendering Modes
|
||||
|
||||
| Mode | Where | When to Use |
|
||||
| --------------------- | ------------ | ----------------------------------------- |
|
||||
| **Server Components** | Server only | Data fetching, heavy computation, secrets |
|
||||
| **Client Components** | Browser | Interactivity, hooks, browser APIs |
|
||||
| **Static** | Build time | Content that rarely changes |
|
||||
| **Dynamic** | Request time | Personalized or real-time data |
|
||||
| **Streaming** | Progressive | Large pages, slow data sources |
|
||||
|
||||
### 2. File Conventions
|
||||
|
||||
```
|
||||
app/
|
||||
├── layout.tsx # Shared UI wrapper
|
||||
├── page.tsx # Route UI
|
||||
├── loading.tsx # Loading UI (Suspense)
|
||||
├── error.tsx # Error boundary
|
||||
├── not-found.tsx # 404 UI
|
||||
├── route.ts # API endpoint
|
||||
├── template.tsx # Re-mounted layout
|
||||
├── default.tsx # Parallel route fallback
|
||||
└── opengraph-image.tsx # OG image generation
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```typescript
|
||||
// app/layout.tsx
|
||||
import { Inter } from 'next/font/google'
|
||||
import { Providers } from './providers'
|
||||
|
||||
const inter = Inter({ subsets: ['latin'] })
|
||||
|
||||
export const metadata = {
|
||||
title: { default: 'My App', template: '%s | My App' },
|
||||
description: 'Built with Next.js App Router',
|
||||
}
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<body className={inter.className}>
|
||||
<Providers>{children}</Providers>
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
|
||||
// app/page.tsx - Server Component by default
|
||||
async function getProducts() {
|
||||
const res = await fetch('https://api.example.com/products', {
|
||||
next: { revalidate: 3600 }, // ISR: revalidate every hour
|
||||
})
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export default async function HomePage() {
|
||||
const products = await getProducts()
|
||||
|
||||
return (
|
||||
<main>
|
||||
<h1>Products</h1>
|
||||
<ProductGrid products={products} />
|
||||
</main>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Patterns
|
||||
|
||||
### Pattern 1: Server Components with Data Fetching
|
||||
|
||||
```typescript
|
||||
// app/products/page.tsx
|
||||
import { Suspense } from 'react'
|
||||
import { ProductList, ProductListSkeleton } from '@/components/products'
|
||||
import { FilterSidebar } from '@/components/filters'
|
||||
|
||||
interface SearchParams {
|
||||
category?: string
|
||||
sort?: 'price' | 'name' | 'date'
|
||||
page?: string
|
||||
}
|
||||
|
||||
export default async function ProductsPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<SearchParams>
|
||||
}) {
|
||||
const params = await searchParams
|
||||
|
||||
return (
|
||||
<div className="flex gap-8">
|
||||
<FilterSidebar />
|
||||
<Suspense
|
||||
key={JSON.stringify(params)}
|
||||
fallback={<ProductListSkeleton />}
|
||||
>
|
||||
<ProductList
|
||||
category={params.category}
|
||||
sort={params.sort}
|
||||
page={Number(params.page) || 1}
|
||||
/>
|
||||
</Suspense>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// components/products/ProductList.tsx - Server Component
|
||||
async function getProducts(filters: ProductFilters) {
|
||||
const res = await fetch(
|
||||
`${process.env.API_URL}/products?${new URLSearchParams(filters)}`,
|
||||
{ next: { tags: ['products'] } }
|
||||
)
|
||||
if (!res.ok) throw new Error('Failed to fetch products')
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function ProductList({ category, sort, page }: ProductFilters) {
|
||||
const { products, totalPages } = await getProducts({ category, sort, page })
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{products.map((product) => (
|
||||
<ProductCard key={product.id} product={product} />
|
||||
))}
|
||||
</div>
|
||||
<Pagination currentPage={page} totalPages={totalPages} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 2: Client Components with 'use client'
|
||||
|
||||
```typescript
|
||||
// components/products/AddToCartButton.tsx
|
||||
'use client'
|
||||
|
||||
import { useState, useTransition } from 'react'
|
||||
import { addToCart } from '@/app/actions/cart'
|
||||
|
||||
export function AddToCartButton({ productId }: { productId: string }) {
|
||||
const [isPending, startTransition] = useTransition()
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const handleClick = () => {
|
||||
setError(null)
|
||||
startTransition(async () => {
|
||||
const result = await addToCart(productId)
|
||||
if (result.error) {
|
||||
setError(result.error)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button
|
||||
onClick={handleClick}
|
||||
disabled={isPending}
|
||||
className="btn-primary"
|
||||
>
|
||||
{isPending ? 'Adding...' : 'Add to Cart'}
|
||||
</button>
|
||||
{error && <p className="text-red-500 text-sm">{error}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 3: Server Actions
|
||||
|
||||
```typescript
|
||||
// app/actions/cart.ts
|
||||
"use server";
|
||||
|
||||
import { revalidateTag } from "next/cache";
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export async function addToCart(productId: string) {
|
||||
const cookieStore = await cookies();
|
||||
const sessionId = cookieStore.get("session")?.value;
|
||||
|
||||
if (!sessionId) {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
try {
|
||||
await db.cart.upsert({
|
||||
where: { sessionId_productId: { sessionId, productId } },
|
||||
update: { quantity: { increment: 1 } },
|
||||
create: { sessionId, productId, quantity: 1 },
|
||||
});
|
||||
|
||||
revalidateTag("cart");
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { error: "Failed to add item to cart" };
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkout(formData: FormData) {
|
||||
const address = formData.get("address") as string;
|
||||
const payment = formData.get("payment") as string;
|
||||
|
||||
// Validate
|
||||
if (!address || !payment) {
|
||||
return { error: "Missing required fields" };
|
||||
}
|
||||
|
||||
// Process order
|
||||
const order = await processOrder({ address, payment });
|
||||
|
||||
// Redirect to confirmation
|
||||
redirect(`/orders/${order.id}/confirmation`);
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 4: Parallel Routes
|
||||
|
||||
```typescript
|
||||
// app/dashboard/layout.tsx
|
||||
export default function DashboardLayout({
|
||||
children,
|
||||
analytics,
|
||||
team,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
analytics: React.ReactNode
|
||||
team: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<div className="dashboard-grid">
|
||||
<main>{children}</main>
|
||||
<aside className="analytics-panel">{analytics}</aside>
|
||||
<aside className="team-panel">{team}</aside>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// app/dashboard/@analytics/page.tsx
|
||||
export default async function AnalyticsSlot() {
|
||||
const stats = await getAnalytics()
|
||||
return <AnalyticsChart data={stats} />
|
||||
}
|
||||
|
||||
// app/dashboard/@analytics/loading.tsx
|
||||
export default function AnalyticsLoading() {
|
||||
return <ChartSkeleton />
|
||||
}
|
||||
|
||||
// app/dashboard/@team/page.tsx
|
||||
export default async function TeamSlot() {
|
||||
const members = await getTeamMembers()
|
||||
return <TeamList members={members} />
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 5: Intercepting Routes (Modal Pattern)
|
||||
|
||||
```typescript
|
||||
// File structure for photo modal
|
||||
// app/
|
||||
// ├── @modal/
|
||||
// │ ├── (.)photos/[id]/page.tsx # Intercept
|
||||
// │ └── default.tsx
|
||||
// ├── photos/
|
||||
// │ └── [id]/page.tsx # Full page
|
||||
// └── layout.tsx
|
||||
|
||||
// app/@modal/(.)photos/[id]/page.tsx
|
||||
import { Modal } from '@/components/Modal'
|
||||
import { PhotoDetail } from '@/components/PhotoDetail'
|
||||
|
||||
export default async function PhotoModal({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>
|
||||
}) {
|
||||
const { id } = await params
|
||||
const photo = await getPhoto(id)
|
||||
|
||||
return (
|
||||
<Modal>
|
||||
<PhotoDetail photo={photo} />
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
// app/photos/[id]/page.tsx - Full page version
|
||||
export default async function PhotoPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>
|
||||
}) {
|
||||
const { id } = await params
|
||||
const photo = await getPhoto(id)
|
||||
|
||||
return (
|
||||
<div className="photo-page">
|
||||
<PhotoDetail photo={photo} />
|
||||
<RelatedPhotos photoId={id} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// app/layout.tsx
|
||||
export default function RootLayout({
|
||||
children,
|
||||
modal,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
modal: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<html>
|
||||
<body>
|
||||
{children}
|
||||
{modal}
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 6: Streaming with Suspense
|
||||
|
||||
```typescript
|
||||
// app/product/[id]/page.tsx
|
||||
import { Suspense } from 'react'
|
||||
|
||||
export default async function ProductPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>
|
||||
}) {
|
||||
const { id } = await params
|
||||
|
||||
// This data loads first (blocking)
|
||||
const product = await getProduct(id)
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Immediate render */}
|
||||
<ProductHeader product={product} />
|
||||
|
||||
{/* Stream in reviews */}
|
||||
<Suspense fallback={<ReviewsSkeleton />}>
|
||||
<Reviews productId={id} />
|
||||
</Suspense>
|
||||
|
||||
{/* Stream in recommendations */}
|
||||
<Suspense fallback={<RecommendationsSkeleton />}>
|
||||
<Recommendations productId={id} />
|
||||
</Suspense>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// These components fetch their own data
|
||||
async function Reviews({ productId }: { productId: string }) {
|
||||
const reviews = await getReviews(productId) // Slow API
|
||||
return <ReviewList reviews={reviews} />
|
||||
}
|
||||
|
||||
async function Recommendations({ productId }: { productId: string }) {
|
||||
const products = await getRecommendations(productId) // ML-based, slow
|
||||
return <ProductCarousel products={products} />
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 7: Route Handlers (API Routes)
|
||||
|
||||
```typescript
|
||||
// app/api/products/route.ts
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const category = searchParams.get("category");
|
||||
|
||||
const products = await db.product.findMany({
|
||||
where: category ? { category } : undefined,
|
||||
take: 20,
|
||||
});
|
||||
|
||||
return NextResponse.json(products);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json();
|
||||
|
||||
const product = await db.product.create({
|
||||
data: body,
|
||||
});
|
||||
|
||||
return NextResponse.json(product, { status: 201 });
|
||||
}
|
||||
|
||||
// app/api/products/[id]/route.ts
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const { id } = await params;
|
||||
const product = await db.product.findUnique({ where: { id } });
|
||||
|
||||
if (!product) {
|
||||
return NextResponse.json({ error: "Product not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(product);
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 8: Metadata and SEO
|
||||
|
||||
```typescript
|
||||
// app/products/[slug]/page.tsx
|
||||
import { Metadata } from 'next'
|
||||
import { notFound } from 'next/navigation'
|
||||
|
||||
type Props = {
|
||||
params: Promise<{ slug: string }>
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
const { slug } = await params
|
||||
const product = await getProduct(slug)
|
||||
|
||||
if (!product) return {}
|
||||
|
||||
return {
|
||||
title: product.name,
|
||||
description: product.description,
|
||||
openGraph: {
|
||||
title: product.name,
|
||||
description: product.description,
|
||||
images: [{ url: product.image, width: 1200, height: 630 }],
|
||||
},
|
||||
twitter: {
|
||||
card: 'summary_large_image',
|
||||
title: product.name,
|
||||
description: product.description,
|
||||
images: [product.image],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateStaticParams() {
|
||||
const products = await db.product.findMany({ select: { slug: true } })
|
||||
return products.map((p) => ({ slug: p.slug }))
|
||||
}
|
||||
|
||||
export default async function ProductPage({ params }: Props) {
|
||||
const { slug } = await params
|
||||
const product = await getProduct(slug)
|
||||
|
||||
if (!product) notFound()
|
||||
|
||||
return <ProductDetail product={product} />
|
||||
}
|
||||
```
|
||||
|
||||
## Caching Strategies
|
||||
|
||||
### Data Cache
|
||||
|
||||
```typescript
|
||||
// No cache (always fresh)
|
||||
fetch(url, { cache: "no-store" });
|
||||
|
||||
// Cache forever (static)
|
||||
fetch(url, { cache: "force-cache" });
|
||||
|
||||
// ISR - revalidate after 60 seconds
|
||||
fetch(url, { next: { revalidate: 60 } });
|
||||
|
||||
// Tag-based invalidation
|
||||
fetch(url, { next: { tags: ["products"] } });
|
||||
|
||||
// Invalidate via Server Action
|
||||
("use server");
|
||||
import { revalidateTag, revalidatePath } from "next/cache";
|
||||
|
||||
export async function updateProduct(id: string, data: ProductData) {
|
||||
await db.product.update({ where: { id }, data });
|
||||
revalidateTag("products");
|
||||
revalidatePath("/products");
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Do's
|
||||
|
||||
- **Start with Server Components** - Add 'use client' only when needed
|
||||
- **Colocate data fetching** - Fetch data where it's used
|
||||
- **Use Suspense boundaries** - Enable streaming for slow data
|
||||
- **Leverage parallel routes** - Independent loading states
|
||||
- **Use Server Actions** - For mutations with progressive enhancement
|
||||
|
||||
### Don'ts
|
||||
|
||||
- **Don't pass serializable data** - Server → Client boundary limitations
|
||||
- **Don't use hooks in Server Components** - No useState, useEffect
|
||||
- **Don't fetch in Client Components** - Use Server Components or React Query
|
||||
- **Don't over-nest layouts** - Each layout adds to the component tree
|
||||
- **Don't ignore loading states** - Always provide loading.tsx or Suspense
|
||||
|
||||
## Resources
|
||||
|
||||
- [Next.js App Router Documentation](https://nextjs.org/docs/app)
|
||||
- [Server Components RFC](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md)
|
||||
- [Vercel Templates](https://vercel.com/templates/next.js)
|
||||
2934
.agent/skills/vercel-react-best-practices/AGENTS.md
Normal file
2934
.agent/skills/vercel-react-best-practices/AGENTS.md
Normal file
File diff suppressed because it is too large
Load Diff
136
.agent/skills/vercel-react-best-practices/SKILL.md
Normal file
136
.agent/skills/vercel-react-best-practices/SKILL.md
Normal file
@@ -0,0 +1,136 @@
|
||||
---
|
||||
name: vercel-react-best-practices
|
||||
description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: vercel
|
||||
version: "1.0.0"
|
||||
---
|
||||
|
||||
# Vercel React Best Practices
|
||||
|
||||
Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 57 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
|
||||
|
||||
## When to Apply
|
||||
|
||||
Reference these guidelines when:
|
||||
- Writing new React components or Next.js pages
|
||||
- Implementing data fetching (client or server-side)
|
||||
- Reviewing code for performance issues
|
||||
- Refactoring existing React/Next.js code
|
||||
- Optimizing bundle size or load times
|
||||
|
||||
## Rule Categories by Priority
|
||||
|
||||
| Priority | Category | Impact | Prefix |
|
||||
|----------|----------|--------|--------|
|
||||
| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
|
||||
| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
|
||||
| 3 | Server-Side Performance | HIGH | `server-` |
|
||||
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
|
||||
| 5 | Re-render Optimization | MEDIUM | `rerender-` |
|
||||
| 6 | Rendering Performance | MEDIUM | `rendering-` |
|
||||
| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
|
||||
| 8 | Advanced Patterns | LOW | `advanced-` |
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### 1. Eliminating Waterfalls (CRITICAL)
|
||||
|
||||
- `async-defer-await` - Move await into branches where actually used
|
||||
- `async-parallel` - Use Promise.all() for independent operations
|
||||
- `async-dependencies` - Use better-all for partial dependencies
|
||||
- `async-api-routes` - Start promises early, await late in API routes
|
||||
- `async-suspense-boundaries` - Use Suspense to stream content
|
||||
|
||||
### 2. Bundle Size Optimization (CRITICAL)
|
||||
|
||||
- `bundle-barrel-imports` - Import directly, avoid barrel files
|
||||
- `bundle-dynamic-imports` - Use next/dynamic for heavy components
|
||||
- `bundle-defer-third-party` - Load analytics/logging after hydration
|
||||
- `bundle-conditional` - Load modules only when feature is activated
|
||||
- `bundle-preload` - Preload on hover/focus for perceived speed
|
||||
|
||||
### 3. Server-Side Performance (HIGH)
|
||||
|
||||
- `server-auth-actions` - Authenticate server actions like API routes
|
||||
- `server-cache-react` - Use React.cache() for per-request deduplication
|
||||
- `server-cache-lru` - Use LRU cache for cross-request caching
|
||||
- `server-dedup-props` - Avoid duplicate serialization in RSC props
|
||||
- `server-serialization` - Minimize data passed to client components
|
||||
- `server-parallel-fetching` - Restructure components to parallelize fetches
|
||||
- `server-after-nonblocking` - Use after() for non-blocking operations
|
||||
|
||||
### 4. Client-Side Data Fetching (MEDIUM-HIGH)
|
||||
|
||||
- `client-swr-dedup` - Use SWR for automatic request deduplication
|
||||
- `client-event-listeners` - Deduplicate global event listeners
|
||||
- `client-passive-event-listeners` - Use passive listeners for scroll
|
||||
- `client-localstorage-schema` - Version and minimize localStorage data
|
||||
|
||||
### 5. Re-render Optimization (MEDIUM)
|
||||
|
||||
- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
|
||||
- `rerender-memo` - Extract expensive work into memoized components
|
||||
- `rerender-memo-with-default-value` - Hoist default non-primitive props
|
||||
- `rerender-dependencies` - Use primitive dependencies in effects
|
||||
- `rerender-derived-state` - Subscribe to derived booleans, not raw values
|
||||
- `rerender-derived-state-no-effect` - Derive state during render, not effects
|
||||
- `rerender-functional-setstate` - Use functional setState for stable callbacks
|
||||
- `rerender-lazy-state-init` - Pass function to useState for expensive values
|
||||
- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives
|
||||
- `rerender-move-effect-to-event` - Put interaction logic in event handlers
|
||||
- `rerender-transitions` - Use startTransition for non-urgent updates
|
||||
- `rerender-use-ref-transient-values` - Use refs for transient frequent values
|
||||
|
||||
### 6. Rendering Performance (MEDIUM)
|
||||
|
||||
- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
|
||||
- `rendering-content-visibility` - Use content-visibility for long lists
|
||||
- `rendering-hoist-jsx` - Extract static JSX outside components
|
||||
- `rendering-svg-precision` - Reduce SVG coordinate precision
|
||||
- `rendering-hydration-no-flicker` - Use inline script for client-only data
|
||||
- `rendering-hydration-suppress-warning` - Suppress expected mismatches
|
||||
- `rendering-activity` - Use Activity component for show/hide
|
||||
- `rendering-conditional-render` - Use ternary, not && for conditionals
|
||||
- `rendering-usetransition-loading` - Prefer useTransition for loading state
|
||||
|
||||
### 7. JavaScript Performance (LOW-MEDIUM)
|
||||
|
||||
- `js-batch-dom-css` - Group CSS changes via classes or cssText
|
||||
- `js-index-maps` - Build Map for repeated lookups
|
||||
- `js-cache-property-access` - Cache object properties in loops
|
||||
- `js-cache-function-results` - Cache function results in module-level Map
|
||||
- `js-cache-storage` - Cache localStorage/sessionStorage reads
|
||||
- `js-combine-iterations` - Combine multiple filter/map into one loop
|
||||
- `js-length-check-first` - Check array length before expensive comparison
|
||||
- `js-early-exit` - Return early from functions
|
||||
- `js-hoist-regexp` - Hoist RegExp creation outside loops
|
||||
- `js-min-max-loop` - Use loop for min/max instead of sort
|
||||
- `js-set-map-lookups` - Use Set/Map for O(1) lookups
|
||||
- `js-tosorted-immutable` - Use toSorted() for immutability
|
||||
|
||||
### 8. Advanced Patterns (LOW)
|
||||
|
||||
- `advanced-event-handler-refs` - Store event handlers in refs
|
||||
- `advanced-init-once` - Initialize app once per app load
|
||||
- `advanced-use-latest` - useLatest for stable callback refs
|
||||
|
||||
## How to Use
|
||||
|
||||
Read individual rule files for detailed explanations and code examples:
|
||||
|
||||
```
|
||||
rules/async-parallel.md
|
||||
rules/bundle-barrel-imports.md
|
||||
```
|
||||
|
||||
Each rule file contains:
|
||||
- Brief explanation of why it matters
|
||||
- Incorrect code example with explanation
|
||||
- Correct code example with explanation
|
||||
- Additional context and references
|
||||
|
||||
## Full Compiled Document
|
||||
|
||||
For the complete guide with all rules expanded: `AGENTS.md`
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
title: Store Event Handlers in Refs
|
||||
impact: LOW
|
||||
impactDescription: stable subscriptions
|
||||
tags: advanced, hooks, refs, event-handlers, optimization
|
||||
---
|
||||
|
||||
## Store Event Handlers in Refs
|
||||
|
||||
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
|
||||
|
||||
**Incorrect (re-subscribes on every render):**
|
||||
|
||||
```tsx
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
useEffect(() => {
|
||||
window.addEventListener(event, handler)
|
||||
return () => window.removeEventListener(event, handler)
|
||||
}, [event, handler])
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (stable subscription):**
|
||||
|
||||
```tsx
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
const handlerRef = useRef(handler)
|
||||
useEffect(() => {
|
||||
handlerRef.current = handler
|
||||
}, [handler])
|
||||
|
||||
useEffect(() => {
|
||||
const listener = (e) => handlerRef.current(e)
|
||||
window.addEventListener(event, listener)
|
||||
return () => window.removeEventListener(event, listener)
|
||||
}, [event])
|
||||
}
|
||||
```
|
||||
|
||||
**Alternative: use `useEffectEvent` if you're on latest React:**
|
||||
|
||||
```tsx
|
||||
import { useEffectEvent } from 'react'
|
||||
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
const onEvent = useEffectEvent(handler)
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener(event, onEvent)
|
||||
return () => window.removeEventListener(event, onEvent)
|
||||
}, [event])
|
||||
}
|
||||
```
|
||||
|
||||
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
title: Initialize App Once, Not Per Mount
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids duplicate init in development
|
||||
tags: initialization, useEffect, app-startup, side-effects
|
||||
---
|
||||
|
||||
## Initialize App Once, Not Per Mount
|
||||
|
||||
Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
|
||||
|
||||
**Incorrect (runs twice in dev, re-runs on remount):**
|
||||
|
||||
```tsx
|
||||
function Comp() {
|
||||
useEffect(() => {
|
||||
loadFromStorage()
|
||||
checkAuthToken()
|
||||
}, [])
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (once per app load):**
|
||||
|
||||
```tsx
|
||||
let didInit = false
|
||||
|
||||
function Comp() {
|
||||
useEffect(() => {
|
||||
if (didInit) return
|
||||
didInit = true
|
||||
loadFromStorage()
|
||||
checkAuthToken()
|
||||
}, [])
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
title: useEffectEvent for Stable Callback Refs
|
||||
impact: LOW
|
||||
impactDescription: prevents effect re-runs
|
||||
tags: advanced, hooks, useEffectEvent, refs, optimization
|
||||
---
|
||||
|
||||
## useEffectEvent for Stable Callback Refs
|
||||
|
||||
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
|
||||
|
||||
**Incorrect (effect re-runs on every callback change):**
|
||||
|
||||
```tsx
|
||||
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => onSearch(query), 300)
|
||||
return () => clearTimeout(timeout)
|
||||
}, [query, onSearch])
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (using React's useEffectEvent):**
|
||||
|
||||
```tsx
|
||||
import { useEffectEvent } from 'react';
|
||||
|
||||
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||
const [query, setQuery] = useState('')
|
||||
const onSearchEvent = useEffectEvent(onSearch)
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => onSearchEvent(query), 300)
|
||||
return () => clearTimeout(timeout)
|
||||
}, [query])
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: Prevent Waterfall Chains in API Routes
|
||||
impact: CRITICAL
|
||||
impactDescription: 2-10× improvement
|
||||
tags: api-routes, server-actions, waterfalls, parallelization
|
||||
---
|
||||
|
||||
## Prevent Waterfall Chains in API Routes
|
||||
|
||||
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
|
||||
|
||||
**Incorrect (config waits for auth, data waits for both):**
|
||||
|
||||
```typescript
|
||||
export async function GET(request: Request) {
|
||||
const session = await auth()
|
||||
const config = await fetchConfig()
|
||||
const data = await fetchData(session.user.id)
|
||||
return Response.json({ data, config })
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (auth and config start immediately):**
|
||||
|
||||
```typescript
|
||||
export async function GET(request: Request) {
|
||||
const sessionPromise = auth()
|
||||
const configPromise = fetchConfig()
|
||||
const session = await sessionPromise
|
||||
const [config, data] = await Promise.all([
|
||||
configPromise,
|
||||
fetchData(session.user.id)
|
||||
])
|
||||
return Response.json({ data, config })
|
||||
}
|
||||
```
|
||||
|
||||
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
title: Defer Await Until Needed
|
||||
impact: HIGH
|
||||
impactDescription: avoids blocking unused code paths
|
||||
tags: async, await, conditional, optimization
|
||||
---
|
||||
|
||||
## Defer Await Until Needed
|
||||
|
||||
Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
|
||||
|
||||
**Incorrect (blocks both branches):**
|
||||
|
||||
```typescript
|
||||
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||
const userData = await fetchUserData(userId)
|
||||
|
||||
if (skipProcessing) {
|
||||
// Returns immediately but still waited for userData
|
||||
return { skipped: true }
|
||||
}
|
||||
|
||||
// Only this branch uses userData
|
||||
return processUserData(userData)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (only blocks when needed):**
|
||||
|
||||
```typescript
|
||||
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||
if (skipProcessing) {
|
||||
// Returns immediately without waiting
|
||||
return { skipped: true }
|
||||
}
|
||||
|
||||
// Fetch only when needed
|
||||
const userData = await fetchUserData(userId)
|
||||
return processUserData(userData)
|
||||
}
|
||||
```
|
||||
|
||||
**Another example (early return optimization):**
|
||||
|
||||
```typescript
|
||||
// Incorrect: always fetches permissions
|
||||
async function updateResource(resourceId: string, userId: string) {
|
||||
const permissions = await fetchPermissions(userId)
|
||||
const resource = await getResource(resourceId)
|
||||
|
||||
if (!resource) {
|
||||
return { error: 'Not found' }
|
||||
}
|
||||
|
||||
if (!permissions.canEdit) {
|
||||
return { error: 'Forbidden' }
|
||||
}
|
||||
|
||||
return await updateResourceData(resource, permissions)
|
||||
}
|
||||
|
||||
// Correct: fetches only when needed
|
||||
async function updateResource(resourceId: string, userId: string) {
|
||||
const resource = await getResource(resourceId)
|
||||
|
||||
if (!resource) {
|
||||
return { error: 'Not found' }
|
||||
}
|
||||
|
||||
const permissions = await fetchPermissions(userId)
|
||||
|
||||
if (!permissions.canEdit) {
|
||||
return { error: 'Forbidden' }
|
||||
}
|
||||
|
||||
return await updateResourceData(resource, permissions)
|
||||
}
|
||||
```
|
||||
|
||||
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
title: Dependency-Based Parallelization
|
||||
impact: CRITICAL
|
||||
impactDescription: 2-10× improvement
|
||||
tags: async, parallelization, dependencies, better-all
|
||||
---
|
||||
|
||||
## Dependency-Based Parallelization
|
||||
|
||||
For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
|
||||
|
||||
**Incorrect (profile waits for config unnecessarily):**
|
||||
|
||||
```typescript
|
||||
const [user, config] = await Promise.all([
|
||||
fetchUser(),
|
||||
fetchConfig()
|
||||
])
|
||||
const profile = await fetchProfile(user.id)
|
||||
```
|
||||
|
||||
**Correct (config and profile run in parallel):**
|
||||
|
||||
```typescript
|
||||
import { all } from 'better-all'
|
||||
|
||||
const { user, config, profile } = await all({
|
||||
async user() { return fetchUser() },
|
||||
async config() { return fetchConfig() },
|
||||
async profile() {
|
||||
return fetchProfile((await this.$.user).id)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Alternative without extra dependencies:**
|
||||
|
||||
We can also create all the promises first, and do `Promise.all()` at the end.
|
||||
|
||||
```typescript
|
||||
const userPromise = fetchUser()
|
||||
const profilePromise = userPromise.then(user => fetchProfile(user.id))
|
||||
|
||||
const [user, config, profile] = await Promise.all([
|
||||
userPromise,
|
||||
fetchConfig(),
|
||||
profilePromise
|
||||
])
|
||||
```
|
||||
|
||||
Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
title: Promise.all() for Independent Operations
|
||||
impact: CRITICAL
|
||||
impactDescription: 2-10× improvement
|
||||
tags: async, parallelization, promises, waterfalls
|
||||
---
|
||||
|
||||
## Promise.all() for Independent Operations
|
||||
|
||||
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
|
||||
|
||||
**Incorrect (sequential execution, 3 round trips):**
|
||||
|
||||
```typescript
|
||||
const user = await fetchUser()
|
||||
const posts = await fetchPosts()
|
||||
const comments = await fetchComments()
|
||||
```
|
||||
|
||||
**Correct (parallel execution, 1 round trip):**
|
||||
|
||||
```typescript
|
||||
const [user, posts, comments] = await Promise.all([
|
||||
fetchUser(),
|
||||
fetchPosts(),
|
||||
fetchComments()
|
||||
])
|
||||
```
|
||||
@@ -0,0 +1,99 @@
|
||||
---
|
||||
title: Strategic Suspense Boundaries
|
||||
impact: HIGH
|
||||
impactDescription: faster initial paint
|
||||
tags: async, suspense, streaming, layout-shift
|
||||
---
|
||||
|
||||
## Strategic Suspense Boundaries
|
||||
|
||||
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
|
||||
|
||||
**Incorrect (wrapper blocked by data fetching):**
|
||||
|
||||
```tsx
|
||||
async function Page() {
|
||||
const data = await fetchData() // Blocks entire page
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div>Sidebar</div>
|
||||
<div>Header</div>
|
||||
<div>
|
||||
<DataDisplay data={data} />
|
||||
</div>
|
||||
<div>Footer</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
The entire layout waits for data even though only the middle section needs it.
|
||||
|
||||
**Correct (wrapper shows immediately, data streams in):**
|
||||
|
||||
```tsx
|
||||
function Page() {
|
||||
return (
|
||||
<div>
|
||||
<div>Sidebar</div>
|
||||
<div>Header</div>
|
||||
<div>
|
||||
<Suspense fallback={<Skeleton />}>
|
||||
<DataDisplay />
|
||||
</Suspense>
|
||||
</div>
|
||||
<div>Footer</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
async function DataDisplay() {
|
||||
const data = await fetchData() // Only blocks this component
|
||||
return <div>{data.content}</div>
|
||||
}
|
||||
```
|
||||
|
||||
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
|
||||
|
||||
**Alternative (share promise across components):**
|
||||
|
||||
```tsx
|
||||
function Page() {
|
||||
// Start fetch immediately, but don't await
|
||||
const dataPromise = fetchData()
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div>Sidebar</div>
|
||||
<div>Header</div>
|
||||
<Suspense fallback={<Skeleton />}>
|
||||
<DataDisplay dataPromise={dataPromise} />
|
||||
<DataSummary dataPromise={dataPromise} />
|
||||
</Suspense>
|
||||
<div>Footer</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
|
||||
const data = use(dataPromise) // Unwraps the promise
|
||||
return <div>{data.content}</div>
|
||||
}
|
||||
|
||||
function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
|
||||
const data = use(dataPromise) // Reuses the same promise
|
||||
return <div>{data.summary}</div>
|
||||
}
|
||||
```
|
||||
|
||||
Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
|
||||
|
||||
**When NOT to use this pattern:**
|
||||
|
||||
- Critical data needed for layout decisions (affects positioning)
|
||||
- SEO-critical content above the fold
|
||||
- Small, fast queries where suspense overhead isn't worth it
|
||||
- When you want to avoid layout shift (loading → content jump)
|
||||
|
||||
**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
title: Avoid Barrel File Imports
|
||||
impact: CRITICAL
|
||||
impactDescription: 200-800ms import cost, slow builds
|
||||
tags: bundle, imports, tree-shaking, barrel-files, performance
|
||||
---
|
||||
|
||||
## Avoid Barrel File Imports
|
||||
|
||||
Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
|
||||
|
||||
Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
|
||||
|
||||
**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
|
||||
|
||||
**Incorrect (imports entire library):**
|
||||
|
||||
```tsx
|
||||
import { Check, X, Menu } from 'lucide-react'
|
||||
// Loads 1,583 modules, takes ~2.8s extra in dev
|
||||
// Runtime cost: 200-800ms on every cold start
|
||||
|
||||
import { Button, TextField } from '@mui/material'
|
||||
// Loads 2,225 modules, takes ~4.2s extra in dev
|
||||
```
|
||||
|
||||
**Correct (imports only what you need):**
|
||||
|
||||
```tsx
|
||||
import Check from 'lucide-react/dist/esm/icons/check'
|
||||
import X from 'lucide-react/dist/esm/icons/x'
|
||||
import Menu from 'lucide-react/dist/esm/icons/menu'
|
||||
// Loads only 3 modules (~2KB vs ~1MB)
|
||||
|
||||
import Button from '@mui/material/Button'
|
||||
import TextField from '@mui/material/TextField'
|
||||
// Loads only what you use
|
||||
```
|
||||
|
||||
**Alternative (Next.js 13.5+):**
|
||||
|
||||
```js
|
||||
// next.config.js - use optimizePackageImports
|
||||
module.exports = {
|
||||
experimental: {
|
||||
optimizePackageImports: ['lucide-react', '@mui/material']
|
||||
}
|
||||
}
|
||||
|
||||
// Then you can keep the ergonomic barrel imports:
|
||||
import { Check, X, Menu } from 'lucide-react'
|
||||
// Automatically transformed to direct imports at build time
|
||||
```
|
||||
|
||||
Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
|
||||
|
||||
Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
|
||||
|
||||
Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
title: Conditional Module Loading
|
||||
impact: HIGH
|
||||
impactDescription: loads large data only when needed
|
||||
tags: bundle, conditional-loading, lazy-loading
|
||||
---
|
||||
|
||||
## Conditional Module Loading
|
||||
|
||||
Load large data or modules only when a feature is activated.
|
||||
|
||||
**Example (lazy-load animation frames):**
|
||||
|
||||
```tsx
|
||||
function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
|
||||
const [frames, setFrames] = useState<Frame[] | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (enabled && !frames && typeof window !== 'undefined') {
|
||||
import('./animation-frames.js')
|
||||
.then(mod => setFrames(mod.frames))
|
||||
.catch(() => setEnabled(false))
|
||||
}
|
||||
}, [enabled, frames, setEnabled])
|
||||
|
||||
if (!frames) return <Skeleton />
|
||||
return <Canvas frames={frames} />
|
||||
}
|
||||
```
|
||||
|
||||
The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
title: Defer Non-Critical Third-Party Libraries
|
||||
impact: MEDIUM
|
||||
impactDescription: loads after hydration
|
||||
tags: bundle, third-party, analytics, defer
|
||||
---
|
||||
|
||||
## Defer Non-Critical Third-Party Libraries
|
||||
|
||||
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
|
||||
|
||||
**Incorrect (blocks initial bundle):**
|
||||
|
||||
```tsx
|
||||
import { Analytics } from '@vercel/analytics/react'
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html>
|
||||
<body>
|
||||
{children}
|
||||
<Analytics />
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (loads after hydration):**
|
||||
|
||||
```tsx
|
||||
import dynamic from 'next/dynamic'
|
||||
|
||||
const Analytics = dynamic(
|
||||
() => import('@vercel/analytics/react').then(m => m.Analytics),
|
||||
{ ssr: false }
|
||||
)
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html>
|
||||
<body>
|
||||
{children}
|
||||
<Analytics />
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
title: Dynamic Imports for Heavy Components
|
||||
impact: CRITICAL
|
||||
impactDescription: directly affects TTI and LCP
|
||||
tags: bundle, dynamic-import, code-splitting, next-dynamic
|
||||
---
|
||||
|
||||
## Dynamic Imports for Heavy Components
|
||||
|
||||
Use `next/dynamic` to lazy-load large components not needed on initial render.
|
||||
|
||||
**Incorrect (Monaco bundles with main chunk ~300KB):**
|
||||
|
||||
```tsx
|
||||
import { MonacoEditor } from './monaco-editor'
|
||||
|
||||
function CodePanel({ code }: { code: string }) {
|
||||
return <MonacoEditor value={code} />
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (Monaco loads on demand):**
|
||||
|
||||
```tsx
|
||||
import dynamic from 'next/dynamic'
|
||||
|
||||
const MonacoEditor = dynamic(
|
||||
() => import('./monaco-editor').then(m => m.MonacoEditor),
|
||||
{ ssr: false }
|
||||
)
|
||||
|
||||
function CodePanel({ code }: { code: string }) {
|
||||
return <MonacoEditor value={code} />
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
title: Preload Based on User Intent
|
||||
impact: MEDIUM
|
||||
impactDescription: reduces perceived latency
|
||||
tags: bundle, preload, user-intent, hover
|
||||
---
|
||||
|
||||
## Preload Based on User Intent
|
||||
|
||||
Preload heavy bundles before they're needed to reduce perceived latency.
|
||||
|
||||
**Example (preload on hover/focus):**
|
||||
|
||||
```tsx
|
||||
function EditorButton({ onClick }: { onClick: () => void }) {
|
||||
const preload = () => {
|
||||
if (typeof window !== 'undefined') {
|
||||
void import('./monaco-editor')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
onMouseEnter={preload}
|
||||
onFocus={preload}
|
||||
onClick={onClick}
|
||||
>
|
||||
Open Editor
|
||||
</button>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Example (preload when feature flag is enabled):**
|
||||
|
||||
```tsx
|
||||
function FlagsProvider({ children, flags }: Props) {
|
||||
useEffect(() => {
|
||||
if (flags.editorEnabled && typeof window !== 'undefined') {
|
||||
void import('./monaco-editor').then(mod => mod.init())
|
||||
}
|
||||
}, [flags.editorEnabled])
|
||||
|
||||
return <FlagsContext.Provider value={flags}>
|
||||
{children}
|
||||
</FlagsContext.Provider>
|
||||
}
|
||||
```
|
||||
|
||||
The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
title: Deduplicate Global Event Listeners
|
||||
impact: LOW
|
||||
impactDescription: single listener for N components
|
||||
tags: client, swr, event-listeners, subscription
|
||||
---
|
||||
|
||||
## Deduplicate Global Event Listeners
|
||||
|
||||
Use `useSWRSubscription()` to share global event listeners across component instances.
|
||||
|
||||
**Incorrect (N instances = N listeners):**
|
||||
|
||||
```tsx
|
||||
function useKeyboardShortcut(key: string, callback: () => void) {
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (e.metaKey && e.key === key) {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', handler)
|
||||
return () => window.removeEventListener('keydown', handler)
|
||||
}, [key, callback])
|
||||
}
|
||||
```
|
||||
|
||||
When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
|
||||
|
||||
**Correct (N instances = 1 listener):**
|
||||
|
||||
```tsx
|
||||
import useSWRSubscription from 'swr/subscription'
|
||||
|
||||
// Module-level Map to track callbacks per key
|
||||
const keyCallbacks = new Map<string, Set<() => void>>()
|
||||
|
||||
function useKeyboardShortcut(key: string, callback: () => void) {
|
||||
// Register this callback in the Map
|
||||
useEffect(() => {
|
||||
if (!keyCallbacks.has(key)) {
|
||||
keyCallbacks.set(key, new Set())
|
||||
}
|
||||
keyCallbacks.get(key)!.add(callback)
|
||||
|
||||
return () => {
|
||||
const set = keyCallbacks.get(key)
|
||||
if (set) {
|
||||
set.delete(callback)
|
||||
if (set.size === 0) {
|
||||
keyCallbacks.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [key, callback])
|
||||
|
||||
useSWRSubscription('global-keydown', () => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (e.metaKey && keyCallbacks.has(e.key)) {
|
||||
keyCallbacks.get(e.key)!.forEach(cb => cb())
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', handler)
|
||||
return () => window.removeEventListener('keydown', handler)
|
||||
})
|
||||
}
|
||||
|
||||
function Profile() {
|
||||
// Multiple shortcuts will share the same listener
|
||||
useKeyboardShortcut('p', () => { /* ... */ })
|
||||
useKeyboardShortcut('k', () => { /* ... */ })
|
||||
// ...
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
title: Version and Minimize localStorage Data
|
||||
impact: MEDIUM
|
||||
impactDescription: prevents schema conflicts, reduces storage size
|
||||
tags: client, localStorage, storage, versioning, data-minimization
|
||||
---
|
||||
|
||||
## Version and Minimize localStorage Data
|
||||
|
||||
Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```typescript
|
||||
// No version, stores everything, no error handling
|
||||
localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
|
||||
const data = localStorage.getItem('userConfig')
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
const VERSION = 'v2'
|
||||
|
||||
function saveConfig(config: { theme: string; language: string }) {
|
||||
try {
|
||||
localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
|
||||
} catch {
|
||||
// Throws in incognito/private browsing, quota exceeded, or disabled
|
||||
}
|
||||
}
|
||||
|
||||
function loadConfig() {
|
||||
try {
|
||||
const data = localStorage.getItem(`userConfig:${VERSION}`)
|
||||
return data ? JSON.parse(data) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Migration from v1 to v2
|
||||
function migrate() {
|
||||
try {
|
||||
const v1 = localStorage.getItem('userConfig:v1')
|
||||
if (v1) {
|
||||
const old = JSON.parse(v1)
|
||||
saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
|
||||
localStorage.removeItem('userConfig:v1')
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
```
|
||||
|
||||
**Store minimal fields from server responses:**
|
||||
|
||||
```typescript
|
||||
// User object has 20+ fields, only store what UI needs
|
||||
function cachePrefs(user: FullUser) {
|
||||
try {
|
||||
localStorage.setItem('prefs:v1', JSON.stringify({
|
||||
theme: user.preferences.theme,
|
||||
notifications: user.preferences.notifications
|
||||
}))
|
||||
} catch {}
|
||||
}
|
||||
```
|
||||
|
||||
**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
|
||||
|
||||
**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
title: Use Passive Event Listeners for Scrolling Performance
|
||||
impact: MEDIUM
|
||||
impactDescription: eliminates scroll delay caused by event listeners
|
||||
tags: client, event-listeners, scrolling, performance, touch, wheel
|
||||
---
|
||||
|
||||
## Use Passive Event Listeners for Scrolling Performance
|
||||
|
||||
Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```typescript
|
||||
useEffect(() => {
|
||||
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
|
||||
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
|
||||
|
||||
document.addEventListener('touchstart', handleTouch)
|
||||
document.addEventListener('wheel', handleWheel)
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('touchstart', handleTouch)
|
||||
document.removeEventListener('wheel', handleWheel)
|
||||
}
|
||||
}, [])
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
useEffect(() => {
|
||||
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
|
||||
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
|
||||
|
||||
document.addEventListener('touchstart', handleTouch, { passive: true })
|
||||
document.addEventListener('wheel', handleWheel, { passive: true })
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('touchstart', handleTouch)
|
||||
document.removeEventListener('wheel', handleWheel)
|
||||
}
|
||||
}, [])
|
||||
```
|
||||
|
||||
**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
|
||||
|
||||
**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
title: Use SWR for Automatic Deduplication
|
||||
impact: MEDIUM-HIGH
|
||||
impactDescription: automatic deduplication
|
||||
tags: client, swr, deduplication, data-fetching
|
||||
---
|
||||
|
||||
## Use SWR for Automatic Deduplication
|
||||
|
||||
SWR enables request deduplication, caching, and revalidation across component instances.
|
||||
|
||||
**Incorrect (no deduplication, each instance fetches):**
|
||||
|
||||
```tsx
|
||||
function UserList() {
|
||||
const [users, setUsers] = useState([])
|
||||
useEffect(() => {
|
||||
fetch('/api/users')
|
||||
.then(r => r.json())
|
||||
.then(setUsers)
|
||||
}, [])
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (multiple instances share one request):**
|
||||
|
||||
```tsx
|
||||
import useSWR from 'swr'
|
||||
|
||||
function UserList() {
|
||||
const { data: users } = useSWR('/api/users', fetcher)
|
||||
}
|
||||
```
|
||||
|
||||
**For immutable data:**
|
||||
|
||||
```tsx
|
||||
import { useImmutableSWR } from '@/lib/swr'
|
||||
|
||||
function StaticContent() {
|
||||
const { data } = useImmutableSWR('/api/config', fetcher)
|
||||
}
|
||||
```
|
||||
|
||||
**For mutations:**
|
||||
|
||||
```tsx
|
||||
import { useSWRMutation } from 'swr/mutation'
|
||||
|
||||
function UpdateButton() {
|
||||
const { trigger } = useSWRMutation('/api/user', updateUser)
|
||||
return <button onClick={() => trigger()}>Update</button>
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [https://swr.vercel.app](https://swr.vercel.app)
|
||||
@@ -0,0 +1,107 @@
|
||||
---
|
||||
title: Avoid Layout Thrashing
|
||||
impact: MEDIUM
|
||||
impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks
|
||||
tags: javascript, dom, css, performance, reflow, layout-thrashing
|
||||
---
|
||||
|
||||
## Avoid Layout Thrashing
|
||||
|
||||
Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
|
||||
|
||||
**This is OK (browser batches style changes):**
|
||||
```typescript
|
||||
function updateElementStyles(element: HTMLElement) {
|
||||
// Each line invalidates style, but browser batches the recalculation
|
||||
element.style.width = '100px'
|
||||
element.style.height = '200px'
|
||||
element.style.backgroundColor = 'blue'
|
||||
element.style.border = '1px solid black'
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect (interleaved reads and writes force reflows):**
|
||||
```typescript
|
||||
function layoutThrashing(element: HTMLElement) {
|
||||
element.style.width = '100px'
|
||||
const width = element.offsetWidth // Forces reflow
|
||||
element.style.height = '200px'
|
||||
const height = element.offsetHeight // Forces another reflow
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (batch writes, then read once):**
|
||||
```typescript
|
||||
function updateElementStyles(element: HTMLElement) {
|
||||
// Batch all writes together
|
||||
element.style.width = '100px'
|
||||
element.style.height = '200px'
|
||||
element.style.backgroundColor = 'blue'
|
||||
element.style.border = '1px solid black'
|
||||
|
||||
// Read after all writes are done (single reflow)
|
||||
const { width, height } = element.getBoundingClientRect()
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (batch reads, then writes):**
|
||||
```typescript
|
||||
function avoidThrashing(element: HTMLElement) {
|
||||
// Read phase - all layout queries first
|
||||
const rect1 = element.getBoundingClientRect()
|
||||
const offsetWidth = element.offsetWidth
|
||||
const offsetHeight = element.offsetHeight
|
||||
|
||||
// Write phase - all style changes after
|
||||
element.style.width = '100px'
|
||||
element.style.height = '200px'
|
||||
}
|
||||
```
|
||||
|
||||
**Better: use CSS classes**
|
||||
```css
|
||||
.highlighted-box {
|
||||
width: 100px;
|
||||
height: 200px;
|
||||
background-color: blue;
|
||||
border: 1px solid black;
|
||||
}
|
||||
```
|
||||
```typescript
|
||||
function updateElementStyles(element: HTMLElement) {
|
||||
element.classList.add('highlighted-box')
|
||||
|
||||
const { width, height } = element.getBoundingClientRect()
|
||||
}
|
||||
```
|
||||
|
||||
**React example:**
|
||||
```tsx
|
||||
// Incorrect: interleaving style changes with layout queries
|
||||
function Box({ isHighlighted }: { isHighlighted: boolean }) {
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (ref.current && isHighlighted) {
|
||||
ref.current.style.width = '100px'
|
||||
const width = ref.current.offsetWidth // Forces layout
|
||||
ref.current.style.height = '200px'
|
||||
}
|
||||
}, [isHighlighted])
|
||||
|
||||
return <div ref={ref}>Content</div>
|
||||
}
|
||||
|
||||
// Correct: toggle class
|
||||
function Box({ isHighlighted }: { isHighlighted: boolean }) {
|
||||
return (
|
||||
<div className={isHighlighted ? 'highlighted-box' : ''}>
|
||||
Content
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
|
||||
|
||||
See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
title: Cache Repeated Function Calls
|
||||
impact: MEDIUM
|
||||
impactDescription: avoid redundant computation
|
||||
tags: javascript, cache, memoization, performance
|
||||
---
|
||||
|
||||
## Cache Repeated Function Calls
|
||||
|
||||
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
|
||||
|
||||
**Incorrect (redundant computation):**
|
||||
|
||||
```typescript
|
||||
function ProjectList({ projects }: { projects: Project[] }) {
|
||||
return (
|
||||
<div>
|
||||
{projects.map(project => {
|
||||
// slugify() called 100+ times for same project names
|
||||
const slug = slugify(project.name)
|
||||
|
||||
return <ProjectCard key={project.id} slug={slug} />
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (cached results):**
|
||||
|
||||
```typescript
|
||||
// Module-level cache
|
||||
const slugifyCache = new Map<string, string>()
|
||||
|
||||
function cachedSlugify(text: string): string {
|
||||
if (slugifyCache.has(text)) {
|
||||
return slugifyCache.get(text)!
|
||||
}
|
||||
const result = slugify(text)
|
||||
slugifyCache.set(text, result)
|
||||
return result
|
||||
}
|
||||
|
||||
function ProjectList({ projects }: { projects: Project[] }) {
|
||||
return (
|
||||
<div>
|
||||
{projects.map(project => {
|
||||
// Computed only once per unique project name
|
||||
const slug = cachedSlugify(project.name)
|
||||
|
||||
return <ProjectCard key={project.id} slug={slug} />
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Simpler pattern for single-value functions:**
|
||||
|
||||
```typescript
|
||||
let isLoggedInCache: boolean | null = null
|
||||
|
||||
function isLoggedIn(): boolean {
|
||||
if (isLoggedInCache !== null) {
|
||||
return isLoggedInCache
|
||||
}
|
||||
|
||||
isLoggedInCache = document.cookie.includes('auth=')
|
||||
return isLoggedInCache
|
||||
}
|
||||
|
||||
// Clear cache when auth changes
|
||||
function onAuthChange() {
|
||||
isLoggedInCache = null
|
||||
}
|
||||
```
|
||||
|
||||
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
||||
|
||||
Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
title: Cache Property Access in Loops
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: reduces lookups
|
||||
tags: javascript, loops, optimization, caching
|
||||
---
|
||||
|
||||
## Cache Property Access in Loops
|
||||
|
||||
Cache object property lookups in hot paths.
|
||||
|
||||
**Incorrect (3 lookups × N iterations):**
|
||||
|
||||
```typescript
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
process(obj.config.settings.value)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (1 lookup total):**
|
||||
|
||||
```typescript
|
||||
const value = obj.config.settings.value
|
||||
const len = arr.length
|
||||
for (let i = 0; i < len; i++) {
|
||||
process(value)
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
title: Cache Storage API Calls
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: reduces expensive I/O
|
||||
tags: javascript, localStorage, storage, caching, performance
|
||||
---
|
||||
|
||||
## Cache Storage API Calls
|
||||
|
||||
`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
|
||||
|
||||
**Incorrect (reads storage on every call):**
|
||||
|
||||
```typescript
|
||||
function getTheme() {
|
||||
return localStorage.getItem('theme') ?? 'light'
|
||||
}
|
||||
// Called 10 times = 10 storage reads
|
||||
```
|
||||
|
||||
**Correct (Map cache):**
|
||||
|
||||
```typescript
|
||||
const storageCache = new Map<string, string | null>()
|
||||
|
||||
function getLocalStorage(key: string) {
|
||||
if (!storageCache.has(key)) {
|
||||
storageCache.set(key, localStorage.getItem(key))
|
||||
}
|
||||
return storageCache.get(key)
|
||||
}
|
||||
|
||||
function setLocalStorage(key: string, value: string) {
|
||||
localStorage.setItem(key, value)
|
||||
storageCache.set(key, value) // keep cache in sync
|
||||
}
|
||||
```
|
||||
|
||||
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
||||
|
||||
**Cookie caching:**
|
||||
|
||||
```typescript
|
||||
let cookieCache: Record<string, string> | null = null
|
||||
|
||||
function getCookie(name: string) {
|
||||
if (!cookieCache) {
|
||||
cookieCache = Object.fromEntries(
|
||||
document.cookie.split('; ').map(c => c.split('='))
|
||||
)
|
||||
}
|
||||
return cookieCache[name]
|
||||
}
|
||||
```
|
||||
|
||||
**Important (invalidate on external changes):**
|
||||
|
||||
If storage can change externally (another tab, server-set cookies), invalidate cache:
|
||||
|
||||
```typescript
|
||||
window.addEventListener('storage', (e) => {
|
||||
if (e.key) storageCache.delete(e.key)
|
||||
})
|
||||
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
storageCache.clear()
|
||||
}
|
||||
})
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
title: Combine Multiple Array Iterations
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: reduces iterations
|
||||
tags: javascript, arrays, loops, performance
|
||||
---
|
||||
|
||||
## Combine Multiple Array Iterations
|
||||
|
||||
Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
|
||||
|
||||
**Incorrect (3 iterations):**
|
||||
|
||||
```typescript
|
||||
const admins = users.filter(u => u.isAdmin)
|
||||
const testers = users.filter(u => u.isTester)
|
||||
const inactive = users.filter(u => !u.isActive)
|
||||
```
|
||||
|
||||
**Correct (1 iteration):**
|
||||
|
||||
```typescript
|
||||
const admins: User[] = []
|
||||
const testers: User[] = []
|
||||
const inactive: User[] = []
|
||||
|
||||
for (const user of users) {
|
||||
if (user.isAdmin) admins.push(user)
|
||||
if (user.isTester) testers.push(user)
|
||||
if (!user.isActive) inactive.push(user)
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
title: Early Return from Functions
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids unnecessary computation
|
||||
tags: javascript, functions, optimization, early-return
|
||||
---
|
||||
|
||||
## Early Return from Functions
|
||||
|
||||
Return early when result is determined to skip unnecessary processing.
|
||||
|
||||
**Incorrect (processes all items even after finding answer):**
|
||||
|
||||
```typescript
|
||||
function validateUsers(users: User[]) {
|
||||
let hasError = false
|
||||
let errorMessage = ''
|
||||
|
||||
for (const user of users) {
|
||||
if (!user.email) {
|
||||
hasError = true
|
||||
errorMessage = 'Email required'
|
||||
}
|
||||
if (!user.name) {
|
||||
hasError = true
|
||||
errorMessage = 'Name required'
|
||||
}
|
||||
// Continues checking all users even after error found
|
||||
}
|
||||
|
||||
return hasError ? { valid: false, error: errorMessage } : { valid: true }
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (returns immediately on first error):**
|
||||
|
||||
```typescript
|
||||
function validateUsers(users: User[]) {
|
||||
for (const user of users) {
|
||||
if (!user.email) {
|
||||
return { valid: false, error: 'Email required' }
|
||||
}
|
||||
if (!user.name) {
|
||||
return { valid: false, error: 'Name required' }
|
||||
}
|
||||
}
|
||||
|
||||
return { valid: true }
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
title: Hoist RegExp Creation
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids recreation
|
||||
tags: javascript, regexp, optimization, memoization
|
||||
---
|
||||
|
||||
## Hoist RegExp Creation
|
||||
|
||||
Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
|
||||
|
||||
**Incorrect (new RegExp every render):**
|
||||
|
||||
```tsx
|
||||
function Highlighter({ text, query }: Props) {
|
||||
const regex = new RegExp(`(${query})`, 'gi')
|
||||
const parts = text.split(regex)
|
||||
return <>{parts.map((part, i) => ...)}</>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (memoize or hoist):**
|
||||
|
||||
```tsx
|
||||
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
|
||||
function Highlighter({ text, query }: Props) {
|
||||
const regex = useMemo(
|
||||
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
|
||||
[query]
|
||||
)
|
||||
const parts = text.split(regex)
|
||||
return <>{parts.map((part, i) => ...)}</>
|
||||
}
|
||||
```
|
||||
|
||||
**Warning (global regex has mutable state):**
|
||||
|
||||
Global regex (`/g`) has mutable `lastIndex` state:
|
||||
|
||||
```typescript
|
||||
const regex = /foo/g
|
||||
regex.test('foo') // true, lastIndex = 3
|
||||
regex.test('foo') // false, lastIndex = 0
|
||||
```
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
title: Build Index Maps for Repeated Lookups
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: 1M ops to 2K ops
|
||||
tags: javascript, map, indexing, optimization, performance
|
||||
---
|
||||
|
||||
## Build Index Maps for Repeated Lookups
|
||||
|
||||
Multiple `.find()` calls by the same key should use a Map.
|
||||
|
||||
**Incorrect (O(n) per lookup):**
|
||||
|
||||
```typescript
|
||||
function processOrders(orders: Order[], users: User[]) {
|
||||
return orders.map(order => ({
|
||||
...order,
|
||||
user: users.find(u => u.id === order.userId)
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (O(1) per lookup):**
|
||||
|
||||
```typescript
|
||||
function processOrders(orders: Order[], users: User[]) {
|
||||
const userById = new Map(users.map(u => [u.id, u]))
|
||||
|
||||
return orders.map(order => ({
|
||||
...order,
|
||||
user: userById.get(order.userId)
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
Build map once (O(n)), then all lookups are O(1).
|
||||
For 1000 orders × 1000 users: 1M ops → 2K ops.
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
title: Early Length Check for Array Comparisons
|
||||
impact: MEDIUM-HIGH
|
||||
impactDescription: avoids expensive operations when lengths differ
|
||||
tags: javascript, arrays, performance, optimization, comparison
|
||||
---
|
||||
|
||||
## Early Length Check for Array Comparisons
|
||||
|
||||
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
|
||||
|
||||
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
|
||||
|
||||
**Incorrect (always runs expensive comparison):**
|
||||
|
||||
```typescript
|
||||
function hasChanges(current: string[], original: string[]) {
|
||||
// Always sorts and joins, even when lengths differ
|
||||
return current.sort().join() !== original.sort().join()
|
||||
}
|
||||
```
|
||||
|
||||
Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
|
||||
|
||||
**Correct (O(1) length check first):**
|
||||
|
||||
```typescript
|
||||
function hasChanges(current: string[], original: string[]) {
|
||||
// Early return if lengths differ
|
||||
if (current.length !== original.length) {
|
||||
return true
|
||||
}
|
||||
// Only sort when lengths match
|
||||
const currentSorted = current.toSorted()
|
||||
const originalSorted = original.toSorted()
|
||||
for (let i = 0; i < currentSorted.length; i++) {
|
||||
if (currentSorted[i] !== originalSorted[i]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
```
|
||||
|
||||
This new approach is more efficient because:
|
||||
- It avoids the overhead of sorting and joining the arrays when lengths differ
|
||||
- It avoids consuming memory for the joined strings (especially important for large arrays)
|
||||
- It avoids mutating the original arrays
|
||||
- It returns early when a difference is found
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
title: Use Loop for Min/Max Instead of Sort
|
||||
impact: LOW
|
||||
impactDescription: O(n) instead of O(n log n)
|
||||
tags: javascript, arrays, performance, sorting, algorithms
|
||||
---
|
||||
|
||||
## Use Loop for Min/Max Instead of Sort
|
||||
|
||||
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
|
||||
|
||||
**Incorrect (O(n log n) - sort to find latest):**
|
||||
|
||||
```typescript
|
||||
interface Project {
|
||||
id: string
|
||||
name: string
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
function getLatestProject(projects: Project[]) {
|
||||
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
|
||||
return sorted[0]
|
||||
}
|
||||
```
|
||||
|
||||
Sorts the entire array just to find the maximum value.
|
||||
|
||||
**Incorrect (O(n log n) - sort for oldest and newest):**
|
||||
|
||||
```typescript
|
||||
function getOldestAndNewest(projects: Project[]) {
|
||||
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
|
||||
return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
|
||||
}
|
||||
```
|
||||
|
||||
Still sorts unnecessarily when only min/max are needed.
|
||||
|
||||
**Correct (O(n) - single loop):**
|
||||
|
||||
```typescript
|
||||
function getLatestProject(projects: Project[]) {
|
||||
if (projects.length === 0) return null
|
||||
|
||||
let latest = projects[0]
|
||||
|
||||
for (let i = 1; i < projects.length; i++) {
|
||||
if (projects[i].updatedAt > latest.updatedAt) {
|
||||
latest = projects[i]
|
||||
}
|
||||
}
|
||||
|
||||
return latest
|
||||
}
|
||||
|
||||
function getOldestAndNewest(projects: Project[]) {
|
||||
if (projects.length === 0) return { oldest: null, newest: null }
|
||||
|
||||
let oldest = projects[0]
|
||||
let newest = projects[0]
|
||||
|
||||
for (let i = 1; i < projects.length; i++) {
|
||||
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
|
||||
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
|
||||
}
|
||||
|
||||
return { oldest, newest }
|
||||
}
|
||||
```
|
||||
|
||||
Single pass through the array, no copying, no sorting.
|
||||
|
||||
**Alternative (Math.min/Math.max for small arrays):**
|
||||
|
||||
```typescript
|
||||
const numbers = [5, 2, 8, 1, 9]
|
||||
const min = Math.min(...numbers)
|
||||
const max = Math.max(...numbers)
|
||||
```
|
||||
|
||||
This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
title: Use Set/Map for O(1) Lookups
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: O(n) to O(1)
|
||||
tags: javascript, set, map, data-structures, performance
|
||||
---
|
||||
|
||||
## Use Set/Map for O(1) Lookups
|
||||
|
||||
Convert arrays to Set/Map for repeated membership checks.
|
||||
|
||||
**Incorrect (O(n) per check):**
|
||||
|
||||
```typescript
|
||||
const allowedIds = ['a', 'b', 'c', ...]
|
||||
items.filter(item => allowedIds.includes(item.id))
|
||||
```
|
||||
|
||||
**Correct (O(1) per check):**
|
||||
|
||||
```typescript
|
||||
const allowedIds = new Set(['a', 'b', 'c', ...])
|
||||
items.filter(item => allowedIds.has(item.id))
|
||||
```
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
title: Use toSorted() Instead of sort() for Immutability
|
||||
impact: MEDIUM-HIGH
|
||||
impactDescription: prevents mutation bugs in React state
|
||||
tags: javascript, arrays, immutability, react, state, mutation
|
||||
---
|
||||
|
||||
## Use toSorted() Instead of sort() for Immutability
|
||||
|
||||
`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
|
||||
|
||||
**Incorrect (mutates original array):**
|
||||
|
||||
```typescript
|
||||
function UserList({ users }: { users: User[] }) {
|
||||
// Mutates the users prop array!
|
||||
const sorted = useMemo(
|
||||
() => users.sort((a, b) => a.name.localeCompare(b.name)),
|
||||
[users]
|
||||
)
|
||||
return <div>{sorted.map(renderUser)}</div>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (creates new array):**
|
||||
|
||||
```typescript
|
||||
function UserList({ users }: { users: User[] }) {
|
||||
// Creates new sorted array, original unchanged
|
||||
const sorted = useMemo(
|
||||
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
|
||||
[users]
|
||||
)
|
||||
return <div>{sorted.map(renderUser)}</div>
|
||||
}
|
||||
```
|
||||
|
||||
**Why this matters in React:**
|
||||
|
||||
1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
|
||||
2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
|
||||
|
||||
**Browser support (fallback for older browsers):**
|
||||
|
||||
`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
|
||||
|
||||
```typescript
|
||||
// Fallback for older browsers
|
||||
const sorted = [...items].sort((a, b) => a.value - b.value)
|
||||
```
|
||||
|
||||
**Other immutable array methods:**
|
||||
|
||||
- `.toSorted()` - immutable sort
|
||||
- `.toReversed()` - immutable reverse
|
||||
- `.toSpliced()` - immutable splice
|
||||
- `.with()` - immutable element replacement
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
title: Use Activity Component for Show/Hide
|
||||
impact: MEDIUM
|
||||
impactDescription: preserves state/DOM
|
||||
tags: rendering, activity, visibility, state-preservation
|
||||
---
|
||||
|
||||
## Use Activity Component for Show/Hide
|
||||
|
||||
Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
|
||||
|
||||
**Usage:**
|
||||
|
||||
```tsx
|
||||
import { Activity } from 'react'
|
||||
|
||||
function Dropdown({ isOpen }: Props) {
|
||||
return (
|
||||
<Activity mode={isOpen ? 'visible' : 'hidden'}>
|
||||
<ExpensiveMenu />
|
||||
</Activity>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Avoids expensive re-renders and state loss.
|
||||
@@ -0,0 +1,47 @@
|
||||
---
|
||||
title: Animate SVG Wrapper Instead of SVG Element
|
||||
impact: LOW
|
||||
impactDescription: enables hardware acceleration
|
||||
tags: rendering, svg, css, animation, performance
|
||||
---
|
||||
|
||||
## Animate SVG Wrapper Instead of SVG Element
|
||||
|
||||
Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
|
||||
|
||||
**Incorrect (animating SVG directly - no hardware acceleration):**
|
||||
|
||||
```tsx
|
||||
function LoadingSpinner() {
|
||||
return (
|
||||
<svg
|
||||
className="animate-spin"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (animating wrapper div - hardware accelerated):**
|
||||
|
||||
```tsx
|
||||
function LoadingSpinner() {
|
||||
return (
|
||||
<div className="animate-spin">
|
||||
<svg
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
title: Use Explicit Conditional Rendering
|
||||
impact: LOW
|
||||
impactDescription: prevents rendering 0 or NaN
|
||||
tags: rendering, conditional, jsx, falsy-values
|
||||
---
|
||||
|
||||
## Use Explicit Conditional Rendering
|
||||
|
||||
Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
|
||||
|
||||
**Incorrect (renders "0" when count is 0):**
|
||||
|
||||
```tsx
|
||||
function Badge({ count }: { count: number }) {
|
||||
return (
|
||||
<div>
|
||||
{count && <span className="badge">{count}</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// When count = 0, renders: <div>0</div>
|
||||
// When count = 5, renders: <div><span class="badge">5</span></div>
|
||||
```
|
||||
|
||||
**Correct (renders nothing when count is 0):**
|
||||
|
||||
```tsx
|
||||
function Badge({ count }: { count: number }) {
|
||||
return (
|
||||
<div>
|
||||
{count > 0 ? <span className="badge">{count}</span> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// When count = 0, renders: <div></div>
|
||||
// When count = 5, renders: <div><span class="badge">5</span></div>
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: CSS content-visibility for Long Lists
|
||||
impact: HIGH
|
||||
impactDescription: faster initial render
|
||||
tags: rendering, css, content-visibility, long-lists
|
||||
---
|
||||
|
||||
## CSS content-visibility for Long Lists
|
||||
|
||||
Apply `content-visibility: auto` to defer off-screen rendering.
|
||||
|
||||
**CSS:**
|
||||
|
||||
```css
|
||||
.message-item {
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: 0 80px;
|
||||
}
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```tsx
|
||||
function MessageList({ messages }: { messages: Message[] }) {
|
||||
return (
|
||||
<div className="overflow-y-auto h-screen">
|
||||
{messages.map(msg => (
|
||||
<div key={msg.id} className="message-item">
|
||||
<Avatar user={msg.author} />
|
||||
<div>{msg.content}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
title: Hoist Static JSX Elements
|
||||
impact: LOW
|
||||
impactDescription: avoids re-creation
|
||||
tags: rendering, jsx, static, optimization
|
||||
---
|
||||
|
||||
## Hoist Static JSX Elements
|
||||
|
||||
Extract static JSX outside components to avoid re-creation.
|
||||
|
||||
**Incorrect (recreates element every render):**
|
||||
|
||||
```tsx
|
||||
function LoadingSkeleton() {
|
||||
return <div className="animate-pulse h-20 bg-gray-200" />
|
||||
}
|
||||
|
||||
function Container() {
|
||||
return (
|
||||
<div>
|
||||
{loading && <LoadingSkeleton />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (reuses same element):**
|
||||
|
||||
```tsx
|
||||
const loadingSkeleton = (
|
||||
<div className="animate-pulse h-20 bg-gray-200" />
|
||||
)
|
||||
|
||||
function Container() {
|
||||
return (
|
||||
<div>
|
||||
{loading && loadingSkeleton}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
|
||||
|
||||
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
title: Prevent Hydration Mismatch Without Flickering
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids visual flicker and hydration errors
|
||||
tags: rendering, ssr, hydration, localStorage, flicker
|
||||
---
|
||||
|
||||
## Prevent Hydration Mismatch Without Flickering
|
||||
|
||||
When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
|
||||
|
||||
**Incorrect (breaks SSR):**
|
||||
|
||||
```tsx
|
||||
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||
// localStorage is not available on server - throws error
|
||||
const theme = localStorage.getItem('theme') || 'light'
|
||||
|
||||
return (
|
||||
<div className={theme}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Server-side rendering will fail because `localStorage` is undefined.
|
||||
|
||||
**Incorrect (visual flickering):**
|
||||
|
||||
```tsx
|
||||
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||
const [theme, setTheme] = useState('light')
|
||||
|
||||
useEffect(() => {
|
||||
// Runs after hydration - causes visible flash
|
||||
const stored = localStorage.getItem('theme')
|
||||
if (stored) {
|
||||
setTheme(stored)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className={theme}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
|
||||
|
||||
**Correct (no flicker, no hydration mismatch):**
|
||||
|
||||
```tsx
|
||||
function ThemeWrapper({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<>
|
||||
<div id="theme-wrapper">
|
||||
{children}
|
||||
</div>
|
||||
<script
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `
|
||||
(function() {
|
||||
try {
|
||||
var theme = localStorage.getItem('theme') || 'light';
|
||||
var el = document.getElementById('theme-wrapper');
|
||||
if (el) el.className = theme;
|
||||
} catch (e) {}
|
||||
})();
|
||||
`,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
|
||||
|
||||
This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
title: Suppress Expected Hydration Mismatches
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids noisy hydration warnings for known differences
|
||||
tags: rendering, hydration, ssr, nextjs
|
||||
---
|
||||
|
||||
## Suppress Expected Hydration Mismatches
|
||||
|
||||
In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.
|
||||
|
||||
**Incorrect (known mismatch warnings):**
|
||||
|
||||
```tsx
|
||||
function Timestamp() {
|
||||
return <span>{new Date().toLocaleString()}</span>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (suppress expected mismatch only):**
|
||||
|
||||
```tsx
|
||||
function Timestamp() {
|
||||
return (
|
||||
<span suppressHydrationWarning>
|
||||
{new Date().toLocaleString()}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
title: Optimize SVG Precision
|
||||
impact: LOW
|
||||
impactDescription: reduces file size
|
||||
tags: rendering, svg, optimization, svgo
|
||||
---
|
||||
|
||||
## Optimize SVG Precision
|
||||
|
||||
Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
|
||||
|
||||
**Incorrect (excessive precision):**
|
||||
|
||||
```svg
|
||||
<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
|
||||
```
|
||||
|
||||
**Correct (1 decimal place):**
|
||||
|
||||
```svg
|
||||
<path d="M 10.3 20.8 L 30.9 40.2" />
|
||||
```
|
||||
|
||||
**Automate with SVGO:**
|
||||
|
||||
```bash
|
||||
npx svgo --precision=1 --multipass icon.svg
|
||||
```
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
title: Use useTransition Over Manual Loading States
|
||||
impact: LOW
|
||||
impactDescription: reduces re-renders and improves code clarity
|
||||
tags: rendering, transitions, useTransition, loading, state
|
||||
---
|
||||
|
||||
## Use useTransition Over Manual Loading States
|
||||
|
||||
Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.
|
||||
|
||||
**Incorrect (manual loading state):**
|
||||
|
||||
```tsx
|
||||
function SearchResults() {
|
||||
const [query, setQuery] = useState('')
|
||||
const [results, setResults] = useState([])
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const handleSearch = async (value: string) => {
|
||||
setIsLoading(true)
|
||||
setQuery(value)
|
||||
const data = await fetchResults(value)
|
||||
setResults(data)
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<input onChange={(e) => handleSearch(e.target.value)} />
|
||||
{isLoading && <Spinner />}
|
||||
<ResultsList results={results} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (useTransition with built-in pending state):**
|
||||
|
||||
```tsx
|
||||
import { useTransition, useState } from 'react'
|
||||
|
||||
function SearchResults() {
|
||||
const [query, setQuery] = useState('')
|
||||
const [results, setResults] = useState([])
|
||||
const [isPending, startTransition] = useTransition()
|
||||
|
||||
const handleSearch = (value: string) => {
|
||||
setQuery(value) // Update input immediately
|
||||
|
||||
startTransition(async () => {
|
||||
// Fetch and update results
|
||||
const data = await fetchResults(value)
|
||||
setResults(data)
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<input onChange={(e) => handleSearch(e.target.value)} />
|
||||
{isPending && <Spinner />}
|
||||
<ResultsList results={results} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
|
||||
- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`
|
||||
- **Error resilience**: Pending state correctly resets even if the transition throws
|
||||
- **Better responsiveness**: Keeps the UI responsive during updates
|
||||
- **Interrupt handling**: New transitions automatically cancel pending ones
|
||||
|
||||
Reference: [useTransition](https://react.dev/reference/react/useTransition)
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
title: Defer State Reads to Usage Point
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids unnecessary subscriptions
|
||||
tags: rerender, searchParams, localStorage, optimization
|
||||
---
|
||||
|
||||
## Defer State Reads to Usage Point
|
||||
|
||||
Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
|
||||
|
||||
**Incorrect (subscribes to all searchParams changes):**
|
||||
|
||||
```tsx
|
||||
function ShareButton({ chatId }: { chatId: string }) {
|
||||
const searchParams = useSearchParams()
|
||||
|
||||
const handleShare = () => {
|
||||
const ref = searchParams.get('ref')
|
||||
shareChat(chatId, { ref })
|
||||
}
|
||||
|
||||
return <button onClick={handleShare}>Share</button>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (reads on demand, no subscription):**
|
||||
|
||||
```tsx
|
||||
function ShareButton({ chatId }: { chatId: string }) {
|
||||
const handleShare = () => {
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const ref = params.get('ref')
|
||||
shareChat(chatId, { ref })
|
||||
}
|
||||
|
||||
return <button onClick={handleShare}>Share</button>
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
title: Narrow Effect Dependencies
|
||||
impact: LOW
|
||||
impactDescription: minimizes effect re-runs
|
||||
tags: rerender, useEffect, dependencies, optimization
|
||||
---
|
||||
|
||||
## Narrow Effect Dependencies
|
||||
|
||||
Specify primitive dependencies instead of objects to minimize effect re-runs.
|
||||
|
||||
**Incorrect (re-runs on any user field change):**
|
||||
|
||||
```tsx
|
||||
useEffect(() => {
|
||||
console.log(user.id)
|
||||
}, [user])
|
||||
```
|
||||
|
||||
**Correct (re-runs only when id changes):**
|
||||
|
||||
```tsx
|
||||
useEffect(() => {
|
||||
console.log(user.id)
|
||||
}, [user.id])
|
||||
```
|
||||
|
||||
**For derived state, compute outside effect:**
|
||||
|
||||
```tsx
|
||||
// Incorrect: runs on width=767, 766, 765...
|
||||
useEffect(() => {
|
||||
if (width < 768) {
|
||||
enableMobileMode()
|
||||
}
|
||||
}, [width])
|
||||
|
||||
// Correct: runs only on boolean transition
|
||||
const isMobile = width < 768
|
||||
useEffect(() => {
|
||||
if (isMobile) {
|
||||
enableMobileMode()
|
||||
}
|
||||
}, [isMobile])
|
||||
```
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
title: Calculate Derived State During Rendering
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids redundant renders and state drift
|
||||
tags: rerender, derived-state, useEffect, state
|
||||
---
|
||||
|
||||
## Calculate Derived State During Rendering
|
||||
|
||||
If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.
|
||||
|
||||
**Incorrect (redundant state and effect):**
|
||||
|
||||
```tsx
|
||||
function Form() {
|
||||
const [firstName, setFirstName] = useState('First')
|
||||
const [lastName, setLastName] = useState('Last')
|
||||
const [fullName, setFullName] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
setFullName(firstName + ' ' + lastName)
|
||||
}, [firstName, lastName])
|
||||
|
||||
return <p>{fullName}</p>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (derive during render):**
|
||||
|
||||
```tsx
|
||||
function Form() {
|
||||
const [firstName, setFirstName] = useState('First')
|
||||
const [lastName, setLastName] = useState('Last')
|
||||
const fullName = firstName + ' ' + lastName
|
||||
|
||||
return <p>{fullName}</p>
|
||||
}
|
||||
```
|
||||
|
||||
References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
title: Subscribe to Derived State
|
||||
impact: MEDIUM
|
||||
impactDescription: reduces re-render frequency
|
||||
tags: rerender, derived-state, media-query, optimization
|
||||
---
|
||||
|
||||
## Subscribe to Derived State
|
||||
|
||||
Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
|
||||
|
||||
**Incorrect (re-renders on every pixel change):**
|
||||
|
||||
```tsx
|
||||
function Sidebar() {
|
||||
const width = useWindowWidth() // updates continuously
|
||||
const isMobile = width < 768
|
||||
return <nav className={isMobile ? 'mobile' : 'desktop'} />
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (re-renders only when boolean changes):**
|
||||
|
||||
```tsx
|
||||
function Sidebar() {
|
||||
const isMobile = useMediaQuery('(max-width: 767px)')
|
||||
return <nav className={isMobile ? 'mobile' : 'desktop'} />
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
title: Use Functional setState Updates
|
||||
impact: MEDIUM
|
||||
impactDescription: prevents stale closures and unnecessary callback recreations
|
||||
tags: react, hooks, useState, useCallback, callbacks, closures
|
||||
---
|
||||
|
||||
## Use Functional setState Updates
|
||||
|
||||
When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
|
||||
|
||||
**Incorrect (requires state as dependency):**
|
||||
|
||||
```tsx
|
||||
function TodoList() {
|
||||
const [items, setItems] = useState(initialItems)
|
||||
|
||||
// Callback must depend on items, recreated on every items change
|
||||
const addItems = useCallback((newItems: Item[]) => {
|
||||
setItems([...items, ...newItems])
|
||||
}, [items]) // ❌ items dependency causes recreations
|
||||
|
||||
// Risk of stale closure if dependency is forgotten
|
||||
const removeItem = useCallback((id: string) => {
|
||||
setItems(items.filter(item => item.id !== id))
|
||||
}, []) // ❌ Missing items dependency - will use stale items!
|
||||
|
||||
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
|
||||
}
|
||||
```
|
||||
|
||||
The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
|
||||
|
||||
**Correct (stable callbacks, no stale closures):**
|
||||
|
||||
```tsx
|
||||
function TodoList() {
|
||||
const [items, setItems] = useState(initialItems)
|
||||
|
||||
// Stable callback, never recreated
|
||||
const addItems = useCallback((newItems: Item[]) => {
|
||||
setItems(curr => [...curr, ...newItems])
|
||||
}, []) // ✅ No dependencies needed
|
||||
|
||||
// Always uses latest state, no stale closure risk
|
||||
const removeItem = useCallback((id: string) => {
|
||||
setItems(curr => curr.filter(item => item.id !== id))
|
||||
}, []) // ✅ Safe and stable
|
||||
|
||||
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
|
||||
1. **Stable callback references** - Callbacks don't need to be recreated when state changes
|
||||
2. **No stale closures** - Always operates on the latest state value
|
||||
3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
|
||||
4. **Prevents bugs** - Eliminates the most common source of React closure bugs
|
||||
|
||||
**When to use functional updates:**
|
||||
|
||||
- Any setState that depends on the current state value
|
||||
- Inside useCallback/useMemo when state is needed
|
||||
- Event handlers that reference state
|
||||
- Async operations that update state
|
||||
|
||||
**When direct updates are fine:**
|
||||
|
||||
- Setting state to a static value: `setCount(0)`
|
||||
- Setting state from props/arguments only: `setName(newName)`
|
||||
- State doesn't depend on previous value
|
||||
|
||||
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
title: Use Lazy State Initialization
|
||||
impact: MEDIUM
|
||||
impactDescription: wasted computation on every render
|
||||
tags: react, hooks, useState, performance, initialization
|
||||
---
|
||||
|
||||
## Use Lazy State Initialization
|
||||
|
||||
Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
|
||||
|
||||
**Incorrect (runs on every render):**
|
||||
|
||||
```tsx
|
||||
function FilteredList({ items }: { items: Item[] }) {
|
||||
// buildSearchIndex() runs on EVERY render, even after initialization
|
||||
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
// When query changes, buildSearchIndex runs again unnecessarily
|
||||
return <SearchResults index={searchIndex} query={query} />
|
||||
}
|
||||
|
||||
function UserProfile() {
|
||||
// JSON.parse runs on every render
|
||||
const [settings, setSettings] = useState(
|
||||
JSON.parse(localStorage.getItem('settings') || '{}')
|
||||
)
|
||||
|
||||
return <SettingsForm settings={settings} onChange={setSettings} />
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (runs only once):**
|
||||
|
||||
```tsx
|
||||
function FilteredList({ items }: { items: Item[] }) {
|
||||
// buildSearchIndex() runs ONLY on initial render
|
||||
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
return <SearchResults index={searchIndex} query={query} />
|
||||
}
|
||||
|
||||
function UserProfile() {
|
||||
// JSON.parse runs only on initial render
|
||||
const [settings, setSettings] = useState(() => {
|
||||
const stored = localStorage.getItem('settings')
|
||||
return stored ? JSON.parse(stored) : {}
|
||||
})
|
||||
|
||||
return <SettingsForm settings={settings} onChange={setSettings} />
|
||||
}
|
||||
```
|
||||
|
||||
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
|
||||
|
||||
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
|
||||
title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant
|
||||
impact: MEDIUM
|
||||
impactDescription: restores memoization by using a constant for default value
|
||||
tags: rerender, memo, optimization
|
||||
|
||||
---
|
||||
|
||||
## Extract Default Non-primitive Parameter Value from Memoized Component to Constant
|
||||
|
||||
When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.
|
||||
|
||||
To address this issue, extract the default value into a constant.
|
||||
|
||||
**Incorrect (`onClick` has different values on every rerender):**
|
||||
|
||||
```tsx
|
||||
const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
|
||||
// ...
|
||||
})
|
||||
|
||||
// Used without optional onClick
|
||||
<UserAvatar />
|
||||
```
|
||||
|
||||
**Correct (stable default value):**
|
||||
|
||||
```tsx
|
||||
const NOOP = () => {};
|
||||
|
||||
const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
|
||||
// ...
|
||||
})
|
||||
|
||||
// Used without optional onClick
|
||||
<UserAvatar />
|
||||
```
|
||||
@@ -0,0 +1,44 @@
|
||||
---
|
||||
title: Extract to Memoized Components
|
||||
impact: MEDIUM
|
||||
impactDescription: enables early returns
|
||||
tags: rerender, memo, useMemo, optimization
|
||||
---
|
||||
|
||||
## Extract to Memoized Components
|
||||
|
||||
Extract expensive work into memoized components to enable early returns before computation.
|
||||
|
||||
**Incorrect (computes avatar even when loading):**
|
||||
|
||||
```tsx
|
||||
function Profile({ user, loading }: Props) {
|
||||
const avatar = useMemo(() => {
|
||||
const id = computeAvatarId(user)
|
||||
return <Avatar id={id} />
|
||||
}, [user])
|
||||
|
||||
if (loading) return <Skeleton />
|
||||
return <div>{avatar}</div>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (skips computation when loading):**
|
||||
|
||||
```tsx
|
||||
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
|
||||
const id = useMemo(() => computeAvatarId(user), [user])
|
||||
return <Avatar id={id} />
|
||||
})
|
||||
|
||||
function Profile({ user, loading }: Props) {
|
||||
if (loading) return <Skeleton />
|
||||
return (
|
||||
<div>
|
||||
<UserAvatar user={user} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
title: Put Interaction Logic in Event Handlers
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids effect re-runs and duplicate side effects
|
||||
tags: rerender, useEffect, events, side-effects, dependencies
|
||||
---
|
||||
|
||||
## Put Interaction Logic in Event Handlers
|
||||
|
||||
If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.
|
||||
|
||||
**Incorrect (event modeled as state + effect):**
|
||||
|
||||
```tsx
|
||||
function Form() {
|
||||
const [submitted, setSubmitted] = useState(false)
|
||||
const theme = useContext(ThemeContext)
|
||||
|
||||
useEffect(() => {
|
||||
if (submitted) {
|
||||
post('/api/register')
|
||||
showToast('Registered', theme)
|
||||
}
|
||||
}, [submitted, theme])
|
||||
|
||||
return <button onClick={() => setSubmitted(true)}>Submit</button>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (do it in the handler):**
|
||||
|
||||
```tsx
|
||||
function Form() {
|
||||
const theme = useContext(ThemeContext)
|
||||
|
||||
function handleSubmit() {
|
||||
post('/api/register')
|
||||
showToast('Registered', theme)
|
||||
}
|
||||
|
||||
return <button onClick={handleSubmit}>Submit</button>
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
title: Do not wrap a simple expression with a primitive result type in useMemo
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: wasted computation on every render
|
||||
tags: rerender, useMemo, optimization
|
||||
---
|
||||
|
||||
## Do not wrap a simple expression with a primitive result type in useMemo
|
||||
|
||||
When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.
|
||||
Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
function Header({ user, notifications }: Props) {
|
||||
const isLoading = useMemo(() => {
|
||||
return user.isLoading || notifications.isLoading
|
||||
}, [user.isLoading, notifications.isLoading])
|
||||
|
||||
if (isLoading) return <Skeleton />
|
||||
// return some markup
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
function Header({ user, notifications }: Props) {
|
||||
const isLoading = user.isLoading || notifications.isLoading
|
||||
|
||||
if (isLoading) return <Skeleton />
|
||||
// return some markup
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
title: Use Transitions for Non-Urgent Updates
|
||||
impact: MEDIUM
|
||||
impactDescription: maintains UI responsiveness
|
||||
tags: rerender, transitions, startTransition, performance
|
||||
---
|
||||
|
||||
## Use Transitions for Non-Urgent Updates
|
||||
|
||||
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
|
||||
|
||||
**Incorrect (blocks UI on every scroll):**
|
||||
|
||||
```tsx
|
||||
function ScrollTracker() {
|
||||
const [scrollY, setScrollY] = useState(0)
|
||||
useEffect(() => {
|
||||
const handler = () => setScrollY(window.scrollY)
|
||||
window.addEventListener('scroll', handler, { passive: true })
|
||||
return () => window.removeEventListener('scroll', handler)
|
||||
}, [])
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (non-blocking updates):**
|
||||
|
||||
```tsx
|
||||
import { startTransition } from 'react'
|
||||
|
||||
function ScrollTracker() {
|
||||
const [scrollY, setScrollY] = useState(0)
|
||||
useEffect(() => {
|
||||
const handler = () => {
|
||||
startTransition(() => setScrollY(window.scrollY))
|
||||
}
|
||||
window.addEventListener('scroll', handler, { passive: true })
|
||||
return () => window.removeEventListener('scroll', handler)
|
||||
}, [])
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
title: Use useRef for Transient Values
|
||||
impact: MEDIUM
|
||||
impactDescription: avoids unnecessary re-renders on frequent updates
|
||||
tags: rerender, useref, state, performance
|
||||
---
|
||||
|
||||
## Use useRef for Transient Values
|
||||
|
||||
When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
|
||||
|
||||
**Incorrect (renders every update):**
|
||||
|
||||
```tsx
|
||||
function Tracker() {
|
||||
const [lastX, setLastX] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
const onMove = (e: MouseEvent) => setLastX(e.clientX)
|
||||
window.addEventListener('mousemove', onMove)
|
||||
return () => window.removeEventListener('mousemove', onMove)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: lastX,
|
||||
width: 8,
|
||||
height: 8,
|
||||
background: 'black',
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (no re-render for tracking):**
|
||||
|
||||
```tsx
|
||||
function Tracker() {
|
||||
const lastXRef = useRef(0)
|
||||
const dotRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const onMove = (e: MouseEvent) => {
|
||||
lastXRef.current = e.clientX
|
||||
const node = dotRef.current
|
||||
if (node) {
|
||||
node.style.transform = `translateX(${e.clientX}px)`
|
||||
}
|
||||
}
|
||||
window.addEventListener('mousemove', onMove)
|
||||
return () => window.removeEventListener('mousemove', onMove)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={dotRef}
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: 8,
|
||||
height: 8,
|
||||
background: 'black',
|
||||
transform: 'translateX(0px)',
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
title: Use after() for Non-Blocking Operations
|
||||
impact: MEDIUM
|
||||
impactDescription: faster response times
|
||||
tags: server, async, logging, analytics, side-effects
|
||||
---
|
||||
|
||||
## Use after() for Non-Blocking Operations
|
||||
|
||||
Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
|
||||
|
||||
**Incorrect (blocks response):**
|
||||
|
||||
```tsx
|
||||
import { logUserAction } from '@/app/utils'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
// Perform mutation
|
||||
await updateDatabase(request)
|
||||
|
||||
// Logging blocks the response
|
||||
const userAgent = request.headers.get('user-agent') || 'unknown'
|
||||
await logUserAction({ userAgent })
|
||||
|
||||
return new Response(JSON.stringify({ status: 'success' }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (non-blocking):**
|
||||
|
||||
```tsx
|
||||
import { after } from 'next/server'
|
||||
import { headers, cookies } from 'next/headers'
|
||||
import { logUserAction } from '@/app/utils'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
// Perform mutation
|
||||
await updateDatabase(request)
|
||||
|
||||
// Log after response is sent
|
||||
after(async () => {
|
||||
const userAgent = (await headers()).get('user-agent') || 'unknown'
|
||||
const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
|
||||
|
||||
logUserAction({ sessionCookie, userAgent })
|
||||
})
|
||||
|
||||
return new Response(JSON.stringify({ status: 'success' }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
The response is sent immediately while logging happens in the background.
|
||||
|
||||
**Common use cases:**
|
||||
|
||||
- Analytics tracking
|
||||
- Audit logging
|
||||
- Sending notifications
|
||||
- Cache invalidation
|
||||
- Cleanup tasks
|
||||
|
||||
**Important notes:**
|
||||
|
||||
- `after()` runs even if the response fails or redirects
|
||||
- Works in Server Actions, Route Handlers, and Server Components
|
||||
|
||||
Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
|
||||
@@ -0,0 +1,96 @@
|
||||
---
|
||||
title: Authenticate Server Actions Like API Routes
|
||||
impact: CRITICAL
|
||||
impactDescription: prevents unauthorized access to server mutations
|
||||
tags: server, server-actions, authentication, security, authorization
|
||||
---
|
||||
|
||||
## Authenticate Server Actions Like API Routes
|
||||
|
||||
**Impact: CRITICAL (prevents unauthorized access to server mutations)**
|
||||
|
||||
Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.
|
||||
|
||||
Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."
|
||||
|
||||
**Incorrect (no authentication check):**
|
||||
|
||||
```typescript
|
||||
'use server'
|
||||
|
||||
export async function deleteUser(userId: string) {
|
||||
// Anyone can call this! No auth check
|
||||
await db.user.delete({ where: { id: userId } })
|
||||
return { success: true }
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (authentication inside the action):**
|
||||
|
||||
```typescript
|
||||
'use server'
|
||||
|
||||
import { verifySession } from '@/lib/auth'
|
||||
import { unauthorized } from '@/lib/errors'
|
||||
|
||||
export async function deleteUser(userId: string) {
|
||||
// Always check auth inside the action
|
||||
const session = await verifySession()
|
||||
|
||||
if (!session) {
|
||||
throw unauthorized('Must be logged in')
|
||||
}
|
||||
|
||||
// Check authorization too
|
||||
if (session.user.role !== 'admin' && session.user.id !== userId) {
|
||||
throw unauthorized('Cannot delete other users')
|
||||
}
|
||||
|
||||
await db.user.delete({ where: { id: userId } })
|
||||
return { success: true }
|
||||
}
|
||||
```
|
||||
|
||||
**With input validation:**
|
||||
|
||||
```typescript
|
||||
'use server'
|
||||
|
||||
import { verifySession } from '@/lib/auth'
|
||||
import { z } from 'zod'
|
||||
|
||||
const updateProfileSchema = z.object({
|
||||
userId: z.string().uuid(),
|
||||
name: z.string().min(1).max(100),
|
||||
email: z.string().email()
|
||||
})
|
||||
|
||||
export async function updateProfile(data: unknown) {
|
||||
// Validate input first
|
||||
const validated = updateProfileSchema.parse(data)
|
||||
|
||||
// Then authenticate
|
||||
const session = await verifySession()
|
||||
if (!session) {
|
||||
throw new Error('Unauthorized')
|
||||
}
|
||||
|
||||
// Then authorize
|
||||
if (session.user.id !== validated.userId) {
|
||||
throw new Error('Can only update own profile')
|
||||
}
|
||||
|
||||
// Finally perform the mutation
|
||||
await db.user.update({
|
||||
where: { id: validated.userId },
|
||||
data: {
|
||||
name: validated.name,
|
||||
email: validated.email
|
||||
}
|
||||
})
|
||||
|
||||
return { success: true }
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
title: Cross-Request LRU Caching
|
||||
impact: HIGH
|
||||
impactDescription: caches across requests
|
||||
tags: server, cache, lru, cross-request
|
||||
---
|
||||
|
||||
## Cross-Request LRU Caching
|
||||
|
||||
`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
|
||||
|
||||
**Implementation:**
|
||||
|
||||
```typescript
|
||||
import { LRUCache } from 'lru-cache'
|
||||
|
||||
const cache = new LRUCache<string, any>({
|
||||
max: 1000,
|
||||
ttl: 5 * 60 * 1000 // 5 minutes
|
||||
})
|
||||
|
||||
export async function getUser(id: string) {
|
||||
const cached = cache.get(id)
|
||||
if (cached) return cached
|
||||
|
||||
const user = await db.user.findUnique({ where: { id } })
|
||||
cache.set(id, user)
|
||||
return user
|
||||
}
|
||||
|
||||
// Request 1: DB query, result cached
|
||||
// Request 2: cache hit, no DB query
|
||||
```
|
||||
|
||||
Use when sequential user actions hit multiple endpoints needing the same data within seconds.
|
||||
|
||||
**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
|
||||
|
||||
**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
|
||||
|
||||
Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
|
||||
@@ -0,0 +1,76 @@
|
||||
---
|
||||
title: Per-Request Deduplication with React.cache()
|
||||
impact: MEDIUM
|
||||
impactDescription: deduplicates within request
|
||||
tags: server, cache, react-cache, deduplication
|
||||
---
|
||||
|
||||
## Per-Request Deduplication with React.cache()
|
||||
|
||||
Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
|
||||
|
||||
**Usage:**
|
||||
|
||||
```typescript
|
||||
import { cache } from 'react'
|
||||
|
||||
export const getCurrentUser = cache(async () => {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) return null
|
||||
return await db.user.findUnique({
|
||||
where: { id: session.user.id }
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
|
||||
|
||||
**Avoid inline objects as arguments:**
|
||||
|
||||
`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
|
||||
|
||||
**Incorrect (always cache miss):**
|
||||
|
||||
```typescript
|
||||
const getUser = cache(async (params: { uid: number }) => {
|
||||
return await db.user.findUnique({ where: { id: params.uid } })
|
||||
})
|
||||
|
||||
// Each call creates new object, never hits cache
|
||||
getUser({ uid: 1 })
|
||||
getUser({ uid: 1 }) // Cache miss, runs query again
|
||||
```
|
||||
|
||||
**Correct (cache hit):**
|
||||
|
||||
```typescript
|
||||
const getUser = cache(async (uid: number) => {
|
||||
return await db.user.findUnique({ where: { id: uid } })
|
||||
})
|
||||
|
||||
// Primitive args use value equality
|
||||
getUser(1)
|
||||
getUser(1) // Cache hit, returns cached result
|
||||
```
|
||||
|
||||
If you must pass objects, pass the same reference:
|
||||
|
||||
```typescript
|
||||
const params = { uid: 1 }
|
||||
getUser(params) // Query runs
|
||||
getUser(params) // Cache hit (same reference)
|
||||
```
|
||||
|
||||
**Next.js-Specific Note:**
|
||||
|
||||
In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:
|
||||
|
||||
- Database queries (Prisma, Drizzle, etc.)
|
||||
- Heavy computations
|
||||
- Authentication checks
|
||||
- File system operations
|
||||
- Any non-fetch async work
|
||||
|
||||
Use `React.cache()` to deduplicate these operations across your component tree.
|
||||
|
||||
Reference: [React.cache documentation](https://react.dev/reference/react/cache)
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
title: Avoid Duplicate Serialization in RSC Props
|
||||
impact: LOW
|
||||
impactDescription: reduces network payload by avoiding duplicate serialization
|
||||
tags: server, rsc, serialization, props, client-components
|
||||
---
|
||||
|
||||
## Avoid Duplicate Serialization in RSC Props
|
||||
|
||||
**Impact: LOW (reduces network payload by avoiding duplicate serialization)**
|
||||
|
||||
RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.
|
||||
|
||||
**Incorrect (duplicates array):**
|
||||
|
||||
```tsx
|
||||
// RSC: sends 6 strings (2 arrays × 3 items)
|
||||
<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />
|
||||
```
|
||||
|
||||
**Correct (sends 3 strings):**
|
||||
|
||||
```tsx
|
||||
// RSC: send once
|
||||
<ClientList usernames={usernames} />
|
||||
|
||||
// Client: transform there
|
||||
'use client'
|
||||
const sorted = useMemo(() => [...usernames].sort(), [usernames])
|
||||
```
|
||||
|
||||
**Nested deduplication behavior:**
|
||||
|
||||
Deduplication works recursively. Impact varies by data type:
|
||||
|
||||
- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
|
||||
- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
|
||||
|
||||
```tsx
|
||||
// string[] - duplicates everything
|
||||
usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
|
||||
|
||||
// object[] - duplicates array structure only
|
||||
users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
|
||||
```
|
||||
|
||||
**Operations breaking deduplication (create new references):**
|
||||
|
||||
- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
|
||||
- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
|
||||
|
||||
**More examples:**
|
||||
|
||||
```tsx
|
||||
// ❌ Bad
|
||||
<C users={users} active={users.filter(u => u.active)} />
|
||||
<C product={product} productName={product.name} />
|
||||
|
||||
// ✅ Good
|
||||
<C users={users} />
|
||||
<C product={product} />
|
||||
// Do filtering/destructuring in client
|
||||
```
|
||||
|
||||
**Exception:** Pass derived data when transformation is expensive or client doesn't need original.
|
||||
@@ -0,0 +1,83 @@
|
||||
---
|
||||
title: Parallel Data Fetching with Component Composition
|
||||
impact: CRITICAL
|
||||
impactDescription: eliminates server-side waterfalls
|
||||
tags: server, rsc, parallel-fetching, composition
|
||||
---
|
||||
|
||||
## Parallel Data Fetching with Component Composition
|
||||
|
||||
React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
|
||||
|
||||
**Incorrect (Sidebar waits for Page's fetch to complete):**
|
||||
|
||||
```tsx
|
||||
export default async function Page() {
|
||||
const header = await fetchHeader()
|
||||
return (
|
||||
<div>
|
||||
<div>{header}</div>
|
||||
<Sidebar />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
async function Sidebar() {
|
||||
const items = await fetchSidebarItems()
|
||||
return <nav>{items.map(renderItem)}</nav>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (both fetch simultaneously):**
|
||||
|
||||
```tsx
|
||||
async function Header() {
|
||||
const data = await fetchHeader()
|
||||
return <div>{data}</div>
|
||||
}
|
||||
|
||||
async function Sidebar() {
|
||||
const items = await fetchSidebarItems()
|
||||
return <nav>{items.map(renderItem)}</nav>
|
||||
}
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<div>
|
||||
<Header />
|
||||
<Sidebar />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Alternative with children prop:**
|
||||
|
||||
```tsx
|
||||
async function Header() {
|
||||
const data = await fetchHeader()
|
||||
return <div>{data}</div>
|
||||
}
|
||||
|
||||
async function Sidebar() {
|
||||
const items = await fetchSidebarItems()
|
||||
return <nav>{items.map(renderItem)}</nav>
|
||||
}
|
||||
|
||||
function Layout({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div>
|
||||
<Header />
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<Layout>
|
||||
<Sidebar />
|
||||
</Layout>
|
||||
)
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: Minimize Serialization at RSC Boundaries
|
||||
impact: HIGH
|
||||
impactDescription: reduces data transfer size
|
||||
tags: server, rsc, serialization, props
|
||||
---
|
||||
|
||||
## Minimize Serialization at RSC Boundaries
|
||||
|
||||
The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.
|
||||
|
||||
**Incorrect (serializes all 50 fields):**
|
||||
|
||||
```tsx
|
||||
async function Page() {
|
||||
const user = await fetchUser() // 50 fields
|
||||
return <Profile user={user} />
|
||||
}
|
||||
|
||||
'use client'
|
||||
function Profile({ user }: { user: User }) {
|
||||
return <div>{user.name}</div> // uses 1 field
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (serializes only 1 field):**
|
||||
|
||||
```tsx
|
||||
async function Page() {
|
||||
const user = await fetchUser()
|
||||
return <Profile name={user.name} />
|
||||
}
|
||||
|
||||
'use client'
|
||||
function Profile({ name }: { name: string }) {
|
||||
return <div>{name}</div>
|
||||
}
|
||||
```
|
||||
BIN
.playwright-mcp/page-2026-01-28T05-34-03-490Z.png
Normal file
BIN
.playwright-mcp/page-2026-01-28T05-34-03-490Z.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 132 KiB |
BIN
.playwright-mcp/page-2026-01-28T05-34-54-677Z.png
Normal file
BIN
.playwright-mcp/page-2026-01-28T05-34-54-677Z.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 148 KiB |
BIN
.playwright-mcp/page-2026-01-28T05-36-56-234Z.png
Normal file
BIN
.playwright-mcp/page-2026-01-28T05-36-56-234Z.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 90 KiB |
BIN
.playwright-mcp/page-2026-01-28T05-38-13-480Z.png
Normal file
BIN
.playwright-mcp/page-2026-01-28T05-38-13-480Z.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 96 KiB |
BIN
.playwright-mcp/page-2026-01-28T05-38-27-126Z.png
Normal file
BIN
.playwright-mcp/page-2026-01-28T05-38-27-126Z.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 121 KiB |
145
AGENTS.md
145
AGENTS.md
@@ -1,131 +1,24 @@
|
||||
# 📔 Repository & Teaching Mentor Guidelines
|
||||
# Codex 적용 가이드 (Anti-Gravity Rules 라우팅)
|
||||
|
||||
이 파일은 프로젝트의 구조, 코딩 규칙 및 AI 어시스턴트의 **'교육용 멘토'** 역할을 정의합니다.
|
||||
이 리포지토리에서 작업할 때는 **작업 유형을 먼저 판단**하고, 아래 매핑에 따라
|
||||
`C:\dev\react-query\.agent\rules`의 규칙을 **해당 작업에만 로드해 적용**한다.
|
||||
규칙 파일은 자동 적용되지 않으므로, 반드시 **명시적으로 읽고 따른다**.
|
||||
|
||||
---
|
||||
## 작업 유형 → 규칙 매핑
|
||||
|
||||
## 🏗️ Project Structure & Module Organization
|
||||
- `src/app`: Next.js App Router 페이지, 레이아웃, 글로벌 스타일 및 API 라우트 (`src/app/api/...`)
|
||||
- `src/features`: 기능 중심 모듈화 (예: `lotto`, `react-query-demo`). 각 기능 내부에 `components`, `hooks`, `api` 등을 응집도 있게 관리합니다.
|
||||
- `src/components/ui`: shadcn/ui 기반의 공통 UI 컴포넌트.
|
||||
- `src/lib`: 프로젝트 전반에서 공유되는 유틸리티 및 설정 (`utils.ts` 등).
|
||||
- `public`: 이미지, 폰트 등 정적 자산.
|
||||
- **새 기능 개발/구현/컴포넌트 추가/API 연동/페이지 생성**
|
||||
- `.agent/rules/builder-rule.md`
|
||||
- **코드 분석/흐름 설명/작동 원리 이해**
|
||||
- `.agent/rules/code-analysis-rule.md`
|
||||
- **주석 추가/문서화/TSDoc/JSDoc 작성**
|
||||
- `.agent/rules/doc-rule.md`
|
||||
- 필요 시 `.agent/rules/code-analysis-rule.md`로 흐름 파악 후 적용
|
||||
- **리팩토링/구조 개선/폴더 정리/성능 개선**
|
||||
- `.agent/rules/refactoring-rule.md`
|
||||
- 필요 시 `.agent/rules/builder-rule.md`로 재구현 기준 보조
|
||||
|
||||
## 💻 Development Commands
|
||||
- `npm run dev`: 로컬 개발 서버 시작 (Next.js)
|
||||
- `npm run dev:turbo`: Turbopack 모드로 더 빠른 개발 서버 시작
|
||||
- `npm run build`: 프로덕션 빌드 생성
|
||||
- `npm run start`: 프로덕션 빌드 실행
|
||||
- `npm run server`: `json-server` 실행 (Port: 3002, `db.json` 참조)
|
||||
## 통합 지침
|
||||
|
||||
## 🎨 Coding Style & Conventions
|
||||
- **Language**: TypeScript + React
|
||||
- **Indentation**: 2-space (Prettier/ESLint 설정 기반)
|
||||
- **Naming**:
|
||||
- Components: `PascalCase` (예: `LottoTable.tsx`)
|
||||
- Hooks: `camelCase` (예: `useLottoDraws.ts`)
|
||||
- Utils/API: `camelCase`
|
||||
- **Styling**: Tailwind CSS + `cn(...)` 유틸리티 활용. UI 원형(Primitives)은 `src/components/ui`를 우선 사용합니다.
|
||||
|
||||
## 🔒 Security & API
|
||||
- **CORS 방지**: 외부 API 호출 시 직접 브라우저에서 호출하기보다 Next.js API Routes(`src/app/api`)를 프록시로 활용하여 보안과 CORS 문제를 해결합니다.
|
||||
- **Environment**: 민감한 정보는 `.env`로 관리하며, 클라이언트 환경변수는 `NEXT_PUBLIC_` 접두사를 사용합니다.
|
||||
|
||||
---
|
||||
|
||||
# 🧑🏫 AI Teaching Mentor Rule Prompt
|
||||
**"단순히 코드만 짜는 로봇이 아닌, 성장을 돕는 친절한 사수가 되어주세요."**
|
||||
|
||||
### 1. 역할 및 기본 페르소나
|
||||
- 당신은 10년 차 이상의 능숙한 시니어 풀스택 개발자이자 실력이 뛰어난 **교육 멘토**입니다.
|
||||
- 답변 시 항상 **친절하고 격려하는 어조**를 유지하며, 모든 설명과 주석은 **한국어(한글)**로 작성합니다.
|
||||
- 사용자가 코드의 구현 결과뿐만 아니라 **"왜(Why)"**와 **"어떻게(Flow)"**를 이해하도록 돕는 것이 당신의 존재 이유입니다.
|
||||
|
||||
### 2. 코드 생성 시 필수 3요소 (AAA)
|
||||
|
||||
#### A. 상세한 해설 (Detailed Explanation)
|
||||
코드를 제안하기 전(또는 후)에 다음 내용을 반드시 명시합니다.
|
||||
1. **무엇인가?**: 구현하려는 기능의 핵심 요약.
|
||||
2. **왜 이렇게 했는가? (Rationale)**: 사용된 기술(React Query, Zustand 등)의 선택 이유와 이점.
|
||||
3. **데이터의 흐름 (Data Flow)**: 컴포넌트 간, 혹은 클라이언트-서버 간 데이터가 어떻게 이동하는지 상세 설명.
|
||||
|
||||
#### B. 교과서 같은 주석 (Educational Comments)
|
||||
작성하는 모든 코드에는 다음 수준의 주석을 포함합니다.
|
||||
1. **JSDoc**: 함수, 인터페이스 상단에 역할, 매개변수, 반환값 명시.
|
||||
2. **논리적 배경**: "단순히 무엇을 한다"가 아니라 "이 조건문이 왜 필요한지"를 주석으로 표현.
|
||||
3. **기술 스택 포인트**:
|
||||
- **React Query**: `queryKey` 설계 이유, 캐싱 전략.
|
||||
- **Zustand**: 상태 원자성(Atomicity) 및 스토어 구조의 장점.
|
||||
4. **의존성 배열 설명**:
|
||||
- `useEffect`/`useMemo`/`useCallback` 등 훅의 의존성 배열이 **"어떤 값이 바뀌면 다시 실행되는지"**를 한 줄로 설명합니다.
|
||||
- 예: "page/totalPages/setPage 중 하나라도 바뀌면 useEffect가 다시 실행됩니다."
|
||||
- 예시 코드:
|
||||
```tsx
|
||||
// page/totalPages/setPage 중 하나라도 바뀌면 이 effect가 다시 실행됩니다.
|
||||
useEffect(() => {
|
||||
if (page > totalPages) {
|
||||
setPage(totalPages);
|
||||
}
|
||||
}, [page, totalPages, setPage]);
|
||||
```
|
||||
- useMemo 예시:
|
||||
```tsx
|
||||
// items/page/pageSize 중 하나라도 바뀌면 계산 결과가 다시 만들어집니다.
|
||||
const pagedItems = useMemo(() => {
|
||||
const startIndex = (page - 1) * pageSize;
|
||||
return items.slice(startIndex, startIndex + pageSize);
|
||||
}, [items, page, pageSize]);
|
||||
```
|
||||
- useCallback 예시:
|
||||
```tsx
|
||||
// totalPages/setPage가 바뀌면 새 콜백을 다시 만듭니다.
|
||||
const handlePageChange = useCallback(
|
||||
(nextPage: number) => {
|
||||
const clamped = Math.min(Math.max(nextPage, 1), totalPages);
|
||||
setPage(clamped);
|
||||
},
|
||||
[totalPages, setPage]
|
||||
);
|
||||
```
|
||||
- React Query `queryKey` 예시:
|
||||
```tsx
|
||||
// userId가 바뀌면 React Query가 다른 캐시 키로 인식해 재요청합니다.
|
||||
const userQuery = useQuery({
|
||||
queryKey: ["users", userId],
|
||||
queryFn: () => getUser(userId),
|
||||
});
|
||||
```
|
||||
- React Query `invalidateQueries` 예시:
|
||||
```tsx
|
||||
// 유저 생성 후 목록 캐시를 무효화해 최신 목록을 다시 가져오게 합니다.
|
||||
const queryClient = useQueryClient();
|
||||
await createUser(payload);
|
||||
queryClient.invalidateQueries({ queryKey: ["users", "list"] });
|
||||
```
|
||||
|
||||
#### C. 다음 단계 가이드 (Next Step)
|
||||
- 현재 구현 완료 후, 학습자가 도전해볼 만한 심화 작업이나 관련 기술 개념을 하나 추천합니다.
|
||||
|
||||
### 3. 답변 템플릿
|
||||
```markdown
|
||||
### 📝 오늘 배울 내용: [기능 이름]
|
||||
[기능에 대한 전반적인 설명과 학습 목표]
|
||||
|
||||
#### 💡 기술적 배경과 의도
|
||||
[이 기술을 선택한 이유와 프로젝트 구조상 이점 설명]
|
||||
|
||||
#### 🔍 주요 코드 흐름
|
||||
1. [흐름 1]
|
||||
2. [흐름 2]
|
||||
|
||||
#### 💻 구현된 소스 코드 (상세 주석 포함)
|
||||
[주석이 가득한 코드 블록]
|
||||
|
||||
#### 🚀 더 나아가기
|
||||
[연관 학습 키워드 또는 다음 과제]
|
||||
```
|
||||
|
||||
### 4. 주의 사항 (Constraints)
|
||||
- 주석 없는 코드는 절대 제공하지 않습니다.
|
||||
- 전문 용어는 가급적 풀어 쓰거나, 필요시 (괄호)를 통해 보충 설명을 덧붙입니다.
|
||||
- 사용자가 질문하지 않은 부분이라도, 실수하기 쉬운 포인트가 있다면 미리 조언해주세요.
|
||||
- 복합 작업일 경우 `.agent/rules/master-integration.md`의 조합 가이드를 우선 참고한다.
|
||||
- 규칙 간 충돌이 있으면 **상위 시스템/개발자 지침을 우선**하고, 그 다음 이 문서,
|
||||
그 다음 개별 규칙 파일을 따른다.
|
||||
|
||||
@@ -27,14 +27,27 @@ export function LottoDashboard() {
|
||||
const dialogOpen = useLottoStore((state) => state.dialogOpen);
|
||||
const setDialogOpen = useLottoStore((state) => state.setDialogOpen);
|
||||
const recommendations = useLottoStore((state) => state.recommendations);
|
||||
const setRecommendations = useLottoStore(
|
||||
(state) => state.setRecommendations
|
||||
);
|
||||
const setRecommendations = useLottoStore((state) => state.setRecommendations);
|
||||
|
||||
// 조건 플래그 상태
|
||||
const condition1 = useLottoStore((state) => state.condition1);
|
||||
const condition2 = useLottoStore((state) => state.condition2);
|
||||
const condition3 = useLottoStore((state) => state.condition3);
|
||||
const excludeRecentDrawsCount = useLottoStore(
|
||||
(state) => state.excludeRecentDrawsCount,
|
||||
);
|
||||
|
||||
// 고급 조건 상태들
|
||||
const applyBalancedOddEven = useLottoStore(
|
||||
(state) => state.applyBalancedOddEven,
|
||||
);
|
||||
const applySumRange = useLottoStore((state) => state.applySumRange);
|
||||
const applyConsecutive = useLottoStore((state) => state.applyConsecutive);
|
||||
const applyComplexityAC = useLottoStore((state) => state.applyComplexityAC);
|
||||
const applyPrimeFilter = useLottoStore((state) => state.applyPrimeFilter);
|
||||
const applyNoDuplicateEnds = useLottoStore(
|
||||
(state) => state.applyNoDuplicateEnds,
|
||||
);
|
||||
|
||||
// React Query 훅으로 서버 데이터를 가져오고, 페이지네이션 정보를 계산합니다.
|
||||
// 이 시점에서 items/totalCount/totalPages가 UI로 흘러갑니다.
|
||||
@@ -49,6 +62,7 @@ export function LottoDashboard() {
|
||||
} = useLottoDraws({
|
||||
page,
|
||||
pageSize: PAGE_SIZE,
|
||||
recentDrawsCount: excludeRecentDrawsCount,
|
||||
});
|
||||
|
||||
// 번호 생성 로직은 utils 함수로 분리해 알고리즘을 쉽게 교체합니다.
|
||||
@@ -56,15 +70,24 @@ export function LottoDashboard() {
|
||||
Array.from({ length: RECOMMENDATION_COUNT }, () =>
|
||||
generateLottoNumbers({
|
||||
recentDraws,
|
||||
excludeRecentDrawsCount,
|
||||
useCondition1: condition1,
|
||||
useCondition2: condition2,
|
||||
useCondition3: condition3,
|
||||
})
|
||||
// 고급 전략 필터 적용
|
||||
applyBalancedOddEven,
|
||||
applySumRange,
|
||||
applyConsecutive,
|
||||
applyComplexityAC,
|
||||
applyPrimeFilter,
|
||||
applyNoDuplicateEnds,
|
||||
}),
|
||||
);
|
||||
|
||||
const handleOpenDialog = () => {
|
||||
// 다이얼로그 열기 전에 추천 번호를 준비해 첫 화면을 즉시 채웁니다.
|
||||
setRecommendations(createRecommendations());
|
||||
// 다이얼로그 열림 상태를 true로 설정하여 화면에 표시합니다.
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
@@ -73,7 +96,6 @@ export function LottoDashboard() {
|
||||
setRecommendations(createRecommendations());
|
||||
};
|
||||
|
||||
|
||||
// 페이지 이동은 범위를 벗어나지 않도록 clamp 처리합니다.
|
||||
const handlePageChange = (nextPage: number) => {
|
||||
const clamped = Math.min(Math.max(nextPage, 1), totalPages);
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
/**
|
||||
* @file LottoRecommendationsDialog.tsx
|
||||
* @description 로또 추천 결과를 조건 필터와 함께 보여주는 다이얼로그.
|
||||
* @remarks
|
||||
* - [UI] Components
|
||||
* - [사용자 흐름] 대시보드 -> 다이얼로그 열기 -> 조건 토글 -> 재생성/닫기
|
||||
* - [데이터 흐름] UI -> Zustand store -> 다이얼로그 UI
|
||||
* - [연관 파일] LottoDashboard.tsx
|
||||
* @author jihoon87.lee
|
||||
*/
|
||||
"use client";
|
||||
|
||||
import type { ChangeEvent } from "react";
|
||||
import { useDialogDragResize } from "@/lib/useDialogDragResize";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -13,28 +24,58 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogClose,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
} from "@/components/ui/dialog";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Sparkles } from "lucide-react";
|
||||
import { useLottoStore } from "../store/useLottoStore";
|
||||
import React, { memo } from "react";
|
||||
|
||||
/**
|
||||
* 추천 번호 다이얼로그에 전달되는 Props입니다.
|
||||
* @property {boolean} open - 다이얼로그 열림 상태입니다.
|
||||
* @property {number[][]} recommendations - 추천 번호 목록입니다.
|
||||
* @property {(open: boolean) => void} onOpenChange - 열림 상태 변경 콜백입니다.
|
||||
* @property {() => void} onRegenerate - 추천 번호 재생성 콜백입니다.
|
||||
*/
|
||||
interface LottoRecommendationsDialogProps {
|
||||
open: boolean;
|
||||
recommendations: number[][];
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onRegenerate: () => void;
|
||||
onRegenerate: (options: any) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 추천 번호 목록을 모달로 보여주는 컴포넌트입니다.
|
||||
* shadcn/ui Dialog를 사용해 접근성과 상태 제어를 함께 가져갑니다.
|
||||
* 로또 추천 리스트 아이템 컴포넌트 (메모이제이션 적용)
|
||||
*/
|
||||
const RecommendationItem = memo(
|
||||
({ numbers, index }: { numbers: number[]; index: number }) => (
|
||||
<div className="flex flex-wrap items-center justify-between gap-4 rounded-xl border border-emerald-100 bg-white px-5 py-4 shadow-[0_2px_10px_-3px_rgba(16,185,129,0.1)] transition-all hover:shadow-md hover:border-emerald-200">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="h-6 rounded-md bg-emerald-50 text-emerald-700 border-emerald-100 px-2 text-[10px] font-bold tracking-tight"
|
||||
>
|
||||
추천 {index + 1}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{numbers.map((value) => (
|
||||
<div
|
||||
key={value}
|
||||
className="flex h-9 w-9 items-center justify-center rounded-full border border-emerald-100 bg-emerald-50/30 text-sm font-bold text-emerald-700 shadow-sm transition-transform hover:scale-110"
|
||||
>
|
||||
{value}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
);
|
||||
RecommendationItem.displayName = "RecommendationItem";
|
||||
|
||||
/**
|
||||
* 로또 추천 다이얼로그 컴포넌트.
|
||||
* @param open 다이얼로그 열림 여부.
|
||||
* @param recommendations 추천 번호 세트.
|
||||
* @param onOpenChange 다이얼로그 열림 상태 변경 핸들러.
|
||||
* @param onRegenerate 추천 번호 재생성 핸들러.
|
||||
* @returns 다이얼로그 UI.
|
||||
* @see LottoDashboard.tsx - 다이얼로그 열림 상태와 추천 목록 전달
|
||||
*/
|
||||
export function LottoRecommendationsDialog({
|
||||
open,
|
||||
@@ -42,10 +83,10 @@ export function LottoRecommendationsDialog({
|
||||
onOpenChange,
|
||||
onRegenerate,
|
||||
}: LottoRecommendationsDialogProps) {
|
||||
// 공용 훅으로 드래그/리사이즈 로직을 연결합니다.
|
||||
const {
|
||||
contentStyle,
|
||||
contentClassName,
|
||||
contentRef,
|
||||
dragHandleProps,
|
||||
dragHandleClassName,
|
||||
resizeHandleProps,
|
||||
@@ -57,120 +98,372 @@ export function LottoRecommendationsDialog({
|
||||
resizable: true,
|
||||
});
|
||||
|
||||
// Zustand store에서 조건 플래그 상태를 가져옵니다.
|
||||
// [State] 조건 토글과 제외 회차 설정 값
|
||||
const condition1 = useLottoStore((state) => state.condition1);
|
||||
const condition2 = useLottoStore((state) => state.condition2);
|
||||
const condition3 = useLottoStore((state) => state.condition3);
|
||||
const excludeRecentDrawsCount = useLottoStore(
|
||||
(state) => state.excludeRecentDrawsCount,
|
||||
);
|
||||
// [State] 조건 및 제외 회차 업데이트 액션
|
||||
const setCondition1 = useLottoStore((state) => state.setCondition1);
|
||||
const setCondition2 = useLottoStore((state) => state.setCondition2);
|
||||
const setCondition3 = useLottoStore((state) => state.setCondition3);
|
||||
const setExcludeRecentDrawsCount = useLottoStore(
|
||||
(state) => state.setExcludeRecentDrawsCount,
|
||||
);
|
||||
|
||||
// [State] 고급 조건들
|
||||
const applyBalancedOddEven = useLottoStore(
|
||||
(state) => state.applyBalancedOddEven,
|
||||
);
|
||||
const applySumRange = useLottoStore((state) => state.applySumRange);
|
||||
const applyConsecutive = useLottoStore((state) => state.applyConsecutive);
|
||||
const applyComplexityAC = useLottoStore((state) => state.applyComplexityAC);
|
||||
const applyPrimeFilter = useLottoStore((state) => state.applyPrimeFilter);
|
||||
const applyNoDuplicateEnds = useLottoStore(
|
||||
(state) => state.applyNoDuplicateEnds,
|
||||
);
|
||||
|
||||
// [State] 고급 조건 Setter들
|
||||
const setApplyBalancedOddEven = useLottoStore(
|
||||
(state) => state.setApplyBalancedOddEven,
|
||||
);
|
||||
const setApplySumRange = useLottoStore((state) => state.setApplySumRange);
|
||||
const setApplyConsecutive = useLottoStore(
|
||||
(state) => state.setApplyConsecutive,
|
||||
);
|
||||
const setApplyComplexityAC = useLottoStore(
|
||||
(state) => state.setApplyComplexityAC,
|
||||
);
|
||||
const setApplyPrimeFilter = useLottoStore(
|
||||
(state) => state.setApplyPrimeFilter,
|
||||
);
|
||||
const setApplyNoDuplicateEnds = useLottoStore(
|
||||
(state) => state.setApplyNoDuplicateEnds,
|
||||
);
|
||||
|
||||
/**
|
||||
* 최근 회차 제외 수 입력 변경 처리.
|
||||
* @param event 숫자 입력 이벤트.
|
||||
* @returns void
|
||||
* @see LottoRecommendationsDialog.tsx - excludeRecentDrawsCount 입력 onChange
|
||||
*/
|
||||
const handleExcludeCountChange = (
|
||||
event: React.ChangeEvent<HTMLInputElement>,
|
||||
) => {
|
||||
// [Step 1] 입력값을 숫자로 변환
|
||||
const nextValue = Number(event.target.value);
|
||||
// [Step 2] 숫자 변환 실패 시 0으로 초기화
|
||||
if (Number.isNaN(nextValue)) {
|
||||
setExcludeRecentDrawsCount(0);
|
||||
return;
|
||||
}
|
||||
// [Step 3] 정상 값이면 스토어에 반영
|
||||
setExcludeRecentDrawsCount(nextValue);
|
||||
};
|
||||
|
||||
return (
|
||||
// shadcn/ui Dialog는 Radix 기반이므로 open/onOpenChange로 상태를 제어합니다.
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
className={cn("flex flex-col gap-0 p-0 overflow-hidden", contentClassName)}
|
||||
ref={contentRef as React.RefObject<HTMLDivElement>}
|
||||
className={cn(
|
||||
"flex flex-col gap-0 p-0 border-none shadow-none",
|
||||
contentClassName,
|
||||
)}
|
||||
style={contentStyle}
|
||||
>
|
||||
<DialogHeader
|
||||
className={cn("px-6 py-4 border-b shrink-0", dragHandleClassName)}
|
||||
className={cn(
|
||||
"px-6 py-6 border-b border-emerald-50 shrink-0 flex flex-col items-start gap-1 text-left sm:text-left bg-white",
|
||||
dragHandleClassName,
|
||||
)}
|
||||
{...dragHandleProps}
|
||||
>
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="w-fit gap-2 bg-emerald-50 text-emerald-700"
|
||||
>
|
||||
<Sparkles className="h-4 w-4" />
|
||||
10줄 추천
|
||||
</Badge>
|
||||
<DialogTitle className="text-2xl">로또 번호 추천</DialogTitle>
|
||||
<DialogDescription>
|
||||
랜덤으로 생성된 10줄 번호를 확인하세요.
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<div className="p-1 rounded-md bg-emerald-50 text-emerald-600">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
</div>
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="bg-emerald-50/50 text-emerald-600 hover:bg-emerald-50/50 border-emerald-100/50 text-[10px]"
|
||||
>
|
||||
10개 추천
|
||||
</Badge>
|
||||
</div>
|
||||
<DialogTitle className="text-2xl font-bold tracking-tight text-slate-900">
|
||||
로또 번호 추천
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-sm text-slate-500 font-medium">
|
||||
당첨 확률을 높여줄 최적의 조합 10개를 확인하세요.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{/* 조건 토글 체크박스 영역 */}
|
||||
<div className="flex flex-wrap items-center gap-4 px-6 py-3 border-b bg-muted/30 shrink-0">
|
||||
<div className="flex items-center gap-2">
|
||||
{/* ========== 조건 설정 영역 ========== */}
|
||||
<div className="flex flex-wrap items-center gap-6 px-6 py-4 border-b border-emerald-50 bg-white shrink-0">
|
||||
<div className="flex items-center gap-3 group">
|
||||
<Checkbox
|
||||
id="condition1"
|
||||
checked={condition1}
|
||||
onCheckedChange={(checked) => setCondition1(checked === true)}
|
||||
className="border-emerald-200 data-[state=checked]:bg-emerald-500 data-[state=checked]:border-emerald-500"
|
||||
/>
|
||||
<Label htmlFor="condition1" className="text-sm cursor-pointer">
|
||||
조건 1: 최근 번호 제외
|
||||
</Label>
|
||||
<div className="flex flex-col">
|
||||
<Label
|
||||
htmlFor="condition1"
|
||||
className="text-sm font-semibold cursor-pointer group-hover:text-emerald-600 transition-colors text-slate-700"
|
||||
>
|
||||
최근 번호 제외
|
||||
</Label>
|
||||
<div className="flex items-center gap-1.5 mt-1">
|
||||
<span className="text-[10px] text-slate-400">최근</span>
|
||||
<input
|
||||
id="excludeRecentDrawsCount"
|
||||
type="number"
|
||||
min={0}
|
||||
step={1}
|
||||
value={excludeRecentDrawsCount}
|
||||
onChange={handleExcludeCountChange}
|
||||
className="h-6 w-12 rounded border border-emerald-100 bg-emerald-50/10 px-1.5 text-[10px] shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-emerald-400"
|
||||
/>
|
||||
<span className="text-[10px] text-slate-400 font-medium">
|
||||
회차 제외
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
|
||||
<div className="h-6 w-px bg-emerald-100/50" />
|
||||
|
||||
<div className="flex items-center gap-3 group">
|
||||
<Checkbox
|
||||
id="condition2"
|
||||
checked={condition2}
|
||||
onCheckedChange={(checked) => setCondition2(checked === true)}
|
||||
className="border-emerald-200 data-[state=checked]:bg-emerald-500 data-[state=checked]:border-emerald-500"
|
||||
/>
|
||||
<Label htmlFor="condition2" className="text-sm cursor-pointer">
|
||||
조건 2: 보너스 번호 제외
|
||||
<Label
|
||||
htmlFor="condition2"
|
||||
className="text-sm font-semibold cursor-pointer group-hover:text-emerald-600 transition-colors text-slate-700"
|
||||
>
|
||||
보너스 번호 제외
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
|
||||
<div className="h-6 w-px bg-emerald-100/50" />
|
||||
|
||||
<div className="flex items-center gap-3 group">
|
||||
<Checkbox
|
||||
id="condition3"
|
||||
checked={condition3}
|
||||
onCheckedChange={(checked) => setCondition3(checked === true)}
|
||||
className="border-emerald-200 data-[state=checked]:bg-emerald-500 data-[state=checked]:border-emerald-500"
|
||||
/>
|
||||
<Label htmlFor="condition3" className="text-sm cursor-pointer">
|
||||
조건 3: Hot & Due 적용
|
||||
<Label
|
||||
htmlFor="condition3"
|
||||
className="text-sm font-semibold cursor-pointer group-hover:text-emerald-600 transition-colors text-slate-700"
|
||||
>
|
||||
Hot & Due 적용
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto px-6 py-4">
|
||||
<div className="grid gap-3">
|
||||
{recommendations.map((numbers, index) => (
|
||||
<div
|
||||
key={`${numbers.join("-")}-${index}`}
|
||||
className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border bg-muted/40 px-4 py-3"
|
||||
>
|
||||
<Badge variant="outline" className="text-xs font-semibold">
|
||||
추천 {index + 1}
|
||||
</Badge>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{numbers.map((value) => (
|
||||
<Badge
|
||||
key={value}
|
||||
variant="outline"
|
||||
className="border-emerald-200 bg-emerald-50 text-emerald-700"
|
||||
>
|
||||
{value}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
{/* ========== 고급 전략 필터 영역 ========== */}
|
||||
<div className="px-6 py-4 border-b border-emerald-50 bg-emerald-50/5 shrink-0">
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="bg-white text-emerald-600 border-emerald-100 text-[10px] font-bold"
|
||||
>
|
||||
고급 전략 필터
|
||||
</Badge>
|
||||
<span className="text-[11px] text-slate-400 font-medium">
|
||||
통계적으로 당첨 확률이 높은 조합을 추출합니다.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 gap-y-4 gap-x-8">
|
||||
{/* 1. 홀짝 비율 */}
|
||||
<div className="flex items-center gap-2.5 group">
|
||||
<Checkbox
|
||||
id="applyBalancedOddEven"
|
||||
checked={applyBalancedOddEven}
|
||||
onCheckedChange={(checked) =>
|
||||
setApplyBalancedOddEven(checked === true)
|
||||
}
|
||||
className="h-4 w-4 border-emerald-200 data-[state=checked]:bg-emerald-500"
|
||||
/>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Label
|
||||
htmlFor="applyBalancedOddEven"
|
||||
className="text-[12px] font-semibold text-slate-700 cursor-pointer group-hover:text-emerald-600 transition-colors"
|
||||
>
|
||||
홀짝 균형 (3:3, 2:4)
|
||||
</Label>
|
||||
<span className="text-[10px] text-slate-400">
|
||||
홀수와 짝수의 비율 조절
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 2. 합계 범위 */}
|
||||
<div className="flex items-center gap-2.5 group">
|
||||
<Checkbox
|
||||
id="applySumRange"
|
||||
checked={applySumRange}
|
||||
onCheckedChange={(checked) =>
|
||||
setApplySumRange(checked === true)
|
||||
}
|
||||
className="h-4 w-4 border-emerald-200 data-[state=checked]:bg-emerald-500"
|
||||
/>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Label
|
||||
htmlFor="applySumRange"
|
||||
className="text-[12px] font-semibold text-slate-700 cursor-pointer group-hover:text-emerald-600 transition-colors"
|
||||
>
|
||||
합계 최적화 (121~160)
|
||||
</Label>
|
||||
<span className="text-[10px] text-slate-400">
|
||||
번호 전체 합계 범위 제한
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 3. 연속 번호 */}
|
||||
<div className="flex items-center gap-2.5 group">
|
||||
<Checkbox
|
||||
id="applyConsecutive"
|
||||
checked={applyConsecutive}
|
||||
onCheckedChange={(checked) =>
|
||||
setApplyConsecutive(checked === true)
|
||||
}
|
||||
className="h-4 w-4 border-emerald-200 data-[state=checked]:bg-emerald-500"
|
||||
/>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Label
|
||||
htmlFor="applyConsecutive"
|
||||
className="text-[12px] font-semibold text-slate-700 cursor-pointer group-hover:text-emerald-600 transition-colors"
|
||||
>
|
||||
연속 번호 포함
|
||||
</Label>
|
||||
<span className="text-[10px] text-slate-400">
|
||||
자연스러운 연속 번호 생성
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 4. AC값(복잡계수) */}
|
||||
<div className="flex items-center gap-2.5 group">
|
||||
<Checkbox
|
||||
id="applyComplexityAC"
|
||||
checked={applyComplexityAC}
|
||||
onCheckedChange={(checked) =>
|
||||
setApplyComplexityAC(checked === true)
|
||||
}
|
||||
className="h-4 w-4 border-emerald-200 data-[state=checked]:bg-emerald-500"
|
||||
/>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Label
|
||||
htmlFor="applyComplexityAC"
|
||||
className="text-[12px] font-semibold text-slate-700 cursor-pointer group-hover:text-emerald-600 transition-colors"
|
||||
>
|
||||
복잡도(AC) 7 이상
|
||||
</Label>
|
||||
<span className="text-[10px] text-slate-400">
|
||||
무작위성 강화 스코어링
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 5. 소수 필터 */}
|
||||
<div className="flex items-center gap-2.5 group">
|
||||
<Checkbox
|
||||
id="applyPrimeFilter"
|
||||
checked={applyPrimeFilter}
|
||||
onCheckedChange={(checked) =>
|
||||
setApplyPrimeFilter(checked === true)
|
||||
}
|
||||
className="h-4 w-4 border-emerald-200 data-[state=checked]:bg-emerald-500"
|
||||
/>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Label
|
||||
htmlFor="applyPrimeFilter"
|
||||
className="text-[12px] font-semibold text-slate-700 cursor-pointer group-hover:text-emerald-600 transition-colors"
|
||||
>
|
||||
소수 포함 (1~3개)
|
||||
</Label>
|
||||
<span className="text-[10px] text-slate-400">
|
||||
2, 3, 5 등 소수 비율 적용
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 6. 동일 끝수 제한 */}
|
||||
<div className="flex items-center gap-2.5 group">
|
||||
<Checkbox
|
||||
id="applyNoDuplicateEnds"
|
||||
checked={applyNoDuplicateEnds}
|
||||
onCheckedChange={(checked) =>
|
||||
setApplyNoDuplicateEnds(checked === true)
|
||||
}
|
||||
className="h-4 w-4 border-emerald-200 data-[state=checked]:bg-emerald-500"
|
||||
/>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Label
|
||||
htmlFor="applyNoDuplicateEnds"
|
||||
className="text-[12px] font-semibold text-slate-700 cursor-pointer group-hover:text-emerald-600 transition-colors"
|
||||
>
|
||||
동일 끝수 제한
|
||||
</Label>
|
||||
<span className="text-[10px] text-slate-400">
|
||||
끝자리 중복 3개 이상 방지
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ========== 추천 목록 영역 (스크롤 가능) ========== */}
|
||||
<div className="flex-1 overflow-y-auto px-6 py-6 bg-white/50">
|
||||
<div className="grid gap-4">
|
||||
{recommendations.map((numbers, index) => (
|
||||
<RecommendationItem
|
||||
key={`${numbers.join("-")}-${index}`}
|
||||
numbers={numbers}
|
||||
index={index}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="px-6 py-4 border-t shrink-0 gap-2 sm:gap-3">
|
||||
{/* ========== 하단 액션 영역 ========== */}
|
||||
<DialogFooter className="px-6 py-5 border-t border-emerald-50 shrink-0 gap-3 bg-white">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-100"
|
||||
className="flex-1 border-emerald-100 bg-white text-emerald-600 hover:bg-emerald-50 hover:border-emerald-200 transition-all font-bold"
|
||||
onClick={onRegenerate}
|
||||
>
|
||||
다시 생성
|
||||
추천 번호 다시 생성
|
||||
</Button>
|
||||
<DialogClose asChild>
|
||||
<Button type="button">닫기</Button>
|
||||
<Button
|
||||
type="button"
|
||||
className="flex-1 bg-emerald-600 hover:bg-emerald-500 shadow-emerald-600/10 shadow-xl font-bold"
|
||||
>
|
||||
닫기
|
||||
</Button>
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
|
||||
{/* 모서리 핸들로 크기 조절을 제공합니다. */}
|
||||
{/* ========== 리사이즈 핸들 ========== */}
|
||||
{isResizable && (
|
||||
<div
|
||||
role="presentation"
|
||||
aria-label="다이얼로그 크기 조절"
|
||||
className={cn(
|
||||
"absolute bottom-3 right-3 h-4 w-4 rounded-sm border border-emerald-200 bg-emerald-50",
|
||||
resizeHandleClassName
|
||||
"absolute bottom-3 right-3 h-4 w-4 rounded-sm border border-emerald-100 bg-white",
|
||||
resizeHandleClassName,
|
||||
)}
|
||||
{...resizeHandleProps}
|
||||
/>
|
||||
@@ -179,4 +472,3 @@ export function LottoRecommendationsDialog({
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import { LottoDraw } from "../types/lotto";
|
||||
interface UseLottoDrawsOptions {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
recentDrawsCount?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -41,6 +42,7 @@ interface UseLottoDrawsResult {
|
||||
export function useLottoDraws({
|
||||
page,
|
||||
pageSize,
|
||||
recentDrawsCount = 3,
|
||||
}: UseLottoDrawsOptions): UseLottoDrawsResult {
|
||||
// queryKey는 "lotto/list"로 고정하여 동일 리스트 캐시를 재사용합니다.
|
||||
// queryKey가 바뀌면 React Query는 다른 데이터로 인식해 새로 요청/캐시합니다.
|
||||
@@ -61,8 +63,8 @@ export function useLottoDraws({
|
||||
// useMemo로 최신 3회차 계산을 캐싱해, items가 바뀔 때만 다시 계산되게 합니다.
|
||||
// data?.items가 바뀌면 다시 실행되어 최신 회차 기준이 유지됩니다.
|
||||
const allItems = data?.items ?? [];
|
||||
return allItems.slice(0, 3);
|
||||
}, [data?.items]);
|
||||
return allItems.slice(0, recentDrawsCount);
|
||||
}, [data?.items, recentDrawsCount]);
|
||||
|
||||
const items = useMemo(() => {
|
||||
// useMemo로 페이지 슬라이스를 캐싱해, page/pageSize/items가 바뀔 때만 다시 계산합니다.
|
||||
|
||||
@@ -2,7 +2,6 @@ import { create } from "zustand";
|
||||
|
||||
/**
|
||||
* 로또 페이지에서 공유하는 UI 상태 타입입니다.
|
||||
* 상태를 원자적으로(Atomic) 나누면 필요한 컴포넌트만 선택적으로 구독할 수 있습니다.
|
||||
*/
|
||||
interface LottoState {
|
||||
/** 현재 페이지 번호(페이지네이션 기준)입니다. */
|
||||
@@ -17,6 +16,21 @@ interface LottoState {
|
||||
condition2: boolean;
|
||||
/** 조건 3: Hot & Due 알고리즘 적용 */
|
||||
condition3: boolean;
|
||||
excludeRecentDrawsCount: number;
|
||||
|
||||
/** 고급: 홀짝 비율 3:3 또는 2:4 (Balanced Odd/Even) */
|
||||
applyBalancedOddEven: boolean;
|
||||
/** 고급: 합계 범위 121~160 (Balanced Sum) */
|
||||
applySumRange: boolean;
|
||||
/** 고급: 2회 이상 연속 번호 존재 여부 제어 */
|
||||
applyConsecutive: boolean;
|
||||
/** 고급: AC값(복잡도) 7 이상 */
|
||||
applyComplexityAC: boolean;
|
||||
/** 고급: 소수(Prime) 1~3개 포함 */
|
||||
applyPrimeFilter: boolean;
|
||||
/** 고급: 동일 끝수 3개 이상 제한 */
|
||||
applyNoDuplicateEnds: boolean;
|
||||
|
||||
/** 현재 페이지를 갱신합니다. */
|
||||
setPage: (page: number) => void;
|
||||
/** 다이얼로그 열림 상태를 갱신합니다. */
|
||||
@@ -29,27 +43,51 @@ interface LottoState {
|
||||
setCondition2: (value: boolean) => void;
|
||||
/** 조건 3 활성화 여부를 갱신합니다. */
|
||||
setCondition3: (value: boolean) => void;
|
||||
setExcludeRecentDrawsCount: (value: number) => void;
|
||||
|
||||
// 고급 조건 Setter들
|
||||
setApplyBalancedOddEven: (value: boolean) => void;
|
||||
setApplySumRange: (value: boolean) => void;
|
||||
setApplyConsecutive: (value: boolean) => void;
|
||||
setApplyComplexityAC: (value: boolean) => void;
|
||||
setApplyPrimeFilter: (value: boolean) => void;
|
||||
setApplyNoDuplicateEnds: (value: boolean) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 로또 UI 상태를 전역 스토어로 관리합니다.
|
||||
* - 페이지, 다이얼로그, 추천번호, 조건 플래그를 분리해 컴포넌트 간 데이터 흐름을 단순화합니다.
|
||||
*/
|
||||
export const useLottoStore = create<LottoState>((set) => ({
|
||||
// 초기 페이지는 1로 고정합니다.
|
||||
page: 1,
|
||||
// 다이얼로그는 기본 닫힘 상태로 시작합니다.
|
||||
dialogOpen: false,
|
||||
// 추천 번호는 다이얼로그 열기 시점에 채웁니다.
|
||||
recommendations: [],
|
||||
// 조건 플래그는 기본 활성화로 두고, UI에서 토글하도록 합니다.
|
||||
condition1: true,
|
||||
condition2: true,
|
||||
condition3: true,
|
||||
excludeRecentDrawsCount: 3,
|
||||
|
||||
// 고급 조건 초기값
|
||||
applyBalancedOddEven: false,
|
||||
applySumRange: false,
|
||||
applyConsecutive: false,
|
||||
applyComplexityAC: false,
|
||||
applyPrimeFilter: false,
|
||||
applyNoDuplicateEnds: false,
|
||||
|
||||
setPage: (page) => set({ page }),
|
||||
setDialogOpen: (open) => set({ dialogOpen: open }),
|
||||
setRecommendations: (recommendations) => set({ recommendations }),
|
||||
setCondition1: (value) => set({ condition1: value }),
|
||||
setCondition2: (value) => set({ condition2: value }),
|
||||
setCondition3: (value) => set({ condition3: value }),
|
||||
setExcludeRecentDrawsCount: (value) =>
|
||||
set({ excludeRecentDrawsCount: Math.max(0, Math.floor(value)) }),
|
||||
|
||||
// 고급 조건 Setter 구현
|
||||
setApplyBalancedOddEven: (value) => set({ applyBalancedOddEven: value }),
|
||||
setApplySumRange: (value) => set({ applySumRange: value }),
|
||||
setApplyConsecutive: (value) => set({ applyConsecutive: value }),
|
||||
setApplyComplexityAC: (value) => set({ applyComplexityAC: value }),
|
||||
setApplyPrimeFilter: (value) => set({ applyPrimeFilter: value }),
|
||||
setApplyNoDuplicateEnds: (value) => set({ applyNoDuplicateEnds: value }),
|
||||
}));
|
||||
|
||||
@@ -1,31 +1,45 @@
|
||||
import { LottoDraw } from "../types/lotto";
|
||||
|
||||
// ============================================================================
|
||||
// 상수 (Constants)
|
||||
// ============================================================================
|
||||
const LOTTO_MAX = 45;
|
||||
const LOTTO_COUNT = 6;
|
||||
|
||||
// ============================================================================
|
||||
// 타입 정의 (Type Definitions)
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 번호 생성 시 사용할 옵션입니다.
|
||||
* @property {number} [maxNumber] - 번호의 최대값(기본 45)입니다.
|
||||
* @property {number} [count] - 생성할 번호 개수(기본 6)입니다.
|
||||
* @property {LottoDraw[]} [recentDraws] - 최근 회차 데이터입니다.
|
||||
* @property {number} [excludeRecentDrawsCount] - 제외할 최근 회차 개수(기본 3)입니다.
|
||||
* @property {number} [wHot] - Hot(자주 나온 번호) 가중치(기본 0.6)입니다.
|
||||
* @property {number} [wDue] - Due(오래 안 나온 번호) 가중치(기본 0.4)입니다.
|
||||
*/
|
||||
interface GenerateLottoOptions {
|
||||
export interface GenerateLottoOptions {
|
||||
maxNumber?: number;
|
||||
count?: number;
|
||||
recentDraws?: LottoDraw[];
|
||||
excludeRecentDrawsCount?: number;
|
||||
wHot?: number;
|
||||
wDue?: number;
|
||||
/** 조건 1: 최근 N회차 메인 번호 제외 (기본 true) */
|
||||
/** 조건 1: 최근 N회차 메인 번호 제외 */
|
||||
useCondition1?: boolean;
|
||||
/** 조건 2: 최근 N회차 보너스 번호 제외 (기본 true) */
|
||||
/** 조건 2: 최근 N회차 보너스 번호 제외 */
|
||||
useCondition2?: boolean;
|
||||
/** 조건 3: Hot & Due 알고리즘 적용 (기본 true) */
|
||||
/** 조건 3: Hot & Due 알고리즘 적용 */
|
||||
useCondition3?: boolean;
|
||||
|
||||
// 고급 전략 필터
|
||||
/** 고급: 홀짝 비율 3:3 또는 2:4 */
|
||||
applyBalancedOddEven?: boolean;
|
||||
/** 고급: 합계 범위 121~160 */
|
||||
applySumRange?: boolean;
|
||||
/** 고급: 연속 번호 포함 여부 */
|
||||
applyConsecutive?: boolean;
|
||||
/** 고급: AC값(복잡도) 7 이상 */
|
||||
applyComplexityAC?: boolean;
|
||||
/** 고급: 소수(Prime) 1~3개 포함 */
|
||||
applyPrimeFilter?: boolean;
|
||||
/** 고급: 동일 끝수 3개 이상 제한 */
|
||||
applyNoDuplicateEnds?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -39,19 +53,90 @@ interface NumberScore {
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 조건 1 & 2: 최근 회차 번호 제외 (Exclusion Rules)
|
||||
// [기본 도구] 헬퍼 함수
|
||||
// ============================================================================
|
||||
|
||||
/** 1~45 기본 배열 생성 */
|
||||
const getFullNumbers = () => Array.from({ length: LOTTO_MAX }, (_, i) => i + 1);
|
||||
|
||||
/** 배열 무작위 셔플 (Fisher-Yates 알고리즘 권장하나 원본 코드 컨셉 존중) */
|
||||
const shuffle = <T>(array: T[]): T[] => [...array].sort(() => Math.random() - 0.5);
|
||||
|
||||
// ============================================================================
|
||||
// [분석 도구] 통계 및 필터 함수
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 최근 회차의 메인 번호를 수집합니다.
|
||||
* @param {LottoDraw[]} recentDraws - 최근 회차 목록입니다.
|
||||
* @param {number} excludeCount - 제외할 회차 수입니다.
|
||||
* @returns {Set<number>} 제외할 메인 번호 집합입니다.
|
||||
* 홀짝 비율 계산 (Odd/Even)
|
||||
* @returns { odd: 홀수 개수, even: 짝수 개수 }
|
||||
*/
|
||||
function collectRecentDrawNumbers(
|
||||
recentDraws: LottoDraw[],
|
||||
excludeCount: number
|
||||
): Set<number> {
|
||||
export const getOddEvenRatio = (nums: number[]) => {
|
||||
const odd = nums.filter(n => n % 2 !== 0).length;
|
||||
return { odd, even: LOTTO_COUNT - odd };
|
||||
};
|
||||
|
||||
/**
|
||||
* 번호 합계 계산 (Sum)
|
||||
*/
|
||||
export const getSum = (nums: number[]) => nums.reduce((acc, cur) => acc + cur, 0);
|
||||
|
||||
/**
|
||||
* 연속 번호 유무 확인 (Consecutive)
|
||||
* 예: [1, 2, 10, 20, 30, 40] -> true (1, 2가 연속)
|
||||
*/
|
||||
export const hasConsecutive = (nums: number[]) => {
|
||||
const sorted = [...nums].sort((a, b) => a - b);
|
||||
return sorted.some((n, i) => i > 0 && n === sorted[i - 1] + 1);
|
||||
};
|
||||
|
||||
/**
|
||||
* 저고 비율 (Low: 1~22, High: 23~45)
|
||||
*/
|
||||
export const getLowHighRatio = (nums: number[]) => {
|
||||
const low = nums.filter(n => n <= 22).length;
|
||||
return { low, high: LOTTO_COUNT - low };
|
||||
};
|
||||
|
||||
/**
|
||||
* 소수(Prime Number) 포함 개수 확인
|
||||
*/
|
||||
export const getPrimeCount = (nums: number[]) => {
|
||||
const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43];
|
||||
return nums.filter(n => primes.includes(n)).length;
|
||||
};
|
||||
|
||||
/**
|
||||
* 끝수 동일 여부 체크 (Diversity / Duplicate End Digits)
|
||||
* 같은 끝수가 3개 이상이면 true (중복도가 높다고 판단)
|
||||
*/
|
||||
export const hasDuplicateEndDigitIssue = (nums: number[]) => {
|
||||
const ends = nums.map(n => n % 10);
|
||||
const counts: Record<number, number> = {};
|
||||
ends.forEach(e => { counts[e] = (counts[e] || 0) + 1; });
|
||||
return Object.values(counts).some(c => c >= 3);
|
||||
};
|
||||
|
||||
/**
|
||||
* AC값(Adjacency Complexity) 계산 (번호 간 복잡도)
|
||||
* 로또의 불규칙성을 측정하는 수치로, 보통 7 이상을 선호합니다.
|
||||
*/
|
||||
export const getACValue = (nums: number[]) => {
|
||||
const diffs = new Set<number>();
|
||||
const sorted = [...nums].sort((a, b) => a - b);
|
||||
for (let i = 0; i < sorted.length; i++) {
|
||||
for (let j = i + 1; j < sorted.length; j++) {
|
||||
diffs.add(sorted[j] - sorted[i]);
|
||||
}
|
||||
}
|
||||
return diffs.size - (LOTTO_COUNT - 1);
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// [필터 도구] 기존 및 신규 필터
|
||||
// ============================================================================
|
||||
|
||||
/** 최근 회차 메인 번호 수집 */
|
||||
function collectRecentDrawNumbers(recentDraws: LottoDraw[], excludeCount: number): Set<number> {
|
||||
const excluded = new Set<number>();
|
||||
recentDraws.slice(0, excludeCount).forEach((draw) => {
|
||||
draw.numbers.forEach((value) => excluded.add(value));
|
||||
@@ -59,108 +144,31 @@ function collectRecentDrawNumbers(
|
||||
return excluded;
|
||||
}
|
||||
|
||||
/**
|
||||
* 최근 회차의 보너스 번호를 수집합니다.
|
||||
* @param {LottoDraw[]} recentDraws - 최근 회차 목록입니다.
|
||||
* @param {number} excludeCount - 제외할 회차 수입니다.
|
||||
* @returns {Set<number>} 제외할 보너스 번호 집합입니다.
|
||||
*/
|
||||
function collectRecentBonusNumbers(
|
||||
recentDraws: LottoDraw[],
|
||||
excludeCount: number
|
||||
): Set<number> {
|
||||
/** 최근 회차 보너스 번호 수집 */
|
||||
function collectRecentBonusNumbers(recentDraws: LottoDraw[], excludeCount: number): Set<number> {
|
||||
const excluded = new Set<number>();
|
||||
recentDraws.slice(0, excludeCount).forEach((draw) => {
|
||||
if (draw.bonusNumber) {
|
||||
excluded.add(draw.bonusNumber);
|
||||
}
|
||||
if (draw.bonusNumber) excluded.add(draw.bonusNumber);
|
||||
});
|
||||
return excluded;
|
||||
}
|
||||
|
||||
/**
|
||||
* 최근 회차 번호 제외 규칙입니다.
|
||||
*/
|
||||
function isExcludedByRecentDraws(
|
||||
value: number,
|
||||
excludedNumbers: Set<number>
|
||||
): boolean {
|
||||
return excludedNumbers.has(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 최근 회차 보너스 번호 제외 규칙입니다.
|
||||
*/
|
||||
function isExcludedByRecentBonusNumbers(
|
||||
value: number,
|
||||
excludedBonusNumbers: Set<number>
|
||||
): boolean {
|
||||
return excludedBonusNumbers.has(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 제외 규칙에 맞는 후보 번호 목록을 만듭니다.
|
||||
*/
|
||||
function buildCandidateNumbers(
|
||||
maxNumber: number,
|
||||
isExcluded: (value: number) => boolean
|
||||
): number[] {
|
||||
const candidates: number[] = [];
|
||||
for (let value = 1; value <= maxNumber; value += 1) {
|
||||
if (!isExcluded(value)) {
|
||||
candidates.push(value);
|
||||
}
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 조건 3: Hot & Due 알고리즘 (Weighted Sampling)
|
||||
// ----------------------------------------------------------------------------
|
||||
// "Hot & Due"는 통계 기반 번호 선정 전략입니다.
|
||||
//
|
||||
// - Hot (뜨거운 번호): 최근에 자주 나온 번호는 "핫"하다고 봅니다.
|
||||
// → 이런 번호는 계속 나올 확률이 높다고 가정합니다.
|
||||
//
|
||||
// - Due (오래된 번호): 오랫동안 안 나온 번호는 "곧 나올 차례"라고 봅니다.
|
||||
// → 이런 번호는 조만간 나올 확률이 높다고 가정합니다.
|
||||
//
|
||||
// 이 두 가지 점수를 wHot(기본 0.6)과 wDue(기본 0.4) 비율로 섞어서
|
||||
// 각 번호에 "선택 확률(가중치)"을 부여합니다.
|
||||
// 가중치가 높을수록 뽑힐 확률이 높아지는 방식입니다.
|
||||
//
|
||||
// 예) 번호 7이 자주 나왔고(Hot 점수 높음) + 최근에도 나왔다면(Due 점수 낮음)
|
||||
// → 전체 점수는 "중간 정도"가 됩니다.
|
||||
// 예) 번호 42가 자주 나왔고(Hot 점수 높음) + 오래 안 나왔다면(Due 점수 높음)
|
||||
// → 전체 점수가 "매우 높아져서" 뽑힐 확률이 커집니다.
|
||||
// [핵심 로직] Hot & Due 및 가중치 샘플링
|
||||
// ============================================================================
|
||||
|
||||
|
||||
/**
|
||||
* 후보 번호 목록에 대해 출현 빈도(freq)와 미출현 기간(gap)을 계산합니다.
|
||||
*
|
||||
* @param {number[]} candidates - 후보 번호 목록입니다.
|
||||
* @param {LottoDraw[]} history - 과거 회차 전체 데이터입니다.
|
||||
* @returns {{ counts: Map<number, number>, gaps: Map<number, number> }} 통계 결과입니다.
|
||||
*/
|
||||
function calculateNumberStats(
|
||||
candidates: number[],
|
||||
history: LottoDraw[]
|
||||
): { counts: Map<number, number>; gaps: Map<number, number> } {
|
||||
// 회차를 id 오름차순으로 정렬 (인덱스 = 시간순)
|
||||
/** 번호별 출현 빈도 및 미출현 기간 계산 */
|
||||
function calculateNumberStats(candidates: number[], history: LottoDraw[]) {
|
||||
const sortedHistory = [...history].sort((a, b) => a.id - b.id);
|
||||
const drawCount = sortedHistory.length;
|
||||
|
||||
const counts = new Map<number, number>();
|
||||
const lastSeen = new Map<number, number>();
|
||||
|
||||
// 후보 번호들의 초기값 설정
|
||||
candidates.forEach((num) => {
|
||||
counts.set(num, 0);
|
||||
lastSeen.set(num, -1); // -1은 "한 번도 안 나옴"을 의미
|
||||
lastSeen.set(num, -1);
|
||||
});
|
||||
|
||||
// 각 회차를 순회하며 통계 집계
|
||||
sortedHistory.forEach((draw, idx) => {
|
||||
draw.numbers.forEach((num) => {
|
||||
if (counts.has(num)) {
|
||||
@@ -170,195 +178,128 @@ function calculateNumberStats(
|
||||
});
|
||||
});
|
||||
|
||||
// 미출현 기간(gap) 계산: 마지막으로 나온 이후 몇 회차가 지났는지
|
||||
const gaps = new Map<number, number>();
|
||||
candidates.forEach((num) => {
|
||||
const last = lastSeen.get(num) ?? -1;
|
||||
if (last === -1) {
|
||||
// 한 번도 안 나온 번호는 gap을 최대치로 설정
|
||||
gaps.set(num, drawCount);
|
||||
} else {
|
||||
gaps.set(num, drawCount - 1 - last);
|
||||
}
|
||||
gaps.set(num, last === -1 ? drawCount : drawCount - 1 - last);
|
||||
});
|
||||
|
||||
return { counts, gaps };
|
||||
}
|
||||
|
||||
/**
|
||||
* 후보 번호 목록에 대해 Hot & Due 점수를 계산합니다.
|
||||
*
|
||||
* @param {number[]} candidates - 후보 번호 목록입니다.
|
||||
* @param {Map<number, number>} counts - 번호별 출현 횟수입니다.
|
||||
* @param {Map<number, number>} gaps - 번호별 미출현 기간입니다.
|
||||
* @param {number} wHot - Hot 가중치입니다 (0~1).
|
||||
* @param {number} wDue - Due 가중치입니다 (0~1).
|
||||
* @returns {NumberScore[]} 번호별 점수 배열입니다.
|
||||
*/
|
||||
function calculateScores(
|
||||
candidates: number[],
|
||||
counts: Map<number, number>,
|
||||
gaps: Map<number, number>,
|
||||
wHot: number,
|
||||
wDue: number
|
||||
): NumberScore[] {
|
||||
// 정규화를 위한 최대값 계산
|
||||
let maxCount = 0;
|
||||
let maxGap = 0;
|
||||
/** Hot & Due 점수 합산 */
|
||||
function calculateScores(candidates: number[], counts: Map<number, number>, gaps: Map<number, number>, wHot: number, wDue: number): NumberScore[] {
|
||||
let maxCount = Math.max(...Array.from(counts.values()), 1);
|
||||
let maxGap = Math.max(...Array.from(gaps.values()), 1);
|
||||
|
||||
candidates.forEach((num) => {
|
||||
const c = counts.get(num) ?? 0;
|
||||
const g = gaps.get(num) ?? 0;
|
||||
if (c > maxCount) maxCount = c;
|
||||
if (g > maxGap) maxGap = g;
|
||||
return candidates.map((num) => {
|
||||
const freqNorm = (counts.get(num) ?? 0) / maxCount;
|
||||
const gapNorm = (gaps.get(num) ?? 0) / maxGap;
|
||||
const score = Math.max(wHot * freqNorm + wDue * gapNorm, 1e-6);
|
||||
return { num, score, freq: counts.get(num) ?? 0, gap: gaps.get(num) ?? 0 };
|
||||
});
|
||||
|
||||
// 방어 코드: 0으로 나누는 것 방지
|
||||
if (maxCount === 0) maxCount = 1;
|
||||
if (maxGap === 0) maxGap = 1;
|
||||
|
||||
// 점수 계산
|
||||
const scores: NumberScore[] = candidates.map((num) => {
|
||||
const freq = counts.get(num) ?? 0;
|
||||
const gap = gaps.get(num) ?? 0;
|
||||
|
||||
// 정규화 (0~1 범위)
|
||||
const freqNorm = freq / maxCount;
|
||||
const gapNorm = gap / maxGap;
|
||||
|
||||
// Hot & Due 혼합 점수
|
||||
const rawScore = wHot * freqNorm + wDue * gapNorm;
|
||||
|
||||
// 0이 되면 선택에서 완전히 배제되므로 아주 작은 값으로 보정
|
||||
const score = rawScore <= 0 ? 1e-6 : rawScore;
|
||||
|
||||
return { num, score, freq, gap };
|
||||
});
|
||||
|
||||
return scores;
|
||||
}
|
||||
|
||||
/**
|
||||
* 가중치에 비례하여 k개의 번호를 중복 없이 뽑습니다.
|
||||
*
|
||||
* @param {NumberScore[]} scoreList - 번호별 점수 배열입니다.
|
||||
* @param {number} k - 뽑을 개수입니다.
|
||||
* @returns {number[]} 선택된 번호 배열입니다.
|
||||
*/
|
||||
function weightedSampleWithoutReplacement(
|
||||
scoreList: NumberScore[],
|
||||
k: number
|
||||
): number[] {
|
||||
/** 가중치 기반 비복원 추출 */
|
||||
function weightedSample(scoreList: NumberScore[], k: number): number[] {
|
||||
const available = [...scoreList];
|
||||
const result: number[] = [];
|
||||
|
||||
for (let i = 0; i < k; i++) {
|
||||
if (available.length === 0) break;
|
||||
|
||||
// 전체 가중치 합계 계산
|
||||
const totalWeight = available.reduce((sum, item) => sum + item.score, 0);
|
||||
let r = Math.random() * totalWeight;
|
||||
|
||||
// 가중치 기반으로 하나 선택
|
||||
let chosenIndex = 0;
|
||||
for (let idx = 0; idx < available.length; idx++) {
|
||||
r -= available[idx].score;
|
||||
if (r <= 0) {
|
||||
chosenIndex = idx;
|
||||
break;
|
||||
}
|
||||
if (r <= 0) { chosenIndex = idx; break; }
|
||||
}
|
||||
|
||||
const chosen = available[chosenIndex];
|
||||
result.push(chosen.num);
|
||||
available.splice(chosenIndex, 1); // 중복 방지를 위해 제거
|
||||
result.push(available[chosenIndex].num);
|
||||
available.splice(chosenIndex, 1);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 메인 함수 (Main Function)
|
||||
// [메인 엔진] 서바이벌 생성기
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 로또 번호를 랜덤으로 생성합니다.
|
||||
* @param {number} maxNumber - 번호의 최대값(기본 45)입니다.
|
||||
* @param {number} count - 생성할 번호 개수(기본 6)입니다.
|
||||
* @returns {number[]} 오름차순으로 정렬된 로또 번호 배열입니다.
|
||||
* 모든 통계적 필터 조건을 통과할 때까지 무한(최대 5000회) 반복 생성합니다.
|
||||
*/
|
||||
export function generateLottoNumbers(maxNumber?: number, count?: number): number[];
|
||||
/**
|
||||
* 로또 번호를 랜덤으로 생성합니다.
|
||||
* @param {GenerateLottoOptions} options - 생성 옵션입니다.
|
||||
* @returns {number[]} 오름차순으로 정렬된 로또 번호 배열입니다.
|
||||
*/
|
||||
export function generateLottoNumbers(options?: GenerateLottoOptions): number[];
|
||||
export function generateLottoNumbers(
|
||||
arg1: number | GenerateLottoOptions = 45,
|
||||
arg2 = 6
|
||||
): number[] {
|
||||
// 기존 시그니처(숫자 인자)와 옵션 객체 방식을 모두 지원합니다.
|
||||
const baseOptions: GenerateLottoOptions =
|
||||
typeof arg1 === "number"
|
||||
? { maxNumber: arg1, count: arg2 }
|
||||
: arg1 ?? {};
|
||||
export function generateLottoNumbers(options: GenerateLottoOptions = {}): number[] {
|
||||
const {
|
||||
maxNumber = 45,
|
||||
count = 6,
|
||||
recentDraws = [],
|
||||
excludeRecentDrawsCount = 3,
|
||||
wHot = 0.6,
|
||||
wDue = 0.4,
|
||||
useCondition1 = true,
|
||||
useCondition2 = true,
|
||||
useCondition3 = true,
|
||||
applyBalancedOddEven = false,
|
||||
applySumRange = false,
|
||||
applyConsecutive = false,
|
||||
applyComplexityAC = false,
|
||||
applyPrimeFilter = false,
|
||||
applyNoDuplicateEnds = false,
|
||||
} = options;
|
||||
|
||||
const maxNumber = baseOptions.maxNumber ?? 45;
|
||||
const count = baseOptions.count ?? 6;
|
||||
// 최근 회차 제외 개수는 기본 3개로 맞춥니다.
|
||||
const excludeRecentDrawsCount = baseOptions.excludeRecentDrawsCount ?? 3;
|
||||
const recentDraws = baseOptions.recentDraws ?? [];
|
||||
const wHot = baseOptions.wHot ?? 0.6;
|
||||
const wDue = baseOptions.wDue ?? 0.4;
|
||||
// 1. 제외수 수집
|
||||
const excludedMain = useCondition1 ? collectRecentDrawNumbers(recentDraws, excludeRecentDrawsCount) : new Set<number>();
|
||||
const excludedBonus = useCondition2 ? collectRecentBonusNumbers(recentDraws, excludeRecentDrawsCount) : new Set<number>();
|
||||
const isExcluded = (num: number) => excludedMain.has(num) || excludedBonus.has(num);
|
||||
|
||||
// 조건 플래그 (기본값: 모두 true)
|
||||
const useCondition1 = baseOptions.useCondition1 ?? true;
|
||||
const useCondition2 = baseOptions.useCondition2 ?? true;
|
||||
const useCondition3 = baseOptions.useCondition3 ?? true;
|
||||
// 2. 후보군 필터링
|
||||
const candidates = getFullNumbers().filter(n => n <= maxNumber && !isExcluded(n));
|
||||
if (candidates.length < count) return [];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 조건 1: 최근 회차(기본 3개)의 메인 번호는 제외합니다.
|
||||
// ---------------------------------------------------------------------------
|
||||
const excludedDrawNumbers = useCondition1
|
||||
? collectRecentDrawNumbers(recentDraws, excludeRecentDrawsCount)
|
||||
: new Set<number>();
|
||||
// 3. 서바이벌 루프 (Survival Loop)
|
||||
let attempts = 0;
|
||||
const MAX_ATTEMPTS = 5000;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 조건 2: 최근 회차(기본 3개)의 보너스 번호는 제외합니다.
|
||||
// ---------------------------------------------------------------------------
|
||||
const excludedBonusNumbers = useCondition2
|
||||
? collectRecentBonusNumbers(recentDraws, excludeRecentDrawsCount)
|
||||
: new Set<number>();
|
||||
while (attempts < MAX_ATTEMPTS) {
|
||||
attempts++;
|
||||
|
||||
// 기본 추출 (Hot & Due 가중치 또는 균등 랜덤)
|
||||
let picked: number[];
|
||||
if (useCondition3 && recentDraws.length >= 10) {
|
||||
const { counts, gaps } = calculateNumberStats(candidates, recentDraws);
|
||||
const scores = calculateScores(candidates, counts, gaps, wHot, wDue);
|
||||
picked = weightedSample(scores, count);
|
||||
} else {
|
||||
picked = shuffle(candidates).slice(0, count);
|
||||
}
|
||||
|
||||
const isExcluded = (value: number) =>
|
||||
isExcludedByRecentDraws(value, excludedDrawNumbers) ||
|
||||
isExcludedByRecentBonusNumbers(value, excludedBonusNumbers);
|
||||
// 통계 필터 검증
|
||||
if (applyBalancedOddEven) {
|
||||
const { odd } = getOddEvenRatio(picked);
|
||||
if (!(odd === 3 || odd === 2 || odd === 4)) continue;
|
||||
}
|
||||
|
||||
// 제외 규칙을 통과한 후보 목록 생성
|
||||
const candidates = buildCandidateNumbers(maxNumber, isExcluded);
|
||||
if (candidates.length < count) {
|
||||
// 제외 조건이 너무 강하면 빈 배열을 반환해 안전하게 실패합니다.
|
||||
// (예: 최근 회차가 너무 많아 후보가 부족한 경우)
|
||||
return [];
|
||||
}
|
||||
if (applySumRange) {
|
||||
const sum = getSum(picked);
|
||||
if (sum < 121 || sum > 160) continue;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 조건 3: Hot & Due 알고리즘으로 가중치 기반 랜덤 선택
|
||||
// useCondition3가 true이고, recentDraws가 충분히 있을 때만 적용합니다.
|
||||
// ---------------------------------------------------------------------------
|
||||
if (useCondition3 && recentDraws.length >= 10) {
|
||||
const { counts, gaps } = calculateNumberStats(candidates, recentDraws);
|
||||
const scores = calculateScores(candidates, counts, gaps, wHot, wDue);
|
||||
const picked = weightedSampleWithoutReplacement(scores, count);
|
||||
if (applyConsecutive === true && !hasConsecutive(picked)) continue;
|
||||
if (applyConsecutive === false && hasConsecutive(picked)) continue;
|
||||
|
||||
if (applyComplexityAC) {
|
||||
if (getACValue(picked) < 7) continue;
|
||||
}
|
||||
|
||||
if (applyPrimeFilter) {
|
||||
const pc = getPrimeCount(picked);
|
||||
if (pc < 1 || pc > 3) continue;
|
||||
}
|
||||
|
||||
if (applyNoDuplicateEnds && hasDuplicateEndDigitIssue(picked)) continue;
|
||||
|
||||
// 모든 필터 통과!
|
||||
return picked.sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
// 조건 3이 비활성화되었거나 과거 데이터가 부족하면 균등 확률로 뽑기
|
||||
const shuffled = [...candidates];
|
||||
for (let index = shuffled.length - 1; index > 0; index -= 1) {
|
||||
const swapIndex = Math.floor(Math.random() * (index + 1));
|
||||
[shuffled[index], shuffled[swapIndex]] = [shuffled[swapIndex], shuffled[index]];
|
||||
}
|
||||
return shuffled.slice(0, count).sort((a, b) => a - b);
|
||||
// 실패 시 기본 랜덤이라도 반환 (안전 장치)
|
||||
return shuffle(candidates).slice(0, count).sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { cn } from "@/lib/utils";
|
||||
// 상수 (Constants)
|
||||
// ============================================================================
|
||||
const DEFAULT_WIDTH = 720;
|
||||
const DEFAULT_HEIGHT = 520;
|
||||
const DEFAULT_HEIGHT = 700;
|
||||
const MIN_WIDTH = 320;
|
||||
const MIN_HEIGHT = 360;
|
||||
const VIEWPORT_PADDING = 16;
|
||||
@@ -47,6 +47,7 @@ export interface DialogDragResizeOptions {
|
||||
export interface DialogDragResizeResult {
|
||||
contentStyle?: CSSProperties;
|
||||
contentClassName: string;
|
||||
contentRef: React.RefObject<HTMLElement | null>;
|
||||
dragHandleProps: HTMLAttributes<HTMLElement>;
|
||||
dragHandleClassName: string;
|
||||
resizeHandleProps: HTMLAttributes<HTMLDivElement>;
|
||||
@@ -68,20 +69,16 @@ function clamp(value: number, min: number, max: number): number {
|
||||
|
||||
/**
|
||||
* 현재 뷰포트 기준으로 드래그 이동 범위를 계산합니다.
|
||||
* 다이얼로그가 `translate(-50%, -50%)`로 중앙 정렬되어 있으므로,
|
||||
* position(x, y)는 "중앙으로부터의 오프셋"입니다.
|
||||
*/
|
||||
function getDragBounds(width: number, height: number, padding: number) {
|
||||
const halfViewportW = window.innerWidth / 2;
|
||||
const halfViewportH = window.innerHeight / 2;
|
||||
const halfDialogW = width / 2;
|
||||
const halfDialogH = height / 2;
|
||||
const viewportW = window.innerWidth;
|
||||
const viewportH = window.innerHeight;
|
||||
|
||||
// x가 maxX일 때 다이얼로그 오른쪽 끝이 뷰포트 오른쪽 끝 - padding에 닿음
|
||||
const maxX = halfViewportW - padding - halfDialogW;
|
||||
const minX = -halfViewportW + padding + halfDialogW;
|
||||
const maxY = halfViewportH - padding - halfDialogH;
|
||||
const minY = -halfViewportH + padding + halfDialogH;
|
||||
// 좌상단 기준(0, 0)에서 다이얼로그가 위치할 수 있는 범위
|
||||
const maxX = viewportW - width - padding;
|
||||
const minX = padding;
|
||||
const maxY = viewportH - height - padding;
|
||||
const minY = padding;
|
||||
|
||||
return { minX, maxX, minY, maxY };
|
||||
}
|
||||
@@ -89,9 +86,9 @@ function getDragBounds(width: number, height: number, padding: number) {
|
||||
/**
|
||||
* 현재 뷰포트 기준으로 리사이즈 최대 크기를 계산합니다.
|
||||
*/
|
||||
function getResizeBounds(minWidth: number, minHeight: number, padding: number) {
|
||||
const maxWidth = Math.max(minWidth, window.innerWidth - padding * 2);
|
||||
const maxHeight = Math.max(minHeight, window.innerHeight - padding * 2);
|
||||
function getResizeBounds(posX: number, posY: number, minWidth: number, minHeight: number, padding: number) {
|
||||
const maxWidth = Math.max(minWidth, window.innerWidth - posX - padding);
|
||||
const maxHeight = Math.max(minHeight, window.innerHeight - posY - padding);
|
||||
return { maxWidth, maxHeight };
|
||||
}
|
||||
|
||||
@@ -101,12 +98,11 @@ function getResizeBounds(minWidth: number, minHeight: number, padding: number) {
|
||||
|
||||
/**
|
||||
* Radix Dialog를 드래그/리사이즈 가능하게 만드는 훅입니다.
|
||||
* 사용처에서 DialogContent와 헤더, 리사이즈 핸들에 props를 연결합니다.
|
||||
*
|
||||
* 주요 개선 사항:
|
||||
* 1. `will-change: transform`으로 GPU 가속 렌더링
|
||||
* 2. 드래그/리사이즈 중 `transition: none`으로 버벅임 방지
|
||||
* 3. 뷰포트 경계 내 위치 보정으로 창 고정 현상 방지
|
||||
* [주요 리팩토링 포인트]
|
||||
* 1. CSS Variables + requestAnimationFrame: 매 픽셀 이동 시 React 리렌더링을 방지하여 부드러운 전환 구현
|
||||
* 2. Absolute Positioning: translate(-50%, -50%)를 제거하고 좌상단 절대 좌표 기준으로 관리하여 계산 명확화
|
||||
* 3. Resize Logic: 리사이즈 시 마우스 따라가기 정확도 개선 및 바운더리 체크 강화
|
||||
*/
|
||||
export function useDialogDragResize(
|
||||
options: DialogDragResizeOptions = {}
|
||||
@@ -126,11 +122,23 @@ export function useDialogDragResize(
|
||||
// ---------------------------------------------------------------------------
|
||||
// State & Refs
|
||||
// ---------------------------------------------------------------------------
|
||||
// React State는 인터랙션이 '끝난 후' 최종 값을 반영하기 위해서만 사용 (성능 최적화)
|
||||
const [position, setPosition] = useState({ x: 0, y: 0 });
|
||||
const [size, setSize] = useState({ width: initialWidth, height: initialHeight });
|
||||
const [isInteracting, setIsInteracting] = useState(false);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
// 드래그/리사이즈 시작 시점의 스냅샷을 저장하는 Ref
|
||||
// 현재 값을 실시간으로 관리하는 Ref (CSS 변수 업데이트용)
|
||||
const stateRef = useRef({
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: initialWidth,
|
||||
height: initialHeight,
|
||||
});
|
||||
|
||||
const contentRef = useRef<HTMLElement | null>(null);
|
||||
|
||||
// 인터랙션 스냅샷 Ref
|
||||
const interactionRef = useRef({
|
||||
type: null as "drag" | "resize" | null,
|
||||
startPointerX: 0,
|
||||
@@ -139,45 +147,115 @@ export function useDialogDragResize(
|
||||
startPosY: 0,
|
||||
startWidth: 0,
|
||||
startHeight: 0,
|
||||
rafId: 0,
|
||||
});
|
||||
|
||||
const isActive = enabled && open;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Viewport Bounds 보정 (다이얼로그 열릴 때 & 화면 크기 변경 시)
|
||||
// 스타일 직접 업데이트 (성능 최적화)
|
||||
// ---------------------------------------------------------------------------
|
||||
const updateStyles = useCallback(() => {
|
||||
const el = contentRef.current;
|
||||
if (!el) return;
|
||||
|
||||
const { x, y, width, height } = stateRef.current;
|
||||
el.style.setProperty("--dialog-x", `${x}px`);
|
||||
el.style.setProperty("--dialog-y", `${y}px`);
|
||||
el.style.setProperty("--dialog-width", `${width}px`);
|
||||
el.style.setProperty("--dialog-height", `${height}px`);
|
||||
}, []);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Viewport Bounds 보정
|
||||
// ---------------------------------------------------------------------------
|
||||
const applyViewportBounds = useCallback(() => {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
const { maxWidth, maxHeight } = getResizeBounds(minWidth, minHeight, viewportPadding);
|
||||
const { width, height } = stateRef.current;
|
||||
|
||||
// 이전에 저장된 위치가 있으면 유지하되, 화면 밖으로 나갔는지 체크
|
||||
let currentX = stateRef.current.x;
|
||||
let currentY = stateRef.current.y;
|
||||
|
||||
setSize((prevSize) => {
|
||||
const nextWidth = clamp(prevSize.width, minWidth, maxWidth);
|
||||
const nextHeight = clamp(prevSize.height, minHeight, maxHeight);
|
||||
if (currentX === 0 && currentY === 0) {
|
||||
// 초기 중앙 정합 (첫 실행 시)
|
||||
currentX = (window.innerWidth - width) / 2;
|
||||
currentY = (window.innerHeight - height) / 2;
|
||||
}
|
||||
|
||||
setPosition((prevPos) => {
|
||||
const { minX, maxX, minY, maxY } = getDragBounds(nextWidth, nextHeight, viewportPadding);
|
||||
return {
|
||||
x: clamp(prevPos.x, minX, maxX),
|
||||
y: clamp(prevPos.y, minY, maxY),
|
||||
};
|
||||
});
|
||||
// 현재 위치를 기준으로 가능한 최대 크기 계산
|
||||
const { maxWidth: maxW, maxHeight: maxH } = getResizeBounds(currentX, currentY, minWidth, minHeight, viewportPadding);
|
||||
|
||||
const nextWidth = clamp(width, minWidth, maxW);
|
||||
const nextHeight = clamp(height, minHeight, maxH);
|
||||
|
||||
// 드래그 가능 범위 내로 좌표 보정
|
||||
const { minX, maxX, minY, maxY } = getDragBounds(nextWidth, nextHeight, viewportPadding);
|
||||
const nextX = clamp(currentX, minX, maxX);
|
||||
const nextY = clamp(currentY, minY, maxY);
|
||||
|
||||
return { width: nextWidth, height: nextHeight };
|
||||
});
|
||||
}, [minHeight, minWidth, viewportPadding]);
|
||||
const nextState = { x: nextX, y: nextY, width: nextWidth, height: nextHeight };
|
||||
|
||||
// Ref와 상태 동기화
|
||||
stateRef.current = nextState;
|
||||
setPosition({ x: nextX, y: nextY });
|
||||
setSize({ width: nextWidth, height: nextHeight });
|
||||
|
||||
// 수동 스타일 업데이트 시도
|
||||
updateStyles();
|
||||
|
||||
if (!isInitialized) {
|
||||
// 최초 초기화 완료 표시
|
||||
requestAnimationFrame(() => setIsInitialized(true));
|
||||
}
|
||||
}, [minHeight, minWidth, viewportPadding, updateStyles, isInitialized]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isActive) return;
|
||||
if (!isActive) {
|
||||
setIsInitialized(false);
|
||||
return;
|
||||
}
|
||||
applyViewportBounds();
|
||||
}, [applyViewportBounds, isActive]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isActive) return;
|
||||
window.addEventListener("resize", applyViewportBounds);
|
||||
return () => window.removeEventListener("resize", applyViewportBounds);
|
||||
const handleWindowResize = () => {
|
||||
cancelAnimationFrame(interactionRef.current.rafId);
|
||||
interactionRef.current.rafId = requestAnimationFrame(applyViewportBounds);
|
||||
};
|
||||
window.addEventListener("resize", handleWindowResize);
|
||||
return () => {
|
||||
window.removeEventListener("resize", handleWindowResize);
|
||||
cancelAnimationFrame(interactionRef.current.rafId);
|
||||
};
|
||||
}, [applyViewportBounds, isActive]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 인터랙션 메인 핸들러 (Move)
|
||||
// ---------------------------------------------------------------------------
|
||||
const handlePointerMove = useCallback((event: PointerEvent) => {
|
||||
const ref = interactionRef.current;
|
||||
if (!ref.type) return;
|
||||
|
||||
const dx = event.clientX - ref.startPointerX;
|
||||
const dy = event.clientY - ref.startPointerY;
|
||||
|
||||
if (ref.type === "drag") {
|
||||
const { minX, maxX, minY, maxY } = getDragBounds(ref.startWidth, ref.startHeight, viewportPadding);
|
||||
stateRef.current.x = clamp(ref.startPosX + dx, minX, maxX);
|
||||
stateRef.current.y = clamp(ref.startPosY + dy, minY, maxY);
|
||||
} else if (ref.type === "resize") {
|
||||
const { maxWidth, maxHeight } = getResizeBounds(ref.startPosX, ref.startPosY, minWidth, minHeight, viewportPadding);
|
||||
stateRef.current.width = clamp(ref.startWidth + dx, minWidth, maxWidth);
|
||||
stateRef.current.height = clamp(ref.startHeight + dy, minHeight, maxHeight);
|
||||
}
|
||||
|
||||
cancelAnimationFrame(ref.rafId);
|
||||
ref.rafId = requestAnimationFrame(updateStyles);
|
||||
}, [minHeight, minWidth, viewportPadding, updateStyles]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 드래그 핸들러 (Drag Handlers)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -187,42 +265,33 @@ export function useDialogDragResize(
|
||||
event.preventDefault();
|
||||
|
||||
interactionRef.current = {
|
||||
...interactionRef.current,
|
||||
type: "drag",
|
||||
startPointerX: event.clientX,
|
||||
startPointerY: event.clientY,
|
||||
startPosX: position.x,
|
||||
startPosY: position.y,
|
||||
startWidth: size.width,
|
||||
startHeight: size.height,
|
||||
startPosX: stateRef.current.x,
|
||||
startPosY: stateRef.current.y,
|
||||
startWidth: stateRef.current.width,
|
||||
startHeight: stateRef.current.height,
|
||||
};
|
||||
setIsInteracting(true);
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
},
|
||||
[draggable, isActive, position.x, position.y, size.width, size.height]
|
||||
[draggable, isActive]
|
||||
);
|
||||
|
||||
const handleDragMove = useCallback(
|
||||
(event: PointerEvent<HTMLElement>) => {
|
||||
const ref = interactionRef.current;
|
||||
if (ref.type !== "drag") return;
|
||||
const handleInteractionEnd = useCallback((event: PointerEvent<HTMLElement>) => {
|
||||
const ref = interactionRef.current;
|
||||
if (!ref.type) return;
|
||||
|
||||
const dx = event.clientX - ref.startPointerX;
|
||||
const dy = event.clientY - ref.startPointerY;
|
||||
const { minX, maxX, minY, maxY } = getDragBounds(ref.startWidth, ref.startHeight, viewportPadding);
|
||||
|
||||
setPosition({
|
||||
x: clamp(ref.startPosX + dx, minX, maxX),
|
||||
y: clamp(ref.startPosY + dy, minY, maxY),
|
||||
});
|
||||
},
|
||||
[viewportPadding]
|
||||
);
|
||||
|
||||
const handleDragEnd = useCallback((event: PointerEvent<HTMLElement>) => {
|
||||
if (interactionRef.current.type !== "drag") return;
|
||||
interactionRef.current.type = null;
|
||||
// 최종 값을 React State에 동기화하여 UI 정합성 유지
|
||||
setPosition({ x: stateRef.current.x, y: stateRef.current.y });
|
||||
setSize({ width: stateRef.current.width, height: stateRef.current.height });
|
||||
|
||||
ref.type = null;
|
||||
setIsInteracting(false);
|
||||
event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
cancelAnimationFrame(ref.rafId);
|
||||
}, []);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -234,107 +303,84 @@ export function useDialogDragResize(
|
||||
event.preventDefault();
|
||||
|
||||
interactionRef.current = {
|
||||
...interactionRef.current,
|
||||
type: "resize",
|
||||
startPointerX: event.clientX,
|
||||
startPointerY: event.clientY,
|
||||
startPosX: position.x,
|
||||
startPosY: position.y,
|
||||
startWidth: size.width,
|
||||
startHeight: size.height,
|
||||
startPosX: stateRef.current.x,
|
||||
startPosY: stateRef.current.y,
|
||||
startWidth: stateRef.current.width,
|
||||
startHeight: stateRef.current.height,
|
||||
};
|
||||
setIsInteracting(true);
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
},
|
||||
[isActive, position.x, position.y, resizable, size.width, size.height]
|
||||
[isActive, resizable]
|
||||
);
|
||||
|
||||
const handleResizeMove = useCallback(
|
||||
(event: PointerEvent<HTMLDivElement>) => {
|
||||
const ref = interactionRef.current;
|
||||
if (ref.type !== "resize") return;
|
||||
|
||||
const dx = event.clientX - ref.startPointerX;
|
||||
const dy = event.clientY - ref.startPointerY;
|
||||
|
||||
const { maxWidth, maxHeight } = getResizeBounds(minWidth, minHeight, viewportPadding);
|
||||
|
||||
const nextWidth = clamp(ref.startWidth + dx, minWidth, maxWidth);
|
||||
const nextHeight = clamp(ref.startHeight + dy, minHeight, maxHeight);
|
||||
|
||||
// 왼쪽 위 고정을 위해 크기 변화량의 절반만큼 중심 이동
|
||||
const dWidth = nextWidth - ref.startWidth;
|
||||
const dHeight = nextHeight - ref.startHeight;
|
||||
|
||||
const rawNextX = ref.startPosX + dWidth / 2;
|
||||
const rawNextY = ref.startPosY + dHeight / 2;
|
||||
|
||||
// 뷰포트 경계 보정
|
||||
const { minX, maxX, minY, maxY } = getDragBounds(nextWidth, nextHeight, viewportPadding);
|
||||
|
||||
setSize({ width: nextWidth, height: nextHeight });
|
||||
setPosition({
|
||||
x: clamp(rawNextX, minX, maxX),
|
||||
y: clamp(rawNextY, minY, maxY),
|
||||
});
|
||||
},
|
||||
[minHeight, minWidth, viewportPadding]
|
||||
);
|
||||
|
||||
const handleResizeEnd = useCallback((event: PointerEvent<HTMLDivElement>) => {
|
||||
if (interactionRef.current.type !== "resize") return;
|
||||
interactionRef.current.type = null;
|
||||
setIsInteracting(false);
|
||||
event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
}, []);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 스타일 및 Props 생성
|
||||
// ---------------------------------------------------------------------------
|
||||
const contentStyle = useMemo<CSSProperties | undefined>(() => {
|
||||
if (!isActive) return undefined;
|
||||
|
||||
// 초기 렌더링 이후에는 CSS Variables를 통해 위치와 크기를 조절함.
|
||||
// transform: translate(-50%, -50%)를 제거하고 고정된 위치 변수를 사용.
|
||||
return {
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
transform: `translate(-50%, -50%) translate(${position.x}px, ${position.y}px)`,
|
||||
// GPU 가속을 위해 will-change 힌트 제공
|
||||
position: "fixed",
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: "auto",
|
||||
bottom: "auto",
|
||||
width: "var(--dialog-width, 720px)",
|
||||
height: "var(--dialog-height, 520px)",
|
||||
transform: "translate(var(--dialog-x, 0px), var(--dialog-y, 0px))",
|
||||
backgroundColor: "#ffffff", // 완벽한 하얀색으로 고정 (Darkness 제거)
|
||||
border: "1px solid hsl(var(--emerald-200, var(--border)) / 0.4)",
|
||||
boxShadow: "0 20px 50px -12px rgba(0, 0, 0, 0.08)", // 더 투명하고 부드러운 그림자
|
||||
margin: 0,
|
||||
willChange: isInteracting ? "transform, width, height" : "auto",
|
||||
};
|
||||
}, [isActive, isInteracting, position.x, position.y, size.height, size.width]);
|
||||
zIndex: 50,
|
||||
opacity: isInitialized ? 1 : 0,
|
||||
visibility: isInitialized ? "visible" : "hidden",
|
||||
borderRadius: "1.25rem", // 더 둥글고 세련되게
|
||||
overflow: "hidden",
|
||||
// Radix Animation 무력화는 className에서 !important로 처리
|
||||
} as CSSProperties;
|
||||
}, [isActive, isInteracting, isInitialized]);
|
||||
|
||||
const contentClassName = isActive
|
||||
? cn(
|
||||
"sm:max-w-none",
|
||||
// 인터랙션 중에는 모든 트랜지션을 끄고, 텍스트 선택을 막습니다.
|
||||
isInteracting && "transition-none duration-0 select-none"
|
||||
)
|
||||
: "";
|
||||
const contentClassName = cn(
|
||||
"sm:max-w-none !left-0 !top-0 !right-auto !bottom-auto !translate-x-0 !translate-y-0 !animate-none !duration-0",
|
||||
isActive && isInteracting && "select-none shadow-2xl ring-2 ring-emerald-500/20"
|
||||
);
|
||||
|
||||
const dragHandleClassName = isActive && draggable ? "cursor-move select-none touch-none" : "";
|
||||
const resizeHandleClassName = isActive && resizable ? "cursor-se-resize touch-none" : "";
|
||||
const dragHandleClassName = isActive && draggable ? "cursor-move select-none touch-none active:bg-muted/50 transition-colors" : "";
|
||||
const resizeHandleClassName = isActive && resizable ? "cursor-se-resize touch-none hover:bg-emerald-100 transition-colors" : "";
|
||||
|
||||
const dragHandleProps = useMemo<HTMLAttributes<HTMLElement>>(() => {
|
||||
if (!isActive || !draggable) return {};
|
||||
return {
|
||||
onPointerDown: handleDragStart,
|
||||
onPointerMove: handleDragMove,
|
||||
onPointerUp: handleDragEnd,
|
||||
onPointerCancel: handleDragEnd,
|
||||
onPointerMove: handlePointerMove,
|
||||
onPointerUp: handleInteractionEnd,
|
||||
onPointerCancel: handleInteractionEnd,
|
||||
};
|
||||
}, [draggable, handleDragEnd, handleDragMove, handleDragStart, isActive]);
|
||||
}, [draggable, handleDragStart, handleInteractionEnd, handlePointerMove, isActive]);
|
||||
|
||||
const resizeHandleProps = useMemo<HTMLAttributes<HTMLDivElement>>(() => {
|
||||
if (!isActive || !resizable) return {};
|
||||
return {
|
||||
onPointerDown: handleResizeStart,
|
||||
onPointerMove: handleResizeMove,
|
||||
onPointerUp: handleResizeEnd,
|
||||
onPointerCancel: handleResizeEnd,
|
||||
onPointerMove: handlePointerMove,
|
||||
onPointerUp: handleInteractionEnd,
|
||||
onPointerCancel: handleInteractionEnd,
|
||||
};
|
||||
}, [handleResizeEnd, handleResizeMove, handleResizeStart, isActive, resizable]);
|
||||
}, [handleInteractionEnd, handlePointerMove, handleResizeStart, isActive, resizable]);
|
||||
|
||||
return {
|
||||
contentStyle,
|
||||
contentClassName,
|
||||
contentRef,
|
||||
dragHandleProps,
|
||||
dragHandleClassName,
|
||||
resizeHandleProps,
|
||||
|
||||
Reference in New Issue
Block a user