Debian Codegraph @

node/@patternfly/react-icons/scripts/parseRHIcons.mjs

raw
1 /* eslint-disable no-console */
2 import { promises as fs } from 'fs';
3 import path from 'path';
4 import { fileURLToPath } from 'url';
5 import { createRequire } from 'module';
6 import { icons } from '@rhds/icons/metadata.js';
7
8 // --- Configuration ---
9 // Prefix for icon keys and output filenames (e.g., "rh" produces "rh-ui-arrow-down" and "rhIconsUI.mjs")
10 const ICON_PREFIX = 'rh';
11
12 // Icon types to process. Comment out any types you don't want to parse.
13 const ICON_TYPES = [
14 'ui',
15 'standard',
16 // 'social',
17 'microns'
18 // Add new types here as they become available in @rhds/icons
19 ];
20
21 const ICON_TYPE_CLASSES = {
22 ui: '',
23 standard: 'pf-v6-icon-rh-standard',
24 // social: '',
25 microns: ''
26 };
27
28 const __dirname = path.dirname(fileURLToPath(import.meta.url));
29 const require = createRequire(import.meta.url);
30
31 // Resolve path to @rhds/icons directory structure
32 const rhdsIconsPath = require.resolve('@rhds/icons/ui/add-circle-fill.svg');
33 const RHDS_ICONS_BASE_DIR = path.dirname(path.dirname(rhdsIconsPath));
34 const OUTPUT_DIR = path.join(__dirname, 'icons');
35 // ---------------------
36
37 /**
38 * Regex to safely extract the four view box numbers from the outer <svg> tag.
39 * It handles different spacing.
40 */
41 const VIEWBOX_REGEX =
42 /<svg[^>]+viewBox="(\s*(-?\d+(\.\d+)?)\s+(-?\d+(\.\d+)?)\s+(-?\d+(\.\d+)?)\s+(-?\d+(\.\d+)?)\s*)"/i;
43
44 /**
45 * Regex to extract all 'd' attribute content from <path> elements.
46 * Uses global flag to match all paths.
47 */
48 const PATH_DATA_REGEX = /<path\s+[^>]*d="([^"]+)"/gi;
49
50 /**
51 * Processes a single SVG file to extract viewbox data and path data.
52 * @param {string} iconName The name of the icon (without .svg extension).
53 * @param {string} iconType The type/category of the icon (ui, standard, social, microns).
54 * @returns {object|null} The parsed icon object, or null on error.
55 */
56 async function processSvgFile(iconName, iconType) {
57 const typeDir = path.join(RHDS_ICONS_BASE_DIR, iconType);
58 const svgPath = path.join(typeDir, `${iconName}.svg`);
59
60 try {
61 // 1. Read the file content
62 const content = await fs.readFile(svgPath, 'utf-8');
63
64 // 2. Extract view box data
65 const viewBoxMatch = content.match(VIEWBOX_REGEX);
66 if (!viewBoxMatch) {
67 console.error(`Skipping ${iconName}: Could not find or parse viewBox attribute.`);
68 return null;
69 }
70
71 // Extract viewBox values: "xOffset yOffset width height"
72 const viewboxValues = viewBoxMatch[1].trim().split(/\s+/).map(Number);
73
74 if (viewboxValues.length !== 4 || viewboxValues.some(isNaN)) {
75 console.error(`Skipping ${iconName}: viewBox values are not valid numbers.`);
76 return null;
77 }
78
79 const [xOffset, yOffset, width, height] = viewboxValues;
80
81 // 3. Extract all path data elements
82 const pathDataMatches = [...content.matchAll(PATH_DATA_REGEX)];
83 if (!pathDataMatches || pathDataMatches.length === 0) {
84 console.error(`Skipping ${iconName}: Could not find 'd' attribute in any <path> element.`);
85 return null;
86 }
87
88 // Extract all path data values
89 const pathDataValues = pathDataMatches.map((match) => match[1]);
90
91 // If there's only one path, store as string; if multiple, store as array of objects with 'path' property
92 // (createIcon expects arrays to be SVGPathObject[] with { path: string, className?: string } structure)
93 const svgPathData =
94 pathDataValues.length === 1 ? pathDataValues[0] : pathDataValues.map((pathData) => ({ path: pathData }));
95
96 // 4. Construct the final object
97 return {
98 iconName,
99 data: {
100 xOffset,
101 yOffset,
102 width,
103 height,
104 svgPathData
105 }
106 };
107 } catch (error) {
108 console.error(`Error processing ${iconName}:`, error.message);
109 return null;
110 }
111 }
112
113 /**
114 * Formats an object as an ES module export with proper formatting.
115 * @param {object} obj The object to format.
116 * @param {string} iconType The set of the icon.
117 * @param {number} indent The indentation level.
118 * @returns {string} Formatted module string.
119 */
120 function formatModule(obj, iconType, indent = 0) {
121 const spaces = ' '.repeat(indent);
122 const entries = Object.entries(obj);
123 if (entries.length === 0) {
124 return '{}';
125 }
126
127 const lines = ['{'];
128 entries.forEach(([key, value], index) => {
129 const isLast = index === entries.length - 1;
130 const comma = isLast ? '' : ',';
131
132 if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
133 // Escape single quotes in key
134 const escapedKey = key.replace(/'/g, "\\'");
135 lines.push(`${spaces} '${escapedKey}': {`);
136 lines.push(`${spaces} xOffset: ${value.xOffset},`);
137 lines.push(`${spaces} yOffset: ${value.yOffset},`);
138 lines.push(`${spaces} width: ${value.width},`);
139 lines.push(`${spaces} height: ${value.height},`);
140
141 // Handle set-specific svgClassName
142 if (ICON_TYPE_CLASSES[iconType]) {
143 lines.push(`${spaces} svgClassName: '${ICON_TYPE_CLASSES[iconType]}',`);
144 }
145
146 // Handle svgPathData: string or array of objects
147 if (Array.isArray(value.svgPathData)) {
148 // Array of path objects with { path: string } structure
149 lines.push(`${spaces} svgPathData: [`);
150 value.svgPathData.forEach((pathObject, idx) => {
151 const isLast = idx === value.svgPathData.length - 1;
152 const escapedPath = pathObject.path.replace(/'/g, "\\'");
153 if (pathObject.className) {
154 const escapedClassName = pathObject.className.replace(/'/g, "\\'");
155 lines.push(
156 `${spaces} { path: '${escapedPath}', className: '${escapedClassName}' }${isLast ? '' : ','}`
157 );
158 } else {
159 lines.push(`${spaces} { path: '${escapedPath}' }${isLast ? '' : ','}`);
160 }
161 });
162 lines.push(`${spaces} ]`);
163 } else {
164 // Single string path data
165 const escapedPathData = value.svgPathData.replace(/'/g, "\\'");
166 lines.push(`${spaces} svgPathData:`);
167 lines.push(`${spaces} '${escapedPathData}'`);
168 }
169 lines.push(`${spaces} }${comma}`);
170 }
171 });
172 lines.push(`${spaces}}`);
173 return lines.join('\n');
174 }
175
176 /**
177 * Processes all icons of a specific type.
178 * @param {string} iconType The type/category of icons to process.
179 * @returns {Promise<object>} Object with iconName as keys and icon data as values.
180 */
181 async function processIconType(iconType) {
182 console.log(`\nProcessing ${iconType} icons...`);
183
184 // Get icons for this type from metadata
185 const typeIcons = icons.get(iconType);
186 if (!typeIcons) {
187 console.warn(`Warning: Icon type '${iconType}' not found in metadata. Skipping.`);
188 return {};
189 }
190
191 const iconList = Array.from(typeIcons);
192 console.log(`Found ${iconList.length} ${iconType} icons to process...`);
193
194 try {
195 // Process all SVGs concurrently
196 const processingPromises = iconList.map((iconName) => processSvgFile(iconName, iconType));
197 const results = await Promise.all(processingPromises);
198
199 // Filter out any icons that failed to process
200 const successfulResults = results.filter((data) => data !== null);
201
202 // Convert array to object with prefixed icon names as keys
203 const iconsObject = {};
204 successfulResults.forEach(({ iconName, data }) => {
205 const prefixedKey = `${ICON_PREFIX}-${iconType}-${iconName}`;
206 iconsObject[prefixedKey] = data;
207 });
208
209 console.log(`Successfully processed ${successfulResults.length} out of ${iconList.length} ${iconType} icons.`);
210 return iconsObject;
211 } catch (error) {
212 console.error(`Error processing ${iconType} icons:`, error);
213 return {};
214 }
215 }
216
217 /**
218 * Main function to process all icon types and create ES module files.
219 */
220 async function processSVGs() {
221 console.log(`Starting SVG processing from @rhds/icons`);
222 console.log(`Processing ${ICON_TYPES.length} icon type(s): ${ICON_TYPES.join(', ')}`);
223
224 // Ensure output directory exists
225 await fs.mkdir(OUTPUT_DIR, { recursive: true });
226
227 const results = {};
228
229 // Process each icon type
230 for (const iconType of ICON_TYPES) {
231 const iconsObject = await processIconType(iconType);
232 if (Object.keys(iconsObject).length > 0) {
233 results[iconType] = iconsObject;
234
235 // Write individual file for this type
236 // Capitalize first letter, and handle special case for 'ui' -> 'UI'
237 const capitalizedType = iconType === 'ui' ? 'UI' : iconType.charAt(0).toUpperCase() + iconType.slice(1);
238 const outputFile = path.join(OUTPUT_DIR, `rhIcons${capitalizedType}.mjs`);
239 const moduleOutput = `export default ${formatModule(iconsObject, iconType)};\n`;
240 await fs.writeFile(outputFile, moduleOutput, 'utf-8');
241 console.log(`Output written to: ${outputFile}`);
242 }
243 }
244
245 // Summary
246 console.log('\n--- SUCCESS ---');
247 const totalIcons = Object.values(results).reduce((sum, icons) => sum + Object.keys(icons).length, 0);
248 console.log(`Total icons processed: ${totalIcons}`);
249 console.log(`Icon types processed: ${Object.keys(results).join(', ')}`);
250 }
251
252 processSVGs();