-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtemp_editor.jsx
More file actions
1775 lines (1658 loc) Β· 111 KB
/
Copy pathtemp_editor.jsx
File metadata and controls
1775 lines (1658 loc) Β· 111 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 React, { useState, useRef, useCallback, useEffect, useMemo } from 'react'
import { useNavigate } from 'react-router-dom'
import Editor from 'react-simple-code-editor'
import Prism from 'prismjs/components/prism-core'
import 'prismjs/components/prism-clike'
import 'prismjs/components/prism-javascript'
import 'prismjs/components/prism-markup'
import 'prismjs/themes/prism-tomorrow.css'
import JSZip from 'jszip'
import * as Babel from '@babel/standalone'
import * as EmulatorComponents from '@openhw/emulator/src/components/index.ts'
// βββ Component Registry (same as SimulatorPage) βββββββββββββββββββββββββββββββ
const COMP_REGISTRY = {}
Object.entries(EmulatorComponents).forEach(([key, module]) => {
if (key === 'BaseComponent') return
if (module && module.manifest) {
const compId = module.manifest.type || module.manifest.id || key
COMP_REGISTRY[compId] = module
}
})
const CATALOG = []
const CATALOG_PIN_DEFS = {}
Object.values(COMP_REGISTRY).forEach(module => {
const manifest = module.manifest
let group = CATALOG.find(g => g.group === manifest.group)
if (!group) { group = { group: manifest.group, items: [] }; CATALOG.push(group) }
const { pins, group: _, ...catalogItem } = manifest
group.items.push(catalogItem)
if (pins) CATALOG_PIN_DEFS[manifest.type] = pins
})
// βββ Constants ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const GROUPS = ['Sensors', 'Outputs', 'Inputs', 'Power', 'Communication', 'Logic', 'Display', 'Other']
const PIN_TYPES = ['digital', 'analog', 'power', 'nc', 'i2c', 'spi', 'uart']
const STEPS = [
{ id:1, label:'Component Details', desc:'Type, label, group and context menu flags' },
{ id:2, label:'Component Image', desc:'Upload SVG, code SVG, or write React JSX for the visual' },
{ id:3, label:'Dimensions', desc:'Canvas size and interactive BOUNDS rectangle' },
{ id:4, label:'Pins', desc:'Place and define electrical pins' },
{ id:5, label:'Simulation', desc:'Write logic.ts, validation.ts and ui.tsx' },
{ id:6, label:'Docs', desc:'Documentation HTML page' },
{ id:7, label:'Save & Export', desc:'Download ZIP or test in simulator' },
]
// Grid cell size β must match simulator's 24 Γ 24 px
const GRID = 24
// Reference component definitions for the Canvas Panel β includes inline SVGs
const REF_COMPONENTS = [
{
label:'LED', w:38, h:38, color:'#ff4444', desc:'wokwi-led',
svg:`<svg xmlns="http://www.w3.org/2000/svg" width="38" height="38" viewBox="0 0 38 38">
<rect x="11" y="27" width="2.5" height="11" fill="#aaa"/>
<rect x="24.5" y="27" width="2.5" height="11" fill="#aaa"/>
<rect x="12" y="30" width="5" height="2" fill="#777"/>
<ellipse cx="19" cy="17" rx="11" ry="12" fill="#1a1a1a" stroke="#555" stroke-width="1.5"/>
<ellipse cx="19" cy="17" rx="7.5" ry="8.5" fill="rgba(255,60,60,0.75)"/>
<ellipse cx="16" cy="13" rx="3" ry="3.5" fill="rgba(255,255,255,0.22)"/>
</svg>`,
},
{
label:'Resistor', w:60, h:24, color:'#c19a6b', desc:'wokwi-resistor',
svg:`<svg xmlns="http://www.w3.org/2000/svg" width="60" height="24" viewBox="0 0 60 24">
<line x1="0" y1="12" x2="12" y2="12" stroke="#aaa" stroke-width="1.5"/>
<line x1="48" y1="12" x2="60" y2="12" stroke="#aaa" stroke-width="1.5"/>
<rect x="12" y="6" width="36" height="12" rx="3" fill="#c8a86b" stroke="#8a6a35" stroke-width="1"/>
<line x1="20" y1="6" x2="20" y2="18" stroke="#f4a" stroke-width="1.5"/>
<line x1="26" y1="6" x2="26" y2="18" stroke="#744" stroke-width="1.5"/>
<line x1="32" y1="6" x2="32" y2="18" stroke="#f80" stroke-width="1.5"/>
<line x1="38" y1="6" x2="38" y2="18" stroke="#888" stroke-width="1.5"/>
</svg>`,
},
{
label:'Uno', w:182, h:128, color:'#3a86ff', desc:'wokwi-arduino-uno',
svg:`<svg xmlns="http://www.w3.org/2000/svg" width="182" height="128" viewBox="0 0 182 128">
<rect x="2" y="2" width="178" height="124" rx="6" fill="#0e5a8a" stroke="#0a3f62" stroke-width="1.5"/>
<rect x="153" y="18" width="24" height="16" rx="2" fill="#666" stroke="#444" stroke-width="1"/>
<rect x="2" y="5" width="55" height="12" rx="2" fill="#0a3f62"/>
<rect x="2" y="111" width="50" height="12" rx="2" fill="#0a3f62"/>
<rect x="8" y="7" width="4" height="8" rx="1" fill="#aaa"/>
<rect x="15" y="7" width="4" height="8" rx="1" fill="#aaa"/>
<rect x="22" y="7" width="4" height="8" rx="1" fill="#aaa"/>
<rect x="29" y="7" width="4" height="8" rx="1" fill="#aaa"/>
<rect x="36" y="7" width="4" height="8" rx="1" fill="#aaa"/>
<rect x="43" y="7" width="4" height="8" rx="1" fill="#aaa"/>
<rect x="8" y="113" width="4" height="8" rx="1" fill="#aaa"/>
<rect x="15" y="113" width="4" height="8" rx="1" fill="#aaa"/>
<rect x="22" y="113" width="4" height="8" rx="1" fill="#aaa"/>
<rect x="29" y="113" width="4" height="8" rx="1" fill="#aaa"/>
<rect x="36" y="113" width="4" height="8" rx="1" fill="#aaa"/>
<rect x="48" y="38" width="62" height="44" rx="4" fill="#0a0a0a" stroke="#333" stroke-width="1"/>
<text x="79" y="63" text-anchor="middle" fill="#4ade80" font-size="6" font-family="monospace">ATmega328P</text>
<rect x="125" y="95" width="8" height="8" rx="2" fill="#000" stroke="#333" stroke-width="1"/>
<circle cx="129" cy="58" r="4" fill="#4ade80" opacity="0.9"/>
<circle cx="139" cy="58" r="4" fill="#ff4444" opacity="0.7"/>
<rect x="153" y="62" width="20" height="30" rx="2" fill="#111" stroke="#333" stroke-width="1"/>
<text x="91" y="120" text-anchor="middle" fill="#74b9ff" font-size="7" font-family="monospace" font-weight="bold">Arduino Uno</text>
</svg>`,
},
{
label:'Servo', w:56, h:72, color:'#f39c12', desc:'wokwi-servo',
svg:`<svg xmlns="http://www.w3.org/2000/svg" width="56" height="72" viewBox="0 0 56 72">
<rect x="3" y="10" width="50" height="52" rx="5" fill="#2c2c2c" stroke="#444" stroke-width="1.5"/>
<rect x="8" y="18" width="40" height="30" rx="3" fill="#1a1a1a"/>
<circle cx="28" cy="33" r="10" fill="#333" stroke="#555" stroke-width="1.5"/>
<circle cx="28" cy="33" r="5" fill="#555"/>
<line x1="28" y1="33" x2="28" y2="24" stroke="#f39c12" stroke-width="2" stroke-linecap="round"/>
<rect x="20" y="56" width="5" height="10" rx="1" fill="#fff"/>
<rect x="27" y="56" width="5" height="10" rx="1" fill="#aaa"/>
<rect x="34" y="56" width="5" height="10" rx="1" fill="#333"/>
<rect x="0" y="26" width="6" height="5" rx="1" fill="#333"/>
<rect x="50" y="26" width="6" height="5" rx="1" fill="#333"/>
</svg>`,
},
]
// βββ Grid styles β same formula as SimulatorPage ββββββββββββββββββββββββββββββ
const mkGrid = (size = GRID, dark = true) => ({
backgroundImage: `linear-gradient(var(--border) 1px, transparent 1px), linear-gradient(90deg, var(--border) 1px, transparent 1px)`,
backgroundSize: `${size}px ${size}px`,
backgroundColor: 'var(--canvas-bg)',
})
// βββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function toPascalCase(s) {
return s.replace(/[^a-zA-Z0-9]+(.)/g, (_, c) => c.toUpperCase())
.replace(/^[a-z]/, c => c.toUpperCase())
.replace(/[^a-zA-Z0-9]/g, '') || 'MyComponent'
}
function normalizeSvg(svg, w, h) {
if (!svg) return svg
// Preserve or derive viewBox so the SVG scales properly
const vbMatch = svg.match(/\bviewBox="([^"]+)"/)
let viewBox = vbMatch ? vbMatch[1] : null
if (!viewBox) {
// Derive from existing width/height attrs on the <svg> tag, fall back to component dims
const wm = svg.match(/<svg\b[^>]*?\bwidth="([\d.]+)"/)
const hm = svg.match(/<svg\b[^>]*?\bheight="([\d.]+)"/)
const vw = wm ? parseFloat(wm[1]) : w
const vh = hm ? parseFloat(hm[1]) : h
viewBox = `0 0 ${vw || w} ${vh || h}`
}
return svg.replace(
/(<svg\b[^>]*?)(\s+viewBox="[^"]*")?(\s+width="[^"]*")?(\s+height="[^"]*")?(\s*\/?>)/,
(_, pre, _vb, _w, _h, close) => {
const stripped = pre
.replace(/\s+viewBox="[^"]*"/gi, '')
.replace(/\s+width="[^"]*"/gi, '')
.replace(/\s+height="[^"]*"/gi, '')
return `${stripped} viewBox="${viewBox}" width="${w}" height="${h}"${close}`
}
)
}
// Make an SVG responsive by replacing fixed width/height with 100% while preserving
// the original viewBox so the content scales correctly inside any container.
function svgToFluid(svg) {
if (!svg) return svg
// Extract existing viewBox or derive one from the width/height attributes
const vbMatch = svg.match(/\bviewBox="([^"]+)"/)
let viewBox = vbMatch ? vbMatch[1] : null
if (!viewBox) {
const wm = svg.match(/<svg\b[^>]*?\bwidth="([\d.]+)"/)
const hm = svg.match(/<svg\b[^>]*?\bheight="([\d.]+)"/)
const vw = wm ? parseFloat(wm[1]) : 100
const vh = hm ? parseFloat(hm[1]) : 80
viewBox = `0 0 ${vw} ${vh}`
}
return svg.replace(
/<svg(\b[^>]*?)>/,
(_, attrs) => {
const cleaned = attrs
.replace(/\s+viewBox="[^"]*"/gi, '')
.replace(/\s+width="[^"]*"/gi, '')
.replace(/\s+height="[^"]*"/gi, '')
return `<svg${cleaned} viewBox="${viewBox}" width="100%" height="100%">`
}
)
}
// βββ Code generators ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function genManifest(d) {
return JSON.stringify({
type: d.type || 'my-component', label: d.label || 'My Component', group: d.group || 'Other',
w: Number(d.w)||100, h: Number(d.h)||80,
...(d.description ? { description: d.description } : {}),
pins: (d.pins||[]).map(({ id,x,y,type,description }) => ({ id,x,y,type,...(description?{description}:{}) })),
...(d.contextMenuDuringRun ? { contextMenuDuringRun: true } : {}),
...(d.contextMenuOnlyDuringRun? { contextMenuOnlyDuringRun: true } : {}),
}, null, 2)
}
function genUICode(d) {
const name = toPascalCase(d.type), w = Number(d.w)||100, h = Number(d.h)||80
const b = d.bounds || { x:5, y:5, w:w-10, h:h-10 }
const boundsLine = `export const BOUNDS = { x: ${b.x}, y: ${b.y}, w: ${b.w}, h: ${b.h} };\n`
const ctxLines = (d.contextMenuDuringRun?'export const contextMenuDuringRun = true;\n':'') + (d.contextMenuOnlyDuringRun?'export const contextMenuOnlyDuringRun = true;\n':'')
// React JSX mode β embed the user's exported component directly
if (d.imageMode === 'react' && d.reactCode?.trim()) {
return `import React from 'react';\n\n${boundsLine}${ctxLines}\n// ββ Component UI (React mode) ββββββββββββββββββββββββββββββββββββββ\n${d.reactCode}\n`
}
// SVG mode β wrap SVG in a div.
// svgToFluid converts fixed width/height to 100%/100% so the SVG always fills
// its container (the comp.w Γ comp.h div in the simulator) without overflowing.
const rawSvg = d.svgCode || `<svg width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" xmlns="http://www.w3.org/2000/svg">
<rect x="2" y="2" width="${w-4}" height="${h-4}" rx="6" fill="#1e1e2e" stroke="#4ade80" strokeWidth="2"/>
<text x="${w/2}" y="${h/2+4}" textAnchor="middle" fill="#4ade80" fontSize="11" fontFamily="monospace">${d.label||'Component'}</text>
</svg>`
const svg = svgToFluid(rawSvg).split('\n').join('\n ')
return `import React from 'react';\n\n${boundsLine}${ctxLines}\nexport const ${name}UI = ({ state, attrs, isRunning }: { state:any; attrs:any; isRunning:boolean }) => (\n <div style={{ pointerEvents:'none', position:'absolute', inset:0 }}>\n ${svg}\n </div>\n);\n`
}
function genLogicCode(d) {
const name = toPascalCase(d.type)
return `import { BaseComponent } from '../../BaseComponent';\n\nexport class ${name}Logic extends BaseComponent {\n private state: any = {};\n reset() { this.state = {}; }\n getSyncState() { return this.state; }\n update(cpuCycles: number, wires: any[], allInstances: any[]) {\n // this.getPinVoltage('VCC') / this.setPinVoltage('OUT', 5)\n }\n onPinStateChange(pinId: string, isHigh: boolean, cpuCycles: number) {}\n}\n`
}
function genValidationCode(d) {
return `// Return { pass: true } for OK, { pass: false, message: '...' } for an error.\nexport const validation = [\n // {\n // id: '${d.type||'my-component'}-vcc',\n // description: 'VCC must be connected',\n // check: (component, wires) => {\n // const pin = component.manifest?.pins?.find(p => p.id === 'VCC');\n // if (!pin) return { pass: true };\n // const ok = wires.some(\n // w => (w.from?.id === component.id && w.from?.pin === pin.id)\n // || (w.to?.id === component.id && w.to?.pin === pin.id)\n // );\n // return { pass: ok, message: ok ? undefined : '${d.label||'Component'}: VCC not connected.' };\n // },\n // },\n];\n`
}
function genIndexCode(d) {
const name = toPascalCase(d.type)
const extras = [d.contextMenuDuringRun&&'contextMenuDuringRun', d.contextMenuOnlyDuringRun&&'contextMenuOnlyDuringRun'].filter(Boolean)
return `import manifest from './manifest.json';\nimport { ${name}UI, BOUNDS${extras.length?', '+extras.join(', '):''} } from './ui';\nimport { ${name}Logic } from './logic';\nimport { validation } from './validation';\n\nexport default {\n manifest,\n UI: ${name}UI,\n LogicClass: ${name}Logic,\n BOUNDS,\n validation,${extras.map(e=>`\n ${e},`).join('')}\n};\n`
}
function genDocsHTML(d) {
return `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"/><title>${d.label||'Component'}</title><style>body{font-family:system-ui,sans-serif;max-width:800px;margin:40px auto;padding:0 20px;background:#0f0f0f;color:#e0e0e0;line-height:1.6}h1{color:#4ade80}h2{color:#86efac;border-bottom:1px solid #333;padding-bottom:8px}code{background:#1e1e2e;padding:2px 6px;border-radius:4px;font-family:monospace}pre{background:#1e1e2e;padding:16px;border-radius:8px}table{width:100%;border-collapse:collapse}td,th{padding:8px 12px;border:1px solid #333}th{background:#1e1e2e;color:#4ade80}</style></head><body><h1>${d.label||'Component'}</h1><p>${d.description||''}</p><h2>Pinout</h2><table><tr><th>Pin</th><th>Type</th><th>Description</th></tr>${(d.pins||[]).map(p=>`<tr><td><code>${p.id}</code></td><td>${p.type}</td><td>${p.description||''}</td></tr>`).join('')}</table><h2>Usage</h2><pre><code>// TODO</code></pre><h2>Notes</h2><ul><li>Size: ${d.w}Γ${d.h} px</li><li>Pins: ${(d.pins||[]).length}</li></ul></body></html>`
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// DragResizeBox
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const HDefs = [
{ id:'nw', pos:{ top:-5, left:-5, cursor:'nw-resize' } },
{ id:'n', pos:{ top:-5, left:'50%', transform:'translateX(-50%)', cursor:'n-resize' } },
{ id:'ne', pos:{ top:-5, right:-5, cursor:'ne-resize' } },
{ id:'e', pos:{ top:'50%', right:-5, transform:'translateY(-50%)', cursor:'e-resize' } },
{ id:'se', pos:{ bottom:-5, right:-5, cursor:'se-resize' } },
{ id:'s', pos:{ bottom:-5, left:'50%', transform:'translateX(-50%)', cursor:'s-resize' } },
{ id:'sw', pos:{ bottom:-5, left:-5, cursor:'sw-resize' } },
{ id:'w', pos:{ top:'50%', left:-5, transform:'translateY(-50%)', cursor:'w-resize' } },
]
function DragResizeBox({ bx=0, by=0, bw=100, bh=100, scale=1, color='#4ade80', label, onChange, onEnd, noMove=false, onlyEdges=false, snap=0 }) {
const startDrag = useCallback((e, handle) => {
e.stopPropagation(); e.preventDefault()
const ox = e.clientX, oy = e.clientY, sv = { x:bx, y:by, w:bw, h:bh }
const move = (me) => {
const dx = (me.clientX-ox)/scale, dy = (me.clientY-oy)/scale
let { x,y,w,h } = sv
if (handle==='move') { x+=dx; y+=dy }
if (handle.includes('w')) { x+=dx; w=Math.max(snap||10,w-dx) }
if (handle.includes('e')) { w=Math.max(snap||10,w+dx) }
if (handle.includes('n')) { y+=dy; h=Math.max(snap||10,h-dy) }
if (handle.includes('s')) { h=Math.max(snap||10,h+dy) }
if (snap > 1) {
x = Math.round(x / snap) * snap
y = Math.round(y / snap) * snap
w = Math.max(snap, Math.round(w / snap) * snap)
h = Math.max(snap, Math.round(h / snap) * snap)
} else {
x = Math.round(x); y = Math.round(y)
w = Math.round(w); h = Math.round(h)
}
onChange({ x, y, w, h })
}
const up = () => { onEnd?.(); document.removeEventListener('pointermove',move); document.removeEventListener('pointerup',up) }
document.addEventListener('pointermove',move); document.addEventListener('pointerup',up)
}, [bx,by,bw,bh,scale,onChange,onEnd,snap])
const handles = onlyEdges ? HDefs.filter(h=>['se','s','e'].includes(h.id)) : HDefs
return (
<div style={{ position:'absolute', left:bx*scale, top:by*scale, width:bw*scale, height:bh*scale, border:`2px solid ${color}`, background:`${color}0d`, zIndex:15, boxSizing:'border-box', pointerEvents:'all' }}>
{label && <div style={{ position:'absolute', top:-17, left:0, fontSize:9, fontWeight:700, color, background:'var(--bg)', padding:'1px 4px', borderRadius:3, whiteSpace:'nowrap' }}>{label}</div>}
{!noMove && <div onPointerDown={e=>startDrag(e,'move')} style={{ position:'absolute', inset:8, cursor:'move', zIndex:16 }} />}
{handles.map(h=>(
<div key={h.id} onPointerDown={e=>startDrag(e,h.id)}
style={{ position:'absolute', width:10, height:10, background:color, border:'2px solid rgba(0,0,0,.5)', borderRadius:2, zIndex:17, ...h.pos }} />
))}
</div>
)
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// SvgPreview β mirrors simulator rendering exactly:
// outer div is w*zoom Γ h*zoom, inner is wΓh (CSS scaled), SVG is fluid
// (width/height=100%) inside a position:absolute inset:0 wrapper β same as
// the <div style={{ pointerEvents:'none', position:'absolute', inset:0 }}><svg>
// pattern that genUICode generates for the simulator.
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function SvgPreview({ svgCode, compW, compH, zoom=1, style }) {
const w = Number(compW)||100, h = Number(compH)||80
const fluid = useMemo(()=>svgToFluid(svgCode),[svgCode])
return (
<div style={{ position:'relative', width:w*zoom, height:h*zoom, flexShrink:0, overflow:'hidden', ...style }}>
{fluid
? <div style={{ position:'absolute', top:0, left:0, width:w, height:h, transform:`scale(${zoom})`, transformOrigin:'top left', pointerEvents:'none' }}>
<div style={{ position:'absolute', inset:0 }}
dangerouslySetInnerHTML={{ __html: fluid }} />
</div>
: <div style={{ position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center', background:'#1e1e2e', border:'1px dashed #333', borderRadius:4 }}>
<span style={{ color:'#555', fontSize:11 }}>{w}Γ{h}</span>
</div>
}
</div>
)
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ReactPreview β compiles JSX code with Babel and renders it
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function ReactPreview({ reactCode, compW, compH, zoom=1, style }) {
const w = Number(compW)||100, h = Number(compH)||80
const [el, setEl] = useState(null)
const [err, setErr] = useState(null)
useEffect(() => {
if (!reactCode?.trim()) { setEl(null); setErr(null); return }
try {
const transformed = Babel.transform(reactCode, { filename:'ui.tsx', presets: ['react', 'typescript', 'env'] }).code
const mod = { exports: {} }
// Find something exported that looks like a component
// eslint-disable-next-line no-new-func
const evalFn = new Function('exports', 'require', 'React', transformed)
evalFn(mod.exports, (m) => m === 'react' ? React : null, React)
const keys = Object.keys(mod.exports)
const compKey = keys.find(k => /ui|component|view|preview/i.test(k)) || keys[0]
const Comp = mod.exports[compKey]
if (typeof Comp !== 'function' && typeof Comp !== 'object') throw new Error('No exported React component found. Export a component from your code.')
setEl(React.createElement(Comp, { state:{}, attrs:{}, isRunning:false }))
setErr(null)
} catch (e) {
setErr(e.message)
setEl(null)
}
}, [reactCode])
return (
<div style={{ position:'relative', width:w*zoom, height:h*zoom, flexShrink:0, overflow:'hidden', ...style }}>
{err
? <div style={{ position:'absolute', inset:0, background:'rgba(255,68,68,.08)', border:'1px solid rgba(255,68,68,.35)', padding:'6px 8px', fontSize:10, color:'#ff6b6b', overflow:'auto', fontFamily:'monospace', borderRadius:4, lineHeight:1.5 }}>
<strong>Compile error:</strong><br/>{err}
</div>
: el
? <div style={{ position:'absolute', top:0, left:0, width:w, height:h, transform:`scale(${zoom})`, transformOrigin:'top left', pointerEvents:'none' }}>{el}</div>
: <div style={{ position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center', background:'#1e1e2e', border:'1px dashed #333', borderRadius:4 }}>
<span style={{ color:'#555', fontSize:11 }}>No component</span>
</div>
}
</div>
)
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// SimPin β simulator-accurate pin (5Γ5 square, hover tooltip)
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function SimPin({ pin, zoom, onClick, selected }) {
const [hovered, setHov] = useState(false)
const color = hovered || selected ? '#f1c40f' : 'rgba(255,255,255,0.25)'
const border = hovered || selected ? '#fff' : 'rgba(255,255,255,0.8)'
return (
<div style={{ position:'absolute', left:pin.x*zoom, top:pin.y*zoom, zIndex: hovered?30:20 }}
onMouseEnter={()=>setHov(true)} onMouseLeave={()=>setHov(false)} onClick={e=>{e.stopPropagation();onClick?.()}}>
<div style={{
width:5, height:5, background:color, border:`1px solid ${border}`, borderRadius:'0%',
cursor:'crosshair', transform:`translate(-50%,-50%)${hovered?' scale(1.5)':''}`, transition:'0.15s',
}} />
{hovered && (
<div style={{ position:'absolute', bottom:12, left:'50%', transform:'translateX(-50%)', background:'#111', color:'#fff', padding:'3px 7px', borderRadius:4, fontSize:10, whiteSpace:'nowrap', zIndex:9999, pointerEvents:'none', border:'1px solid #444', boxShadow:'0 2px 5px rgba(0,0,0,.5)' }}>
{pin.description||pin.id}
</div>
)}
</div>
)
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// CanvasPanel β simulator-accurate canvas preview (same engine as SimulatorPage)
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const USER_COMP_ID = '__user_comp__'
function CanvasPanel({ open, onToggle, svgCode, reactCode, imageMode, compW, compH, bounds, pins, ctxDuringRun, ctxOnlyDuringRun, compType, compLabel }) {
const w = Number(compW)||100, h = Number(compH)||80
// ββ Evaluate React code into a component (same approach as SimulatorPage) ββ
const [evalComp, setEvalComp] = useState(null)
const [evalCtxMenu, setEvalCtxMenu] = useState(null)
const [evalErr, setEvalErr] = useState(null)
const [userAttrs, setUserAttrs] = useState({})
useEffect(() => {
if (imageMode !== 'react' || !reactCode?.trim()) { setEvalComp(null); setEvalCtxMenu(null); setEvalErr(null); return }
try {
const transformed = Babel.transform(reactCode, { filename:'ui.tsx', presets: ['react', 'typescript', 'env'] }).code
const exportsUI = {}
const evalFn = new Function('exports', 'require', 'React', transformed)
evalFn(exportsUI, (m) => m === 'react' ? React : null, React)
// Match SimulatorPage: pick UI component (key ending with 'ui' or first function)
const uiKey = Object.keys(exportsUI).find(k => typeof exportsUI[k] === 'function' && k.toLowerCase().endsWith('ui'))
|| Object.keys(exportsUI).find(k => typeof exportsUI[k] === 'function')
|| Object.keys(exportsUI)[0]
const Comp = exportsUI[uiKey]
if (typeof Comp !== 'function') throw new Error('No exported React component found.')
setEvalComp(() => Comp)
// Match SimulatorPage: pick ContextMenu component
const ctxKey = Object.keys(exportsUI).find(k => k.toLowerCase().includes('contextmenu'))
setEvalCtxMenu(ctxKey && typeof exportsUI[ctxKey] === 'function' ? () => exportsUI[ctxKey] : null)
setUserAttrs({})
setEvalErr(null)
} catch (e) {
setEvalComp(null)
setEvalCtxMenu(null)
setEvalErr(e.message)
}
}, [reactCode, imageMode])
// ββ Fluid SVG for SVG mode (same approach as SimulatorPage) ββββββββββββββββ
const fluidSvg = useMemo(() => imageMode !== 'react' ? svgToFluid(svgCode) : null, [svgCode, imageMode])
// ββ Canvas state (same as SimulatorPage) ββββββββββββββββββββββββββββββββββββ
const canvasRef = useRef(null)
const [canvasOffset, setCanvasOffset] = useState({ x:80, y:80 })
const [canvasZoom, setCanvasZoom] = useState(1)
const canvasOffsetRef = useRef({ x:80, y:80 })
const canvasZoomRef = useRef(1)
const isPanningRef = useRef(false)
const panStartRef = useRef({ x:0, y:0, ox:0, oy:0 })
const didPanRef = useRef(false)
const movingCompRef = useRef(null)
// ββ UI state ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const [isRunning, setRunning] = useState(false)
const [selected, setSelected] = useState(null)
const [hoveredPin, setHoveredPin] = useState(null) // 'compId:pinId'
const [refComps, setRefComps] = useState([])
const [panelW, setPanelW] = useState(380)
// ββ Quick-add popup βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const [quickAdd, setQuickAdd] = useState(null) // { screenX, screenY, canvasX, canvasY }
const [quickSearch, setQuickSearch] = useState('')
const [quickIdx, setQuickIdx] = useState(0)
const quickInputRef = useRef(null)
useEffect(() => { if (quickAdd && quickInputRef.current) quickInputRef.current.focus() }, [quickAdd])
useEffect(() => { setQuickIdx(0) }, [quickSearch])
useEffect(() => {
if (!quickAdd) return
const close = (e) => { if (!e.target.closest('[data-quickadd]')) setQuickAdd(null) }
document.addEventListener('mousedown', close)
return () => document.removeEventListener('mousedown', close)
}, [quickAdd])
// ββ Quick-add search results ββββββββββββββββββββββββββββββββββββββββββββββββ
const quickResults = useMemo(() => {
const q = quickSearch.trim().toLowerCase()
const all = CATALOG.flatMap(g => g.items.map(item => ({ ...item, group: g.group })))
if (!q) return all.slice(0, 20)
return all.filter(i => i.label?.toLowerCase().includes(q) || i.type?.toLowerCase().includes(q)).slice(0, 20)
}, [quickSearch])
// ββ Panel resize (left edge drag) βββββββββββββββββββββββββββββββββββββββββββ
const startPanelResize = useCallback((e) => {
e.preventDefault()
const startX = e.clientX, startW = panelW
const onMove = (me) => setPanelW(Math.max(260, Math.min(700, startW + (startX - me.clientX))))
const onUp = () => { document.removeEventListener('pointermove', onMove); document.removeEventListener('pointerup', onUp) }
document.addEventListener('pointermove', onMove)
document.addEventListener('pointerup', onUp)
}, [panelW])
// ββ Global mouse events for panning & component dragging ββββββββββββββββββββ
useEffect(() => {
const onMove = (e) => {
if (movingCompRef.current) {
movingCompRef.current.moved = true
const { id, sx, sy, cx, cy } = movingCompRef.current
setRefComps(prev => prev.map(c => c.id === id
? { ...c, x: cx + (e.clientX-sx)/canvasZoomRef.current, y: cy + (e.clientY-sy)/canvasZoomRef.current }
: c))
return
}
if (isPanningRef.current) {
const dx = e.clientX - panStartRef.current.x
const dy = e.clientY - panStartRef.current.y
if (!didPanRef.current && (Math.abs(dx)>3 || Math.abs(dy)>3)) didPanRef.current = true
if (didPanRef.current) {
const newOff = { x: panStartRef.current.ox+dx, y: panStartRef.current.oy+dy }
setCanvasOffset(newOff)
canvasOffsetRef.current = newOff
}
}
}
const onUp = () => { movingCompRef.current = null; isPanningRef.current = false }
document.addEventListener('mousemove', onMove)
document.addEventListener('mouseup', onUp)
return () => { document.removeEventListener('mousemove', onMove); document.removeEventListener('mouseup', onUp) }
}, [])
// ββ Get BOUNDS for any component ββββββββββββββββββββββββββββββββββββββββββββ
const getBounds = useCallback((comp) => {
if (comp.id === USER_COMP_ID) return bounds || { x:0, y:0, w, h }
const reg = COMP_REGISTRY[comp.type]
if (!reg) return { x:0, y:0, w:comp.w, h:comp.h }
if (typeof reg.BOUNDS === 'function') return reg.BOUNDS({})
return reg.BOUNDS || { x:0, y:0, w:comp.w, h:comp.h }
}, [bounds, w, h])
// ββ Get pins for any component ββββββββββββββββββββββββββββββββββββββββββββββ
const getCompPins = useCallback((comp) => {
if (comp.id === USER_COMP_ID) return pins || []
return CATALOG_PIN_DEFS[comp.type] || []
}, [pins])
// ββ Render component UI βββββββββββββββββββββββββββββββββββββββββββββββββββββ
const renderUI = useCallback((comp) => {
if (comp.id === USER_COMP_ID) {
if (imageMode === 'react') {
if (evalErr) return (
<div style={{ position:'absolute', inset:0, background:'rgba(255,68,68,.08)', border:'1px solid rgba(255,68,68,.35)', padding:'6px 8px', fontSize:10, color:'#ff6b6b', overflow:'auto', fontFamily:'monospace', borderRadius:4, lineHeight:1.5 }}>
<strong>Compile error:</strong><br/>{evalErr}
</div>
)
if (evalComp) return React.createElement(evalComp, { state: userAttrs, attrs: userAttrs, isRunning })
return (
<div style={{ position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center', background:'#1e1e2e', border:'1px dashed #333', borderRadius:4 }}>
<span style={{ color:'#555', fontSize:11 }}>No component</span>
</div>
)
}
// SVG mode β render fluid SVG directly, same as SimulatorPage
if (fluidSvg) return (
<div style={{ position:'absolute', inset:0, pointerEvents:'none' }}
dangerouslySetInnerHTML={{ __html: fluidSvg }} />
)
return (
<div style={{ position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center', background:'#1e1e2e', border:'1px dashed #333', borderRadius:4 }}>
<span style={{ color:'#555', fontSize:11 }}>{w}Γ{h}</span>
</div>
)
}
const reg = COMP_REGISTRY[comp.type]
if (reg?.UI) return React.createElement(reg.UI, { state:{}, attrs:{}, isRunning })
return (
<div style={{ width:'100%', height:'100%', background:'#333', border:'1px solid #555',
display:'flex', alignItems:'center', justifyContent:'center', fontSize:10, color:'#aaa' }}>
{comp.type}
</div>
)
}, [imageMode, evalComp, evalErr, fluidSvg, w, h, isRunning, userAttrs])
// ββ Add component at canvas coordinates βββββββββββββββββββββββββββββββββββββ
const addComponent = useCallback((item, canvasX, canvasY) => {
const x = canvasX - (item.w||60)/2
const y = canvasY - (item.h||60)/2
setRefComps(prev => [...prev, {
id: `ref_${item.type}_${Date.now()}`,
type: item.type, label: item.label,
x: Math.max(0, x), y: Math.max(0, y),
w: item.w||60, h: item.h||60,
}])
setQuickAdd(null)
}, [])
// ββ Delete a reference component ββββββββββββββββββββββββββββββββββββββββββββ
const deleteRefComp = useCallback((id) => {
setRefComps(prev => prev.filter(c => c.id !== id))
if (selected === id) setSelected(null)
}, [selected])
// ββ Context menu visibility (same logic as SimulatorPage) βββββββββββββββββββ
const showCtxMenu = (() => {
if (selected !== USER_COMP_ID) return false
if (!evalCtxMenu) return false
const hasDuringRun = ctxDuringRun || ctxOnlyDuringRun
if (isRunning && !hasDuringRun) return false
if (!isRunning && ctxOnlyDuringRun) return false
return true
})()
// ββ All components: user comp first, then reference comps βββββββββββββββββββ
const allComps = useMemo(() => {
const userComp = {
id: USER_COMP_ID, type: compType||'custom',
label: compLabel||'My Component', x: 0, y: 0, w, h,
}
return [userComp, ...refComps]
}, [compType, compLabel, w, h, refComps])
// ββ Canvas mousedown β start pan ββββββββββββββββββββββββββββββββββββββββββββ
const onCanvasMD = (e) => {
if (e.button !== 0 || movingCompRef.current) return
e.preventDefault()
didPanRef.current = false
isPanningRef.current = true
panStartRef.current = { x: e.clientX, y: e.clientY, ox: canvasOffsetRef.current.x, oy: canvasOffsetRef.current.y }
}
// ββ Canvas click β deselect βββββββββββββββββββββββββββββββββββββββββββββββββ
const onCanvasClick = (e) => { if (!didPanRef.current) setSelected(null) }
// ββ Double-click β open quick-add βββββββββββββββββββββββββββββββββββββββββββ
const onCanvasDblClick = (e) => {
if (isRunning) return
const tag = e.target.tagName.toLowerCase()
if (tag === 'input' || tag === 'button') return
if (!canvasRef.current) return
const rect = canvasRef.current.getBoundingClientRect()
const cx = (e.clientX - rect.left - canvasOffsetRef.current.x) / canvasZoomRef.current
const cy = (e.clientY - rect.top - canvasOffsetRef.current.y) / canvasZoomRef.current
setQuickAdd({ screenX: e.clientX, screenY: e.clientY, canvasX: cx, canvasY: cy })
setQuickSearch('')
setQuickIdx(0)
}
// ββ Component mousedown β start drag (ref comps only) βββββββββββββββββββββββ
const onCompMD = (e, comp) => {
if (comp.id === USER_COMP_ID) return
e.stopPropagation()
movingCompRef.current = { id: comp.id, sx: e.clientX, sy: e.clientY, cx: comp.x, cy: comp.y, moved: false }
}
// ββ Component click β select ββββββββββββββββββββββββββββββββββββββββββββββββ
const onCompClick = (e, comp) => { e.stopPropagation(); setSelected(comp.id) }
// ββ Collapsed tab ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if (!open) {
return (
<div style={{ width:22, flexShrink:0, background:'var(--bg2)', borderLeft:'1px solid var(--border)', display:'flex', flexDirection:'column', alignItems:'center', paddingTop:12, gap:6, cursor:'pointer' }}
onClick={onToggle} title="Open Canvas Preview">
<div style={{ fontSize:14, color:'var(--accent)', transform:'rotate(180deg)', userSelect:'none' }}>βΆ</div>
<div style={{ writingMode:'vertical-rl', fontSize:9, fontWeight:700, color:'var(--text3)', letterSpacing:'.08em', textTransform:'uppercase', marginTop:6, userSelect:'none' }}>Canvas</div>
</div>
)
}
const gridPx = GRID * canvasZoom
return (
<div style={{ width:panelW, flexShrink:0, borderLeft:'1px solid var(--border)', display:'flex', flexDirection:'column', background:'var(--bg2)', position:'relative', overflow:'hidden' }}>
{/* ββ Left-edge resize handle ββββββββββββββββββββββββββββββββββββββββ */}
<div onPointerDown={startPanelResize}
style={{ position:'absolute', top:0, left:0, width:5, height:'100%', cursor:'ew-resize', zIndex:20 }} />
{/* ββ Panel header βββββββββββββββββββββββββββββββββββββββββββββββββββ */}
<div style={{ height:36, display:'flex', alignItems:'center', justifyContent:'space-between', padding:'0 8px 0 12px', borderBottom:'1px solid var(--border)', gap:6, flexShrink:0 }}>
<span style={{ fontSize:11, fontWeight:700, color:'var(--text)' }}>Canvas Preview</span>
<div style={{ display:'flex', gap:4, alignItems:'center', marginLeft:'auto' }}>
<PanelBtn on={isRunning} onClick={()=>setRunning(r=>!r)} title={isRunning?'Stop (context menu preview)':'Run (test context menu)'}>
{isRunning ? 'βΉ' : 'βΆ'}
</PanelBtn>
<PanelBtn onClick={()=>{ const z=Math.min(3,+(canvasZoom+0.25).toFixed(2)); setCanvasZoom(z); canvasZoomRef.current=z }} title="Zoom in">+</PanelBtn>
<PanelBtn onClick={()=>{ const z=Math.max(0.1,+(canvasZoom-0.25).toFixed(2)); setCanvasZoom(z); canvasZoomRef.current=z }} title="Zoom out">β</PanelBtn>
<PanelBtn onClick={()=>{ setCanvasZoom(1); setCanvasOffset({x:80,y:80}); canvasOffsetRef.current={x:80,y:80}; canvasZoomRef.current=1 }} title="Fit to view">β‘</PanelBtn>
<PanelBtn onClick={onToggle} title="Collapse panel">βΆ</PanelBtn>
</div>
</div>
{/* ββ Status pill ββββββββββββββββββββββββββββββββββββββββββββββββββββ */}
<div style={{ display:'flex', alignItems:'center', gap:6, padding:'4px 10px', borderBottom:'1px solid var(--border)', flexShrink:0 }}>
<div style={{ width:6, height:6, borderRadius:'50%', background:isRunning?'#4ade80':'#666', transition:'0.3s' }} />
<span style={{ fontSize:10, color:isRunning?'var(--accent)':'var(--text3)' }}>
{isRunning ? 'Running Β· context menu active' : 'Stopped Β· double-click canvas to add components'}
</span>
<span style={{ fontSize:10, color:'var(--text3)', marginLeft:'auto' }}>{Math.round(canvasZoom*100)}%</span>
</div>
{/* ββ Canvas area βββββββββββββββββββββββββββββββββββββββββββββββββββ */}
<main
ref={canvasRef}
style={{
flex:1, position:'relative', overflow:'hidden',
backgroundColor:'var(--canvas-bg)',
backgroundImage:'linear-gradient(var(--border) 1px,transparent 1px),linear-gradient(90deg,var(--border) 1px,transparent 1px)',
backgroundSize:`${gridPx}px ${gridPx}px`,
cursor: 'grab',
}}
onMouseDown={onCanvasMD}
onClick={onCanvasClick}
onDoubleClick={onCanvasDblClick}
>
{/* ββ Zoom wrapper βββββββββββββββββββββββββββββββββββββββββββββββ */}
<div style={{
position:'absolute', top:0, left:0,
transform:`translate(${canvasOffset.x}px,${canvasOffset.y}px) scale(${canvasZoom})`,
transformOrigin:'0 0',
}}>
{/* ββ Context menu (user component, renders actual ContextMenu like SimulatorPage) ββ */}
{showCtxMenu && (() => {
const b = bounds || { x:0, y:0, w, h }
return (
<div data-contextmenu="true" style={{
position:'absolute',
left: b.x + b.w / 2,
top: b.y - 14,
transform:'translateX(-50%) translateY(-100%)',
background:'var(--bg2)', border:'1px solid var(--border)',
display:'flex', alignItems:'center', gap:8,
padding:'6px 10px', borderRadius:10,
boxShadow:'0 8px 24px rgba(0,0,0,0.6)', cursor:'default',
pointerEvents:'all', whiteSpace:'nowrap', zIndex:200,
}}
onMouseDown={e=>e.stopPropagation()} onClick={e=>e.stopPropagation()}
onDoubleClick={e=>e.stopPropagation()}>
{React.createElement(evalCtxMenu, {
attrs: userAttrs,
onUpdate: (key, value) => setUserAttrs(prev => ({ ...prev, [key]: value }))
})}
<div style={{ position:'absolute', bottom:-6, left:'50%', transform:'translateX(-50%)', width:0, height:0, borderLeft:'6px solid transparent', borderRight:'6px solid transparent', borderTop:'6px solid var(--border)' }} />
<div style={{ position:'absolute', bottom:-5, left:'50%', transform:'translateX(-50%)', width:0, height:0, borderLeft:'5px solid transparent', borderRight:'5px solid transparent', borderTop:'5px solid var(--bg2)' }} />
</div>
)
})()}
{/* ββ Components βββββββββββββββββββββββββββββββββββββββββββββ */}
{allComps.map(comp => {
const compPins = getCompPins(comp)
const b = getBounds(comp)
const isSelected = selected === comp.id
const isUserComp = comp.id === USER_COMP_ID
return (
<div key={comp.id} style={{
position:'absolute', left:comp.x, top:comp.y, width:comp.w, height:comp.h,
pointerEvents:'none', userSelect:'none',
}}>
{/* Hit box β BOUNDS sized, captures click & drag */}
<div style={{
position:'absolute', left:b.x, top:b.y, width:b.w, height:b.h,
cursor: isUserComp ? 'default' : 'move',
pointerEvents:'auto', zIndex:3,
}}
onMouseDown={e => onCompMD(e, comp)}
onClick={e => onCompClick(e, comp)}
onDoubleClick={e => e.stopPropagation()}
/>
{/* Selection ring β same as SimulatorPage */}
{isSelected && (
<div style={{
position:'absolute', left:b.x-6, top:b.y-6, width:b.w+12, height:b.h+12,
borderRadius:8, border:'2px solid var(--accent)',
boxShadow:'0 0 16px var(--glow)', pointerEvents:'none', zIndex:10,
}} />
)}
{/* BOUNDS dashed overlay (user comp only) */}
{isUserComp && (
<div style={{
position:'absolute', pointerEvents:'none',
left:b.x, top:b.y, width:b.w, height:b.h,
border:'1px dashed rgba(96,165,250,.65)',
background:'rgba(96,165,250,.03)', borderRadius:2, zIndex:8,
}} />
)}
{/* Delete button (reference comps when selected) */}
{!isUserComp && isSelected && (
<button
onMouseDown={e => e.stopPropagation()}
onClick={e => { e.stopPropagation(); deleteRefComp(comp.id) }}
style={{
position:'absolute', left:b.x+b.w+4, top:b.y, zIndex:20,
width:18, height:18, borderRadius:4, border:'none',
background:'rgba(255,68,68,.75)', color:'#fff',
cursor:'pointer', fontSize:11, display:'flex',
alignItems:'center', justifyContent:'center', pointerEvents:'all',
}}>β</button>
)}
{/* Component UI render */}
<div style={{ pointerEvents:'none', position:'absolute', inset:0, zIndex:1 }}>
{renderUI(comp)}
</div>
{/* Pins β identical to SimulatorPage */}
{compPins.map(pin => {
const pinKey = `${comp.id}:${pin.id}`
const isHov = hoveredPin === pinKey
const pinColor = isHov ? '#f1c40f' : 'rgba(255,255,255,0.2)'
const pinBorder = isHov ? '#fff' : 'rgba(255,255,255,0.8)'
return (
<div key={pin.id} style={{
position:'absolute', left:pin.x, top:pin.y,
width:5, height:5,
background:pinColor, border:`1px solid ${pinBorder}`,
borderRadius:'0%', cursor:'crosshair',
zIndex:isHov?30:20,
transform:`translate(-50%,-50%)${isHov?' scale(1.5)':''}`,
transition:'0.2s', pointerEvents:'all',
}}
onMouseEnter={() => setHoveredPin(pinKey)}
onMouseLeave={() => setHoveredPin(null)}
>
{/* Pin label tooltip */}
{isHov && (
<div style={{
position:'absolute', bottom:18, left:'50%',
transform:'translateX(-50%)',
background:'#111', color:'#fff',
padding:'4px 8px', borderRadius:4,
fontSize:10, whiteSpace:'nowrap', zIndex:9999,
pointerEvents:'none', border:'1px solid #444',
boxShadow:'0 2px 5px rgba(0,0,0,0.5)',
}}>
{pin.description || pin.id}
</div>
)}
</div>
)
})}
{/* Component label below BOUNDS β same as SimulatorPage */}
<div style={{
position:'absolute',
top: b.y + b.h + 4,
left: b.x + b.w / 2,
transform:'translateX(-50%)',
fontSize:10, color:'var(--text3)',
whiteSpace:'nowrap',
fontFamily:'JetBrains Mono,monospace',
pointerEvents:'none', zIndex:12,
}}>
{comp.label}
</div>
</div>
)
})}
</div>{/* end zoom wrapper */}
{/* ββ Quick-add popup (double-click to open) βββββββββββββββββββββ */}
{quickAdd && (() => {
const VW = window.innerWidth, VH = window.innerHeight
const menuW = 240, approxH = Math.min(quickResults.length, 8) * 32 + 52
const left = quickAdd.screenX + menuW > VW ? quickAdd.screenX - menuW : quickAdd.screenX + 4
const top = quickAdd.screenY + approxH > VH ? quickAdd.screenY - approxH : quickAdd.screenY + 4
const selIdx = Math.max(0, Math.min(quickIdx, quickResults.length - 1))
return (
<div data-quickadd="true" style={{
position:'fixed', left, top, zIndex:2000,
background:'var(--bg2)', border:'1px solid var(--border)',
borderRadius:10, boxShadow:'0 8px 32px rgba(0,0,0,0.55)',
width:menuW, overflow:'hidden',
}}
onMouseDown={e => e.stopPropagation()}
onClick={e => e.stopPropagation()}>
<input
ref={quickInputRef}
value={quickSearch}
onChange={e => setQuickSearch(e.target.value)}
placeholder="Search componentsβ¦"
style={{
width:'100%', padding:'9px 12px', border:'none',
borderBottom:'1px solid var(--border)',
background:'var(--bg)', color:'var(--text)',
fontSize:12, fontFamily:'inherit', outline:'none', boxSizing:'border-box',
}}
onKeyDown={e => {
if (e.key === 'ArrowDown') { e.preventDefault(); setQuickIdx(i => Math.min(i+1, quickResults.length-1)) }
if (e.key === 'ArrowUp') { e.preventDefault(); setQuickIdx(i => Math.max(i-1, 0)) }
if (e.key === 'Enter' && quickResults[selIdx]) addComponent(quickResults[selIdx], quickAdd.canvasX, quickAdd.canvasY)
if (e.key === 'Escape') setQuickAdd(null)
}}
/>
<div style={{ maxHeight:260, overflowY:'auto' }}>
{quickResults.length === 0
? <div style={{ padding:'10px 12px', fontSize:12, color:'var(--text3)' }}>No components found.</div>
: quickResults.map((item, i) => (
<button key={item.type} style={{
display:'flex', alignItems:'center', gap:8, width:'100%',
textAlign:'left',
background: i === selIdx ? 'rgba(74,222,128,.12)' : 'none',
border:'none',
color: i === selIdx ? 'var(--accent)' : 'var(--text)',
padding:'7px 12px', fontSize:12, cursor:'pointer', fontFamily:'inherit',
}}
onMouseEnter={() => setQuickIdx(i)}
onMouseDown={e => { e.preventDefault(); addComponent(item, quickAdd.canvasX, quickAdd.canvasY) }}>
<span style={{ flex:1 }}>{item.label}</span>
<span style={{ fontSize:9, color:'var(--text3)', textTransform:'uppercase' }}>{item.group}</span>
</button>
))
}
</div>
</div>
)
})()}
{/* ββ Info footer ββββββββββββββββββββββββββββββββββββββββββββββββ */}
<div style={{
position:'absolute', bottom:0, left:0, right:0,
padding:'4px 10px', background:'var(--bg2)',
borderTop:'1px solid var(--border)',
display:'flex', alignItems:'center', gap:10, zIndex:50,
}}>
<div style={{ fontSize:10, color:'var(--text3)' }}>
Context:
{ctxOnlyDuringRun && !isRunning
? <span style={{ color:'#ff6b6b' }}>hidden (run-only)</span>
: ctxDuringRun
? <span style={{ color:'var(--accent)' }}>visible Β· running:{isRunning?'yes':'no'}</span>
: <span>standard</span>
}
</div>
<div style={{ fontSize:10, color:'var(--text3)', marginLeft:'auto' }}>
BOUNDS ({bounds?.x},{bounds?.y}) {bounds?.w}Γ{bounds?.h} Β· {w}Γ{h}
</div>
</div>
</main>
</div>
)
}
function PanelBtn({ children, onClick, title, on }) {
return (
<button onClick={onClick} title={title} style={{
width:24, height:24, borderRadius:4, border:'1px solid var(--border)', cursor:'pointer',
background: on ? 'var(--accent)' : 'var(--bg3)', color: on ? '#000' : 'var(--text2)',
fontSize:12, display:'flex', alignItems:'center', justifyContent:'center', padding:0,
}}>{children}</button>
)
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ZoomControls β zoom in/out/fit for any preview
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function ZoomBar({ zoom, onZoom, onFit, fitZoom }) {
return (
<div style={{ display:'flex', alignItems:'center', gap:5, padding:'5px 0 0' }}>
<button onClick={()=>onZoom(z=>Math.max(0.1,+(z-0.25).toFixed(2)))} style={zoomBtnS}>β</button>
<span style={{ fontSize:10, color:'var(--text3)', minWidth:38, textAlign:'center' }}>{Math.round(zoom*100)}%</span>
<button onClick={()=>onZoom(z=>Math.min(4,+(z+0.25).toFixed(2)))} style={zoomBtnS}>+</button>
<button onClick={onFit} title="Fit" style={{ ...zoomBtnS, padding:'0 8px', fontSize:10 }}>Fit</button>
</div>
)
}
const zoomBtnS = { width:24, height:22, background:'var(--bg3)', border:'1px solid var(--border)', borderRadius:4, color:'var(--text2)', cursor:'pointer', fontSize:13, display:'flex', alignItems:'center', justifyContent:'center', padding:0 }
// "Check on Canvas" button
function CheckBtn({ onClick }) {
return (
<button onClick={onClick} style={{ marginTop:8, width:'100%', padding:'6px 0', borderRadius:5, background:'rgba(96,165,250,.08)', border:'1px dashed rgba(96,165,250,.4)', color:'#60a5fa', fontSize:11, fontWeight:600, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', gap:6 }}>
<svg width="13" height="13" viewBox="0 0 13 13" fill="none"><rect x="1" y="1" width="11" height="11" rx="2" stroke="currentColor" strokeWidth="1.2"/><circle cx="6.5" cy="6.5" r="2" stroke="currentColor" strokeWidth="1.2"/></svg>
Check on Canvas
</button>
)
}
// Small inline Btn component
function Btn({ children, onClick, v='def', sm, disabled, style:xs }) {
const base = { padding:sm?'3px 9px':'6px 14px', borderRadius:5, cursor:disabled?'not-allowed':'pointer', fontSize:sm?11:12, fontWeight:600, border:'none', display:'inline-flex', alignItems:'center', gap:5, opacity:disabled?.5:1, whiteSpace:'nowrap', ...xs }
const vars = { def:{background:'var(--bg3)',color:'var(--text)',border:'1px solid var(--border)'}, primary:{background:'var(--accent)',color:'#000'}, ghost:{background:'transparent',color:'var(--text2)',border:'1px solid var(--border)'}, danger:{background:'rgba(255,68,68,.14)',color:'#ff5555',border:'1px solid rgba(255,68,68,.3)'}, green:{background:'rgba(74,222,128,.14)',color:'#4ade80',border:'1px solid rgba(74,222,128,.3)'}, yellow:{background:'rgba(251,191,36,.14)',color:'#fbbf24',border:'1px solid rgba(251,191,36,.3)'}, blue:{background:'rgba(96,165,250,.14)',color:'#60a5fa',border:'1px solid rgba(96,165,250,.3)'} }
return <button onClick={onClick} disabled={disabled} style={{ ...base, ...vars[v] }}>{children}</button>
}
const Sep = ({ v }) => <div style={v ? { width:1, height:18, background:'var(--border)' } : { height:1, background:'var(--border)', margin:'8px 0' }} />
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Styles
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const S = {
page: { position:'fixed', inset:0, display:'flex', flexDirection:'column', background:'var(--bg)', color:'var(--text)', fontFamily:"'JetBrains Mono',monospace", zIndex:1000 },
header: { height:46, background:'var(--bg2)', borderBottom:'1px solid var(--border)', display:'flex', alignItems:'center', gap:8, padding:'0 12px', flexShrink:0 },
body: { flex:1, display:'flex', overflow:'hidden' },
sidebar: { width:200, borderRight:'1px solid var(--border)', background:'var(--bg2)', display:'flex', flexDirection:'column', padding:'10px 0', flexShrink:0 },
stepBtn: (on,done) => ({ display:'flex', alignItems:'center', gap:8, padding:'7px 12px', background:on?'rgba(74,222,128,.09)':'transparent', color:on?'var(--accent)':done?'var(--text2)':'var(--text3)', border:'none', borderLeft:on?'3px solid var(--accent)':'3px solid transparent', width:'100%', textAlign:'left', fontSize:11, fontWeight:on?700:500, cursor:'pointer' }),
stepNum: (on,done) => ({ width:18, height:18, borderRadius:'50%', display:'flex', alignItems:'center', justifyContent:'center', fontSize:10, fontWeight:700, flexShrink:0, background:on?'var(--accent)':done?'rgba(74,222,128,.3)':'var(--border)', color:on?'#000':done?'var(--accent)':'var(--text3)' }),
main: { flex:1, display:'flex', flexDirection:'column', overflow:'hidden', minWidth:0 },
stepHeader: { padding:'12px 22px 9px', borderBottom:'1px solid var(--border)', background:'var(--bg2)', flexShrink:0 },
content: { flex:1, overflowY:'auto', overflowX:'hidden', padding:'16px 22px' },
footer: { height:48, borderTop:'1px solid var(--border)', background:'var(--bg2)', display:'flex', alignItems:'center', justifyContent:'space-between', padding:'0 18px', flexShrink:0 },
label: { display:'block', fontSize:10, fontWeight:600, color:'var(--text2)', marginBottom:4, textTransform:'uppercase', letterSpacing:'.06em' },
input: { width:'100%', background:'var(--bg3)', border:'1px solid var(--border)', borderRadius:5, color:'var(--text)', padding:'6px 8px', fontSize:12, outline:'none', boxSizing:'border-box' },
textarea: { width:'100%', background:'var(--bg3)', border:'1px solid var(--border)', borderRadius:5, color:'var(--text)', padding:'6px 8px', fontSize:12, outline:'none', boxSizing:'border-box', resize:'vertical', minHeight:60, fontFamily:'inherit' },
select: { width:'100%', background:'var(--bg3)', border:'1px solid var(--border)', borderRadius:5, color:'var(--text)', padding:'6px 8px', fontSize:12, outline:'none', boxSizing:'border-box' },
g2: { display:'grid', gridTemplateColumns:'1fr 1fr', gap:13 },
g4: { display:'grid', gridTemplateColumns:'1fr 1fr 1fr 1fr', gap:9 },
infoBox: { background:'rgba(74,222,128,.05)', border:'1px solid rgba(74,222,128,.2)', borderRadius:6, padding:'7px 11px', marginBottom:11, fontSize:11, color:'var(--text2)', lineHeight:1.6 },
warnBox: { background:'rgba(251,191,36,.06)', border:'1px solid rgba(251,191,36,.3)', borderRadius:6, padding:'7px 11px', marginBottom:9, fontSize:11, color:'#fbbf24', lineHeight:1.5 },
card: { background:'var(--bg3)', borderRadius:7, padding:'11px 13px', border:'1px solid var(--border)', marginBottom:11 },
previewWrap: (extra={}) => ({ background:'var(--canvas-bg)', ...mkGrid(), borderRadius:7, border:'1px solid var(--border)', display:'flex', alignItems:'center', justifyContent:'center', overflow:'hidden', position:'relative', ...extra }),
tab: (on) => ({ padding:'4px 11px', borderRadius:'5px 5px 0 0', fontSize:11, fontWeight:600, cursor:'pointer', background:on?'var(--bg)':'var(--bg3)', border:'1px solid var(--border)', borderBottom:on?'1px solid var(--bg)':'1px solid var(--border)', color:on?'var(--accent)':'var(--text3)', marginRight:2 }),
codeWrap: { background:'var(--bg)', borderRadius:'0 6px 6px 6px', border:'1px solid var(--border)', overflow:'auto', flex:1 },
pinRowS: (ed) => ({ display:'flex', alignItems:'center', gap:7, padding:'5px 8px', background:ed?'var(--bg)':'var(--bg3)', borderRadius:ed?'6px 6px 0 0':6, marginBottom:ed?0:4, border:`1px solid ${ed?'var(--accent)':'var(--border)'}`, cursor:'pointer' }),
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Main Page
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export default function ComponentEditorPage() {
const navigate = useNavigate()
// ββ Theme βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const [theme, setTheme] = useState(() => document.documentElement.getAttribute('data-theme') || 'dark')
const toggleTheme = () => {
const nt = theme === 'dark' ? 'light' : 'dark'
setTheme(nt); document.documentElement.setAttribute('data-theme', nt)