---
description: "Figma URL -> SwiftUI component generation (full pipeline, Phase 0-8, with SubPhases)"
allowed-tools: Read, Write, Edit, Glob, Grep, Bash, Agent, WebFetch, TaskCreate, TaskUpdate
---

# Figma -> SwiftUI Component Generator

Generate a production-ready SwiftUI component from a Figma design URL.

**Input**: $ARGUMENTS (Figma URL, or component name if already gathered)

## Phase Order

```
0-Init -> 1-Gather -> 2A-TestingIDs -> 2B-Localization -> 2C-Accessibility -> 2D-Analytics
-> 3-TokenMapping -> 4A-Configuration -> 4B-View -> 4C-Docs -> 4D-Preview -> 4E-Modifiers
-> 4F-Wiki -> 5A-ViewInspector -> 5B-Snapshot -> 5C-Unit -> 6-CodeConnect
-> 7-IssueBodyUpdate -> 8-Cleanup
```

When invoked from `/multi-agent` with `instructionDriven == true` (figma instruction file detected), this skill takes over Phase 3 of the main pipeline. Progress is reported as SubPhases under the main pipeline's Phase 3:

```
* Phase 3: Dev (figma)       in progress
  ■ SubPhase 3.0: Init            completed
  ■ SubPhase 3.1: Gather          completed
  * SubPhase 3.4F: Wiki           writing wiki pages...
  □ SubPhase 3.5C: Unit Tests     pending
  ...
```

## Phase 0: Init

1. Parse Figma URL  -  extract fileKey and nodeId
2. Detect component name from Figma metadata or user input
3. Create branch: `feature/{JIRA_KEY}-{component-name}`
4. Create task list for all phases

## Phase 1: Gather

1. Fetch design context from Figma (use `get_design_context` if Figma MCP available, or screenshot)
2. Identify: variants, states, properties, design tokens
3. Document in a gathering summary

## Phase 2: Preparation (parallel sub-phases)

### 2A: Testing Identifiers
- Define `UITestingIdentifiers` enum for every interactive element
- Pattern: `{ComponentName}_{elementName}` (e.g., `Button_title`, `Button_icon`)

### 2B: Localization
- Extract all user-facing strings
- Create localization keys: `{componentName}.{element}` (e.g., `button.title`)

### 2C: Accessibility
- Define VoiceOver labels, hints, traits for each element
- Minimum tap target: 44x44pt
- Dynamic Type support plan

### 2D: Analytics
- Define analytics events per interaction
- Pattern: `{componentName}_{action}` (e.g., `button_tapped`)

## Phase 3: Token Mapping

Map Figma design values to project design tokens:

| Figma Value | Token |
|-------------|-------|
| Padding 16 | `.Spacing.spacing16` |
| Color #E31837 | `Color.Primary.primary` |
| Font 16/semibold | `.typographyStyle(.body1)` |
| Corner 8 | `.CornerRadius.radius8` |

**Rules**:
- No magic numbers  -  all values reference design tokens
- No raw hex colors  -  use semantic color tokens
- No raw `.font()`  -  use typography tokens
- Token hierarchy: Spacing > Size > Radius > BorderWidth > Color > Typography

## Phase 4: Implementation (sequential sub-phases)

### 4A: Configuration
```swift
// {Name}Configuration.swift
struct {Name}Configuration {
    var title: String = ""
    var style: {Name}Style = .primary
    var isEnabled: Bool = true
    // ... all properties from Figma variants
}
```
- Pure value type, no side effects, no view logic
- Every Figma variant maps to a property
- Sensible defaults for all properties

### 4B: View
```swift
// {Name}View.swift
struct {Name}View: View {
    let configuration: {Name}Configuration

    var body: some View {
        // Render using configuration + design tokens
    }
}
```
- Renders Configuration only
- Uses design tokens (no magic numbers)
- Accessibility identifiers on every interactive element

### 4C: Documentation
```markdown
// FIGMA.md
## {Name} Component
| Variant | Property | Values |
|---------|----------|--------|
| Style   | style    | primary, secondary, ghost |
| Size    | size     | small, medium, large |
```

