[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+236 -66
View File
@@ -2,91 +2,261 @@
id: wiki-2026-0508-figma-integration
title: Figma Integration
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Figma API, Figma plugin, design tokens, Figma to code, Dev Mode, AI Figma]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.94
verification_status: applied
tags: [figma, design-system, design-tokens, plugin, dev-mode, ai-design]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: TypeScript / JavaScript
framework: Figma Plugin API / REST API / Dev Mode
---
# [[Figma Integration|Figma Integration]]
# Figma Integration
## 📌 한 줄 통찰 (The Karpathy Summary)
[[Figma|Figma]] Integration(피그마 통합)은 현대적인 React 프론트엔드 아키텍처에서 디자인 결정 사항을 코드와 동기화하고 자동화하는 핵심 프로세스입니다 [1, 2]. 주로 Figma에서 색상, 폰트, 간격 등의 디자인 토큰을 JSON 형식으로 추출하여 개발 환경에 적용하는 방식을 의미합니다 [2]. 더 나아가, AI 에이전트와 전용 프로토콜을 활용하여 Figma 파일 내에서 컴포넌트 명세서를 자동으로 생성하는 등 디자인과 개발 간의 간극을 줄이고 확장성 있는 UI 시스템을 구축하는 데 필수적으로 사용됩니다 [3, 4].
## 한 줄
> **"매 Figma 의 의 의 design 의 code / system 의 connect"**. 매 REST API + 매 Plugin API + 매 Dev Mode + 매 Variables (design tokens). 매 modern: 매 AI 매 (Anima, Builder.io, Locofy) figma → React.
## 📖 구조화된 지식 (Synthesized Content)
* **디자인 토큰 추출 및 변환:** Figma는 확장 가능한 디자인 시스템의 단일 진실 공급원([[Single_Source_of_Truth|Single Source of Truth]]) 역할을 합니다 [1, 5]. Tokens Studio for Figma와 같은 플러그인을 사용하면 디자이너가 설정한 디자인 결정을 JSON 구조로 추출할 수 있습니다 [2, 6]. 이렇게 내보낸 JSON 파일은 Style Dictionary와 같은 도구를 거쳐 React 애플리케이션에서 직접 사용할 수 있는 CSS 변수나 [[JavaScript|JavaScript]]/TypeScript 테마 객체로 자동 변환됩니다 [7, 8].
* **파이프라인 동기화:** Figma를 개발 툴 체인 파이프라인과 직접 연결하면 디자인 시스템의 일관성을 유지할 수 있습니다 [9]. 디자인 토큰을 수동으로 동기화하거나 공유 저장소에 저장하는 방식을 넘어, Superflex.ai와 같은 자동화 플랫폼을 활용해 Figma의 디자인 시스템 변경 사항을 React 코드로 즉시 동기화하고 생성할 수 있습니다 [6, 10].
* **AI 기반 컴포넌트 명세([[Specification|Specification]]) 자동화:** Uber의 사례처럼, 대규모 컴포넌트 라이브러리 관리를 위해 AI와 Figma를 통합하는 고도화된 방식도 존재합니다 [3]. Uber는 오픈 소스인 'Figma Console MCP(Model Context Protocol)'를 통해 Cursor의 AI 에이전트를 Figma 데스크톱에 로컬로 직접 연결하는 'uSpec' 시스템을 구축했습니다 [4, 11].
* **명세서 렌더링:** 이 통합 시스템은 AI가 Figma 파일의 컴포넌트 트리, 하위 컴포넌트 구조, 디자인 토큰 및 변수를 크롤링하여 API, 색상 주석, 화면 판독기(Screen reader) 접근성 속성 등을 파악하게 합니다 [11-13]. 이후 AI가 완성된 디자인 설계 명세서를 Figma 파일 내에 직접 렌더링함으로써, 수동으로 몇 주가 걸리던 문서화 작업을 단 몇 분으로 단축시킵니다 [3, 14].
## 매 핵심
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Design Tokens|Design Tokens]], Style Dictionary, [[Dynamic Theming|Dynamic Theming]]
- **Projects/Contexts:** Uber Base DesignSystem, Figma Console MCP, Tokens Studio for Figma
- **Contradictions/Notes:** 소스 내에서 Figma 통합에 대한 모순된 주장은 발견되지 않으며, 모든 소스가 공통적으로 Figma를 단일 진실 공급원(Source of Truth)으로 삼아 코드 및 문서화를 자동 동기화하는 파이프라인 구축을 권장합니다 [3, 5, 15].
### 매 API surface
- **REST**: 매 read file structure.
- **Plugin API**: 매 in-Figma scripting.
- **Webhook**: 매 file 의 변화 의 react.
- **Variables API** (2024+): 매 design tokens.
- **Dev Mode**: 매 inspection + token reference.
---
*Last updated: 2026-04-26*
### 매 응용
1. **Design tokens**: 매 Figma → CSS / Tailwind.
2. **Code generation**: 매 React / SwiftUI.
3. **Documentation**: 매 component → Storybook.
4. **Localization**: 매 string export.
5. **Asset export**: 매 SVG / PNG / icons.
6. **AI prompt**: 매 design → spec.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 modern AI tool
- **Anima**: 매 figma → React/Vue.
- **Builder.io Visual Copilot**: 매 figma + AI.
- **Locofy.ai**.
- **FigJam AI**.
- **Magic Patterns**: 매 design → component.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### REST API (read file)
```typescript
async function getFigmaFile(fileKey: string, token: string) {
const r = await fetch(`https://api.figma.com/v1/files/${fileKey}`, {
headers: { 'X-Figma-Token': token },
});
return r.json();
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Variables API (design tokens)
```typescript
async function getVariables(fileKey: string, token: string) {
const r = await fetch(`https://api.figma.com/v1/files/${fileKey}/variables/local`, {
headers: { 'X-Figma-Token': token },
});
return r.json();
}
**선택 A를 써야 할 때:**
- *(TODO)*
// 매 transform → CSS variables
function variablesToCss(variables: any[]): string {
return variables.map(v => `--${v.name}: ${v.value};`).join('\n');
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Plugin (TS, manifest.json)
```json
{
"name": "Token Sync",
"id": "1234",
"api": "1.0.0",
"main": "code.js",
"ui": "ui.html",
"editorType": ["figma"]
}
```
**기본값:**
> *(TODO)*
### Plugin script (sync tokens)
```typescript
// 매 code.ts
figma.showUI(__html__, { width: 320, height: 480 });
## ❌ 안티패턴 (Anti-Patterns)
figma.ui.onmessage = async msg => {
if (msg.type === 'export-tokens') {
const collections = await figma.variables.getLocalVariableCollectionsAsync();
const tokens: any = {};
for (const c of collections) {
tokens[c.name] = {};
for (const id of c.variableIds) {
const v = await figma.variables.getVariableByIdAsync(id);
tokens[c.name][v.name] = v.valuesByMode;
}
}
figma.ui.postMessage({ type: 'tokens', data: tokens });
}
};
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Token JSON (design tokens W3C)
```json
{
"color": {
"primary": { "$value": "#3b82f6", "$type": "color" },
"danger": { "$value": "#ef4444", "$type": "color" }
},
"spacing": {
"sm": { "$value": "8px", "$type": "dimension" },
"md": { "$value": "16px", "$type": "dimension" }
}
}
```
### Style Dictionary (Amazon)
```javascript
// 매 figma → JSON → all platforms
const StyleDictionary = require('style-dictionary').extend({
source: ['tokens.json'],
platforms: {
css: { transformGroup: 'css', files: [{ destination: 'tokens.css', format: 'css/variables' }] },
ios: { transformGroup: 'ios-swift', files: [{ destination: 'Tokens.swift', format: 'ios-swift/class.swift' }] },
android: { transformGroup: 'android', files: [{ destination: 'colors.xml', format: 'android/colors' }] },
},
});
StyleDictionary.buildAllPlatforms();
```
### Figma to React (Anima-style)
```python
def figma_to_react(figma_node):
"""매 simplified."""
if figma_node.type == 'FRAME':
return f"<div style={{{node_to_style(figma_node)}}}>{children_jsx(figma_node)}</div>"
if figma_node.type == 'TEXT':
return f"<span>{figma_node.characters}</span>"
# ...
```
### Webhook (file update)
```typescript
app.post('/figma-webhook', (req, res) => {
const { event_type, file_key } = req.body;
if (event_type === 'FILE_VERSION_UPDATE') {
syncTokens(file_key);
}
res.sendStatus(200);
});
```
### Dev Mode plugin (code connect)
```typescript
import { figma } from '@figma/code-connect';
import { Button } from './Button';
figma.connect(Button, '<figma-component-url>', {
props: {
label: figma.string('Label'),
variant: figma.enum('Variant', { Primary: 'primary', Secondary: 'secondary' }),
disabled: figma.boolean('Disabled'),
},
example: ({ label, variant, disabled }) => (
<Button variant={variant} disabled={disabled}>{label}</Button>
),
});
```
### Asset export (SVG)
```typescript
async function exportSvg(fileKey: string, nodeId: string, token: string) {
const r = await fetch(`https://api.figma.com/v1/images/${fileKey}?ids=${nodeId}&format=svg`, {
headers: { 'X-Figma-Token': token },
});
const { images } = await r.json();
return fetch(images[nodeId]).then(r => r.text());
}
```
### Component prop sync
```typescript
// 매 figma component property → typescript prop
function syncComponentProps(figmaComponent: any) {
const props = figmaComponent.componentPropertyDefinitions;
return Object.entries(props).map(([key, def]: [string, any]) => ({
name: key,
type: def.type === 'BOOLEAN' ? 'boolean' : 'string',
default: def.defaultValue,
}));
}
```
### LLM-aided figma → spec
```python
def llm_design_spec(figma_node, llm):
prompt = f"""You are a UX engineer. Given this Figma frame structure:
{json.dumps(figma_node, indent=2)}
Generate:
1. React component spec (props + behavior)
2. Accessibility checklist
3. Edge cases (empty, error, loading)"""
return llm.generate(prompt)
```
### Variables → Tailwind config
```javascript
const figmaTokens = require('./tokens.json');
module.exports = {
theme: {
colors: Object.fromEntries(Object.entries(figmaTokens.color).map(([k, v]) => [k, v.$value])),
spacing: Object.fromEntries(Object.entries(figmaTokens.spacing).map(([k, v]) => [k, v.$value])),
},
};
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Tokens sync | Variables API + Style Dictionary |
| Code gen | Anima / Builder.io / manual |
| Asset export | REST images endpoint |
| Live sync | Webhook + plugin |
| Component-level | Code Connect (Dev Mode) |
| AI augment | Visual Copilot |
**기본값**: 매 Variables (tokens) + 매 Style Dictionary + 매 Code Connect + 매 manual code (no auto-codegen) + 매 webhook for sync.
## 🔗 Graph
- 부모: [[Design-System]] · [[UI-UX]]
- 변형: [[Design-Tokens]] · [[Code-Connect]]
- 응용: [[Storybook]] · [[Style-Dictionary]] · [[Tailwind]]
- Adjacent: [[Anima]] · [[Builder-io]] · [[Web-Components]]
## 🤖 LLM 활용
**언제**: 매 design system. 매 design-to-code workflow.
**언제 X**: 매 one-off design.
## ❌ 안티패턴
- **Manual token copy**: 매 drift.
- **Auto-generated 의 ship**: 매 quality 의 review X.
- **No webhook**: 매 stale tokens.
- **Pixel-perfect codegen**: 매 component fail.
- **Asset embed in JS bundle**: 매 size.
## 🧪 검증 / 중복
- Verified (Figma API docs, Code Connect, Style Dictionary).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — REST + plugin + tokens + Code Connect + AI codegen |