-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathResponsiveCodegen.ts
More file actions
2203 lines (1952 loc) · 74.6 KB
/
ResponsiveCodegen.ts
File metadata and controls
2203 lines (1952 loc) · 74.6 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
import { Codegen } from '../Codegen'
import {
applyTextChildrenTransform,
getSelectorPropsForGroup,
sanitizePropertyName,
} from '../props/selector'
import { renderComponent, renderNode } from '../render'
import type { NodeTree, Props } from '../types'
import { getComponentPropertyDefinitions } from '../utils/get-component-property-definitions'
import { paddingLeftMultiline } from '../utils/padding-left-multiline'
import { perfEnd, perfStart } from '../utils/perf'
import {
BREAKPOINT_ORDER,
type BreakpointKey,
createVariantPropValue,
getBreakpointByWidth,
isEqual,
mergePropsToResponsive,
mergePropsToVariant,
optimizeResponsiveValue,
type PropValue,
viewportToBreakpoint,
} from '.'
const POSITION_PROP_KEYS = new Set([
'pos',
'top',
'left',
'right',
'bottom',
'display',
])
const RESERVED_VARIANT_KEYS = new Set(['effect', 'viewport'])
function firstMapValue<V>(map: Map<unknown, V>): V {
for (const v of map.values()) return v
throw new Error('empty map')
}
function firstMapEntry<K, V>(map: Map<K, V>): [K, V] {
for (const entry of map.entries()) return entry
throw new Error('empty map')
}
/**
* Build a stable merged order of child names across multiple variants/breakpoints.
* Uses topological sort on a DAG of ordering constraints from all variants,
* with average-position tie-breaking for deterministic output.
*
* Example: variant A has [Icon, TextA, Arrow], variant B has [Icon, TextB, Arrow]
* → edges: Icon→TextA, TextA→Arrow, Icon→TextB, TextB→Arrow
* → topo sort: [Icon, TextA, TextB, Arrow] (Arrow stays last)
*/
function mergeChildNameOrder(
childrenMaps: Map<unknown, Map<string, NodeTree[]>>,
): string[] {
// Collect distinct child name sequences from each variant
const sequences: string[][] = []
for (const childMap of childrenMaps.values()) {
const seq: string[] = []
for (const name of childMap.keys()) {
seq.push(name)
}
sequences.push(seq)
}
// Collect all unique names
const allNames = new Set<string>()
for (const seq of sequences) {
for (const name of seq) {
allNames.add(name)
}
}
if (allNames.size === 0) return []
if (allNames.size === 1) return [...allNames]
// Build DAG: for each variant, add edge from consecutive distinct names
const edges = new Map<string, Set<string>>()
const inDegree = new Map<string, number>()
for (const name of allNames) {
edges.set(name, new Set())
inDegree.set(name, 0)
}
for (const seq of sequences) {
for (let i = 0; i < seq.length - 1; i++) {
const from = seq[i]
const to = seq[i + 1]
const fromEdges = edges.get(from)
if (fromEdges && !fromEdges.has(to)) {
fromEdges.add(to)
inDegree.set(to, (inDegree.get(to) || 0) + 1)
}
}
}
// Compute average normalized position for tie-breaking
const avgPosition = new Map<string, number>()
for (const name of allNames) {
let totalPos = 0
let count = 0
for (const seq of sequences) {
const idx = seq.indexOf(name)
if (idx >= 0) {
// Normalize to 0..1 range
totalPos += seq.length > 1 ? idx / (seq.length - 1) : 0.5
count++
}
}
avgPosition.set(name, count > 0 ? totalPos / count : 0.5)
}
// Kahn's algorithm with priority-based tie-breaking
const queue: string[] = []
for (const [name, deg] of inDegree) {
if (deg === 0) queue.push(name)
}
// Sort initial queue by average position (stable)
queue.sort((a, b) => (avgPosition.get(a) || 0) - (avgPosition.get(b) || 0))
const result: string[] = []
while (queue.length > 0) {
const node = queue.shift()
if (!node) break
result.push(node)
for (const neighbor of edges.get(node) || []) {
const newDeg = (inDegree.get(neighbor) || 1) - 1
inDegree.set(neighbor, newDeg)
if (newDeg === 0) {
queue.push(neighbor)
// Re-sort to maintain priority order
queue.sort(
(a, b) => (avgPosition.get(a) || 0) - (avgPosition.get(b) || 0),
)
}
}
}
// Cycle fallback: append any remaining nodes (shouldn't happen with consistent data)
if (result.length < allNames.size) {
for (const name of allNames) {
if (!result.includes(name)) {
result.push(name)
}
}
}
return result
}
/**
* Generate responsive code by merging children inside a Section.
* Uses Codegen to build NodeTree for each breakpoint, then merges them.
*/
export class ResponsiveCodegen {
private breakpointNodes: Map<BreakpointKey, SceneNode> = new Map()
constructor(private sectionNode: SectionNode | null) {
if (this.sectionNode) {
this.categorizeChildren()
}
}
/**
* Group Section children by width to decide breakpoints.
*/
private categorizeChildren() {
if (!this.sectionNode) return
for (const child of this.sectionNode.children) {
if ('width' in child) {
const breakpoint = getBreakpointByWidth(child.width)
// If multiple nodes share a breakpoint, keep the first.
if (!this.breakpointNodes.has(breakpoint)) {
this.breakpointNodes.set(breakpoint, child)
}
}
}
}
/**
* Generate responsive code.
*/
async generateResponsiveCode(): Promise<string> {
if (this.breakpointNodes.size === 0) {
return '// No responsive variants found in section'
}
if (this.breakpointNodes.size === 1) {
// If only one breakpoint, generate normal code using Codegen.
const [, node] = firstMapEntry(this.breakpointNodes)
const codegen = new Codegen(node)
const tree = await codegen.getTree()
return Codegen.renderTree(tree, 0)
}
// Extract trees per breakpoint using Codegen — all independent, run in parallel.
const breakpointTrees = new Map<BreakpointKey, NodeTree>()
for (const [bp, node] of this.breakpointNodes) {
const codegen = new Codegen(node)
const tree = await codegen.getTree()
breakpointTrees.set(bp, tree)
}
// Merge trees and generate code.
return this.generateMergedCode(breakpointTrees, 0)
}
/**
* Convert NodeTree children array to Map by nodeName.
*/
private treeChildrenToMap(tree: NodeTree): Map<string, NodeTree[]> {
const result = new Map<string, NodeTree[]>()
for (const child of tree.children) {
const existing = result.get(child.nodeName) || []
existing.push(child)
result.set(child.nodeName, existing)
}
return result
}
/**
* Generate merged responsive code from NodeTree objects.
*/
generateMergedCode(
treesByBreakpoint: Map<BreakpointKey, NodeTree>,
depth: number,
): string {
const firstTree = firstMapValue(treesByBreakpoint)
// If node is INSTANCE or COMPONENT, render as component reference
if (firstTree.isComponent) {
// For components, we might still need position props
const propsMap = new Map<BreakpointKey, Props>()
for (const [bp, tree] of treesByBreakpoint) {
const posProps: Props = {}
if (tree.props.pos) posProps.pos = tree.props.pos
if (tree.props.top) posProps.top = tree.props.top
if (tree.props.left) posProps.left = tree.props.left
if (tree.props.right) posProps.right = tree.props.right
if (tree.props.bottom) posProps.bottom = tree.props.bottom
if (tree.props.display) posProps.display = tree.props.display
propsMap.set(bp, posProps)
}
const mergedPositionProps = mergePropsToResponsive(propsMap)
// Extract variant props (non-position props) - these are Instance variant values
// They should be the same across breakpoints, so just use firstTree
// Filter out reserved variant keys (effect, viewport) which are used internally
const variantProps: Props = {}
for (const [key, value] of Object.entries(firstTree.props)) {
const lowerKey = key.toLowerCase()
if (
!POSITION_PROP_KEYS.has(key) &&
!RESERVED_VARIANT_KEYS.has(lowerKey)
) {
variantProps[key] = value
}
}
// If component has position props, wrap in Box
if (Object.keys(mergedPositionProps).length > 0) {
const componentCode = renderNode(
firstTree.component,
variantProps,
0,
[],
)
return renderNode('Box', mergedPositionProps, depth, [componentCode])
}
return renderNode(firstTree.component, variantProps, depth, [])
}
// Handle WRAPPER nodes (position wrapper for components)
if (firstTree.nodeType === 'WRAPPER') {
const propsMap = new Map<BreakpointKey, Props>()
for (const [bp, tree] of treesByBreakpoint) {
propsMap.set(bp, tree.props)
}
const mergedProps = mergePropsToResponsive(propsMap)
// Recursively merge the inner component
const innerTrees = new Map<BreakpointKey, NodeTree>()
for (const [bp, tree] of treesByBreakpoint) {
if (tree.children.length > 0) {
innerTrees.set(bp, tree.children[0])
}
}
const innerCode =
innerTrees.size > 0 ? this.generateMergedCode(innerTrees, 0) : ''
return renderNode('Box', mergedProps, depth, innerCode ? [innerCode] : [])
}
// Merge props across breakpoints
const propsMap = new Map<BreakpointKey, Props>()
for (const [bp, tree] of treesByBreakpoint) {
propsMap.set(bp, tree.props)
}
const mergedProps = mergePropsToResponsive(propsMap)
// Handle TEXT nodes with textChildren
if (firstTree.textChildren && firstTree.textChildren.length > 0) {
// Merge text children across breakpoints
const mergedTextChildren =
this.mergeTextChildrenAcrossBreakpoints(treesByBreakpoint)
return renderNode(
firstTree.component,
mergedProps,
depth,
mergedTextChildren,
)
}
// Merge children by name
const childrenCodes: string[] = []
// Convert all trees' children to maps
const childrenMaps = new Map<BreakpointKey, Map<string, NodeTree[]>>()
for (const [bp, tree] of treesByBreakpoint) {
childrenMaps.set(bp, this.treeChildrenToMap(tree))
}
// Get all child names in stable merged order across all breakpoints
const allChildNames = mergeChildNameOrder(childrenMaps)
for (const childName of allChildNames) {
// Find the maximum number of children with this name across all breakpoints
let maxChildCount = 0
for (const childMap of childrenMaps.values()) {
const children = childMap.get(childName)
if (children) {
maxChildCount = Math.max(maxChildCount, children.length)
}
}
// Process each child index separately
for (let childIndex = 0; childIndex < maxChildCount; childIndex++) {
const childByBreakpoint = new Map<BreakpointKey, NodeTree>()
const presentBreakpoints = new Set<BreakpointKey>()
for (const [bp, childMap] of childrenMaps) {
const children = childMap.get(childName)
if (children && children.length > childIndex) {
childByBreakpoint.set(bp, children[childIndex])
presentBreakpoints.add(bp)
}
}
if (childByBreakpoint.size > 0) {
// Add display:none props for breakpoints where child doesn't exist
// This handles both:
// 1. Child exists only in mobile (needs display:none in pc)
// 2. Child exists only in pc (needs display:none in mobile)
for (const bp of treesByBreakpoint.keys()) {
if (!presentBreakpoints.has(bp)) {
const firstChildTree = firstMapValue(childByBreakpoint)
const hiddenTree: NodeTree = {
...firstChildTree,
props: { ...firstChildTree.props, display: 'none' },
}
childByBreakpoint.set(bp, hiddenTree)
}
}
const childCode = this.generateMergedCode(childByBreakpoint, 0)
childrenCodes.push(childCode)
}
}
}
return renderNode(firstTree.component, mergedProps, depth, childrenCodes)
}
/**
* Check if node is Section and can generate responsive.
*/
static canGenerateResponsive(node: SceneNode): node is SectionNode {
return node.type === 'SECTION'
}
/**
* Return parent Section if exists.
*/
static hasParentSection(node: SceneNode): SectionNode | null {
if (node.parent?.type === 'SECTION') {
return node.parent as SectionNode
}
return null
}
/**
* Generate responsive component codes for COMPONENT_SET with viewport variant.
* Groups components by non-viewport variants and merges viewport variants.
*/
static async generateViewportResponsiveComponents(
componentSet: ComponentSetNode,
componentName: string,
): Promise<ReadonlyArray<readonly [string, string]>> {
// Find viewport and effect variant keys
const viewportDefs = getComponentPropertyDefinitions(componentSet)
let viewportKey: string | undefined
let effectKey: string | undefined
for (const key in viewportDefs) {
const lower = key.toLowerCase()
if (lower === 'viewport') viewportKey = key
else if (lower === 'effect') effectKey = key
}
if (!viewportKey) {
return []
}
// Get variants excluding viewport
const variants: Record<string, string> = {}
for (const name in viewportDefs) {
const definition = viewportDefs[name]
const lowerName = name.toLowerCase()
if (lowerName !== 'viewport' && lowerName !== 'effect') {
const sanitizedName = sanitizePropertyName(name)
if (definition.type === 'VARIANT') {
variants[sanitizedName] =
definition.variantOptions?.map((opt) => `'${opt}'`).join(' | ') ||
''
} else if (definition.type === 'INSTANCE_SWAP') {
variants[sanitizedName] = 'React.ReactNode'
} else if (definition.type === 'BOOLEAN') {
variants[sanitizedName] = 'boolean'
} else if (definition.type === 'TEXT') {
variants[sanitizedName] = 'string'
}
}
}
const { variants: finalVariants, variantComments } =
applyTextChildrenTransform(variants)
// Group components by non-viewport, non-effect variants
const groups = new Map<string, Map<BreakpointKey, ComponentNode>>()
for (const child of componentSet.children) {
if (child.type !== 'COMPONENT') continue
const component = child as ComponentNode
const variantProps = component.variantProperties || {}
// Skip non-default effect variants (they become pseudo-selectors)
if (effectKey && variantProps[effectKey] !== 'default') continue
const viewportValue = variantProps[viewportKey]
if (!viewportValue) continue
const breakpoint = viewportToBreakpoint(viewportValue)
// Create group key from non-viewport, non-effect variants
const parts: string[] = []
for (const key in variantProps) {
const lowerKey = key.toLowerCase()
if (lowerKey !== 'viewport' && lowerKey !== 'effect') {
parts.push(`${key}=${variantProps[key]}`)
}
}
parts.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
const groupKey = parts.join('|') || '__default__'
if (!groups.has(groupKey)) {
groups.set(groupKey, new Map())
}
const group = groups.get(groupKey)
if (group) {
group.set(breakpoint, component)
}
}
// Generate responsive code for each group
const results: Array<readonly [string, string]> = []
const responsiveCodegen = new ResponsiveCodegen(null)
for (const [groupKey, viewportComponents] of groups) {
// Parse group key to get variant filter for getSelectorPropsForGroup
const variantFilter: Record<string, string> = {}
if (groupKey !== '__default__') {
for (const part of groupKey.split('|')) {
const [key, value] = part.split('=')
// Exclude effect from filter (we want all effect variants for this group)
if (key.toLowerCase() !== 'effect') {
variantFilter[key] = value
}
}
}
// Build trees for each viewport — all independent, run in parallel.
const treesByBreakpoint = new Map<BreakpointKey, NodeTree>()
for (const [bp, component] of viewportComponents) {
let t = perfStart()
const codegen = new Codegen(component)
const tree = await codegen.getTree()
perfEnd('Codegen.getTree(viewportVariant)', t)
// Get pseudo-selector props for this specific variant group AND viewport
// This ensures hover/active colors are correctly responsive per viewport
if (effectKey) {
const viewportValue = component.variantProperties?.[viewportKey]
t = perfStart()
const selectorProps = await getSelectorPropsForGroup(
componentSet,
variantFilter,
viewportValue,
)
perfEnd('getSelectorPropsForGroup(viewport)', t)
if (Object.keys(selectorProps).length > 0) {
tree.props = Object.assign({}, tree.props, selectorProps)
}
}
treesByBreakpoint.set(bp, tree)
}
// Generate merged responsive code
const mergedCode = responsiveCodegen.generateMergedCode(
treesByBreakpoint,
0,
)
results.push([
componentName,
renderComponent(
componentName,
mergedCode,
finalVariants,
variantComments,
),
] as const)
}
return results
}
/**
* Generate component code for COMPONENT_SET with viewport AND other variants.
* First merges by viewport (responsive arrays), then by other variants (conditional objects).
*
* Example output for status variant:
* - Props: w={{ scroll: [1, 2], default: [3, 4] }[status]}
* - Conditional nodes: {status === "scroll" && <Node/>}
*/
static async generateVariantResponsiveComponents(
componentSet: ComponentSetNode,
componentName: string,
): Promise<ReadonlyArray<readonly [string, string]>> {
const tTotal = perfStart()
// Find viewport and effect variant keys
const variantDefs = getComponentPropertyDefinitions(componentSet)
let viewportKey: string | undefined
let effectKey: string | undefined
for (const key in variantDefs) {
const lower = key.toLowerCase()
if (lower === 'viewport') viewportKey = key
else if (lower === 'effect') effectKey = key
}
// Get all variant keys excluding viewport and effect
const otherVariantKeys: string[] = []
const variants: Record<string, string> = {}
// Map from original name to sanitized name
const variantKeyToSanitized: Record<string, string> = {}
for (const name in variantDefs) {
const definition = variantDefs[name]
if (definition.type === 'VARIANT') {
const lowerName = name.toLowerCase()
// Exclude both viewport and effect from variant keys
// viewport is handled by responsive merging
// effect is handled by getSelectorProps (pseudo-selectors like _hover, _active)
if (lowerName !== 'viewport' && lowerName !== 'effect') {
const sanitizedName = sanitizePropertyName(name)
otherVariantKeys.push(name) // Keep original for Figma data access
variantKeyToSanitized[name] = sanitizedName
variants[sanitizedName] =
definition.variantOptions?.map((opt) => `'${opt}'`).join(' | ') ||
''
}
} else if (definition.type === 'INSTANCE_SWAP') {
const sanitizedName = sanitizePropertyName(name)
variants[sanitizedName] = 'React.ReactNode'
} else if (definition.type === 'BOOLEAN') {
const sanitizedName = sanitizePropertyName(name)
variants[sanitizedName] = 'boolean'
} else if (definition.type === 'TEXT') {
const sanitizedName = sanitizePropertyName(name)
variants[sanitizedName] = 'string'
}
}
const { variants: finalVariants, variantComments } =
applyTextChildrenTransform(variants)
// If effect variant only, generate code from defaultVariant with pseudo-selectors
if (effectKey && !viewportKey && otherVariantKeys.length === 0) {
const r = await ResponsiveCodegen.generateEffectOnlyComponents(
componentSet,
componentName,
)
perfEnd('generateVariantResponsiveComponents(total)', tTotal)
return r
}
// If no viewport variant, just handle other variants
if (!viewportKey) {
const r = await ResponsiveCodegen.generateNonViewportVariantComponents(
componentSet,
componentName,
otherVariantKeys,
finalVariants,
)
perfEnd('generateVariantResponsiveComponents(total)', tTotal)
return r
}
// If no other variants, use existing viewport-only logic
if (otherVariantKeys.length === 0) {
const r = await ResponsiveCodegen.generateViewportResponsiveComponents(
componentSet,
componentName,
)
perfEnd('generateVariantResponsiveComponents(total)', tTotal)
return r
}
// Handle both viewport and other variants
// Group by ALL variant keys combined, then by viewport within each group
// e.g., for size+variant: { "Md|primary" => { "mobile" => Component, "pc" => Component }, ... }
// Reverse mapping from sanitized to original names
const sanitizedToOriginal: Record<string, string> = {}
for (const [original, sanitized] of Object.entries(variantKeyToSanitized)) {
sanitizedToOriginal[sanitized] = original
}
// Sanitized variant keys for code generation
const sanitizedVariantKeys = otherVariantKeys.map(
(key) => variantKeyToSanitized[key],
)
// Build a composite key from all variant values (using sanitized names)
const buildCompositeKey = (
variantProps: Record<string, string>,
): string => {
return otherVariantKeys
.map((key) => {
const sanitizedKey = variantKeyToSanitized[key]
return `${sanitizedKey}=${variantProps[key] || '__default__'}`
})
.join('|')
}
// Parse composite key to original Figma variant names (for getSelectorPropsForGroup)
const parseCompositeKeyToOriginal = (
compositeKey: string,
): Record<string, string> => {
const result: Record<string, string> = {}
for (const part of compositeKey.split('|')) {
const [sanitizedKey, value] = part.split('=')
const originalKey = sanitizedToOriginal[sanitizedKey]
if (originalKey) {
result[originalKey] = value
}
}
return result
}
const byCompositeVariant = new Map<
string,
Map<BreakpointKey, ComponentNode>
>()
for (const child of componentSet.children) {
if (child.type !== 'COMPONENT') continue
const component = child as ComponentNode
const variantProps = component.variantProperties || {}
// Skip effect variants for grouping (they become pseudo-selectors)
if (effectKey && variantProps[effectKey] !== 'default') continue
const viewportValue = variantProps[viewportKey]
if (!viewportValue) continue
const breakpoint = viewportToBreakpoint(viewportValue)
const compositeKey = buildCompositeKey(variantProps)
if (!byCompositeVariant.has(compositeKey)) {
byCompositeVariant.set(compositeKey, new Map())
}
const byBreakpoint = byCompositeVariant.get(compositeKey)
if (byBreakpoint) {
byBreakpoint.set(breakpoint, component)
}
}
if (byCompositeVariant.size === 0) {
perfEnd('generateVariantResponsiveComponents(total)', tTotal)
return []
}
const responsiveCodegen = new ResponsiveCodegen(null)
// Step 1: For each variant combination, merge by viewport to get responsive props
const responsivePropsByComposite = new Map<
string,
Map<BreakpointKey, NodeTree>
>()
// Build trees for all composite variants — each is independent.
for (const [compositeKey, viewportComponents] of byCompositeVariant) {
// Use original names for Figma data access
const variantFilter = parseCompositeKeyToOriginal(compositeKey)
// Build trees for each viewport within this composite.
const treesByBreakpoint = new Map<BreakpointKey, NodeTree>()
for (const [bp, component] of viewportComponents) {
let t = perfStart()
const codegen = new Codegen(component)
const tree = await codegen.getTree()
perfEnd('Codegen.getTree(variant)', t)
// Get pseudo-selector props for this specific variant group AND viewport
if (effectKey) {
const viewportValue = component.variantProperties?.[viewportKey]
t = perfStart()
const selectorProps = await getSelectorPropsForGroup(
componentSet,
variantFilter,
viewportValue,
)
perfEnd('getSelectorPropsForGroup()', t)
if (Object.keys(selectorProps).length > 0) {
tree.props = Object.assign({}, tree.props, selectorProps)
}
}
treesByBreakpoint.set(bp, tree)
}
responsivePropsByComposite.set(compositeKey, treesByBreakpoint)
}
// Step 2: Merge across variant values, handling multiple variant keys
const mergedCode = responsiveCodegen.generateMultiVariantMergedCode(
sanitizedVariantKeys,
responsivePropsByComposite,
0,
)
const result: Array<readonly [string, string]> = [
[
componentName,
renderComponent(
componentName,
mergedCode,
finalVariants,
variantComments,
),
],
]
return result
}
/**
* Generate component code for COMPONENT_SET with effect variant only (no other variants).
* Uses defaultVariant as the base and adds pseudo-selector props from getSelectorProps.
*/
private static async generateEffectOnlyComponents(
componentSet: ComponentSetNode,
componentName: string,
): Promise<ReadonlyArray<readonly [string, string]>> {
// Use defaultVariant as the base component
const defaultComponent = componentSet.defaultVariant
if (!defaultComponent) {
return []
}
// Get base props from defaultVariant
const codegen = new Codegen(defaultComponent)
const tree = await codegen.getTree()
// Get pseudo-selector props (hover, active, disabled, etc.)
const selectorProps = await getSelectorPropsForGroup(componentSet, {})
if (Object.keys(selectorProps).length > 0) {
tree.props = Object.assign({}, tree.props, selectorProps)
}
// Render the tree to JSX
const code = Codegen.renderTree(tree, 0)
// Collect BOOLEAN and INSTANCE_SWAP props for the interface
// (effect is handled via pseudo-selectors, VARIANT keys don't exist in effect-only path)
const variants: Record<string, string> = {}
const effectDefs = getComponentPropertyDefinitions(componentSet)
for (const name in effectDefs) {
const definition = effectDefs[name]
if (definition.type === 'INSTANCE_SWAP') {
variants[sanitizePropertyName(name)] = 'React.ReactNode'
} else if (definition.type === 'BOOLEAN') {
variants[sanitizePropertyName(name)] = 'boolean'
} else if (definition.type === 'TEXT') {
variants[sanitizePropertyName(name)] = 'string'
}
}
const { variants: finalVariants, variantComments } =
applyTextChildrenTransform(variants)
const result: Array<readonly [string, string]> = [
[
componentName,
renderComponent(componentName, code, finalVariants, variantComments),
],
]
return result
}
/**
* Generate component code for COMPONENT_SET with non-viewport variants only.
*/
private static async generateNonViewportVariantComponents(
componentSet: ComponentSetNode,
componentName: string,
variantKeys: string[],
variants: Record<string, string>,
): Promise<ReadonlyArray<readonly [string, string]>> {
if (variantKeys.length === 0) {
return []
}
// Check if componentSet has effect variant (pseudo-selector)
const groupVariantDefs = getComponentPropertyDefinitions(componentSet)
let hasEffect = false
for (const key in groupVariantDefs) {
if (key.toLowerCase() === 'effect') {
hasEffect = true
break
}
}
// Map from original name to sanitized name
const variantKeyToSanitized: Record<string, string> = {}
for (const key of variantKeys) {
variantKeyToSanitized[key] = sanitizePropertyName(key)
}
const sanitizedVariantKeys = variantKeys.map(
(key) => variantKeyToSanitized[key],
)
// Single variant key: use simpler single-dimension merge
if (variantKeys.length === 1) {
return ResponsiveCodegen.generateSingleVariantComponents(
componentSet,
componentName,
variantKeys[0],
sanitizedVariantKeys[0],
variants,
hasEffect,
)
}
// Multiple variant keys: build trees for ALL combinations, use multi-dimensional merge
// Build composite key for each component (e.g., "size=lg|varient=primary")
const buildCompositeKey = (
variantProps: Record<string, string>,
): string => {
return variantKeys
.map((key) => {
const sanitizedKey = variantKeyToSanitized[key]
return `${sanitizedKey}=${variantProps[key] || '__default__'}`
})
.join('|')
}
// Reverse mapping from sanitized to original names (for getSelectorPropsForGroup)
const sanitizedToOriginal: Record<string, string> = {}
for (const [original, sanitized] of Object.entries(variantKeyToSanitized)) {
sanitizedToOriginal[sanitized] = original
}
const parseCompositeKeyToOriginal = (
compositeKey: string,
): Record<string, string> => {
const result: Record<string, string> = {}
for (const part of compositeKey.split('|')) {
const [sanitizedKey, value] = part.split('=')
const originalKey = sanitizedToOriginal[sanitizedKey]
if (originalKey) {
result[originalKey] = value
}
}
return result
}
// Group components by composite variant key (all variant values combined)
const componentsByComposite = new Map<string, ComponentNode>()
for (const child of componentSet.children) {
if (child.type !== 'COMPONENT') continue
const component = child as ComponentNode
const variantProps = component.variantProperties || {}
// Skip effect variants (they become pseudo-selectors)
if (hasEffect) {
const effectValue =
variantProps[
Object.keys(groupVariantDefs).find(
(k) => k.toLowerCase() === 'effect',
) || ''
]
if (effectValue && effectValue !== 'default') continue
}
const compositeKey = buildCompositeKey(variantProps)
if (!componentsByComposite.has(compositeKey)) {
componentsByComposite.set(compositeKey, component)
}
}
// Build trees for each combination
const treesByComposite = new Map<string, NodeTree>()
for (const [compositeKey, component] of componentsByComposite) {
const variantFilter = parseCompositeKeyToOriginal(compositeKey)
let t = perfStart()
const selectorProps = hasEffect
? await getSelectorPropsForGroup(componentSet, variantFilter)
: null
perfEnd('getSelectorPropsForGroup(nonViewport)', t)
t = perfStart()
const codegen = new Codegen(component)
const tree = await codegen.getTree()
perfEnd('Codegen.getTree(nonViewportVariant)', t)
// Use the component tree from addComponentTree if available — it includes
// ALL children (even invisible BOOLEAN-controlled ones) with condition fields
// and INSTANCE_SWAP slot placeholders, which buildTree() skips.
const componentTree = codegen.getComponentTree()
if (componentTree) {
tree.children = componentTree.tree.children
}
if (selectorProps && Object.keys(selectorProps).length > 0) {
tree.props = Object.assign({}, tree.props, selectorProps)
}
treesByComposite.set(compositeKey, tree)
}
// Use multi-dimensional merge (same as viewport+variant path but without viewport)
// Wrap each tree in a single-breakpoint map so generateMultiVariantMergedCode works
const treesByCompositeAndBreakpoint = new Map<
string,
Map<BreakpointKey, NodeTree>
>()
for (const [compositeKey, tree] of treesByComposite) {
const singleBreakpointMap = new Map<BreakpointKey, NodeTree>()
singleBreakpointMap.set('pc', tree)
treesByCompositeAndBreakpoint.set(compositeKey, singleBreakpointMap)
}
const responsiveCodegen = new ResponsiveCodegen(null)
const mergedCode = responsiveCodegen.generateMultiVariantMergedCode(
sanitizedVariantKeys,
treesByCompositeAndBreakpoint,
0,
)
const result: Array<readonly [string, string]> = [
[componentName, renderComponent(componentName, mergedCode, variants)],
]
return result
}
/**
* Generate component code for single variant key (original simple path).
*/
private static async generateSingleVariantComponents(
componentSet: ComponentSetNode,
componentName: string,
variantKey: string,
sanitizedVariantKey: string,
variants: Record<string, string>,
hasEffect: boolean,
): Promise<ReadonlyArray<readonly [string, string]>> {
// Group components by variant value
const componentsByVariant = new Map<string, ComponentNode>()
for (const child of componentSet.children) {
if (child.type !== 'COMPONENT') continue
const component = child as ComponentNode
const variantProps = component.variantProperties || {}
const variantValue = variantProps[variantKey] || '__default__'