# ClaudeDesign2Figma (`CD2F`) — Technical Design Specification v1.0

> **Mục tiêu:** Xây dựng hệ thống chuyển đổi **Claude Design → Figma** vượt trội `html.to.design` về độ chính xác ngữ nghĩa, không giới hạn lượt/cloud lock-in, và đặc biệt là **đọc trực tiếp Design System của Claude Design** để tạo hoặc đồng bộ Variables, Styles, và Component Libraries chuẩn sản xuất trong Figma.

---

## 1. Tại sao cần kiến trúc riêng cho Claude Design?

`html.to.design` (‹div›RIOTS) xử lý HTML như một trang web vô danh:
1. Đẩy DOM qua cloud & giới hạn 10 imports/tháng ở bản Free.
2. Không đọc `tokens.json`, `tokens.css`, `design-system.json` hay cấu trúc `canvas.json` / `deck.json` của Claude Design.
3. Tạo local styles rời rạc thay vì 2-tier **Figma Variable Collections (`Primitives` + `Tokens` Light/Dark Modes)** có `scopes` và `codeSyntax.WEB`.
4. Sinh ra cây layer sâu ("div soup") và tách các card/button giống nhau thành nhiều Frame độc lập thay vì Component + Instances.
5. Các repo open-source như `brianleach/claude-to-figma` tự viết CSS cascade engine (`postcss`) + `yoga-layout` nên gãy với CSS hiện đại (`oklch()`, `color-mix()`, `clamp()`, `calc()`, Tailwind runtime, `*.standalone.html`).

**Giải pháp của `CD2F`:**
* **Không viết lại CSS engine.** Dùng **Chromium thật** (Playwright headless trên server/CLI hoặc Chrome Extension trên tab live) để hydrate hoàn toàn React/Babel/Tailwind/`__bundler` rồi đọc `getComputedStyle()` + `getBoundingClientRect()` + `Range.getClientRects()`.
* **Đọc trực tiếp Claude Design System Artifacts:** parse `tokens.json`, `tokens.css`, `:root` & `[data-theme="dark"]` CSS custom properties, và `project/fonts/`.
* **Two-Way Design System Sync:** Nhận inventory Variables/Styles/Components từ file Figma đang mở qua WebSocket để **Bind vào DS sẵn có của team** hoặc **Bootstrap DS mới hoàn chỉnh**.

---

## 2. Kiến trúc 5 tầng (5-Layer Pipeline)

```text
Inputs: .zip Project Archive | *.standalone.html | Raw HTML | Public URL
   │
   ▼
[Layer 1] Ingestion & Chromium Hydrator (@cd2f/compiler)
   ├── Giải nén .zip: đọc canvas.json, deck.json, design-system.json, ds/*/tokens.json
   ├── Loopback asset server: serve ảnh/font/blob nội bộ an toàn
   ├── Ẩn Tweaks overlay của Claude trước khi đo
   └── Render multi-viewport (1440, 390...) & multi-theme (Light, Dark)
   │
   ▼
[Layer 2] DOM Extractor (@cd2f/dom-extractor - IIFE chạy trong Browser)
   ├── Walk visible DOM tree, đọc resolved box & computed styles
   ├── Text measurement qua Range.getClientRects() (biết chính xác line wrap)
   ├── Trích xuất :root / dark CSS custom properties từ document.styleSheets
   ├── Hover probe (optional) lấy style delta của button/card/link
   └── Flag Auto-Snapshot cho subtree phức tạp (3D, canvas, SVG filter/mask)
   │
   ▼
[Layer 3] Design System Engine + Semantic Scene Compiler (@cd2f/compiler)
   ├── Color Normalizer: oklch() / oklab() / hsl() / color-mix() -> sRGB [0..1]
   ├── 2-Tier Variables: Primitives + Semantic Tokens (Light/Dark Modes)
   ├── Semantic Text Styles (role-based) & Effect Styles (shadow/*, blur/*)
   ├── Div-Soup Flattener + Semantic Layer Naming
   ├── Flex & Figma Native GRID Mapper
   ├── Subtree Structural Hasher -> Component + Instances (Text & Image overrides)
   ├── SVG Normalizer (rect/circle/arc A -> Cubic Bézier C)
   └── Two-Way Figma DS Matcher (khớp codeSyntax, tên, hoặc OKLab Delta-E)
   │
   ▼
[Layer 4] CD2F-IR v1 (@cd2f/ir - Zod Schema)
   └── JSON trung gian bất biến, tách biệt Web DOM khỏi Figma Plugin API
   │
   ▼
[Layer 5] Relay & Figma Plugin Builder (@cd2f/server + @cd2f/figma-plugin)
   ├── WebSocket Room Relay (wss://cd2f.santaris.app/ws?room=XXXX)
   ├── Figma Inventory Handshake (Figma -> Web Studio)
   ├── Font Gatekeeper (listAvailableFontsAsync + fallback mapping)
   └── Scene Builder (Variables -> Styles -> Components -> Artboards -> PluginData)
```

