Skip to content

Commit 095371a

Browse files
Rafal Przetakowskibeeflow
authored andcommitted
feat(figma-mcp-component-generator): add code generation tool for Figma components
Add CLI tool to generate React components, stories, and tests from Figma designs. Includes: - Figma client with REST/MCP support - DSL mapper for Figma to React component conversion - Handlebars templates for component, story, and test files - Configuration for design system mappings - Documentation and development guidelines
1 parent 2d4aca7 commit 095371a

File tree

14 files changed

+13644
-1559
lines changed

14 files changed

+13644
-1559
lines changed

.env.dist

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
VITE_DEFAULT_LOCALE=en
22
VITE_API_URL=mock
33
VITE_SENTRY_DSN=
4+
FIGMA_API_TOKEN=
5+
MCP_FIGMA_BASE_URL="http://localhost:8787"

.github/copilot-instructions.md

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
# React Starter — Copilot Instructions (Authoritative Project Rules)
2+
3+
> **Goal:** Copilot must always produce a **complete, runnable** implementation (pages, routing, components, exports, tests) that **passes typecheck, lint and tests** without manual fixes. No internal generators, no CLI helpers — **generate everything in code**.
4+
5+
---
6+
7+
## 1) Framework & Language
8+
9+
* **React + TypeScript** in **strict** mode. No JS files.
10+
* **Functional components only**.
11+
* UI imports **only** from `@/shared/ui`; layout primitives from `@/shared/layout`.
12+
* Do **not** add external UI libraries.
13+
* Comments/strings in **British English**.
14+
15+
---
16+
17+
## 2) Architecture, Quality & Style
18+
19+
* Principles: **DRY, SOLID, KISS**, early‑exit, prefer **branchless** patterns when reasonable.
20+
* **No `else` blocks** in business/UI logic. Split branches into **separate small functions**. Max nesting: **2 levels**.
21+
* Keep components **presentational**; lift state when needed. Memoise where useful (`React.memo`, `useMemo`, `useCallback`).
22+
* Explicit types everywhere; no `any`.
23+
24+
---
25+
26+
## 3) Project Structure & Naming
27+
28+
* **Pages:** `src/pages/<PageName>.tsx` (one entry per page).
29+
* **Features/sections:** `src/features/<page>/components/<ComponentName>/`.
30+
* **Inside a component folder:**
31+
32+
* `ComponentName.tsx`
33+
* `index.ts` (barrel)
34+
* **Tests:**
35+
36+
* **Unit:** `tests/unit/<page>/<ComponentName>.test.tsx` (Vitest)
37+
* **E2E (only if repo has `e2e/`):** `e2e/<page>/<feature>.spec.ts` (match repo runner: Playwright/Cypress)
38+
* Prefer **named exports**; re‑export via barrel files.
39+
* Use TS path aliases (e.g. `@/shared/ui`). Avoid deep relative paths (`../../..`).
40+
41+
---
42+
43+
## 4) Routing (must include)
44+
45+
* Use **React Router v6+** (or the router already used in repo; detect imports). Create/update:
46+
47+
* `src/app/router.tsx` with route objects and lazy‑loaded pages.
48+
* `src/app/App.tsx` hosting `<RouterProvider>` / `<BrowserRouter>`.
49+
* Update `src/main.tsx` (or equivalent) to render `<App />`.
50+
* Include **404** route and basic **error boundary**.
51+
52+
---
53+
54+
## 5) Layout, Spacing & Styling
55+
56+
* Layout via **CSS Grid / Flexbox** only. Avoid absolute positioning unless essential.
57+
* Spacing via **design tokens** only (e.g. `gap-1 .. gap-8`, `p-1 .. p-8`).
58+
* Typography & colours via **semantic tokens** (e.g. `text.h1`, `colour.primary.600`).
59+
* **Forbidden:** inline styles, hard‑coded pixels/colours, ad‑hoc CSS.
60+
61+
---
62+
63+
## 6) Accessibility (non‑negotiable)
64+
65+
* All controls must be **keyboard focusable** with visible focus.
66+
* Accurate `aria-*` attributes; labels associated with inputs; meaningful `alt` text.
67+
* Semantic HTML (`<h1…h6>`, `<p>`, lists) and landmarks where appropriate.
68+
69+
---
70+
71+
## 7) Image → Code Workflow (no generators)
72+
73+
* When given a **Figma screenshot**, infer layout and map elements to the design system:
74+
75+
* **Cards / elevation**`<Card elevation="sm|md|lg" />`.
76+
* **Buttons**`<Button variant="primary|secondary|ghost" size="sm|md|lg" />`.
77+
* **Inputs**`<TextField/>`, `<Select/>`, `<Checkbox/>`, `<Switch/>`.
78+
* **Tables**`<DataTable columns={…} data={…} />` (columns from visible headers).
79+
* **Avatars / Icons**`<Avatar/>`, `<Icon name="…"/>`.
80+
* If no exact mapping exists, pick the **closest semantic** component from `@/shared/ui`. Do **not** invent bespoke styles.
81+
82+
---
83+
84+
## 8) Testing (Unit & E2E) and Storybook
85+
86+
* **Unit tests** (Vitest) for each new component/page in `tests/unit/...`:
87+
88+
* Render snapshot + one behaviour/assertion (e.g. CTA click, conditional render).
89+
* **E2E tests** **only if `e2e/` exists**; add a smoke test for the new route and critical interactions.
90+
* **Storybook (CSF3)** stories for significant variants/states **when Storybook is present**.
91+
* Tests/stories import from the **public API** (barrels), not deep paths.
92+
93+
---
94+
95+
## 9) Performance & States
96+
97+
* Provide **empty**, **loading** and **error** states if data is involved.
98+
* Avoid prop drilling; compose components. Defer expensive work; memoise thoughtfully.
99+
100+
---
101+
102+
## 10) Copilot Output Contract (critical)
103+
104+
Copilot must output:
105+
106+
1. **File tree** to be created/updated, including routing files.
107+
2. **Complete code blocks** for every new/changed file — no placeholders or TODOs.
108+
3. **Barrel export** updates (exact lines to add).
109+
4. **Tests** in `tests/unit/...` and **e2e** in `e2e/...` if folder exists.
110+
5. **Validation & auto‑fix commands** (and confirm they pass locally):
111+
112+
```bash
113+
pnpm typecheck && pnpm lint --fix && pnpm test
114+
# If Storybook exists in this repo:
115+
pnpm build:storybook
116+
```
117+
6. State explicitly that all checks **passed** with zero TypeScript/ESLint errors and green tests.
118+
119+
---
120+
121+
## 11) Pull Requests & CI Gates
122+
123+
* Conventional commit titles (e.g. `feat(dashboard): add StatsGrid route + components`).
124+
* PR description must include:
125+
126+
* Source (screenshot/Figma frame id/name).
127+
* Any deviations from design + rationale.
128+
* Confirmation that unit/e2e tests were added (if applicable) and all CI commands passed.
129+
130+
---
131+
132+
## 12) Quick Checklist (paste into PR)
133+
134+
* [ ] React + TS (strict), functional only; British English
135+
* [ ] Routing added/updated with lazy pages, 404, error boundary
136+
* [ ] Components use `@/shared/ui` & tokens only; no inline styles
137+
* [ ] Max nesting ≤ 2; no `else` blocks; early exits; branchless where reasonable
138+
* [ ] Unit tests in `tests/unit/...` (and e2e if `e2e/` exists)
139+
* [ ] Barrels updated; no deep relative imports
140+
* [ ] `pnpm typecheck && pnpm lint --fix && pnpm test` all green (and Storybook build if present)

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,5 @@ e2e/scripts/**/*.js
3030
e2e/testsResults
3131

