-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathresponsive-merger.js
More file actions
executable file
·1954 lines (1633 loc) · 67.1 KB
/
responsive-merger.js
File metadata and controls
executable file
·1954 lines (1633 loc) · 67.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* Responsive Merger - CSS-Pure Approach
*
* Merges modular components from 3 breakpoints (Desktop, Tablet, Mobile)
* into responsive components using pure CSS media queries.
*
* Usage:
* node scripts/responsive-merger.js \
* --desktop node-6055-2436-1762733564 \
* --tablet node-6055-2654-1762712319 \
* --mobile node-6055-2872-1762733537
*
* Output: src/generated/responsive-screens/responsive-merger-<TIMESTAMP>/
*/
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { parseStringPromise } from 'xml2js';
import { parse as babelParse } from '@babel/parser';
import traverseLib from '@babel/traverse';
import generateLib from '@babel/generator';
import { compileResponsiveClasses, compileResponsiveClassesPerComponent } from './responsive-css-compiler.js';
import { execute as extractPropsExecute } from './transformations/extract-props.js';
const traverseDefault = traverseLib.default || traverseLib;
const generateDefault = generateLib.default || generateLib;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const PROJECT_ROOT = path.resolve(__dirname, '..');
// ═══════════════════════════════════════════════════════════════
// ANSI COLOR CODES & LOGGING
// ═══════════════════════════════════════════════════════════════
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
dim: '\x1b[2m',
// Colors
cyan: '\x1b[36m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
red: '\x1b[31m',
gray: '\x1b[90m',
// Background
bgCyan: '\x1b[46m',
bgGreen: '\x1b[42m',
bgYellow: '\x1b[43m',
};
const log = {
phase: (title) => {
console.log(`\n${colors.bright}${colors.cyan}┌${'─'.repeat(60)}┐${colors.reset}`);
console.log(`${colors.bright}${colors.cyan}│ ${title.padEnd(58)}│${colors.reset}`);
console.log(`${colors.bright}${colors.cyan}└${'─'.repeat(60)}┘${colors.reset}\n`);
},
task: (emoji, text) => {
console.log(`${colors.bright}${emoji} ${colors.blue}${text}${colors.reset}`);
},
success: (text) => {
console.log(` ${colors.green}✓${colors.reset} ${colors.dim}${text}${colors.reset}`);
},
warning: (text) => {
console.log(` ${colors.yellow}⚠${colors.reset} ${colors.dim}${text}${colors.reset}`);
},
info: (text) => {
console.log(` ${colors.cyan}ℹ${colors.reset} ${colors.dim}${text}${colors.reset}`);
},
error: (text) => {
console.log(`\n${colors.red}✗ ${text}${colors.reset}`);
},
header: (text) => {
console.log(`\n${colors.bright}${colors.magenta}🚀 ${text}${colors.reset}\n`);
},
divider: () => {
console.log(`${colors.gray}${'─'.repeat(60)}${colors.reset}`);
}
};
// ═══════════════════════════════════════════════════════════════
// CLI ARGUMENT PARSING
// ═══════════════════════════════════════════════════════════════
/**
* Parse CLI arguments with breakpoint sizes
* Format: --desktop 1440px node-xxx --tablet 960px node-yyy --mobile 420px node-zzz
*/
function parseArguments() {
const args = process.argv.slice(2);
const desktopIdx = args.indexOf('--desktop');
const tabletIdx = args.indexOf('--tablet');
const mobileIdx = args.indexOf('--mobile');
if (desktopIdx === -1 || tabletIdx === -1 || mobileIdx === -1) {
log.error('Missing required arguments\n');
console.log(`${colors.dim}Usage: node responsive-merger.js \\`);
console.log(`${colors.dim} --desktop <width> <testId> \\`);
console.log(`${colors.dim} --tablet <width> <testId> \\`);
console.log(`${colors.dim} --mobile <width> <testId>\n${colors.reset}`);
console.log(`${colors.dim}Example:`);
console.log(`${colors.dim} node responsive-merger.js \\`);
console.log(`${colors.dim} --desktop 1440px node-6055-2436-1762733564 \\`);
console.log(`${colors.dim} --tablet 960px node-6055-2654-1762712319 \\`);
console.log(`${colors.dim} --mobile 420px node-6055-2872-1762733537${colors.reset}`);
process.exit(1);
}
// Parse width (can be "1440px", "1440", or 1440)
function parseWidth(widthStr) {
const parsed = parseInt(widthStr.toString().replace(/px/i, ''), 10);
if (isNaN(parsed) || parsed <= 0) {
log.error(`Invalid width: ${widthStr}`);
log.info('Width must be a positive number (e.g., "1440px", "1440", or 1440)');
process.exit(1);
}
return parsed;
}
const desktopWidth = parseWidth(args[desktopIdx + 1]);
const desktopId = args[desktopIdx + 2];
const tabletWidth = parseWidth(args[tabletIdx + 1]);
const tabletId = args[tabletIdx + 2];
const mobileWidth = parseWidth(args[mobileIdx + 1]);
const mobileId = args[mobileIdx + 2];
// Validation check IDs exist
if (!desktopId || !tabletId || !mobileId) {
log.error('Missing test IDs\n');
log.info('Format: --desktop <width> <testId> --tablet <width> <testId> --mobile <width> <testId>');
process.exit(1);
}
// Validate breakpoint order: Desktop > Tablet > Mobile
if (!(desktopWidth > tabletWidth && tabletWidth > mobileWidth)) {
log.error('Invalid breakpoint order!\n');
log.info(`Current: Desktop=${desktopWidth}px, Tablet=${tabletWidth}px, Mobile=${mobileWidth}px`);
log.info('Required: Desktop > Tablet > Mobile');
log.warning(`\nExample of correct order:`);
log.warning(` Desktop: 1440px (largest)`);
log.warning(` Tablet: 960px (medium)`);
log.warning(` Mobile: 420px (smallest)\n`);
process.exit(1);
}
return {
desktop: { width: desktopWidth, id: desktopId },
tablet: { width: tabletWidth, id: tabletId },
mobile: { width: mobileWidth, id: mobileId }
};
}
// ═══════════════════════════════════════════════════════════════
// VALIDATION & METADATA
// ═══════════════════════════════════════════════════════════════
function validateBreakpoint(testId, breakpointName, explicitWidth) {
const testDir = path.join(PROJECT_ROOT, 'src/generated/export_figma', testId);
if (!fs.existsSync(testDir)) {
log.error(`${breakpointName} test directory not found`);
log.info(`Looking for: ${testDir}`);
process.exit(1);
}
const componentsDir = path.join(testDir, 'components');
if (!fs.existsSync(componentsDir)) {
log.error(`${breakpointName} missing components/ directory`);
log.info('Components should be automatically generated during export');
log.info(`If missing, run: docker exec mcp-figma-v1 node scripts/post-processing/component-splitter.js ${testDir}`);
process.exit(1);
}
// Read metadata.json
const metadataPath = path.join(testDir, 'metadata.json');
if (!fs.existsSync(metadataPath)) {
log.error(`${breakpointName} missing metadata.json`);
process.exit(1);
}
const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf8'));
return {
testId,
testDir,
componentsDir,
metadata,
width: explicitWidth, // Use explicit width from CLI args
height: metadata.dimensions?.height || 0
};
}
function validateBreakpoints(breakpoints) {
log.task('🔍', 'Validating breakpoints');
const desktop = validateBreakpoint(breakpoints.desktop.id, 'Desktop', breakpoints.desktop.width);
const tablet = validateBreakpoint(breakpoints.tablet.id, 'Tablet', breakpoints.tablet.width);
const mobile = validateBreakpoint(breakpoints.mobile.id, 'Mobile', breakpoints.mobile.width);
log.success(`Desktop: ${breakpoints.desktop.id} (${breakpoints.desktop.width}px)`);
log.success(`Tablet: ${breakpoints.tablet.id} (${breakpoints.tablet.width}px)`);
log.success(`Mobile: ${breakpoints.mobile.id} (${breakpoints.mobile.width}px)\n`);
return { desktop, tablet, mobile };
}
// ═══════════════════════════════════════════════════════════════
// COMPONENT DETECTION
// ═══════════════════════════════════════════════════════════════
function getModularComponents(componentsDir) {
if (!fs.existsSync(componentsDir)) return [];
return fs.readdirSync(componentsDir)
.filter(file => file.endsWith('.tsx'))
.map(file => path.basename(file, '.tsx'))
.sort();
}
function detectCommonComponents(desktop, tablet, mobile) {
console.log('📊 Detecting common components...\n');
const desktopComps = getModularComponents(desktop.componentsDir);
const tabletComps = getModularComponents(tablet.componentsDir);
const mobileComps = getModularComponents(mobile.componentsDir);
console.log(` Desktop: ${desktopComps.length} components`);
console.log(` Tablet: ${tabletComps.length} components`);
console.log(` Mobile: ${mobileComps.length} components\n`);
// Find common components (present in all 3)
const common = desktopComps.filter(name =>
tabletComps.includes(name) && mobileComps.includes(name)
);
console.log(`✅ Found ${common.length} common components:\n`);
common.forEach(name => console.log(` - ${name}`));
console.log('');
// Warn about unique components
const desktopOnly = desktopComps.filter(n => !common.includes(n));
const tabletOnly = tabletComps.filter(n => !common.includes(n));
const mobileOnly = mobileComps.filter(n => !common.includes(n));
if (desktopOnly.length > 0) {
console.log(`⚠️ Desktop-only: ${desktopOnly.join(', ')}`);
}
if (tabletOnly.length > 0) {
console.log(`⚠️ Tablet-only: ${tabletOnly.join(', ')}`);
}
if (mobileOnly.length > 0) {
console.log(`⚠️ Mobile-only: ${mobileOnly.join(', ')}`);
}
if (desktopOnly.length + tabletOnly.length + mobileOnly.length > 0) {
console.log('');
}
if (common.length === 0) {
console.error('❌ Error: No common components found across breakpoints');
process.exit(1);
}
return common;
}
// ═══════════════════════════════════════════════════════════════
// COMPONENT ORDER (FROM DESKTOP METADATA.XML)
// ═══════════════════════════════════════════════════════════════
async function getComponentOrder(desktopDir, commonComponents) {
const metadataXmlPath = path.join(desktopDir, 'metadata.xml');
if (!fs.existsSync(metadataXmlPath)) {
console.warn('⚠️ Warning: metadata.xml not found, using alphabetical order');
return commonComponents.sort();
}
// Normalize component name: "title section" → "Titlesection"
function normalizeComponentName(name) {
return name
.split(/[\s_-]+/) // Split on spaces, underscores, hyphens
.map((word) => {
// Capitalize first letter of each word
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
})
.join('');
}
try {
const xmlContent = fs.readFileSync(metadataXmlPath, 'utf8');
const parsed = await parseStringPromise(xmlContent);
// Extract component names in order from XML
// The root element is <frame>, so parsed.frame contains the root frame object
const orderedNames = [];
function extractNames(node) {
if (!node) return;
const rawName = node.$?.name;
if (rawName) {
// Normalize the name to match component file names
const normalized = normalizeComponentName(rawName);
// Check if this normalized name matches any component
if (commonComponents.includes(normalized) && !orderedNames.includes(normalized)) {
orderedNames.push(normalized);
}
}
// Recursively process all child types as arrays
// Each child type (node, frame, instance, text) is an array
if (Array.isArray(node.instance)) {
node.instance.forEach(child => extractNames(child));
}
if (Array.isArray(node.frame)) {
node.frame.forEach(child => extractNames(child));
}
if (Array.isArray(node.node)) {
node.node.forEach(child => extractNames(child));
}
if (Array.isArray(node.text)) {
node.text.forEach(child => extractNames(child));
}
}
// Start extraction from the root <frame> element (single object, not array)
if (parsed.frame) {
extractNames(parsed.frame);
}
// Add any missing components alphabetically at the end
const missing = commonComponents.filter(c => !orderedNames.includes(c));
const finalOrder = [...orderedNames, ...missing.sort()];
console.log('📋 Component order (from Desktop metadata.xml):\n');
finalOrder.forEach((name, idx) => console.log(` ${idx + 1}. ${name}`));
console.log('');
return finalOrder;
} catch (error) {
console.warn('⚠️ Warning: Failed to parse metadata.xml, using alphabetical order');
console.warn(` Error: ${error.message}\n`);
return commonComponents.sort();
}
}
// ═══════════════════════════════════════════════════════════════
// CSS PARSING
// ═══════════════════════════════════════════════════════════════
function parseCSSIntoSections(css) {
const sections = {
imports: '',
root: '',
utilities: '',
customClasses: ''
};
// Extract @import statements (handle URLs with semicolons in query params)
const importMatches = css.match(/@import\s+(?:url\(['"].*?['"]\)|['"][^'"]*['"])[^;]*;/g);
if (importMatches) {
sections.imports = importMatches.join('\n');
}
// Extract :root variables
const rootMatch = css.match(/:root\s*\{[^}]+\}/s);
if (rootMatch) {
sections.root = rootMatch[0];
}
// Extract Figma utilities (content-start, content-end, etc.)
const utilMatch = css.match(/\/\*\s*Figma-specific utility classes\s*\*\/\n([\s\S]*?)(?=\n\/\*|$)/);
if (utilMatch) {
sections.utilities = utilMatch[0];
}
// Extract custom classes (everything else)
const sectionMarkerMatch = css.match(/\/\*\s*=====\s*[3-9]\..*?\*\/[\s\S]*$/);
if (sectionMarkerMatch) {
sections.customClasses = sectionMarkerMatch[0];
} else {
// Fallback: extract everything after utilities
const afterUtils = css.indexOf(sections.utilities) + sections.utilities.length;
sections.customClasses = css.substring(afterUtils).trim();
}
return sections;
}
function parseClassDefinitions(css) {
const map = new Map();
const regex = /\.([a-z0-9_-]+)\s*\{([^}]+)\}/gi;
let match;
while ((match = regex.exec(css)) !== null) {
const className = match[1];
const definition = `.${className} {${match[2]}}`;
map.set(className, definition);
}
return map;
}
function getClassDifferences(baseCSS, targetCSS) {
const baseClasses = parseClassDefinitions(baseCSS);
const targetClasses = parseClassDefinitions(targetCSS);
let diff = '';
for (const [className, targetDef] of targetClasses) {
const baseDef = baseClasses.get(className);
// Include if: new class OR different definition
if (!baseDef || baseDef !== targetDef) {
diff += targetDef + '\n';
}
}
return diff;
}
function mergeRootVariables(rootSections) {
const vars = new Map();
rootSections.forEach(section => {
if (!section) return;
const varPattern = /(--[a-z0-9-]+):\s*([^;]+);/g;
let match;
while ((match = varPattern.exec(section)) !== null) {
vars.set(match[1], match[2]);
}
});
if (vars.size === 0) return '';
let root = ':root {\n';
for (const [varName, value] of vars) {
root += ` ${varName}: ${value};\n`;
}
root += '}';
return root;
}
function indentCSS(css) {
return css.split('\n')
.map(line => line ? ' ' + line : line)
.join('\n');
}
// ═══════════════════════════════════════════════════════════════
// CSS MERGER (CORE ALGORITHM)
// ═══════════════════════════════════════════════════════════════
function readCSS(dir, componentName) {
const cssPath = path.join(dir, 'components', `${componentName}.css`);
return fs.existsSync(cssPath) ? fs.readFileSync(cssPath, 'utf8') : '';
}
function mergeCSS(desktopCSS, tabletCSS, mobileCSS, componentName, breakpoints) {
const desktopSections = parseCSSIntoSections(desktopCSS);
const tabletSections = parseCSSIntoSections(tabletCSS);
const mobileSections = parseCSSIntoSections(mobileCSS);
const desktopWidth = breakpoints?.desktop || 1440;
const tabletWidth = breakpoints?.tablet || 960;
const mobileWidth = breakpoints?.mobile || 420;
let merged = `/* Auto-generated responsive CSS for ${componentName} */\n`;
merged += `/* Generated by responsive-merger.js */\n`;
merged += `/* Breakpoints: Desktop ${desktopWidth}px | Tablet ${tabletWidth}px | Mobile ${mobileWidth}px */\n\n`;
// 1. Google Fonts (from desktop)
if (desktopSections.imports) {
merged += desktopSections.imports + '\n\n';
}
// 2. :root variables (merged from all 3)
const rootVars = mergeRootVariables([
desktopSections.root,
tabletSections.root,
mobileSections.root
]);
if (rootVars) {
merged += rootVars + '\n\n';
}
// 3. Utility classes (Figma-specific, from desktop)
if (desktopSections.utilities) {
merged += desktopSections.utilities + '\n\n';
}
// 4. Desktop styles (default - no media query)
merged += `/* ========== Desktop Styles (${desktopWidth}px) ========== */\n`;
merged += desktopSections.customClasses + '\n\n';
// 5. Tablet overrides (media query)
const tabletDiff = getClassDifferences(
desktopSections.customClasses,
tabletSections.customClasses
);
if (tabletDiff.trim()) {
merged += `/* ========== Tablet Overrides (≤${tabletWidth}px) ========== */\n`;
merged += `@media (max-width: ${tabletWidth}px) {\n`;
merged += indentCSS(tabletDiff);
merged += '}\n\n';
}
// 6. Mobile overrides (media query)
const mobileDiff = getClassDifferences(
tabletSections.customClasses,
mobileSections.customClasses
);
if (mobileDiff.trim()) {
merged += `/* ========== Mobile Overrides (≤${mobileWidth}px) ========== */\n`;
merged += `@media (max-width: ${mobileWidth}px) {\n`;
merged += indentCSS(mobileDiff);
merged += '}';
}
return merged;
}
// ═══════════════════════════════════════════════════════════════
// TSX RESPONSIVE MERGING (TAILWIND PREFIXES)
// ═══════════════════════════════════════════════════════════════
/**
* Extract className value from JSX element's attributes
* @param {object} jsxElement - Babel JSX element node
* @returns {string|null} - className value or null
*/
function extractClassNameFromJSX(jsxElement) {
if (!jsxElement || !jsxElement.openingElement) {
return null;
}
const classNameAttr = jsxElement.openingElement.attributes.find(
attr => attr.type === 'JSXAttribute' && attr.name?.name === 'className'
);
if (!classNameAttr || !classNameAttr.value) {
return null;
}
// Handle string literal
if (classNameAttr.value.type === 'StringLiteral') {
return classNameAttr.value.value.trim();
}
// Handle JSX expression (template string, variable, etc.)
if (classNameAttr.value.type === 'JSXExpressionContainer') {
const expr = classNameAttr.value.expression;
if (expr.type === 'StringLiteral') {
return expr.value.trim();
}
if (expr.type === 'TemplateLiteral') {
// For template literals, try to extract static parts
const staticParts = expr.quasis.map(q => q.value.cooked).join(' ');
return staticParts.trim();
}
}
return null;
}
/**
* Normalize className string (split, sort, dedupe)
* @param {string} className - Raw className string
* @returns {Array<string>} - Normalized class array
*/
function normalizeClassName(className) {
if (!className || typeof className !== 'string') {
return [];
}
return className
.trim()
.split(/\s+/)
.filter(c => c.length > 0)
.sort()
.filter((c, i, arr) => i === 0 || c !== arr[i - 1]); // Dedupe
}
/**
* Compare two className strings and return differences
* @param {string} baseClasses - Base (Desktop) className
* @param {string} targetClasses - Target (Tablet/Mobile) className
* @returns {object} - { added: [], removed: [], unchanged: [] }
*/
function diffClassNames(baseClasses, targetClasses) {
const base = new Set(normalizeClassName(baseClasses));
const target = new Set(normalizeClassName(targetClasses));
const added = [...target].filter(c => !base.has(c));
const removed = [...base].filter(c => !target.has(c));
const unchanged = [...base].filter(c => target.has(c));
return { added, removed, unchanged };
}
/**
* Merge className differences with Tailwind breakpoint prefixes
* Mobile-first approach: sm: (≥420px), md: (≥960px), lg: (≥1440px)
*
* @param {string} desktopClasses - Desktop className (default, no prefix)
* @param {string} tabletClasses - Tablet className
* @param {string} mobileClasses - Mobile className (base)
* @param {object} breakpoints - { desktop, tablet, mobile } widths
* @returns {string} - Merged responsive className
*/
function mergeClassNamesResponsive(desktopClasses, tabletClasses, mobileClasses, breakpoints) {
// Normalize all classNames
const mobile = normalizeClassName(mobileClasses);
const tablet = normalizeClassName(tabletClasses);
const desktop = normalizeClassName(desktopClasses);
// Mobile-first: start with mobile classes (no prefix)
const result = new Set(mobile);
// Find what changes from mobile → tablet
const mobileToTablet = diffClassNames(mobileClasses, tabletClasses);
// Remove mobile classes that disappear on tablet
mobileToTablet.removed.forEach(cls => result.delete(cls));
// Add tablet classes with md: prefix
mobileToTablet.added.forEach(cls => result.add(`md:${cls}`));
// Find what changes from tablet → desktop
const tabletToDesktop = diffClassNames(tabletClasses, desktopClasses);
// Remove tablet classes that disappear on desktop (with md: prefix)
tabletToDesktop.removed.forEach(cls => {
result.delete(`md:${cls}`);
result.delete(cls); // Also remove unprefixed version if exists
});
// Add desktop classes with lg: prefix
tabletToDesktop.added.forEach(cls => result.add(`lg:${cls}`));
return Array.from(result).join(' ');
}
/**
* Recursively parse JSX element and extract structure + classNames
* @param {object} jsxElement - Babel JSX element node
* @returns {object} - { dataName, className, children: [...] }
*/
function parseJSXElement(jsxElement) {
if (!jsxElement || jsxElement.type !== 'JSXElement') {
return null;
}
// Extract data-name attribute
const dataNameAttr = jsxElement.openingElement.attributes.find(
attr => attr.type === 'JSXAttribute' && attr.name?.name === 'data-name'
);
const dataName = dataNameAttr?.value?.value || null;
// Extract className
const className = extractClassNameFromJSX(jsxElement);
// Parse children recursively
const children = [];
if (jsxElement.children) {
for (const child of jsxElement.children) {
if (child.type === 'JSXElement') {
const parsed = parseJSXElement(child);
if (parsed) {
children.push(parsed);
}
}
}
}
return { dataName, className, children };
}
/**
* Merge 3 TSX files using responsive transformation pipeline
* @param {string} desktopTSX - Desktop TSX content
* @param {string} tabletTSX - Tablet TSX content
* @param {string} mobileTSX - Mobile TSX content
* @param {object} breakpoints - { desktop, tablet, mobile } widths
* @returns {Promise<{code: string, stats: object}>} - Merged responsive TSX and transformation stats
*/
async function mergeTSXStructure(desktopTSX, tabletTSX, mobileTSX, breakpoints) {
try {
// Import pipeline (dynamic import to avoid circular dependencies)
const { runResponsivePipeline, formatPipelineStats } = await import('./responsive-pipeline.js');
// Parse all 3 TSX files into AST
const desktopAST = babelParse(desktopTSX, {
sourceType: 'module',
plugins: ['jsx', 'typescript']
});
const tabletAST = babelParse(tabletTSX, {
sourceType: 'module',
plugins: ['jsx', 'typescript']
});
const mobileAST = babelParse(mobileTSX, {
sourceType: 'module',
plugins: ['jsx', 'typescript']
});
// Run responsive transformation pipeline
const config = { transforms: {} }; // All transforms enabled by default
const context = await runResponsivePipeline(
desktopAST,
tabletAST,
mobileAST,
breakpoints,
config
);
// Log pipeline statistics
if (Object.keys(context.stats).length > 0) {
const statsFormatted = formatPipelineStats(context.stats);
log.info('Responsive Pipeline Stats:\n' + statsFormatted);
}
// Generate merged TSX code from modified Desktop AST
const mergedCode = generateDefault(context.desktopAST).code;
// Return both code and stats for metadata
return {
code: mergedCode,
stats: context.stats || {}
};
} catch (err) {
log.warning(`Failed to merge TSX structures: ${err.message}`);
log.info('Falling back to Desktop TSX only');
return {
code: desktopTSX,
stats: { error: err.message }
};
}
}
// ═══════════════════════════════════════════════════════════════
// HELPER FUNCTION EXTRACTION & INJECTION
// ═══════════════════════════════════════════════════════════════
/**
* Extract helper functions from Component-optimized.tsx (or Component-clean.tsx as fallback)
* Returns Map<helperName, { code, imports }>
*/
function extractHelperFunctions(testDir, mainComponentNames) {
// Try Component-optimized.tsx first (new process), fallback to Component-clean.tsx
let componentPath = path.join(testDir, 'Component-optimized.tsx');
if (!fs.existsSync(componentPath)) {
componentPath = path.join(testDir, 'Component-clean.tsx');
}
if (!fs.existsSync(componentPath)) {
return new Map();
}
const sourceCode = fs.readFileSync(componentPath, 'utf8');
try {
const ast = babelParse(sourceCode, {
sourceType: 'module',
plugins: ['jsx', 'typescript']
});
const helpers = new Map();
const imports = [];
// Collect all imports
traverseDefault(ast, {
ImportDeclaration(path) {
imports.push(generateDefault(path.node).code);
}
});
// Find all function declarations
traverseDefault(ast, {
FunctionDeclaration(path) {
const functionName = path.node.id?.name;
// Skip if it's a main component
if (functionName && !mainComponentNames.includes(functionName)) {
// This is a helper function
const helperCode = generateDefault(path.node).code;
// Find which imports this helper uses
const usedImports = [];
const helperIdentifiers = [];
// Collect identifiers from this function
path.traverse({
Identifier(identPath) {
const name = identPath.node.name;
if (!helperIdentifiers.includes(name)) {
helperIdentifiers.push(name);
}
}
});
// Match identifiers with imports
for (const name of helperIdentifiers) {
const matchingImport = imports.find(imp =>
imp.includes(`import ${name} `) ||
imp.includes(`{ ${name}`) ||
imp.includes(`, ${name}`)
);
if (matchingImport && !usedImports.includes(matchingImport)) {
usedImports.push(matchingImport);
}
}
helpers.set(functionName, {
code: helperCode,
imports: usedImports
});
}
}
});
return helpers;
} catch (err) {
console.error(' ⚠️ Error parsing Component-clean.tsx:', err.message);
return new Map();
}
}
/**
* Find which helpers are used in a TSX file
* Returns Set<helperNames> with recursive dependencies resolved
*/
function findUsedHelpers(tsxContent, availableHelpers) {
const usedHelpers = new Set();
try {
const ast = babelParse(tsxContent, {
sourceType: 'module',
plugins: ['jsx', 'typescript']
});
// Find JSX elements and function calls
traverseDefault(ast, {
JSXIdentifier(path) {
const name = path.node.name;
if (availableHelpers.has(name)) {
usedHelpers.add(name);
}
},
CallExpression(path) {
if (path.node.callee.type === 'Identifier') {
const name = path.node.callee.name;
if (availableHelpers.has(name)) {
usedHelpers.add(name);
}
}
}
});
// Resolve dependencies recursively
const resolvedHelpers = new Set(usedHelpers);
let changed = true;
while (changed) {
changed = false;
for (const helperName of resolvedHelpers) {
const helper = availableHelpers.get(helperName);
if (helper) {
// Check if this helper uses other helpers
const helperUsedHelpers = findUsedHelpers(helper.code, availableHelpers);
for (const dep of helperUsedHelpers) {
if (!resolvedHelpers.has(dep)) {
resolvedHelpers.add(dep);
changed = true;
}
}
}
}
}
return resolvedHelpers;
} catch (err) {
console.error(' ⚠️ Error analyzing helper usage:', err.message);
return usedHelpers;
}
}
/**
* Inject helper functions into a component TSX file
* Returns modified TSX content
*/
function injectHelpersIntoComponent(tsxContent, usedHelperNames, helpersMap) {
if (usedHelperNames.size === 0) {
return tsxContent; // No helpers needed
}
try {
const ast = babelParse(tsxContent, {
sourceType: 'module',
plugins: ['jsx', 'typescript']
});
// Collect all imports and helpers to inject
const importsToAdd = new Set();
const helpersToAdd = [];
const existingImports = new Set();
const existingFunctions = new Set();
// Get existing imports and function names
traverseDefault(ast, {
ImportDeclaration(path) {
existingImports.add(generateDefault(path.node).code);
// Also track import specifiers to avoid duplicate imports
path.node.specifiers.forEach(spec => {
if (spec.type === 'ImportDefaultSpecifier' || spec.type === 'ImportSpecifier') {
existingImports.add(spec.local.name);
}
});
},
FunctionDeclaration(path) {
if (path.node.id && path.node.id.name) {
existingFunctions.add(path.node.id.name);
}
}
});
// Collect helper code and imports
for (const helperName of usedHelperNames) {
const helper = helpersMap.get(helperName);
if (helper) {
// Only add helper if it doesn't exist already
if (!existingFunctions.has(helperName)) {
helpersToAdd.push(helper.code);
// Add imports, fixing paths for nested subcomponents
for (const imp of helper.imports) {
// Fix image import paths: "./img/" -> "../img/"
const fixedImport = imp.replace(/from\s+["']\.\/img\//g, 'from "../img/');
// Check if import statement already exists OR import name is already imported
const importName = imp.match(/import\s+(\w+)/)?.[1];
if (!existingImports.has(fixedImport) && (!importName || !existingImports.has(importName))) {
importsToAdd.add(fixedImport);
}
}
}
}
}
// Find the position of the last import or start of file
let lastImportEnd = 0;
let exportDefaultStart = tsxContent.length;
traverseDefault(ast, {
ImportDeclaration(path) {
if (path.node.end > lastImportEnd) {
lastImportEnd = path.node.end;
}
},
ExportDefaultDeclaration(path) {
if (path.node.start < exportDefaultStart) {
exportDefaultStart = path.node.start;
}
}
});
// Build injected code
let result = tsxContent;
// Insert imports after existing imports
if (importsToAdd.size > 0) {
const importsCode = '\n' + Array.from(importsToAdd).join('\n') + '\n';
result = result.slice(0, lastImportEnd) + importsCode + result.slice(lastImportEnd);
exportDefaultStart += importsCode.length;
}