---

## 3. Đặc tả `CD2F-IR v1` (Intermediate Representation)

### 3.1. Root Document (`Cd2fDocument`)
* `version`: `"1.0"`
* `source`: `{ kind: "zip" | "html" | "url", title: string, claudeFormat?: "canvas" | "deck" | "design-system" | "standalone" | "html" }`
* `designSystem`:
  * `collections`: mảng `VariableCollectionIR` (`Primitives`, `Tokens`)
    * `modes`: `{ id: string, name: string }[]` (ví dụ `Light`, `Dark`)
    * `variables`: `{ id, name, type: "COLOR" | "FLOAT" | "STRING", scopes: VariableScope[], codeSyntaxWeb?: string, valuesByMode: Record<modeId, rawValue | { aliasOf: varId }> }[]`
  * `paintStyles`: `{ id, name, paints: PaintIR[] }[]`
  * `textStyles`: `{ id, name, role, fontFamily, fontStyle, fontSize, lineHeightPx, letterSpacingPercent, textCase? }[]`
  * `effectStyles`: `{ id, name, effects: EffectIR[] }[]`
  * `dsMatchSummary`: thống kê token nào đã match với `FigmaInventory` sẵn có (`matchedVariableId`, `matchedComponentKey`, `deltaE`).
* `components`: `ComponentIR[]` (master templates được detect từ repeated subtrees hoặc `components/` trong DS)
* `artboards`: `ArtboardIR[]` (mỗi viewport × theme hoặc từng slide trong `deck.json` / artboard trong `canvas.json`, kèm tọa độ `canvasX`, `canvasY` và `root: NodeIR`)
* `snapshots`: `Record<snapshotId, string>` (base64 PNG @2x cho `IMAGE` và `autoSnapshot` fallback)
* `fonts`: `{ family: string, styles: string[], googleFontsUrl?: string }[]`

### 3.2. Node Types (`NodeIR`)
Mỗi node có `id`, `name`, `x`, `y`, `width`, `height`, `opacity`, `visible`, `pluginData` (`selector`, `domHash`, `boundVars`), `hoverDelta?`:
1. **`FRAME`**:
   * `layout`:
     * `mode`: `"NONE" | "HORIZONTAL" | "VERTICAL" | "GRID"`
     * Flex props: `primaryAxisAlignItems`, `counterAxisAlignItems`, `itemSpacing`, `counterAxisSpacing`, `wrap`, `padding` (`top/right/bottom/left`), `primarySizing` (`FIXED|HUG|FILL`), `counterSizing`
     * Grid props (Figma Native Grid): `gridColumnCount`, `gridRowCount`, `gridColumnGap`, `gridRowGap`, `gridColumnSizes` (`{ type: "FIXED"|"FLEX"|"HUG", value? }[]`), `gridRowSizes`
   * `childLayout`: `positioning` (`AUTO|ABSOLUTE`), `layoutGrow`, `gridColumnAnchorIndex`, `gridRowAnchorIndex`, `gridColumnSpan`, `gridRowSpan`
   * `fills`, `strokes`, `strokeWeight`, `strokeAlign`, `cornerRadius` (per-corner `[tl, tr, br, bl]`), `effects`, `clipsContent`, `children: NodeIR[]`
