ruchy 3.75.0

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
Documentation
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ruchy Notebook - Professional Computing Environment</title>
    
    <!-- CodeMirror for syntax highlighting -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/theme/material-darker.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/theme/default.min.css">
    
    <!-- Marked for Markdown rendering -->
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    
    <!-- KaTeX for LaTeX math -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
    <script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
    
    <style>
        /* CSS Variables for theming */
        :root {
            --background-color: #ffffff;
            --text-color: #24292e;
            --border-color: #e1e4e8;
            --cell-background: #ffffff;
            --toolbar-background: #f6f8fa;
            --code-background: #f6f8fa;
            --hover-background: #f3f4f6;
            --accent-color: #0969da;
            --success-color: #1a7f37;
            --error-color: #cf222e;
            --warning-color: #bf8700;
            --font-mono: 'SF Mono', Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;
            --font-sans: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
        }
        
        [data-theme="dark"] {
            --background-color: #0d1117;
            --text-color: #c9d1d9;
            --border-color: #30363d;
            --cell-background: #161b22;
            --toolbar-background: #010409;
            --code-background: #161b22;
            --hover-background: #1f2428;
            --accent-color: #58a6ff;
            --success-color: #3fb950;
            --error-color: #f85149;
            --warning-color: #d29922;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: var(--font-sans);
            background-color: var(--background-color);
            color: var(--text-color);
            line-height: 1.5;
            transition: background-color 0.3s, color 0.3s;
        }
        
        /* Toolbar */
        .notebook-toolbar {
            position: sticky;
            top: 0;
            z-index: 100;
            background: var(--toolbar-background);
            border-bottom: 1px solid var(--border-color);
            padding: 8px 16px;
            display: flex;
            align-items: center;
            gap: 16px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }
        
        .toolbar-group {
            display: flex;
            gap: 4px;
            align-items: center;
        }
        
        .toolbar-separator {
            width: 1px;
            height: 24px;
            background: var(--border-color);
            margin: 0 8px;
        }
        
        .btn {
            padding: 6px 12px;
            border: 1px solid var(--border-color);
            background: var(--cell-background);
            color: var(--text-color);
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            gap: 4px;
        }
        
        .btn:hover {
            background: var(--hover-background);
            border-color: var(--accent-color);
        }
        
        .btn:active {
            transform: scale(0.98);
        }
        
        .btn-primary {
            background: var(--accent-color);
            color: white;
            border-color: var(--accent-color);
        }
        
        .btn-primary:hover {
            background: var(--accent-color);
            opacity: 0.9;
        }
        
        .theme-toggle {
            margin-left: auto;
        }
        
        /* Notebook Container */
        .notebook-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 24px;
        }
        
        .cell-list {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        
        /* Cell Structure */
        .cell {
            display: flex;
            position: relative;
            border: 1px solid transparent;
            border-radius: 8px;
            transition: all 0.2s;
        }
        
        .cell:hover {
            border-color: var(--border-color);
        }
        
        .cell.selected {
            border-color: var(--accent-color);
            box-shadow: 0 0 0 1px var(--accent-color);
        }
        
        .cell.cell-running .execution-count {
            animation: pulse 1s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        /* Cell Prompt Area */
        .cell-prompt {
            width: 80px;
            padding: 8px;
            text-align: right;
            font-family: var(--font-mono);
            font-size: 12px;
            color: var(--text-color);
            opacity: 0.6;
            user-select: none;
        }
        
        .execution-count {
            display: inline-block;
        }
        
        .cell-running .execution-count::before {
            content: '[*]: ';
        }
        
        .cell-completed .execution-count::before {
            content: '[';
        }
        
        .cell-completed .execution-count::after {
            content: ']: ';
        }
        
        /* Cell Content Area */
        .cell-content {
            flex: 1;
            min-width: 0;
        }
        
        .cell-toolbar {
            display: flex;
            gap: 4px;
            padding: 4px;
            opacity: 0;
            transition: opacity 0.2s;
            position: absolute;
            right: 8px;
            top: 8px;
            z-index: 10;
        }
        
        .cell:hover .cell-toolbar {
            opacity: 1;
        }
        
        .cell-toolbar button {
            padding: 4px 8px;
            font-size: 12px;
            border: 1px solid var(--border-color);
            background: var(--cell-background);
            border-radius: 4px;
            cursor: pointer;
        }
        
        .cell-toolbar button:hover {
            background: var(--hover-background);
        }
        
        /* Code Cell */
        .cell-type-code .cell-input {
            background: var(--code-background);
            border: 1px solid var(--border-color);
            border-radius: 6px;
            overflow: hidden;
        }
        
        .CodeMirror {
            height: auto;
            background: transparent;
            font-family: var(--font-mono);
            font-size: 14px;
        }
        
        .CodeMirror-lines {
            padding: 8px 0;
        }
        
        .syntax-highlight {
            background: var(--code-background);
        }
        
        /* Markdown Cell */
        .cell-type-markdown .markdown-preview {
            padding: 12px;
            cursor: pointer;
        }
        
        .cell-type-markdown .markdown-preview h1 { font-size: 2em; margin: 0.67em 0; }
        .cell-type-markdown .markdown-preview h2 { font-size: 1.5em; margin: 0.75em 0; }
        .cell-type-markdown .markdown-preview h3 { font-size: 1.17em; margin: 0.83em 0; }
        .cell-type-markdown .markdown-preview code {
            background: var(--code-background);
            padding: 2px 4px;
            border-radius: 3px;
            font-family: var(--font-mono);
            font-size: 0.9em;
        }
        
        .cell-type-markdown .markdown-preview pre {
            background: var(--code-background);
            padding: 12px;
            border-radius: 6px;
            overflow-x: auto;
        }
        
        .cell-type-markdown.editing .markdown-preview {
            display: none;
        }
        
        .cell-type-markdown.editing .markdown-edit {
            display: block;
        }
        
        .markdown-edit {
            display: none;
            width: 100%;
            min-height: 100px;
            padding: 12px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            font-family: var(--font-mono);
            font-size: 14px;
            background: var(--code-background);
            color: var(--text-color);
            resize: vertical;
        }
        
        /* Output Area */
        .cell-output {
            margin-top: 8px;
            padding: 12px;
            background: var(--cell-background);
            border: 1px solid var(--border-color);
            border-radius: 6px;
            font-family: var(--font-mono);
            font-size: 14px;
            white-space: pre-wrap;
            word-break: break-all;
            max-height: 400px;
            overflow-y: auto;
        }
        
        .output-text {
            color: var(--text-color);
        }
        
        .error-output {
            color: var(--error-color);
            background: rgba(248, 81, 73, 0.1);
            padding: 12px;
            border-radius: 6px;
            border-left: 3px solid var(--error-color);
        }
        
        .traceback {
            font-family: var(--font-mono);
            font-size: 12px;
            line-height: 1.4;
        }
        
        /* DataFrame Output */
        .dataframe-output {
            overflow-x: auto;
        }
        
        .table-wrapper {
            display: inline-block;
            max-width: 100%;
        }
        
        .dataframe-output table {
            border-collapse: collapse;
            font-size: 13px;
        }
        
        .dataframe-output th,
        .dataframe-output td {
            padding: 6px 12px;
            border: 1px solid var(--border-color);
            text-align: left;
        }
        
        .dataframe-output th {
            background: var(--toolbar-background);
            font-weight: 600;
        }
        
        .dataframe-output tr:hover {
            background: var(--hover-background);
        }
        
        /* Cell Status Indicators */
        .cell-status {
            position: absolute;
            left: 4px;
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 40px;
            border-radius: 2px;
            background: transparent;
            transition: background 0.3s;
        }
        
        .cell-running .cell-status {
            background: var(--warning-color);
        }
        
        .cell-queued .cell-status {
            background: var(--border-color);
        }
        
        .cell-completed .cell-status {
            background: var(--success-color);
        }
        
        .execution-progress {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 2px;
            background: var(--accent-color);
            transform-origin: left;
            animation: progress 2s infinite;
            display: none;
        }
        
        .cell-running .execution-progress {
            display: block;
        }
        
        @keyframes progress {
            0% { transform: scaleX(0); }
            50% { transform: scaleX(1); }
            100% { transform: scaleX(0); }
        }
        
        /* Keyboard Shortcuts Modal */
        .shortcuts-modal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: var(--cell-background);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            padding: 24px;
            z-index: 1000;
            max-width: 500px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
        }
        
        .shortcuts-modal h3 {
            margin-bottom: 16px;
        }
        
        .shortcut-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid var(--border-color);
        }
        
        .shortcut-key {
            background: var(--code-background);
            padding: 2px 6px;
            border-radius: 4px;
            font-family: var(--font-mono);
            font-size: 12px;
        }
        
        /* Responsive Design */
        @media (max-width: 768px) {
            .notebook-container {
                padding: 12px;
            }
            
            .cell-prompt {
                width: 60px;
                font-size: 11px;
            }
            
            .toolbar-group {
                flex-wrap: wrap;
            }
        }
        
        /* Accessibility */
        .sr-only, .visually-hidden {
            position: absolute;
            width: 1px;
            height: 1px;
            padding: 0;
            margin: -1px;
            overflow: hidden;
            clip: rect(0,0,0,0);
            white-space: nowrap;
            border: 0;
        }
        
        /* Print Styles */
        @media print {
            .notebook-toolbar,
            .cell-toolbar,
            .theme-toggle {
                display: none !important;
            }
            
            .cell {
                page-break-inside: avoid;
            }
        }
    </style>