### 4D: Preview
```swift
#Preview("{Name} - All Variants") {
    VStack {
        // Every meaningful variant combination
        // Light + Dark
        // LTR + RTL
    }
}
```

### 4E: Modifiers
```swift
// {Name}+Modifiers.swift
extension {Name}View {
    func title(_ value: String) -> {Name}View {
        var config = configuration
        config.title = value
        return {Name}View(configuration: config)
    }
}
```
- Fluent API chain for every configuration property

### 4F: Wiki (auto-detected, auto-skipped if no wiki submodule)

Generate and push wiki documentation pages to the wiki submodule.

**Prerequisites check** (deterministic, no prompt):

```bash
# 1. Wiki submodule  -  auto-detect from .gitmodules
WIKI_REL=$(git -C "$PROJECT_ROOT" config -f .gitmodules --get-regexp 'submodule\..*\.path' 2>/dev/null \
  | awk '{print $2}' | grep -i 'wiki' | head -1)

# Preference override
WIKI_PATH_PREF=$(jq -r ".projects[\"$PROJECT\"].wikiPath // empty" "$PREFS_FILE")
[ -n "$WIKI_PATH_PREF" ] && WIKI_REL_ABS="$WIKI_PATH_PREF"
[ -n "$WIKI_REL" ] && WIKI_REL_ABS="$PROJECT_ROOT/$WIKI_REL"

# User preference: disabled?
WIKI_PREF=$(jq -r ".projects[\"$PROJECT\"].wikiPhase // empty" "$PREFS_FILE")
[ "$WIKI_PREF" = "disabled" ] && { log "4F-Wiki disabled for $PROJECT  -  skipping"; exit 0; }

# No wiki found
[ -z "$WIKI_REL_ABS" ] && {
  if autopilot; then exit 0; fi   # autopilot: silent skip
  ask_user "No wiki submodule. (1) add submodule (2) use custom path (3) skip once (4) disable permanently"
  # Persist user choice to prefs
}

# Figma token
DESIGN_TOKEN_KEY=$(jq -r '.global.keychainMapping.figma // empty' "$PREFS_FILE")
[ -z "$DESIGN_TOKEN_KEY" ] && DESIGN_TOKEN_KEY="${USER}_Figma_Access_Token"
DESIGN_TOKEN=$(~/.claude/lib/credential-store.sh get "$DESIGN_TOKEN_KEY" 2>/dev/null)

# Default branch
WIKI_BRANCH=$(git -C "$WIKI_REL_ABS" symbolic-ref refs/remotes/origin/HEAD 2>/dev/null \
  | sed 's|refs/remotes/origin/||')
[ -z "$WIKI_BRANCH" ] && WIKI_BRANCH=$(git -C "$WIKI_REL_ABS" branch --show-current)
```

**Steps**:

1. **Create wiki component dir**:
   ```bash
   mkdir -p "$WIKI_REL_ABS/{wikiCategory}/{ComponentName}/assets"
   ```
   `wikiCategory` mirrors the component's folder layout inside the product repo.

2. **Fetch design-source screenshot** (Figma by default; other sources swap the fetch call):
   ```bash
   RESPONSE=$(printf 'X-Figma-Token: %s\n' "$DESIGN_TOKEN" | curl -s -H @- \
     "https://api.figma.com/v1/images/{fileKey}?ids={nodeId}&format=png&scale=2")
   IMAGE_URL=$(echo "$RESPONSE" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['images']['{nodeId}'])")
   curl -s -o "$WIKI_REL_ABS/{wikiCategory}/{ComponentName}/assets/screenshot.png" "$IMAGE_URL"
   ```
   If `DESIGN_TOKEN` missing: leave a `TODO: add screenshot` placeholder, continue.

3. **Generate main wiki page** (`{ComponentName}.md`)  -  sections:
   Title · screenshot embed · Figma link · Screen/Section/Size metadata · Overview · Testing Identifiers · Localization Keys · Accessibility · Analytics Events · Sub-Components · Platform Implementations (iOS/Android/Web status) · Changelog.