2. **`TEXT`**:
   * `characters`, `fontFamily`, `fontStyle` (`Regular|Medium|SemiBold|Bold|...`), `fontSize`, `lineHeight` (`PIXELS` | `AUTO`), `letterSpacingPercent`, `textAlignHorizontal`, `textDecoration`, `textCase`, `fills`, `hyperlink?`, `textStyleRef?`, `textAutoResize` (`WIDTH_AND_HEIGHT` | `HEIGHT` | `NONE`)
3. **`VECTOR`**:
   * `svgMarkup` (đã normalize qua SVG Rewriter: không còn `A`/`H`/`V` path error, đã resolve `currentColor`)
4. **`IMAGE`**:
   * `snapshotRef` (key trỏ vào `snapshots`), `scaleMode` (`FILL` | `FIT`), `cornerRadius`, `isAutoSnapshotFallback?: boolean`
5. **`INSTANCE`**:
   * `componentId`, `matchedFigmaComponentKey?`, `textOverrides: Record<nodeRelPath, string>`, `imageOverrides: Record<nodeRelPath, snapshotRef>`, `fillOverrides?: ...`

---

## 4. Bảng Mapping CSS → Figma Plugin API (Chuẩn hóa & Edge Cases)

### 4.1. Layout & Box Model
* `display: flex; flex-direction: row|column` → `frame.layoutMode = 'HORIZONTAL' | 'VERTICAL'`
* `flex-wrap: wrap` → `frame.layoutWrap = 'WRAP'`
* `gap / row-gap / column-gap` → `itemSpacing`, `counterAxisSpacing` (và bind spacing variable nếu khớp token)
* `display: grid` → `frame.layoutMode = 'GRID'`, parse `grid-template-columns` kết hợp resolved pixels:
  * Giá trị `fr` → `{ type: 'FLEX', value: frCount }`
  * Giá trị `px` cố định → `{ type: 'FIXED', value: px }`
  * Child có `grid-column: span N` → `child.gridColumnSpan = N` (đặt `gridColumnAnchorIndex` theo vị trí Chromium đo được)
* `position: absolute | fixed` → append vào parent rồi mới đặt `child.layoutPositioning = 'ABSOLUTE'`, gán `child.x`, `child.y` tương đối theo parent content box.
* **Gotcha Figma API:** Luôn đặt `parent.layoutMode` **trước** khi gán `child.layoutSizingHorizontal = 'FILL'` hoặc `layoutGrow = 1`, nếu không Figma sandbox sẽ throw error.

### 4.2. Màu sắc & Variables
* Mọi giá trị màu `oklch(L C H / a)`, `oklab()`, `hsl()`, `color-mix()` được convert trong `@cd2f/ir` sang sRGB `{ r, g, b, a }` trong khoảng `[0..1]`.
* **Gotcha Figma API:** `node.fills` và `node.strokes` là **read-only immutable arrays**. Để bind Variable vào Paint:
  * Phải clone object paint `SOLID`, gọi `figma.variables.setBoundVariableForPaint(basePaint, 'color', variable)` và gán lại cả mảng `[boundPaint]`.
  * Gradient & Image paint **không** bind color variable trực tiếp được → giữ inline gradient stops.
* **Scopes bắt buộc:**
  * Token màu nền: `['FRAME_FILL', 'SHAPE_FILL']`
  * Token màu chữ: `['TEXT_FILL']`
  * Token viền: `['STROKE_COLOR']`
  * Token spacing/gap: `['GAP']`
  * Token bo góc: `['CORNER_RADIUS']`
  * Primitives: `[]` (ẩn khỏi color picker của designer để chỉ dùng Semantic tokens)

