|
| 1 | +/** |
| 2 | + * Shared utilities for icon generation and connection |
| 3 | + */ |
| 4 | +import path from 'path'; |
| 5 | +import { fileURLToPath } from 'url'; |
| 6 | +import fs from 'fs/promises'; |
| 7 | +import { existsSync } from 'fs'; |
| 8 | + |
| 9 | +/** |
| 10 | + * Extract node ID from a Figma URL |
| 11 | + * @param {string} url - Figma URL |
| 12 | + * @returns {string|null} - Node ID or null if not found |
| 13 | + */ |
| 14 | +export function extractNodeId(url) { |
| 15 | + if (!url) { |
| 16 | + return null; |
| 17 | + } |
| 18 | + const nodeIdMatch = url.match(/node-id=([^&]+)/); |
| 19 | + return nodeIdMatch ? nodeIdMatch[1] : null; |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | + * Extract icon names from import statement |
| 24 | + * @param {string} importStatement - The full import statement |
| 25 | + * @returns {string[]} Array of unique icon names |
| 26 | + */ |
| 27 | +export function extractIconNames(importStatement, logger) { |
| 28 | + if (!importStatement) { |
| 29 | + logger?.warn('Import statement is undefined or empty'); |
| 30 | + return []; |
| 31 | + } |
| 32 | + |
| 33 | + try { |
| 34 | + // Remove comments and extra whitespace |
| 35 | + const cleanImport = importStatement |
| 36 | + .replace(/\/\/.*|\/\*[\s\S]*?\*\//g, '') |
| 37 | + .replace(/\s+/g, ' ') |
| 38 | + .trim(); |
| 39 | + |
| 40 | + // Extract icons between { } |
| 41 | + const matchIcons = cleanImport.match(/{\s*(.+?)\s*}/); |
| 42 | + if (!matchIcons) { |
| 43 | + logger?.warn('No icon matches found in import statement'); |
| 44 | + return []; |
| 45 | + } |
| 46 | + |
| 47 | + // Split icons and clean up |
| 48 | + return [ |
| 49 | + ...new Set( |
| 50 | + matchIcons[1] |
| 51 | + .split(',') |
| 52 | + .map((icon) => icon.trim()) |
| 53 | + .filter((icon) => icon && !icon.includes('=') && !icon.startsWith('Icon Size') && !icon.includes('(')) |
| 54 | + ) |
| 55 | + ]; |
| 56 | + } catch (error) { |
| 57 | + logger?.error('Error extracting icon names', error); |
| 58 | + return []; |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * Find repo root directory |
| 64 | + * @returns {string} Path to repository root |
| 65 | + */ |
| 66 | +export function findRepoRoot() { |
| 67 | + const __filename = fileURLToPath(import.meta.url); |
| 68 | + const __dirname = path.dirname(__filename); |
| 69 | + |
| 70 | + // Traverse up the directory tree to find the repo root |
| 71 | + let currentDir = __dirname; |
| 72 | + while (currentDir !== path.dirname(currentDir)) { |
| 73 | + if (existsSync(path.join(currentDir, '.git')) || existsSync(path.join(currentDir, 'package.json'))) { |
| 74 | + return currentDir; |
| 75 | + } |
| 76 | + currentDir = path.dirname(currentDir); |
| 77 | + } |
| 78 | + return __dirname; // Fallback |
| 79 | +} |
| 80 | + |
| 81 | +/** |
| 82 | + * Load and validate icon data |
| 83 | + * @param {string} iconsDataPath - Path to icon data JSON |
| 84 | + * @param {Object} config - Configuration object |
| 85 | + * @param {Object} logger - Logger instance |
| 86 | + * @returns {Array} Array of icon data objects |
| 87 | + */ |
| 88 | +export async function loadIconData(iconsDataPath, config, logger) { |
| 89 | + try { |
| 90 | + const iconsDataContent = await fs.readFile(iconsDataPath, 'utf8'); |
| 91 | + const iconsData = JSON.parse(iconsDataContent); |
| 92 | + |
| 93 | + if (!Array.isArray(iconsData)) { |
| 94 | + logger.warn('Icon data is not an array, initializing as empty array'); |
| 95 | + return []; |
| 96 | + } |
| 97 | + |
| 98 | + // Validate icon data |
| 99 | + const validIcons = iconsData.filter((icon) => { |
| 100 | + const isValid = icon && icon.iconName && icon.fileName && icon.reactName; |
| 101 | + if (!isValid) { |
| 102 | + logger.warn(`Found invalid icon data: ${JSON.stringify(icon)}`); |
| 103 | + } |
| 104 | + return isValid; |
| 105 | + }); |
| 106 | + |
| 107 | + logger.success(`Loaded ${validIcons.length} valid icons from ${iconsDataPath}`); |
| 108 | + return validIcons; |
| 109 | + } catch (error) { |
| 110 | + logger.error('Failed to read icons data', error); |
| 111 | + |
| 112 | + // Provide example data if file is missing |
| 113 | + return [ |
| 114 | + { |
| 115 | + iconName: 'angle-down', |
| 116 | + fileName: 'angle-down-icon', |
| 117 | + reactName: 'AngleDownIcon', |
| 118 | + url: `${config.figmaBaseUrl}?node-id=${config.defaultNodeId}&m=dev`, |
| 119 | + svgPath: '<path d="M12 15.5l-6-6 1.4-1.4 4.6 4.6 4.6-4.6 1.4 1.4z" />' |
| 120 | + } |
| 121 | + ]; |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +/** |
| 126 | + * Generate a figma.connect statement for an icon |
| 127 | + * @param {string} iconName - React component name |
| 128 | + * @param {string} url - Figma URL |
| 129 | + * @returns {string} - Formatted figma.connect statement |
| 130 | + */ |
| 131 | +export function generateConnectStatement(iconName, url) { |
| 132 | + return `figma.connect(${iconName}, "${url}", { |
| 133 | + props: {}, |
| 134 | + example: (props) => <${iconName} {...props} /> |
| 135 | +});`; |
| 136 | +} |
| 137 | + |
| 138 | +/** |
| 139 | + * Find matching icon configuration by name |
| 140 | + * @param {string} iconName - React component name to find |
| 141 | + * @param {Array} iconsData - Array of icon configurations |
| 142 | + * @returns {Object|null} - Matching icon configuration or null |
| 143 | + */ |
| 144 | +export function findIconByName(iconName, iconsData) { |
| 145 | + if (!Array.isArray(iconsData)) { |
| 146 | + return null; |
| 147 | + } |
| 148 | + |
| 149 | + return iconsData.find( |
| 150 | + (icon) => |
| 151 | + icon.reactName === iconName || |
| 152 | + (icon.fileName && icon.fileName.replace('-icon', '') === iconName.replace('Icon', '').toLowerCase()) |
| 153 | + ); |
| 154 | +} |
| 155 | + |
| 156 | +/** |
| 157 | + * Generate summary statistics for icon generation |
| 158 | + * @param {Object} stats - Statistics object |
| 159 | + * @returns {string} - Formatted summary string |
| 160 | + */ |
| 161 | +export function generateSummary(stats) { |
| 162 | + const elapsedTime = stats.endTime - stats.startTime; |
| 163 | + |
| 164 | + return ` |
| 165 | +Icon Generation Summary: |
| 166 | +---------------------- |
| 167 | +Total Icons: ${stats.totalIcons} |
| 168 | +New Icons: ${stats.newIcons} |
| 169 | +Updated Icons: ${stats.updatedIcons} |
| 170 | +Errors: ${stats.errors} |
| 171 | +---------------------- |
| 172 | +Time Elapsed: ${elapsedTime}ms |
| 173 | +`; |
| 174 | +} |
0 commit comments