4. **Generate platform-specific page** (`{ComponentName}-iOS.md`)  -  sections:
   Initializer · Parameters · Modifiers · Usage · Design Tokens · Testing Identifiers iOS · Code Connect · Snapshot Tests (image embeds) · Test Coverage · Changelog.

5. **Commit and push**:
   ```bash
   cd "$WIKI_REL_ABS"
   git add "{wikiCategory}/{ComponentName}/"
   git -c user.name="{identity.name}" -c user.email="{identity.email}" \
     commit -F - <<'MA_MSG'
   docs({scope}): add {ComponentName} wiki pages [{jiraId}]
   MA_MSG
   git fetch origin && git rebase "origin/$WIKI_BRANCH"
   git push origin "HEAD:$WIKI_BRANCH"
   ```
   Retry rebase up to 3 times on reject; never force-push.

## Phase 5: Testing (3-layer strategy)

### 5A: ViewInspector (Structural)
- Verify subview hierarchy
- Verify modifiers applied correctly
- Verify accessibility identifiers present

### 5B: Snapshot Tests (Visual)
- Light mode + Dark mode
- LTR + RTL
- All variant combinations

### 5C: Unit Tests (Behavioral)
- Configuration mutations
- Modifier chain correctness
- Default values

## Phase 6: Code Connect

```swift
// {Name}.figma.swift
import FigmaConnect

@FigmaConnect("{fileKey}", "{nodeId}")
struct {Name}CodeConnect {
    // Map Figma variants to Configuration properties
}
```

## Phase 7: Issue Body Update (GitHub Issue only)

If a GitHub Issue tracks this component, update its body after commit + PR:
- Fill the `### Pull Requests` section with PR URL(s), one row per submodule touched
- Flip Implementation / Testing / Code Connect flags from Pending to Done using whatever marker the template uses (match in place, don't introduce new markers)
- Flip the Wiki flag to Done (SubPhase 4F already pushed the wiki pages)
- Write the updated body to a temp file and apply it with `gh issue edit {issueNo} --body-file <file>`  -  preserve every other section unchanged
- NEVER use `Closes:` / `Fixes:` / `Resolves:` keywords  -  use `Ref:` or `Related:` instead

Skip this phase if the task has no GitHub Issue (Jira-only or free-text runs).

## Phase 8: Cleanup & Review

Run the 14-item checklist:
1. File completeness (Configuration, View, Modifiers, .figma.swift, FIGMA.md)
2. No magic numbers (design tokens required)
3. Configuration purity (no side effects)
4. Modifier correctness (fluent API)
5. Accessibility identifiers on every interactive element
6. Analytics events tracked
7. Testing identifier pipeline
8. Preview quality (LTR + RTL, Light + Dark)
9. Code Connect mapping
10. View implementation quality
11. FIGMA.md documentation complete
12. Artifact cleanup
13. Build verification (`xcodebuild`)
14. Test verification (ViewInspector + Snapshot + Unit)

## Output Files

| File | Content |
|------|---------|
| `{Name}Configuration.swift` | Pure value type: all properties |
| `{Name}View.swift` | SwiftUI view, renders Configuration |
| `{Name}+Modifiers.swift` | Fluent modifier API chain |
| `{Name}.figma.swift` | Code Connect registration |
| `FIGMA.md` | Variant matrix, usage examples |
| `{Name}Tests.swift` | ViewInspector structural tests |
| `{Name}SnapshotTests.swift` | Snapshot visual tests |
| `{Name}UnitTests.swift` | Unit behavioral tests |

## Sub-Commands

| Command | What It Does |
|---------|-------------|
| `/figma-to-swiftui <url>` | Full pipeline (this command) |
| `/figma-to-swiftui commit <Name>` | 14-item review + commit + PR |
| `/figma-to-swiftui review <Name>` | Interactive review (approve/request changes) |
