-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1212 lines (1109 loc) · 66.4 KB
/
index.html
File metadata and controls
1212 lines (1109 loc) · 66.4 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" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CodeLens Pro — Step Visualizer</title>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&family=Outfit:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<style>
/* ═══════════════════════ THEME VARIABLES ═══════════════════════ */
:root {
--bg:#0d1117;--surface:#161b22;--surface2:#1c2128;--surface3:#21262d;
--border:#30363d;--border2:#3d444d;
--text:#e6edf3;--text2:#8b949e;--text3:#656d76;
--accent:#2ea043;--accent-h:#3fb950;--accent-d:rgba(46,160,67,.15);
--blue:#388bfd;--blue-d:rgba(56,139,253,.12);
--warn:#d29922;--warn-d:rgba(210,153,34,.12);
--red:#f85149;--red-d:rgba(248,81,73,.1);
--purple:#bc8cff;--purple-d:rgba(188,140,255,.12);
--cyan:#39c5cf;--cyan-d:rgba(57,197,207,.1);
--orange:#f0883e;
--shadow:0 4px 24px rgba(0,0,0,.4);
}
[data-theme="light"]{
--bg:#f6f8fa;--surface:#fff;--surface2:#f0f3f6;--surface3:#e8ecf0;
--border:#d0d7de;--border2:#afb8c1;
--text:#1f2328;--text2:#57606a;--text3:#8c959f;
--accent:#1a7f37;--accent-h:#2ea043;--accent-d:rgba(26,127,55,.1);
--blue:#0969da;--blue-d:rgba(9,105,218,.08);
--warn:#9a6700;--warn-d:rgba(154,103,0,.08);
--red:#cf222e;--red-d:rgba(207,34,46,.08);
--purple:#8250df;--purple-d:rgba(130,80,223,.08);
--cyan:#0598bc;--cyan-d:rgba(5,152,188,.08);
--orange:#bc4c00;
--shadow:0 4px 24px rgba(0,0,0,.12);
}
*{box-sizing:border-box;margin:0;padding:0}
html,body{height:100%;font-family:'Outfit',sans-serif;background:var(--bg);color:var(--text);overflow:hidden}
/* ═══════════════════════ LAYOUT ═══════════════════════ */
.app{display:flex;flex-direction:column;height:100vh}
.header{display:flex;align-items:center;gap:8px;padding:8px 14px;background:var(--surface);border-bottom:1px solid var(--border);flex-shrink:0;flex-wrap:wrap;z-index:10}
.logo{font-size:.95rem;font-weight:800;display:flex;align-items:center;gap:7px;margin-right:6px;letter-spacing:-.3px}
.logo-gem{color:var(--accent);font-size:1.1rem}
.logo sub{font-size:.55rem;font-weight:600;color:var(--accent);letter-spacing:1px;text-transform:uppercase;margin-left:2px;vertical-align:super}
.vsep{width:1px;height:20px;background:var(--border);flex-shrink:0}
.main{display:grid;grid-template-columns:1fr 1fr;flex:1;overflow:hidden}
.panel{display:flex;flex-direction:column;overflow:hidden}
.panel-l{border-right:1px solid var(--border)}
.phead{padding:7px 12px;background:var(--surface);border-bottom:1px solid var(--border);font-size:.68rem;font-weight:700;color:var(--text3);letter-spacing:1.2px;text-transform:uppercase;display:flex;align-items:center;gap:7px;flex-shrink:0}
.phead-dot{width:7px;height:7px;border-radius:50%;flex-shrink:0}
.statusbar{padding:4px 14px;background:var(--surface);border-top:1px solid var(--border);font-size:.7rem;color:var(--text2);display:flex;align-items:center;gap:8px;flex-shrink:0;font-family:'JetBrains Mono',monospace}
/* ═══════════════════════ BUTTONS & CONTROLS ═══════════════════════ */
.btn{padding:5px 13px;border-radius:6px;border:1px solid var(--border2);background:var(--surface3);color:var(--text);font-family:'Outfit',sans-serif;font-size:.78rem;font-weight:600;cursor:pointer;transition:all .12s;display:inline-flex;align-items:center;gap:5px;white-space:nowrap}
.btn:hover:not(:disabled){background:var(--border);border-color:var(--border2)}
.btn:active:not(:disabled){transform:scale(.97)}
.btn:disabled{opacity:.35;cursor:not-allowed}
.btn-green{background:var(--accent);border-color:var(--accent);color:#fff}
.btn-green:hover:not(:disabled){background:var(--accent-h)!important;border-color:var(--accent-h)!important}
.btn-red{background:var(--red);border-color:var(--red);color:#fff}
.btn-red:hover:not(:disabled){opacity:.85!important}
.btn-icon{padding:5px 9px;font-size:.85rem}
.badge{font-family:'JetBrains Mono',monospace;font-size:.72rem;color:var(--text2);background:var(--surface2);border:1px solid var(--border);border-radius:5px;padding:4px 9px;min-width:68px;text-align:center}
.badge b{color:var(--accent)}
select.ctl{background:var(--surface2);border:1px solid var(--border);color:var(--text);padding:5px 9px;border-radius:6px;font-family:'Outfit',sans-serif;font-size:.78rem;cursor:pointer;outline:none}
input[type=range].speed-slider{width:80px;accent-color:var(--accent);cursor:pointer;vertical-align:middle}
.speed-label{font-family:'JetBrains Mono',monospace;font-size:.68rem;color:var(--text2);min-width:28px}
/* ═══════════════════════ EDITOR PANEL ═══════════════════════ */
.editor-wrap{flex:1;display:flex;overflow:hidden;position:relative;background:var(--bg)}
.linenos{padding:14px 0;background:var(--surface);border-right:1px solid var(--border);min-width:44px;font-family:'JetBrains Mono',monospace;font-size:.75rem;line-height:20px;text-align:right;color:var(--text3);overflow:hidden;user-select:none;flex-shrink:0}
.lno{display:block;padding:0 8px 0 4px;transition:color .15s;cursor:pointer;position:relative}
.lno:hover{color:var(--text2)}
.lno.active{color:var(--accent);font-weight:600}
.lno.bp::before{content:'●';position:absolute;left:2px;color:var(--red);font-size:.55rem;top:50%;transform:translateY(-50%)}
#code{flex:1;border:none;outline:none;resize:none;background:transparent;color:var(--text);font-family:'JetBrains Mono',monospace;font-size:.75rem;line-height:20px;padding:14px 12px;white-space:pre;overflow:auto;tab-size:2;caret-color:var(--accent)}
#code::placeholder{color:var(--text3)}
.hl-overlay{position:absolute;top:14px;left:44px;right:0;pointer-events:none}
.hl-line{height:20px}
.hl-line.active{background:rgba(46,160,67,.14);border-left:2px solid var(--accent)}
.hl-line.bp-line{background:rgba(248,81,73,.08)!important;border-left:2px solid var(--red)!important}
.prog{height:2px;background:var(--border);flex-shrink:0}
.prog-fill{height:100%;background:var(--accent);transition:width .3s}
/* ── Syntax highlight overlay ── */
.syntax-display{position:absolute;top:0;left:44px;right:0;bottom:0;pointer-events:none;font-family:'JetBrains Mono',monospace;font-size:.75rem;line-height:20px;padding:14px 12px;white-space:pre;overflow:hidden;color:transparent}
.kw{color:#ff7b72}.str{color:#a5d6ff}.num{color:#79c0ff}.cmt{color:#8b949e;font-style:italic}.fn-c{color:#d2a8ff}.op{color:#ff7b72}.bool-c{color:#79c0ff}
[data-theme="light"] .kw{color:#cf222e}[data-theme="light"] .str{color:#0550ae}[data-theme="light"] .num{color:#0550ae}[data-theme="light"] .cmt{color:#6e7781}[data-theme="light"] .fn-c{color:#8250df}[data-theme="light"] .bool-c{color:#0550ae}
/* ── Timeline scrubber ── */
.timeline{padding:6px 12px;background:var(--surface2);border-bottom:1px solid var(--border);display:none;align-items:center;gap:8px;flex-shrink:0}
.timeline.show{display:flex}
#scrubber{flex:1;accent-color:var(--accent);cursor:pointer;height:4px}
/* ═══════════════════════ VIZ PANEL ═══════════════════════ */
.viz-tabs{display:flex;border-bottom:1px solid var(--border);background:var(--surface);flex-shrink:0}
.vtab{padding:7px 14px;font-size:.72rem;font-weight:600;color:var(--text3);cursor:pointer;border-bottom:2px solid transparent;transition:all .15s;letter-spacing:.3px}
.vtab:hover{color:var(--text2)}
.vtab.active{color:var(--accent);border-bottom-color:var(--accent)}
.viz-scroll{flex:1;overflow-y:auto;padding:12px;display:flex;flex-direction:column;gap:9px}
.viz-scroll::-webkit-scrollbar{width:4px}.viz-scroll::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px}
.empty{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:10px;color:var(--text3);text-align:center;padding:20px}
.empty-gem{font-size:2.5rem;opacity:.2}
/* ═══════════════════════ VIZ BLOCKS ═══════════════════════ */
.vb{border-radius:8px;border:1px solid var(--border);overflow:hidden;animation:ain .2s ease}
@keyframes ain{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}
.vb-head{padding:6px 11px;font-size:.67rem;font-weight:700;letter-spacing:.8px;text-transform:uppercase;display:flex;align-items:center;gap:6px}
.vb-body{padding:10px 11px;background:var(--surface2);font-family:'JetBrains Mono',monospace;font-size:.75rem}
.vb-step .vb-head{background:var(--accent-d);color:var(--accent);border-bottom:1px solid rgba(46,160,67,.2)}
.vb-vars .vb-head{background:var(--blue-d);color:var(--blue);border-bottom:1px solid rgba(56,139,253,.2)}
.vb-out .vb-head{background:var(--cyan-d);color:var(--cyan);border-bottom:1px solid rgba(57,197,207,.2)}
.vb-loop .vb-head{background:var(--warn-d);color:var(--warn);border-bottom:1px solid rgba(210,153,34,.2)}
.vb-cond .vb-head{background:var(--red-d);color:var(--red);border-bottom:1px solid rgba(248,81,73,.2)}
.vb-call .vb-head{background:var(--purple-d);color:var(--purple);border-bottom:1px solid rgba(188,140,255,.2)}
.vb-ds .vb-head{background:rgba(240,136,62,.1);color:var(--orange);border-bottom:1px solid rgba(240,136,62,.2)}
.snippet{background:var(--bg);border-radius:5px;padding:6px 10px;color:var(--accent);border:1px solid rgba(46,160,67,.18);margin-bottom:6px;white-space:pre;overflow-x:auto;font-size:.75rem}
.desc{font-family:'Outfit',sans-serif;font-size:.82rem;color:var(--text)}
.tip{font-family:'Outfit',sans-serif;font-size:.73rem;color:var(--text2);margin-top:4px;padding:5px 8px;background:var(--surface3);border-radius:4px;border-left:2px solid var(--warn)}
/* Variables table */
.vtable{width:100%;border-collapse:collapse}
.vtable th{font-size:.65rem;color:var(--text3);text-align:left;padding-bottom:5px;border-bottom:1px solid var(--border);font-weight:600;letter-spacing:.5px}
.vtable td{padding:4px 0;border-bottom:1px solid rgba(255,255,255,.04);vertical-align:top}
[data-theme="light"] .vtable td{border-bottom-color:rgba(0,0,0,.04)}
.vn{color:#79c0ff;width:30%}[data-theme="light"] .vn{color:#0550ae}
.vt{color:var(--text3);font-size:.68rem;width:20%}
.vv{color:var(--text)}
.vv.changed{color:var(--accent);font-weight:600}
.arr-box{display:flex;flex-wrap:wrap;gap:3px;margin-top:4px}
.arr-cell{min-width:30px;text-align:center;border:1px solid var(--border2);border-radius:4px;padding:3px 6px;font-size:.7rem;background:var(--bg);transition:all .2s}
.arr-cell.hl-cell{border-color:var(--accent);color:var(--accent);background:var(--accent-d)}
.arr-idx{font-size:.58rem;color:var(--text3);text-align:center}
.out-line{color:#56d364;padding:2px 0;border-bottom:1px solid rgba(255,255,255,.04)}
[data-theme="light"] .out-line{color:#1a7f37}
/* Stack frames */
.stack-frame{background:var(--bg);border-left:2px solid var(--purple);border-radius:4px;padding:6px 10px;margin-bottom:4px}
.sf-name{color:var(--purple);font-weight:600;font-size:.75rem}
.sf-args{color:var(--text3);font-size:.68rem;margin-top:2px}
/* ═══════════════════════ DATA STRUCTURE VIZ ═══════════════════════ */
#ds-canvas{width:100%;flex:1;overflow:auto;background:var(--bg)}
.ds-svg{width:100%;min-height:200px}
/* Array DS */
.ds-array-wrap{padding:12px;display:flex;flex-direction:column;gap:8px}
.ds-label{font-family:'Outfit',sans-serif;font-size:.7rem;font-weight:700;color:var(--text3);letter-spacing:.8px;text-transform:uppercase;margin-bottom:4px}
.ds-arr{display:flex;flex-wrap:wrap;gap:4px}
.ds-arr-cell{display:flex;flex-direction:column;align-items:center;gap:2px}
.ds-arr-box{min-width:40px;height:36px;display:flex;align-items:center;justify-content:center;border:1.5px solid var(--border2);border-radius:5px;background:var(--surface2);font-family:'JetBrains Mono',monospace;font-size:.8rem;color:var(--text);transition:all .3s;padding:0 8px}
.ds-arr-box.hl{border-color:var(--accent);background:var(--accent-d);color:var(--accent)}
.ds-arr-idx{font-family:'JetBrains Mono',monospace;font-size:.6rem;color:var(--text3)}
.ds-pointer{font-size:.65rem;color:var(--accent);text-align:center;font-family:'JetBrains Mono',monospace}
/* Stack DS */
.ds-stack{display:flex;flex-direction:column;gap:3px;max-width:160px}
.ds-stack-cell{padding:6px 14px;border:1.5px solid var(--border2);border-radius:5px;background:var(--surface2);font-family:'JetBrains Mono',monospace;font-size:.78rem;text-align:center;transition:all .3s}
.ds-stack-cell.top{border-color:var(--accent);background:var(--accent-d);color:var(--accent)}
.ds-stack-label{font-size:.6rem;color:var(--accent);text-align:right;font-family:'JetBrains Mono',monospace}
/* Tree DS (SVG-based) */
.tree-svg{overflow:visible}
/* ═══════════════════════ CALL STACK PANEL ═══════════════════════ */
.callstack-viz{padding:12px;display:flex;flex-direction:column;gap:6px}
.cs-frame{border:1px solid var(--border);border-radius:6px;padding:8px 11px;background:var(--surface2);transition:all .2s}
.cs-frame.current{border-color:var(--accent);background:var(--accent-d)}
.cs-name{font-family:'JetBrains Mono',monospace;font-size:.78rem;font-weight:600;color:var(--text)}
.cs-frame.current .cs-name{color:var(--accent)}
.cs-detail{font-size:.7rem;color:var(--text3);font-family:'JetBrains Mono',monospace;margin-top:3px}
.cs-vars{margin-top:6px;display:flex;flex-direction:column;gap:3px}
.cs-var{font-size:.7rem;color:var(--text2);font-family:'JetBrains Mono',monospace;display:flex;gap:8px}
.cs-var-name{color:#79c0ff}[data-theme="light"] .cs-var-name{color:#0550ae}
/* ═══════════════════════ BREAKPOINT MENU ═══════════════════════ */
.bp-list{padding:10px 12px;display:flex;flex-direction:column;gap:5px}
.bp-item{display:flex;align-items:center;justify-content:space-between;padding:5px 9px;border:1px solid var(--red-d);border-radius:5px;background:var(--red-d);font-family:'JetBrains Mono',monospace;font-size:.73rem}
.bp-item span{color:var(--text2)}
.bp-remove{cursor:pointer;color:var(--red);font-weight:700;padding:1px 5px}
.bp-empty{color:var(--text3);font-size:.8rem;text-align:center;padding:20px;font-family:'Outfit',sans-serif}
/* ═══════════════════════ MODAL / EXPORT ═══════════════════════ */
.modal-bg{display:none;position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:100;align-items:center;justify-content:center}
.modal-bg.open{display:flex}
.modal{background:var(--surface);border:1px solid var(--border2);border-radius:10px;padding:20px;max-width:480px;width:90%;box-shadow:var(--shadow)}
.modal h3{font-size:1rem;font-weight:700;margin-bottom:12px}
.modal-btns{display:flex;gap:8px;margin-top:14px;flex-wrap:wrap}
.code-share{background:var(--bg);border:1px solid var(--border);border-radius:6px;padding:10px;font-family:'JetBrains Mono',monospace;font-size:.72rem;color:var(--text2);word-break:break-all;max-height:100px;overflow:auto;margin-bottom:8px}
/* ═══════════════════════ PILLS ═══════════════════════ */
.pill{padding:2px 8px;border-radius:20px;font-size:.63rem;font-weight:700;letter-spacing:.4px}
.p-ready{background:rgba(125,133,144,.15);color:var(--text3)}
.p-run{background:var(--blue-d);color:var(--blue)}
.p-done{background:var(--accent-d);color:var(--accent)}
.p-err{background:var(--red-d);color:var(--red)}
.p-bp{background:var(--red-d);color:var(--red)}
/* ═══════════════════════ TOOLTIP ═══════════════════════ */
[title]{cursor:help}
/* ═══════════════════════ SCROLLBAR ═══════════════════════ */
::-webkit-scrollbar{width:4px;height:4px}::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px}
/* ═══════════════════════ RESPONSIVE ═══════════════════════ */
@media(max-width:720px){
.main{grid-template-columns:1fr;grid-template-rows:1fr 1fr}
.panel-l{border-right:none;border-bottom:1px solid var(--border)}
.header{gap:5px}
}
</style>
</head>
<body>
<div class="app">
<!-- ══════════ HEADER ══════════ -->
<div class="header">
<div class="logo">⬡ CodeLens<sub>PRO</sub></div>
<div class="vsep"></div>
<select class="ctl" id="lang">
<option value="python">Python</option>
<option value="javascript">JavaScript</option>
<option value="java">Java / C++</option>
<option value="pseudo">Pseudocode</option>
</select>
<button class="btn btn-green" onclick="startViz()" title="Analyze and trace code (Ctrl+Enter)">▶ Visualize</button>
<button class="btn" onclick="resetAll()" title="Reset everything">↺</button>
<div class="vsep"></div>
<button class="btn btn-icon" id="btnP" onclick="prevStep()" disabled title="Previous step (←)">◀</button>
<div class="badge" id="badge">— / —</div>
<button class="btn btn-icon" id="btnN" onclick="nextStep()" disabled title="Next step (→)">▶</button>
<button class="btn btn-icon" id="btnPlay" onclick="togglePlay()" disabled title="Auto-play (Space)">⏵</button>
<div class="vsep"></div>
<span style="font-size:.7rem;color:var(--text3)">Speed</span>
<input type="range" class="speed-slider" id="speedSlider" min="1" max="10" value="5" title="Playback speed">
<span class="speed-label" id="speedLabel">5x</span>
<div class="vsep"></div>
<button class="btn btn-icon" onclick="jumpToBreakpoint()" id="btnBP" disabled title="Run to next breakpoint (B)">◉</button>
<button class="btn btn-icon" onclick="toggleTheme()" title="Toggle light/dark theme" id="themeBtn">☀</button>
<button class="btn btn-icon" onclick="openExport()" title="Export / Share">⬆</button>
</div>
<!-- ══════════ MAIN PANELS ══════════ -->
<div class="main">
<!-- LEFT: EDITOR -->
<div class="panel panel-l">
<div class="phead"><span class="phead-dot" style="background:#3fb950"></span>Code Editor <span style="margin-left:auto;font-size:.63rem;color:var(--text3)">Click line numbers to set breakpoints</span></div>
<div class="timeline" id="timeline">
<span style="font-size:.68rem;color:var(--text3);white-space:nowrap">Step</span>
<input type="range" id="scrubber" min="0" value="0" oninput="scrubTo(this.value)">
<span style="font-size:.68rem;color:var(--text3);white-space:nowrap" id="scrubLabel">0</span>
</div>
<div class="editor-wrap" id="edWrap">
<div class="linenos" id="lnos"></div>
<textarea id="code" spellcheck="false" placeholder="# Paste your code here — any Python, JS, Java or C code
# Example:
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
numbers = [64, 34, 25, 12, 22, 11, 90]
result = bubble_sort(numbers)
print(result)"></textarea>
<div class="hl-overlay" id="hlOverlay"></div>
</div>
<div class="prog"><div class="prog-fill" id="progFill" style="width:0%"></div></div>
</div>
<!-- RIGHT: VIZ -->
<div class="panel">
<div class="viz-tabs">
<div class="vtab active" onclick="switchTab('trace')" id="tab-trace">Trace</div>
<div class="vtab" onclick="switchTab('vars')" id="tab-vars">Variables</div>
<div class="vtab" onclick="switchTab('ds')" id="tab-ds">Data Structures</div>
<div class="vtab" onclick="switchTab('stack')" id="tab-stack">Call Stack</div>
<div class="vtab" onclick="switchTab('bps')" id="tab-bps">Breakpoints</div>
<div class="vtab" onclick="switchTab('out')" id="tab-out">Output</div>
</div>
<!-- TRACE TAB -->
<div class="viz-scroll" id="tab-trace-content">
<div class="empty">
<div class="empty-gem">⬡</div>
<div style="font-weight:700;font-size:.9rem">Paste your code on the left</div>
<div style="font-size:.8rem">Click <b>▶ Visualize</b> then step through with <b>Next ▶</b></div>
<div style="font-size:.73rem;margin-top:4px;color:var(--text3)">Keyboard: ← → to navigate · Space to auto-play · B for breakpoints</div>
</div>
</div>
<!-- VARS TAB -->
<div class="viz-scroll" id="tab-vars-content" style="display:none">
<div class="empty"><div class="empty-gem" style="font-size:1.5rem">□</div><div>Variables will appear here once you start stepping</div></div>
</div>
<!-- DS TAB -->
<div class="viz-scroll" id="tab-ds-content" style="display:none">
<div class="empty"><div class="empty-gem" style="font-size:1.5rem">⬡</div><div>Arrays, stacks, trees and lists will be visualized here</div></div>
</div>
<!-- STACK TAB -->
<div class="viz-scroll" id="tab-stack-content" style="display:none">
<div class="empty"><div class="empty-gem" style="font-size:1.5rem">≡</div><div>Call stack frames appear here during function calls</div></div>
</div>
<!-- BREAKPOINTS TAB -->
<div class="viz-scroll" id="tab-bps-content" style="display:none">
<div class="bp-empty">No breakpoints set.<br>Click a line number in the editor to add one.</div>
</div>
<!-- OUTPUT TAB -->
<div class="viz-scroll" id="tab-out-content" style="display:none">
<div class="empty"><div class="empty-gem" style="font-size:1.5rem">▸</div><div>Console output appears here</div></div>
</div>
</div>
</div>
<!-- STATUS BAR -->
<div class="statusbar">
<span class="pill p-ready" id="spill">READY</span>
<span id="smsg">Waiting for code...</span>
<span style="margin-left:auto" id="sline"></span>
</div>
</div>
<!-- EXPORT MODAL -->
<div class="modal-bg" id="exportModal">
<div class="modal">
<h3>⬆ Export & Share</h3>
<div style="display:flex;flex-direction:column;gap:10px">
<div>
<div style="font-size:.78rem;color:var(--text2);margin-bottom:5px">Shareable URL (code encoded):</div>
<div class="code-share" id="shareUrl">Click "Generate Link" to create</div>
</div>
<div style="font-size:.78rem;color:var(--text2)">Or export the current step as text snapshot:</div>
<textarea id="exportText" style="background:var(--bg);border:1px solid var(--border);color:var(--text);border-radius:6px;padding:8px;font-family:'JetBrains Mono',monospace;font-size:.7rem;height:100px;resize:none;width:100%;outline:none" readonly></textarea>
</div>
<div class="modal-btns">
<button class="btn btn-green" onclick="generateShareLink()">🔗 Generate Link</button>
<button class="btn" onclick="copySnapshot()">📋 Copy Snapshot</button>
<button class="btn" onclick="downloadHTML()">💾 Download App</button>
<button class="btn" onclick="closeExport()">Close</button>
</div>
</div>
</div>
<script>
// ═══════════════════════════════════════════════════════════════════════
// STATE
// ═══════════════════════════════════════════════════════════════════════
let steps=[], cur=-1, prevVars={}, breakpoints=new Set(), playTimer=null, isPlaying=false, activeTab='trace', allOutputs=[];
// ═══════════════════════════════════════════════════════════════════════
// LINE NUMBERS + BREAKPOINTS
// ═══════════════════════════════════════════════════════════════════════
const codeEl=document.getElementById('code');
const lnosEl=document.getElementById('lnos');
const hlOv=document.getElementById('hlOverlay');
function updateLineNums(){
const ls=codeEl.value.split('\n');
lnosEl.innerHTML=ls.map((_,i)=>{
const ln=i+1;
const hasBP=breakpoints.has(ln);
return `<span class="lno${hasBP?' bp':''}" id="ln${ln}" onclick="toggleBP(${ln})">${ln}</span>`;
}).join('');
hlOv.innerHTML=ls.map((_,i)=>{
const ln=i+1;
const hasBP=breakpoints.has(ln);
return `<div class="hl-line${hasBP?' bp-line':''}" id="hl${ln}"></div>`;
}).join('');
}
codeEl.addEventListener('input',updateLineNums);
codeEl.addEventListener('scroll',()=>{
lnosEl.scrollTop=codeEl.scrollTop;
hlOv.style.top=(14-codeEl.scrollTop)+'px';
});
function toggleBP(ln){
if(breakpoints.has(ln)) breakpoints.delete(ln);
else breakpoints.add(ln);
updateLineNums();
renderBPTab();
document.getElementById('btnBP').disabled=breakpoints.size===0||steps.length===0;
}
// ═══════════════════════════════════════════════════════════════════════
// SYNTAX HIGHLIGHTING
// ═══════════════════════════════════════════════════════════════════════
function highlightCode(code,lang){
let h=code.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
// comments
h=h.replace(/(#[^\n]*)/g,'<span class="cmt">$1</span>');
h=h.replace(/(\/\/[^\n]*)/g,'<span class="cmt">$1</span>');
// strings
h=h.replace(/("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,'<span class="str">$1</span>');
// numbers
h=h.replace(/\b(\d+\.?\d*)\b/g,'<span class="num">$1</span>');
// keywords
const kwPy=['def','class','return','if','elif','else','for','while','in','and','or','not','import','from','True','False','None','pass','break','continue','lambda','yield','with','as','try','except','finally','raise','global','nonlocal','del','assert'];
const kwJs=['function','const','let','var','return','if','else','for','while','do','switch','case','break','continue','class','new','this','typeof','instanceof','null','undefined','true','false','import','export','default','async','await','try','catch','finally','throw'];
const kwJava=['int','float','double','long','char','boolean','String','void','class','public','private','protected','static','final','return','if','else','for','while','do','new','null','true','false','import','package','this','super','extends','implements','interface','abstract','try','catch','finally','throw','throws'];
const kws=lang==='python'?kwPy:lang==='javascript'?kwJs:kwJava;
const kwRe=new RegExp('\\b('+kws.join('|')+')\\b','g');
h=h.replace(kwRe,'<span class="kw">$1</span>');
// function calls
h=h.replace(/\b([a-zA-Z_]\w*)\s*(?=\()/g,'<span class="fn-c">$1</span>');
return h;
}
// ═══════════════════════════════════════════════════════════════════════
// PYTHON TRACER
// ═══════════════════════════════════════════════════════════════════════
function tracePython(code){
const lines=code.split('\n');
const steps=[];
const vars={};
const outputs=[];
const callStack=[];
const funcDefs={};
function addStep(lineNum,desc,type,note){
steps.push({line:lineNum,description:desc,type:type,variables:JSON.parse(JSON.stringify(vars)),output:'',callStack:[...callStack],note:note||''});
}
function splitArgs(s){
const args=[];let depth=0,cur2='',inStr=false,strChar='';
for(let i=0;i<s.length;i++){
const c=s[i];
if(inStr){cur2+=c;if(c===strChar&&s[i-1]!=='\\')inStr=false;continue}
if(c==='"'||c==="'"){inStr=true;strChar=c;cur2+=c;continue}
if(c==='('||c==='['||c==='{'){depth++;cur2+=c;continue}
if(c===')'||c===']'||c==='}'){depth--;cur2+=c;continue}
if(c===','&&depth===0){args.push(cur2.trim());cur2='';continue}
cur2+=c;
}
if(cur2.trim())args.push(cur2.trim());
return args;
}
function evalSimple(expr,scope){
expr=expr.trim();
while(expr.startsWith('(')&&expr.endsWith(')'))expr=expr.slice(1,-1).trim();
if((expr.startsWith('"')&&expr.endsWith('"'))||(expr.startsWith("'")&&expr.endsWith("'")))
return{value:expr.slice(1,-1),type:'str'};
if(expr==='True')return{value:true,type:'bool'};
if(expr==='False')return{value:false,type:'bool'};
if(expr==='None')return{value:null,type:'NoneType'};
if(!isNaN(expr)&&expr!==''){const n=Number(expr);return{value:n,type:Number.isInteger(n)?'int':'float'};}
if(expr.startsWith('[')){
try{const items=splitArgs(expr.slice(1,-1)).map(x=>evalSimple(x,scope).value);return{value:items,type:'list'};}catch{}
}
if(expr.startsWith('{')&&expr.endsWith('}')){
return{value:{},type:'dict'};
}
if(expr.startsWith('f"')||expr.startsWith("f'")){
const s=expr.slice(2,-1);
const resolved=s.replace(/\{([^}]+)\}/g,(_,k)=>{const v=scope[k.trim()];return v!==undefined?(v.value!==undefined?v.value:v):k});
return{value:resolved,type:'str'};
}
try{
const safe=expr.replace(/\b([a-zA-Z_]\w*)\b/g,m=>{
if(scope[m]){const v=scope[m].value;return typeof v==='string'?JSON.stringify(v):v!==null&&v!==undefined?v:m}
if(m==='True')return 'true';if(m==='False')return 'false';if(m==='None')return 'null';
return m;
}).replace(/\band\b/g,'&&').replace(/\bor\b/g,'||').replace(/\bnot\b/g,'!').replace(/==/g,'===').replace(/!=/g,'!==').replace(/\*\*/g,'**');
// eslint-disable-next-line no-new-func
const res=Function('"use strict";return ('+safe+')')();
const t=typeof res==='boolean'?'bool':typeof res==='number'?(Number.isInteger(res)?'int':'float'):typeof res==='string'?'str':Array.isArray(res)?'list':'object';
return{value:res,type:t};
}catch{}
if(scope[expr])return scope[expr];
return{value:expr,type:'expr'};
}
function getIndent(line){let n=0;for(const c of line){if(c===' ')n++;else if(c==='\t')n+=4;else break}return n;}
// first pass: find function defs
lines.forEach((line,idx)=>{
const m=line.match(/^\s*def\s+(\w+)\s*\(([^)]*)\)/);
if(m)funcDefs[m[1]]={lineNum:idx+1,params:splitArgs(m[2])};
});
function traceBlock(lineArr,offset){
let i=0;
while(i<lineArr.length){
const raw=lineArr[i];
const line=raw.trim();
const lineNum=(offset||0)+i+1;
i++;
if(!line||line.startsWith('#')){
if(line.startsWith('#'))addStep(lineNum,'Comment — skipped','other','Comments are notes for humans, not executed');
continue;
}
const indent=getIndent(raw);
if(line.startsWith('import ')||line.startsWith('from ')){
const mod=line.replace(/^(import|from)\s+/,'').split(/\s/)[0];
addStep(lineNum,`Import module "${mod}"`, 'import','Makes extra functions available');
continue;
}
if(line.match(/^def\s+/)){
const m=line.match(/^def\s+(\w+)\s*\(([^)]*)\)/);
const fname=m?m[1]:'function';
addStep(lineNum,`Define function "${fname}"`, 'define','Function body only runs when called');
const bi=indent+4;
while(i<lineArr.length&&(lineArr[i].trim()===''||getIndent(lineArr[i])>=bi))i++;
continue;
}
if(line.match(/^class\s+/)){
const m=line.match(/^class\s+(\w+)/);
addStep(lineNum,`Define class "${m?m[1]:'Class'}"`, 'define','');
const bi=indent+4;
while(i<lineArr.length&&(lineArr[i].trim()===''||getIndent(lineArr[i])>=bi))i++;
continue;
}
if(line.match(/^for\s+/)){
const m=line.match(/^for\s+(\w+)\s+in\s+(.+):/);
if(m){
const loopVar=m[1],iterExpr=m[2].trim();
let iterVals=[];
const rangeM=iterExpr.match(/^range\((.+)\)$/);
if(rangeM){
const args=splitArgs(rangeM[1]).map(a=>{const v=evalSimple(a,vars);return typeof v.value==='number'?v.value:parseInt(a)||0});
let start=0,stop=0,step=1;
if(args.length===1){stop=args[0]}else if(args.length===2){[start,stop]=args}else{[start,stop,step]=args}
for(let x=start;step>0?x<stop:x>stop;x+=step)iterVals.push(x);
} else {
const sv=vars[iterExpr];
if(sv&&Array.isArray(sv.value))iterVals=sv.value;
else{const ev=evalSimple(iterExpr,vars);if(Array.isArray(ev.value))iterVals=[...ev.value];else iterVals=[0,1,2];}
}
const bi=indent+4;
const bodyLines=[];
while(i<lineArr.length&&(lineArr[i].trim()===''||getIndent(lineArr[i])>=bi)){bodyLines.push(lineArr[i]);i++;}
addStep(lineNum,`Start for-loop: iterate ${iterVals.length} times`,'loop',`Loop variable: ${loopVar}`);
iterVals.forEach((val,idx2)=>{
vars[loopVar]={value:val,type:typeof val==='number'?(Number.isInteger(val)?'int':'float'):'str'};
addStep(lineNum,`Iteration ${idx2+1}/${iterVals.length}: ${loopVar} = ${val}`,'loop',`${iterVals.length-idx2-1} iterations remaining`);
bodyLines.forEach((braw,bi2)=>{
const bl=braw.trim();
if(!bl||bl.startsWith('#'))return;
traceOneLine(bl,lineNum+bi2+1,vars,outputs,callStack,addStep,evalSimple,splitArgs);
});
});
addStep(lineNum,`For-loop complete — ${iterVals.length} iterations done`,'loop','');
}
continue;
}
if(line.match(/^while\s+/)){
const m=line.match(/^while\s+(.+):/);
const cond=m?m[1]:'...';
const bi=indent+4;
const bodyLines=[];
while(i<lineArr.length&&(lineArr[i].trim()===''||getIndent(lineArr[i])>=bi)){bodyLines.push(lineArr[i]);i++;}
let guard=0,MAX=30;
addStep(lineNum,`Start while-loop: "${cond}"`,'loop','Runs as long as condition is True');
while(guard<MAX){
let cv=false;
try{
const safe=cond.replace(/\b([a-zA-Z_]\w*)\b/g,m2=>{
if(vars[m2]){const v=vars[m2].value;return typeof v==='string'?JSON.stringify(v):v}
return m2==='True'?'true':m2==='False'?'false':m2;
}).replace(/\band\b/g,'&&').replace(/\bor\b/g,'||').replace(/\bnot\b/g,'!').replace(/==/g,'===').replace(/!=/g,'!==');
// eslint-disable-next-line no-new-func
cv=Function('"use strict";return ('+safe+')')();
}catch{cv=false;}
addStep(lineNum,`While: "${cond}" is ${cv?'True ✓':'False ✗'}`,'condition','');
if(!cv)break;
bodyLines.forEach((braw,bi2)=>{
const bl=braw.trim();
if(!bl||bl.startsWith('#'))return;
traceOneLine(bl,lineNum+bi2+1,vars,outputs,callStack,addStep,evalSimple,splitArgs);
});
guard++;
}
addStep(lineNum,'While-loop finished','loop','');
continue;
}
if(line.match(/^(if|elif)\s+/)){
const m=line.match(/^(if|elif)\s+(.+):/);
const cond=m?m[2]:'';
let cv=false;
try{
const safe=cond.replace(/\b([a-zA-Z_]\w*)\b/g,m2=>{
if(vars[m2]){const v=vars[m2].value;return typeof v==='string'?JSON.stringify(v):v}
return m2==='True'?'true':m2==='False'?'false':m2;
}).replace(/\band\b/g,'&&').replace(/\bor\b/g,'||').replace(/\bnot\b/g,'!').replace(/==/g,'===').replace(/!=/g,'!==');
// eslint-disable-next-line no-new-func
cv=Function('"use strict";return ('+safe+')')();
}catch{cv=false;}
addStep(lineNum,`Check: "${cond}" → ${cv?'True ✓':'False ✗'}`,'condition',cv?'This branch will execute':'This branch is skipped');
const bi=indent+4;
const bodyLines=[];
while(i<lineArr.length&&(lineArr[i].trim()===''||getIndent(lineArr[i])>=bi)){bodyLines.push(lineArr[i]);i++;}
if(cv)bodyLines.forEach((braw,bi2)=>{
const bl=braw.trim();if(!bl||bl.startsWith('#'))return;
traceOneLine(bl,lineNum+bi2+1,vars,outputs,callStack,addStep,evalSimple,splitArgs);
});
continue;
}
if(line==='else:'){
addStep(lineNum,'Else branch','condition','');
const bi=indent+4;
while(i<lineArr.length&&(lineArr[i].trim()===''||getIndent(lineArr[i])>=bi))i++;
continue;
}
traceOneLine(line,lineNum,vars,outputs,callStack,addStep,evalSimple,splitArgs);
}
}
traceBlock(lines,0);
return{steps,outputs};
}
function traceOneLine(line,lineNum,vars,outputs,callStack,addStep,evalSimple,splitArgs){
// print
const pM=line.match(/^print\s*\((.+)\)$/);
if(pM){
let val;try{val=evalSimple(pM[1],vars);}catch{val={value:pM[1],type:'str'};}
const out=val.value!==null&&val.value!==undefined?String(val.value):pM[1];
const s=addStep(lineNum,`Print → ${out}`,'print','print() sends output to the console');
outputs.push(out);
if(s&&s.length)s[s.length-1].output=out;
// patch last step
return;
}
// augmented
const augM=line.match(/^(\w+)\s*(\+=|-=|\*=|\/=|\/\/=|%=|\*\*=)\s*(.+)$/);
if(augM){
const[,vn,op,rhs]=augM;
const rv=evalSimple(rhs,vars);
const cur2=vars[vn]?vars[vn].value:0;
let nv;
try{
const opMap={'+=':'+','-=':'-','*=':'*','/=':'/','//=':'/','^=':'^','%=':'%','**=':'**'};
const l2=typeof cur2==='string'?JSON.stringify(cur2):cur2;
const r2=typeof rv.value==='string'?JSON.stringify(rv.value):rv.value;
if(op==='//=')nv=Math.floor(l2/r2);
else if(op==='**=')nv=Math.pow(l2,r2);
// eslint-disable-next-line no-new-func
else nv=Function('"use strict";return ('+l2+opMap[op]+r2+')')();
}catch{nv=rv.value;}
const type=typeof nv==='number'?(Number.isInteger(nv)?'int':'float'):typeof nv;
vars[vn]={value:nv,type};
addStep(lineNum,`${vn} ${op} ${rhs} → ${nv}`,'assign',`Was ${cur2}, now ${nv}`);
return;
}
// swap / multi-assign
const swapM=line.match(/^(\w+)\s*,\s*(\w+)\s*=\s*(.+),\s*(.+)$/);
if(swapM){
const[,v1,v2,e1,e2]=swapM;
const r1=evalSimple(e1,vars),r2=evalSimple(e2,vars);
vars[v1]=r1;vars[v2]=r2;
addStep(lineNum,`Swap: ${v1}=${r1.value}, ${v2}=${r2.value}`,'assign','Python evaluates right-hand side before assigning');
return;
}
// list index assign
const idxM=line.match(/^(\w+)\s*\[(.+)\]\s*=\s*(.+)$/);
if(idxM){
const[,arr,idxE,valE]=idxM;
const idx=Math.round(Number(evalSimple(idxE,vars).value));
const val=evalSimple(valE,vars);
if(vars[arr]&&Array.isArray(vars[arr].value))vars[arr].value[idx]=val.value;
addStep(lineNum,`${arr}[${idx}] = ${val.value}`,'assign',`Updating index ${idx} in list`);
return;
}
// assignment
const assignM=line.match(/^(\w+)\s*=\s*(.+)$/);
if(assignM){
const[,vn,expr]=assignM;
const val=evalSimple(expr,vars);
const old=vars[vn];
vars[vn]=val;
addStep(lineNum,old?`Update ${vn}: ${JSON.stringify(old.value)} → ${JSON.stringify(val.value)}`:`Create ${vn} = ${JSON.stringify(val.value)}`,'assign',old?'':'New variable created in memory');
return;
}
// return
if(line.startsWith('return')){
const expr=line.slice(6).trim();
const val=expr?evalSimple(expr,vars):{value:null,type:'NoneType'};
addStep(lineNum,`Return ${expr?expr+' ('+JSON.stringify(val.value)+')':'None'}`,'return','Exits function and passes value back to caller');
return;
}
// function call
const callM=line.match(/^(\w+)\s*\((.*)?\)$/);
if(callM){
addStep(lineNum,`Call: ${callM[1]}(${callM[2]||''})`,'call','');
return;
}
addStep(lineNum,`Execute: ${line.slice(0,50)}`,'other','');
}
// Fix print output capture
const _origAddStep_holder={fn:null};
// ─── JS Tracer ───────────────────────────────────────────────────────
function traceJS(code){
const lines=code.split('\n');
const steps=[];const vars={};const outputs=[];
function addStep(ln,desc,type,note){steps.push({line:ln,description:desc,type,variables:JSON.parse(JSON.stringify(vars)),output:'',callStack:[],note:note||''});}
lines.forEach((raw,idx)=>{
const line=raw.trim();const ln=idx+1;
if(!line||line.startsWith('//')||line==='{'||line==='}')return;
const logM=line.match(/console\.log\((.+)\)/);
if(logM){outputs.push(logM[1]);steps.push({line:ln,description:`Log: ${logM[1]}`,type:'print',variables:JSON.parse(JSON.stringify(vars)),output:logM[1],callStack:[],note:''});return;}
const declM=line.match(/^(let|const|var)\s+(\w+)\s*=\s*(.+?);?$/);
if(declM){
const[,kw,name,expr]=declM;
let val=expr.replace(/;$/,'');
const n=Number(val);if(!isNaN(n)&&val!=='')val=n;
else if(val.startsWith('['))try{val=JSON.parse(val.replace(/'/g,'"'))}catch{}
vars[name]={value:val,type:kw==='const'?'const':typeof val};
addStep(ln,`Declare ${kw} ${name} = ${JSON.stringify(val)}`,'assign',kw==='const'?'const cannot be reassigned later':'');return;
}
const augM=line.match(/^(\w+)\s*(\+=|-=|\*=|\/=|%=|\+\+|--)\s*(.+)?;?$/);
if(augM){
const[,vn,op]=augM;
const cur2=vars[vn]?vars[vn].value:0;
let nv=op==='++'?cur2+1:op==='--'?cur2-1:cur2;
if(vars[vn])vars[vn].value=nv;
addStep(ln,`${vn} ${op} → ${nv}`,'assign','');return;
}
if(line.match(/^(function\s+\w+|const\s+\w+\s*=\s*(function|\()|\w+\s*=\s*function)/)){
const m=line.match(/function\s+(\w+)|const\s+(\w+)/);
addStep(ln,`Define function "${m?m[1]||m[2]:'fn'}"`,'define','Runs only when called');return;
}
if(line.match(/^for\s*\(/)){addStep(ln,'For loop iteration','loop','');return;}
if(line.match(/^while\s*\(/)){addStep(ln,'While condition check','loop','');return;}
if(line.match(/^if\s*\(/)){addStep(ln,`Condition: ${line.slice(0,40)}`,'condition','');return;}
if(line.match(/^return\s/)){addStep(ln,`Return: ${line.slice(7,40)}`,'return','');return;}
addStep(ln,`Execute: ${line.slice(0,50)}`,'other','');
});
return{steps,outputs};
}
// ─── Generic (Java/C) tracer ─────────────────────────────────────────
function traceGeneric(code){
const lines=code.split('\n');const steps=[];const vars={};const outputs=[];
function addStep(ln,desc,type,note){steps.push({line:ln,description:desc,type,variables:JSON.parse(JSON.stringify(vars)),output:'',callStack:[],note:note||''});}
lines.forEach((raw,idx)=>{
const line=raw.trim();const ln=idx+1;
if(!line||line.startsWith('//')||line==='{'||line==='}')return;
if(line.match(/(System\.out\.print|printf|cout<<|puts\s*\()/)){
outputs.push(line.slice(0,40));
steps.push({line:ln,description:'Output to console',type:'print',variables:JSON.parse(JSON.stringify(vars)),output:line.slice(0,40),callStack:[],note:''});return;
}
const declM=line.match(/^(int|float|double|long|char|String|bool|boolean|auto)\s+(\w+)\s*=\s*(.+?);?$/);
if(declM){
const[,type2,name,val]=declM;
vars[name]={value:val.replace(/;$/,''),type:type2};
addStep(ln,`Declare ${type2} ${name} = ${val.replace(/;$/,'')}`,'assign','');return;
}
if(line.match(/^for\s*\(/)){addStep(ln,'For loop','loop','');return;}
if(line.match(/^while\s*\(/)){addStep(ln,'While loop','loop','');return;}
if(line.match(/^if\s*\(/)){addStep(ln,`Condition: ${line.slice(0,40)}`,'condition','');return;}
if(line.match(/^return\s/)){addStep(ln,`Return: ${line.slice(7)}`,'return','');return;}
addStep(ln,`Execute: ${line.slice(0,50)}`,'other','');
});
return{steps,outputs};
}
// ─── Pseudocode tracer ───────────────────────────────────────────────
function tracePseudo(code){
const lines=code.split('\n');const steps=[];const vars={};
function addStep(ln,desc,type,note){steps.push({line:ln,description:desc,type,variables:JSON.parse(JSON.stringify(vars)),output:'',callStack:[],note:note||''});}
lines.forEach((raw,idx)=>{
const line=raw.trim();const ln=idx+1;
if(!line)return;
if(/^(SET|LET)\s+(\w+)\s*(=|TO)\s*(.+)/i.test(line)){
const m=line.match(/(?:SET|LET)\s+(\w+)\s*(?:=|TO)\s*(.+)/i);
if(m)vars[m[1]]={value:m[2],type:'variable'};
addStep(ln,`Assign: ${line}`,'assign','');
} else if(/^(PRINT|OUTPUT|DISPLAY|WRITE)/i.test(line)){
addStep(ln,`Output: ${line}`,'print','');
} else if(/^IF\s/i.test(line)){addStep(ln,`Condition: ${line}`,'condition','');}
else if(/^(FOR|WHILE|REPEAT|LOOP)/i.test(line)){addStep(ln,`Loop: ${line}`,'loop','');}
else {addStep(ln,line.slice(0,60),'other','');}
});
return{steps,outputs:[]};
}
// ═══════════════════════════════════════════════════════════════════════
// MAIN ENTRY
// ═══════════════════════════════════════════════════════════════════════
function startViz(){
const code=codeEl.value.trim();
if(!code){setStatus('err','No code found — paste your code on the left!');return;}
const lang=document.getElementById('lang').value;
stopPlay();
let result;
try{
if(lang==='python')result=tracePython(code);
else if(lang==='javascript')result=traceJS(code);
else if(lang==='pseudo')result=tracePseudo(code);
else result=traceGeneric(code);
}catch(e){setStatus('err','Parse error: '+e.message);return;}
steps=result.steps||[];
allOutputs=result.outputs||[];
if(!steps.length){setStatus('err','No executable lines found. Check your code.');return;}
// patch outputs into steps
let oi=0;
steps.forEach(s=>{if(s.type==='print'&&oi<allOutputs.length)s.output=allOutputs[oi++];});
cur=-1;prevVars={};
updateLineNums();clearHighlights();
document.getElementById('progFill').style.width='0%';
document.getElementById('badge').innerHTML=`<b>0</b> / ${steps.length}`;
document.getElementById('btnN').disabled=false;
document.getElementById('btnP').disabled=true;
document.getElementById('btnPlay').disabled=false;
document.getElementById('btnBP').disabled=breakpoints.size===0;
const sc=document.getElementById('scrubber');
sc.max=steps.length-1;sc.value=0;
document.getElementById('timeline').classList.add('show');
setStatus('run',`${steps.length} steps traced — click Next ▶ or Space to auto-play`);
showEmpty('Trace','Ready! Press Next ▶ to step through your code line by line.');
switchTab(activeTab);
}
// ═══════════════════════════════════════════════════════════════════════
// NAVIGATION
// ═══════════════════════════════════════════════════════════════════════
function nextStep(){if(cur<steps.length-1){cur++;render();}}
function prevStep(){if(cur>0){cur--;rebuildPrev();render();}}
function scrubTo(val){cur=parseInt(val);rebuildPrev();render();}
function rebuildPrev(){
prevVars={};
for(let i=0;i<cur;i++){const s=steps[i];if(s.variables)Object.assign(prevVars,JSON.parse(JSON.stringify(s.variables)));}
}
function jumpToBreakpoint(){
if(!breakpoints.size)return;
for(let i=cur+1;i<steps.length;i++){
if(breakpoints.has(steps[i].line)){cur=i;rebuildPrev();render();setStatus('p-bp','Hit breakpoint at line '+steps[i].line);return;}
}
setStatus('run','No more breakpoints after current position');
}
function togglePlay(){
if(isPlaying)stopPlay();
else startPlay();
}
function startPlay(){
if(cur>=steps.length-1){cur=-1;prevVars={};}
isPlaying=true;
document.getElementById('btnPlay').textContent='⏸';
const spd=parseInt(document.getElementById('speedSlider').value);
const delay=Math.round(1200/spd);
function tick(){
if(!isPlaying||cur>=steps.length-1){stopPlay();return;}
cur++;render();
// pause on breakpoint
if(breakpoints.has(steps[cur].line)){stopPlay();setStatus('p-bp','Paused at breakpoint: line '+steps[cur].line);return;}
playTimer=setTimeout(tick,delay);
}
tick();
}
function stopPlay(){
isPlaying=false;
clearTimeout(playTimer);
document.getElementById('btnPlay').textContent='⏵';
}
document.getElementById('speedSlider').addEventListener('input',function(){
document.getElementById('speedLabel').textContent=this.value+'x';
if(isPlaying){stopPlay();startPlay();}
});
// ═══════════════════════════════════════════════════════════════════════
// RENDER
// ═══════════════════════════════════════════════════════════════════════
function render(){
const s=steps[cur];const total=steps.length;
// line highlight
clearHighlights();
if(s.line){
const hl=document.getElementById(`hl${s.line}`);
const ln=document.getElementById(`ln${s.line}`);
if(hl)hl.classList.add('active');
if(ln)ln.classList.add('active');
codeEl.scrollTop=Math.max(0,(s.line-5)*20);
}
// controls
document.getElementById('badge').innerHTML=`<b>${cur+1}</b> / ${total}`;
document.getElementById('btnP').disabled=cur<=0;
document.getElementById('btnN').disabled=cur>=total-1;
document.getElementById('progFill').style.width=`${((cur+1)/total)*100}%`;
document.getElementById('scrubber').value=cur;
document.getElementById('scrubLabel').textContent=cur+1;
document.getElementById('sline').textContent=`Line ${s.line||'?'}`;
setStatus(cur>=total-1?'done':'run',cur>=total-1?'Execution complete ✓':`Line ${s.line}: ${s.description}`);
prevVars=cur>0?JSON.parse(JSON.stringify(steps[cur-1].variables||{})):{};
renderTraceTab(s);
renderVarsTab(s);
renderDSTab(s);
renderStackTab(s);
renderOutputTab();
}
// ─── TRACE TAB ────────────────────────────────────────────────────────
function renderTraceTab(s){
const lineCode=(codeEl.value.split('\n')[s.line-1]||'').trim();
let html='';
html+=vb('step',`${typeIcon(s.type)} Step ${cur+1} — ${s.type.toUpperCase()}`,`
<div class="snippet">${esc(lineCode)}</div>
<div class="desc">${esc(s.description)}</div>
${s.note?`<div class="tip">💡 ${esc(s.note)}</div>`:''}
`);
if(s.type==='loop')html+=vb('loop','↻ Loop Iteration',`<div class="desc">Watch variables below update on each iteration.</div>`);
if(s.type==='condition')html+=vb('cond','? Condition Evaluated',`<div class="desc">${esc(s.description)}</div>`);
if(s.type==='call'||s.type==='return'){
const frames=s.callStack&&s.callStack.length?s.callStack:['(global scope)'];
html+=vb('call','≡ Call Stack',frames.map((f,i)=>`<div class="stack-frame"><div class="sf-name">${esc(f)}</div><div class="sf-args">${i===0?'← current':'caller'} · line ${s.line}</div></div>`).join(''));
}
// mini vars inline
const ve=Object.entries(s.variables||{});
if(ve.length){
const rows=ve.map(([name,info])=>{
const wasVal=prevVars[name]?JSON.stringify(prevVars[name].value):undefined;
const isNew=wasVal===undefined||wasVal!==JSON.stringify(info.value);
return `<tr><td class="vn">${esc(name)}</td><td class="vt">${esc(info.type||'?')}</td><td class="vv${isNew?' changed':''}">${fmtVal(info.value)}</td></tr>`;
}).join('');
html+=vb('vars','□ Variables at this step',`<table class="vtable"><tr><th>Name</th><th>Type</th><th>Value</th></tr>${rows}</table>`);
}
// output so far
const outs=steps.slice(0,cur+1).map(x=>x.output).filter(Boolean);
if(outs.length)html+=vb('out','▸ Console Output',outs.map(o=>`<div class="out-line">› ${esc(o)}</div>`).join(''));
setTabContent('trace',html);
}
// ─── VARS TAB ────────────────────────────────────────────────────────
function renderVarsTab(s){
const ve=Object.entries(s.variables||{});
if(!ve.length){setTabContent('vars','<div class="empty"><div style="opacity:.3;font-size:1.5rem">□</div><div>No variables in scope yet</div></div>');return;}
const rows=ve.map(([name,info])=>{
const wasVal=prevVars[name]?JSON.stringify(prevVars[name].value):undefined;
const isNew=wasVal===undefined||wasVal!==JSON.stringify(info.value);
return `<tr>
<td class="vn" style="padding:6px 0">${esc(name)}</td>
<td class="vt" style="padding:6px 0">${esc(info.type||'?')}</td>
<td class="vv${isNew?' changed':''}" style="padding:6px 0">${fmtValFull(info.value)}</td>
</tr>`;
}).join('');
setTabContent('vars',`<div class="vb vb-vars"><div class="vb-head">□ All Variables</div><div class="vb-body"><table class="vtable" style="width:100%"><tr><th>Name</th><th>Type</th><th>Value</th></tr>${rows}</table></div></div>`);
}
// ─── DS TAB ──────────────────────────────────────────────────────────
function renderDSTab(s){
const vars2=s.variables||{};
let html='';
let found=false;
Object.entries(vars2).forEach(([name,info])=>{
if(Array.isArray(info.value)&&info.value.length>0){
found=true;
const isStack=name.toLowerCase().includes('stack');
const isQueue=name.toLowerCase().includes('queue');
if(isStack){
html+=`<div class="vb vb-ds"><div class="vb-head">⬡ Stack: ${esc(name)}</div><div class="vb-body">`;
html+=`<div class="ds-label">Top ↑</div><div class="ds-stack">`;
[...info.value].reverse().forEach((v,i)=>{
html+=`<div class="ds-stack-cell${i===0?' top':''}">${esc(String(v))}</div>`;
});
if(i===0)html+=`<div class="ds-stack-label">← top</div>`;
html+=`</div></div></div>`;
} else {
html+=`<div class="vb vb-ds"><div class="vb-head">□ Array/List: ${esc(name)}</div><div class="vb-body">`;
html+=`<div class="ds-arr">`;
info.value.forEach((v,i2)=>{
html+=`<div class="ds-arr-cell"><div class="arr-idx">${i2}</div><div class="ds-arr-box">${esc(String(v))}</div></div>`;
});
html+=`</div>`;
html+=`<div style="margin-top:8px;font-size:.68rem;color:var(--text3);font-family:'JetBrains Mono',monospace">length = ${info.value.length}</div>`;
html+=`</div></div>`;
}
}