</head>
<body>
    <!-- Toolbar -->
    <div class="notebook-toolbar" role="toolbar" aria-label="Notebook controls">
        <div class="toolbar-group">
            <button class="btn btn-primary" id="btn-run-all" title="Run All Cells">
                â–¶ Run All
            </button>
            <button class="btn" id="btn-interrupt" title="Interrupt Execution">
                ⬛ Interrupt
            </button>
            <button class="btn" id="btn-restart-kernel" title="Restart Kernel">
                🔄 Restart
            </button>
        </div>
        
        <div class="toolbar-separator"></div>
        
        <div class="toolbar-group">
            <button class="btn" id="btn-save" title="Save Notebook">
                💾 Save
            </button>
            <button class="btn add-cell-button" id="btn-add-cell" title="Add Cell Below">
                âž• Add Cell
            </button>
        </div>
        
        <div class="toolbar-separator"></div>
        
        <div class="toolbar-group">
            <select id="cell-type-selector" class="btn" aria-label="Cell type">
                <option value="code">Code</option>
                <option value="markdown">Markdown</option>
                <option value="raw">Raw</option>
            </select>
        </div>
        
        <button class="btn theme-toggle" id="theme-toggle" title="Toggle Theme">
            🌓 Theme
        </button>
    </div>
    
    <!-- Notebook Container -->
    <div class="notebook-container">
        <div class="cell-list" id="notebook-cells" role="main">
            <!-- Initial cell -->
            <div class="cell cell-type-code selected" data-cell-id="cell-1" data-execution-count="0">
                <div class="cell-status"></div>
                <div class="cell-prompt">
                    <span class="execution-count" id="execution-number">1</span>
                </div>
                <div class="cell-content">
                    <div class="cell-toolbar">
                        <button class="execute-button" onclick="runCell('cell-1')" title="Run Cell">â–¶</button>
                        <button class="delete-cell-button" onclick="deleteCell('cell-1')" id="btn-delete-cell" title="Delete Cell">🗑</button>
                        <button class="move-up-button" onclick="moveUp('cell-1')" id="btn-move-up" title="Move Up">↑</button>
                        <button class="move-down-button" onclick="moveDown('cell-1')" id="btn-move-down" title="Move Down">↓</button>
                    </div>
                    <div class="cell-input">
                        <textarea id="editor-cell-1" class="code-editor cell-input">// Welcome to Ruchy Notebook