3232
.credentials.json
33-
stats.html
33+
stats.html
34+
.env

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ npm run [command_name]
108108
3. [React Query abstraction](/docs/03-react-query-abstraction.md)
109109
4. [Using plop commands](/docs/04-using-plop-commands.md)
110110
5. [E2E tests](/docs/05-e2e-tests.md)
111+
6. [Generating Components from Figma](/docs/06-figma-generator.md)
111112

112113
## How to Contribute
113114

docs/06-figma-generator.md

Lines changed: 226 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,226 @@
1+
# Figma to React Generator
2+
3+
Custom system for generating high-quality React components from Figma designs.
4+
5+
## Installation
6+
7+
The system is already configured in the project. No external dependencies needed - it uses our custom built tools:
8+
- `tools/figma/advanced-mapper.ts` - Figma to React conversion
9+
- `tools/figma/code-generator.ts` - TypeScript/JSX code generation
10+
- `tools/figma/figmaClient.ts` - Figma API client
11+
12+
## Usage
13+
14+
### Basic Command
15+
16+
```bash
17+
pnpm figma:builder --url "FIGMA_URL" --feature FEATURE_NAME --name COMPONENT_NAME
18+
```
19+
20+
### Examples
21+
22+
```bash
23+
# With Figma URL
24+
pnpm figma:builder \
25+
--url "https://www.figma.com/design/GhUCE2ZLNtDvUSVOa4w0Xg/FoodBlog--Admin-dashboard?node-id=83-50804" \
26+
--feature dashboard \
27+
--name HeaderComponent
28+
29+
# With fileKey and query
30+
pnpm figma:builder \
31+
--file GhUCE2ZLNtDvUSVOa4w0Xg \
32+
--query "thumbnail|preview" \
33+
--feature ui \
34+
--name PreviewCard
35+
36+
# With specific sectionId
37+
pnpm figma:builder \
38+
--file GhUCE2ZLNtDvUSVOa4w0Xg \
39+
--sectionId "1:2" \
40+
--feature components \
41+
--name ThumbnailCard
42+
43+
# With page and section
44+
pnpm figma:builder \
45+
--file GhUCE2ZLNtDvUSVOa4w0Xg \
46+
--page "GOB-98 / Admin's dashboard" \
47+
--section "stats" \
48+
--feature dashboard \
49+
--name StatsWidget
50+
```
51+
52+
## Options
53+
54+
| Option | Description | Example |
55+
|-------|------|----------|
56+
| `--url` | Full Figma URL (extracts fileKey and node-id) | `--url "https://figma.com/design/abc123?node-id=1-2"` |
57+
| `--file` | File key from Figma | `--file GhUCE2ZLNtDvUSVOa4w0Xg` |
58+
| `--page` | Page name (CANVAS) in Figma | `--page "Dashboard"` |
59+
| `--section` | Frame/component name to export | `--section "Header"` |
60+
| `--sectionId` | Frame ID (skips name search) | `--sectionId "1:2"` |
61+
| `--query` | Search pattern (supports 'a\|b\|c') | `--query "card\|widget"` |
62+
| `--feature` | **Required** - feature folder | `--feature dashboard` |
63+
| `--name` | **Required** - component name | `--name HeaderComponent` |
64+
| `--outDir` | Output directory | `--outDir src/features` (default) |
65+
66+
## What It Generates
67+
68+
The system generates a complete component structure:
69+
70+
```
71+
src/features/{feature}/components/{ComponentName}/
72+
├── ComponentName.tsx # React component with TypeScript
73+
├── ComponentName.css # CSS styles with exact values from Figma
74+
├── ComponentName.stories.tsx # Storybook story
75+
└── ComponentName.test.tsx # Unit test
76+
```
77+
78+
### Additional Files
79+
80+
- **Route**: `src/routes/{feature}-{ComponentName}/index.tsx` - automatic routing
81+
- **Export**: updates `src/features/{feature}/components/index.ts`
82+
83+
## Features
84+
85+
### 🎨 Precise Style Conversion
86+
- Precise dimensions from Figma (px, rem)
87+
- RGB/RGBA colours with opacity
88+
- Linear gradients
89+
- Shadows (box-shadow)
90+
- Border radius
91+
- Typography (font-size, weight, line-height)
92+
93+
### 🧩 Intelligent Components
94+
- Automatic component type detection (Button, Input, Card, etc.)
95+
- Semantic JSX elements
96+
- Tailwind classes for layout
97+
- Custom CSS classes for detailed styles
98+
99+
### 📱 Responsiveness
100+
- Flex layouts from Figma
101+
- Gap, padding, margin
102+
- Alignment (justify-content, align-items)
103+
- Breakpoints (can be extended)
104+
105+
### ♿ Accessibility
106+
- Semantic HTML
107+
- Alt texts for images
108+
- ARIA attributes (in development)
109+
- Focus management (in development)
110+
111+
## Frame Search Strategy
112+
113+
The system automatically finds the best frame for conversion:
114+
115+
1. **Exact sectionId** - if `--sectionId` is provided, uses it directly
116+
2. **Exact section name** - exact name matching
117+
3. **Query/loose match** - fuzzy search with scoring:
118+
- Exact match: 100 points
119+
- Contains term: 50 points
120+
- Word contains term: 25 points
121+
4. **Biggest frame** - if nothing matches, takes the largest
122+
123+
## Configuration
124+
125+
### Environment Variables
126+
127+
```env
128+
FIGMA_API_TOKEN=your_figma_token_here
129+
```
130+
131+
### Configuration
132+
133+
The generator is fully configured via CLI parameters - no config files needed:
134+
135+
- `--url`: Full Figma URL (extracts fileKey and node-id automatically)
136+
- `--feature`: Target feature folder (e.g., 'dashboard')
137+
- `--name`: Component name (e.g., 'StatsGrid')
138+
139+
The generator automatically uses:
140+
- **Framework**: React with TypeScript
141+
- **Styling**: Tailwind CSS with generated CSS files
142+
- **Output**: Barrel exports, Storybook stories, and tests
143+
```
144+
145+
## Examples of Generated Components
146+
147+
### Simple Component
148+
149+
```tsx
150+
import React from 'react';
151+
import './HeaderComponent.css';
152+
153+
interface HeaderComponentProps {
154+
className?: string;
155+
children?: React.ReactNode;
156+
}
157+
158+
const HeaderComponent: React.FC<HeaderComponentProps> = ({ className = "", ...props }) => {
159+
return (
160+
<div className="flex flex-row justify-between items-center figma-abc123">
161+
<h1 className="text-2xl font-bold figma-def456">Dashboard</h1>
162+
<button className="bg-blue-500 text-white px-4 py-2 rounded figma-ghi789">
163+
Settings
164+
</button>
165+
</div>
166+
);
167+
};
168+
169+
export default HeaderComponent;
170+
export { HeaderComponent };
171+
```
172+
173+
### CSS with Precise Styles
174+
175+
```css
176+
.figma-abc123 {
177+
width: 1200px;
178+
height: 80px;
179+
background-color: rgb(255, 255, 255);
180+
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
181+
padding: 16px 24px;
182+
}
183+
184+
.figma-def456 {
185+
font-size: 28px;
186+
font-weight: 700;
187+
line-height: 34px;
188+
color: rgb(31, 41, 55);
189+
}
190+
```
191+
192+
## Troubleshooting
193+
194+
### Incorrect Styles
195+
- Check if the frame has all necessary properties in Figma
196+
- Ensure the design doesn't use library components (e.g., Safari toolbar)
197+
198+
### Missing Frames
199+
- Check available pages: the system will display a list if none found
200+
- Use `--query` with alternatives: `--query "card|widget|component"`
201+
202+
### API Errors
203+
- Check if `FIGMA_API_TOKEN` is correct
204+
- Ensure you have access to the Figma file
205+
206+
## Comparison with Other Tools
207+
208+
| Feature | Our Generator | Builder.io Visual Copilot | Figma Dev Mode |
209+
|---------|---------------|---------------------------|----------------|
210+
| Style Accuracy | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
211+
| Automation | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐ |
212+
| Customisation | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐ |
213+
| TypeScript | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
214+
| Tailwind Integration | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐ |
215+
| Free Usage | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐ |
216+
| CLI Automation | ⭐⭐⭐⭐⭐ | ⭐⭐ ||
217+
218+
## Development
219+
220+
The system can be extended with:
221+
- More CSS frameworks (styled-components, emotion)
222+
- Advanced component detection patterns
223+
- Image optimization and conversion
224+
- Animation and interaction conversion
225+
- Design tokens extraction and generation
226+
- Better responsive breakpoint handling

0 commit comments

Comments
 (0)