├── mcp-settings-example.json ├── tsconfig.json ├── .gitignore ├── package.json ├── LICENSE ├── README.md └── src ├── figma-client.ts ├── index.ts ├── figma-tools.ts ├── accessibility.ts ├── figma-tailwind-converter.ts ├── figma-react-tools.ts └── component-generator.ts /mcp-settings-example.json: -------------------------------------------------------------------------------- 1 | { 2 | "mcpServers": { 3 | "figma-to-react": { 4 | "command": "node", 5 | "args": ["path/to/mcp-figma-to-react/dist/index.js", "--transport=stdio"], 6 | "env": { 7 | "FIGMA_API_TOKEN": "your_figma_api_token_here" 8 | }, 9 | "disabled": false, 10 | "alwaysAllow": [] 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2020", 4 | "module": "NodeNext", 5 | "moduleResolution": "NodeNext", 6 | "esModuleInterop": true, 7 | "strict": true, 8 | "outDir": "dist", 9 | "sourceMap": true, 10 | "declaration": true, 11 | "resolveJsonModule": true, 12 | "skipLibCheck": true, 13 | "forceConsistentCasingInFileNames": true 14 | }, 15 | "include": ["src/**/*"], 16 | "exclude": ["node_modules", "dist"] 17 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Dependency directories 2 | node_modules/ 3 | 4 | # Build output 5 | dist/ 6 | 7 | # Environment variables 8 | .env 9 | .env.local 10 | .env.development.local 11 | .env.test.local 12 | .env.production.local 13 | 14 | # Logs 15 | logs 16 | *.log 17 | npm-debug.log* 18 | yarn-debug.log* 19 | yarn-error.log* 20 | 21 | # Editor directories and files 22 | .idea/ 23 | .vscode/ 24 | *.suo 25 | *.ntvs* 26 | *.njsproj 27 | *.sln 28 | *.sw? 29 | 30 | # OS generated files 31 | .DS_Store 32 | .DS_Store? 33 | ._* 34 | .Spotlight-V100 35 | .Trashes 36 | ehthumbs.db 37 | Thumbs.db 38 | pnpm-lock.yaml 39 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mcp-figma-to-react", 3 | "version": "1.0.0", 4 | "description": "MCP server for converting Figma designs to React components", 5 | "main": "dist/index.js", 6 | "type": "module", 7 | "scripts": { 8 | "build": "tsc", 9 | "start": "node dist/index.js", 10 | "dev": "tsc -w & node --watch dist/index.js", 11 | "test": "echo \"Error: no test specified\" && exit 1" 12 | }, 13 | "keywords": [ 14 | "figma", 15 | "react", 16 | "mcp", 17 | "component-generator" 18 | ], 19 | "author": "", 20 | "license": "ISC", 21 | "dependencies": { 22 | "@modelcontextprotocol/sdk": "1.10.2", 23 | "axios": "^1.8.4", 24 | "express": "5.1.0", 25 | "prettier": "^3.5.3", 26 | "typescript": "5.8.3", 27 | "ws": "^8.18.1", 28 | "zod": "3.24.3" 29 | }, 30 | "devDependencies": { 31 | "@types/express": "^5.0.1", 32 | "@types/node": "22.14.1", 33 | "@types/ws": "8.18.1" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Rod Lewis 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MCP Figma to React Converter 2 | 3 | This is a Model Context Protocol (MCP) server that converts Figma designs to React components. It provides tools for fetching Figma designs and generating React components with TypeScript and Tailwind CSS. 4 | 5 | ## Features 6 | 7 | - Fetch Figma designs using the Figma API 8 | - Extract components from Figma designs 9 | - Generate React components with TypeScript 10 | - Apply Tailwind CSS classes based on Figma styles 11 | - Enhance components with accessibility features 12 | - Support for both stdio and SSE transports 13 | 14 | ## Prerequisites 15 | 16 | - Node.js 18 or higher 17 | - A Figma API token 18 | 19 | ## Installation 20 | 21 | 1. Clone the repository 22 | 2. Install dependencies: 23 | 24 | ```bash 25 | npm install 26 | ``` 27 | 28 | 3. Build the project: 29 | 30 | ```bash 31 | npm run build 32 | ``` 33 | 34 | ## Configuration 35 | 36 | You need to set the `FIGMA_API_TOKEN` environment variable to your Figma API token. You can get a personal access token from the Figma account settings page. 37 | 38 | ## Usage 39 | 40 | ### Running as a local MCP server 41 | 42 | ```bash 43 | FIGMA_API_TOKEN=your_token_here npm start 44 | ``` 45 | 46 | Or with explicit transport: 47 | 48 | ```bash 49 | FIGMA_API_TOKEN=your_token_here node dist/index.js --transport=stdio 50 | ``` 51 | 52 | ### Running as an HTTP server 53 | 54 | ```bash 55 | FIGMA_API_TOKEN=your_token_here node dist/index.js --transport=sse 56 | ``` 57 | 58 | ## Available Tools 59 | 60 | ### Figma Tools 61 | 62 | - `getFigmaProject`: Get a Figma project structure 63 | - `getFigmaComponentNodes`: Get component nodes from a Figma file 64 | - `extractFigmaComponents`: Extract components from a Figma file 65 | - `getFigmaComponentSets`: Get component sets from a Figma file 66 | 67 | ### React Tools 68 | 69 | - `generateReactComponent`: Generate a React component from a Figma node 70 | - `generateComponentLibrary`: Generate multiple React components from Figma components 71 | - `writeComponentsToFiles`: Write generated components to files 72 | - `figmaToReactWorkflow`: Complete workflow to convert Figma designs to React components 73 | 74 | ## Example Workflow 75 | 76 | 1. Get a Figma file key (the string after `figma.com/file/` in the URL) 77 | 2. Use the `figmaToReactWorkflow` tool with the file key and output directory 78 | 3. The tool will extract components, generate React code, and save the files 79 | 80 | ## Development 81 | 82 | For development, you can use the watch mode: 83 | 84 | ```bash 85 | npm run dev 86 | ``` 87 | 88 | ## License 89 | 90 | ISC -------------------------------------------------------------------------------- /src/figma-client.ts: -------------------------------------------------------------------------------- 1 | import axios from 'axios'; 2 | 3 | // Define types for Figma API responses 4 | export interface FigmaNode { 5 | id: string; 6 | name: string; 7 | type: string; 8 | [key: string]: any; 9 | } 10 | 11 | export interface GetFileResponse { 12 | document: { 13 | children: FigmaNode[]; 14 | [key: string]: any; 15 | }; 16 | components: Record; 17 | styles: Record; 18 | [key: string]: any; 19 | } 20 | 21 | export interface GetFileNodesResponse { 22 | nodes: Record; 25 | styles?: Record; 26 | [key: string]: any; 27 | }>; 28 | } 29 | 30 | export class FigmaClient { 31 | private token: string; 32 | private baseUrl = 'https://api.figma.com/v1'; 33 | 34 | constructor(token: string) { 35 | this.token = token; 36 | } 37 | 38 | async getFile(fileKey: string): Promise { 39 | try { 40 | const response = await axios.get( 41 | `${this.baseUrl}/files/${fileKey}`, 42 | { 43 | headers: { 44 | 'X-Figma-Token': this.token 45 | } 46 | } 47 | ); 48 | return response.data; 49 | } catch (error) { 50 | if (axios.isAxiosError(error)) { 51 | throw new Error(`Figma API error: ${error.response?.data?.message || error.message}`); 52 | } 53 | throw error; 54 | } 55 | } 56 | 57 | async getFileNodes(fileKey: string, nodeIds: string[]): Promise { 58 | try { 59 | const response = await axios.get( 60 | `${this.baseUrl}/files/${fileKey}/nodes`, 61 | { 62 | params: { ids: nodeIds.join(',') }, 63 | headers: { 64 | 'X-Figma-Token': this.token 65 | } 66 | } 67 | ); 68 | return response.data; 69 | } catch (error) { 70 | if (axios.isAxiosError(error)) { 71 | throw new Error(`Figma API error: ${error.response?.data?.message || error.message}`); 72 | } 73 | throw error; 74 | } 75 | } 76 | 77 | async getImageFills(fileKey: string, nodeIds: string[]): Promise> { 78 | try { 79 | const response = await axios.get( 80 | `${this.baseUrl}/images/${fileKey}`, 81 | { 82 | params: { ids: nodeIds.join(','), format: 'png' }, 83 | headers: { 84 | 'X-Figma-Token': this.token 85 | } 86 | } 87 | ); 88 | return response.data.images || {}; 89 | } catch (error) { 90 | if (axios.isAxiosError(error)) { 91 | throw new Error(`Figma API error: ${error.response?.data?.message || error.message}`); 92 | } 93 | throw error; 94 | } 95 | } 96 | 97 | async getComponentSets(fileKey: string): Promise { 98 | try { 99 | const response = await axios.get( 100 | `${this.baseUrl}/files/${fileKey}/component_sets`, 101 | { 102 | headers: { 103 | 'X-Figma-Token': this.token 104 | } 105 | } 106 | ); 107 | return response.data; 108 | } catch (error) { 109 | if (axios.isAxiosError(error)) { 110 | throw new Error(`Figma API error: ${error.response?.data?.message || error.message}`); 111 | } 112 | throw error; 113 | } 114 | } 115 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; 3 | import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; 4 | import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'; 5 | import express from 'express'; 6 | import { FigmaClient } from './figma-client.js'; 7 | import { registerFigmaTools } from './figma-tools.js'; 8 | import { ComponentGenerator } from './component-generator.js'; 9 | import { registerReactTools } from './figma-react-tools.js'; 10 | 11 | // Get Figma API token from environment variable 12 | const FIGMA_API_TOKEN = process.env.FIGMA_API_TOKEN; 13 | if (!FIGMA_API_TOKEN) { 14 | console.error('FIGMA_API_TOKEN environment variable is required'); 15 | process.exit(1); 16 | } 17 | 18 | // Create the MCP server 19 | const server = new McpServer({ 20 | name: 'Figma to React Converter', 21 | version: '1.0.0', 22 | description: 'MCP server for converting Figma designs to React components' 23 | }); 24 | 25 | // Initialize Figma client and component generator 26 | const figmaClient = new FigmaClient(FIGMA_API_TOKEN); 27 | const componentGenerator = new ComponentGenerator(); 28 | 29 | // Register tools with the server 30 | registerFigmaTools(server, figmaClient); 31 | registerReactTools(server, componentGenerator, figmaClient); 32 | 33 | // Determine the transport to use based on command-line arguments 34 | const transportArg = process.argv.find(arg => arg.startsWith('--transport=')); 35 | const transportType = transportArg ? transportArg.split('=')[1] : 'stdio'; 36 | 37 | async function main() { 38 | try { 39 | if (transportType === 'stdio') { 40 | // Use stdio transport for local MCP server 41 | const transport = new StdioServerTransport(); 42 | await server.connect(transport); 43 | console.error('Figma to React MCP server running on stdio'); 44 | } else if (transportType === 'sse') { 45 | // Set up Express server 46 | const app = express(); 47 | const port = process.env.PORT ? parseInt(process.env.PORT) : 3000; 48 | 49 | app.use(express.json()); 50 | 51 | // Health check endpoint 52 | app.get('/health', (_req, res) => { 53 | res.status(200).send('OK'); 54 | }); 55 | 56 | // SSE endpoint 57 | app.get('/sse', async (req: express.Request, res: express.Response) => { 58 | res.setHeader('Content-Type', 'text/event-stream'); 59 | res.setHeader('Cache-Control', 'no-cache'); 60 | res.setHeader('Connection', 'keep-alive'); 61 | 62 | const transport = new SSEServerTransport('/messages', res); 63 | await server.connect(transport); 64 | 65 | req.on('close', async () => { 66 | await server.close(); 67 | }); 68 | }); 69 | 70 | // Message endpoint 71 | app.post('/messages', express.json(), async (req: express.Request, res: express.Response) => { 72 | // This endpoint would be used by the client to send messages to the server 73 | res.status(200).json({ status: 'ok' }); 74 | }); 75 | 76 | // Start the Express server 77 | const httpServer = app.listen(port, () => { 78 | console.error(`Figma to React MCP server running on port ${port}`); 79 | }); 80 | 81 | // Handle server shutdown 82 | process.on('SIGINT', async () => { 83 | console.error('Shutting down server...'); 84 | await server.close(); 85 | httpServer.close(); 86 | process.exit(0); 87 | }); 88 | } else { 89 | console.error(`Unsupported transport type: ${transportType}`); 90 | process.exit(1); 91 | } 92 | } catch (error) { 93 | console.error('Error starting server:', error); 94 | process.exit(1); 95 | } 96 | } 97 | 98 | // Start the server 99 | main().catch(console.error); -------------------------------------------------------------------------------- /src/figma-tools.ts: -------------------------------------------------------------------------------- 1 | import { FigmaClient } from './figma-client.js'; 2 | import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; 3 | import { z } from 'zod'; 4 | 5 | export function registerFigmaTools(server: McpServer, figmaClient: FigmaClient): void { 6 | // Register getFigmaProject tool 7 | server.tool( 8 | 'getFigmaProject', 9 | { 10 | fileKey: z.string().describe('Figma file key') 11 | }, 12 | async ({ fileKey }) => { 13 | try { 14 | const fileData = await figmaClient.getFile(fileKey); 15 | return { 16 | content: [ 17 | { 18 | type: 'text', 19 | text: JSON.stringify({ 20 | name: fileData.name, 21 | documentId: fileData.document.id, 22 | lastModified: fileData.lastModified, 23 | version: fileData.version, 24 | componentCount: Object.keys(fileData.components || {}).length, 25 | styleCount: Object.keys(fileData.styles || {}).length 26 | }, null, 2) 27 | } 28 | ] 29 | }; 30 | } catch (error) { 31 | return { 32 | isError: true, 33 | content: [ 34 | { 35 | type: 'text', 36 | text: `Failed to get Figma project: ${error instanceof Error ? error.message : String(error)}` 37 | } 38 | ] 39 | }; 40 | } 41 | } 42 | ); 43 | 44 | // Register getFigmaComponentNodes tool 45 | server.tool( 46 | 'getFigmaComponentNodes', 47 | { 48 | fileKey: z.string().describe('Figma file key'), 49 | nodeIds: z.array(z.string()).describe('Node IDs to fetch') 50 | }, 51 | async ({ fileKey, nodeIds }) => { 52 | try { 53 | const nodesData = await figmaClient.getFileNodes(fileKey, nodeIds); 54 | return { 55 | content: [ 56 | { 57 | type: 'text', 58 | text: JSON.stringify(nodesData.nodes, null, 2) 59 | } 60 | ] 61 | }; 62 | } catch (error) { 63 | return { 64 | isError: true, 65 | content: [ 66 | { 67 | type: 'text', 68 | text: `Failed to get Figma component nodes: ${error instanceof Error ? error.message : String(error)}` 69 | } 70 | ] 71 | }; 72 | } 73 | } 74 | ); 75 | 76 | // Register extractFigmaComponents tool 77 | server.tool( 78 | 'extractFigmaComponents', 79 | { 80 | fileKey: z.string().describe('Figma file key') 81 | }, 82 | async ({ fileKey }) => { 83 | try { 84 | const fileData = await figmaClient.getFile(fileKey); 85 | 86 | // Find all components in the file 87 | const components: Array<{ id: string, name: string, type: string }> = []; 88 | 89 | // Helper function to recursively traverse the document 90 | function findComponents(node: any) { 91 | if (node.type === 'COMPONENT' || node.type === 'COMPONENT_SET') { 92 | components.push({ 93 | id: node.id, 94 | name: node.name, 95 | type: node.type 96 | }); 97 | } 98 | 99 | if (node.children) { 100 | for (const child of node.children) { 101 | findComponents(child); 102 | } 103 | } 104 | } 105 | 106 | // Start traversal from the document root 107 | findComponents(fileData.document); 108 | 109 | return { 110 | content: [ 111 | { 112 | type: 'text', 113 | text: JSON.stringify({ components }, null, 2) 114 | } 115 | ] 116 | }; 117 | } catch (error) { 118 | return { 119 | isError: true, 120 | content: [ 121 | { 122 | type: 'text', 123 | text: `Failed to extract Figma components: ${error instanceof Error ? error.message : String(error)}` 124 | } 125 | ] 126 | }; 127 | } 128 | } 129 | ); 130 | 131 | // Register getFigmaComponentSets tool 132 | server.tool( 133 | 'getFigmaComponentSets', 134 | { 135 | fileKey: z.string().describe('Figma file key') 136 | }, 137 | async ({ fileKey }) => { 138 | try { 139 | const componentSets = await figmaClient.getComponentSets(fileKey); 140 | return { 141 | content: [ 142 | { 143 | type: 'text', 144 | text: JSON.stringify(componentSets, null, 2) 145 | } 146 | ] 147 | }; 148 | } catch (error) { 149 | return { 150 | isError: true, 151 | content: [ 152 | { 153 | type: 'text', 154 | text: `Failed to get Figma component sets: ${error instanceof Error ? error.message : String(error)}` 155 | } 156 | ] 157 | }; 158 | } 159 | } 160 | ); 161 | } -------------------------------------------------------------------------------- /src/accessibility.ts: -------------------------------------------------------------------------------- 1 | import { FigmaNode } from './figma-client.js'; 2 | 3 | // Determine the likely heading level based on font size and other properties 4 | function determineLikelyHeadingLevel(figmaNode: any): number { 5 | if (!figmaNode.style) return 2; // Default to h2 if no style information 6 | 7 | const { fontSize, fontWeight } = figmaNode.style; 8 | 9 | // Use font size as the primary indicator 10 | if (fontSize >= 32) return 1; 11 | if (fontSize >= 24) return 2; 12 | if (fontSize >= 20) return 3; 13 | if (fontSize >= 18) return 4; 14 | if (fontSize >= 16) return 5; 15 | return 6; 16 | } 17 | 18 | // Check if a node is likely a button based on its properties 19 | function isLikelyButton(figmaNode: FigmaNode): boolean { 20 | // Check name for button-related keywords 21 | const nameLower = figmaNode.name.toLowerCase(); 22 | if (nameLower.includes('button') || nameLower.includes('btn')) return true; 23 | 24 | // Check for common button styles 25 | if (figmaNode.cornerRadius && figmaNode.cornerRadius > 0) { 26 | // Buttons often have rounded corners 27 | if (figmaNode.fills && figmaNode.fills.length > 0) { 28 | // Buttons typically have a background fill 29 | return true; 30 | } 31 | } 32 | 33 | return false; 34 | } 35 | 36 | // Check if a node is likely an image 37 | function isLikelyImage(figmaNode: FigmaNode): boolean { 38 | if (figmaNode.type === 'IMAGE') return true; 39 | 40 | const nameLower = figmaNode.name.toLowerCase(); 41 | if (nameLower.includes('image') || nameLower.includes('img') || nameLower.includes('icon')) return true; 42 | 43 | // Check for image fills 44 | if (figmaNode.fills) { 45 | for (const fill of figmaNode.fills) { 46 | if (fill.type === 'IMAGE') return true; 47 | } 48 | } 49 | 50 | return false; 51 | } 52 | 53 | // Check if a node is likely an input field 54 | function isLikelyInputField(figmaNode: FigmaNode): boolean { 55 | const nameLower = figmaNode.name.toLowerCase(); 56 | return nameLower.includes('input') || 57 | nameLower.includes('field') || 58 | nameLower.includes('text field') || 59 | nameLower.includes('form field'); 60 | } 61 | 62 | // Generate appropriate alt text for an image 63 | function generateAltText(figmaNode: FigmaNode): string { 64 | // Start with the node name 65 | let altText = figmaNode.name; 66 | 67 | // Remove common prefixes/suffixes that aren't useful in alt text 68 | altText = altText.replace(/^(img|image|icon|pic|picture)[-_\s]*/i, ''); 69 | altText = altText.replace(/[-_\s]*(img|image|icon|pic|picture)$/i, ''); 70 | 71 | // If the alt text is empty or just contains "image" or similar, use a more generic description 72 | if (!altText || /^(img|image|icon|pic|picture)$/i.test(altText)) { 73 | altText = 'Image'; 74 | } 75 | 76 | return altText; 77 | } 78 | 79 | export function enhanceWithAccessibility(jsx: string, figmaNode: FigmaNode): string { 80 | let enhancedJsx = jsx; 81 | 82 | // Add appropriate ARIA attributes based on component type 83 | if (figmaNode.type === 'TEXT' || (figmaNode.characters && figmaNode.characters.length > 0)) { 84 | // For text elements, check if they might be headings 85 | if (figmaNode.style && figmaNode.style.fontSize >= 16) { 86 | const headingLevel = determineLikelyHeadingLevel(figmaNode); 87 | enhancedJsx = enhancedJsx.replace(/]*)>(.*?)<\/div>/g, `$2`); 88 | } 89 | } 90 | 91 | // Add alt text to images 92 | if (isLikelyImage(figmaNode)) { 93 | const altText = generateAltText(figmaNode); 94 | if (enhancedJsx.includes(']*)>/g, ``); 96 | } else if (enhancedJsx.includes(']*)>/g, ``); 98 | } else { 99 | // If it's a div with a background image, add role="img" and aria-label 100 | enhancedJsx = enhancedJsx.replace( 101 | /]*)>/g, 102 | `` 103 | ); 104 | } 105 | } 106 | 107 | // Add appropriate role attributes for interactive elements 108 | if (isLikelyButton(figmaNode)) { 109 | if (!enhancedJsx.includes(']*)>/g, 112 | ' e.key === "Enter" && onClick && onClick(e)}>' 113 | ); 114 | 115 | // If there's an onClick handler, make sure it's keyboard accessible 116 | enhancedJsx = enhancedJsx.replace( 117 | /onClick={([^}]+)}/g, 118 | 'onClick={$1}' 119 | ); 120 | } 121 | } 122 | 123 | // Add label and appropriate attributes for input fields 124 | if (isLikelyInputField(figmaNode)) { 125 | const inputId = `input-${figmaNode.id.replace(/[^a-zA-Z0-9]/g, '-')}`; 126 | const labelText = figmaNode.name.replace(/input|field|text field|form field/gi, '').trim() || 'Input'; 127 | 128 | if (enhancedJsx.includes(']*)>/g, 131 | `` 132 | ); 133 | } else { 134 | // If it's a div that should be an input, transform it 135 | enhancedJsx = enhancedJsx.replace( 136 | /]*)>(.*?)<\/div>/g, 137 | `` 138 | ); 139 | } 140 | } 141 | 142 | return enhancedJsx; 143 | } -------------------------------------------------------------------------------- /src/figma-tailwind-converter.ts: -------------------------------------------------------------------------------- 1 | // Helper functions for color conversion 2 | function rgbToHex(r: number, g: number, b: number): string { 3 | return '#' + [r, g, b] 4 | .map(x => Math.round(x).toString(16).padStart(2, '0')) 5 | .join(''); 6 | } 7 | 8 | // Map RGB color to closest Tailwind color 9 | function mapToTailwindColor(hexColor: string): string { 10 | // This is a simplified implementation 11 | // In a real-world scenario, you would have a more comprehensive mapping 12 | const tailwindColors: Record = { 13 | '#000000': 'text-black', 14 | '#ffffff': 'text-white', 15 | '#ef4444': 'text-red-500', 16 | '#3b82f6': 'text-blue-500', 17 | '#10b981': 'text-green-500', 18 | '#f59e0b': 'text-yellow-500', 19 | '#6366f1': 'text-indigo-500', 20 | '#8b5cf6': 'text-purple-500', 21 | '#ec4899': 'text-pink-500', 22 | '#6b7280': 'text-gray-500', 23 | // Add more color mappings as needed 24 | }; 25 | 26 | // Find the closest color by calculating the distance in RGB space 27 | let minDistance = Number.MAX_VALUE; 28 | let closestColor = 'text-black'; 29 | 30 | const r1 = parseInt(hexColor.slice(1, 3), 16); 31 | const g1 = parseInt(hexColor.slice(3, 5), 16); 32 | const b1 = parseInt(hexColor.slice(5, 7), 16); 33 | 34 | for (const [color, className] of Object.entries(tailwindColors)) { 35 | const r2 = parseInt(color.slice(1, 3), 16); 36 | const g2 = parseInt(color.slice(3, 5), 16); 37 | const b2 = parseInt(color.slice(5, 7), 16); 38 | 39 | const distance = Math.sqrt( 40 | Math.pow(r1 - r2, 2) + Math.pow(g1 - g2, 2) + Math.pow(b1 - b2, 2) 41 | ); 42 | 43 | if (distance < minDistance) { 44 | minDistance = distance; 45 | closestColor = className; 46 | } 47 | } 48 | 49 | return closestColor; 50 | } 51 | 52 | // Map font size to Tailwind class 53 | function mapFontSizeToTailwind(fontSize: number): string { 54 | if (fontSize <= 12) return 'text-xs'; 55 | if (fontSize <= 14) return 'text-sm'; 56 | if (fontSize <= 16) return 'text-base'; 57 | if (fontSize <= 18) return 'text-lg'; 58 | if (fontSize <= 20) return 'text-xl'; 59 | if (fontSize <= 24) return 'text-2xl'; 60 | if (fontSize <= 30) return 'text-3xl'; 61 | if (fontSize <= 36) return 'text-4xl'; 62 | if (fontSize <= 48) return 'text-5xl'; 63 | return 'text-6xl'; 64 | } 65 | 66 | // Map font weight to Tailwind class 67 | function mapFontWeightToTailwind(fontWeight: number): string { 68 | if (fontWeight < 400) return 'font-light'; 69 | if (fontWeight < 500) return 'font-normal'; 70 | if (fontWeight < 600) return 'font-medium'; 71 | if (fontWeight < 700) return 'font-semibold'; 72 | return 'font-bold'; 73 | } 74 | 75 | // Map size values to Tailwind size classes 76 | function mapToTailwindSize(size: number): string { 77 | // This is a simplified implementation 78 | if (size <= 4) return '1'; 79 | if (size <= 8) return '2'; 80 | if (size <= 12) return '3'; 81 | if (size <= 16) return '4'; 82 | if (size <= 20) return '5'; 83 | if (size <= 24) return '6'; 84 | if (size <= 32) return '8'; 85 | if (size <= 40) return '10'; 86 | if (size <= 48) return '12'; 87 | if (size <= 64) return '16'; 88 | if (size <= 80) return '20'; 89 | if (size <= 96) return '24'; 90 | if (size <= 128) return '32'; 91 | if (size <= 160) return '40'; 92 | if (size <= 192) return '48'; 93 | if (size <= 256) return '64'; 94 | if (size <= 320) return '80'; 95 | if (size <= 384) return '96'; 96 | return 'full'; 97 | } 98 | 99 | export function convertFigmaStylesToTailwind(figmaStyles: any): string[] { 100 | const tailwindClasses: string[] = []; 101 | 102 | // Convert colors 103 | if (figmaStyles.fills && figmaStyles.fills.length > 0) { 104 | const fill = figmaStyles.fills[0]; 105 | if (fill && fill.type === 'SOLID') { 106 | const { r, g, b } = fill.color; 107 | // Convert RGB to hex and find closest Tailwind color 108 | const hexColor = rgbToHex(r * 255, g * 255, b * 255); 109 | const tailwindColor = mapToTailwindColor(hexColor); 110 | tailwindClasses.push(tailwindColor); 111 | 112 | // Add opacity if needed 113 | if (fill.opacity && fill.opacity < 1) { 114 | const opacityValue = Math.round(fill.opacity * 100); 115 | tailwindClasses.push(`opacity-${opacityValue}`); 116 | } 117 | } 118 | } 119 | 120 | // Convert typography 121 | if (figmaStyles.style) { 122 | const { fontSize, fontWeight, lineHeight, letterSpacing } = figmaStyles.style; 123 | 124 | // Map font size to Tailwind classes 125 | if (fontSize) { 126 | tailwindClasses.push(mapFontSizeToTailwind(fontSize)); 127 | } 128 | 129 | // Map font weight 130 | if (fontWeight) { 131 | tailwindClasses.push(mapFontWeightToTailwind(fontWeight)); 132 | } 133 | 134 | // Map line height 135 | if (lineHeight) { 136 | // Simplified mapping 137 | if (lineHeight <= 1) tailwindClasses.push('leading-none'); 138 | else if (lineHeight <= 1.25) tailwindClasses.push('leading-tight'); 139 | else if (lineHeight <= 1.5) tailwindClasses.push('leading-normal'); 140 | else if (lineHeight <= 1.75) tailwindClasses.push('leading-relaxed'); 141 | else tailwindClasses.push('leading-loose'); 142 | } 143 | 144 | // Map letter spacing 145 | if (letterSpacing) { 146 | // Simplified mapping 147 | if (letterSpacing <= -0.05) tailwindClasses.push('tracking-tighter'); 148 | else if (letterSpacing <= 0) tailwindClasses.push('tracking-tight'); 149 | else if (letterSpacing <= 0.05) tailwindClasses.push('tracking-normal'); 150 | else if (letterSpacing <= 0.1) tailwindClasses.push('tracking-wide'); 151 | else tailwindClasses.push('tracking-wider'); 152 | } 153 | } 154 | 155 | // Convert layout properties 156 | if (figmaStyles.absoluteBoundingBox) { 157 | const { width, height } = figmaStyles.absoluteBoundingBox; 158 | tailwindClasses.push(`w-${mapToTailwindSize(width)}`); 159 | tailwindClasses.push(`h-${mapToTailwindSize(height)}`); 160 | } 161 | 162 | // Convert border radius 163 | if (figmaStyles.cornerRadius) { 164 | if (figmaStyles.cornerRadius <= 2) tailwindClasses.push('rounded-sm'); 165 | else if (figmaStyles.cornerRadius <= 4) tailwindClasses.push('rounded'); 166 | else if (figmaStyles.cornerRadius <= 6) tailwindClasses.push('rounded-md'); 167 | else if (figmaStyles.cornerRadius <= 8) tailwindClasses.push('rounded-lg'); 168 | else if (figmaStyles.cornerRadius <= 12) tailwindClasses.push('rounded-xl'); 169 | else if (figmaStyles.cornerRadius <= 16) tailwindClasses.push('rounded-2xl'); 170 | else if (figmaStyles.cornerRadius <= 24) tailwindClasses.push('rounded-3xl'); 171 | else tailwindClasses.push('rounded-full'); 172 | } 173 | 174 | // Convert borders 175 | if (figmaStyles.strokes && figmaStyles.strokes.length > 0) { 176 | const stroke = figmaStyles.strokes[0]; 177 | if (stroke && stroke.type === 'SOLID') { 178 | const { r, g, b } = stroke.color; 179 | const hexColor = rgbToHex(r * 255, g * 255, b * 255); 180 | const tailwindColor = mapToTailwindColor(hexColor).replace('text-', 'border-'); 181 | tailwindClasses.push(tailwindColor); 182 | 183 | // Border width 184 | if (figmaStyles.strokeWeight) { 185 | if (figmaStyles.strokeWeight <= 1) tailwindClasses.push('border'); 186 | else if (figmaStyles.strokeWeight <= 2) tailwindClasses.push('border-2'); 187 | else if (figmaStyles.strokeWeight <= 4) tailwindClasses.push('border-4'); 188 | else tailwindClasses.push('border-8'); 189 | } 190 | } 191 | } 192 | 193 | // Convert shadows 194 | if (figmaStyles.effects) { 195 | const shadowEffect = figmaStyles.effects.find((effect: any) => effect.type === 'DROP_SHADOW'); 196 | if (shadowEffect) { 197 | if (shadowEffect.offset.x === 0 && shadowEffect.offset.y === 1 && shadowEffect.radius <= 2) { 198 | tailwindClasses.push('shadow-sm'); 199 | } else if (shadowEffect.offset.y <= 3 && shadowEffect.radius <= 4) { 200 | tailwindClasses.push('shadow'); 201 | } else if (shadowEffect.offset.y <= 8 && shadowEffect.radius <= 10) { 202 | tailwindClasses.push('shadow-md'); 203 | } else if (shadowEffect.offset.y <= 15 && shadowEffect.radius <= 15) { 204 | tailwindClasses.push('shadow-lg'); 205 | } else { 206 | tailwindClasses.push('shadow-xl'); 207 | } 208 | } 209 | } 210 | 211 | return tailwindClasses; 212 | } -------------------------------------------------------------------------------- /src/figma-react-tools.ts: -------------------------------------------------------------------------------- 1 | import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; 2 | import { z } from 'zod'; 3 | import { ComponentGenerator } from './component-generator.js'; 4 | import { FigmaClient, FigmaNode } from './figma-client.js'; 5 | import * as fs from 'fs/promises'; 6 | import * as path from 'path'; 7 | 8 | export function registerReactTools(server: McpServer, componentGenerator: ComponentGenerator, figmaClient: FigmaClient): void { 9 | // Register generateReactComponent tool 10 | server.tool( 11 | 'generateReactComponent', 12 | { 13 | componentName: z.string().describe('Name for the React component'), 14 | figmaNodeId: z.string().describe('Figma node ID'), 15 | fileKey: z.string().describe('Figma file key') 16 | }, 17 | async ({ componentName, figmaNodeId, fileKey }) => { 18 | try { 19 | // Get the Figma node data 20 | const nodeData = await figmaClient.getFileNodes(fileKey, [figmaNodeId]); 21 | const figmaNode = nodeData.nodes[figmaNodeId]?.document; 22 | 23 | if (!figmaNode) { 24 | return { 25 | isError: true, 26 | content: [ 27 | { 28 | type: 'text', 29 | text: `Figma node with ID ${figmaNodeId} not found` 30 | } 31 | ] 32 | }; 33 | } 34 | 35 | // Generate the React component 36 | const componentCode = await componentGenerator.generateReactComponent(componentName, figmaNode); 37 | 38 | return { 39 | content: [ 40 | { 41 | type: 'text', 42 | text: componentCode 43 | } 44 | ] 45 | }; 46 | } catch (error) { 47 | return { 48 | isError: true, 49 | content: [ 50 | { 51 | type: 'text', 52 | text: `Failed to generate React component: ${error instanceof Error ? error.message : String(error)}` 53 | } 54 | ] 55 | }; 56 | } 57 | } 58 | ); 59 | 60 | // Register generateComponentLibrary tool 61 | server.tool( 62 | 'generateComponentLibrary', 63 | { 64 | components: z.array( 65 | z.object({ 66 | name: z.string(), 67 | nodeId: z.string() 68 | }) 69 | ).describe('Components to generate'), 70 | fileKey: z.string().describe('Figma file key') 71 | }, 72 | async ({ components, fileKey }) => { 73 | try { 74 | // Get all node IDs 75 | const nodeIds = components.map(comp => comp.nodeId); 76 | 77 | // Get the Figma node data for all components 78 | const nodesData = await figmaClient.getFileNodes(fileKey, nodeIds); 79 | 80 | // Prepare the components for generation 81 | const componentsForGeneration = components 82 | .filter(comp => nodesData.nodes[comp.nodeId]?.document) 83 | .map(comp => ({ 84 | name: comp.name, 85 | node: nodesData.nodes[comp.nodeId].document 86 | })); 87 | 88 | // Generate the component library 89 | const generatedComponents = await componentGenerator.generateComponentLibrary(componentsForGeneration); 90 | 91 | return { 92 | content: [ 93 | { 94 | type: 'text', 95 | text: JSON.stringify( 96 | Object.entries(generatedComponents).map(([name, code]) => ({ 97 | name, 98 | code 99 | })), 100 | null, 101 | 2 102 | ) 103 | } 104 | ] 105 | }; 106 | } catch (error) { 107 | return { 108 | isError: true, 109 | content: [ 110 | { 111 | type: 'text', 112 | text: `Failed to generate component library: ${error instanceof Error ? error.message : String(error)}` 113 | } 114 | ] 115 | }; 116 | } 117 | } 118 | ); 119 | 120 | // Register writeComponentsToFiles tool 121 | server.tool( 122 | 'writeComponentsToFiles', 123 | { 124 | components: z.array( 125 | z.object({ 126 | name: z.string(), 127 | code: z.string() 128 | }) 129 | ).describe('Components to write to files'), 130 | outputDir: z.string().describe('Output directory') 131 | }, 132 | async ({ components, outputDir }) => { 133 | try { 134 | // Create the output directory if it doesn't exist 135 | await fs.mkdir(outputDir, { recursive: true }); 136 | 137 | // Write each component to a file 138 | const results = await Promise.all( 139 | components.map(async (component) => { 140 | const fileName = `${component.name}.tsx`; 141 | const filePath = path.join(outputDir, fileName); 142 | 143 | await fs.writeFile(filePath, component.code, 'utf-8'); 144 | 145 | return { 146 | name: component.name, 147 | path: filePath 148 | }; 149 | }) 150 | ); 151 | 152 | return { 153 | content: [ 154 | { 155 | type: 'text', 156 | text: JSON.stringify({ results }, null, 2) 157 | } 158 | ] 159 | }; 160 | } catch (error) { 161 | return { 162 | isError: true, 163 | content: [ 164 | { 165 | type: 'text', 166 | text: `Failed to write components to files: ${error instanceof Error ? error.message : String(error)}` 167 | } 168 | ] 169 | }; 170 | } 171 | } 172 | ); 173 | 174 | // Register figmaToReactWorkflow tool 175 | server.tool( 176 | 'figmaToReactWorkflow', 177 | { 178 | fileKey: z.string().describe('Figma file key'), 179 | outputDir: z.string().describe('Output directory for components') 180 | }, 181 | async ({ fileKey, outputDir }) => { 182 | try { 183 | // Step 1: Extract components from Figma file 184 | const fileData = await figmaClient.getFile(fileKey); 185 | 186 | // Find all components in the file 187 | const components: Array<{ id: string, name: string, type: string }> = []; 188 | 189 | // Helper function to recursively traverse the document 190 | function findComponents(node: any) { 191 | if (node.type === 'COMPONENT' || node.type === 'COMPONENT_SET') { 192 | components.push({ 193 | id: node.id, 194 | name: node.name, 195 | type: node.type 196 | }); 197 | } 198 | 199 | if (node.children) { 200 | for (const child of node.children) { 201 | findComponents(child); 202 | } 203 | } 204 | } 205 | 206 | // Start traversal from the document root 207 | findComponents(fileData.document); 208 | 209 | // Step 2: Get the Figma node data for all components 210 | const nodeIds = components.map(comp => comp.id); 211 | const nodesData = await figmaClient.getFileNodes(fileKey, nodeIds); 212 | 213 | // Step 3: Prepare the components for generation 214 | const componentsForGeneration = components 215 | .filter(comp => nodesData.nodes[comp.id]?.document) 216 | .map(comp => ({ 217 | name: comp.name, 218 | node: nodesData.nodes[comp.id].document 219 | })); 220 | 221 | // Step 4: Generate the component library 222 | const generatedComponents = await componentGenerator.generateComponentLibrary(componentsForGeneration); 223 | 224 | // Step 5: Create the output directory if it doesn't exist 225 | await fs.mkdir(outputDir, { recursive: true }); 226 | 227 | // Step 6: Write each component to a file 228 | const results = await Promise.all( 229 | Object.entries(generatedComponents).map(async ([name, code]) => { 230 | const fileName = `${name}.tsx`; 231 | const filePath = path.join(outputDir, fileName); 232 | 233 | await fs.writeFile(filePath, code, 'utf-8'); 234 | 235 | return { 236 | name, 237 | path: filePath 238 | }; 239 | }) 240 | ); 241 | 242 | return { 243 | content: [ 244 | { 245 | type: 'text', 246 | text: JSON.stringify({ 247 | componentsFound: components.length, 248 | componentsGenerated: results.length, 249 | results 250 | }, null, 2) 251 | } 252 | ] 253 | }; 254 | } catch (error) { 255 | return { 256 | isError: true, 257 | content: [ 258 | { 259 | type: 'text', 260 | text: `Failed to execute Figma to React workflow: ${error instanceof Error ? error.message : String(error)}` 261 | } 262 | ] 263 | }; 264 | } 265 | } 266 | ); 267 | } -------------------------------------------------------------------------------- /src/component-generator.ts: -------------------------------------------------------------------------------- 1 | import * as prettier from 'prettier'; 2 | import { FigmaNode } from './figma-client.js'; 3 | import { convertFigmaStylesToTailwind } from './figma-tailwind-converter.js'; 4 | import { enhanceWithAccessibility } from './accessibility.js'; 5 | 6 | interface PropDefinition { 7 | name: string; 8 | type: string; 9 | defaultValue?: string; 10 | description?: string; 11 | } 12 | 13 | interface ReactComponentParts { 14 | jsx: string; 15 | imports: string[]; 16 | props: PropDefinition[]; 17 | styles?: Record; 18 | } 19 | 20 | // Helper function to convert Figma node name to a valid React component name 21 | function toComponentName(name: string): string { 22 | // Remove invalid characters and convert to PascalCase 23 | return name 24 | .replace(/[^\w\s-]/g, '') 25 | .split(/[-_\s]+/) 26 | .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) 27 | .join(''); 28 | } 29 | 30 | // Helper function to convert Figma node name to a valid prop name 31 | function toPropName(name: string): string { 32 | // Convert to camelCase 33 | const parts = name 34 | .replace(/[^\w\s-]/g, '') 35 | .split(/[-_\s]+/); 36 | 37 | return parts[0].toLowerCase() + 38 | parts.slice(1) 39 | .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) 40 | .join(''); 41 | } 42 | 43 | // Extract potential props from Figma node 44 | function extractProps(node: FigmaNode): PropDefinition[] { 45 | const props: PropDefinition[] = []; 46 | 47 | // Text content could be a prop 48 | if (node.type === 'TEXT' && node.characters) { 49 | const propName = toPropName(node.name) || 'text'; 50 | props.push({ 51 | name: propName, 52 | type: 'string', 53 | defaultValue: JSON.stringify(node.characters), 54 | description: `Text content for ${node.name}` 55 | }); 56 | } 57 | 58 | // If node has a "variant" property, it could be a prop 59 | if (node.name.toLowerCase().includes('variant')) { 60 | props.push({ 61 | name: 'variant', 62 | type: "'primary' | 'secondary' | 'outline' | 'text'", 63 | defaultValue: "'primary'", 64 | description: 'Visual variant of the component' 65 | }); 66 | } 67 | 68 | // If node looks like a button, add onClick prop 69 | if (node.name.toLowerCase().includes('button') || node.name.toLowerCase().includes('btn')) { 70 | props.push({ 71 | name: 'onClick', 72 | type: '() => void', 73 | description: 'Function called when button is clicked' 74 | }); 75 | } 76 | 77 | // If node has children that could be dynamic, add children prop 78 | if (node.children && node.children.length > 0) { 79 | // Check if it has a container-like name 80 | if ( 81 | node.name.toLowerCase().includes('container') || 82 | node.name.toLowerCase().includes('wrapper') || 83 | node.name.toLowerCase().includes('layout') || 84 | node.name.toLowerCase().includes('section') 85 | ) { 86 | props.push({ 87 | name: 'children', 88 | type: 'React.ReactNode', 89 | description: 'Child elements to render inside the component' 90 | }); 91 | } 92 | } 93 | 94 | // Add className prop for styling customization 95 | props.push({ 96 | name: 'className', 97 | type: 'string', 98 | description: 'Additional CSS classes to apply' 99 | }); 100 | 101 | return props; 102 | } 103 | 104 | // Convert a Figma node to JSX 105 | function figmaNodeToJSX(node: FigmaNode, level = 0): ReactComponentParts { 106 | const imports: string[] = []; 107 | const allProps: PropDefinition[] = []; 108 | 109 | // Default result 110 | let result: ReactComponentParts = { 111 | jsx: '', 112 | imports: [], 113 | props: [] 114 | }; 115 | 116 | // Handle different node types 117 | switch (node.type) { 118 | case 'TEXT': 119 | // Extract text content and convert to JSX 120 | const textContent = node.characters || ''; 121 | const tailwindClasses = convertFigmaStylesToTailwind(node); 122 | const textProps = extractProps(node); 123 | 124 | result = { 125 | jsx: `

{${textProps[0]?.name || 'text'}}

`, 126 | imports: [], 127 | props: textProps 128 | }; 129 | break; 130 | 131 | case 'RECTANGLE': 132 | case 'ELLIPSE': 133 | case 'POLYGON': 134 | case 'STAR': 135 | case 'VECTOR': 136 | case 'LINE': 137 | // Convert to a div with appropriate styling 138 | const shapeClasses = convertFigmaStylesToTailwind(node); 139 | 140 | result = { 141 | jsx: `
`, 142 | imports: [], 143 | props: [] 144 | }; 145 | break; 146 | 147 | case 'COMPONENT': 148 | case 'INSTANCE': 149 | case 'FRAME': 150 | case 'GROUP': 151 | // These are container elements that might have children 152 | const containerClasses = convertFigmaStylesToTailwind(node); 153 | const containerProps = extractProps(node); 154 | 155 | // Process children if they exist 156 | let childrenJSX = ''; 157 | if (node.children && node.children.length > 0) { 158 | for (const child of node.children) { 159 | const childResult = figmaNodeToJSX(child, level + 1); 160 | childrenJSX += `\n${' '.repeat(level + 1)}${childResult.jsx}`; 161 | 162 | // Collect imports and props from children 163 | imports.push(...childResult.imports); 164 | allProps.push(...childResult.props); 165 | } 166 | childrenJSX += `\n${' '.repeat(level)}`; 167 | } 168 | 169 | // If this is a component that looks like a button 170 | if (node.name.toLowerCase().includes('button') || node.name.toLowerCase().includes('btn')) { 171 | result = { 172 | jsx: ``, 176 | imports: imports, 177 | props: [...containerProps, ...allProps] 178 | }; 179 | } else { 180 | // Check if we should use children prop 181 | const hasChildrenProp = containerProps.some(p => p.name === 'children'); 182 | 183 | result = { 184 | jsx: `
${hasChildrenProp ? '{children}' : childrenJSX}
`, 187 | imports: imports, 188 | props: [...containerProps, ...(hasChildrenProp ? [] : allProps)] 189 | }; 190 | } 191 | break; 192 | 193 | case 'IMAGE': 194 | // Convert to an img tag 195 | const imageClasses = convertFigmaStylesToTailwind(node); 196 | 197 | result = { 198 | jsx: `${node.name}`, 203 | imports: [], 204 | props: [{ 205 | name: 'src', 206 | type: 'string', 207 | description: 'Image source URL' 208 | }] 209 | }; 210 | break; 211 | 212 | default: 213 | // Default to a simple div 214 | result = { 215 | jsx: `
`, 216 | imports: [], 217 | props: [] 218 | }; 219 | } 220 | 221 | return result; 222 | } 223 | 224 | export class ComponentGenerator { 225 | async generateReactComponent(componentName: string, figmaNode: FigmaNode): Promise { 226 | // Extract styles, structure, and props from Figma node 227 | const componentParts = figmaNodeToJSX(figmaNode); 228 | 229 | // Enhance with accessibility features 230 | const enhancedJSX = enhanceWithAccessibility(componentParts.jsx, figmaNode); 231 | 232 | // Deduplicate props 233 | const uniqueProps = componentParts.props.filter((prop, index, self) => 234 | index === self.findIndex(p => p.name === prop.name) 235 | ); 236 | 237 | // Create component template 238 | const componentCode = ` 239 | import React from 'react'; 240 | ${componentParts.imports.join('\n')} 241 | 242 | interface ${componentName}Props { 243 | ${uniqueProps.map(prop => 244 | `/** ${prop.description || ''} */ 245 | ${prop.name}${prop.type.includes('?') || prop.defaultValue ? '?' : ''}: ${prop.type};` 246 | ).join('\n ')} 247 | } 248 | 249 | export const ${componentName} = ({ 250 | ${uniqueProps.map(p => 251 | p.defaultValue 252 | ? `${p.name} = ${p.defaultValue}` 253 | : p.name 254 | ).join(', ')} 255 | }: ${componentName}Props) => { 256 | return ( 257 | ${enhancedJSX} 258 | ); 259 | }; 260 | `; 261 | 262 | // Format the code 263 | try { 264 | return await prettier.format(componentCode, { 265 | parser: 'typescript', 266 | singleQuote: true, 267 | trailingComma: 'es5', 268 | tabWidth: 2 269 | }); 270 | } catch (error) { 271 | console.error('Error formatting component code:', error); 272 | return componentCode; 273 | } 274 | } 275 | 276 | async generateComponentLibrary(components: Array<{ name: string, node: FigmaNode }>): Promise> { 277 | const generatedComponents: Record = {}; 278 | 279 | for (const { name, node } of components) { 280 | const componentName = toComponentName(name); 281 | generatedComponents[componentName] = await this.generateReactComponent(componentName, node); 282 | } 283 | 284 | return generatedComponents; 285 | } 286 | } --------------------------------------------------------------------------------