-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1716 lines (1573 loc) · 76.6 KB
/
Copy pathindex.html
File metadata and controls
1716 lines (1573 loc) · 76.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FLUX Visual Editor — SuperInstance</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
:root {
--bg: #0d1117; --bg2: #161b22; --bg3: #21262d; --bg4: #0a0e14;
--accent: #e94560; --accent2: #f0883e;
--text: #e6edf3; --dim: #8b949e; --dimmer: #484f58;
--green: #3fb950; --yellow: #d29922; --blue: #58a6ff; --red: #f85149;
--purple: #bc8cff; --cyan: #39d2c0; --pink: #f778ba;
--border: #30363d; --border-light: #6e7681;
--node-bg: #11161c;
--shadow: 0 2px 8px rgba(0,0,0,0.4);
--radius: 6px;
}
body {
background: var(--bg); color: var(--text);
font-family: -apple-system, 'Segoe UI', Helvetica, Arial, sans-serif;
overflow: hidden; height: 100vh; display: flex; flex-direction: column;
}
/* === Top Bar === */
#topbar {
background: var(--bg2); border-bottom: 1px solid var(--border);
padding: 8px 16px; display: flex; gap: 6px; align-items: center;
flex-shrink: 0; flex-wrap: wrap; box-shadow: var(--shadow); z-index: 10;
}
#topbar .brand {
font-size: 18px; font-weight: 700; color: var(--accent);
white-space: nowrap; display: flex; align-items: center; gap: 6px;
}
#topbar .brand .sub { font-size: 11px; color: var(--dim); font-weight: 400; }
#topbar .divider { width: 1px; height: 24px; background: var(--border); margin: 0 4px; }
#topbar button {
background: var(--bg3); color: var(--text); border: 1px solid var(--border);
padding: 6px 14px; cursor: pointer; font-family: inherit; font-size: 12px;
border-radius: var(--radius); transition: all 0.15s; font-weight: 500;
}
#topbar button:hover { border-color: var(--accent); background: #1c2331; }
#topbar button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
#topbar button.primary:hover { background: #ff5577; }
#topbar button.success { background: #1a4a2a; border-color: var(--green); color: var(--green); }
#topbar button.success:hover { background: #256b3a; }
#topbar select {
background: var(--bg3); color: var(--text); border: 1px solid var(--border);
padding: 6px 10px; cursor: pointer; font-family: inherit; font-size: 12px;
border-radius: var(--radius);
}
#topbar .spacer { margin-left: auto; }
#topbar .hint { font-size: 11px; color: var(--dimmer); }
/* === Layout === */
#main { display: flex; flex: 1; overflow: hidden; }
#sidebar {
width: 180px; background: var(--bg2); border-right: 1px solid var(--border);
padding: 10px; overflow-y: auto; flex-shrink: 0;
}
#sidebar h3 {
color: var(--dim); font-size: 10px; text-transform: uppercase;
letter-spacing: 0.08em; margin: 12px 0 6px 0; font-weight: 600;
}
#sidebar h3:first-child { margin-top: 0; }
#canvas-area {
flex: 1; position: relative; overflow: auto; background: var(--bg4);
}
#right-panel {
width: 360px; background: var(--bg2); border-left: 1px solid var(--border);
display: flex; flex-direction: column; flex-shrink: 0; overflow-y: auto;
}
/* === Palette === */
.palette-node {
background: var(--bg3); border: 1px solid var(--border);
padding: 8px 10px; margin: 3px 0; cursor: grab; text-align: left;
font-size: 12px; border-radius: var(--radius); user-select: none;
transition: all 0.15s; display: flex; align-items: center; gap: 8px;
}
.palette-node:hover { border-color: var(--accent); background: #1c2331; transform: translateX(2px); }
.palette-node:active { cursor: grabbing; }
.palette-node .icon { font-size: 14px; }
.palette-node .label { font-weight: 500; }
.palette-node .sub { font-size: 9px; color: var(--dimmer); margin-top: 2px; }
/* === Canvas === */
#canvas {
position: relative; width: 4000px; height: 3000px;
background-image:
radial-gradient(circle, #1a2030 1px, transparent 1px);
background-size: 24px 24px;
}
#wire-svg {
position: absolute; top: 0; left: 0; width: 100%; height: 100%;
pointer-events: none; z-index: 1;
}
#wire-svg path { fill: none; stroke-width: 2; pointer-events: stroke; cursor: pointer; transition: stroke-width 0.15s; }
#wire-svg path:hover { stroke-width: 4; }
#wire-temp { fill: none; stroke: var(--yellow); stroke-width: 2; stroke-dasharray: 5; }
/* === Nodes === */
.node {
position: absolute; min-width: 160px; background: var(--node-bg);
border: 2px solid var(--border-light); border-radius: var(--radius);
z-index: 2; user-select: none; box-shadow: var(--shadow);
transition: border-color 0.15s, box-shadow 0.15s;
}
.node:hover { border-color: var(--dim); }
.node.selected { border-color: var(--yellow); box-shadow: 0 0 0 2px rgba(210,153,34,0.3); }
.node.active { border-color: var(--accent) !important; box-shadow: 0 0 20px rgba(233,69,96,0.5); animation: pulse 0.6s infinite alternate; }
@keyframes pulse { to { box-shadow: 0 0 30px rgba(233,69,96,0.7); } }
.node-header {
padding: 6px 10px; font-size: 12px; font-weight: 600;
border-radius: 4px 4px 0 0; cursor: move; display: flex;
justify-content: space-between; align-items: center;
}
.node-header .del { cursor: pointer; color: var(--dimmer); font-size: 14px; padding: 0 4px; transition: color 0.15s; }
.node-header .del:hover { color: var(--red); }
.node-body { padding: 8px; font-size: 11px; }
.node-body input, .node-body select {
background: var(--bg4); color: var(--text); border: 1px solid var(--border);
padding: 3px 6px; font-family: inherit; font-size: 11px; border-radius: 3px;
outline: none; transition: border-color 0.15s;
}
.node-body input:focus, .node-body select:focus { border-color: var(--blue); }
.node-body label { display: inline-block; width: 52px; color: var(--dim); font-size: 10px; }
.node-body .row { margin-bottom: 4px; }
.port {
width: 14px; height: 14px; border-radius: 50%;
position: absolute; cursor: crosshair; z-index: 3;
border: 2px solid var(--node-bg); transition: transform 0.1s;
}
.port:hover { transform: scale(1.3); }
.port.input { left: -9px; }
.port.output { right: -9px; }
.port-title {
position: absolute; font-size: 9px; color: var(--dim);
pointer-events: none; line-height: 14px; white-space: nowrap;
}
/* Node type colors */
.node[data-type="constant"] { border-color: #3fb950; }
.node[data-type="constant"] .node-header { background: rgba(63,185,80,0.12); color: var(--green); }
.node[data-type="constant"] .port { background: var(--green); }
.node[data-type="comparator"] { border-color: #bc8cff; }
.node[data-type="comparator"] .node-header { background: rgba(188,140,255,0.12); color: var(--purple); }
.node[data-type="comparator"] .port { background: var(--purple); }
.node[data-type="budget"] { border-color: var(--accent2); }
.node[data-type="budget"] .node-header { background: rgba(240,136,62,0.12); color: var(--accent2); }
.node[data-type="budget"] .port { background: var(--accent2); }
.node[data-type="gate"] { border-color: var(--red); }
.node[data-type="gate"] .node-header { background: rgba(248,81,73,0.12); color: var(--red); }
.node[data-type="gate"] .port { background: var(--red); }
.node[data-type="decision"] { border-color: var(--yellow); }
.node[data-type="decision"] .node-header { background: rgba(210,153,34,0.12); color: var(--yellow); }
.node[data-type="decision"] .port { background: var(--yellow); }
.node[data-type="llm"] { border-color: var(--cyan); }
.node[data-type="llm"] .node-header { background: rgba(57,210,192,0.12); color: var(--cyan); }
.node[data-type="llm"] .port { background: var(--cyan); }
.node[data-type="room"] { border-color: var(--pink); }
.node[data-type="room"] .node-header { background: rgba(247,120,186,0.12); color: var(--pink); }
.node[data-type="room"] .port { background: var(--pink); }
.node[data-type="io"] { border-color: var(--blue); }
.node[data-type="io"] .node-header { background: rgba(88,166,255,0.12); color: var(--blue); }
.node[data-type="io"] .port { background: var(--blue); }
/* Legacy node types */
.node[data-type="arithmetic"] { border-color: var(--accent2); }
.node[data-type="arithmetic"] .node-header { background: rgba(240,136,62,0.12); color: var(--accent2); }
.node[data-type="arithmetic"] .port { background: var(--accent2); }
.node[data-type="branch"] { border-color: var(--yellow); }
.node[data-type="branch"] .node-header { background: rgba(210,153,34,0.12); color: var(--yellow); }
.node[data-type="branch"] .port { background: var(--yellow); }
.node[data-type="memory"] { border-color: var(--blue); }
.node[data-type="memory"] .node-header { background: rgba(88,166,255,0.12); color: var(--blue); }
.node[data-type="memory"] .port { background: var(--blue); }
.node[data-type="stack"] { border-color: var(--green); }
.node[data-type="stack"] .node-header { background: rgba(63,185,80,0.12); color: var(--green); }
.node[data-type="stack"] .port { background: var(--green); }
.node[data-type="output"] { border-color: var(--dim); }
.node[data-type="output"] .node-header { background: rgba(139,148,158,0.12); color: var(--dim); }
.node[data-type="output"] .port { background: var(--dim); }
.node[data-type="halt"] { border-color: var(--dimmer); }
.node[data-type="halt"] .node-header { background: rgba(72,79,88,0.12); color: var(--dimmer); }
.node[data-type="halt"] .port { background: var(--dimmer); }
/* === Right Panel === */
#right-panel .panel-section {
padding: 10px 12px; border-bottom: 1px solid var(--border);
}
#right-panel h3 {
color: var(--dim); font-size: 10px; text-transform: uppercase;
letter-spacing: 0.08em; margin-bottom: 8px; font-weight: 600;
display: flex; justify-content: space-between; align-items: center;
}
#right-panel h3 .badge {
font-size: 10px; color: var(--dimmer); font-weight: 400;
text-transform: none; letter-spacing: 0;
}
#asm-output {
width: 100%; min-height: 180px; background: var(--bg4); color: var(--green);
border: 1px solid var(--border); font-family: 'SF Mono', 'Fira Code', 'Courier New', monospace;
font-size: 11px; padding: 8px; border-radius: 4px; resize: vertical; line-height: 1.5;
}
#hex-output {
width: 100%; min-height: 80px; max-height: 120px; overflow-y: auto;
background: var(--bg4); color: var(--blue);
border: 1px solid var(--border); font-family: 'SF Mono', 'Fira Code', 'Courier New', monospace;
font-size: 10px; padding: 8px; border-radius: 4px; word-break: break-all;
margin-top: 6px;
}
#vm-output {
width: 100%; min-height: 60px; background: var(--bg4);
border: 1px solid var(--border); font-family: 'SF Mono', 'Fira Code', monospace;
font-size: 11px; padding: 8px; border-radius: 4px; color: var(--yellow);
line-height: 1.5;
}
/* Conservation Ledger */
#ledger-output {
background: var(--bg4); border: 1px solid var(--border);
border-radius: 4px; padding: 8px; font-size: 11px; min-height: 40px;
}
.ledger-entry {
display: flex; justify-content: space-between; align-items: center;
padding: 4px 0; border-bottom: 1px solid rgba(48,54,61,0.5);
}
.ledger-entry:last-child { border-bottom: none; }
.ledger-entry .lname { color: var(--accent2); font-weight: 500; }
.ledger-entry .ltype { color: var(--dim); font-size: 9px; text-transform: uppercase; }
.ledger-entry .lval { color: var(--green); font-family: monospace; }
.ledger-empty { color: var(--dimmer); font-style: italic; text-align: center; padding: 8px; }
/* Register table */
#reg-display { display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px; }
.reg-cell {
background: var(--bg3); padding: 4px 6px; font-size: 10px;
border-radius: 3px; text-align: center; font-family: monospace;
transition: background 0.2s; border: 1px solid transparent;
}
.reg-cell.nonzero { color: var(--green); font-weight: 600; }
.reg-cell.changed { background: rgba(63,185,80,0.15); border-color: var(--green); }
/* Console */
#console {
font-size: 10px; color: var(--dim); max-height: 140px; overflow-y: auto;
font-family: 'SF Mono', 'Fira Code', monospace;
}
#console div { padding: 1px 0; line-height: 1.4; }
#console .log-time { color: var(--dimmer); }
/* Step controls */
#step-controls { display: flex; gap: 4px; align-items: center; }
/* === Modal === */
#modal-overlay {
display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: rgba(1,4,9,0.8); z-index: 100; justify-content: center; align-items: center;
backdrop-filter: blur(4px);
}
#modal-overlay.show { display: flex; }
#modal {
background: var(--bg2); border: 1px solid var(--border); border-radius: 12px;
padding: 20px; max-width: 600px; width: 90%; max-height: 80vh; overflow-y: auto;
box-shadow: 0 16px 48px rgba(0,0,0,0.6);
}
#modal h2 { color: var(--accent); font-size: 16px; margin-bottom: 12px; }
#modal textarea {
width: 100%; height: 300px; background: var(--bg4); color: var(--text);
border: 1px solid var(--border); font-family: monospace; font-size: 11px;
padding: 10px; border-radius: 6px; resize: vertical;
}
#modal .modal-buttons { display: flex; gap: 8px; margin-top: 12px; justify-content: flex-end; }
#modal button {
background: var(--bg3); color: var(--text); border: 1px solid var(--border);
padding: 8px 18px; cursor: pointer; font-family: inherit; font-size: 12px;
border-radius: 6px; font-weight: 500;
}
#modal button:hover { border-color: var(--accent); background: #1c2331; }
#modal button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
#modal .share-url {
width: 100%; background: var(--bg4); color: var(--blue);
border: 1px solid var(--border); padding: 10px; font-size: 11px;
border-radius: 6px; word-break: break-all;
}
/* === Scrollbar === */
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: var(--bg4); }
::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: var(--border-light); }
/* === Mobile === */
@media (max-width: 768px) {
#topbar { padding: 4px 8px; gap: 4px; }
#topbar .brand { font-size: 14px; }
#topbar .brand .sub { display: none; }
#topbar button, #topbar select { padding: 4px 8px; font-size: 10px; }
#topbar .hint { display: none; }
#main { flex-direction: column; }
#sidebar {
width: 100%; max-height: 80px; display: flex; gap: 4px;
overflow-x: auto; border-right: none; border-bottom: 1px solid var(--border); padding: 4px;
}
#sidebar h3 { display: none; }
.palette-node { white-space: nowrap; margin: 0; padding: 6px 10px; min-width: auto; }
.palette-node .sub { display: none; }
#canvas-area { flex: 1; overflow: auto; }
#right-panel { width: 100%; max-height: 40vh; border-left: none; border-top: 1px solid var(--border); }
#reg-display { grid-template-columns: repeat(8, 1fr); }
.reg-cell { font-size: 9px; padding: 2px 3px; }
}
</style>
</head>
<body>
<div id="topbar">
<div class="brand">⚡ FLUX <span class="sub">Visual Editor</span></div>
<div class="divider"></div>
<button class="primary" onclick="compileGraph()">📋 Compile</button>
<button class="success" onclick="runBytecode()">▶ Run</button>
<span id="step-controls">
<button onclick="stepReset()" title="Reset to start">⏮ Reset</button>
<button onclick="stepForward()" title="Execute one instruction">⏭ Step</button>
</span>
<div class="divider"></div>
<button onclick="downloadBin()">💾 Download .bin</button>
<select id="example-select" onchange="loadExample(this.value); this.value=''">
<option value="">— Examples —</option>
<optgroup label="Conservation">
<option value="token_budget">Token Budget Enforcer</option>
<option value="rate_limiter">Rate Limiter</option>
<option value="room_entry">Room Entry Protocol</option>
</optgroup>
<optgroup label="Classic">
<option value="hello">Hello World</option>
<option value="counter">Counter Loop</option>
<option value="deadband">Deadband Controller</option>
<option value="factorial">Factorial</option>
</optgroup>
</select>
<div class="divider"></div>
<button onclick="showExport()">📤 Export</button>
<button onclick="showImport()">📥 Import</button>
<button onclick="shareProgram()">🔗 Share</button>
<button onclick="clearCanvas()">🗑 Clear</button>
<span class="spacer"></span>
<span class="hint">Drag nodes → canvas · Click ● then ● to wire</span>
</div>
<div id="main">
<div id="sidebar">
<h3>Conservation</h3>
<div class="palette-node" draggable="true" data-type="budget">
<span class="icon">🛡</span>
<div><div class="label">Budget</div><div class="sub">Bounded quantity</div></div>
</div>
<div class="palette-node" draggable="true" data-type="gate">
<span class="icon">🚦</span>
<div><div class="label">Action Gate</div><div class="sub">Permit / block</div></div>
</div>
<div class="palette-node" draggable="true" data-type="decision">
<span class="icon">🔀</span>
<div><div class="label">Decision</div><div class="sub">If/else branch</div></div>
</div>
<h3>Agents & Rooms</h3>
<div class="palette-node" draggable="true" data-type="llm">
<span class="icon">🤖</span>
<div><div class="label">LLM Call</div><div class="sub">Model invoke</div></div>
</div>
<div class="palette-node" draggable="true" data-type="room">
<span class="icon">💬</span>
<div><div class="label">Room Protocol</div><div class="sub">PLATO msg</div></div>
</div>
<h3>Flow</h3>
<div class="palette-node" draggable="true" data-type="io">
<span class="icon">埠</span>
<div><div class="label">I/O Port</div><div class="sub">Entry / exit</div></div>
</div>
<div class="palette-node" draggable="true" data-type="constant">
<span class="icon">📦</span>
<div><div class="label">Constant</div><div class="sub">Static value</div></div>
</div>
<div class="palette-node" draggable="true" data-type="comparator">
<span class="icon">🔍</span>
<div><div class="label">Comparator</div><div class="sub">==, <, ></div></div>
</div>
<h3>Low-Level</h3>
<div class="palette-node" draggable="true" data-type="arithmetic">
<span class="icon">🔧</span>
<div><div class="label">Arithmetic</div><div class="sub">+ − × ÷</div></div>
</div>
<div class="palette-node" draggable="true" data-type="branch">
<span class="icon">↪</span>
<div><div class="label">Branch</div><div class="sub">Jump</div></div>
</div>
<div class="palette-node" draggable="true" data-type="memory">
<span class="icon">💾</span>
<div><div class="label">Memory</div><div class="sub">Load / store</div></div>
</div>
<div class="palette-node" draggable="true" data-type="stack">
<span class="icon">📚</span>
<div><div class="label">Stack</div><div class="sub">Push / pop</div></div>
</div>
<div class="palette-node" draggable="true" data-type="output">
<span class="icon">📊</span>
<div><div class="label">Output</div><div class="sub">Display reg</div></div>
</div>
<div class="palette-node" draggable="true" data-type="halt">
<span class="icon">⏹</span>
<div><div class="label">Halt</div><div class="sub">Stop exec</div></div>
</div>
</div>
<div id="canvas-area">
<div id="canvas">
<svg id="wire-svg"></svg>
</div>
</div>
<div id="right-panel">
<div class="panel-section">
<h3>Assembly <span class="badge" id="bytecount-badge"></span></h3>
<textarea id="asm-output" readonly placeholder="// Compile to see FLUX assembly"></textarea>
<h3 style="margin-top:8px;">Bytecode Hex</h3>
<div id="hex-output">—</div>
</div>
<div class="panel-section">
<h3>Conservation Ledger <span class="badge" id="ledger-badge"></span></h3>
<div id="ledger-output"><div class="ledger-empty">No budgets defined — add a Budget node to begin</div></div>
</div>
<div class="panel-section">
<h3>Execution <span class="badge" id="exec-badge"></span></h3>
<div id="vm-output">—</div>
</div>
<div class="panel-section">
<h3>Registers <span class="badge">R0–R15</span></h3>
<div id="reg-display"></div>
</div>
<div class="panel-section" style="flex:1; min-height:0;">
<h3>Console</h3>
<div id="console"></div>
</div>
</div>
</div>
<div id="modal-overlay">
<div id="modal">
<h2 id="modal-title">Modal</h2>
<div id="modal-body"></div>
<div class="modal-buttons">
<button onclick="closeModal()">Close</button>
</div>
</div>
</div>
<script>
// ═══════════════════════════════════════════════════════════════════════════
// EMBEDDED FLUX VM (from flux-js, trimmed)
// ═══════════════════════════════════════════════════════════════════════════
const OP = {
NOP:0x00, MOV:0x01, LOAD:0x02, STORE:0x03,
JMP:0x04, JZ:0x05, JNZ:0x06, CALL:0x07,
IADD:0x08, ISUB:0x09, IMUL:0x0A, IDIV:0x0B,
IMOD:0x0C, INEG:0x0D, INC:0x0E, DEC:0x0F,
IAND:0x10, IOR:0x11, IXOR:0x12, INOT:0x13,
ISHL:0x14, ISHR:0x15,
PUSH:0x20, POP:0x21, DUP:0x22,
RET:0x28, MOVI:0x2B, CMP:0x2D,
JE:0x2E, JNE:0x2F,
HALT:0x80, YIELD:0x81
};
const MNEMONIC = Object.fromEntries(Object.entries(OP).map(([k,v])=>[v,k]));
const INST_SIZES = {
[OP.HALT]:1,[OP.NOP]:1,[OP.DUP]:1,[OP.YIELD]:1,
[OP.INC]:2,[OP.DEC]:2,[OP.PUSH]:2,[OP.POP]:2,
[OP.MOV]:3,[OP.LOAD]:3,[OP.STORE]:3,[OP.CMP]:3,
[OP.IADD]:4,[OP.ISUB]:4,[OP.IMUL]:4,[OP.IDIV]:4,[OP.IMOD]:4,
[OP.IAND]:4,[OP.IOR]:4,[OP.IXOR]:4,[OP.ISHL]:4,[OP.ISHR]:4,
[OP.MOVI]:4,[OP.JMP]:4,[OP.JZ]:4,[OP.JNZ]:4,[OP.CALL]:4,[OP.JE]:4,[OP.JNE]:4,
[OP.RET]:3
};
class FluxVM {
constructor(bytecode, maxCycles=10_000_000) {
this.gp = new Int32Array(16);
this.pc = 0; this.halted = false; this.cycles = 0;
this.stack = []; this.output = [];
this.bc = bytecode instanceof Uint8Array ? bytecode : new Uint8Array(bytecode);
this.maxCycles = maxCycles; this.error = null;
this._flagZero = false; this._flagSign = false;
this.mem = new Int32Array(256);
this.prevRegs = new Int32Array(16);
this.changedRegs = new Set();
}
reg(i){ return this.gp[i]||0; }
_u8(){ return this.bc[this.pc++]; }
_i16(){ const lo=this.bc[this.pc++],hi=this.bc[this.pc++]; const v=lo|(hi<<8); return v>=32768?v-65536:v; }
_setFlags(r){ this._flagZero=(r===0); this._flagSign=(r<0); }
step() {
if (this.halted || this.pc >= this.bc.length) return false;
this.prevRegs.set(this.gp);
this.changedRegs.clear();
const op = this._u8();
this.cycles++;
try {
switch(op) {
case 0x80: this.halted=true; break;
case 0x00: break;
case 0x01: { const d=this._u8(),s=this._u8(); this.gp[d]=this.gp[s]; this.changedRegs.add(d); break; }
case 0x2B: { const d=this._u8(); this.gp[d]=this._i16(); this.changedRegs.add(d); break; }
case 0x08: { const d=this._u8(),a=this._u8(),b=this._u8(); const r=(this.gp[a]+this.gp[b])|0; this.gp[d]=r; this._setFlags(r); this.changedRegs.add(d); break; }
case 0x09: { const d=this._u8(),a=this._u8(),b=this._u8(); const r=(this.gp[a]-this.gp[b])|0; this.gp[d]=r; this._setFlags(r); this.changedRegs.add(d); break; }
case 0x0A: { const d=this._u8(),a=this._u8(),b=this._u8(); const r=(this.gp[a]*this.gp[b])|0; this.gp[d]=r; this._setFlags(r); this.changedRegs.add(d); break; }
case 0x0B: { const d=this._u8(),a=this._u8(),b=this._u8(); if(this.gp[b]===0) throw new Error('Division by zero'); this.gp[d]=(this.gp[a]/this.gp[b])|0; this._setFlags(this.gp[d]); this.changedRegs.add(d); break; }
case 0x0C: { const d=this._u8(),a=this._u8(),b=this._u8(); if(this.gp[b]===0) throw new Error('Modulo by zero'); this.gp[d]=(this.gp[a]%this.gp[b])|0; this._setFlags(this.gp[d]); this.changedRegs.add(d); break; }
case 0x0E: { const r=this._u8(); const v=(this.gp[r]+1)|0; this.gp[r]=v; this._setFlags(v); this.changedRegs.add(r); break; }
case 0x0F: { const r=this._u8(); const v=(this.gp[r]-1)|0; this.gp[r]=v; this._setFlags(v); this.changedRegs.add(r); break; }
case 0x20: this.stack.push(this.gp[this._u8()]); break;
case 0x21: { const r=this._u8(); this.gp[r]=this.stack.pop()||0; this.changedRegs.add(r); break; }
case 0x22: { if(this.stack.length>0){ const v=this.stack[this.stack.length-1]; this.stack.push(v);} break; }
case 0x04: { const _r=this._u8(),off=this._i16(); this.pc=(this.pc+off)&0xFFFFFFFF; break; }
case 0x05: { const r=this._u8(),off=this._i16(); if(this.gp[r]===0) this.pc=(this.pc+off)&0xFFFFFFFF; break; }
case 0x06: { const r=this._u8(),off=this._i16(); if(this.gp[r]!==0) this.pc=(this.pc+off)&0xFFFFFFFF; break; }
case 0x07: { const _r=this._u8(),off=this._i16(); this.stack.push(this.pc); this.pc=(this.pc+off)&0xFFFFFFFF; break; }
case 0x28: { const _r=this._u8(),_p=this._u8(); if(this.stack.length>0){ this.pc=this.stack.pop(); } break; }
case 0x2D: { const a=this._u8(),b=this._u8(); this._flagZero=this.gp[a]===this.gp[b]; this._flagSign=this.gp[a]<this.gp[b]; break; }
case 0x2E: { const _r=this._u8(),off=this._i16(); if(this._flagZero) this.pc=(this.pc+off)&0xFFFFFFFF; break; }
case 0x2F: { const _r=this._u8(),off=this._i16(); if(!this._flagZero) this.pc=(this.pc+off)&0xFFFFFFFF; break; }
case 0x10: { const d=this._u8(),a=this._u8(),b=this._u8(); const r=this.gp[a]&this.gp[b]; this.gp[d]=r; this._setFlags(r); this.changedRegs.add(d); break; }
case 0x11: { const d=this._u8(),a=this._u8(),b=this._u8(); const r=this.gp[a]|this.gp[b]; this.gp[d]=r; this._setFlags(r); this.changedRegs.add(d); break; }
case 0x12: { const d=this._u8(),a=this._u8(),b=this._u8(); const r=this.gp[a]^this.gp[b]; this.gp[d]=r; this._setFlags(r); this.changedRegs.add(d); break; }
case 0x13: { const d=this._u8(),s=this._u8(); const r=~this.gp[s]; this.gp[d]=r; this._setFlags(r); this.changedRegs.add(d); break; }
case 0x14: { const d=this._u8(),a=this._u8(),b=this._u8(); const r=this.gp[a]<<(this.gp[b]&0x1f); this.gp[d]=r; this._setFlags(r); this.changedRegs.add(d); break; }
case 0x15: { const d=this._u8(),a=this._u8(),b=this._u8(); const r=this.gp[a]>>(this.gp[b]&0x1f); this.gp[d]=r; this._setFlags(r); this.changedRegs.add(d); break; }
case 0x03: { const d=this._u8(),a=this._u8(); this.mem[this.gp[a]&0xFF]=this.gp[d]; break; }
case 0x02: { const d=this._u8(),a=this._u8(); this.gp[d]=this.mem[this.gp[a]&0xFF]; this.changedRegs.add(d); break; }
case 0x81: break;
default: throw new Error(`Unknown opcode: 0x${op.toString(16).padStart(2,'0')}`);
}
} catch(e) { this.error = e.message; return false; }
return !this.halted && this.pc < this.bc.length && this.cycles < this.maxCycles;
}
execute() {
this.halted=false; this.cycles=0; this.error=null;
this.prevRegs.set(this.gp);
try {
while(!this.halted && this.pc<this.bc.length && this.cycles<this.maxCycles) {
if(!this.step()) break;
}
} catch(e) { this.error = e.message; }
return this;
}
dump() {
const regs=[];
for(let i=0;i<16;i++) if(this.gp[i]!==0) regs.push(`R${i}=${this.gp[i]}`);
return `PC=${this.pc} cycles=${this.cycles} halted=${this.halted} [${regs.join(' ')}]`;
}
}
function assemble(text) {
const labels={}; const instructions=[];
let pc=0;
for(const rawLine of text.split('\n')) {
let line=rawLine.trim();
if(!line||line.startsWith('//')||line.startsWith(';')) continue;
if(line.includes(':')) {
const [labelPart,...rest]=line.split(':');
labels[labelPart.trim()]=pc;
line=rest.join(':').trim();
if(!line) continue;
}
const parts=line.replace(/,/g,' ').split(/\s+/);
const mn=parts[0].toUpperCase();
instructions.push({parts,pc});
if(mn in OP) {
if(['HALT','NOP','DUP','YIELD'].includes(mn)) pc+=1;
else if(['INC','DEC','PUSH','POP','INEG','INOT'].includes(mn)) pc+=2;
else if(['MOV','LOAD','STORE','CMP'].includes(mn)) pc+=3;
else if(['IADD','ISUB','IMUL','IDIV','IMOD','IAND','IOR','IXOR','ISHL','ISHR'].includes(mn)) pc+=4;
else if(['MOVI','JMP','JZ','JNZ','CALL','JE','JNE'].includes(mn)) pc+=4;
else if(mn==='RET') pc+=3;
}
}
const bc=[];
const resolveValue=(token,currentPc)=>{ token=token.trim(); const num=parseInt(token); if(!isNaN(num)) return num; if(token in labels) return labels[token]-currentPc; throw new Error(`Cannot resolve: ${token}`); };
for(const {parts,pc:instPc} of instructions) {
const mn=parts[0].toUpperCase();
if(!(mn in OP)) continue;
const op=OP[mn];
if(['HALT','NOP','DUP','YIELD'].includes(mn)) { bc.push(op); }
else if(['INC','DEC','PUSH','POP'].includes(mn)) { bc.push(op,parseInt(parts[1].slice(1))); }
else if(['MOV','LOAD','STORE','CMP'].includes(mn)) { bc.push(op,parseInt(parts[1].slice(1)),parseInt(parts[2].slice(1))); }
else if(['IADD','ISUB','IMUL','IDIV','IMOD','IAND','IOR','IXOR','ISHL','ISHR'].includes(mn)) {
bc.push(op,parseInt(parts[1].slice(1)),parseInt(parts[2].slice(1)),parts.length>3?parseInt(parts[3].slice(1)):parseInt(parts[1].slice(1)));
} else if(mn==='MOVI') {
bc.push(op,parseInt(parts[1].slice(1)));
const v=resolveValue(parts[2],bc.length+1); bc.push(v&0xFF,(v>>8)&0xFF);
} else if(['JMP','JZ','JNZ','CALL','JE','JNE'].includes(mn)) {
bc.push(op,parseInt(parts[1]?parts[1].slice(1):'0')||0);
const labelOrOff=parts[2]||parts[1];
const v=isNaN(parseInt(labelOrOff))?resolveValue(labelOrOff,bc.length+2):parseInt(labelOrOff);
bc.push(v&0xFF,(v>>8)&0xFF);
} else if(mn==='RET') { bc.push(op,0,0); }
}
return new Uint8Array(bc);
}
// ═══════════════════════════════════════════════════════════════════════════
// VISUAL EDITOR STATE
// ═══════════════════════════════════════════════════════════════════════════
let nodes = [];
let wires = [];
let nextId = 1;
let selectedNode = null;
let dragNode = null;
let dragOffset = {x:0,y:0};
let wireStart = null;
let stepVM = null;
let lastCompiledBC = null;
let lastCompiledASM = '';
const canvas = document.getElementById('canvas');
const svg = document.getElementById('wire-svg');
const canvasArea = document.getElementById('canvas-area');
// Memory address allocation for budget tracking
const BUDGET_BASE_ADDR = 100; // Budgets stored at mem[100+]
// ═══════════════════════════════════════════════════════════════════════════
// NODE DEFINITIONS
// ═══════════════════════════════════════════════════════════════════════════
const NODE_DEFS = {
// ── Conservation Nodes ──
budget: {
title: '🛡 Conservation Budget',
inputs: [], outputs: ['budget'],
props: [
{key:'name', label:'Name', default:'token_budget', type:'text'},
{key:'type', label:'Type', default:'tokens', type:'select', options:['tokens','actions','time','calls']},
{key:'limit', label:'Limit', default:1000, type:'number'},
{key:'reg', label:'Reg', default:0, type:'number'},
{key:'addr', label:'Addr', default:100, type:'number'}
],
compile: (n) => {
const reg = n.props.reg||0;
const addr = n.props.addr||100;
const limit = n.props.limit||1000;
return `MOVI R${reg}, ${limit} ; budget[${n.props.name||'unnamed'}] = ${limit} ${n.props.type||'tokens'}\nMOVI R14, ${addr}\nSTORE R${reg}, R14`;
},
ledger: (n) => ({name: n.props.name||'unnamed', type: n.props.type||'tokens', limit: n.props.limit||0, addr: n.props.addr||100})
},
gate: {
title: '🚦 Action Gate',
inputs: ['check'], outputs: ['permit', 'deny'],
props: [
{key:'budgetAddr', label:'B-Addr', default:100, type:'number'},
{key:'cost', label:'Cost', default:1, type:'number'},
{key:'reg', label:'Reg', default:0, type:'number'}
],
compile: (n) => {
const reg = n.props.reg||0;
const addr = n.props.budgetAddr||100;
const cost = n.props.cost||1;
return `MOVI R14, ${addr} ; load remaining budget\nLOAD R${reg}, R14\nMOVI R15, ${cost} ; cost per action\nCMP R${reg}, R15 ; budget >= cost?\nJE R0, _gate_permit_${n.reg || n.id}\n; deny path\nMOVI R0, 0 ; BLOCKED\nHALT\n_gate_permit_${n.reg || n.id}:\nISUB R${reg}, R${reg}, R15 ; deduct\nSTORE R${reg}, R14 ; save remaining\nMOVI R0, 1 ; PERMITTED`;
}
},
decision: {
title: '🔀 Decision Point',
inputs: ['cond'], outputs: ['true', 'false'],
props: [
{key:'rA', label:'Reg A', default:0, type:'number'},
{key:'rB', label:'Reg B', default:1, type:'number'},
{key:'op', label:'Op', default:'==', type:'select', options:['==','!=','<','>','<=','>=']}
],
compile: (n) => {
const rA = n.props.rA||0;
const rB = n.props.rB||1;
const label = `L_${n.id}`;
// CMP sets zero flag when equal
return `CMP R${rA}, R${rB} ; decision: R${rA} ${n.props.op||'=='} R${rB}`;
}
},
// ── Agent / Room Nodes ──
llm: {
title: '🤖 LLM Call',
inputs: ['prompt', 'budget'], outputs: ['response'],
props: [
{key:'model', label:'Model', default:'glm-5.2', type:'text'},
{key:'maxTok', label:'MaxTok', default:512, type:'number'},
{key:'temp', label:'Temp', default:7, type:'number'},
{key:'reg', label:'Reg', default:0, type:'number'}
],
compile: (n) => {
const reg = n.props.reg||0;
const maxTok = n.props.maxTok||512;
return `; LLM[${n.props.model||'default'}] max=${maxTok} temp=${n.props.temp||7}\nMOVI R${reg}, ${maxTok} ; bounded max_tokens\nPUSH R${reg} ; push token budget\n; CALL model subroutine would go here\n; response placeholder:\nMOVI R${reg}, 1 ; success`;
}
},
room: {
title: '💬 Room Protocol',
inputs: ['message'], outputs: ['sent'],
props: [
{key:'action', label:'Action', default:'send', type:'select', options:['send','recv','enter','exit']},
{key:'room', label:'Room', default:'plato-main', type:'text'},
{key:'reg', label:'Reg', default:0, type:'number'}
],
compile: (n) => {
const reg = n.props.reg||0;
const action = n.props.action||'send';
const room = n.props.room||'plato-main';
return `; ROOM ${action} → ${room}\nMOVI R${reg}, ${action.charCodeAt(0)} ; action code\nPUSH R${reg} ; queue message\nMOVI R${reg}, 1 ; success`;
}
},
// ── Flow Nodes ──
io: {
title: '埠 I/O Port',
inputs: [], outputs: ['signal'],
props: [
{key:'mode', label:'Mode', default:'input', type:'select', options:['input','output']},
{key:'reg', label:'Reg', default:0, type:'number'},
{key:'value', label:'Value', default:0, type:'number'}
],
compile: (n) => {
if (n.props.mode === 'input') {
return `MOVI R${n.props.reg||0}, ${n.props.value||0} ; INPUT port`;
}
return `; OUTPUT port: R${n.props.reg||0} = ${n.props.value||0}\nMOVI R${n.props.reg||0}, ${n.props.value||0}`;
}
},
// ── Basic Nodes ──
constant: {
title: '📦 Constant',
inputs: [], outputs: ['val'],
props: [{key:'value', label:'Value', default:42, type:'number'},
{key:'reg', label:'Reg', default:0, type:'number'}],
compile: (n) => `MOVI R${n.props.reg||0}, ${n.props.value||0}`
},
comparator: {
title: '🔍 Comparator',
inputs: ['A', 'B'], outputs: ['flags'],
props: [{key:'rA', label:'Reg A', default:0, type:'number'},
{key:'rB', label:'Reg B', default:1, type:'number'},
{key:'op', label:'Op', default:'==', type:'select', options:['==','!=','<','>','<=','>=']}],
compile: (n) => `CMP R${n.props.rA||0}, R${n.props.rB||1} ; compare R${n.props.rA||0} ${n.props.op||'=='} R${n.props.rB||1}`
},
// ── Legacy Nodes ──
arithmetic: {
title: '🔧 Arithmetic',
inputs: ['A','B'], outputs: ['result'],
props: [{key:'op', label:'Op', default:'ADD', type:'select', options:['ADD','SUB','MUL','DIV','MOD']},
{key:'reg', label:'Dest', default:0, type:'number'},
{key:'rA', label:'RA', default:1, type:'number'},
{key:'rB', label:'RB', default:2, type:'number'}],
compile: (n) => {
const m = {ADD:'IADD',SUB:'ISUB',MUL:'IMUL',DIV:'IDIV',MOD:'IMOD'};
return `${m[n.props.op]||'IADD'} R${n.props.reg||0}, R${n.props.rA||1}, R${n.props.rB||2}`;
}
},
branch: {
title: '↪ Branch',
inputs: ['cond'], outputs: ['→ target'],
props: [{key:'type', label:'Type', default:'JE', type:'select', options:['JE','JNE','JZ','JNZ','JMP']},
{key:'reg', label:'Reg', default:0, type:'number'},
{key:'label', label:'Label', default:'target', type:'text'}],
compile: (n) => `${n.props.type||'JE'} R${n.props.reg||0}, ${n.props.label||'target'}`
},
memory: {
title: '💾 Memory',
inputs: ['addr/val'], outputs: ['loaded'],
props: [{key:'op', label:'Op', default:'STORE', type:'select', options:['STORE','LOAD']},
{key:'reg', label:'Reg', default:0, type:'number'},
{key:'addrReg', label:'AddrR', default:1, type:'number'}],
compile: (n) => n.props.op==='STORE'
? `STORE R${n.props.reg||0}, R${n.props.addrReg||1}`
: `LOAD R${n.props.reg||0}, R${n.props.addrReg||1}`
},
stack: {
title: '📚 Stack',
inputs: ['val'], outputs: ['popped'],
props: [{key:'op', label:'Op', default:'PUSH', type:'select', options:['PUSH','POP','DUP']},
{key:'reg', label:'Reg', default:0, type:'number'}],
compile: (n) => {
const op = n.props.op||'PUSH';
if(op==='DUP') return 'DUP';
return `${op} R${n.props.reg||0}`;
}
},
output: {
title: '📊 Output',
inputs: ['value'], outputs: [],
props: [{key:'reg', label:'Reg', default:0, type:'number'}],
compile: (n) => `; OUT: R${n.props.reg||0} = (display in output panel)`
},
halt: {
title: '⏹ Halt',
inputs: [], outputs: [],
props: [],
compile: () => 'HALT'
}
};
// ═══════════════════════════════════════════════════════════════════════════
// NODE CREATION & RENDERING
// ═══════════════════════════════════════════════════════════════════════════
function createNode(type, x, y, props) {
const def = NODE_DEFS[type];
if (!def) return;
const node = { id: nextId++, type, x, y, props: {} };
for (const p of def.props) {
node.props[p.key] = props && props[p.key] !== undefined ? props[p.key] : p.default;
}
nodes.push(node);
renderNode(node);
updateLedger();
return node;
}
function renderNode(node) {
const def = NODE_DEFS[node.type];
const el = document.createElement('div');
el.className = 'node';
el.dataset.type = node.type;
el.dataset.id = node.id;
el.style.left = node.x + 'px';
el.style.top = node.y + 'px';
let html = `<div class="node-header" onmousedown="startDrag(event,${node.id})">
<span>${def.title}</span>
<span class="del" onclick="deleteNode(${node.id})">✕</span>
</div>`;
html += '<div class="node-body">';
for (const p of def.props) {
html += `<div class="row"><label>${p.label}</label>`;
if (p.type === 'select') {
html += `<select onchange="updateProp(${node.id},'${p.key}',this.value)">`;
for (const opt of p.options) {
html += `<option value="${opt}" ${node.props[p.key]===opt?'selected':''}>${opt}</option>`;
}
html += `</select>`;
} else {
html += `<input type="${p.type==='number'?'number':'text'}" value="${node.props[p.key]}" onchange="updateProp(${node.id},'${p.key}',this.value)" style="width:auto;max-width:90px;">`;
}
html += `</div>`;
}
html += '</div>';
el.innerHTML = html;
// Calculate port positions based on body height
const inputCount = def.inputs.length;
const outputCount = def.outputs.length;
const maxPorts = Math.max(inputCount, outputCount);
def.inputs.forEach((name, i) => {
const portTop = 34 + i * 22 + 12;
const port = document.createElement('div');
port.className = 'port input';
port.style.top = portTop + 'px';
port.dataset.nodeId = node.id;
port.dataset.portType = 'input';
port.dataset.portIdx = i;
port.onmousedown = (e) => { e.stopPropagation(); handlePortClick(node.id, 'input', i, e); };
el.appendChild(port);
const lbl = document.createElement('span');
lbl.className = 'port-title input';
lbl.style.top = (portTop - 1) + 'px';
lbl.textContent = name;
el.appendChild(lbl);
});
def.outputs.forEach((name, i) => {
const portTop = 34 + i * 22 + 12;
const port = document.createElement('div');
port.className = 'port output';
port.style.top = portTop + 'px';
port.dataset.nodeId = node.id;
port.dataset.portType = 'output';
port.dataset.portIdx = i;
port.onmousedown = (e) => { e.stopPropagation(); handlePortClick(node.id, 'output', i, e); };
el.appendChild(port);
const lbl = document.createElement('span');
lbl.className = 'port-title output';
lbl.style.top = (portTop - 1) + 'px';
lbl.textContent = name;
el.appendChild(lbl);
});
canvas.appendChild(el);
}
function updateProp(id, key, val) {
const node = nodes.find(n => n.id === id);
if (!node) return;
const def = NODE_DEFS[node.type].props.find(p => p.key === key);
node.props[key] = def && def.type === 'number' ? parseInt(val) || 0 : val;
updateLedger();
}
function deleteNode(id) {
nodes = nodes.filter(n => n.id !== id);
wires = wires.filter(w => w.from.nodeId !== id && w.to.nodeId !== id);
rerenderAll();
updateLedger();
}
function startDrag(e, id) {
e.preventDefault();
const node = nodes.find(n => n.id === id);
if (!node) return;
const el = canvas.querySelector(`.node[data-id="${id}"]`);
const rect = el.getBoundingClientRect();
dragOffset = { x: e.clientX - rect.left, y: e.clientY - rect.top };
dragNode = id;
selectedNode = id;
document.querySelectorAll('.node').forEach(n => n.classList.remove('selected'));
el.classList.add('selected');
}
function getEventPos(e) {
if (e.touches && e.touches[0]) return {x: e.touches[0].clientX, y: e.touches[0].clientY};
return {x: e.clientX, y: e.clientY};
}
document.addEventListener('mousemove', (e) => {
if (dragNode !== null) {
const node = nodes.find(n => n.id === dragNode);
if (!node) return;
const canvasRect = canvas.getBoundingClientRect();
node.x = e.clientX - canvasRect.left - dragOffset.x;
node.y = e.clientY - canvasRect.top - dragOffset.y;
const el = canvas.querySelector(`.node[data-id="${dragNode}"]`);
if (el) { el.style.left = node.x + 'px'; el.style.top = node.y + 'px'; }
drawWires();
}
if (wireStart) drawTempWire(e);
});
document.addEventListener('mouseup', () => { dragNode = null; });
// ═══════════════════════════════════════════════════════════════════════════
// WIRING
// ═══════════════════════════════════════════════════════════════════════════
function handlePortClick(nodeId, portType, portIdx, e) {
if (portType === 'output') {
wireStart = { nodeId, portIdx };
log('Wire started from node ' + nodeId);
} else if (portType === 'input' && wireStart) {
if (wireStart.nodeId === nodeId) { wireStart = null; clearTempWire(); return; }
wires = wires.filter(w => !(w.to.nodeId === nodeId && w.to.port === portIdx));
wires.push({ from: { nodeId: wireStart.nodeId, port: wireStart.portIdx }, to: { nodeId, port: portIdx } });
wireStart = null;
clearTempWire();
drawWires();
log('Wire connected');
}
}
function clearTempWire() {
const temp = document.getElementById('wire-temp');
if (temp) temp.remove();