-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCodegen.ts
More file actions
795 lines (724 loc) · 26.5 KB
/
Codegen.ts
File metadata and controls
795 lines (724 loc) · 26.5 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
import { getComponentName } from '../utils'
import { toCamel } from '../utils/to-camel'
import { getProps } from './props'
import { getPositionProps } from './props/position'
import { getSelectorProps, sanitizePropertyName } from './props/selector'
import { getTransformProps } from './props/transform'
import { renderComponent, renderNode } from './render'
import { renderText } from './render/text'
import type { ComponentTree, NodeTree } from './types'
import { checkAssetNode } from './utils/check-asset-node'
import { checkSameColor } from './utils/check-same-color'
import { extractInstanceVariantProps } from './utils/extract-instance-variant-props'
import {
getDevupComponentByNode,
getDevupComponentByProps,
} from './utils/get-devup-component'
import { getPageNode } from './utils/get-page-node'
import { paddingLeftMultiline } from './utils/padding-left-multiline'
import { perfEnd, perfStart } from './utils/perf'
import { buildCssUrl } from './utils/wrap-url'
// Global cache for node.getMainComponentAsync() results.
// Multiple Codegen instances (from ResponsiveCodegen) process the same INSTANCE nodes,
// each calling getMainComponentAsync which is an expensive Figma IPC call.
// Keyed by instance node.id; stores the Promise to deduplicate concurrent calls.
const mainComponentCache = new Map<string, Promise<ComponentNode | null>>()
export function resetMainComponentCache(): void {
mainComponentCache.clear()
}
function getMainComponentCached(
node: InstanceNode,
): Promise<ComponentNode | null> {
const cacheKey = node.id
if (cacheKey) {
const cached = mainComponentCache.get(cacheKey)
if (cached) return cached
}
const promise = node.getMainComponentAsync()
if (cacheKey) {
mainComponentCache.set(cacheKey, promise)
}
return promise
}
// Global buildTree cache shared across all Codegen instances.
// ResponsiveCodegen creates multiple Codegen instances for the same component
// variants — without this, each instance rebuilds the entire subtree.
// Returns cloned trees (shallow-cloned props at every level) because
// downstream code mutates tree.props via Object.assign.
const globalBuildTreeCache = new Map<string, Promise<NodeTree>>()
export function resetGlobalBuildTreeCache(): void {
globalBuildTreeCache.clear()
}
// Global asset node registry populated during buildTree().
// Tracks nodes classified as SVG/PNG assets so callers (e.g. export commands)
// can collect them without re-walking the Figma node tree via IPC.
const globalAssetNodes = new Map<
string,
{ node: SceneNode; type: 'svg' | 'png' }
>()
export function resetGlobalAssetNodes(): void {
globalAssetNodes.clear()
}
export function getGlobalAssetNodes(): ReadonlyMap<
string,
{ node: SceneNode; type: 'svg' | 'png' }
> {
return globalAssetNodes
}
/**
* Get componentPropertyReferences from a node (if available).
*/
function getPropertyRefs(node: SceneNode): Record<string, string> | undefined {
if (
'componentPropertyReferences' in node &&
node.componentPropertyReferences
) {
return node.componentPropertyReferences as Record<string, string>
}
return undefined
}
/**
* Check if a child node is bound to an INSTANCE_SWAP component property.
* Returns the sanitized slot name if it is, undefined otherwise.
*/
function getInstanceSwapSlotName(
node: SceneNode,
swapSlots: Map<string, string>,
): string | undefined {
if (swapSlots.size === 0) return undefined
const refs = getPropertyRefs(node)
if (refs?.mainComponent && swapSlots.has(refs.mainComponent)) {
return swapSlots.get(refs.mainComponent)
}
return undefined
}
/**
* Check if a child node is controlled by a BOOLEAN component property (visibility).
* Returns the sanitized boolean prop name if it is, undefined otherwise.
*/
function getBooleanConditionName(
node: SceneNode,
booleanSlots: Map<string, string>,
): string | undefined {
if (booleanSlots.size === 0) return undefined
const refs = getPropertyRefs(node)
if (refs?.visible && booleanSlots.has(refs.visible)) {
return booleanSlots.get(refs.visible)
}
return undefined
}
/**
* Check if a child node's text characters are bound to a TEXT component property.
* Returns the sanitized text prop name if it is, undefined otherwise.
*/
function getTextPropName(
node: SceneNode,
textSlots: Map<string, string>,
): string | undefined {
if (textSlots.size === 0) return undefined
const refs = getPropertyRefs(node)
if (refs?.characters && textSlots.has(refs.characters)) {
return textSlots.get(refs.characters)
}
return undefined
}
/**
* Recursively apply BOOLEAN conditions and TEXT bindings to nested descendants.
* buildTree produces the tree structure but doesn't check BOOLEAN/TEXT bindings —
* those are only available via componentPropertyReferences on the original Figma nodes.
* This walks the tree and Figma node tree in parallel, applying conditions at every level.
*/
function applyNestedConditions(
tree: NodeTree,
node: SceneNode,
booleanSlots: Map<string, string>,
textSlots: Map<string, string>,
): void {
// Skip component references and wrappers — their children aren't expanded in the tree
if (tree.isComponent || tree.nodeType === 'WRAPPER') return
if (!('children' in node) || tree.children.length === 0) return
const figmaChildren = (node as SceneNode & ChildrenMixin).children
const len = Math.min(figmaChildren.length, tree.children.length)
for (let i = 0; i < len; i++) {
const childTree = tree.children[i]
const childNode = figmaChildren[i]
if (!childTree.condition) {
const conditionName = getBooleanConditionName(childNode, booleanSlots)
if (conditionName) {
childTree.condition = conditionName
}
}
const textPropName = getTextPropName(childNode, textSlots)
if (
textPropName &&
childTree.textChildren &&
!childTree.textChildren[0]?.startsWith('{')
) {
childTree.textChildren = [`{${textPropName}}`]
}
applyNestedConditions(childTree, childNode, booleanSlots, textSlots)
}
}
/**
* Shallow-clone a NodeTree — creates a new object so that per-instance
* property reassignment (e.g., `tree.props = { ...tree.props, ...selectorProps }`)
* doesn't leak across Codegen instances. Props object itself is shared by
* reference — callers that need to merge create their own objects.
*/
function cloneTree(tree: NodeTree): NodeTree {
return {
component: tree.component,
props: tree.props,
children: tree.children,
nodeType: tree.nodeType,
nodeName: tree.nodeName,
isComponent: tree.isComponent,
isSlot: tree.isSlot,
condition: tree.condition,
textChildren: tree.textChildren,
}
}
export class Codegen {
components: Map<
string,
{
node: SceneNode
code: string
variants: Record<string, string>
variantComments?: Record<string, string>
}
> = new Map()
code: string = ''
// Tree representations
private tree: NodeTree | null = null
private componentTrees: Map<string, ComponentTree> = new Map()
// Cache buildTree results by node.id to avoid duplicate subtree builds
// (e.g., when addComponentTree and main tree walk process the same children)
private buildTreeCache: Map<string, Promise<NodeTree>> = new Map()
// Collect fire-and-forget addComponentTree promises so we can await them
// before rendering component codes (decouples INSTANCE buildTree from addComponentTree)
private pendingComponentTrees: Promise<void>[] = []
constructor(private node: SceneNode) {
this.node = node
// if (node.type === 'COMPONENT' && node.parent?.type === 'COMPONENT_SET') {
// this.node = node.parent
// } else {
// this.node = node
// }
// if (node.type === 'COMPONENT' && node.parent?.type === 'COMPONENT_SET') {
// this.node = node.parent
// } else {
// this.node = node
// }
}
getCode() {
return this.code
}
/**
* Get the component tree built by addComponentTree for this node.
* Unlike getTree(), which skips invisible children in buildTree(),
* this tree includes ALL children with BOOLEAN conditions and
* INSTANCE_SWAP slot placeholders preserved.
* Returns undefined if no component tree was built (non-COMPONENT nodes).
*/
getComponentTree(): ComponentTree | undefined {
const nodeId = this.node.id || this.node.name
return this.componentTrees.get(nodeId)
}
getComponentsCodes() {
const result: Array<readonly [string, string]> = []
for (const {
node,
code,
variants,
variantComments,
} of this.components.values()) {
const name = getComponentName(node)
result.push([
name,
renderComponent(name, code, variants, variantComments),
])
}
return result
}
/**
* Get the component nodes (SceneNode values from components Map).
* Useful for generating responsive codes for each component.
*/
getComponentNodes() {
const result: SceneNode[] = []
for (const { node } of this.components.values()) result.push(node)
return result
}
/**
* Run the codegen process: build tree and render to JSX string.
*/
async run(node: SceneNode = this.node, depth: number = 0): Promise<string> {
// Build the tree first
const tree = await this.buildTree(node)
// Render the tree to JSX string
const ret = Codegen.renderTree(tree, depth)
if (node === this.node) {
this.code = ret
this.tree = tree
}
// Await all fire-and-forget addComponentTree calls before rendering
if (this.pendingComponentTrees.length > 0) {
await Promise.all(this.pendingComponentTrees)
this.pendingComponentTrees = []
}
// Sync componentTrees to components
for (const [compId, compTree] of this.componentTrees) {
if (!this.components.has(compId)) {
this.components.set(compId, {
node: compTree.node,
code: Codegen.renderTree(compTree.tree, 0),
variants: compTree.variants,
variantComments: compTree.variantComments,
})
}
}
return ret
}
/**
* Build a NodeTree representation of the node hierarchy.
* This is the intermediate JSON representation that can be compared/merged.
*
* Uses a two-level cache:
* 1. Global cache (across instances) — returns cloned trees to prevent mutation leaks
* 2. Per-instance cache — returns the same promise within a single Codegen.run()
*/
async buildTree(node: SceneNode = this.node): Promise<NodeTree> {
const cacheKey = node.id
if (cacheKey) {
// Per-instance cache (same tree object reused within one Codegen)
const instanceCached = this.buildTreeCache.get(cacheKey)
if (instanceCached) return instanceCached
// Global cache (shared across Codegen instances from ResponsiveCodegen).
// Returns a CLONE because downstream code mutates tree.props.
const globalCached = globalBuildTreeCache.get(cacheKey)
if (globalCached) {
const resolved = await globalCached
const cloned = cloneTree(resolved)
const clonedPromise = Promise.resolve(cloned)
this.buildTreeCache.set(cacheKey, clonedPromise)
return clonedPromise
}
}
const promise = this.doBuildTree(node)
if (cacheKey) {
this.buildTreeCache.set(cacheKey, promise)
globalBuildTreeCache.set(cacheKey, promise)
}
const result = await promise
// When called as the root-level buildTree (node === this.node),
// drain any fire-and-forget addComponentTree promises so that
// getComponentTrees() is populated before the caller inspects it.
if (node === this.node && this.pendingComponentTrees.length > 0) {
await Promise.all(this.pendingComponentTrees)
this.pendingComponentTrees = []
}
return result
}
private async doBuildTree(node: SceneNode): Promise<NodeTree> {
const tBuild = perfStart()
// Handle COMPONENT_SET or COMPONENT — fire addComponentTree BEFORE any early returns
// (e.g., asset detection) so that BOOLEAN conditions and INSTANCE_SWAP slots are always
// detected on children, even when the COMPONENT itself is classified as an asset.
if (
(node.type === 'COMPONENT_SET' || node.type === 'COMPONENT') &&
((this.node.type === 'COMPONENT_SET' &&
node === this.node.defaultVariant) ||
this.node.type === 'COMPONENT')
) {
this.pendingComponentTrees.push(
this.addComponentTree(
node.type === 'COMPONENT_SET' ? node.defaultVariant : node,
),
)
}
// Handle native Figma SLOT nodes — render as {slotName} in the component.
// SLOT is a newer Figma node type not yet in @figma/plugin-typings.
// The slot name is sanitized here; addComponentTree renames single slots to 'children'.
if ((node.type as string) === 'SLOT') {
perfEnd('buildTree()', tBuild)
return {
component: toCamel(sanitizePropertyName(node.name)),
props: {},
children: [],
nodeType: 'SLOT',
nodeName: node.name,
isSlot: true,
}
}
// Handle asset nodes (images/SVGs)
const assetNode = checkAssetNode(node)
if (assetNode) {
// Register in global asset registry for export commands
const assetKey = `${assetNode}/${node.name}`
if (!globalAssetNodes.has(assetKey)) {
globalAssetNodes.set(assetKey, { node, type: assetNode })
}
const props = await getProps(node)
props.src = `/${assetNode === 'svg' ? 'icons' : 'images'}/${node.name}.${assetNode}`
if (assetNode === 'svg') {
const maskColor = await checkSameColor(node)
if (maskColor) {
props.maskImage = buildCssUrl(props.src as string)
props.maskRepeat = 'no-repeat'
props.maskSize = 'contain'
props.maskPos = 'center'
props.bg = maskColor
delete props.src
}
}
perfEnd('buildTree()', tBuild)
return {
component: 'src' in props ? 'Image' : 'Box',
props,
children: [],
nodeType: node.type,
nodeName: node.name,
}
}
// Handle INSTANCE nodes first — they only need position props (all sync),
// skipping the expensive full getProps() with 6 async Figma API calls.
if (node.type === 'INSTANCE') {
const mainComponent = await getMainComponentCached(node)
// Fire addComponentTree without awaiting — it runs in the background.
// All pending promises are collected and awaited in run() before rendering.
if (mainComponent) {
this.pendingComponentTrees.push(this.addComponentTree(mainComponent))
}
const componentName = getComponentName(mainComponent || node)
const variantProps = extractInstanceVariantProps(node)
// Check for native SLOT children and build their overridden content.
// SLOT children contain the content placed into the component's slot.
// Group by slot name to distinguish single-slot (children) vs multi-slot (named props).
const slotsByName = new Map<string, NodeTree[]>()
if ('children' in node) {
for (const child of node.children) {
if ((child.type as string) === 'SLOT' && 'children' in child) {
const slotName = toCamel(sanitizePropertyName(child.name))
const content: NodeTree[] = []
for (const slotContent of (child as SceneNode & ChildrenMixin)
.children) {
content.push(await this.buildTree(slotContent))
}
if (content.length > 0) {
slotsByName.set(slotName, content)
}
}
}
}
// Single SLOT → pass content as children (renders as <Comp>content</Comp>)
// Multiple SLOTs → render each as a named JSX prop (renders as <Comp header={<X/>} content={<Y/>} />)
let slotChildren: NodeTree[] = []
if (slotsByName.size === 1) {
slotChildren = [...slotsByName.values()][0]
} else if (slotsByName.size > 1) {
for (const [slotName, content] of slotsByName) {
let jsx: string
if (content.length === 1) {
jsx = Codegen.renderTree(content[0], 0)
} else {
const children = content.map((c) => Codegen.renderTree(c, 0))
const childrenStr = children
.map((c) => paddingLeftMultiline(c, 1))
.join('\n')
jsx = `<>\n${childrenStr}\n</>`
}
variantProps[slotName] = { __jsxSlot: true, jsx }
}
}
// Only compute position + transform (sync, no Figma API calls)
const posProps = getPositionProps(node)
if (posProps?.pos) {
const transformProps = getTransformProps(node)
perfEnd('buildTree()', tBuild)
return {
component: 'Box',
props: {
pos: posProps.pos,
top: posProps.top,
left: posProps.left,
right: posProps.right,
bottom: posProps.bottom,
transform: posProps.transform || transformProps?.transform,
w:
(getPageNode(node as BaseNode & ChildrenMixin) as SceneNode)
?.width === node.width
? '100%'
: undefined,
},
children: [
{
component: componentName,
props: variantProps,
children: slotChildren,
nodeType: node.type,
nodeName: node.name,
isComponent: true,
},
],
nodeType: 'WRAPPER',
nodeName: `${node.name}_wrapper`,
}
}
perfEnd('buildTree()', tBuild)
return {
component: componentName,
props: variantProps,
children: slotChildren,
nodeType: node.type,
nodeName: node.name,
isComponent: true,
}
}
// Fire getProps early for non-INSTANCE nodes — it runs while we process children.
const propsPromise = getProps(node)
// Build children sequentially — Figma's single-threaded IPC means
// concurrent subtree builds add overhead without improving throughput,
// and sequential order maximizes cache hits for shared nodes.
const children: NodeTree[] = []
if ('children' in node) {
for (const child of node.children) {
children.push(await this.buildTree(child))
}
}
// Now await props (likely already resolved while children were processing)
const baseProps = await propsPromise
// Handle TEXT nodes — create NEW merged object instead of mutating getProps() result.
let textChildren: string[] | undefined
let props: Record<string, unknown>
if (node.type === 'TEXT') {
const { children: textContent, props: textProps } = await renderText(node)
textChildren = textContent
props = { ...baseProps, ...textProps }
} else {
props = baseProps
}
const component = getDevupComponentByNode(node, props)
perfEnd('buildTree()', tBuild)
return {
component,
props,
children,
nodeType: node.type,
nodeName: node.name,
textChildren,
}
}
/**
* Get the NodeTree representation of the node.
* Builds the tree if not already built.
*/
async getTree(): Promise<NodeTree> {
if (!this.tree) {
this.tree = await this.buildTree(this.node)
// Await any fire-and-forget addComponentTree calls launched during buildTree
if (this.pendingComponentTrees.length > 0) {
await Promise.all(this.pendingComponentTrees)
this.pendingComponentTrees = []
}
}
return this.tree
}
/**
* Get component trees (for COMPONENT_SET/COMPONENT nodes).
*/
getComponentTrees(): Map<string, ComponentTree> {
return this.componentTrees
}
/**
* Add a component to componentTrees.
*/
// Cache in-flight addComponentTree promises to prevent duplicate work
// when multiple INSTANCE nodes reference the same component
private addComponentTreePromises: Map<string, Promise<void>> = new Map()
private async addComponentTree(node: ComponentNode): Promise<void> {
const nodeId = node.id || node.name
if (this.componentTrees.has(nodeId)) return
// If already in-flight, await the same promise
const inflight = this.addComponentTreePromises.get(nodeId)
if (inflight) return inflight
const promise = this.doAddComponentTree(node, nodeId)
this.addComponentTreePromises.set(nodeId, promise)
return promise
}
private async doAddComponentTree(
node: ComponentNode,
nodeId: string,
): Promise<void> {
const tAdd = perfStart()
// Reserve position in componentTrees so parent components appear
// before their children in Map iteration order.
// Map.set() with the same key later updates the value without changing position.
this.componentTrees.set(nodeId, {
name: getComponentName(node),
node,
tree: {
component: '',
props: {},
children: [],
nodeType: node.type,
nodeName: node.name,
},
variants: {},
})
// Fire getProps + getSelectorProps early (2 independent API calls)
const propsPromise = getProps(node)
const t = perfStart()
const selectorPropsPromise = getSelectorProps(node)
// Collect INSTANCE_SWAP and BOOLEAN property definitions for slot/condition detection.
const parentSet = node.parent?.type === 'COMPONENT_SET' ? node.parent : null
const propDefs =
parentSet?.componentPropertyDefinitions ||
node.componentPropertyDefinitions ||
{}
const instanceSwapSlots = new Map<string, string>()
const booleanSlots = new Map<string, string>()
const textSlots = new Map<string, string>()
for (const [key, def] of Object.entries(propDefs)) {
if (def.type === 'INSTANCE_SWAP') {
instanceSwapSlots.set(key, sanitizePropertyName(key))
} else if (def.type === 'BOOLEAN') {
booleanSlots.set(key, sanitizePropertyName(key))
} else if (def.type === 'TEXT') {
textSlots.set(key, sanitizePropertyName(key))
}
}
if (textSlots.size === 1) {
const [key] = [...textSlots.entries()][0]
textSlots.set(key, 'children')
}
// Build children sequentially, replacing INSTANCE_SWAP targets with slot placeholders
// and wrapping BOOLEAN-controlled children with conditional rendering.
const childrenTrees: NodeTree[] = []
if ('children' in node) {
for (const child of node.children) {
const slotName = getInstanceSwapSlotName(child, instanceSwapSlots)
if (slotName) {
const conditionName = getBooleanConditionName(child, booleanSlots)
childrenTrees.push({
component: slotName,
props: {},
children: [],
nodeType: 'SLOT',
nodeName: child.name,
isSlot: true,
condition: conditionName,
})
} else {
const tree = await this.buildTree(child)
const conditionName = getBooleanConditionName(child, booleanSlots)
if (conditionName) {
tree.condition = conditionName
}
const textPropName = getTextPropName(child, textSlots)
if (textPropName && tree.textChildren) {
tree.textChildren = [`{${textPropName}}`]
}
// Apply conditions to nested descendants (grandchildren and deeper)
applyNestedConditions(tree, child, booleanSlots, textSlots)
childrenTrees.push(tree)
}
}
}
// Await props + selectorProps (likely already resolved while children built)
const [baseProps, selectorProps] = await Promise.all([
propsPromise,
selectorPropsPromise,
])
perfEnd('getSelectorProps()', t)
const variants: Record<string, string> = {}
// Create a NEW merged object instead of mutating getProps() result.
// This allows getProps cache to return raw references without cloning.
const props = selectorProps
? { ...baseProps, ...selectorProps.props }
: baseProps
if (selectorProps) {
Object.assign(variants, selectorProps.variants)
}
const variantComments = selectorProps?.variantComments || {}
// Detect native SLOT children — single slot becomes 'children', multiple keep names.
// Exclude INSTANCE_SWAP-created slots (they're already handled by selectorProps.variants).
const instanceSwapNames = new Set(instanceSwapSlots.values())
const nativeSlots = childrenTrees.filter(
(child) =>
child.nodeType === 'SLOT' &&
child.isSlot &&
!instanceSwapNames.has(child.component),
)
if (nativeSlots.length === 1) {
// Single SLOT → rename to 'children' for idiomatic React
nativeSlots[0].component = 'children'
if (!variants.children) {
variants.children = 'React.ReactNode'
}
} else if (nativeSlots.length > 1) {
// Multiple SLOTs → keep sanitized names as individual React.ReactNode props
for (const slot of nativeSlots) {
if (!variants[slot.component]) {
variants[slot.component] = 'React.ReactNode'
}
}
}
this.componentTrees.set(nodeId, {
name: getComponentName(node),
node,
tree: {
component: getDevupComponentByProps(props),
props,
children: childrenTrees,
nodeType: node.type,
nodeName: node.name,
},
variants,
variantComments,
})
perfEnd('addComponentTree()', tAdd)
}
/**
* Check if the node is a COMPONENT_SET with viewport variant.
*/
hasViewportVariant(): boolean {
if (this.node.type !== 'COMPONENT_SET') return false
for (const key in (this.node as ComponentSetNode)
.componentPropertyDefinitions) {
if (key.toLowerCase() === 'viewport') return true
}
return false
}
/**
* Render a NodeTree to JSX string.
* Static method so it can be used independently.
*/
static renderTree(tree: NodeTree, depth: number = 0): string {
// Handle INSTANCE_SWAP slot placeholders — render as {propName}
if (tree.isSlot) {
if (tree.condition) {
return `{${tree.condition} && ${tree.component}}`
}
return `{${tree.component}}`
}
// Render the core JSX
let result: string
if (tree.textChildren && tree.textChildren.length > 0) {
result = renderNode(tree.component, tree.props, depth, tree.textChildren)
} else {
const childrenCodes = tree.children.map((child) =>
Codegen.renderTree(child, 0),
)
result = renderNode(tree.component, tree.props, depth, childrenCodes)
}
// Wrap with BOOLEAN conditional rendering if needed
if (tree.condition) {
if (result.includes('\n')) {
return `{${tree.condition} && (\n${paddingLeftMultiline(result, 1)}\n)}`
}
return `{${tree.condition} && ${result}}`
}
return result
}
}