-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcodeprep.html
More file actions
1070 lines (873 loc) · 49.9 KB
/
codeprep.html
File metadata and controls
1070 lines (873 loc) · 49.9 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>CodePrep - Your user-friendly coding practice platform</title>
<link rel="icon" type="image/png" href="https://raw.githubusercontent.com/Tebby2008/OpenNotes/main/resources/codeprep_favicon.png">
<link rel="manifest" href="resources/manifest-codeprep.json">
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
mono: ['Source Code Pro', 'ui-monospace', 'SFMono-Regular', 'Menlo', 'Monaco', 'Consolas', 'Liberation Mono', 'Courier New', 'monospace'],
},
colors: {
'accent-blue': '#198cff',
'accent-dark-bg': '#1C1C1E',
'glass-surface': 'rgba(44, 44, 46, 0.85)',
}
}
}
}
</script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:[email protected]&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@400;600&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200');
body {
min-height: 100vh;
display: flex;
flex-direction: column;
background: linear-gradient(135deg, #1f2937, #0f172a);
color: #E5E5E5;
}
.glass-card {
background-color: var(--tw-color-glass-surface);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(255, 255, 255, 0.1);
transition: all 0.3s ease;
}
textarea::-webkit-scrollbar, .scroll-area::-webkit-scrollbar {
width: 8px;
}
textarea::-webkit-scrollbar-thumb, .scroll-area::-webkit-scrollbar-thumb {
background-color: rgba(255, 255, 255, 0.3);
border-radius: 4px;
}
textarea::-webkit-scrollbar-track, .scroll-area::-webkit-scrollbar-track {
background: transparent;
}
#code-editor {
caret-color: #198cff;
}
.file-tab {
margin-right: 0.5rem;
padding: 0.5rem 1rem;
font-size: 0.875rem;
font-weight: 500;
border-top-left-radius: 0.75rem;
border-top-right-radius: 0.75rem;
transition: all 150ms ease-in-out;
cursor: pointer;
background-color: rgba(41, 44, 51, 0.8);
color: #9ca3af;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
border-bottom: 2px solid #27272a;
}
.file-tab:not(.active):hover {
background-color: #374151;
color: #ffffff;
}
.file-tab.active {
background-color: rgba(17, 24, 39, 0.6);
color: #ffffff;
font-weight: 600;
border-bottom: 2px solid transparent;
}
.modal-content-transition {
transition: opacity 0.3s cubic-bezier(0.25, 0.8, 0.25, 1), transform 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}
.modal-enter {
opacity: 0;
transform: scale(0.9);
}
.modal-enter-active {
opacity: 1;
transform: scale(1);
}
.modal-leave-active {
opacity: 0;
transform: scale(0.9);
}
.backdrop-transition {
transition: opacity 0.3s ease-out;
opacity: 0;
}
.backdrop-active {
opacity: 1;
}
.scrollable-content {
max-height: 50vh;
overflow-y: auto;
padding-right: 1rem;
}
.spinner {
border: 4px solid rgba(255, 255, 255, 0.1);
border-left-color: #198cff;
border-radius: 50%;
width: 30px;
height: 30px;
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
</style>
</head>
<body class="font-sans p-4 md:p-8">
<div id="app" class="max-w-7xl mx-auto space-y-6 flex-grow">
<header class="text-center py-4">
<h1 class="text-6xl font-bold text-white tracking-tight p-6">\\: CodePrep</h1>
<p class="text-gray-400 mt-1 text-sm">Your user-friendly coding practice platform from OpenNotes. Tailored specifically for your AP CSA needs.</p>
<a href="https://opennotes.pages.dev/" target="_blank" class="inline-block mt-3 text-sm font-medium text-gray-300 hover:text-white transition-colors border border-gray-700/50 hover:border-accent-blue px-4 py-1.5 rounded-xl bg-gray-700/50 hover:bg-gray-600/70 shadow-md">
Explore OpenNotes Platform
</a>
</header>
<div class="lg:grid lg:grid-cols-3 gap-6">
<div class="lg:col-span-1 glass-card p-6 rounded-2xl shadow-xl h-full flex flex-col mb-6 lg:mb-0">
<div class="flex items-center justify-between mb-4">
<h2 id="current-problem-title" class="text-xl font-semibold text-accent-blue">Loading Problems...</h2>
<span id="current-problem-difficulty" class="px-3 py-1 text-xs rounded-full font-medium" style="background-color: rgba(255, 255, 255, 0.1);"></span>
</div>
<div id="problem-description" class="text-gray-300 scroll-area overflow-y-auto flex-grow" style="max-height: 100vh;">
Fetching problem data from **problems.json**...
</div>
</div>
<div class="lg:col-span-2 glass-card p-6 rounded-2xl shadow-xl flex flex-col">
<h2 class="text-xl font-semibold mb-4 text-white">Your Solution (Java)</h2>
<div id="file-manager" class="mb-[-2px] transition-all duration-300 overflow-x-auto whitespace-nowrap hidden">
<div id="file-tabs" class="flex border-b border-gray-700/50">
</div>
<div class="flex space-x-2 mt-2 mb-2">
<button onclick="addFile()" class="text-sm text-gray-400 hover:text-white transition-colors px-2 py-1 rounded-md bg-gray-700/50 hover:bg-gray-600/70">
+ Add Class
</button>
<button id="remove-file-btn" onclick="removeFile()" class="text-sm text-red-400 hover:text-red-300 transition-colors px-2 py-1 rounded-md bg-gray-700/50 hover:bg-gray-600/70">
- Remove Class
</button>
</div>
</div>
<textarea id="code-editor" class="font-mono text-sm w-full h-96 p-4 rounded-lg bg-gray-900/60 text-white outline-none resize-none border-2 border-transparent focus:border-accent-blue transition-colors shadow-inner" spellcheck="false" placeholder="Write your complete Java class here..."></textarea>
</div>
</div>
<div class="glass-card p-4 rounded-2xl shadow-xl flex flex-col md:flex-row justify-between items-center space-y-4 md:space-y-0 md:space-x-4">
<div class="flex space-x-3 w-full md:w-auto">
<button onclick="toggleProblemSelector(true)" class="bg-gray-700/80 hover:bg-gray-600 text-white font-medium py-2 px-4 rounded-xl shadow-md transition-colors">
Problem Selector
</button>
<button id="random-problem-btn" onclick="loadRandomProblem()" class="bg-accent-blue hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-xl shadow-md transition-colors">
Random Problem
</button>
</div>
<button id="check-code-btn" onclick="confirmSubmission()" class="w-full md:w-auto bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-xl shadow-lg transition-colors transform ">
Check Code
</button>
</div>
</div>
<div id="problem-selector-modal" class="hidden fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4 backdrop-transition" onclick="if(event.target.id === 'problem-selector-modal') toggleProblemSelector(false)">
<div id="problem-selector-content" class="glass-card w-full max-w-xl rounded-2xl p-6 shadow-2xl relative modal-content-transition modal-enter">
<h3 class="text-2xl font-bold mb-4 text-white">Select Challenge</h3>
<div class="mb-4">
<p class="text-sm text-gray-400 mb-2">Filter by Difficulty:</p>
<div id="difficulty-filters" class="flex space-x-3">
</div>
</div>
<div id="problem-list" class="space-y-3 scroll-area overflow-y-auto max-h-72">
</div>
<button onclick="toggleProblemSelector(false)" class="absolute top-4 right-4 text-gray-400 hover:text-white transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /></svg>
</button>
</div>
</div>
<div id="confirmation-modal" class="hidden fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4 backdrop-transition" onclick="if(event.target.id === 'confirmation-modal') cancelSubmission()">
<div id="confirmation-content" class="glass-card w-full max-w-md rounded-2xl p-6 shadow-2xl relative modal-content-transition modal-enter">
<h3 class="text-2xl font-bold mb-4 text-red-500">Confirm Submission</h3>
<div id="confirmation-message" class="text-gray-300 space-y-4">
<p>⚠️ <b>Are you sure you want to submit your code?</b></p>
<p class="text-sm text-yellow-400">This simulates a formal testing environment. Once submitted your current attempt will be graded. Revise your code carefully beforehand!</p>
</div>
<div class="mt-6 flex justify-end space-x-4">
<button onclick="cancelSubmission()" class="bg-gray-700/80 hover:bg-gray-600 text-white font-medium py-2 px-4 rounded-xl shadow-md transition-colors">
Cancel
</button>
<button onclick="handleConfirmedSubmission()" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-6 rounded-xl shadow-lg transition-colors">
Submit Final Code
</button>
</div>
</div>
</div>
<div id="result-modal" class="hidden fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4 backdrop-transition" onclick="if(event.target.id === 'result-modal') hideResultModal()">
<div id="result-content" class="glass-card w-full max-w-2xl rounded-2xl p-6 shadow-2xl relative modal-content-transition modal-enter">
<h3 id="result-modal-title" class="text-2xl font-bold mb-4 text-accent-blue"></h3>
<div id="result-modal-content-area" class="text-gray-300 space-y-4 scrollable-content">
<p id="result-modal-message" class="text-gray-300"></p>
<pre id="result-modal-code" class="font-mono text-sm p-3 rounded-lg bg-gray-900/60 text-yellow-300 whitespace-pre-wrap"></pre>
</div>
<div id="result-modal-actions" class="mt-6 flex flex-col md:flex-row space-y-3 md:space-y-0 md:space-x-4">
</div>
<button onclick="hideResultModal()" class="absolute top-4 right-4 text-gray-400 hover:text-white transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /></svg>
</button>
</div>
</div>
<div id="loading-modal" class="hidden fixed inset-0 bg-black/70 z-50 flex flex-col items-center justify-center p-4 backdrop-transition">
<div class="glass-card p-8 rounded-2xl shadow-2xl flex flex-col items-center">
<div class="spinner mb-4"></div>
<p class="text-white text-lg font-medium">Processing request...</p>
<p class="text-gray-400 text-sm mt-1">Analyzing your code for conceptual errors.</p>
</div>
</div>
<footer class="mt-12 text-gray-400 text-sm">
<div class="max-w-7xl mx-auto px-4 md:px-0 flex justify-between items-center flex-wrap gap-4">
<div class="flex flex-wrap gap-x-6 gap-y-2">
<a href="https://opennotes.pages.dev" target="_blank" rel="noopener" class="flex items-center gap-1 hover:text-accent-blue transition-colors">
OpenNotes
</a>
<a href="https://github.com/Tebby2008/OpenNotes" target="_blank" rel="noopener" class="flex items-center gap-1 hover:text-accent-blue transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 96" fill="currentColor" class="h-4 w-4"><path fill-rule="evenodd" clip-rule="evenodd" d="M48.854 0C21.839 0 0 22 0 49.217c0 21.756 13.993 40.172 33.405 46.69 2.427.49 3.316-1.059 3.316-2.362 0-1.141-.08-5.052-.08-9.127-13.59 2.934-16.42-5.867-16.42-5.867-2.184-5.704-5.42-7.17-5.42-7.17-4.448-3.015.324-3.015.324-3.015 4.934.326 7.523 5.052 7.523 5.052 4.367 7.496 11.404 5.378 14.235 4.074.404-3.178 1.699-5.378 3.074-6.6-10.839-1.141-22.243-5.378-22.243-24.283 0-5.378 1.94-9.778 5.014-13.2-.485-1.222-2.184-6.275.486-13.038 0 0 4.125-1.304 13.426 5.052a46.97 46.97 0 0 1 12.214-1.63c4.125 0 8.33.571 12.213 1.63 9.302-6.356 13.427-5.052 13.427-5.052 2.67 6.763.97 11.816.485 13.038 3.155 3.422 5.015 7.822 5.015 13.2 0 18.905-11.404 23.06-22.324 24.283 1.78 1.548 3.316 4.481 3.316 9.126 0 6.6-.08 11.897-.08 13.526 0 1.304.89 2.853 3.316 2.364 19.412-6.52 33.405-24.935 33.405-46.691C97.707 22 75.788 0 48.854 0z"/></svg>
Github
</a>
</div>
<div class="flex items-center gap-2 text-gray-400">
<span class="material-symbols-outlined text-lg">visibility</span>
<span id="websiteViews" class="font-medium text-gray-400">0</span>
</div>
</div>
</footer>
<script>
const editor = document.getElementById('code-editor');
const titleEl = document.getElementById('current-problem-title');
const difficultyEl = document.getElementById('current-problem-difficulty');
const descriptionEl = document.getElementById('problem-description');
const problemListEl = document.getElementById('problem-list');
const filterContainerEl = document.getElementById('difficulty-filters');
const randomBtnEl = document.getElementById('random-problem-btn');
const checkCodeBtn = document.getElementById('check-code-btn');
const fileManagerEl = document.getElementById('file-manager');
const fileTabsEl = document.getElementById('file-tabs');
const resultModalMessageEl = document.getElementById('result-modal-message');
const WORKER_BASE_URL = 'https://java-compiler-worker.tebby2008-li.workers.dev';
const COMPILER_URL = `${WORKER_BASE_URL}/compile`;
const TUTOR_URL = `${WORKER_BASE_URL}/tutor`;
const PROBLEM_DATA_URL = 'https://raw.githubusercontent.com/Tebby2008/OpenNotes/main/resources/coding_problems.json'; // URL for the JSON file
const TRANSITION_DURATION = 300;
const API_URL = "https://open-notes.tebby2008-li.workers.dev";
const websiteViewsEl = document.getElementById('websiteViews');
let problems = [];
let currentProblem = null;
let activeFilters = {
'Easy': true,
'Medium': true,
'Hard': true
};
let codeFiles = [];
let currentFileIndex = 0;
function showModalWithTransition(modalId, contentId) {
const modal = document.getElementById(modalId);
const content = contentId ? document.getElementById(contentId) : null;
modal.classList.remove('hidden');
setTimeout(() => {
modal.classList.add('backdrop-active');
if (content) {
content.classList.remove('modal-enter');
content.classList.add('modal-enter-active');
}
}, 10);
}
function hideModalWithTransition(modalId, contentId) {
const modal = document.getElementById(modalId);
const content = contentId ? document.getElementById(contentId) : null;
modal.classList.remove('backdrop-active');
if (content) {
content.classList.remove('modal-enter-active');
content.classList.add('modal-leave-active');
}
setTimeout(() => {
modal.classList.add('hidden');
if (content) {
content.classList.remove('modal-leave-active');
content.classList.add('modal-enter');
}
}, TRANSITION_DURATION);
}
function showLoadingModal() {
showModalWithTransition('loading-modal', null);
}
function hideLoadingModal() {
hideModalWithTransition('loading-modal', null);
}
function convertMarkdownToHtml(text) {
if (!text) return '';
text = text.replace(/`([^`]+)`/g, '<code class="font-mono text-yellow-300 bg-gray-800 px-1 py-0.5 rounded">\$1</code>');
text = text.replace(/\*\*([^\*]+)\*\*/g, '<strong>\$1</strong>');
text = text.replace(/\n/g, '<br>');
return text;
}
editor.addEventListener('input', () => {
if (codeFiles.length > 0 && currentFileIndex >= 0) {
const currentContent = editor.value;
codeFiles[currentFileIndex].content = currentContent;
const classNameRegex = /(?:public|private|protected)\s+class\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/;
const match = currentContent.match(classNameRegex);
let newName = codeFiles[currentFileIndex].name;
if (match && match[1]) {
newName = match[1] + '.java';
} else if (!codeFiles[currentFileIndex].name.startsWith('<unnamed_')) {
newName = 'Class.java';
} else if (codeFiles[currentFileIndex].name.startsWith('<unnamed_')) {
newName = codeFiles[currentFileIndex].name;
}
if (codeFiles[currentFileIndex].name !== newName) {
codeFiles[currentFileIndex].name = newName;
renderFileTabs();
}
}
});
editor.addEventListener('keydown', function(e) {
if (e.key === 'Tab') {
e.preventDefault();
const start = this.selectionStart;
const end = this.selectionEnd;
const fourSpaces = ' ';
this.value = this.value.substring(0, start) + fourSpaces + this.value.substring(end);
this.selectionStart = this.selectionEnd = start + fourSpaces.length;
}
});
function getDifficultyStyle(difficulty) {
switch (difficulty) {
case 'Easy':
return { text: 'text-green-300', bg: 'bg-green-700/30' };
case 'Medium':
return { text: 'text-yellow-300', bg: 'bg-yellow-700/30' };
case 'Hard':
return { text: 'text-red-300', bg: 'bg-red-700/30' };
default:
return { text: 'text-gray-300', bg: 'bg-gray-700/30' };
}
}
function loadProblem(problem) {
currentProblem = problem;
titleEl.textContent = problem.title;
descriptionEl.innerHTML = convertMarkdownToHtml(problem.description);
codeFiles = problem.requiredClasses.map(name => ({
name: name,
content: ''
}));
currentFileIndex = 0;
const isMultiClass = problem.requiredClasses.length > 1;
fileManagerEl.classList.toggle('hidden', !isMultiClass);
if (codeFiles.length > 0) {
editor.value = codeFiles[currentFileIndex].content;
} else {
editor.value = '';
}
const style = getDifficultyStyle(problem.difficulty);
difficultyEl.textContent = problem.difficulty;
difficultyEl.className = `px-3 py-1 text-xs rounded-full font-medium ${style.text} ${style.bg}`;
renderFileTabs();
hideResultModal();
toggleProblemSelector(false);
}
function renderFileTabs() {
fileTabsEl.innerHTML = '';
document.getElementById('remove-file-btn').classList.toggle('opacity-50', codeFiles.length <= 1);
document.getElementById('remove-file-btn').disabled = codeFiles.length <= 1;
codeFiles.forEach((file, index) => {
const tab = document.createElement('div');
tab.textContent = file.name;
const isActive = index === currentFileIndex;
tab.className = `file-tab ${isActive ? 'active' : ''}`;
tab.onclick = () => switchFile(index);
fileTabsEl.appendChild(tab);
});
}
function switchFile(index) {
if (index === currentFileIndex) return;
if (codeFiles.length > 0) {
codeFiles[currentFileIndex].content = editor.value;
}
currentFileIndex = index;
editor.value = codeFiles[currentFileIndex].content;
renderFileTabs();
}
function addFile() {
const newFileName = `<unnamed_${Date.now()}>.java`;
codeFiles.push({ name: newFileName, content: '' });
switchFile(codeFiles.length - 1);
}
function removeFile() {
if (codeFiles.length > 1) {
codeFiles.splice(currentFileIndex, 1);
currentFileIndex = Math.max(0, currentFileIndex - 1);
editor.value = codeFiles[currentFileIndex].content;
renderFileTabs();
}
}
function loadRandomProblem() {
let filteredProblems = problems.filter(p => activeFilters[p.difficulty]);
if (currentProblem) {
filteredProblems = filteredProblems.filter(p => p.id !== currentProblem.id);
}
if (filteredProblems.length === 0) {
const message = currentProblem
? 'Only the current problem is available in the current filter settings.'
: 'No problems match the current filter. Please adjust the difficulty settings.';
showResultModal('No New Problems Available', message, 'error', null);
return;
}
const randomIndex = Math.floor(Math.random() * filteredProblems.length);
loadProblem(filteredProblems[randomIndex]);
}
function confirmSubmission() {
if (!currentProblem) {
showResultModal('Error', 'Please select a problem before attempting to check code.', 'error', null);
return;
}
if (codeFiles.length > 0 && currentFileIndex >= 0) {
codeFiles[currentFileIndex].content = editor.value;
}
showModalWithTransition('confirmation-modal', 'confirmation-content');
}
function cancelSubmission() {
hideModalWithTransition('confirmation-modal', 'confirmation-content');
}
const TEST_DELIMITER = "__TEST_CASE_DELIMITER__";
function createJavaTestDriver(tests, problem) {
let mainMethodBody = '';
tests.forEach((test, index) => {
let callString = problem.driverCallTemplate;
const inputParts = test.input.split(',').map(s => s.trim());
const inputRegex = /##__IN_(\d+)__##/g;
callString = callString.replace(inputRegex, (match, p1) => {
const i = parseInt(p1, 10) - 1;
return (i >= 0 && i < inputParts.length) ? inputParts[i] : match;
});
mainMethodBody += `
System.out.println("${TEST_DELIMITER}");
${callString};
System.out.println("${TEST_DELIMITER}");
`;
});
return `
class TestDriver {
public static void main(String[] args) {
${mainMethodBody}
}
}
`;
}
async function handleConfirmedSubmission() {
cancelSubmission();
showLoadingModal();
checkCodeBtn.textContent = 'Checking Code...';
checkCodeBtn.disabled = true;
if (codeFiles.length > 0) {
codeFiles[currentFileIndex].content = editor.value;
}
const userCode = codeFiles.map(f => f.content).join('\n');
const MAX_CODE_LENGTH = 2000;
const JAVA_CHARSET_REGEX = /[^\w\s{}\[\]();,.:<>="'+\/\%&|^\~?\@\#\$\-\\]/g;
let finalResults = [];
if (userCode.length > MAX_CODE_LENGTH) {
finalResults.push({
status: 'FAILED_VALIDATION',
actual: `Your combined code length is ${userCode.length} characters, which exceeds the limit of ${MAX_CODE_LENGTH} characters. Please shorten your code.`,
input: 'Length Check',
expected: `Code length <= ${MAX_CODE_LENGTH} characters`
});
}
const illegalCharsMatch = userCode.match(JAVA_CHARSET_REGEX);
if (illegalCharsMatch) {
const uniqueIllegalChars = [...new Set(illegalCharsMatch)].join(', ');
finalResults.push({
status: 'FAILED_VALIDATION',
actual: `Found non-standard characters in your code which could cause compilation issues. The following characters were flagged: ${uniqueIllegalChars}. Only use standard Java/ASCII characters.`,
input: 'Character Set Check',
expected: 'Only standard Java/ASCII characters'
});
}
if (finalResults.length > 0) {
hideLoadingModal();
checkCodeBtn.textContent = 'Check Code';
checkCodeBtn.disabled = false;
showFailureResult(finalResults, userCode);
return;
}
if (userCode.trim() === "") {
hideLoadingModal();
showFailureResult([ { status: 'FAILED_COMPILATION', actual: 'Your editor is empty. The compiler requires a complete class definition to proceed.', input: '', expected: '' } ], userCode);
return;
}
const isFullProgramMode = currentProblem.runAsMain;
const tests = currentProblem.tests;
let fullProgram;
let expectedOutput;
let inputForCompiler = null;
if (isFullProgramMode) {
fullProgram = userCode;
inputForCompiler = tests.map(t => t.input).join(`\n${TEST_DELIMITER}\n`);
expectedOutput = tests.map(t => t.expectedOutput).join('');
} else {
const driverCode = createJavaTestDriver(tests, currentProblem);
fullProgram = userCode + '\n' + driverCode;
expectedOutput = tests.map(t => t.expectedOutput).join('');
}
try {
const response = await fetch(COMPILER_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
code: fullProgram,
input: inputForCompiler
})
});
const rawOutput = await response.text();
let combinedStatus = 'PASSED';
let actualOutput = rawOutput;
let compilationFailed = false;
if (rawOutput.startsWith('COMPILATION_ERROR:')) {
combinedStatus = 'FAILED_COMPILATION';
compilationFailed = true;
} else if (rawOutput.startsWith('RUNTIME_ERROR:')) {
combinedStatus = 'FAILED_RUNTIME';
compilationFailed = true;
}
if (compilationFailed) {
finalResults = [{
input: 'All Tests',
expected: '',
actual: actualOutput,
status: combinedStatus
}];
} else {
const expectedOutputsCount = tests.length;
const rawParts = actualOutput.split(TEST_DELIMITER);
let outputs = [];
for (let i = 0; i < expectedOutputsCount; i++) {
const outputIndex = (2 * i) + 1;
if (outputIndex < rawParts.length) {
outputs.push(rawParts[outputIndex].trim());
} else {
outputs.push("[ERROR: Output Missing]");
}
}
if (outputs.length !== tests.length) {
combinedStatus = 'FAILED_LOGIC';
finalResults = [{
input: 'Test Parsing Error',
expected: 'Expected ' + tests.length + ' test results.',
actual: `Received ${outputs.length} results. Raw output (first 500 chars): ${actualOutput.substring(0, 500)}`,
status: combinedStatus
}];
} else {
finalResults = tests.map((test, i) => {
const rawActual = outputs[i];
const rawExpected = test.expectedOutput;
const sanitize = (str) => {
if (typeof str !== 'string') return '';
str = str.replace(/\r\n/g, '\n');
return str.trim();
};
const isRandomIntMatch = (expected, actual) => {
const randomIntRegex = /^##__Randint_(-?\d+)_(-?\d+)__##$/;
const match = expected.trim().match(randomIntRegex);
if (match) {
const min = parseInt(match[1], 10);
const max = parseInt(match[2], 10);
const actualInt = parseInt(actual, 10);
if (actual === String(actualInt) && !isNaN(actualInt) && actualInt >= min && actualInt <= max) {
return true;
}
return false;
} else {
return actual === sanitize(expected);
}
};
const actual = sanitize(rawActual);
let status = isRandomIntMatch(rawExpected, actual) ? 'PASSED' : 'FAILED_LOGIC';
if (status !== 'PASSED') { combinedStatus = 'FAILED_LOGIC'; }
return {
input: test.input,
expected: rawExpected,
actual: rawActual,
status: status
};
});
}
}
hideLoadingModal();
const firstFailure = finalResults.find(r => r.status.startsWith('FAILED'));
if (firstFailure) {
showFailureResult(finalResults, userCode);
} else {
showSuccessResult(finalResults);
}
} catch (error) {
hideLoadingModal();
showFailureResult([ { status: 'FAILED_NETWORK', actual: `Failed to reach the compiler service: ${error.message}.`, input: '', expected: '' } ], userCode);
return;
}
}
let lastFailedCode = '';
function showSuccessResult(testResults) {
checkCodeBtn.textContent = 'Check Code';
checkCodeBtn.disabled = false;
const passedCount = testResults.filter(r => r.status === 'PASSED').length;
let testOutput = "Compilation Success! All tests passed.\n\n";
testResults.forEach((test, index) => {
testOutput += `[✅ PASSED] Test Case ${index + 1} (Input: ${test.input})\n`;
testOutput += ` - Expected Output: ${test.expected}\n`;
testOutput += ` - Actual Output: ${test.actual}\n\n`;
});
const message = `Congratulations! All ${passedCount}/${testResults.length} tests passed successfully. You have completed the challenge.`;
const actions = document.getElementById('result-modal-actions');
actions.innerHTML = `
<button onclick="toggleProblemSelector(true); hideResultModal();" class="bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-8 rounded-xl shadow-md transition-colors w-full">
Select Next Problem
</button>
`;
showResultModal('Challenge Complete', message, 'success', testOutput);
}
function showFailureResult(testResults, userCode) {
lastFailedCode = userCode;
checkCodeBtn.textContent = 'Check Code';
checkCodeBtn.disabled = false;
const firstFailure = testResults ? testResults.find(r => r.status.startsWith('FAILED')) || testResults[0] : null;
const isCompilationError = firstFailure && firstFailure.status.includes('COMPILATION');
const isRuntimeError = firstFailure && firstFailure.status.includes('RUNTIME');
let title = 'Test Failed: Logic Error';
let message = 'Your code ran, but the output did not match expectations for one or more test cases. Review the detailed test results.';
let codeContent = '';
let testOutput = '';
if (testResults) {
testResults.forEach((test, index) => {
const icon = test.status.startsWith('FAILED') ? '❌' : '✅';
const statusText = test.status.startsWith('FAILED') ? test.status.replace('FAILED_', '').padEnd(12) : 'PASSED';
testOutput += `[${icon} ${statusText}] Test Case ${index + 1} (Input: ${test.input})\n`;
if (test.status.startsWith('FAILED')) {
testOutput += ` - Expected Output: ${test.expected || 'N/A'}\n`;
testOutput += ` - Actual Output: ${test.actual}\n\n`;
} else {
testOutput += ` - Actual Output: ${test.actual}\n\n`;
}
});
}
if (isCompilationError) {
title = 'Compilation Error';
message = `The Java compiler failed to build your code. This is typically due to a syntax error, incorrect class/method signature, or missing required classes. The compiler reported an error (see box below). Use the AI explanation for a hint!`;
codeContent = firstFailure.actual;
} else if (isRuntimeError) {
title = 'Runtime Error';
message = `Your code compiled but crashed during execution (e.g., NullPointerException). The runtime reported an error (see box below). Use the AI explanation for a hint!`;
codeContent = firstFailure.actual;
} else if (firstFailure.status === 'FAILED_NETWORK') {
title = 'Network Error';
message = `There was an issue connecting to the compilation service. Please check your internet connection or try again.`;
codeContent = firstFailure.actual;
}
else {
codeContent = testOutput;
}
const actions = document.getElementById('result-modal-actions');
actions.innerHTML = `
<div class="flex flex-col md:flex-row w-full space-y-3 md:space-y-0 md:space-x-3">
<button onclick="restartFromScratch()"
class="bg-red-600 hover:bg-red-700 text-white font-medium py-2 px-4 rounded-xl shadow-md transition-colors
w-full md:flex-grow whitespace-nowrap">
Restart From Scratch
</button>
<button onclick="explainWithAI()"
class="bg-gradient-to-br from-cyan-500 to-indigo-600 hover:from-cyan-600 hover:to-indigo-700
text-white font-medium py-2 px-4 rounded-xl shadow-md transition-colors
w-full md:flex-grow whitespace-nowrap
flex items-center justify-center">
<span class="material-symbols-outlined mr-2 text-lg [font-variation-settings:'FILL'_1]"> auto_awesome</span>
<span class="text-base">Explain with AI</span>
</button>
<button onclick="showHelp()"
class="bg-gray-700/80 hover:bg-gray-600 text-white font-medium py-2 px-4 rounded-xl shadow-md transition-colors
w-full md:flex-grow whitespace-nowrap">
Show Solution
</button>
</div>
`;
showResultModal(title, message, 'error', codeContent);
}
function showResultModal(title, message, type, codeContent) {
const modal = document.getElementById('result-modal');
document.getElementById('result-modal-title').textContent = title;
resultModalMessageEl.innerHTML = convertMarkdownToHtml(message);
const codeEl = document.getElementById('result-modal-code');
document.getElementById('result-modal-content-area').scrollTop = 0;
if (codeContent) {
codeEl.textContent = codeContent;
codeEl.style.display = 'block';
document.getElementById('result-modal-title').classList.remove('text-accent-blue', 'text-green-500', 'text-red-500', 'text-yellow-300');
document.getElementById('result-modal-title').classList.add(type === 'success' ? 'text-green-500' : (type === 'error' ? 'text-red-500' : 'text-yellow-300'));
} else {
codeEl.style.display = 'none';
document.getElementById('result-modal-title').classList.remove('text-accent-blue', 'text-green-500', 'text-red-500', 'text-yellow-300');
document.getElementById('result-modal-title').classList.add(type === 'success' ? 'text-green-500' : (type === 'error' ? 'text-red-500' : 'text-accent-blue'));
}
showModalWithTransition('result-modal', 'result-content');
}
function hideResultModal() {
hideModalWithTransition('result-modal', 'result-content');
}
function restartFromScratch() {
codeFiles.forEach(file => file.content = '');
editor.value = '';
currentFileIndex = 0;
renderFileTabs();
hideResultModal();
}
function showHelp() {
if (currentProblem) {
const message = "Here is the verified solution for the problem. Use this to compare against your attempt.";
const actions = document.getElementById('result-modal-actions');
actions.innerHTML = `
<button onclick="hideResultModal()" class="bg-accent-blue hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-xl shadow-md transition-colors w-full">
Back to Editor
</button>
`;
showResultModal('Solution Revealed', message, 'help', currentProblem.solution);
}
}
async function explainWithAI() {
hideResultModal();
showLoadingModal();
if (!lastFailedCode || !currentProblem) {
hideLoadingModal();
showResultModal('Error', 'No failed code found or problem data is missing.', 'error', null);
return;
}
const userQuestion = "Please review my failing code and identify the most critical flaw (e.g., incorrect loop structure, wrong return type, missing keyword, or conceptual mistake) compared to the correct solution. Do NOT provide the correct code or method signature. Guide me towards the fix.";
const problemDescription = `The problem title is: "${currentProblem.title}". The problem requires: ${currentProblem.description}. For your internal comparison, the correct solution is: \n\n\`\`\`java\n${currentProblem.solution}\n\`\`\n`;
let generatedText = "Apologies, the **AI explanation service is currently unavailable**. This may be due to a network connection issue or an error in the service. Please try again later or use the 'Help (Show Solution)' button.";
try {
const payload = {
question: userQuestion,
code: lastFailedCode,
problemDescription: problemDescription
};
const response = await fetch(TUTOR_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!response.ok) {
generatedText = `The AI explanation service returned an error (Status: ${response.status}).`;
if (response.status === 403) {
generatedText = "The AI explanation service failed due to a **403 Forbidden Error**. This is usually because a browser security setting (like an extension) is blocking the required authentication process, or the Worker's CORS settings are incorrect.";
}
throw new Error(`Worker API HTTP error! status: ${response.status}`);
}
generatedText = await response.text();
} catch (error) {
console.error("AI explain Fetch Error:", error);
}
hideLoadingModal();
showResultModal(
'Explain with AI',
convertMarkdownToHtml(generatedText),
'help',
null
);
}
function toggleProblemSelector(show = true) {
if (show) {
renderProblemList();
showModalWithTransition('problem-selector-modal', 'problem-selector-content');
} else {
hideModalWithTransition('problem-selector-modal', 'problem-selector-content');
}
}
function renderProblemList() {
problemListEl.innerHTML = '';
const filteredProblems = problems.filter(p => activeFilters[p.difficulty]);
if (filteredProblems.length === 0) {
problemListEl.innerHTML = '<p class="text-center text-gray-500 p-4">No problems match the current filter. Try selecting more difficulties.</p>';
randomBtnEl.textContent = 'Random Problem (None)';
randomBtnEl.disabled = true;
randomBtnEl.classList.add('opacity-50');
return;
}
filteredProblems.forEach(p => {
const style = getDifficultyStyle(p.difficulty);
const problemItem = document.createElement('div');
problemItem.className = 'p-3 rounded-xl bg-gray-900/50 hover:bg-gray-700/70 transition-colors cursor-pointer flex justify-between items-center';
problemItem.onclick = () => loadProblem(p);
problemItem.innerHTML = `
<span class="font-medium text-white">${p.title}</span>
<span class="px-3 py-1 text-xs rounded-full font-medium ${style.text} ${style.bg}">${p.difficulty}</span>
`;
problemListEl.appendChild(problemItem);
});
randomBtnEl.textContent = `Random Problem (${filteredProblems.length})`;
randomBtnEl.disabled = false;
randomBtnEl.classList.remove('opacity-50');
}
function renderFilters() {
const difficulties = ['Easy', 'Medium', 'Hard'];
filterContainerEl.innerHTML = '';
difficulties.forEach(diff => {
const style = getDifficultyStyle(diff);
const isChecked = activeFilters[diff];
const button = document.createElement('button');
button.textContent = diff;