### 4.3. Typography & Range Measurement
* Browser render font weight bằng số (`400`, `500`, `600`, `700`). Map sang Figma `fontStyle`:
  * `100` → `Thin`, `200` → `ExtraLight`, `300` → `Light`, `400` → `Regular`, `500` → `Medium`, `600` → `SemiBold`, `700` → `Bold`, `800` → `ExtraBold`, `900` → `Black` (kèm `Italic` nếu `fontStyle === 'italic'`).
* `figma.loadFontAsync({ family, style })` bắt buộc phải gọi **trước** mọi mutation trên `TextNode` hoặc `TextStyle`.
* Nếu font không có trên máy user, plugin giữ nguyên tên font gốc trong `pluginData('cd2f_orig_font')` và tạm render bằng font fallback do user chọn (mặc định `Inter` hoặc `Roboto`) để không crash giữa chừng.

### 4.4. SVG & Auto-Snapshot Gate
* **SVG Rewriter:** Chuyển `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>`, `<polyline>` thành `<path>`, hạ lệnh `H`/`V` thành `L`, và chuyển Elliptical Arc (`A`/`a`) sang chuỗi Cubic Bézier (`C`) trước khi gọi `figma.createNodeFromSvg()`.
* **Auto-Snapshot Gate (tự động rasterize @2x PNG):** Kích hoạt ngay khi gặp một trong các dấu hiệu:
  1. Element có attribute `data-c2f="snapshot"` hoặc `data-figma="snapshot"`.
  2. Thẻ `<canvas>` (chart, WebGL, animation).
  3. CSS `transform` có 3D (`matrix3d`, `rotateX`, `rotateY`, `perspective`).
  4. `mix-blend-mode` khác `normal`, hoặc `mask-image` / `clip-path: path(...)` / `clip-path: polygon(...)`.
  5. SVG chứa `<filter>`, `<mask>`, `<pattern>`, `<foreignObject>`, hoặc `<text>`.

---

## 5. Giao thức WebSocket Relay & Figma Inventory Handshake

Endpoint: `wss://cd2f.santaris.app/ws?room=<ROOM_CODE>&role=web|figma`

1. **Figma → Server → Web Studio (`FIGMA_INVENTORY`):**
   * Ngay khi plugin mở và kết nối room, plugin quét file hiện tại (read-only):
     * `figma.variables.getLocalVariableCollectionsAsync()` + `getLocalVariablesAsync()` (gồm `id`, `name`, `resolvedType`, `codeSyntax`, giá trị mode đầu).
     * `figma.getLocalPaintStylesAsync()`, `getLocalTextStylesAsync()`.
     * `figma.root.findAllWithCriteria({ types: ['COMPONENT', 'COMPONENT_SET'] })` (lấy `key`, `name`, variant properties).
   * Gửi gói `FIGMA_INVENTORY` lên Web Studio để hiển thị trạng thái *"Connected to Figma file: <fileName>"* và bật tính năng **Match & Bind into Existing Team DS**.
2. **Web Studio → Server → Figma (`BUILD_IR`):**
   * User bấm **Send to Figma** → gửi `Cd2fDocument` (tự chunk nếu payload lớn > 2MB) qua WebSocket xuống plugin.
   * Plugin trả tiến độ `BUILD_PROGRESS` (`0..100%`) và `BUILD_DONE` (`{ pageId, artboardIds, missingFonts, stats }`).

---

## 6. Bảo mật & Quyền riêng tư
* Dữ liệu HTML/ZIP xử lý trực tiếp trên server VPS riêng (`cd2f.santaris.app`), không lưu trữ vĩnh viễn trên đĩa (chỉ giữ trong RAM/scratch trong phiên xử lý và tự dọn).
* Headless Chromium chạy với `--no-sandbox` trong context cô lập, chặn truy cập `file://` và metadata IPs (`169.254.169.254`, `127.0.0.1` ngoài loopback asset server của chính job đó).
* Chế độ hoàn toàn offline: User luôn có thể tải `.cd2f.json` và kéo thả trực tiếp vào tab **File / Paste** của Figma Plugin.