[작업내용] :
- e17af8f4 가 색칠된 외벽선을 selectable:false 로 잠가, 지붕형상 저장 후 일반 상태에서 외벽선 클릭 선택이 막히던 회귀 수정
- useRoofShapeSetting(자동) / useRoofShapePassivitySetting(수동) 저장 시 외벽선 selectable:true 로 복원
- 드래그는 lockMovement(useCanvas 전역), 보조선 클릭 가로채기는 z-order(18abbeb9)로 이미 별도 차단되어 부작용 없음
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- solveRectangleKerab: 4변 타입만으로 힙/마루 재생성(forward·revert 단일 공식)
- nGable=0 우진각·1 Y apex·1 CASE B 케라바·2 맞배 지원, 그 외 기존 maze 폴백
- hip attributes.extended=true 부여 → integrateExtensionLines merge 스킵 → split 4면 정상 할당
- outerLine bbox 기준 sideOf 수정(出幅 offset 좌표 불일치 해소)
- apex depth clamp min(L/2, oppDist) → R3-outside 방지
- detectKerabHipMarks·extendKerabHipsTo45 함수 추출(reclick·revert 45° 통합)
- KERAB-EXTHIP-COORD-CLEAN: orphan ext-hip 좌표 기반 재제거
- useRefFiles: 변환 API FileData 누락 시 에러 메시지 swalFire 안내
- kerab-offset-surgical: skipKerabHips 옵션(케라바 hip t-ratio 재계산 방지)
Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
[작업내용] :
- getDerivedStateFromError 가 errorInfo 를 채우지 않아 첫 fallback 렌더에서 this.state.errorInfo 가 null
- componentStack 접근에 옵셔널 체이닝(?.) 추가 — componentDidCatch 의 setState 후 정상 표시
- ErrorBoundary 가 자기 자신을 크래시시켜 원본 에러를 가리던 이중 에러 해소
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
[작업내용] :
- drawGableRoof 가 처마선 innerLine 생성(roof.innerLines.push) 후 roof 원본 외곽(stroke)을 transparent 로 숨김
- 박공은 split 공용 함수를 거치지 않으므로 drawGableRoof 내에서 직접 처리
- 처마선 삭제 시 roof 기본 stroke:'black' 이 노출되던 문제 해결 (변별/용마루와 동일 동작)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
[작업내용] :
- splitRoofLinesToInnerLines 가 처마변 innerLine화 후 roof 원본 외곽(stroke)을 transparent 로 숨기도록 통합
- 변별/용마루 양 경로 공통 적용 — 처마선 삭제 시 roof 기본 stroke:'black' 이 노출되던 문제 해결
- 용마루 호출부(skeletonBuilder)의 개별 roof.set 제거 (split 함수가 담당)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- applyTypeGableToEavesPattern inward 방향을 변의 폴리곤 안쪽 법선으로 도출
(2회차 리버트 apex 폴리곤 밖 폭주 = roofLine 절삭 불변식 위반 수정)
- reconstructHipRoofRidgeIfComplete 신규: 양쪽 박공이 모두 처마가 되면
X자 세로 마루 스텁을 버리고 힙 4개 절삭(R2/R3) + 가로 마루 1개(R1)로 재구성
- type-eaves 분기 최종 형상에 runKerabRuleCheck 추가
Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
[작업내용] :
- 추녀 연장(drawBaselineToRooflineHelpers) 후 splitRoofLinesToInnerLines 호출 → 처마변을 편집 가능한 innerLine(hip/roofLine)으로 등록
- 처마선 innerLine 이 외곽선을 전담하므로 roof 원본 외곽(stroke) 숨김 처리
- 설계 문서 정정: 대상 브랜치 roofline-edit, §4 리스크1 검증 완료, §9 측정 시점 정정
(추녀 연장 후 종점이 처마변 위에 정합 → split 은 연장 다음에 호출)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
[작업내용] :
- 지붕형상 저장 시 외벽선을 bringToFront(맨 앞) 대신 WALL/ROOF 폴리곤 바로 위 인덱스에 삽입
- offset 0이면 보조선이 외벽선과 같은 좌표에 그려지는데, 외벽선이 맨 위에 있으면
클릭을 가로채(selectable:false라도 evented는 유지됨) 보조선 선택이 불가능했음
- z-order를 폴리곤 < 외벽선 < 보조선·텍스트로 유지해 색 표시와 보조선 클릭을 양립
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
등구배 지붕에서 마루는 양쪽 처마에서 등거리(절반) — 이 불변식을 적용.
기존 ridge-stop 우선/없으면 wall 끝까지 휴리스틱은 방향(가로/세로)에 따라
결과가 들쭉날쭉했다. (start + wallHit) / 2 중점으로 고정, 방향 무관 통일.
wLine(wallBase) 도 vEnd(절반) 파생으로 '-extend' 라인 제거.
Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
[작업내용] :
- canvas.remove()에 배열을 통째로 넘겨 Fabric이 무시(silent no-op)하던 것을 spread로 개별 전달하도록 수정
- addPitchText의 중복 방지가 무력화되어 같은 자리에 경사/출폭 텍스트가 겹겹이 쌓이던 문제 해결
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
골짜기(케라바 패턴)·일반 라인을 독립 핸들러로 분리해 상호 간섭(whack-a-mole) 차단.
일반 라인은 절대 재계산(apex 불변, roofLine-hit 끝점만 재교차) + apex junction degree≥1 임계.
KERAB-RULE-CHECK(R1~R4) forward/revert 검증, RIDGE-DIAG 자연 마루 길이 불변 감시 추가.
REVERT/VALLEY-EXT 끝점 공유 가드로 게이블 hip 확장·길이 0 붕괴 방지.
Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
[작업내용] :
- 지붕형상 저장 후 색칠된 외벽선 선택·드래그 차단, 변별로 설정 재진입 시 선택 복원
- 수동설정 저장 시에도 자동설정과 동일하게 외벽선을 타입별 색상으로 표시
- 두 모달을 진입 시 스냅샷 → 저장 시 커밋 / 저장 없이 닫으면 롤백 구조로 변경
(팝업을 열었다 닫기만 해도 외벽선이 숨겨지고 지붕면이 삭제되던 문제 수정)
- 롤백 시 WALL 폴리곤은 원본 객체를 원래 z-순서에 재삽입
(재생성 시 최상단에 올라가 보조선 클릭을 가로채던 문제 방지)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- canvas.selection: 모듈 기본설정 + 手動配置 비활성 조건에서만 true
- refineModuleSelection: 비모듈 혼합 선택 시 모듈만 재구성, 단일/복수 이동잠금 해제
- commitModuleDragMove: 드래그 완료 후 지붕면 이탈/겹침 검증, 위반 시 시작 위치 복원
- modulesRemove: 복수선택 일괄 삭제 지원, 회로 연결 시 전체 차단
- QContextMenu: 2개 이상 선택 시 컨텍스트 메뉴 차단
Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
- §7 4경로(변별/박공/용마루/한쪽흐름) 외곽 지붕선 처리·편집 가능 여부 종합
- §8 한쪽흐름 경사변 plane≠actual 대응: splitRoofLinesToInnerLines degreeOf 콜백 주입
- §6 YAGNI 박공/한쪽흐름 항목을 범위 편입으로 갱신
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
wLine 이동 후 케라바 변경 시 선택된 target 은 이동 전 wallLine 좌표를 가짐.
wall.baseLines 에서 wallId 매칭으로 이동된 실제 끝점(t1/t2)을 찾아
kLine foot 계산 기준으로 사용 → 이상한 대각선 수정.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
작업내용 :
- 밴드 이중 생성 제거: buildOverlapLine(케라바 토글) + RECALC 중복 → RECALC 전 기존 kerabValleyOverlapLine 제거로 단일 소스 통일
- ladder → 단일 quad 밴드: V1+3변(connector/wall)만 생성, 내부 분할 제거
- 밴드 식별 ov≥2: split 후 V1 edge가 lineName 유실 → overlap-typed 변 2개 이상인 sub-roof를 밴드로 식별
- fold 방식 교체: detour 우회 → V1 전체를 가진 면(F-3)에 OV 외곽경로로 변 연장 흡수. 대각선 제거, 면적 보존 검증 추가
- vExt split(Option A): ridge 교차점에서 vExt를 분할해 RG-2를 할당 그래프에 연결
- QPolygon: ROOF-FACE-DIAG 디버그 라벨 + debugCapture 덤프 추가 (local 가드)
Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
- useSwal alert 분기에 html 옵션 지원 추가 (html 있으면 html, 없으면 text)
- roof-pitch-warning: text → html + \n을 <br>로 치환하여 줄바꿈 렌더링
- ja.json: 構造物 → 架台 용어 수정 + \n 추가
- ko.json: 문구 다듬기 + \n 추가
qpolygon-utils 지붕 생성 구조 / drawRoofByAttribute 내부 구조 /
skeleton-utils 용마루 두 경로 차이 분석. roofline-edit 구현 시 reference.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
drawSkeletonRidgeRoof 경로에서 숨겨진 외곽 지붕선을 변별 경로와 동일한
selectable innerLine으로 생성해 기존 select+우클릭 편집 기능을 재사용하는 설계.
splitRoofLinesToInnerLines 공용 추출 + 정렬버그 수정 방향 포함.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- Adds a new `start:btob` script to `package.json` for launching the Next.js application on port 5060 for the BtoB environment.
- Introduces `startscript-btob.js` as a convenience executable to run the `start:btob` command.
- 「배치면 초기설정」 모달 寸法入力方法 라디오에 '도면 파일 업로드' 옵션 추가
- 선택 시 PDF 파일 업로드 + 읽기 페이지 설정(전체/입면도·평면도 지정) UI 노출
- 保存 클릭 시 /api/gemini/floor-plan 호출 → 외곽선을 캔버스에 반영한 후 기존 저장 흐름 진행
- Gemini File API 업로드 + finally 파일 폐기, 정점/면적 검증, 페이지 힌트 프롬프트 주입
- usePdfImport 훅: mm→canvas 좌표 변환, CCW 정규화, 기존 외곽선 덮어쓰기 confirm 후 QLine/QPolygon 생성
- @google/generative-ai 의존성 추가, GEMINI_MODEL env 4개 환경에 동기화
- 다국어(ja/ko) 메시지 추가, .playwright-mcp/ gitignore
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
[작업내용] :
- 대전제 반영: 케라바 ridge 가 생기는 분기에서 c1·c2 에 붙은 outer hip 2개 제거
· inner hip(junction 너머) 보존
· __removedHipsSnapshot 첨부 → revert 시 hip 2개 자동 복원
- revert 분기에서 hip 스냅샷 + ridge 스냅샷 둘 다 순회 복원하도록 대칭 보강
- 케라바 패턴 생성 라인 strokeWidth 2 → 4 (SK 라인과 동일, 6개소)
Integrates a PreToolUse hook that provides context from the 'graphify' knowledge graph.
When the AI is about to use search commands (e.g., `grep`, `find`, `ripgrep`),
it will be prompted to consult `GRAPH_REPORT.md` if a graph exists, guiding it to
leverage structured knowledge before searching raw files.
- .env.development / .env.production 에 GEMINI_API_KEY 추가 (PDF 평면도 분석 기능용)
- docs/ 에 PDF → Gemini → 캔버스 반영 기능 구현 계획서(html) 추가
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
5개 이미지 API 라우트(upload/cad/map/canvas/estimate-image-copy)의 서버 처리,
클라이언트 콜러(useRefFiles/useImgLoader/useEstimateController), S3 키 레이아웃,
캔버스 캡처 가드 조건과 알려진 거친 모서리를 한 문서에 정리.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- Stack / Scripts / Env / Routes / Source Layout / Deployment / Conventions / Troubleshooting 섹션을 현재 코드 상태(package.json, next.config.mjs, .env.*, ecosystem 파일) 기반으로 작성
- CLAUDE.md (gotcha 위주) 와 역할 분담: README 는 stack·디렉토리·env·배포 같은 기본 정보 담당
- docs/ PDF 와 .agents/skills/ 참조 인덱스 포함
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- README.md 가 사실상 create-next-app 보일러플레이트인데 "authoritative" 라고 안내하던 문구 교체 — 단일 진실 공급원이 CLAUDE.md + docs/ PDF 임을 명시
- graphify-out/ 디렉토리 부재 및 .gitignore 미등록 현실 반영, 28줄 가이드를 5줄 핵심 사용법으로 축소
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
closing edge 의 FP drift 누적(15mm/576mm ≈ 1.5°) 으로 가로/세로 라인이
기울어 보이는 문제. snapNearAxisEdges(angleTolDeg=2) 각도 기반 스냅을
4종 폴리곤(trestle/dormerTrestle/trestlePolygon/moduleSetupSurface) 에 적용.
- QPolygon.initialize name 가드: load/new 대부분 케이스 커버
- handleOuterlinesTest 끝 snap: trestlePolygon 은 makePolygon 후 .set 이라 별도
#1956 (vertical tilt, 2026-04-08) 의 horizontal 형제 케이스.
- .gitignore: .claude/** 차단 + settings.json·md negation 화이트리스트로 전환.
settings.local.json/projects·history·todos·cache 등 머신 전용 파일 누수 차단.
- .claude/settings.json: PreToolUse 훅 case 패턴을 첫 토큰 정확 매칭으로 교체.
*grep* 과매칭(egrep·git grep·grepl) 및 rg 단독 미매칭 문제 해소.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- AGENTS.md alias 한 줄 추가 (Codex 등 타 에이전트 호환)
- .agents/skills 섹션 신설 — Vercel·Next.js 룰북 95개 위치/트리거 안내
- graphify-out 이 gitignore 된 로컬 캐시임 + 빈 상태 부트스트랩 방법 명시
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
gitignore 의 *.md / .claude/ 차단을 풀어 다음 파일을 git 으로 추적.
- /CLAUDE.md, /AGENTS.md (루트 에이전트 가이드)
- .agents/**/*.md (skills 문서 95개)
- .claude/settings.json (Claude Code 프로젝트 설정)
.claude/worktrees/ 는 git worktree 메타이므로 신규 ignore 라인으로 제외.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
graphify 지식 그래프 산출물(AST 캐시·graph.json·HTML·리포트)은 로컬 캐시이며
post-commit hook 으로 자동 갱신되므로 git 추적에서 제외.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
passivityCircuitAllocationRef (useRef) 선언 제거
원인: function component에 ref 전달 시 React warning 발생 (forwardRef 미사용)
PCS 접속함 응답에 추가된 moduleTpCd 필드를 Cross Mix 식별을 위해 프론트 상태 보존 및 getQuotationItem 제출 파라미터까지 흘려보내고, dedupe 키를 (itemId, moduleTpCd) 조합으로 변경.
passivityCircuitAllocationRef (useRef) 선언 제거
원인: function component에 ref 전달 시 React warning 발생 (forwardRef 미사용)
PCS 접속함 응답에 추가된 moduleTpCd 필드를 Cross Mix 식별을 위해 프론트 상태 보존 및 getQuotationItem 제출 파라미터까지 흘려보내고, dedupe 키를 (itemId, moduleTpCd) 조합으로 변경.
Parallel routes render multiple pages in the same layout. Intercepting routes show a different UI when navigating from within your app vs direct URL access. Together they enable modal patterns.
## File Structure
```
app/
├── @modal/ # Parallel route slot
│ ├── default.tsx # Required! Returns null
│ ├── (.)photos/ # Intercepts /photos/*
│ │ └── [id]/
│ │ └── page.tsx # Modal content
│ └── [...]catchall/ # Optional: catch unmatched
│ └── page.tsx
├── photos/
│ └── [id]/
│ └── page.tsx # Full page (direct access)
├── layout.tsx # Renders both children and @modal
└── page.tsx
```
## Step 1: Root Layout with Slot
```tsx
// app/layout.tsx
export default function RootLayout({
children,
modal,
}: {
children: React.ReactNode;
modal: React.ReactNode;
}) {
return (
<html>
<body>
{children}
{modal}
</body>
</html>
);
}
```
## Step 2: Default File (Critical!)
**Every parallel route slot MUST have a `default.tsx`** to prevent 404s on hard navigation.
```tsx
// app/@modal/default.tsx
export default function Default() {
return null;
}
```
Without this file, refreshing any page will 404 because Next.js can't determine what to render in the `@modal` slot.
## Step 3: Intercepting Route (Modal)
The `(.)` prefix intercepts routes at the same level.
```tsx
// app/@modal/(.)photos/[id]/page.tsx
import { Modal } from '@/components/modal';
export default async function PhotoModal({
params
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params;
const photo = await getPhoto(id);
return (
<Modal>
<imgsrc={photo.url}alt={photo.title}/>
</Modal>
);
}
```
## Step 4: Full Page (Direct Access)
```tsx
// app/photos/[id]/page.tsx
export default async function PhotoPage({
params
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params;
const photo = await getPhoto(id);
return (
<divclassName="full-page">
<imgsrc={photo.url}alt={photo.title}/>
<h1>{photo.title}</h1>
</div>
);
}
```
## Step 5: Modal Component with Correct Closing
**Critical: Use `router.back()` to close modals, NOT `router.push()` or `<Link>`.**
```tsx
// components/modal.tsx
'use client';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useRef } from 'react';
export function Modal({ children }: { children: React.ReactNode }) {
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 70 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)
Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.
**Incorrect (Effect Event added as a dependency):**
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
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)
When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.
This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.
**Incorrect:**
```typescript
const someFlag = await getFlag()
if (someFlag && someCondition) {
// ...
}
```
**Correct:**
```typescript
if (someCondition) {
const someFlag = await getFlag()
if (someFlag) {
// ...
}
}
```
This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.
Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).
Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe.
Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code.
When analysis becomes too broad, the cost is real:
- Larger server bundles
- Slower builds
- Worse cold starts
- More memory use
### Import Paths
**Incorrect (the bundler cannot tell what may be imported):**
```ts
const PAGE_MODULES = {
home: './pages/home',
settings: './pages/settings',
} as const
const Page = await import(PAGE_MODULES[pageName])
```
**Correct (use an explicit map of allowed modules):**
```ts
const PAGE_MODULES = {
home: () => import('./pages/home'),
settings: () => import('./pages/settings'),
} as const
const Page = await PAGE_MODULES[pageName]()
```
### File-System Paths
**Incorrect (a 2-value enum still hides the final path from static analysis):**
**Correct (make each final path literal at the callsite):**
```ts
const baseDir =
kind === ContentKind.Blog
? path.join(process.cwd(), 'content/blog')
: path.join(process.cwd(), 'content/docs')
```
In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage.
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 - Next.js 13.5+ (recommended):**
```js
// next.config.js - automatically optimizes barrel imports at build time
// Keep the standard imports - Next.js transforms them to direct imports
import { Check, X, Menu } from 'lucide-react'
// Full TypeScript support, no manual path wrangling
```
This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.
**Correct - Direct imports (non-Next.js projects):**
```tsx
import Button from '@mui/material/Button'
import TextField from '@mui/material/TextField'
// Loads only what you use
```
> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.
These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
// 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.
## 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.
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):**
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.
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
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)
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.
## Defer Non-Critical Work with requestIdleCallback
**Impact: MEDIUM (keeps UI responsive during background tasks)**
Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.
**Incorrect (blocks main thread during user interaction):**
```typescript
function handleSearch(query: string) {
const results = searchItems(query)
setResults(results)
// These block the main thread immediately
analytics.track('search', { query })
saveToRecentSearches(query)
prefetchTopResults(results.slice(0, 3))
}
```
**Correct (defers non-critical work to idle time):**
```typescript
function handleSearch(query: string) {
const results = searchItems(query)
setResults(results)
// Defer non-critical work to idle periods
requestIdleCallback(() => {
analytics.track('search', { query })
})
requestIdleCallback(() => {
saveToRecentSearches(query)
})
requestIdleCallback(() => {
prefetchTopResults(results.slice(0, 3))
})
}
```
**With timeout for required work:**
```typescript
// Ensure analytics fires within 2 seconds even if browser stays busy
## 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)
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.
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 &&<spanclassName="badge">{count}</span>}
</div>
)
}
// When count = 0, renders: <div>0</div>
// When count = 5, renders: <div><spanclass="badge">5</span></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.
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
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 (
<divclassName={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 (
<>
<divid="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.
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.
**Impact: HIGH (reduces load time for critical resources)**
React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.
- **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to
- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server
- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon
- **`preloadModule(href)`**: Fetch an ES module you'll use soon
- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script
- **`preinitModule(href)`**: Fetch and evaluate an ES module
**Example (preconnect to third-party APIs):**
```tsx
import { preconnect, prefetchDNS } from 'react-dom'
export default function App() {
prefetchDNS('https://analytics.example.com')
preconnect('https://api.example.com')
return <main>{/* content */}</main>
}
```
**Example (preload critical fonts and styles):**
```tsx
import { preload, preinit } from 'react-dom'
export default function RootLayout({ children }) {
Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.
- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order
- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order
Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.
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
<pathd="M 10.293847 20.847362 L 30.938472 40.192837"/>
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.
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
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):**
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.
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
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.
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):**
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 <Avatarid={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 <Avatarid={id}/>
})
function Profile({ user, loading }: Props) {
if (loading) return <Skeleton/>
return (
<div>
<UserAvataruser={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.
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.
Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
impactDescription: prevents remount on every render
tags: rerender, components, remount, performance
---
## Don't Define Components Inside Components
**Impact: HIGH (prevents remount on every render)**
Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.
A common reason developers do this is to access parent variables without passing props. Always pass props instead.
Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.
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.
When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.
This pattern also applies to `useEffect` when combining unrelated side effects:
**Incorrect (both effects run when either dependency changes):**
```tsx
useEffect(() => {
analytics.trackPageView(pathname)
document.title = `${pageTitle} | My App`
}, [pathname, pageTitle])
```
**Correct (effects run independently):**
```tsx
useEffect(() => {
analytics.trackPageView(pathname)
}, [pathname])
useEffect(() => {
document.title = `${pageTitle} | My App`
}, [pageTitle])
```
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.
## Use useDeferredValue for Expensive Derived Renders
When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.
**Incorrect (input feels laggy while filtering):**
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.
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.
**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) {
`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.
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.
**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.
**Impact: HIGH (avoids repeated file/network I/O per request)**
When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.
**Incorrect (reads font file on every request):**
```typescript
// app/api/og/route.tsx
import { ImageResponse } from 'next/og'
export async function GET(request: Request) {
// Runs on EVERY request - expensive!
const fontData = await fetch(
new URL('./fonts/Inter.ttf', import.meta.url)
).then(res => res.arrayBuffer())
const logoData = await fetch(
new URL('./images/logo.png', import.meta.url)
).then(res => res.arrayBuffer())
return new ImageResponse(
<divstyle={{fontFamily:'Inter'}}>
<imgsrc={logoData}/>
Hello World
</div>,
{ fonts: [{ name: 'Inter', data: fontData }] }
)
}
```
**Correct (loads once at module initialization):**
```typescript
// app/api/og/route.tsx
import { ImageResponse } from 'next/og'
// Module-level: runs ONCE when module is first imported
export async function processRequest(data: Data) {
const [config, template] = await Promise.all([
configPromise,
templatePromise,
])
return render(template, data, config)
}
```
When to use this pattern:
- Loading fonts for OG image generation
- Loading static logos, icons, or watermarks
- Reading configuration files that don't change at runtime
- Loading email templates or other static templates
- Any static asset that's the same across all requests
When not to use this pattern:
- Assets that vary per request or user
- Files that may change during runtime (use caching with TTL instead)
- Large files that would consume too much memory if kept loaded
- Sensitive data that shouldn't persist in memory
With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.
In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.
impactDescription: prevents concurrency bugs and request data leaks
tags: server, rsc, ssr, concurrency, security, state
---
## Avoid Shared Module State for Request Data
For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response.
Treat module scope on the server as process-wide shared memory, not request-local state.
**Incorrect (request data leaks across concurrent renders):**
```tsx
let currentUser: User | null = null
export default async function Page() {
currentUser = await auth()
return <Dashboard/>
}
async function Dashboard() {
return <div>{currentUser?.name}</div>
}
```
If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`.
**Correct (keep request data local to the render tree):**
```tsx
export default async function Page() {
const user = await auth()
return <Dashboarduser={user}/>
}
function Dashboard({ user }: { user: User | null }) {
return <div>{user?.name}</div>
}
```
Safe exceptions:
- Immutable static assets or config loaded once at module scope
- Shared caches intentionally designed for cross-request reuse and keyed correctly
- Process-wide singletons that do not store request- or user-specific mutable data
For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md).
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.
description: qpolygon-utils.js drawRoofByAttribute (1680-5455, 3777줄) 의 단계별 정밀 분석. 라인 분류→가선분(linesAnalysis) 누적→MAX_ITERATIONS 교점 처리→하단지붕 파생→최종 split. 수정 시 어느 stage 인지 식별 필수.
type: project
---
# drawRoofByAttribute 내부 구조 (후반부 상세)
`src/util/qpolygon-utils.js:1680-5455` 의 정밀 분해. catch-all 함수라 모든 비표준 케이스(요세무네/맨사드/형이동/벽취합/팔작/반절처/케라바 혼합 등)가 여기 모인다.
[stage6 최종 split] roof.lines × innerLinesPoints 분할 → drawHip/RoofLine
↓
roof.innerLines = innerLines (덮어쓰기)
```
`innerLines` 와 `linesAnalysis` 는 **다른 컨테이너**:
- `innerLines`: 실제 캔버스에 그려진 QLine 객체들 (drawHip/Ridge/RoofLine 반환값)
- `linesAnalysis`: 가상 선분 메타데이터 (`{start, end, left, right, type, degree, gableId?, connectCnt?}`) — 아직 캔버스에 안 그려짐, 교점 계산용
`TYPES = { HIP, RIDGE, GABLE_LINE, NEW }` 는 linesAnalysis 내부 enum (canvas 의 `LINE_TYPE.SUBLINE` 과 별개).
## 1. 전반부 (1680-1995) — 이미 파악된 영역
- **1680-1759 형이동 zero-merge**: `wall.baseLines` 중 `planeSize<EPSILON` 인덱스를 prev/next 페어로 모아 같은 vector 라인 끼리 합쳐 `baseLines` 재구성. zero-merge 후엔 `wall.baseLines` 의 중간 라인이 사라진 짧은 형태가 됨.
- **1761 `checkWallPolygon`**: `baseLines` 의 시작점만 모아 만든 임시 QPolygon. inPolygon 판정 전용.
2. prevRoofLine/nextRoofLine 와 currentRoofLine 의 사잇각 vector 로 prevHipPoint/nextHipPoint 산출 (지붕 안쪽 방향 정규화)
3. **HIP 2개 즉시 그림** (`innerLines.push(drawHipLine prev, next)`)
4. 양옆이 모두 EAVES (gable 이 짧을 때): midPoint 에서 양쪽 gable hip 두개 추가 + roofVector 반대 방향으로 10000 길이 가선 그어서 반대편 roof 교점 → `getRidgeDrivePoint` 로 클램프 → `oppLine.attributes.type` 별 offset 보정 (HIPANDGABLE=width, JERKINHEAD=width/2, WALL=0) → **RIDGE 가선분 push**
5. else (gable 길이 충분): `drawRoofLine(gablePoint)` 즉시 그림. 길이 ~0 이면 RIDGE 가선분만 push
### 5-3. eaves 처리 (2701-3143)
eaves 를 `planeSize` 오름차순 sort 후 두 그룹으로 분리:
- **`ridgeEaves`** (2704-2723): 양옆 모두 EAVES + prev/next vector 가 다른 방향 + checkWallPolygon.inPolygon(midPoint+nextVector) — 즉 처마-처마-처마 코너에서 안쪽 들여진 모양
- inPolygon1/2 체크, 밖이면 vector 내 가장 가까운 roof.line 으로 보정
- roof boundary 위에 있는 점이 1개만이면 그 점이 startPoint
- **RIDGE 가선분 push** (중복 체크)
#### 4185-4231 — 양옆 vector 같음 (반절마루 불가) 케이스
`prevLineVector === nextLineVector` (U자): roofLine 직각 방향으로 가선 → 반대편 roof.line 교점 (가장 먼 것) → 시작점은 roofLine 양 끝 중 교점에서 먼 쪽 → **GABLE_LINE 가선분 push** (`degree = prevLine.pitch`, `gableId=baseLines.findIndex(currentLine)`, `connectCnt=0`)
## 6. MAX_ITERATIONS 루프 (4242-4608) — 가선분 교점 처리
`linesAnalysis` 가 비거나 1000회 도달까지 반복:
### 6-1. intersections 수집 (4248-4297)
각 currLine 마다:
- length<EPSILON무시
- GABLE_LINE + connectCnt>1 무시
- 다른 nextLine 과 `lineIntersection(seg-seg)` 시도
- 가장 짧은 distance1 (+ 같은 GABLE_LINE pair gableId 같으면 skip) 의 partner 선택
- distance1==minDistance 일 때 `isSameLine` (left/right 공유) 우선
### 6-2. 단일 교점 보정 (4302-4305)
`intersectPoints` unique 가 1개고 intersections 가 ≥2 → 첫 두개를 서로 partner 로 강제.
### 6-3. for-of 처리 (4310-4597)
intersection 페어마다:
- mutual partner 아니거나 left/right 공통 안 되면 skip
- 각각 drawHip/Ridge 그림 (innerLines.push, alreadyPoints 중복 차단):
description: src/util/qpolygon-utils.js (6507줄) 의 지붕 그리기 3대 진입점(drawGableRoof / drawShedRoof / drawRoofByAttribute) + 하부 헬퍼 + 호출 경로 매핑. 지붕 생성 로직 수정 전 필독.
type: project
---
# qpolygon-utils 지붕 생성 구조 (수정 작업 전 reference)
`src/util/qpolygon-utils.js` 는 6507줄·49개 top-level decl. **지붕 그리기는 이 파일이 단독 책임**(용마루/SK 케이스만 `skeleton-utils.js` 로 분기).
- `analyzeEavesLine(line)` — 처마 분석. horizontal/vertical/diagonal 분류 (tolerance 1°), `roofVector` (안쪽 향한 단위벡터), 매칭되는 roofLine 검색 (offset=0 이면 wall 자기 자신을 fallback)
- `isOverlapLine(curr, check)` — 같은 방향 + 같은 좌표축 + range 겹침
- `analyzeAllEavesLines(lines)` — `forwardLines`(directionVector x>0 또는 y>0) / `backwardLines` 분리, 같은 방향 겹침은 합병
- `calculateIntersection(distance, angleA, angleB)` — `tan` 으로 마루 정점까지의 거리 분배
- `findPloygonLineOverlap(polygon, linePoints)` — line 을 polygon 경계 안쪽으로 클립
- `findInnerRidge(currentLine, roofVector, lines, tolerance=1)` — currentLine 안쪽에 있는 ridge 라인들을 거리 정렬해 ridge1/ridge2 매핑
- `drawRoofPlane(currentLine)` — eaves 1개당 지붕면 1개 빌드
2. `forwardLines.forEach`: backward 매칭 찾고 `calculateIntersection` 으로 각도별 정점 → `findPloygonLineOverlap` 으로 ridge 좌표 클립 → `drawRidgeLine` 호출 → `ridgeLines[]` 추가
3. forward+backward 각각에 `drawRoofPlane` 호출 → 안쪽 ridge 와 inner roof line 매칭, `getSortedOrthogonalPoints` 정렬, 같은 방향이면 `drawRoofLine` 다른 방향이면 `drawHipLine` 호출 → `innerLines[]` 추가
| `drawRoofLine(points, canvas, roof, textMode)` | **`SUBLINE.HIP`** (의도적 재사용) | `#1083E3` | `calcLinePlaneSize` | hip 와 같은 name 으로 분류됨 — 대칭 hip 평균화 후처리에 영향 |
description: src/util/skeleton-utils.js 의 drawSkeletonRidgeRoof(일반) vs drawSkeletonRidgeRoofFromBaseLines(오버 전용) 차이 + skeletonBuilder 전처리 파이프라인 + SK_INPUT_USE_WALL_BASELINE_DIRECT 플래그. 용마루(전체 EAVES) 케이스 수정 전 reference.
type: project
---
# skeleton-utils 용마루 지붕 — 일반 vs 오버 두 경로
`src/util/skeleton-utils.js`. **용마루 지붕(라인 type 이 전부 EAVES)** 케이스 전용. straight-skeleton(`SkeletonBuilder.BuildFromGeoJSON`)으로 용마루/추녀 내부선 생성. 박공/한쪽흐름/변별은 `qpolygon-utils.js` 가 담당 (별도 메모리 참조: [[qpolygon-utils 지붕 생성 구조]]).
skeletonBuilder(roofId, canvas, textMode) // 얇은 래퍼
}
```
실체는 `skeletonBuilder` (:922). 전처리 파이프라인:
1. roof.lines ↔ wall.lines index 매칭으로 `wallLine` id 주입
2. `baseLines = wall.baseLines.filter(planeSize>0)`, `createOrderedBasePoints` 로 roof.points 순서 정렬
3. **45° 대각 확장 계산** (:1011-1066): contactData(baseLine→roofLine 방향벡터) → `maxStep`(전체 꼭짓점 중 min(|dx|,|dy|) 의 max) → centroid 보정 → `changRoofLinePoints` (maxContactDistance=√2·maxStep 확장)
4. 마루이동(`moveFlowLine`/`moveUpDown` ≠ 0) 시 `safeMovedPointsWithFallback` 의 `movedPoints` 로 대체 (:1071-1121)
5. **⚠️ `SK_INPUT_USE_WALL_BASELINE_DIRECT = true` (:36, :1128)** → 위 3·4 결과를 **전부 무시**하고 `orderedBaseLinePoints`(=wall.baseLines corner) 직접 사용. + 평행오버 corner 흡수(DUP_EPS=1.0, COLLINEAR_EPS=50.0, 최대 5패스)
| 공통 | createInnerLinesFromSkeleton, planeSize<1스킵|동일|
**현 시점 진짜 차이**: 플래그(`SK_INPUT_USE_WALL_BASELINE_DIRECT=true`) 때문에 두 함수의 SK 입력 좌표는 거의 같아짐. 실질 차이는 **주변 상태(roof.points/lastPoints 등) 를 mutate 하느냐 보존하느냐**. 오버를 undo/redo 단축수단으로 쓸 때 history snapshot(wall.baseLines/roof.lines) 오염 없이 SK 만 재그리기 위함 (현재 `feature/redo-undo` 브랜치 맥락).
## 5. 수정 시 주의
1. **45° 확장 코드(:1011-1066) 는 dead 입력** — `SK_INPUT_USE_WALL_BASELINE_DIRECT` 끄지 않는 한 결과 미사용. 만지기 전 플래그 확인.
2. `createInnerLinesFromSkeleton` (:1455) 은 두 경로 공유 — 여기 바꾸면 양쪽 영향. `processEavesEdge`(처마) + `processGableEdge`(케라바 후처리) 호출.
"command":"CMD=$(python3 -c \"import json,sys; d=json.load(sys.stdin); print(d.get('tool_input',d).get('command',''))\" 2>/dev/null || true); set -- $CMD; case \"$1\" in grep|egrep|fgrep|rg|ripgrep|find|fd|ack|ag) [ -f graphify-out/graph.json ] && echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files.\"}}' || true ;; esac"
"command":"CMD=$(python3 -c \"import json,sys; d=json.load(sys.stdin); print(d.get('tool_input',d).get('command',''))\" 2>/dev/null || true); set -- $CMD; case \"$1\" in grep|egrep|fgrep|rg|ripgrep|find|fd|ack|ag) [ -f graphify-out/graph.json ] && echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files.\"}}' || true ;; esac"
}
]
}
]
}
}
Some files were not shown because too many files have changed in this diff
Show More
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.