-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcode.test.ts
More file actions
810 lines (730 loc) · 22.2 KB
/
code.test.ts
File metadata and controls
810 lines (730 loc) · 22.2 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
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
mock,
spyOn,
} from 'bun:test'
import * as devupModule from '../commands/devup'
import * as exportAssetsModule from '../commands/exportAssets'
import * as exportComponentsModule from '../commands/exportComponents'
let codeModule: typeof import('../code-impl')
beforeAll(async () => {
;(globalThis as { figma?: unknown }).figma = {
editorType: 'dev',
mode: 'codegen',
command: 'noop',
codegen: { on: mock(() => {}) },
closePlugin: mock(() => {}),
} as unknown as typeof figma
codeModule = await import('../code-impl')
})
beforeEach(() => {
spyOn(devupModule, 'exportDevup').mockImplementation(
mock(() => Promise.resolve()),
)
spyOn(devupModule, 'importDevup').mockImplementation(
mock(() => Promise.resolve()),
)
spyOn(exportAssetsModule, 'exportAssets').mockImplementation(
mock(() => Promise.resolve()),
)
spyOn(exportComponentsModule, 'exportComponents').mockImplementation(
mock(() => Promise.resolve()),
)
})
afterEach(() => {
;(globalThis as { figma?: unknown }).figma = undefined
mock.restore()
})
describe('runCommand', () => {
it.each([
['export-devup', ['json'], 'exportDevup'],
['export-devup-without-treeshaking', ['json', false], 'exportDevup'],
['export-devup-excel', ['excel'], 'exportDevup'],
['export-devup-excel-without-treeshaking', ['excel', false], 'exportDevup'],
['import-devup', ['json'], 'importDevup'],
['import-devup-excel', ['excel'], 'importDevup'],
['export-assets', [], 'exportAssets'],
['export-components', [], 'exportComponents'],
] as const)('dispatches %s', async (command, args, fn) => {
const closePlugin = mock(() => {})
const figmaMock = {
editorType: 'figma',
command,
closePlugin,
} as unknown as typeof figma
await codeModule.runCommand(figmaMock as typeof figma)
switch (fn) {
case 'exportDevup':
expect(devupModule.exportDevup).toHaveBeenCalledWith(...args)
break
case 'importDevup':
expect(devupModule.importDevup).toHaveBeenCalledWith(...args)
break
case 'exportAssets':
expect(exportAssetsModule.exportAssets).toHaveBeenCalled()
break
case 'exportComponents':
expect(exportComponentsModule.exportComponents).toHaveBeenCalled()
break
}
expect(closePlugin).toHaveBeenCalled()
})
})
describe('registerCodegen', () => {
it.each([
[
{
editorType: 'dev',
mode: 'codegen',
command: 'noop',
},
{
node: {
type: 'COMPONENT',
name: 'Test',
visible: true,
},
language: 'devup-ui',
},
],
[
{
editorType: 'dev',
mode: 'codegen',
command: 'noop',
},
{
node: {
type: 'FRAME',
name: 'Main',
visible: true,
},
language: 'devup-ui',
},
],
[
{
editorType: 'dev',
mode: 'codegen',
command: 'noop',
},
{
node: {
type: 'FRAME',
name: 'Other',
visible: true,
},
language: 'other',
},
],
] as const)('should register codegen', async (figmaInfo, event) => {
const figmaMock = {
...figmaInfo,
codegen: { on: mock(() => {}) },
closePlugin: mock(() => {}),
} as unknown as typeof figma
codeModule.registerCodegen(figmaMock)
expect(figmaMock.codegen.on).toHaveBeenCalledWith(
'generate',
expect.any(Function),
)
expect(
await (figmaMock.codegen.on as ReturnType<typeof mock>).mock.calls[0][1](
event,
),
).toMatchSnapshot()
})
it('should generate responsive code when root node is SECTION', async () => {
const figmaMock = {
editorType: 'dev',
mode: 'codegen',
command: 'noop',
codegen: { on: mock(() => {}) },
closePlugin: mock(() => {}),
} as unknown as typeof figma
codeModule.registerCodegen(figmaMock)
const sectionNode = {
type: 'SECTION',
name: 'ResponsiveSection',
visible: true,
children: [
{
type: 'FRAME',
name: 'MobileFrame',
visible: true,
width: 375,
height: 200,
children: [],
layoutMode: 'VERTICAL',
},
{
type: 'FRAME',
name: 'DesktopFrame',
visible: true,
width: 1440,
height: 200,
children: [],
layoutMode: 'HORIZONTAL',
},
],
}
const result = await (
figmaMock.codegen.on as ReturnType<typeof mock>
).mock.calls[0][1]({
node: sectionNode,
language: 'devup-ui',
})
expect(result).toMatchSnapshot()
})
})
it('should not register codegen if figma is not defined', async () => {
codeModule.run(undefined as unknown as typeof figma)
expect(devupModule.exportDevup).not.toHaveBeenCalled()
expect(devupModule.importDevup).not.toHaveBeenCalled()
expect(exportAssetsModule.exportAssets).not.toHaveBeenCalled()
expect(exportComponentsModule.exportComponents).not.toHaveBeenCalled()
})
it('should run command', async () => {
const figmaMock = {
editorType: 'figma',
command: 'export-devup',
closePlugin: mock(() => {}),
} as unknown as typeof figma
codeModule.run(figmaMock as typeof figma)
expect(devupModule.exportDevup).toHaveBeenCalledWith('json')
expect(devupModule.importDevup).not.toHaveBeenCalled()
expect(exportAssetsModule.exportAssets).not.toHaveBeenCalled()
expect(exportComponentsModule.exportComponents).not.toHaveBeenCalled()
})
it('auto-runs on module load when figma is present', async () => {
const codegenOn = mock(() => {})
;(globalThis as { figma?: unknown }).figma = {
editorType: 'dev',
mode: 'codegen',
command: 'noop',
codegen: { on: codegenOn },
closePlugin: mock(() => {}),
} as unknown as typeof figma
await import(`../code?with-figma=${Date.now()}`)
expect(codegenOn).toHaveBeenCalledWith('generate', expect.any(Function))
})
describe('extractImports', () => {
it('should extract keyframes import when code contains keyframes(', () => {
const result = codeModule.extractImports([
[
'AnimatedBox',
'<Box animationName={keyframes({ "0%": { opacity: 0 } })} />',
],
])
expect(result).toContain('keyframes')
expect(result).toContain('Box')
})
it('should extract keyframes import when code contains keyframes`', () => {
const result = codeModule.extractImports([
['AnimatedBox', '<Box animationName={keyframes`from { opacity: 0 }`} />'],
])
expect(result).toContain('keyframes')
expect(result).toContain('Box')
})
it('should not extract keyframes when not present', () => {
const result = codeModule.extractImports([
['SimpleBox', '<Box w="100px" />'],
])
expect(result).not.toContain('keyframes')
expect(result).toContain('Box')
})
})
describe('extractCustomComponentImports', () => {
it('should extract custom component imports', () => {
const result = codeModule.extractCustomComponentImports([
['MyComponent', '<Box><CustomButton /><CustomInput /></Box>'],
])
expect(result).toContain('CustomButton')
expect(result).toContain('CustomInput')
expect(result).not.toContain('Box')
expect(result).not.toContain('MyComponent')
})
it('should not include devup-ui components', () => {
const result = codeModule.extractCustomComponentImports([
[
'MyComponent',
'<Box><Flex><VStack><CustomCard /></VStack></Flex></Box>',
],
])
expect(result).toContain('CustomCard')
expect(result).not.toContain('Box')
expect(result).not.toContain('Flex')
expect(result).not.toContain('VStack')
})
it('should return empty array when no custom components', () => {
const result = codeModule.extractCustomComponentImports([
['MyComponent', '<Box><Flex><Text>Hello</Text></Flex></Box>'],
])
expect(result).toEqual([])
})
it('should sort custom components alphabetically', () => {
const result = codeModule.extractCustomComponentImports([
['MyComponent', '<Box><Zebra /><Apple /><Mango /></Box>'],
])
expect(result).toEqual(['Apple', 'Mango', 'Zebra'])
})
it('should handle multiple components with same custom component', () => {
const result = codeModule.extractCustomComponentImports([
['ComponentA', '<Box><SharedButton /></Box>'],
['ComponentB', '<Flex><SharedButton /></Flex>'],
])
expect(result).toEqual(['SharedButton'])
})
it('should handle nested custom components', () => {
const result = codeModule.extractCustomComponentImports([
['Parent', '<Box><ChildA><ChildB><ChildC /></ChildB></ChildA></Box>'],
])
expect(result).toContain('ChildA')
expect(result).toContain('ChildB')
expect(result).toContain('ChildC')
})
})
describe('registerCodegen with viewport variant', () => {
type CodegenHandler = (event: {
node: SceneNode
language: string
}) => Promise<unknown[]>
it('should generate responsive component codes for COMPONENT_SET with viewport variant', async () => {
let capturedHandler: CodegenHandler | null = null
const figmaMock = {
editorType: 'dev',
mode: 'codegen',
command: 'noop',
codegen: {
on: (_event: string, handler: CodegenHandler) => {
capturedHandler = handler
},
},
closePlugin: mock(() => {}),
} as unknown as typeof figma
codeModule.registerCodegen(figmaMock)
expect(capturedHandler).not.toBeNull()
if (capturedHandler === null) throw new Error('Handler not captured')
const componentSetNode = {
type: 'COMPONENT_SET',
name: 'ResponsiveButton',
visible: true,
componentPropertyDefinitions: {
viewport: {
type: 'VARIANT',
defaultValue: 'desktop',
variantOptions: ['mobile', 'desktop'],
},
},
children: [
{
type: 'COMPONENT',
name: 'viewport=mobile',
visible: true,
variantProperties: { viewport: 'mobile' },
children: [],
layoutMode: 'VERTICAL',
width: 320,
height: 100,
},
{
type: 'COMPONENT',
name: 'viewport=desktop',
visible: true,
variantProperties: { viewport: 'desktop' },
children: [],
layoutMode: 'HORIZONTAL',
width: 1200,
height: 100,
},
],
defaultVariant: {
type: 'COMPONENT',
name: 'viewport=desktop',
visible: true,
variantProperties: { viewport: 'desktop' },
children: [],
},
} as unknown as SceneNode
const handler = capturedHandler as CodegenHandler
const result = await handler({
node: componentSetNode,
language: 'devup-ui',
})
// Should include responsive components result
const responsiveResult = result.find(
(r: unknown) =>
typeof r === 'object' &&
r !== null &&
'title' in r &&
(r as { title: string }).title.includes('Responsive'),
)
expect(responsiveResult).toBeDefined()
})
it('should generate responsive component with multiple variants (viewport + size)', async () => {
let capturedHandler: CodegenHandler | null = null
const figmaMock = {
editorType: 'dev',
mode: 'codegen',
command: 'noop',
codegen: {
on: (_event: string, handler: CodegenHandler) => {
capturedHandler = handler
},
},
closePlugin: mock(() => {}),
} as unknown as typeof figma
codeModule.registerCodegen(figmaMock)
expect(capturedHandler).not.toBeNull()
if (capturedHandler === null) throw new Error('Handler not captured')
// COMPONENT_SET with both viewport and size variants
const componentSetNode = {
type: 'COMPONENT_SET',
name: 'ResponsiveButton',
visible: true,
componentPropertyDefinitions: {
viewport: {
type: 'VARIANT',
defaultValue: 'desktop',
variantOptions: ['mobile', 'desktop'],
},
size: {
type: 'VARIANT',
defaultValue: 'md',
variantOptions: ['sm', 'md', 'lg'],
},
},
children: [
{
type: 'COMPONENT',
name: 'viewport=mobile, size=md',
visible: true,
variantProperties: { viewport: 'mobile', size: 'md' },
children: [],
layoutMode: 'VERTICAL',
width: 320,
height: 100,
},
{
type: 'COMPONENT',
name: 'viewport=desktop, size=md',
visible: true,
variantProperties: { viewport: 'desktop', size: 'md' },
children: [],
layoutMode: 'HORIZONTAL',
width: 1200,
height: 100,
},
],
defaultVariant: {
type: 'COMPONENT',
name: 'viewport=desktop, size=md',
visible: true,
variantProperties: { viewport: 'desktop', size: 'md' },
children: [],
},
} as unknown as SceneNode
const handler = capturedHandler as CodegenHandler
const result = await handler({
node: componentSetNode,
language: 'devup-ui',
})
// Should include responsive components result
const responsiveResult = result.find(
(r: unknown) =>
typeof r === 'object' &&
r !== null &&
'title' in r &&
(r as { title: string }).title.includes('Responsive'),
)
expect(responsiveResult).toBeDefined()
// The generated code should include the size variant in the interface
const resultWithCode = responsiveResult as { code: string } | undefined
if (resultWithCode?.code) {
expect(resultWithCode.code).toContain('size')
}
})
it('should generate responsive code for node with parent SECTION', async () => {
let capturedHandler: CodegenHandler | null = null
const figmaMock = {
editorType: 'dev',
mode: 'codegen',
command: 'noop',
codegen: {
on: (_event: string, handler: CodegenHandler) => {
capturedHandler = handler
},
},
closePlugin: mock(() => {}),
} as unknown as typeof figma
codeModule.registerCodegen(figmaMock)
expect(capturedHandler).not.toBeNull()
if (capturedHandler === null) throw new Error('Handler not captured')
// Create a SECTION node with children of different widths
const sectionNode = {
type: 'SECTION',
name: 'ResponsiveSection',
visible: true,
children: [
{
type: 'FRAME',
name: 'MobileFrame',
visible: true,
width: 375,
height: 200,
children: [],
layoutMode: 'VERTICAL',
},
{
type: 'FRAME',
name: 'DesktopFrame',
visible: true,
width: 1200,
height: 200,
children: [],
layoutMode: 'HORIZONTAL',
},
],
}
// Create a child node that has the SECTION as parent
const childNode = {
type: 'FRAME',
name: 'ChildFrame',
visible: true,
width: 375,
height: 100,
children: [],
layoutMode: 'VERTICAL',
parent: sectionNode,
} as unknown as SceneNode
const handler = capturedHandler as CodegenHandler
const result = await handler({
node: childNode,
language: 'devup-ui',
})
// Should include responsive result from parent section
const responsiveResult = result.find(
(r: unknown) =>
typeof r === 'object' &&
r !== null &&
'title' in r &&
(r as { title: string }).title.includes('Responsive'),
)
expect(responsiveResult).toBeDefined()
})
it('should generate CLI with custom component imports', async () => {
let capturedHandler: CodegenHandler | null = null
const figmaMock = {
editorType: 'dev',
mode: 'codegen',
command: 'noop',
codegen: {
on: (_event: string, handler: CodegenHandler) => {
capturedHandler = handler
},
},
closePlugin: mock(() => {}),
} as unknown as typeof figma
codeModule.registerCodegen(figmaMock)
expect(capturedHandler).not.toBeNull()
if (capturedHandler === null) throw new Error('Handler not captured')
// Create a custom component that will be referenced
const customComponent = {
type: 'COMPONENT',
name: 'CustomButton',
visible: true,
children: [],
width: 100,
height: 40,
layoutMode: 'NONE',
componentPropertyDefinitions: {},
parent: null,
}
// Create an INSTANCE referencing the custom component
const instanceNode = {
type: 'INSTANCE',
name: 'CustomButton',
visible: true,
width: 100,
height: 40,
getMainComponentAsync: async () => customComponent,
}
// Create a COMPONENT that contains the INSTANCE
const componentNode = {
type: 'COMPONENT',
name: 'MyComponent',
visible: true,
children: [instanceNode],
width: 200,
height: 100,
layoutMode: 'VERTICAL',
componentPropertyDefinitions: {},
reactions: [],
parent: null,
} as unknown as SceneNode
// Create COMPONENT_SET parent with proper children array
const componentSetNode = {
type: 'COMPONENT_SET',
name: 'MyComponentSet',
componentPropertyDefinitions: {},
children: [componentNode],
defaultVariant: componentNode,
reactions: [],
}
// Set parent reference
;(componentNode as { parent: unknown }).parent = componentSetNode
const handler = capturedHandler as CodegenHandler
const result = await handler({
node: componentNode,
language: 'devup-ui',
})
// Should include CLI outputs
const bashCLI = result.find(
(r: unknown) =>
typeof r === 'object' &&
r !== null &&
'title' in r &&
(r as { title: string }).title.includes('CLI (Bash)'),
)
const powershellCLI = result.find(
(r: unknown) =>
typeof r === 'object' &&
r !== null &&
'title' in r &&
(r as { title: string }).title.includes('CLI (PowerShell)'),
)
expect(bashCLI).toBeDefined()
expect(powershellCLI).toBeDefined()
// Check that custom component import is included (bash escapes quotes)
const bashCode = (bashCLI as { code: string } | undefined)?.code
const powershellCode = (powershellCLI as { code: string } | undefined)?.code
if (bashCode) {
expect(bashCode).toContain(
"import { CustomButton } from \\'@/components/CustomButton\\'",
)
}
if (powershellCode) {
expect(powershellCode).toContain(
"import { CustomButton } from '@/components/CustomButton'",
)
}
})
it('should generate componentsResponsiveCodes when FRAME contains INSTANCE of COMPONENT_SET with viewport', async () => {
let capturedHandler: CodegenHandler | null = null
const figmaMock = {
editorType: 'dev',
mode: 'codegen',
command: 'noop',
codegen: {
on: (_event: string, handler: CodegenHandler) => {
capturedHandler = handler
},
},
closePlugin: mock(() => {}),
} as unknown as typeof figma
codeModule.registerCodegen(figmaMock)
expect(capturedHandler).not.toBeNull()
if (capturedHandler === null) throw new Error('Handler not captured')
// Create a COMPONENT_SET with viewport variants
const componentSetNode = {
type: 'COMPONENT_SET',
name: 'ResponsiveButton',
visible: true,
componentPropertyDefinitions: {
viewport: {
type: 'VARIANT',
defaultValue: 'desktop',
variantOptions: ['mobile', 'desktop'],
},
},
children: [] as unknown[],
defaultVariant: null as unknown,
}
// Create COMPONENT children for the COMPONENT_SET
const mobileComponent = {
type: 'COMPONENT',
name: 'viewport=mobile',
visible: true,
variantProperties: { viewport: 'mobile' },
children: [],
layoutMode: 'VERTICAL',
width: 320,
height: 100,
parent: componentSetNode,
componentPropertyDefinitions: {},
reactions: [],
}
const desktopComponent = {
type: 'COMPONENT',
name: 'viewport=desktop',
visible: true,
variantProperties: { viewport: 'desktop' },
children: [],
layoutMode: 'HORIZONTAL',
width: 1200,
height: 100,
parent: componentSetNode,
componentPropertyDefinitions: {},
reactions: [],
}
componentSetNode.children = [mobileComponent, desktopComponent]
componentSetNode.defaultVariant = desktopComponent
// Create an INSTANCE that references the desktop component
const instanceNode = {
type: 'INSTANCE',
name: 'ResponsiveButton',
visible: true,
width: 1200,
height: 100,
getMainComponentAsync: async () => desktopComponent,
}
// Create a FRAME that contains the INSTANCE
const frameNode = {
type: 'FRAME',
name: 'MyFrame',
visible: true,
children: [instanceNode],
width: 1400,
height: 200,
layoutMode: 'VERTICAL',
} as unknown as SceneNode
const handler = capturedHandler as CodegenHandler
const result = await handler({
node: frameNode,
language: 'devup-ui',
})
// Should include Components Responsive results
const responsiveResult = result.find(
(r: unknown) =>
typeof r === 'object' &&
r !== null &&
'title' in r &&
(r as { title: string }).title === 'MyFrame - Components Responsive',
)
expect(responsiveResult).toBeDefined()
// Should also include CLI results for Components Responsive
const bashCLI = result.find(
(r: unknown) =>
typeof r === 'object' &&
r !== null &&
'title' in r &&
(r as { title: string }).title ===
'MyFrame - Components Responsive CLI (Bash)',
)
expect(bashCLI).toBeDefined()
const powershellCLI = result.find(
(r: unknown) =>
typeof r === 'object' &&
r !== null &&
'title' in r &&
(r as { title: string }).title ===
'MyFrame - Components Responsive CLI (PowerShell)',
)
expect(powershellCLI).toBeDefined()
})
})