@su-record/vibe 2.8.0 → 2.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1520 @@
1
+ ---
2
+ description: Figma design to code — extract + generate in one step
3
+ argument-hint: "figma-url" ["figma-url-2"] [--standalone]
4
+ ---
5
+
6
+ # /vibe.figma
7
+
8
+ Extract Figma design data and generate production-ready component code, tailored to the project's tech stack.
9
+
10
+ ## Usage
11
+
12
+ ```
13
+ /vibe.figma "url" # Single design → project integrated (default)
14
+ /vibe.figma "mobile-url" "desktop-url" # Responsive — auto-detect viewport from frame width
15
+ /vibe.figma "url" --standalone # Self-contained output folder
16
+ /vibe.figma "url" --component LoginForm # Name the root component
17
+ /vibe.figma --local # Skip extraction, use existing figma-output/
18
+ ```
19
+
20
+ ### Generation Mode
21
+
22
+ | Flag | Behavior |
23
+ |------|----------|
24
+ | _(default)_ | **Project integration.** Use project's design system, existing tokens, component patterns. Place files in project's component directory. |
25
+ | `--standalone` | **Independent folder.** Create self-contained folder with own global styles, tokens, and components. No dependency on project's existing styles. Ready to copy-paste into any project. |
26
+ | _(multi URL)_ | **Responsive mode.** Auto-detected when 2+ URLs provided. Compares designs across viewports and generates responsive code with fluid scaling. |
27
+
28
+ ### Responsive Mode
29
+
30
+ When multiple URLs are provided:
31
+ 1. CLI extracts each URL → `figma-output/` with numbered files (`layers.1.json`, `frame.1.png`, etc.)
32
+ 2. Frame width auto-detects viewport: ≤480px = mobile, ≤1024px = tablet, >1024px = desktop
33
+ 3. `responsive.json` manifest maps each viewport to its files
34
+ 4. Code generation produces a **single component** with breakpoint-aware styles
35
+
36
+ ## File Reading Policy (Mandatory)
37
+
38
+ ### Single design mode
39
+ - **Image first**: ALWAYS read `figma-output/frame.png` with the Read tool before anything else
40
+ - **Then JSON**: Read `figma-output/layers.json` to extract structural data and tokens
41
+
42
+ ### Responsive mode (responsive.json exists)
43
+ - **Manifest first**: Read `figma-output/responsive.json` to identify viewports
44
+ - **All images**: Read each `frame.{N}.png` — compare visual differences across viewports
45
+ - **All layers**: Read each `layers.{N}.json` — extract per-viewport tokens and layout
46
+
47
+ ### Always
48
+ - **Project config**: Read `.claude/vibe/config.json` to determine tech stack
49
+ - **Design context**: Read `.claude/vibe/design-context.json` if it exists (brand, tokens, theme)
50
+ - **Existing code**: Scan project for existing component patterns, theme config, design system
51
+
52
+ ## Context Reset
53
+
54
+ **When this command runs, previous conversation is ignored.**
55
+ - Start fresh from the extracted Figma data
56
+ - Base all decisions on the design image + layer data + project stack
57
+
58
+ ---
59
+
60
+ > **⏱️ Timer**: Call `getCurrentTime` tool at the START. Record the result as `{start_time}`.
61
+
62
+ ## Phase 0: Figma Data Extraction
63
+
64
+ **Skip this phase if `--local` flag is provided and `figma-output/` already exists.**
65
+
66
+ ### 0-1. Token Check
67
+
68
+ Check Figma access token availability:
69
+
70
+ ```
71
+ 1. Read ~/.vibe/config.json → credentials.figma.accessToken
72
+ 2. Fallback: FIGMA_ACCESS_TOKEN env variable
73
+ 3. If neither → ask user: "vibe figma setup <token> 으로 토큰을 설정해주세요"
74
+ ```
75
+
76
+ ### 0-2. Extract via CLI
77
+
78
+ Parse all URLs from the argument. URLs are space-separated, each quoted.
79
+
80
+ **Single URL:**
81
+ ```bash
82
+ npx vibe figma extract "$url"
83
+ ```
84
+
85
+ **Multiple URLs (responsive mode):**
86
+ ```bash
87
+ npx vibe figma extract "$url1" "$url2"
88
+ ```
89
+
90
+ Single URL produces:
91
+ - `figma-output/layers.json` — Figma layer structure with design tokens
92
+ - `figma-output/frame.png` — Rendered frame image (when node-id present in URL)
93
+
94
+ Multiple URLs produce:
95
+ - `figma-output/layers.1.json`, `figma-output/layers.2.json`, ... — Per-viewport layer data
96
+ - `figma-output/frame.1.png`, `figma-output/frame.2.png`, ... — Per-viewport frame images
97
+ - `figma-output/responsive.json` — Viewport manifest with width/label/file mapping
98
+
99
+ ### 0-3. Verify Output & Detect Mode
100
+
101
+ ```
102
+ 1. Check figma-output/responsive.json exists → if yes, enter RESPONSIVE MODE
103
+ 2. If responsive mode:
104
+ - Read responsive.json → verify all listed files exist
105
+ - Confirm at least 2 viewports with different width classes
106
+ 3. If single mode:
107
+ - Check figma-output/layers.json exists → if not, report error and stop
108
+ - Check figma-output/frame.png exists → optional (only with node-id)
109
+ 4. Validate all layers JSON files have children array → warn if empty
110
+ ```
111
+
112
+ ---
113
+
114
+ ## Phase 1: Design Analysis (Image-First)
115
+
116
+ ### Single mode
117
+
118
+ Read `figma-output/frame.png` and analyze:
119
+
120
+ | Aspect | What to Extract |
121
+ |--------|-----------------|
122
+ | Layout | Flex/Grid direction, alignment, wrapping |
123
+ | Components | Visual boundaries (cards, buttons, inputs, modals) |
124
+ | Spacing | Padding, margins, gaps between elements |
125
+ | Typography | Font sizes, weights, line heights, hierarchy |
126
+ | Colors | Background, text, border, accent colors |
127
+ | States | Hover/active/disabled indicators if visible |
128
+ | Responsive hints | Breakpoint indicators, fluid vs fixed widths |
129
+
130
+ ### Responsive mode
131
+
132
+ Read **ALL** frame images and analyze **side-by-side**:
133
+
134
+ | Aspect | What to Compare |
135
+ |--------|-----------------|
136
+ | Layout shift | Which elements reflow? (e.g., horizontal → vertical stack) |
137
+ | Visibility | Which elements hide/show per viewport? |
138
+ | Typography scale | Font size ratio between viewports |
139
+ | Spacing scale | Padding/gap ratio between viewports |
140
+ | Component shape | Does the component change form? (e.g., drawer → sidebar) |
141
+ | Navigation | Does nav change? (e.g., hamburger ↔ full nav bar) |
142
+
143
+ Build a **viewport diff table**:
144
+
145
+ ```
146
+ | Element | Mobile (375px) | Desktop (1440px) | Strategy |
147
+ |---------------|------------------------|------------------------|-------------------|
148
+ | Nav | hamburger + drawer | horizontal bar | component swap |
149
+ | Hero title | 24px | 48px | fluid: clamp() |
150
+ | Card grid | 1 column | 3 columns | grid auto-fit |
151
+ | Sidebar | hidden | visible | display toggle |
152
+ | Body text | 14px | 16px | fluid: clamp() |
153
+ | Padding | 16px | 48px | fluid: clamp() |
154
+ ```
155
+
156
+ ## Phase 2: Layer Data Extraction
157
+
158
+ ### Single mode
159
+
160
+ Read `figma-output/layers.json` and extract:
161
+
162
+ 1. **Component hierarchy** — Map nested layers to component tree
163
+ 2. **Design tokens** — Colors (fill, stroke), font properties, spacing values, border radius, shadows
164
+ 3. **Auto-layout** — Direction, gap, padding (maps directly to flex/grid)
165
+ 4. **Constraints** — Fixed vs fluid sizing
166
+ 5. **Component instances** — Identify reusable patterns
167
+ 6. **Image fills** — Identify layers with `type: "IMAGE"` fills (see Phase 2-A)
168
+
169
+ ### Responsive mode
170
+
171
+ Read **ALL** `layers.{N}.json` files and extract **per-viewport**:
172
+
173
+ 1. **Per-viewport tokens** — Record exact values for each viewport:
174
+ ```
175
+ { "mobile": { "h1": 24, "body": 14, "padding": 16 },
176
+ "desktop": { "h1": 48, "body": 16, "padding": 48 } }
177
+ ```
178
+ 2. **Layout differences** — Auto-layout direction changes (e.g., HORIZONTAL → VERTICAL)
179
+ 3. **Visibility map** — Which layers exist in one viewport but not the other
180
+ 4. **Shared tokens** — Values identical across all viewports (colors, border-radius, shadows are usually shared)
181
+
182
+ ### Phase 2-A: Image Fill Classification
183
+
184
+ Figma에서 이미지는 레이어의 `fills` 배열에 `type: "IMAGE"`로 들어옴. 이를 **용도별로 분류**해야 코드에서 올바른 패턴을 생성할 수 있음.
185
+
186
+ #### 감지 방법
187
+
188
+ `layers.json`에서 아래 패턴을 탐색:
189
+
190
+ ```
191
+ fills: [{ type: "IMAGE", scaleMode: "FILL" | "FIT" | "CROP" | "TILE", imageRef: "..." }]
192
+ ```
193
+
194
+ #### 분류 기준
195
+
196
+ | 판별 조건 | 분류 | 코드 패턴 |
197
+ |----------|------|----------|
198
+ | 레이어가 프레임/섹션의 **직계 배경**이고, 위에 텍스트/UI 요소가 겹침 | **Background Image** | `background-image` + `background-size` |
199
+ | 레이어가 독립적이고, 위에 겹치는 요소 없음 | **Content Image** | `<img>` 또는 `<picture>` |
200
+ | 레이어 이름에 `icon`, `logo`, `avatar` 포함 | **Inline Asset** | `<img>` (작은 크기) |
201
+ | 레이어가 반복 패턴(`scaleMode: "TILE"`) | **Pattern/Texture** | `background-image` + `background-repeat` |
202
+ | 레이어가 전체 프레임을 덮고 opacity < 1 또는 blendMode 적용 | **Overlay Image** | `background-image` + overlay `::before`/`::after` |
203
+
204
+ #### 이미지-텍스트 겹침 판별 (Background vs Content)
205
+
206
+ ```
207
+ frame의 fills에 IMAGE가 있고, children에 TEXT 레이어가 있으면:
208
+ → Background Image (텍스트 아래 깔리는 배경)
209
+
210
+ 독립 레이어의 fills에 IMAGE가 있고, 형제 레이어와 겹치지 않으면:
211
+ → Content Image
212
+ ```
213
+
214
+ #### 이미지 소스 추출
215
+
216
+ - `imageRef` 값으로 Figma API의 이미지 렌더링 사용 (`/images/{fileKey}`)
217
+ - 추출된 이미지는 `figma-output/assets/` 디렉토리에 저장
218
+ - 파일명은 레이어 이름 기반: `hero-bg.png`, `product-photo.jpg`
219
+
220
+ ### Responsive Scaling Calculation
221
+
222
+ Per-viewport 토큰 쌍에서 clamp() 값을 계산. 공식은 **Phase 4-3** 참조.
223
+
224
+ 핵심: Figma 디자인이 2x 스케일(2560px/720px)이므로, 반드시 타겟 해상도(1920px/480px)로 환산 후 clamp를 계산해야 함.
225
+
226
+ **Correction rule**: When image and JSON disagree, **image wins**. The image shows designer intent; JSON may have structural artifacts.
227
+
228
+ ## Phase 3: Project Stack Detection + Mode Resolution
229
+
230
+ ### 3-1. Detect Stack
231
+
232
+ 1. Read `.claude/vibe/config.json` → check `stacks` field
233
+ 2. If no config, detect from project files:
234
+ - `package.json` → React, Vue, Svelte, Angular, etc.
235
+ - `tailwind.config.*` → Tailwind CSS
236
+ - `next.config.*` → Next.js
237
+ - `nuxt.config.*` → Nuxt
238
+ - `*.module.css` → CSS Modules pattern
239
+ - `*.scss` / `sass` in deps → SCSS
240
+ - `styled-components` / `@emotion` in deps → CSS-in-JS
241
+
242
+ ### 3-2. Load Design Context (Design Skill Integration)
243
+
244
+ Read these files **in order** — later sources override earlier ones:
245
+
246
+ 1. **`.claude/vibe/design-context.json`** — brand personality, aesthetic direction, constraints
247
+ - `aesthetic.style` → guides visual weight (minimal vs bold)
248
+ - `aesthetic.colorMood` → warm/cool/vibrant tone for token selection
249
+ - `brand.personality` → preserve brand-expressive elements
250
+ - `constraints.accessibility` → AA or AAA level (affects contrast, focus, ARIA depth)
251
+ - `constraints.devices` → responsive breakpoints priority
252
+ 2. **`.claude/vibe/design-system/{project}/MASTER.md`** — authoritative token definitions
253
+ - If MASTER.md exists: **map Figma tokens to MASTER.md tokens first**, only create new tokens for values with no match
254
+ - If no MASTER.md: generate `figma-tokens.css` as standalone token source
255
+
256
+ **Decision rule**: When Figma token ≈ existing MASTER.md token (within 10% color distance or ±2px spacing), **use the existing token** — do not duplicate.
257
+
258
+ ### 3-3. Load Breakpoints
259
+
260
+ Breakpoints are loaded from multiple sources in priority order:
261
+
262
+ #### Source Priority
263
+
264
+ | Priority | Source | How |
265
+ |----------|--------|-----|
266
+ | 1 | **`~/.vibe/config.json`** | `figma.breakpoints` — user-customized via `vibe figma breakpoints --set` |
267
+ | 2 | **Project CSS/Tailwind** | Grep `tailwind.config.*` → `theme.screens`, or `@media.*min-width` patterns in codebase |
268
+ | 3 | **`responsive.json`** | Breakpoints embedded by CLI extract (from config at extraction time) |
269
+ | 4 | **Defaults** | Built-in values (breakpoint: 1024px, etc.) |
270
+
271
+ #### Default Breakpoints (built-in)
272
+
273
+ Based on game industry responsive storyboard standards:
274
+
275
+ ```
276
+ breakpoint: 1024px ← PC↔Mobile boundary (@media min-width)
277
+ pcTarget: 1920px ← PC main target resolution
278
+ mobilePortrait: 480px ← Mobile portrait max width
279
+ mobileMinimum: 360px ← Mobile minimum supported width
280
+ designPc: 2560px ← Figma PC artboard width (design is 2x scale)
281
+ designMobile: 720px ← Figma Mobile artboard width (design is 2x scale)
282
+ ```
283
+
284
+ #### How to use in code generation
285
+
286
+ ```
287
+ @media breakpoint:
288
+ - Single breakpoint model: @media (min-width: {breakpoint}px)
289
+ - Mobile-first: styles below breakpoint = mobile, above = PC
290
+
291
+ clamp() range:
292
+ - minVw = mobileMinimum (360px) — smallest supported viewport
293
+ - maxVw = pcTarget (1920px) — largest target viewport
294
+ - Values scale linearly between these bounds
295
+
296
+ Design scale factor:
297
+ - PC design at {designPc}px targets {pcTarget}px → scale = pcTarget/designPc
298
+ - Mobile design at {designMobile}px targets {mobilePortrait}px → scale = mobilePortrait/designMobile
299
+ - Apply scale to convert Figma pixel values to target pixel values
300
+ ```
301
+
302
+ #### User customization
303
+
304
+ Users can override any value via CLI:
305
+
306
+ ```bash
307
+ vibe figma breakpoints # Show current values
308
+ vibe figma breakpoints --set breakpoint=768 # Change PC↔Mobile boundary
309
+ vibe figma breakpoints --set mobileMinimum=320 # Change mobile minimum
310
+ ```
311
+
312
+ Stored in `~/.vibe/config.json` → `figma.breakpoints`. Partial overrides merge with defaults.
313
+
314
+ ### 3-4. Resolve Generation Mode
315
+
316
+ ```
317
+ if --standalone flag:
318
+ → create isolated output folder (default: figma-output/generated/)
319
+ → generate self-contained global styles + component styles
320
+ → no dependency on project's existing code
321
+
322
+ default (no flag):
323
+ → scan existing component directories, theme files, token definitions
324
+ → map output to project's conventions (file location, naming, imports)
325
+ → add only NEW tokens that don't exist yet
326
+ ```
327
+
328
+ ---
329
+
330
+ ## Phase 4: Style Architecture
331
+
332
+ ### 4-1. Global Styles File
333
+
334
+ **Token resolution priority** (default mode):
335
+
336
+ 1. **MASTER.md tokens** — if `.claude/vibe/design-system/{project}/MASTER.md` exists, map Figma values to these tokens
337
+ 2. **design-context.json tokens** — if `detectedStack.fonts`, `aesthetic.colorMood` exist, align with these
338
+ 3. **New figma-tokens** — only for values that have no existing match
339
+
340
+ **Standalone mode**: Always generate a self-contained token file (no MASTER.md dependency).
341
+
342
+ #### --standalone mode output:
343
+
344
+ ```
345
+ figma-output/generated/
346
+ ├── styles/
347
+ │ ├── tokens.css ← CSS custom properties (colors, spacing, typography, shadows)
348
+ │ ├── global.css ← Reset + base typography + global layout
349
+ │ └── index.css ← Re-exports tokens.css + global.css
350
+ ├── components/
351
+ │ ├── ComponentName/
352
+ │ │ ├── ComponentName.tsx ← Component code
353
+ │ │ └── ComponentName.module.css (or .styles.ts)
354
+ │ └── ...
355
+ └── index.ts ← Barrel export
356
+ ```
357
+
358
+ #### Default (project integration) mode output:
359
+
360
+ ```
361
+ {project-component-dir}/ ← e.g., src/components/
362
+ ├── ComponentName/
363
+ │ ├── ComponentName.tsx
364
+ │ └── ComponentName.module.css (or .styles.ts)
365
+ └── ...
366
+
367
+ {project-style-dir}/ ← e.g., src/styles/ or extend existing
368
+ └── figma-tokens.css ← Only NEW tokens not already in project
369
+ ```
370
+
371
+ ### 4-2. Token File Format
372
+
373
+ **CSS Custom Properties (default):**
374
+
375
+ ```css
376
+ /* figma-tokens.css — Auto-generated from Figma. Do not edit manually. */
377
+ /* Source: https://www.figma.com/design/{fileKey} */
378
+
379
+ :root {
380
+ /* Colors */
381
+ --figma-primary: #3B82F6;
382
+ --figma-primary-hover: #2563EB;
383
+ --figma-surface: #FFFFFF;
384
+ --figma-surface-secondary: #F9FAFB;
385
+ --figma-text-primary: #111827;
386
+ --figma-text-secondary: #6B7280;
387
+ --figma-border: #E5E7EB;
388
+
389
+ /* Typography */
390
+ --figma-font-family: 'Inter', system-ui, sans-serif;
391
+ --figma-text-xs: 0.75rem; /* 12px */
392
+ --figma-text-sm: 0.875rem; /* 14px */
393
+ --figma-text-base: 1rem; /* 16px */
394
+ --figma-text-lg: 1.125rem; /* 18px */
395
+ --figma-text-xl: 1.25rem; /* 20px */
396
+ --figma-leading-tight: 1.25;
397
+ --figma-leading-normal: 1.5;
398
+
399
+ /* Spacing */
400
+ --figma-space-1: 0.25rem; /* 4px */
401
+ --figma-space-2: 0.5rem; /* 8px */
402
+ --figma-space-3: 0.75rem; /* 12px */
403
+ --figma-space-4: 1rem; /* 16px */
404
+ --figma-space-6: 1.5rem; /* 24px */
405
+ --figma-space-8: 2rem; /* 32px */
406
+
407
+ /* Shadows */
408
+ --figma-shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
409
+ --figma-shadow-md: 0 4px 6px rgba(0, 0, 0, 0.07);
410
+
411
+ /* Border Radius */
412
+ --figma-radius-sm: 0.25rem; /* 4px */
413
+ --figma-radius-md: 0.5rem; /* 8px */
414
+ --figma-radius-lg: 0.75rem; /* 12px */
415
+ --figma-radius-full: 9999px;
416
+ }
417
+ ```
418
+
419
+ **Tailwind extend (if Tailwind detected):**
420
+
421
+ ```js
422
+ // figma.config.ts — merge into tailwind.config.ts theme.extend
423
+ export const figmaTokens = {
424
+ colors: {
425
+ figma: {
426
+ primary: '#3B82F6',
427
+ 'primary-hover': '#2563EB',
428
+ // ...
429
+ },
430
+ },
431
+ spacing: { /* ... */ },
432
+ borderRadius: { /* ... */ },
433
+ };
434
+ ```
435
+
436
+ **SCSS (if `*.scss` or `sass` detected):**
437
+
438
+ ```scss
439
+ // _figma-tokens.scss — Auto-generated from Figma. Do not edit manually.
440
+
441
+ // ── Variables ──
442
+ $figma-primary: #3B82F6;
443
+ $figma-primary-hover: #2563EB;
444
+ $figma-surface: #FFFFFF;
445
+ $figma-text-primary: #111827;
446
+ $figma-text-secondary: #6B7280;
447
+ $figma-border: #E5E7EB;
448
+
449
+ $figma-font-family: 'Inter', system-ui, sans-serif;
450
+ $figma-text-xs: 0.75rem;
451
+ $figma-text-sm: 0.875rem;
452
+ $figma-text-base: 1rem;
453
+ $figma-text-lg: 1.125rem;
454
+ $figma-text-xl: 1.25rem;
455
+
456
+ $figma-space-1: 0.25rem;
457
+ $figma-space-2: 0.5rem;
458
+ $figma-space-4: 1rem;
459
+ $figma-space-6: 1.5rem;
460
+ $figma-space-8: 2rem;
461
+
462
+ $figma-radius-sm: 0.25rem;
463
+ $figma-radius-md: 0.5rem;
464
+ $figma-radius-lg: 0.75rem;
465
+
466
+ $figma-shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
467
+ $figma-shadow-md: 0 4px 6px rgba(0, 0, 0, 0.07);
468
+
469
+ // ── Breakpoints ──
470
+ $figma-bp: 1024px;
471
+ $figma-bp-mobile-min: 360px;
472
+ $figma-bp-pc-target: 1920px;
473
+
474
+ // ── Mixins ──
475
+ @mixin figma-pc {
476
+ @media (min-width: $figma-bp) { @content; }
477
+ }
478
+
479
+ @mixin figma-mobile-only {
480
+ @media (max-width: $figma-bp - 1px) { @content; }
481
+ }
482
+
483
+ // ── Functions ──
484
+ @function figma-fluid($mobile, $desktop, $min-vw: $figma-bp-mobile-min, $max-vw: $figma-bp-pc-target) {
485
+ $slope: ($desktop - $mobile) / ($max-vw - $min-vw);
486
+ $intercept: $mobile - $slope * $min-vw;
487
+ @return clamp(#{$mobile}, #{$intercept} + #{$slope * 100}vw, #{$desktop});
488
+ }
489
+
490
+ // Usage: font-size: figma-fluid(1rem, 2rem);
491
+ ```
492
+
493
+ **SCSS 사용 시 추가 규칙:**
494
+ - CSS custom properties 대신 `$변수` 사용 (프로젝트 컨벤션에 따라 둘 다 가능)
495
+ - `@mixin figma-pc` 로 breakpoint 일관성 유지 — `@media` 직접 사용 금지
496
+ - `figma-fluid()` 함수로 clamp() 계산 자동화 — 수동 계산 금지
497
+ - 파일명: `_figma-tokens.scss` (partial, `_` prefix)
498
+ - `@use 'figma-tokens' as figma;` 로 네임스페이스 import
499
+
500
+ ### 4-3. Responsive Token Format (responsive mode only)
501
+
502
+ When `responsive.json` exists, tokens that **differ across viewports** use `clamp()` for fluid scaling.
503
+ Tokens that are **identical** across viewports remain static.
504
+
505
+ **clamp() range uses breakpoints from Phase 3-3:**
506
+
507
+ ```
508
+ minVw = mobileMinimum (default: 360px)
509
+ maxVw = pcTarget (default: 1920px)
510
+ breakpoint = breakpoint (default: 1024px) ← used for @media
511
+
512
+ Design values must be scaled before clamp:
513
+ PC Figma value × (pcTarget / designPc) = target PC value
514
+ Mobile Figma value × (mobilePortrait / designMobile) = target mobile value
515
+ ```
516
+
517
+ **CSS Custom Properties (responsive):**
518
+
519
+ ```css
520
+ /* figma-tokens.css — Responsive tokens from Figma */
521
+ /* clamp range: {mobileMinimum}px → {pcTarget}px */
522
+ /* Breakpoint: {breakpoint}px (PC↔Mobile) */
523
+ /* Design scale: PC {designPc}→{pcTarget}, Mobile {designMobile}→{mobilePortrait} */
524
+
525
+ :root {
526
+ /* === Shared (same across all viewports) === */
527
+ --figma-primary: #3B82F6;
528
+ --figma-font-family: 'Inter', system-ui, sans-serif;
529
+ --figma-radius-md: 0.5rem;
530
+ --figma-shadow-md: 0 4px 6px rgba(0, 0, 0, 0.07);
531
+
532
+ /* === Fluid Typography (scales with viewport) === */
533
+ /* Figma PC 96px → target 36px, Figma Mobile 48px → target 32px */
534
+ --figma-text-h1: clamp(2rem, {intercept}rem + {slope}vw, 2.25rem);
535
+ --figma-text-body: clamp(0.875rem, {intercept}rem + {slope}vw, 1rem);
536
+
537
+ /* === Fluid Spacing (scales with viewport) === */
538
+ --figma-space-section: clamp(1rem, {intercept}rem + {slope}vw, 3rem);
539
+ --figma-space-content: clamp(0.75rem, {intercept}rem + {slope}vw, 1.5rem);
540
+
541
+ /* === Breakpoint (from config, user-customizable) === */
542
+ --figma-bp: 1024px;
543
+ }
544
+ ```
545
+
546
+ **clamp() calculation formula:**
547
+
548
+ ```
549
+ Step 1: Scale Figma values to target viewport
550
+ targetMobile = figmaMobileValue × (mobilePortrait / designMobile)
551
+ targetPc = figmaPcValue × (pcTarget / designPc)
552
+
553
+ Example (defaults): Figma PC h1=96px, Figma Mobile h1=48px
554
+ targetPc = 96 × (1920 / 2560) = 72px
555
+ targetMobile = 48 × (480 / 720) = 32px
556
+
557
+ Step 2: Calculate clamp()
558
+ minVw = mobileMinimum (360)
559
+ maxVw = pcTarget (1920)
560
+ min = targetMobile, max = targetPc
561
+
562
+ slope = (max - min) / (maxVw - minVw)
563
+ intercept = min - slope * minVw
564
+ → clamp({min/16}rem, {intercept/16}rem + {slope*100}vw, {max/16}rem)
565
+
566
+ Example:
567
+ slope = (72 - 32) / (1920 - 360) = 0.02564
568
+ intercept = 32 - 0.02564 × 360 = 22.77
569
+ → clamp(2rem, 1.423rem + 2.564vw, 4.5rem)
570
+ ```
571
+
572
+ **Tailwind (responsive — if Tailwind detected):**
573
+
574
+ Use Tailwind's responsive prefixes instead of clamp() for layout, clamp() for typography/spacing:
575
+
576
+ ```js
577
+ export const figmaTokens = {
578
+ fontSize: {
579
+ 'figma-h1': ['clamp(1.5rem, 1.076rem + 1.878vw, 3rem)', { lineHeight: '1.2' }],
580
+ 'figma-body': ['clamp(0.875rem, 0.828rem + 0.188vw, 1rem)', { lineHeight: '1.5' }],
581
+ },
582
+ spacing: {
583
+ 'figma-section': 'clamp(1rem, 0.248rem + 3.286vw, 3rem)',
584
+ },
585
+ };
586
+ ```
587
+
588
+ **SCSS (responsive):**
589
+
590
+ ```scss
591
+ // _figma-tokens.scss — figma-fluid() 함수로 자동 계산
592
+ @use 'sass:math';
593
+
594
+ $figma-bp: 1024px;
595
+ $figma-bp-mobile-min: 360px;
596
+ $figma-bp-pc-target: 1920px;
597
+
598
+ @function figma-fluid($mobile, $desktop, $min-vw: $figma-bp-mobile-min, $max-vw: $figma-bp-pc-target) {
599
+ $slope: math.div($desktop - $mobile, $max-vw - $min-vw);
600
+ $intercept: $mobile - $slope * $min-vw;
601
+ @return clamp(#{$mobile}, #{$intercept} + #{$slope * 100}vw, #{$desktop});
602
+ }
603
+
604
+ @mixin figma-pc { @media (min-width: $figma-bp) { @content; } }
605
+
606
+ // Token 사용
607
+ $figma-text-h1: figma-fluid(2rem, 4.5rem);
608
+ $figma-text-body: figma-fluid(0.875rem, 1rem);
609
+ $figma-space-section: figma-fluid(1rem, 3rem);
610
+ ```
611
+
612
+ ```scss
613
+ // Component.module.scss — 사용 예시
614
+ @use 'figma-tokens' as figma;
615
+
616
+ .heroSection {
617
+ padding: figma.$figma-space-section;
618
+ }
619
+
620
+ .heroTitle {
621
+ font-size: figma.$figma-text-h1;
622
+ }
623
+
624
+ .cardGrid {
625
+ display: grid;
626
+ grid-template-columns: 1fr;
627
+
628
+ @include figma.figma-pc {
629
+ grid-template-columns: repeat(3, 1fr);
630
+ }
631
+ }
632
+ ```
633
+
634
+ ### 4-4. Class Naming Rules
635
+
636
+ 클래스 이름은 **역할(role)**을 드러내야 하며, 구조나 스타일 속성을 이름에 넣지 않는다.
637
+
638
+ #### 네이밍 원칙
639
+
640
+ | 원칙 | 좋은 예 | 나쁜 예 |
641
+ |------|--------|--------|
642
+ | **역할 기반** | `.heroSection`, `.productCard`, `.navPrimary` | `.section1`, `.card`, `.nav` |
643
+ | **용도 명시** | `.heroBg`, `.cardThumbnail`, `.avatarImg` | `.bg`, `.img`, `.image1` |
644
+ | **상태 포함** | `.buttonPrimary`, `.inputError` | `.blueButton`, `.redBorder` |
645
+ | **관계 표현** | `.heroTitle`, `.heroDescription` | `.title`, `.text` |
646
+ | **축약 금지** | `.navigationMenu`, `.backgroundImage` | `.navMnu`, `.bgImg` |
647
+
648
+ #### 구체적 규칙
649
+
650
+ ```
651
+ 1. 컴포넌트 루트: 섹션/컴포넌트 이름 그대로
652
+ .loginForm, .heroSection, .productGrid
653
+
654
+ 2. 자식 요소: 부모이름 + 역할
655
+ .heroTitle, .heroDescription, .heroCta
656
+ .loginFormInput, .loginFormSubmit
657
+
658
+ 3. 이미지 클래스: 반드시 용도를 명시
659
+ .heroBg ← 히어로 배경 이미지
660
+ .heroBgOverlay ← 배경 위 오버레이
661
+ .productPhoto ← 상품 사진
662
+ .brandLogo ← 브랜드 로고
663
+
664
+ 4. 상태 변형: variant/state 접미사
665
+ .buttonPrimary, .buttonDisabled
666
+ .cardHighlight, .cardCompact
667
+ ```
668
+
669
+ #### Anti-Patterns
670
+
671
+ ```css
672
+ /* WRONG: 의미 없는 이름 */
673
+ .wrapper { }
674
+ .inner { }
675
+ .box { }
676
+ .item { }
677
+ .text1 { }
678
+
679
+ /* CORRECT: 역할이 드러나는 이름 */
680
+ .eventSection { }
681
+ .eventContent { }
682
+ .rewardCard { }
683
+ .rewardItem { }
684
+ .eventDescription { }
685
+ ```
686
+
687
+ **Component style file MUST reference global tokens:**
688
+
689
+ ```css
690
+ /* LoginForm.module.css */
691
+ .loginForm {
692
+ padding: var(--figma-space-6);
693
+ background: var(--figma-surface);
694
+ border-radius: var(--figma-radius-lg);
695
+ box-shadow: var(--figma-shadow-md);
696
+ }
697
+
698
+ .loginFormTitle {
699
+ font-size: var(--figma-text-xl);
700
+ font-weight: 600;
701
+ color: var(--figma-text-primary);
702
+ line-height: var(--figma-leading-tight);
703
+ }
704
+
705
+ .loginFormSubmit {
706
+ background: var(--figma-primary);
707
+ color: var(--figma-surface);
708
+ border-radius: var(--figma-radius-md);
709
+ padding: var(--figma-space-2) var(--figma-space-4);
710
+ transition: background 150ms ease;
711
+ }
712
+
713
+ .loginFormSubmit:hover {
714
+ background: var(--figma-primary-hover);
715
+ }
716
+ ```
717
+
718
+ ---
719
+
720
+ ## Phase 5: Markup Quality Standards
721
+
722
+ ### 5-1. Semantic HTML (Mandatory)
723
+
724
+ Every element MUST use the most specific semantic tag available. `<div>` is a last resort.
725
+
726
+ | Visual Element | Correct Tag | Wrong |
727
+ |---------------|------------|-------|
728
+ | Page section | `<section>`, `<article>`, `<aside>` | `<div>` |
729
+ | Navigation | `<nav>` | `<div class="nav">` |
730
+ | Page header | `<header>` | `<div class="header">` |
731
+ | Page footer | `<footer>` | `<div class="footer">` |
732
+ | Heading hierarchy | `<h1>`→`<h6>` (sequential, no skips) | `<div class="title">` |
733
+ | Paragraph text | `<p>` | `<div>` or `<span>` |
734
+ | List of items | `<ul>`/`<ol>` + `<li>` | `<div>` repeated |
735
+ | Clickable action | `<button>` | `<div onClick>` |
736
+ | Navigation link | `<a href>` | `<span onClick>` |
737
+ | Form field | `<input>` + `<label>` | `<div contenteditable>` |
738
+ | Image | `<img alt="descriptive">` or `<figure>` + `<figcaption>` | `<div style="background-image">` for content images |
739
+ | Tabular data | `<table>` + `<thead>` + `<tbody>` | `<div>` grid |
740
+ | Time/Date | `<time datetime>` | `<span>` |
741
+ | Emphasized text | `<strong>`, `<em>` | `<span class="bold">` |
742
+ | Grouped fields | `<fieldset>` + `<legend>` | `<div>` |
743
+
744
+ ### 5-2. Accessibility Checklist
745
+
746
+ Every generated component MUST pass:
747
+
748
+ - [ ] All interactive elements keyboard-reachable (tab order)
749
+ - [ ] `<button>` for actions, `<a>` for navigation — never reversed
750
+ - [ ] `<img>` has descriptive `alt` (not "image", not filename)
751
+ - [ ] Form `<input>` linked to `<label>` (via `htmlFor` / `id`)
752
+ - [ ] Color contrast >= 4.5:1 (text), >= 3:1 (large text, UI controls)
753
+ - [ ] Focus indicator visible on all interactive elements
754
+ - [ ] `aria-label` on icon-only buttons
755
+ - [ ] `role` attribute on custom interactive widgets
756
+ - [ ] Heading hierarchy is sequential (no h1 → h3 skip)
757
+ - [ ] `<ul>`/`<ol>` for any visually listed items
758
+
759
+ ### 5-3. Wrapper Elimination (Fragment / template)
760
+
761
+ **불필요한 래핑 태그를 제거**하고 프레임워크가 제공하는 투명 래퍼를 사용:
762
+
763
+ | Stack | 투명 래퍼 | 사용 시점 |
764
+ |-------|----------|----------|
765
+ | React / Next.js | `<>...</>` 또는 `<React.Fragment>` | 형제 요소를 그룹핑할 때 (DOM에 노드 추가 안 함) |
766
+ | Vue / Nuxt | `<template>` (컴포넌트 루트 이외) | `v-if`, `v-for` 로 여러 요소를 조건부 렌더링할 때 |
767
+ | Svelte | `{#if}`, `{#each}` 블록 | 자체적으로 래핑 불필요 |
768
+
769
+ ```tsx
770
+ // WRONG: 불필요한 div 래핑
771
+ <div>
772
+ <Header />
773
+ <Main />
774
+ <Footer />
775
+ </div>
776
+
777
+ // CORRECT: React Fragment
778
+ <>
779
+ <Header />
780
+ <Main />
781
+ <Footer />
782
+ </>
783
+ ```
784
+
785
+ ```vue
786
+ <!-- WRONG: 불필요한 div 래핑 -->
787
+ <div v-if="showGroup">
788
+ <ItemA />
789
+ <ItemB />
790
+ </div>
791
+
792
+ <!-- CORRECT: Vue template (DOM에 렌더링 안 됨) -->
793
+ <template v-if="showGroup">
794
+ <ItemA />
795
+ <ItemB />
796
+ </template>
797
+ ```
798
+
799
+ **규칙**: 래핑 요소에 스타일이나 이벤트가 없으면 → Fragment/template 사용. 스타일이 있으면 → semantic 태그 사용.
800
+
801
+ ### 5-4. Similar UI Consolidation (80% Rule)
802
+
803
+ 디자인에서 **유사도 80% 이상**인 UI 패턴이 발견되면, 별도 컴포넌트로 분리하지 말고 **하나의 컴포넌트 + variant props/slots**으로 통합:
804
+
805
+ ```
806
+ 유사도 판단 기준:
807
+ - 레이아웃 구조 동일
808
+ - 색상/크기/텍스트만 다름
809
+ → 하나의 컴포넌트 + props로 변형
810
+
811
+ - 구조 자체가 다름 (요소 추가/제거, 레이아웃 방향 변경)
812
+ → 별도 컴포넌트
813
+ ```
814
+
815
+ | Stack | 변형 방법 |
816
+ |-------|----------|
817
+ | React | `variant` prop + 조건부 className / style |
818
+ | Vue | `variant` prop + `<slot>` for 커스텀 영역 |
819
+ | Svelte | `variant` prop + `<slot>` |
820
+ | React Native | `variant` prop + StyleSheet 조건 선택 |
821
+
822
+ ```tsx
823
+ // React — 하나의 Card 컴포넌트가 3가지 변형 처리
824
+ interface CardProps {
825
+ variant: 'default' | 'highlight' | 'compact';
826
+ title: string;
827
+ children: React.ReactNode;
828
+ }
829
+
830
+ export function Card({ variant, title, children }: CardProps): JSX.Element {
831
+ return (
832
+ <article className={styles[variant]}>
833
+ <h3 className={styles.title}>{title}</h3>
834
+ {children}
835
+ </article>
836
+ );
837
+ }
838
+ ```
839
+
840
+ ```vue
841
+ <!-- Vue — slot으로 커스텀 영역 제공 -->
842
+ <template>
843
+ <article :class="$style[variant]">
844
+ <h3 :class="$style.title">{{ title }}</h3>
845
+ <slot />
846
+ </article>
847
+ </template>
848
+
849
+ <script setup lang="ts">
850
+ defineProps<{ variant: 'default' | 'highlight' | 'compact'; title: string }>();
851
+ </script>
852
+ ```
853
+
854
+ ### 5-5. Component Structure Rules
855
+
856
+ ```
857
+ Max nesting depth: 3 levels (container > group > element)
858
+ Max component length: 50 lines
859
+ Max props: 5 per component
860
+ ```
861
+
862
+ **Split triggers:**
863
+
864
+ | Signal | Action |
865
+ |--------|--------|
866
+ | Component > 50 lines | Split into sub-components |
867
+ | Repeated visual pattern (2+ times) | Extract shared component |
868
+ | **Similar pattern (80%+ match)** | **Single component + variant prop** |
869
+ | Distinct visual boundary (card, modal, form) | Own component + own style file |
870
+ | 3+ related props | Group into object prop or extract sub-component |
871
+
872
+ ### 5-6. Markup Anti-Patterns (NEVER Generate)
873
+
874
+ ```tsx
875
+ // WRONG: div soup
876
+ <div className="card">
877
+ <div className="card-header">
878
+ <div className="title">Login</div>
879
+ </div>
880
+ <div className="card-body">
881
+ <div className="input-group">
882
+ <div className="label">Email</div>
883
+ <div className="input"><input /></div>
884
+ </div>
885
+ </div>
886
+ </div>
887
+
888
+ // CORRECT: semantic markup
889
+ <article className={styles.card}>
890
+ <header className={styles.header}>
891
+ <h2 className={styles.title}>Login</h2>
892
+ </header>
893
+ <form className={styles.body}>
894
+ <fieldset className={styles.fieldGroup}>
895
+ <label htmlFor="email" className={styles.label}>Email</label>
896
+ <input id="email" type="email" className={styles.input} />
897
+ </fieldset>
898
+ </form>
899
+ </article>
900
+ ```
901
+
902
+ ```tsx
903
+ // WRONG: 불필요한 래핑
904
+ <div>
905
+ <ComponentA />
906
+ <ComponentB />
907
+ </div>
908
+
909
+ // CORRECT: Fragment
910
+ <>
911
+ <ComponentA />
912
+ <ComponentB />
913
+ </>
914
+ ```
915
+
916
+ ```tsx
917
+ // WRONG: 유사한 UI를 별도 컴포넌트로
918
+ <DefaultCard /> // 구조 동일, 색상만 다름
919
+ <HighlightCard /> // 구조 동일, 색상만 다름
920
+
921
+ // CORRECT: 단일 컴포넌트 + variant
922
+ <Card variant="default" />
923
+ <Card variant="highlight" />
924
+ ```
925
+
926
+ ---
927
+
928
+ ## Phase 6: Code Generation
929
+
930
+ ### 6-0. Apply Design Context (from Phase 3-2)
931
+
932
+ If `design-context.json` was loaded, apply these rules to ALL generated code:
933
+
934
+ | Context Field | Effect on Code Generation |
935
+ |---------------|--------------------------|
936
+ | `constraints.accessibility = "AAA"` | Use `aria-describedby` on all form fields, `prefers-reduced-motion` media query, `prefers-contrast` support |
937
+ | `constraints.devices = ["mobile"]` | Mobile-only layout, no desktop breakpoints, touch target ≥ 44px |
938
+ | `constraints.devices = ["mobile","desktop"]` | Mobile-first with `md:` breakpoint |
939
+ | `aesthetic.style = "minimal"` | Reduce visual weight — fewer shadows, thinner borders, more whitespace |
940
+ | `aesthetic.style = "bold"` | Stronger shadows, thicker borders, larger typography scale |
941
+ | `brand.personality` | Preserve brand-unique visual patterns (do NOT distill these away) |
942
+ | `detectedStack.fonts` | Use project's existing font stack instead of Figma's font family |
943
+
944
+ ### 6-1. Stack-Specific Rules
945
+
946
+ Generate code following these rules per stack:
947
+
948
+ #### React / Next.js + TypeScript
949
+
950
+ ```
951
+ - Functional components with explicit return types
952
+ - Props interface defined above component
953
+ - Named exports (not default)
954
+ - <></> Fragment for sibling grouping (no unnecessary wrapper div)
955
+ - CSS Modules: import styles from './Component.module.css'
956
+ - Tailwind: classes in JSX, extract repeated patterns to @apply
957
+ - Responsive: mobile-first breakpoints
958
+ - Variant pattern: discriminated union props for similar UI
959
+ - useMemo/useCallback only when measurably needed (not by default)
960
+ - Next.js: use 'use client' only when client interactivity needed
961
+ - Next.js: Image component for images, Link for navigation
962
+ ```
963
+
964
+ #### Vue 3 / Nuxt
965
+
966
+ ```
967
+ - <script setup lang="ts"> composition API
968
+ - defineProps with TypeScript interface (with defaults via withDefaults)
969
+ - <template> for invisible grouping (v-if, v-for on multiple elements)
970
+ - <style scoped> (or <style module>) with CSS custom property references
971
+ - v-bind in <style> for dynamic values: color: v-bind(themeColor)
972
+ - <slot> + named slots for composable variant patterns
973
+ - <Teleport> for modals/overlays
974
+ - Or Tailwind classes in template
975
+ - Nuxt: <NuxtLink> for navigation, <NuxtImg> for images
976
+ - Nuxt: definePageMeta for page-level config
977
+ - computed() for derived state (not methods for template expressions)
978
+ ```
979
+
980
+ #### Svelte
981
+
982
+ ```
983
+ - TypeScript in <script lang="ts">
984
+ - Export let for props with types
985
+ - {#if}/{#each}/{#await} blocks — inherently wrapper-free
986
+ - <slot> for composable patterns
987
+ - <style> block with CSS custom property references
988
+ - Or Tailwind classes in markup
989
+ - Reactive declarations ($:) for derived values
990
+ - transition: directive for animations
991
+ ```
992
+
993
+ #### SCSS (any framework with SCSS)
994
+
995
+ ```
996
+ - @use 'figma-tokens' as figma — namespaced import (not @import)
997
+ - $변수 for tokens: figma.$figma-primary, figma.$figma-space-4
998
+ - @include figma.figma-pc { } for breakpoint — @media 직접 사용 금지
999
+ - figma-fluid($mobile, $desktop) for responsive values — 수동 clamp() 금지
1000
+ - Nesting max 3 levels: .section { .title { .icon { } } } ← 한계
1001
+ - & for BEM-like modifiers: &--active, &__title
1002
+ - @each for variant generation from map
1003
+ - Partials: _figma-tokens.scss, _figma-mixins.scss
1004
+ - Vue: <style lang="scss" scoped> with @use
1005
+ ```
1006
+
1007
+ ```scss
1008
+ // Component usage example
1009
+ @use 'figma-tokens' as figma;
1010
+
1011
+ .heroSection {
1012
+ position: relative;
1013
+ padding: figma.figma-fluid(1rem, 3rem);
1014
+
1015
+ &Title {
1016
+ font-size: figma.figma-fluid(1.5rem, 3rem);
1017
+ color: figma.$figma-text-primary;
1018
+ }
1019
+
1020
+ &Cta {
1021
+ background: figma.$figma-primary;
1022
+ border-radius: figma.$figma-radius-md;
1023
+
1024
+ &:hover { background: figma.$figma-primary-hover; }
1025
+ }
1026
+ }
1027
+
1028
+ .cardGrid {
1029
+ display: grid;
1030
+ grid-template-columns: 1fr;
1031
+
1032
+ @include figma.figma-pc {
1033
+ grid-template-columns: repeat(3, 1fr);
1034
+ }
1035
+ }
1036
+ ```
1037
+
1038
+ #### React Native
1039
+
1040
+ ```
1041
+ - StyleSheet.create at bottom of file
1042
+ - <></> Fragment for sibling grouping
1043
+ - Dimensions-aware responsive layout
1044
+ - Platform.select / Platform.OS for platform-specific styles
1045
+ - Extract shared style constants to styles/tokens.ts
1046
+ ```
1047
+
1048
+ #### Flutter (Dart)
1049
+
1050
+ ```
1051
+ - StatelessWidget or StatefulWidget as appropriate
1052
+ - Theme.of(context) for design tokens
1053
+ - Extract shared values to lib/theme/figma_tokens.dart
1054
+ - Proper widget composition
1055
+ ```
1056
+
1057
+ ### 6-2. Image Code Patterns (from Phase 2-A classification)
1058
+
1059
+ Phase 2-A에서 분류된 이미지 유형별 코드 생성 규칙:
1060
+
1061
+ #### Background Image Class Separation (핵심 원칙)
1062
+
1063
+ 배경 이미지 관련 요소는 **용도별로 별도 클래스**로 분리한다. 레이아웃과 이미지를 합치지 않는다.
1064
+
1065
+ ##### 별도 클래스로 분리해야 하는 유형
1066
+
1067
+ | 유형 | 클래스 예시 | 분리 이유 |
1068
+ |------|-----------|----------|
1069
+ | **섹션 전면 배경** | `.heroBg`, `.eventBg`, `.rewardsBg` | 이벤트 기간/시즌별 이미지 교체 |
1070
+ | **오버레이** | `.heroBgOverlay`, `.eventBgOverlay` | 투명도/그라데이션 독립 조절 |
1071
+ | **패턴/텍스처** | `.sectionPattern`, `.headerTexture` | `background-repeat`/`size` 별도 제어 |
1072
+ | **파티클/장식 효과** | `.heroParticle`, `.sparkleEffect` | 애니메이션 on/off, 성능 이슈 시 제거 |
1073
+ | **캐릭터/일러스트** | `.heroCharacter`, `.eventIllust` | 콜라보/캐릭터별 교체, position 조절 |
1074
+ | **그라데이션** | `.sectionGradient`, `.fadeBottom` | 테마별 색상 변경 |
1075
+ | **비디오 포스터** | `.videoPoster` | 비디오 로드 전 폴백, JS에서 교체 |
1076
+
1077
+ ##### Multi-Layer Pattern (섹션 배경 기본 구조)
1078
+
1079
+ Figma에서 배경 이미지가 있는 섹션은 다음 레이어 구조로 생성:
1080
+
1081
+ ```
1082
+ .{section}Section ← 레이아웃 (position, size, padding, overflow)
1083
+ .{section}Bg ← 배경 이미지 (URL, size, position) — z-index: 0
1084
+ .{section}BgOverlay ← 오버레이 (gradient, opacity) — z-index: 1
1085
+ .{section}Character ← 캐릭터/일러스트 (선택) — z-index: 2
1086
+ .{section}Pattern ← 패턴/텍스처 (선택) — z-index: 1
1087
+ .{section}Content ← 텍스트/버튼/UI — z-index: 최상위
1088
+ ```
1089
+
1090
+ ```tsx
1091
+ // 실제 마크업 예시 — 게임 이벤트 히어로 섹션
1092
+ <section className={styles.heroSection}>
1093
+ <div className={styles.heroBg} />
1094
+ <div className={styles.heroBgOverlay} />
1095
+ <div className={styles.heroCharacter} />
1096
+ <div className={styles.heroContent}>
1097
+ <h1 className={styles.heroTitle}>Stellar Blade × PUBG</h1>
1098
+ <p className={styles.heroDescription}>기간한정 콜라보 이벤트</p>
1099
+ <a href="#rewards" className={styles.heroCta}>보상 확인하기</a>
1100
+ </div>
1101
+ </section>
1102
+ ```
1103
+
1104
+ ```css
1105
+ /* heroSection.module.css */
1106
+ .heroSection { position: relative; overflow: hidden; min-height: 100vh; }
1107
+
1108
+ .heroBg {
1109
+ position: absolute; inset: 0; z-index: 0;
1110
+ background-image: url('/assets/hero-bg.webp');
1111
+ background-size: cover;
1112
+ background-position: center;
1113
+ }
1114
+
1115
+ .heroBgOverlay {
1116
+ position: absolute; inset: 0; z-index: 1;
1117
+ background: linear-gradient(to bottom, rgba(0,0,0,0.3), rgba(0,0,0,0.7));
1118
+ }
1119
+
1120
+ .heroCharacter {
1121
+ position: absolute; bottom: 0; right: 5%; z-index: 2;
1122
+ width: 40%; height: 80%;
1123
+ background-image: url('/assets/hero-character.webp');
1124
+ background-size: contain;
1125
+ background-position: bottom center;
1126
+ background-repeat: no-repeat;
1127
+ }
1128
+
1129
+ .heroContent { position: relative; z-index: 3; }
1130
+ ```
1131
+
1132
+ **모든 배경 관련 이미지가 독립 클래스**이므로:
1133
+ - JS에서 `.heroBg`만 교체하면 배경만 바뀜
1134
+ - `.heroCharacter`만 교체하면 캐릭터만 바뀜
1135
+ - `.heroBgOverlay`의 opacity를 조절하면 텍스트 가독성만 조절 가능
1136
+ - 성능 이슈 시 `.heroParticle`만 `display: none`
1137
+
1138
+ #### Responsive Background Image (반응형 배경 — PC/Mobile 분기)
1139
+
1140
+ ```css
1141
+ /* 배경 이미지 클래스 안에서만 반응형 처리 */
1142
+ .heroBg {
1143
+ background-image: url('/assets/hero-mobile.webp');
1144
+ background-size: cover;
1145
+ background-position: center;
1146
+ position: absolute;
1147
+ inset: 0;
1148
+ z-index: 0;
1149
+ }
1150
+
1151
+ @media (min-width: 1024px) { /* {breakpoint}px */
1152
+ .heroBg {
1153
+ background-image: url('/assets/hero-pc.webp');
1154
+ }
1155
+ }
1156
+ ```
1157
+
1158
+ **섹션별 배경 이미지가 여러 개인 경우** — 각각 고유 클래스:
1159
+
1160
+ ```css
1161
+ .heroBg { background-image: url('/assets/hero-bg.webp'); /* ... */ }
1162
+ .eventBg { background-image: url('/assets/event-bg.webp'); /* ... */ }
1163
+ .rewardsBg { background-image: url('/assets/rewards-bg.webp'); /* ... */ }
1164
+ ```
1165
+
1166
+ **Figma 오버레이 감지**: 레이어에 `opacity < 1` 또는 `fills`에 반투명 색상이 IMAGE 위에 있으면 → `{section}BgOverlay` 클래스로 처리.
1167
+
1168
+ #### Content Image (독립적인 이미지 콘텐츠)
1169
+
1170
+ ```tsx
1171
+ // React / Next.js
1172
+ <img
1173
+ src="/assets/product.webp"
1174
+ alt="상품 설명" // Figma 레이어 이름 기반
1175
+ width={600} // Figma 레이어 width (scaled)
1176
+ height={400} // Figma 레이어 height (scaled)
1177
+ loading="lazy" // 뷰포트 밖이면 lazy
1178
+ />
1179
+
1180
+ // Next.js — Image 컴포넌트 우선
1181
+ import Image from 'next/image';
1182
+ <Image
1183
+ src="/assets/product.webp"
1184
+ alt="상품 설명"
1185
+ width={600}
1186
+ height={400}
1187
+ priority={false} // hero 이미지만 priority={true}
1188
+ />
1189
+ ```
1190
+
1191
+ ```vue
1192
+ <!-- Nuxt — NuxtImg 우선 -->
1193
+ <NuxtImg
1194
+ src="/assets/product.webp"
1195
+ alt="상품 설명"
1196
+ width="600"
1197
+ height="400"
1198
+ loading="lazy"
1199
+ />
1200
+ ```
1201
+
1202
+ #### Responsive Content Image (뷰포트별 다른 이미지)
1203
+
1204
+ ```html
1205
+ <picture>
1206
+ <source media="(min-width: 1024px)" srcset="/assets/hero-pc.webp" />
1207
+ <img src="/assets/hero-mobile.webp" alt="히어로 이미지" loading="eager" />
1208
+ </picture>
1209
+ ```
1210
+
1211
+ #### 이미지 공통 규칙
1212
+
1213
+ | 규칙 | 설명 |
1214
+ |------|------|
1215
+ | **format** | `.webp` 우선 (fallback: `.png`/`.jpg`) |
1216
+ | **alt** | Figma 레이어 이름에서 파생, 장식 이미지는 `alt=""` + `aria-hidden="true"` |
1217
+ | **width/height** | 항상 명시 (CLS 방지), Figma 레이어 크기를 스케일 팩터 적용 후 사용 |
1218
+ | **loading** | 뷰포트 상단(hero, header) → `eager`, 나머지 → `lazy` |
1219
+ | **object-fit** | `cover` (배경/히어로), `contain` (로고/아이콘), `fill` 사용 금지 |
1220
+ | **반응형 크기** | Content image는 `max-width: 100%; height: auto;` 기본 |
1221
+ | **배경 이미지 + 텍스트** | 반드시 오버레이(`::before` 또는 gradient)로 텍스트 가독성 확보 |
1222
+ | **장식 패턴** | `background-repeat: repeat` + `background-size` 조절 |
1223
+
1224
+ #### Anti-Patterns
1225
+
1226
+ ```tsx
1227
+ // WRONG: 레이아웃 클래스에 background-image를 합침
1228
+ <section className={styles.hero} /> /* .hero에 bg-image + padding + flex 등 다 섞임 */
1229
+
1230
+ // CORRECT: 배경 이미지는 별도 클래스
1231
+ <section className={styles.heroSection}>
1232
+ <div className={styles.heroBg} />
1233
+ <div className={styles.heroContent}>...</div>
1234
+ </section>
1235
+ ```
1236
+
1237
+ ```tsx
1238
+ // WRONG: inline style로 배경 이미지
1239
+ <div style={{ backgroundImage: `url(${bg})` }} />
1240
+
1241
+ // CORRECT: 전용 클래스에 이미지 URL
1242
+ <div className={styles.heroBg} />
1243
+ /* JS 동적 교체 시: element.style.backgroundImage = url(...) on .heroBg만 */
1244
+ ```
1245
+
1246
+ ```css
1247
+ /* WRONG: 배경 + 텍스트, 오버레이 없음 */
1248
+ .hero { background-image: url(...); color: white; }
1249
+
1250
+ /* CORRECT: 3-layer 분리 (bg / overlay / content) */
1251
+ .heroSection { position: relative; }
1252
+ .heroBg { background-image: url(...); position: absolute; inset: 0; z-index: 0; }
1253
+ .heroBgOverlay { position: absolute; inset: 0; background: rgba(0,0,0,0.5); z-index: 1; }
1254
+ .heroContent { position: relative; z-index: 2; color: white; }
1255
+ ```
1256
+
1257
+ ```css
1258
+ /* WRONG: 의미 없는 이름 */
1259
+ .bg { }
1260
+ .bgImg { }
1261
+ .overlay { }
1262
+
1263
+ /* CORRECT: 섹션별 명시적 이름 */
1264
+ .heroBg { }
1265
+ .heroBgOverlay { }
1266
+ .eventBg { }
1267
+ .rewardsBg { }
1268
+ ```
1269
+
1270
+ ### 6-3. Responsive Code Generation (responsive mode only)
1271
+
1272
+ When `responsive.json` exists, apply these rules on top of stack-specific rules:
1273
+
1274
+ #### Principle: Fluid First, Breakpoint Second
1275
+
1276
+ ```
1277
+ 1. Typography & Spacing → clamp() fluid tokens (no breakpoints needed)
1278
+ 2. Layout direction changes → @media at project breakpoint (flex-direction, grid-template)
1279
+ 3. Visibility toggles → @media at project breakpoint (display: none/block)
1280
+ 4. Component swaps → conditional render with useMediaQuery or CSS
1281
+ ```
1282
+
1283
+ **Breakpoint selection**: Use `{breakpoints}` from Phase 3-3. Pick the breakpoint closest to where the layout structurally changes between Figma viewports. For example:
1284
+ - Figma mobile=375px, desktop=1440px → use project's `md` (typically 768px) as primary breakpoint
1285
+ - If project has `tablet: 1024px` → use that instead
1286
+ - If 3 viewports (mobile/tablet/desktop) → use 2 breakpoints (e.g., `sm` and `lg`)
1287
+
1288
+ #### CSS Modules (responsive example)
1289
+
1290
+ ```css
1291
+ /* Component.module.css */
1292
+ /* Breakpoints from project: {breakpoints} */
1293
+
1294
+ .container {
1295
+ display: flex;
1296
+ flex-direction: column; /* mobile-first */
1297
+ gap: var(--figma-space-content); /* fluid: clamp() */
1298
+ padding: var(--figma-space-section); /* fluid: clamp() */
1299
+ }
1300
+
1301
+ .title {
1302
+ font-size: var(--figma-text-h1); /* fluid: clamp() */
1303
+ line-height: 1.2;
1304
+ }
1305
+
1306
+ .cardGrid {
1307
+ display: grid;
1308
+ grid-template-columns: 1fr; /* mobile: single column */
1309
+ gap: var(--figma-space-content);
1310
+ }
1311
+
1312
+ /* Layout breakpoint — use project's breakpoint, NOT hardcoded */
1313
+ @media (min-width: 1024px) { /* {breakpoint}px from Phase 3-3 */ /* or project's md value */
1314
+ .container {
1315
+ flex-direction: row;
1316
+ }
1317
+ .cardGrid {
1318
+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
1319
+ }
1320
+ }
1321
+
1322
+ /* Visibility toggle — same breakpoint */
1323
+ .mobileOnly { display: block; }
1324
+ .desktopOnly { display: none; }
1325
+
1326
+ @media (min-width: 1024px) { /* {breakpoint}px from Phase 3-3 */
1327
+ .mobileOnly { display: none; }
1328
+ .desktopOnly { display: block; }
1329
+ }
1330
+ ```
1331
+
1332
+ #### Tailwind (responsive example)
1333
+
1334
+ Use project's Tailwind screen prefixes (e.g., `sm:`, `md:`, `lg:`) — NOT hardcoded pixel values.
1335
+
1336
+ ```tsx
1337
+ {/* Uses project's Tailwind breakpoints — md: maps to project's screens.md */}
1338
+ <div className="flex flex-col md:flex-row gap-[--figma-space-content] p-[--figma-space-section]">
1339
+ <h1 className="text-[length:--figma-text-h1] leading-tight">Title</h1>
1340
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-[--figma-space-content]">
1341
+ {/* cards */}
1342
+ </div>
1343
+ <nav className="md:hidden">Mobile Nav</nav>
1344
+ <nav className="hidden md:flex">Desktop Nav</nav>
1345
+ </div>
1346
+ ```
1347
+
1348
+ #### Anti-Patterns (NEVER do in responsive mode)
1349
+
1350
+ | Wrong | Right |
1351
+ |-------|-------|
1352
+ | Separate mobile/desktop component files | Single component with responsive CSS |
1353
+ | `@media` for font-size/spacing | `clamp()` via fluid tokens |
1354
+ | Hardcoded `@media (min-width: 768px)` | Use project breakpoint from Phase 3-3 or Tailwind prefix |
1355
+ | Pixel values in responsive styles | Token variables everywhere |
1356
+ | Duplicated markup for each viewport | Visibility toggles or conditional sections |
1357
+ | `window.innerWidth` checks in JS | CSS-only responsive (`@media`, `clamp()`, `auto-fit`) |
1358
+ | Inventing new breakpoints | Use project's existing breakpoint system |
1359
+
1360
+ ---
1361
+
1362
+ ## Phase 7: Token Mapping (default mode)
1363
+
1364
+ **Only in default (project integration) mode.** Map extracted Figma tokens to the project's existing token system.
1365
+
1366
+ ### Token Source Priority
1367
+
1368
+ ```
1369
+ 1. MASTER.md (.claude/vibe/design-system/{project}/MASTER.md) ← 최우선
1370
+ 2. design-context.json (.claude/vibe/design-context.json) ← 보조
1371
+ 3. Project theme files (tailwind.config, CSS variables, etc.) ← 폴백
1372
+ 4. Generate new figma-tokens ← 마지막 수단
1373
+ ```
1374
+
1375
+ ### Mapping Rules
1376
+
1377
+ 1. **MASTER.md exists** → authoritative token source
1378
+ - Figma color ≈ MASTER.md color (ΔE < 5) → use MASTER.md token name
1379
+ - Figma spacing ≈ MASTER.md spacing (±2px) → use MASTER.md token name
1380
+ - Figma font ≈ MASTER.md font → use MASTER.md token name
1381
+ - Unmatched Figma values → add to `figma-tokens.css` as supplementary tokens
1382
+
1383
+ 2. **No MASTER.md, but design-context.json exists** →
1384
+ - Use `detectedStack` info for naming convention
1385
+ - Use `aesthetic.colorMood` to validate token naming (e.g., warm palette → warm- prefix)
1386
+ - Generate `figma-tokens.css` grouped by category
1387
+
1388
+ 3. **No design system at all** →
1389
+ - Generate `figma-tokens.css` (or Tailwind extend)
1390
+ - Group tokens by category (color, typography, spacing, shadow)
1391
+
1392
+ ### Output Mapping Comment
1393
+
1394
+ Always output token mapping as a comment block at the top of the token file:
1395
+
1396
+ ```
1397
+ /* Figma Token Mapping:
1398
+ * Figma "Primary/Default" → var(--figma-primary) = #3B82F6
1399
+ * ✅ Matched: var(--color-blue-500) from MASTER.md
1400
+ * Figma "Text/Body" → var(--figma-text-base) = 1rem / 1.5
1401
+ * ✅ Matched: var(--text-base) from MASTER.md
1402
+ * Figma "Accent/Glow" → var(--figma-accent-glow) = #7C3AED
1403
+ * ⚠️ New token: no existing match
1404
+ */
1405
+ ```
1406
+
1407
+ ---
1408
+
1409
+ ## Phase 8: Correction Notes
1410
+
1411
+ After generating code, output a brief correction report:
1412
+
1413
+ ```markdown
1414
+ ## Correction Notes
1415
+
1416
+ ### Generation Mode
1417
+ - Mode: default / --standalone / responsive
1418
+ - Output directory: {path}
1419
+ - Viewports: {list of viewport labels + widths, if responsive}
1420
+
1421
+ ### Files Generated
1422
+ | File | Type | Description |
1423
+ |------|------|-------------|
1424
+ | styles/tokens.css | Global tokens | {N} colors, {N} spacing, {N} typography |
1425
+ | styles/global.css | Base styles | Reset + typography + layout |
1426
+ | ComponentName/ComponentName.tsx | Component | Root component |
1427
+ | ComponentName/ComponentName.module.css | Styles | Component-specific styles |
1428
+
1429
+ ### Responsive Summary (responsive mode only)
1430
+ | Token | Mobile | Desktop | Strategy |
1431
+ |-------|--------|---------|----------|
1432
+ | --figma-text-h1 | 24px | 48px | clamp() |
1433
+ | --figma-space-section | 16px | 48px | clamp() |
1434
+ | Card grid | 1col | 3col | @media grid |
1435
+ | Sidebar | hidden | visible | @media display |
1436
+
1437
+ - Fluid tokens generated: {N}
1438
+ - Layout breakpoints used: {list}
1439
+ - Component swaps: {list or "none"}
1440
+
1441
+ ### Layer Issues Found
1442
+ - [Layer name] was ambiguous → interpreted as [component] based on image
1443
+ - [Layer structure] didn't match visual → used image-based layout
1444
+
1445
+ ### Markup Quality
1446
+ - Semantic tags used: {list}
1447
+ - Accessibility: {pass/fail items}
1448
+
1449
+ ### Recommendations for Figma File
1450
+ - Use Auto Layout for [specific frame] to improve extraction accuracy
1451
+ - Name layers semantically (e.g., "login-form" not "Frame 47")
1452
+ - Use consistent spacing tokens
1453
+ - (responsive) Keep same component names across mobile/desktop frames for easier mapping
1454
+ ```
1455
+
1456
+ ---
1457
+
1458
+ ## Tool Usage Rules
1459
+
1460
+ | Tool | When |
1461
+ |------|------|
1462
+ | Read | Frame image, layers JSON, project config, existing components |
1463
+ | Glob | Find existing components, theme files, design tokens |
1464
+ | Grep | Search for existing color/spacing/typography definitions |
1465
+ | Write | Create new component files and style files |
1466
+ | Edit | Update existing theme/token files to add new tokens (default mode) |
1467
+ | Bash | `npx vibe figma extract` for data extraction, dependency checks |
1468
+
1469
+ ## Important
1470
+
1471
+ - **Never guess colors** — extract from layers.json or image analysis
1472
+ - **Never invent spacing** — use extracted values mapped to token scale
1473
+ - **Never hardcode values** — all visual properties reference token variables
1474
+ - **Preserve existing patterns** — match the project's existing component style (default mode)
1475
+ - **Image is truth** — when layer structure is confusing, trust what the image shows
1476
+ - **Ask before overwriting** — if a component file already exists, ask the user first
1477
+ - **No console.log** — never include debug logging in generated code
1478
+ - **No div soup** — every element uses the correct semantic tag
1479
+ - **Component size limit** — split components exceeding 50 lines
1480
+ - **Style separation** — global tokens file + per-component style files, always
1481
+
1482
+ ## Next Steps: Design Quality Pipeline
1483
+
1484
+ After generating code, present the following pipeline to the user:
1485
+
1486
+ ### Quick (default recommendation)
1487
+ ```
1488
+ /design-normalize → /design-audit
1489
+ ```
1490
+ - Normalize: 하드코딩 값 → MASTER.md 토큰으로 치환
1491
+ - Audit: A11Y + 성능 + 반응형 + AI Slop 검출
1492
+
1493
+ ### Thorough (recommended for production)
1494
+ ```
1495
+ /design-normalize → /design-audit → /design-critique → /design-polish
1496
+ ```
1497
+ - + Critique: Nielsen 10 휴리스틱 + 5 페르소나 분석
1498
+ - + Polish: 인터랙션 상태 보완 (hover/focus/loading/error)
1499
+
1500
+ ### Pre-requisite check
1501
+ If `.claude/vibe/design-context.json` does NOT exist:
1502
+ ```
1503
+ ⚠️ 디자인 컨텍스트가 없습니다. /design-teach 를 먼저 실행하면
1504
+ 브랜드, 접근성, 타겟 디바이스에 맞춘 더 정확한 코드를 생성할 수 있습니다.
1505
+ ```
1506
+
1507
+ ### Output format
1508
+ ```
1509
+ ## 🎨 Design Quality Pipeline
1510
+
1511
+ 생성된 파일: {file list}
1512
+
1513
+ 추천 다음 단계:
1514
+ 1. /design-normalize — 토큰 정렬 (하드코딩 제거)
1515
+ 2. /design-audit — 기술 품질 검사
1516
+ 3. /design-critique — UX 휴리스틱 리뷰
1517
+ 4. /design-polish — 최종 인터랙션 보완
1518
+
1519
+ 💡 /design-teach 가 아직 설정되지 않았다면 먼저 실행하세요.
1520
+ ```