-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1117 lines (987 loc) · 51.4 KB
/
index.html
File metadata and controls
1117 lines (987 loc) · 51.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">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Python Adventure: Learn to Code</title>
<script src="https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js"></script>
<script type="module">
import { tutorialContent } from './tutorial.js';
window.tutorialContent = tutorialContent;
// Move initialization to after module loads
window.addEventListener('load', function() {
initPyodide();
loadTutorialContent();
});
</script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<!-- CodeMirror for line numbers and syntax highlighting -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.15/codemirror.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.15/theme/neat.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.15/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.15/mode/python/python.min.js"></script>
<style>
body {
background-color: #f8f9fa;
}
main {
background-color: #f0f2f5; /* A slightly darker, neutral background for the main area */
padding-top: 1.5rem !important;
}
.sidebar {
background-color: #fbfdff; /* Softer, slightly cool off-white */
border-right: 1px solid #dee2e6;
height: 100vh;
position: sticky;
top: 0;
}
.chapter-container {
border-bottom: 1px solid #dee2e6; /* Divider line */
}
.sidebar h4 {
font-weight: 600;
color: #495057;
letter-spacing: 0.5px;
}
#chapter-list .list-group-item {
font-weight: 500; /* Medium weight for chapter titles */
font-weight: 600; /* Bolder for chapter titles */
color: #343a40;
border: none; /* Remove default borders */
padding: 0.85rem 1.5rem; /* More vertical and horizontal space */
transition: background-color 0.2s ease-in-out;
}
#chapter-list .list-group-item.active {
background-color: #e7f5ff; /* Light blue background for active */
color: #0c63e4;
font-weight: 600; /* Bolder when active */
border-left: 4px solid #0c63e4; /* Accent border */
padding-left: calc(1.5rem - 4px); /* Adjust padding to align text */
}
#chapter-list .list-group-item:not(.active):hover {
background-color: #f1f3f5; /* Subtle hover for non-active items */
}
.sidebar .bi { /* Style for progress icons */
margin-right: 8px;
font-size: 0.9em;
vertical-align: middle;
position: relative;
top: -1px;
}
.tutorial-section {
max-height: 800px;
overflow-y: auto; /* Keep scrolling for long content */
padding: 2rem;
background-color: #fff;
border-radius: 8px;
margin-bottom: 2rem;
box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}
.code-wrapper {
position: relative;
}
.code-actions {
position: absolute;
top: 0.5rem;
right: 0.5rem;
opacity: 0;
transition: opacity 0.2s ease-in-out;
display: flex;
gap: 0.5rem;
}
.code-wrapper:hover .code-actions {
opacity: 1;
}
.tutorial-section pre {
background-color: #f1f3f5; /* A light, soft gray */
color: #212529; /* Dark text for contrast */
padding: 1rem;
border-radius: 0.3rem;
white-space: pre-wrap; /* Wrap long lines */
border: 1px solid #dee2e6; /* A subtle border */
}
.tutorial-section pre code {
color: #d63384; /* A pleasant pink for code elements */
}
/* CodeMirror styling */
.CodeMirror {
border: 1px solid #ccc;
border-radius: 4px; /* Existing style */
height: 150px; /* Smaller initial height for the editor */
max-height: 300px; /* Allows editor to expand up to this height */
overflow-y: auto; /* Adds scrollbar if content exceeds max-height */
}
#output {
width: 100%;
min-height: 50px; /* Smaller minimum height for the output */
border: 1px solid #ccc;
border-radius: 4px;
padding: 10px;
background-color: #f8f9fa;
font-family: monospace;
white-space: pre-wrap;
box-shadow: inset 0 1px 3px rgba(0,0,0,0.05); /* Existing style */
max-height: 200px; /* Limits max height for output, then scrolls */
overflow-y: auto; /* Adds scrollbar if content exceeds max-height */
}
.exercise {
padding: 1.5rem;
margin-top: 1rem;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}
.exercise pre {
white-space: pre-wrap; /* Allows text to wrap */
word-wrap: break-word; /* Breaks long words if necessary */
}
.interactive-zone {
background-color: #fbfdff;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}
.exercises-list .btn {
border-radius: 20px; /* Pill-shaped buttons */
font-weight: 500;
}
.exercises-list .btn.active {
background-color: #0d6efd;
color: white;
box-shadow: 0 2px 4px rgba(13,110,253,0.3);
}
.chapter-nav {
margin-bottom: 20px;
}
.exercises-list .btn.active {
background-color: #0d6efd;
color: white;
}
.hint-container {
background-color: #eef2f7; /* A softer blue */
border-left: 5px solid #0d6efd; /* A prominent left border */
padding: 15px;
margin-top: 15px;
border-radius: 5px;
display: flex; /* Use flexbox for alignment */
align-items: center;
gap: 10px; /* Space between icon and text */
}
.hint-container i {
font-size: 1.2rem;
}
#section-list .list-group-item {
border: none;
}
.section-list-wrapper {
background-color: #f8f9fa; /* A neutral light gray for better contrast */
border-top: 1px solid #dee2e6;
border-bottom: 1px solid #dee2e6;
margin: 0;
padding: 0.5rem 0;
box-shadow: inset 0 4px 8px -4px rgba(0,0,0,0.1); /* Inset shadow for depth */
}
.section-list-for-chapter a.list-group-item {
padding-top: 0.1rem; /* Much less vertical padding */
padding-bottom: 0.1rem; /* Much less vertical padding */
padding-left: calc(4.5rem - 3px); /* Even more indentation */
font-size: 0.85rem; /* Smaller font for section titles */
color: #6c757d !important; /* Lighter text for sections, with !important to override Bootstrap */
transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
border-left: 3px solid transparent; /* Placeholder for alignment */
background-color: transparent; /* Ensure it inherits from wrapper */
}
.section-list-for-chapter .list-group-item:hover {
background-color: #dbeaff; /* A slightly darker blue on hover */
border-left-color: #a9caff;
}
.section-list-for-chapter .list-group-item.active-section {
color: #0c63e4;
font-weight: 500;
border-left-color: #0c63e4; /* Make border visible for active section */
}
.main-header {
background: linear-gradient(to right, #e7f5ff, #fbfdff);
border-radius: 8px;
padding: 1rem 1.5rem;
margin-bottom: 1.5rem;
}
.inline-exercise-header {
background: linear-gradient(to right, #e6f9f1, #fdfdff); /* Light green to off-white */
border-radius: 8px;
padding: 1.5rem;
margin-top: 1.5rem;
border: 1px solid #eee;
border-bottom: none;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<!-- Sidebar -->
<nav class="col-md-3 col-lg-2 d-md-block sidebar p-0">
<div class="position-sticky">
<h4 class="px-3 pt-3">Chapters</h4>
<div id="chapter-list" class="list-group list-group-flush">
<!-- Chapter links will be loaded here -->
</div>
</div>
</nav>
<!-- Main Content -->
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
<div class="main-header">
<h1 class="h2">Python Adventure: Learn to Code</h1>
</div>
<!-- Tutorial Content Area -->
<div class="tutorial-section" id="tutorial">
<!-- Tutorial content loads here -->
</div>
<!-- Interactive Zone for Exercises and Code -->
<div class="interactive-zone" id="interactive-zone">
<div class="row">
<div class="col-12">
<h3>Exercises</h3>
<div class="exercises-list mb-3">
<!-- Exercise selection buttons load here -->
<p>Select a chapter from the sidebar to see its exercises.</p>
</div>
<div id="current-exercise-content" class="exercise mb-4" style="display: none;">
<!-- Exercise description loads here -->
</div>
</div>
<div id="exercise-workspace-container" class="col-12 mt-4 mt-lg-0" style="display: none;">
<div class="d-flex justify-content-between align-items-center mb-2">
<div class="d-flex align-items-center">
<h3>Exercise Workspace</h3>
<span id="back-to-lesson-container" class="ms-3"></span>
</div>
<button id="btn-hint" class="btn btn-warning" onclick="showHint()" style="display: none;"><i class="bi bi-lightbulb"></i> Hint</button>
</div>
<div id="hint-section" style="display: none;">
<div id="hint-box" class="hint-container mb-2" style="display: none;">
<i class="bi bi-lightbulb-fill"></i>
<span id="hint-text"></span>
</div>
</div>
<textarea id="editor" placeholder="Try some python code here ..."></textarea>
<div class="d-flex mb-2">
<button class="btn btn-primary" onclick="runCode()">Run Code</button>
<button id="btn-check-exercise" class="btn btn-info" onclick="checkMainExercise()" style="display: none;">Check Exercise</button>
<button id="btn-reset-code" class="btn btn-outline-danger" onclick="resetCode()" style="display: none;"><i class="bi bi-arrow-counterclockwise"></i> Reset</button>
<button id="btn-next-exercise" class="btn btn-success ms-auto" onclick="loadNextExercise()" style="display: none;">Next Exercise</button>
</div>
<div id="output"></div>
</div>
</div>
</div>
<!-- Template for inline playgrounds -->
<template id="inline-playground-template">
<div class="inline-playground mt-2 mb-3 p-3 border rounded bg-light">
<textarea class="inline-editor"></textarea>
<div class="d-flex mt-2">
<button class="btn btn-primary btn-sm run-inline-code">
<i class="bi bi-play-fill"></i> Run
</button>
<button class="btn btn-secondary btn-sm ms-2 close-inline-playground">
<i class="bi bi-x-lg"></i> Close
</button>
</div>
<div class="inline-output mt-2 p-2 border rounded bg-white" style="min-height: 50px; font-family: monospace; white-space: pre-wrap;"></div>
</div>
</template>
<div class="chapter-nav d-flex justify-content-between mt-4">
<button id="btn-prev-chapter" class="btn btn-outline-secondary" onclick="loadPrevChapter()"><i class="bi bi-arrow-left"></i> Previous Chapter</button>
<button id="btn-next-chapter" class="btn btn-outline-secondary" onclick="loadNextChapter()">Next Chapter <i class="bi bi-arrow-right"></i></button>
</div>
</main>
</div>
</div>
<!-- Reset Confirmation Modal -->
<div class="modal fade" id="resetConfirmModal" tabindex="-1" aria-labelledby="resetConfirmModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="resetConfirmModalLabel">Confirm Reset</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Are you sure you want to reset your code? Your current work on this exercise will be lost.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-danger" id="confirmResetBtn">Reset Code</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
let pyodide = null;
let currentChapter = 'chapter1';
let codeEditor = null; // To hold the CodeMirror instance
let currentExercise = null;
async function initPyodide() {
pyodide = await loadPyodide();
document.getElementById('output').textContent = 'Python environment ready!';
}
function getProgress() {
const progress = localStorage.getItem('pythonAdventureProgress');
return progress ? JSON.parse(progress) : {};
}
function saveProgress(chapterId, exerciseId) {
const progress = getProgress();
if (!progress[chapterId]) {
progress[chapterId] = [];
}
if (!progress[chapterId].includes(exerciseId)) {
progress[chapterId].push(exerciseId);
}
localStorage.setItem('pythonAdventureProgress', JSON.stringify(progress));
}
function saveCodeForExercise(chapterId, exerciseId, code, exercise) {
if (!chapterId || !exerciseId || !exercise) return;
const key = `code-${chapterId}-${exerciseId}`;
const dataToSave = {
code: code,
version: exercise.version || 1 // Save code with its version
};
localStorage.setItem(key, JSON.stringify(dataToSave));
}
function getSavedCodeForExercise(chapterId, exerciseId, exercise) {
if (!chapterId || !exerciseId || !exercise) return null;
const key = `code-${chapterId}-${exerciseId}`;
const savedData = localStorage.getItem(key);
if (!savedData) return null;
const parsedData = JSON.parse(savedData);
// If saved version matches current exercise version, return the code.
if (parsedData.version === exercise.version) {
return parsedData.code;
}
return null; // Otherwise, discard saved code.
}
function updateChapterMarker(chapterId) {
const chapterLink = document.getElementById(`ch-btn-${chapterId}`);
if (!chapterLink) return;
const chapter = tutorialContent[chapterId];
const progress = getProgress();
const completedCount = (progress[chapterId] || []).length;
const totalCount = chapter.exercises ? chapter.exercises.length : 0;
let marker = '';
if (totalCount > 0) {
if (completedCount === totalCount) {
marker = '<i class="bi bi-check-circle-fill text-success"></i>'; // All done
} else if (completedCount > 0) {
marker = '<i class="bi bi-pencil-fill text-primary"></i>'; // In progress
}
}
chapterLink.innerHTML = marker + chapter.title;
}
function highlightActiveChapter(chapterId) {
document.querySelectorAll('#chapter-list .list-group-item').forEach(item => item.classList.remove('active'));
document.getElementById(`ch-btn-${chapterId}`).classList.add('active');
// Also manage a class on the parent for section styling
document.querySelectorAll('.chapter-container').forEach(item => item.classList.remove('active-chapter'));
document.getElementById(`ch-btn-${chapterId}`).closest('.chapter-container').classList.add('active-chapter');
}
function loadChapter(chapterId) {
// Save code from the current exercise before switching chapters
if (currentChapter && currentExercise && codeEditor) {
const code = codeEditor.getValue();
saveCodeForExercise(currentChapter, currentExercise.id, code);
}
currentChapter = chapterId;
localStorage.setItem('lastChapter', chapterId); // Save chapter
localStorage.removeItem('lastExercise'); // Clear last exercise
const chapter = tutorialContent[chapterId];
let chapterHtml = '';
// Check for the new structure (story + sections)
if (chapter.story && chapter.sections) {
// Apply consistent formatting to the story here
chapterHtml += `<div class="alert alert-info">${chapter.story}</div>`;
chapter.sections.forEach((section, index) => {
const sectionId = `section-${chapterId}-${index}`;
if (index > 0) {
chapterHtml += '<hr class="my-4">'; // Add a separator between sections
}
chapterHtml += `<h3 id="${sectionId}">${section.title}</h3><div>${section.content}</div>`;
// If the section has an exercise, append a placeholder for it
if (section.exercise) {
chapterHtml += `
<div class="inline-exercise-container"
data-chapter-id="${chapterId}"
data-exercise-id="${section.exercise.id}"
data-section-index="${index}">
<!-- Inline exercise will be loaded here -->
</div>
`;
}
});
} else { // Fallback to the old structure (single content property)
chapterHtml = chapter.content;
}
document.getElementById('tutorial').innerHTML = chapterHtml;
// Add copy buttons to all <pre> blocks in the tutorial section
document.querySelectorAll('.tutorial-section pre').forEach(pre => {
const wrapper = document.createElement('div');
wrapper.className = 'code-wrapper';
const actionsWrapper = document.createElement('div');
actionsWrapper.className = 'code-actions';
const tryButton = document.createElement('button');
tryButton.className = 'btn btn-sm btn-primary';
tryButton.innerHTML = '<i class="bi bi-play-circle"></i> Try It';
tryButton.title = 'Try this code';
tryButton.onclick = (e) => sendToPlayground(pre, e);
const copyButton = document.createElement('button');
copyButton.className = 'btn btn-sm btn-secondary';
copyButton.innerHTML = '<i class="bi bi-clipboard"></i>';
copyButton.title = 'Copy to clipboard';
copyButton.onclick = (e) => copyCodeToClipboard(e, pre);
pre.parentNode.insertBefore(wrapper, pre);
wrapper.appendChild(pre);
actionsWrapper.appendChild(tryButton);
actionsWrapper.appendChild(copyButton);
wrapper.appendChild(actionsWrapper);
});
// Load exercise and section lists
// First, hide all section lists
document.querySelectorAll('.section-list-wrapper').forEach(wrapper => {
wrapper.style.display = 'none';
const list = wrapper.querySelector('.section-list-for-chapter');
if (list) list.innerHTML = '';
});
const exercisesListDiv = document.querySelector('.exercises-list');
if (chapter.exercises && chapter.exercises.length > 0) {
exercisesListDiv.innerHTML = `<button class="btn btn-success" onclick="startExercises()">Start Exercises</button>`;
} else {
exercisesListDiv.innerHTML = `<p>No exercises for this chapter.</p>`;
}
// Populate and show the section list for the CURRENT chapter
if (chapter.sections && chapter.sections.length > 0) {
const sectionListContainer = document.getElementById(`sections-for-${chapterId}`);
sectionListContainer.parentElement.style.display = 'block'; // Show the wrapper
const progress = getProgress();
chapter.sections.forEach((section, index) => {
const sectionId = `section-${chapterId}-${index}`;
const link = document.createElement('a');
link.href = `#${sectionId}`;
link.className = 'list-group-item list-group-item-action border-0'; // border-0 for cleaner look
let linkHTML = section.title.replace(/<[^>]*>/g, '').replace(/(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])/g, '').trim();
// Add a checkmark if the section's exercise is complete
if (section.exercise && (progress[chapterId] || []).includes(section.exercise.id)) {
linkHTML = '✅ ' + linkHTML;
}
link.innerHTML = linkHTML;
link.id = `section-link-${chapterId}-${index}`;
// Add click listener to highlight active section
link.onclick = () => {
document.querySelectorAll('.section-list-for-chapter .list-group-item').forEach(item => item.classList.remove('active-section'));
link.classList.add('active-section');
// We return true to allow the default anchor behavior to proceed
return true;
};
sectionListContainer.appendChild(link);
});
// Add a link to the exercises at the end of the section list
if (chapter.exercises && chapter.exercises.length > 0) {
const exerciseLink = document.createElement('a');
exerciseLink.href = `#interactive-zone`;
exerciseLink.className = 'list-group-item list-group-item-action border-0';
exerciseLink.innerHTML = '<i class="bi bi-joystick"></i> Exercises'; // Add an icon for flair
exerciseLink.onclick = () => {
document.querySelectorAll('.section-list-for-chapter .list-group-item').forEach(item => item.classList.remove('active-section'));
exerciseLink.classList.add('active-section');
startExercises(); // Ensure exercise buttons are visible
return true; // Allow default anchor behavior
};
sectionListContainer.appendChild(exerciseLink);
}
}
// After setting the chapter HTML, load any inline exercises
document.querySelectorAll('.inline-exercise-container').forEach(container => {
const chapId = container.dataset.chapterId;
const exId = container.dataset.exerciseId;
loadInlineExercise(container, chapId, exId);
});
// Reset exercise view
document.getElementById('current-exercise-content').style.display = 'none';
document.getElementById('output').textContent = '';
currentExercise = null;
document.getElementById('btn-next-exercise').style.display = 'none';
document.getElementById('btn-check-exercise').style.display = 'none';
document.getElementById('btn-reset-code').style.display = 'none';
document.getElementById('hint-section').style.display = 'none';
document.getElementById('exercise-workspace-container').style.display = 'none';
document.getElementById('back-to-lesson-container').innerHTML = ''; // Clear back link
// Update chapter navigation buttons visibility
const chapterKeys = Object.keys(tutorialContent);
const currentChapterIndex = chapterKeys.indexOf(chapterId);
const prevButton = document.getElementById('btn-prev-chapter');
const nextButton = document.getElementById('btn-next-chapter');
prevButton.style.display = currentChapterIndex === 0 ? 'none' : 'inline-block';
nextButton.style.display = currentChapterIndex === chapterKeys.length - 1 ? 'none' : 'inline-block';
}
function loadInlineExercise(container, chapterId, exerciseId) {
const chapter = tutorialContent[chapterId];
const exercise = chapter.sections.flatMap(s => s.exercise || []).find(ex => ex.id === exerciseId);
if (!exercise) return;
// Use a template for the exercise workspace
const exerciseHeader = document.createElement('div');
exerciseHeader.className = 'inline-exercise-header';
const workspace = document.getElementById('inline-playground-template').content.cloneNode(true);
const exerciseTitle = document.createElement('h4');
exerciseTitle.textContent = exercise.title;
const exerciseDesc = document.createElement('div');
exerciseDesc.innerHTML = exercise.description;
exerciseHeader.appendChild(exerciseTitle);
exerciseHeader.appendChild(exerciseDesc);
container.appendChild(exerciseHeader);
container.appendChild(workspace);
const textarea = container.querySelector('.inline-editor');
const savedCode = getSavedCodeForExercise(chapterId, exerciseId, exercise);
textarea.value = savedCode || exercise.starter_code || '';
const editor = CodeMirror.fromTextArea(textarea, {
lineNumbers: true,
mode: 'python',
theme: 'neat',
indentUnit: 4
});
setTimeout(() => editor.refresh(), 10);
const outputDiv = container.querySelector('.inline-output');
const runButton = container.querySelector('.run-inline-code');
const checkButton = document.createElement('button');
checkButton.className = 'btn btn-info btn-sm ms-2';
checkButton.textContent = 'Check Exercise';
runButton.after(checkButton);
// Rename "Close" to "Reset" and change its function
const resetButton = container.querySelector('.close-inline-playground');
resetButton.innerHTML = '<i class="bi bi-arrow-counterclockwise"></i> Reset';
resetButton.onclick = () => {
if (confirm('Are you sure you want to reset your code?')) {
editor.setValue(exercise.starter_code || '');
}
};
// Wire up the buttons
runButton.onclick = () => runInlineCode(editor, outputDiv, chapterId, exerciseId, exercise);
checkButton.onclick = () => checkExercise(editor, outputDiv, chapterId, exercise);
}
function startExercises() {
const chapter = tutorialContent[currentChapter];
if (!chapter.exercises || chapter.exercises.length === 0) return;
const progress = getProgress();
const completedExercises = progress[currentChapter] || [];
// Replace "Start" button with the list of exercise buttons
const exercisesListDiv = document.querySelector('.exercises-list');
exercisesListDiv.innerHTML = chapter.exercises.map(ex => {
const isDone = completedExercises.includes(ex.id);
const doneMarker = isDone ? '✅ ' : '';
return `<button class="btn btn-outline-primary m-1" id="btn-ex-${ex.id}" onclick="loadExercise('${ex.id}')">${doneMarker}${ex.title}</button>`;
}).join('');
// Automatically load the first exercise
loadExercise(chapter.exercises[0].id);
}
function loadExercise(exerciseId) {
// Save code from the previous exercise before loading the new one
if (currentChapter && currentExercise && codeEditor) {
const code = codeEditor.getValue(); // Get value from editor
saveCodeForExercise(currentChapter, currentExercise.id, code, currentExercise); // Pass the exercise object
}
const chapter = tutorialContent[currentChapter];
currentExercise = chapter.exercises.find(ex => ex.id === exerciseId);
localStorage.setItem('lastExercise', exerciseId); // Save exercise
// Show and populate the exercise content area
const exerciseContentDiv = document.getElementById('current-exercise-content');
exerciseContentDiv.style.display = 'block';
exerciseContentDiv.innerHTML = `
<h4>${currentExercise.title}</h4>
<div>${currentExercise.description}</div>
`;
// Show the entire workspace container
document.getElementById('exercise-workspace-container').style.display = 'block';
// Refresh the editor to fix layout issues when it becomes visible
setTimeout(() => codeEditor.refresh(), 10);
const savedCode = getSavedCodeForExercise(currentChapter, exerciseId, currentExercise);
codeEditor.setValue(savedCode || currentExercise.starter_code || '');
document.getElementById('output').textContent = '';
// Show exercise-specific buttons
document.getElementById('btn-check-exercise').style.display = 'inline-block';
document.getElementById('btn-reset-code').style.display = 'inline-block';
// Show hint section if a hint exists, but hide the hint box itself
const hintButton = document.getElementById('btn-hint');
if (currentExercise.hint) {
hintButton.style.display = 'inline-block';
document.getElementById('hint-box').style.display = 'none';
document.getElementById('hint-text').textContent = '';
} else {
hintButton.style.display = 'none';
document.getElementById('hint-box').style.display = 'none'; // Also hide the box
}
// Update active button
document.querySelectorAll('.exercises-list .btn').forEach(btn => btn.classList.remove('active'));
document.getElementById(`btn-ex-${exerciseId}`).classList.add('active');
// Add 'in-progress' marker (✏️)
document.querySelectorAll('.exercises-list .btn').forEach(btn => {
// Remove marker from all buttons first
btn.innerHTML = btn.innerHTML.replace('✏️ ', '');
});
const currentButton = document.getElementById(`btn-ex-${exerciseId}`);
if (currentButton && !currentButton.innerHTML.includes('✅')) {
currentButton.innerHTML = '✏️ ' + currentButton.innerHTML;
}
// Show/hide the 'Next Exercise' button
const nextButton = document.getElementById('btn-next-exercise');
const exercises = chapter.exercises;
const currentIndex = exercises.findIndex(ex => ex.id === currentExercise.id);
if (currentIndex !== -1 && currentIndex < exercises.length - 1) {
nextButton.style.display = 'inline-block';
} else {
nextButton.style.display = 'none';
}
}
function loadNextExercise() {
if (!currentChapter || !currentExercise) {
alert("Please select an exercise first.");
return;
}
const chapter = tutorialContent[currentChapter];
const exercises = chapter.exercises;
const currentIndex = exercises.findIndex(ex => ex.id === currentExercise.id);
if (currentIndex !== -1 && currentIndex < exercises.length - 1) {
// Load the next exercise in the current chapter
const nextExercise = exercises[currentIndex + 1];
loadExercise(nextExercise.id);
} else {
alert("You've reached the last exercise of this chapter!");
}
}
function loadNextChapter() {
const chapterKeys = Object.keys(tutorialContent);
const currentChapterIndex = chapterKeys.indexOf(currentChapter);
if (currentChapterIndex < chapterKeys.length - 1) {
const nextChapterId = chapterKeys[currentChapterIndex + 1];
loadChapter(nextChapterId);
highlightActiveChapter(nextChapterId);
}
}
function loadPrevChapter() {
const chapterKeys = Object.keys(tutorialContent);
const currentChapterIndex = chapterKeys.indexOf(currentChapter);
if (currentChapterIndex > 0) {
const prevChapterId = chapterKeys[currentChapterIndex - 1];
loadChapter(prevChapterId);
highlightActiveChapter(prevChapterId);
}
}
function resetCode() {
if (!currentChapter || !currentExercise) {
// This case should ideally not be hit if button is hidden correctly
console.warn("Reset button clicked without an active exercise.");
return;
}
// Show the Bootstrap confirmation modal
const resetModal = new bootstrap.Modal(document.getElementById('resetConfirmModal'));
resetModal.show();
// The actual reset logic is now handled by an event listener on the modal's button
// to prevent it from running before confirmation.
}
function showHint() {
if (currentExercise && currentExercise.hint) {
const hintBox = document.getElementById('hint-box');
const hintText = document.getElementById('hint-text');
// Toggle hint visibility
if (hintBox.style.display === 'none') {
hintText.textContent = currentExercise.hint;
hintBox.parentElement.style.display = 'block'; // Show the container
hintBox.style.display = 'flex';
} else {
hintBox.style.display = 'none';
}
}
}
function sendToPlayground(preElement, event) {
const wrapper = preElement.closest('.code-wrapper');
if (!wrapper) return;
// If a playground already exists for this snippet, do nothing.
if (wrapper.nextElementSibling && wrapper.nextElementSibling.classList.contains('inline-playground')) {
return;
}
// Clone the template
const template = document.getElementById('inline-playground-template');
const playground = template.content.cloneNode(true).firstElementChild;
// Insert the new playground right after the code wrapper
wrapper.after(playground);
const code = preElement.querySelector('code')?.innerText || preElement.innerText;
const textarea = playground.querySelector('.inline-editor');
textarea.value = code;
// Initialize CodeMirror on the new textarea
const inlineEditor = CodeMirror.fromTextArea(textarea, {
lineNumbers: true,
mode: 'python',
theme: 'neat',
indentUnit: 4
});
// Refresh the editor to fix layout issues when it becomes visible
setTimeout(() => inlineEditor.refresh(), 10);
const outputDiv = playground.querySelector('.inline-output');
const runButton = playground.querySelector('.run-inline-code');
const closeButton = playground.querySelector('.close-inline-playground');
// Wire up the buttons
runButton.onclick = () => runInlineCode(inlineEditor, outputDiv);
closeButton.onclick = () => {
playground.remove();
event.target.style.display = 'inline-block'; // Show 'Try It' button again
};
// Hide the 'Try It' button that was clicked
event.target.style.display = 'none';
inlineEditor.focus();
}
function copyCodeToClipboard(event, preElement) {
const button = event.currentTarget;
const code = preElement.querySelector('code')?.innerText || preElement.innerText;
navigator.clipboard.writeText(code).then(() => {
button.innerHTML = '<i class="bi bi-check-lg"></i>';
button.title = 'Copied!';
setTimeout(() => {
button.innerHTML = '<i class="bi bi-clipboard"></i>';
button.title = 'Copy to clipboard';
}, 2000);
}).catch(err => {
console.error('Failed to copy code', err);
});
}
async function runInlineCode(editorInstance, outputElement, chapterId, exerciseId, exercise) {
if (!pyodide) return;
const code = editorInstance.getValue();
let output = '';
// Save code for inline exercises too
if (chapterId && exerciseId && exercise) {
saveCodeForExercise(chapterId, exerciseId, code, exercise);
}
try {
outputElement.textContent = 'Running...';
pyodide.runPython(`
import io, sys
sys.stdout = io.StringIO()
`);
await pyodide.runPythonAsync(code);
output = pyodide.runPython("sys.stdout.getvalue()");
} catch (error) {
output = 'Error: ' + error.message;
}
outputElement.textContent = output;
return output;
}
async function runCode() {
if (!pyodide) return;
const code = codeEditor.getValue();
if (currentChapter && currentExercise) {
saveCodeForExercise(currentChapter, currentExercise.id, code, currentExercise);
}
let output = '';
try {
pyodide.runPython(`
import io, sys
sys.stdout = io.StringIO()
`);
await pyodide.runPythonAsync(code);
output = pyodide.runPython("sys.stdout.getvalue()");
} catch (error) {
output = 'Error: ' + error.message;
}
document.getElementById('output').textContent = output;
return output;
}
function checkMainExercise() {
checkExercise(codeEditor, document.getElementById('output'), currentChapter, currentExercise);
}
async function checkExercise(editor = codeEditor, outputEl = document.getElementById('output'), chapId = currentChapter, exercise = currentExercise) {
if (!exercise) {
alert('Please select an exercise first!');
return;
}
const userCode = editor.getValue();
const userOutput = await runInlineCode(editor, outputEl, chapId, exercise.id, exercise); // Use runInlineCode to get output
const expectedOutput = await runSolution(exercise.solution);
// Clear previous check results from output
if (outputEl.textContent.includes('--- CHECK RESULTS ---')) {
outputEl.textContent = userOutput;
}
let feedback = [];
let allChecksPassed = true;
// 1. Check the final output
if (userOutput.trim() === expectedOutput.trim()) {
feedback.push('✅ Output is correct!');
} else {
feedback.push('❌ Output is incorrect.');
allChecksPassed = false;
}
// 2. Run custom validation checks if they exist
if (exercise.validation) {
for (const check of exercise.validation) { // Use for...of to handle async
if (check.type === 'code_contains' && !userCode.includes(check.value)) {
feedback.push(check.message);
allChecksPassed = false;
}
if (check.type === 'ast_check') {
const { passed, message } = await runAstCheck(userCode, check.script);
if (!passed) {
feedback.push(message);
allChecksPassed = false;
}
}
if (check.type === 'output_match_cases') {
for (const testCase of check.cases) {
const caseResult = await runCodeWithSetup(userCode, testCase.setup_code, exercise);
if (caseResult.trim() === testCase.expected_output.trim()) {
feedback.push(`✅ ${testCase.name}: Passed`);
} else {
feedback.push(`❌ ${testCase.name}: Failed`);
feedback.push(` - Expected: ${JSON.stringify(testCase.expected_output.trim())}`);
feedback.push(` - Got: ${JSON.stringify(caseResult.trim())}`);
allChecksPassed = false;
}
}
}
}
}
let summaryMessage = '';
if(allChecksPassed) {
summaryMessage = '\n\n🎉 Great job! All checks passed!';
saveProgress(chapId, exercise.id);
const button = document.getElementById(`btn-ex-${exercise.id}`);
if (button) {
button.innerHTML = button.innerHTML.replace('✏️ ', '');
if (!button.innerHTML.includes('✅')) {
button.innerHTML = '✅ ' + button.innerHTML;
}
}
updateChapterMarker(chapId); // Update chapter status in sidebar
// Update section link in sidebar if it was an inline exercise
const section = tutorialContent[chapId].sections.find(s => s.exercise && s.exercise.id === exercise.id);
if (section) {
const sectionIndex = tutorialContent[chapId].sections.indexOf(section);
const sectionLink = document.getElementById(`section-link-${chapId}-${sectionIndex}`);
if (sectionLink && !sectionLink.innerHTML.includes('✅')) {
sectionLink.innerHTML = '✅ ' + sectionLink.innerHTML;
}
}
} else {
summaryMessage = '\n\n🤔 Not quite there yet. Review the feedback below and try again!';
}
const detailedFeedback = '\n\n--- CHECK RESULTS ---\n' + feedback.join('\n');
// Prepend the summary and then add the detailed feedback
outputEl.textContent += summaryMessage + detailedFeedback;
}
async function runSolution(solution) {
pyodide.runPython(`
import io, sys
sys.stdout = io.StringIO()
`);
await pyodide.runPythonAsync(solution);
return pyodide.runPython("sys.stdout.getvalue()");
}