// Press Shift+Enter to run this cell

println("Hello, Ruchy!")
2 + 3</textarea>
                    </div>
                    <div class="cell-output" id="output-cell-1" style="display: none;"></div>
                </div>
                <div class="execution-progress"></div>
            </div>
        </div>
    </div>
    
    <!-- Keyboard Shortcuts Modal -->
    <div class="shortcuts-modal" id="shortcuts-modal" role="dialog" aria-label="Keyboard shortcuts">
        <h3>Keyboard Shortcuts</h3>
        <div class="shortcut-item">
            <span>Run cell and select below</span>
            <span class="shortcut-key">Shift+Enter</span>
        </div>
        <div class="shortcut-item">
            <span>Run cell</span>
            <span class="shortcut-key">Ctrl+Enter</span>
        </div>
        <div class="shortcut-item">
            <span>Run cell and insert below</span>
            <span class="shortcut-key">Alt+Enter</span>
        </div>
        <div class="shortcut-item">
            <span>Command mode</span>
            <span class="shortcut-key">Esc</span>
        </div>
        <div class="shortcut-item">
            <span>Edit mode</span>
            <span class="shortcut-key">Enter</span>
        </div>
    </div>
    
    <!-- CodeMirror -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/javascript/javascript.min.js"></script>
    
    <script>
        // State management
        let cells = new Map();
        let currentCellId = 'cell-1';
        let executionCount = 1;
        let editorInstances = new Map();
        let cellMode = 'edit'; // 'edit' or 'command'
        
        // Initialize CodeMirror for syntax highlighting
        function initializeEditor(cellId) {
            const textarea = document.getElementById(`editor-${cellId}`);
            if (!textarea || editorInstances.has(cellId)) return;
            
            const editor = CodeMirror.fromTextArea(textarea, {
                mode: 'javascript',
                theme: document.body.dataset.theme === 'dark' ? 'material-darker' : 'default',
                lineNumbers: true,
                lineWrapping: true,
                indentUnit: 4,
                indentWithTabs: false,
                extraKeys: {
                    'Shift-Enter': () => runCellAndSelectBelow(cellId),
                    'Ctrl-Enter': () => runCell(cellId),
                    'Alt-Enter': () => runCellAndInsertBelow(cellId),
                    'Esc': () => commandMode(),
                    'Tab': 'indentMore'
                }
            });
            
            editorInstances.set(cellId, editor);
            return editor;
        }
        
        // Cell execution
        async function runCell(cellId) {
            const cell = document.querySelector(`[data-cell-id="${cellId}"]`);
            if (!cell) return;
            
            const editor = editorInstances.get(cellId);
            const code = editor ? editor.getValue() : document.getElementById(`editor-${cellId}`).value;
            
            // Update UI to show running state
            cell.classList.add('cell-running');
            cell.classList.remove('cell-completed', 'cell-queued');
            
            // Update execution count
            const execCount = ++executionCount;
            cell.dataset.executionCount = execCount;
            cell.querySelector('.execution-count').textContent = execCount;
            
            try {
                const response = await fetch('/api/execute', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        source: code  // Backend expects 'source' not 'code'
                    })
                });
                
                const result = await response.json();
                displayOutput(cellId, result);
                
                cell.classList.remove('cell-running');
                cell.classList.add('cell-completed');
            } catch (error) {
                displayError(cellId, error.message);
                cell.classList.remove('cell-running');
                cell.classList.add('cell-completed');
            }
        }
        
        function displayOutput(cellId, result) {
            const outputDiv = document.getElementById(`output-${cellId}`);
            if (!outputDiv) return;
            
            outputDiv.style.display = 'block';
            
            if (result.success) {
                // Check for different output types
                if (result.dataframe) {
                    outputDiv.innerHTML = `<div class="dataframe-output">${formatDataFrame(result.dataframe)}</div>`;
                } else if (result.html) {
                    outputDiv.innerHTML = `<div class="output-html">${result.html}</div>`;
                } else if (result.image) {
                    outputDiv.innerHTML = `<img src="data:image/png;base64,${result.image}" />`;
                } else {
                    outputDiv.innerHTML = `<div class="output-text">${escapeHtml(result.result || '')}</div>`;
                }
            } else {
                outputDiv.innerHTML = `<div class="error-output cell-error"><div class="traceback">${escapeHtml(result.error || result.result || 'Unknown error')}</div></div>`;
            }
        }
        
        function displayError(cellId, error) {
            const outputDiv = document.getElementById(`output-${cellId}`);
            if (!outputDiv) return;
            
            outputDiv.style.display = 'block';
            outputDiv.innerHTML = `<div class="error-output cell-error"><div class="traceback">Error: ${escapeHtml(error)}</div></div>`;
        }
        
        function formatDataFrame(df) {
            // Format DataFrame as HTML table
            let html = '<div class="table-wrapper"><table>';
            
            // Header
            html += '<thead><tr>';
            for (const col of df.columns || []) {
                html += `<th>${escapeHtml(col)}</th>`;
            }
            html += '</tr></thead>';
            
            // Body
            html += '<tbody>';
            for (const row of df.rows || []) {
                html += '<tr>';
                for (const cell of row) {
                    html += `<td>${escapeHtml(String(cell))}</td>`;
                }
                html += '</tr>';
            }
            html += '</tbody></table></div>';
            
            return html;
        }
        
        // Cell manipulation
        function runCellAndSelectBelow(cellId) {
            runCell(cellId);
            selectNextCell(cellId);
        }
        
        function runCellAndInsertBelow(cellId) {
            runCell(cellId);
            addCellAfter(cellId);
        }
        
        function addCell() {
            const cellId = `cell-${Date.now()}`;
            const cellHtml = createCellHtml(cellId, 'code');
            
            document.getElementById('notebook-cells').insertAdjacentHTML('beforeend', cellHtml);
            initializeEditor(cellId);
            selectCell(cellId);
        }
        
        function addCellAfter(afterCellId) {
            const cellId = `cell-${Date.now()}`;
            const cellHtml = createCellHtml(cellId, 'code');
            
            const afterCell = document.querySelector(`[data-cell-id="${afterCellId}"]`);
            if (afterCell) {
                afterCell.insertAdjacentHTML('afterend', cellHtml);
                initializeEditor(cellId);
                selectCell(cellId);
            }
        }
        
        function createCellHtml(cellId, cellType) {
            return `
                <div class="cell cell-type-${cellType}" data-cell-id="${cellId}" data-execution-count="0">
                    <div class="cell-status"></div>
                    <div class="cell-prompt">
                        <span class="execution-count"></span>
                    </div>
                    <div class="cell-content">
                        <div class="cell-toolbar">
                            <button class="execute-button" onclick="runCell('${cellId}')" title="Run Cell">â–¶</button>
                            <button class="delete-cell-button" onclick="deleteCell('${cellId}')" title="Delete Cell">🗑</button>
                            <button class="move-up-button" onclick="moveUp('${cellId}')" title="Move Up">↑</button>
                            <button class="move-down-button" onclick="moveDown('${cellId}')" title="Move Down">↓</button>
                        </div>
                        <div class="cell-input">
                            <textarea id="editor-${cellId}" class="code-editor cell-input"></textarea>
                        </div>
                        <div class="cell-output" id="output-${cellId}" style="display: none;"></div>
                    </div>
                    <div class="execution-progress"></div>
                </div>
            `;
        }
        
        function deleteCell(cellId) {
            const cell = document.querySelector(`[data-cell-id="${cellId}"]`);
            if (cell && document.querySelectorAll('.cell').length > 1) {
                const editor = editorInstances.get(cellId);
                if (editor) {
                    editor.toTextArea();
                    editorInstances.delete(cellId);
                }
                cell.remove();
            }
        }
        
        function moveUp(cellId) {
            const cell = document.querySelector(`[data-cell-id="${cellId}"]`);
            if (cell && cell.previousElementSibling) {
                cell.parentNode.insertBefore(cell, cell.previousElementSibling);
            }
        }
        
        function moveDown(cellId) {
            const cell = document.querySelector(`[data-cell-id="${cellId}"]`);
            if (cell && cell.nextElementSibling) {
                cell.parentNode.insertBefore(cell.nextElementSibling, cell);
            }
        }
        
        function selectCell(cellId) {
            document.querySelectorAll('.cell').forEach(c => c.classList.remove('selected'));
            const cell = document.querySelector(`[data-cell-id="${cellId}"]`);
            if (cell) {
                cell.classList.add('selected');
                currentCellId = cellId;
                cell.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }
        }
        
        function selectNextCell(cellId) {
            const cell = document.querySelector(`[data-cell-id="${cellId}"]`);
            if (cell && cell.nextElementSibling) {
                const nextCellId = cell.nextElementSibling.dataset.cellId;
                selectCell(nextCellId);
            }
        }
        
        // Modes
        function commandMode() {
            cellMode = 'command';
            const editor = editorInstances.get(currentCellId);
            if (editor) {
                editor.getInputField().blur();
            }
        }
        
        function editMode() {
            cellMode = 'edit';
            const editor = editorInstances.get(currentCellId);
            if (editor) {
                editor.focus();
            }
        }
        
        // Theme management
        function toggleTheme() {
            const currentTheme = document.body.dataset.theme || 'light';
            const newTheme = currentTheme === 'light' ? 'dark' : 'light';
            document.body.dataset.theme = newTheme;
            localStorage.setItem('notebook-theme', newTheme);
            
            // Update CodeMirror theme
            editorInstances.forEach(editor => {
                editor.setOption('theme', newTheme === 'dark' ? 'material-darker' : 'default');
            });
        }
        
        // Run all cells
        async function runAllCells() {
            const cells = document.querySelectorAll('.cell-type-code');
            for (const cell of cells) {
                await runCell(cell.dataset.cellId);
                await new Promise(resolve => setTimeout(resolve, 100)); // Small delay between cells
            }
        }
        
        // Kernel management
        async function restartKernel() {
            try {
                const response = await fetch('/api/kernel/restart', { method: 'POST' });
                if (response.ok) {
                    console.log('Kernel restarted');
                    executionCount = 0;
                    // Clear all outputs
                    document.querySelectorAll('.cell-output').forEach(output => {
                        output.style.display = 'none';
                        output.innerHTML = '';
                    });
                }
            } catch (error) {
                console.error('Failed to restart kernel:', error);
            }
        }
        
        async function interruptKernel() {
            try {
                const response = await fetch('/api/kernel/interrupt', { method: 'POST' });
                if (response.ok) {
                    console.log('Kernel interrupted');
                    // Stop all running cells
                    document.querySelectorAll('.cell-running').forEach(cell => {
                        cell.classList.remove('cell-running');
                    });
                }
            } catch (error) {
                console.error('Failed to interrupt kernel:', error);
            }
        }
        
        // Utility functions
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        // Event listeners
        document.getElementById('btn-run-all').addEventListener('click', runAllCells);
        document.getElementById('btn-restart-kernel').addEventListener('click', restartKernel);
        document.getElementById('btn-interrupt').addEventListener('click', interruptKernel);
        document.getElementById('btn-save').addEventListener('click', () => {
            console.log('Save functionality to be implemented');
        });
        document.getElementById('btn-add-cell').addEventListener('click', addCell);
        document.getElementById('theme-toggle').addEventListener('click', toggleTheme);
        
        // Global keyboard shortcuts
        document.addEventListener('keydown', (e) => {
            if (cellMode === 'command') {
                switch(e.key) {
                    case 'Enter':
                        e.preventDefault();
                        editMode();
                        break;
                    case 'a':
                        e.preventDefault();
                        addCellAfter(currentCellId);
                        break;
                    case 'b':
                        e.preventDefault();
                        addCell();
                        break;
                    case 'd':
                        if (e.repeat) {
                            e.preventDefault();
                            deleteCell(currentCellId);
                        }
                        break;
                    case 'ArrowUp':
                        e.preventDefault();
                        const prevCell = document.querySelector(`[data-cell-id="${currentCellId}"]`)?.previousElementSibling;
                        if (prevCell) selectCell(prevCell.dataset.cellId);
                        break;
                    case 'ArrowDown':
                        e.preventDefault();
                        const nextCell = document.querySelector(`[data-cell-id="${currentCellId}"]`)?.nextElementSibling;
                        if (nextCell) selectCell(nextCell.dataset.cellId);
                        break;
                }
            }
            
            // Show shortcuts modal
            if (e.key === '?' && e.shiftKey) {
                const modal = document.getElementById('shortcuts-modal');
                modal.style.display = modal.style.display === 'block' ? 'none' : 'block';
            }
        });
        
        // Cell click to select
        document.addEventListener('click', (e) => {
            const cell = e.target.closest('.cell');
            if (cell) {
                selectCell(cell.dataset.cellId);
            }
        });
        
        // Initialize
        document.addEventListener('DOMContentLoaded', () => {
            // Load theme
            const savedTheme = localStorage.getItem('notebook-theme') || 'light';
            document.body.dataset.theme = savedTheme;
            
            // Initialize first cell editor
            initializeEditor('cell-1');
            
            // Focus first cell
            selectCell('cell-1');
            
            // MIME type support indicators (for tests)
            window.supportedMimeTypes = ['text/plain', 'text/html', 'image/png', 'application/json'];
        });
    </script>
</body>
</html>