Repository navigation
Expand file tree
/
Copy pathdsa-app.js
More file actions
4330 lines (4100 loc) · 180 KB
/
Copy pathdsa-app.js
File metadata and controls
4330 lines (4100 loc) · 180 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
/**
* Code Explorer Data Structures and Algorithms workspace controller.
*
* Chunk 7 completes Tier A with 535 reviewed programs, the shared
* bounded Python worker, trace playback, eighteen evidence-aware learning
* views, prepared input, and non-destructive study comments. All persistence is
* same-origin browser storage. No learner source or derived trace leaves the
* browser through application code.
*/
import { createPythonEditor, EDITOR_FONT_SIZES } from "./shared-editor.js?v=20260728-35";
import { applyTheme, preferredTheme, readLocalText, toggleTheme, writeLocalText } from "./shared-ui.js?v=20260728-35";
import { catalogSearchText, matchesCatalogSearch } from "./catalog-search.js?v=20260728-35";
import {
DSA_AREAS,
DSA_EVIDENCE_LABELS,
DSA_VIEWS,
} from "./dsa-contracts.js?v=20260728-35";
import {
DSA_CHUNK_ONE_PROGRAMS,
DSA_CHUNK_ONE_SECTIONS,
} from "./dsa-curriculum.js?v=20260728-35";
import {
DSA_CHUNK_TWO_PROGRAMS,
DSA_CHUNK_TWO_SECTIONS,
} from "./dsa-curriculum-chunk2.js?v=20260728-35";
import {
DSA_CHUNK_THREE_PROGRAMS,
DSA_CHUNK_THREE_SECTIONS,
} from "./dsa-curriculum-chunk3.js?v=20260728-35";
import {
DSA_CHUNK_FOUR_PROGRAMS,
DSA_CHUNK_FOUR_SECTIONS,
} from "./dsa-curriculum-chunk4.js?v=20260728-35";
import {
DSA_CHUNK_FIVE_PROGRAMS,
DSA_CHUNK_FIVE_SECTIONS,
} from "./dsa-curriculum-chunk5.js?v=20260728-35";
import {
DSA_CHUNK_SIX_PROGRAMS,
DSA_CHUNK_SIX_SECTIONS,
} from "./dsa-curriculum-chunk6.js?v=20260728-35";
import {
DSA_CHUNK_SEVEN_PROGRAMS,
DSA_CHUNK_SEVEN_SECTIONS,
} from "./dsa-curriculum-chunk7.js?v=20260728-35";
import {
DSA_COMMENT_PREFIX,
buildDsaCommentedSource,
classifyDsaEvent,
nearestCondition,
observedConditionOutcome,
serializedLabel,
structureCandidate,
variableChanges,
variableComparisons,
variablesForStep,
} from "./dsa-runtime.js?v=20260728-35";
/** Implemented sections remain in teaching order across committed chunks. */
const DSA_IMPLEMENTED_SECTIONS = Object.freeze([
...DSA_CHUNK_ONE_SECTIONS,
...DSA_CHUNK_TWO_SECTIONS,
...DSA_CHUNK_THREE_SECTIONS,
...DSA_CHUNK_FOUR_SECTIONS,
...DSA_CHUNK_FIVE_SECTIONS,
...DSA_CHUNK_SIX_SECTIONS,
...DSA_CHUNK_SEVEN_SECTIONS,
]);
/** One immutable catalog supports matching, filtering, comparison, and counts. */
const DSA_IMPLEMENTED_PROGRAMS = Object.freeze([
...DSA_CHUNK_ONE_PROGRAMS,
...DSA_CHUNK_TWO_PROGRAMS,
...DSA_CHUNK_THREE_PROGRAMS,
...DSA_CHUNK_FOUR_PROGRAMS,
...DSA_CHUNK_FIVE_PROGRAMS,
...DSA_CHUNK_SIX_PROGRAMS,
...DSA_CHUNK_SEVEN_PROGRAMS,
]);
/**
* Prepared text indexes every reviewed field once instead of flattening 535
* complete records after every keystroke. The index and query stay in memory.
*/
const DSA_PROGRAM_SEARCH_INDEX = new Map(
DSA_IMPLEMENTED_PROGRAMS.map((program) => [program, catalogSearchText(program)]),
);
/** The first reviewed program is the safe source for a learner's first visit. */
const DEFAULT_DSA_CODE = DSA_IMPLEMENTED_PROGRAMS[0].code;
/** Same-origin keys remain separate from the original Python workspace. */
const STORAGE_KEYS = Object.freeze({
source: "code-explorer-dsa-source",
editorPreferences: "code-explorer-dsa-editor-preferences",
activeView: "code-explorer-dsa-active-view",
preparedInputs: "code-explorer-dsa-prepared-inputs",
selectedProgram: "code-explorer-dsa-selected-program",
});
/** Bounded limits protect browser responsiveness and readable displays. */
const LIMITS = Object.freeze({
executionTimeoutMs: 30_000,
structureCells: 30,
watches: 12,
referenceGraphElements: 90,
operationJourneyRows: 30,
algorithmPathSteps: 80,
stepTableRows: 120,
preparedInputCharacters: 20_000,
preparedInputPreviewRows: 30,
comparisonRuns: 2,
comparisonOutputCharacters: 800,
playbackMinimumMs: 100,
});
/** Safe defaults mirror the proven Python editor presentation. */
const DEFAULT_EDITOR_PREFERENCES = Object.freeze({ wrap: true, fontSize: 14 });
/** Cached elements make event wiring and renderer ownership auditable. */
const els = Object.fromEntries(
[
"runtimeStatus", "runtimeLabel", "themeButton", "themeLabel", "dsaExamplesButton",
"dsaLearningCommentsButton", "dsaRunButton", "dsaEditorPanel", "dsaEditor", "dsaEditorShell",
"dsaSelectedProgramQuestion", "dsaSelectedProgramQuestionTitle",
"dsaSelectedProgramQuestionDescription",
"dsaWrapButton", "dsaAutomaticCommentsButton", "dsaAutomaticPreview",
"dsaAutomaticPreviewDocument", "dsaAutomaticLineCount",
"dsaFontSizeSelect", "dsaCopyButton", "dsaPasteButton", "dsaCodeStats",
"dsaAreaNav", "dsaViewTabs", "dsaViewStage", "dsaStepCount",
"dsaPreviousButton", "dsaPlayButton", "dsaNextButton", "dsaRestartButton",
"dsaTimeline", "dsaProgressLabel", "dsaSpeedSelect", "dsaClearOutputButton",
"dsaConsoleOutput", "dsaExamplesDialog",
"dsaCloseExamplesButton", "dsaExampleBrowserBody", "dsaExampleSearchInput",
"dsaExampleFilters", "dsaExampleCount", "dsaExampleGrid", "dsaExamplePreview",
"dsaCommentsDialog", "dsaCloseCommentsButton",
"dsaCommentDetail", "dsaCommentsSummary", "dsaCommentPreview",
"dsaCommentLineCount", "dsaCopyCommentsButton",
"dsaReplaceCommentsButton", "toast",
].map((id) => [id, document.getElementById(id)]),
);
/**
* Workspace state separates persistent presentation and source from session-only
* trace evidence. Comparisons never survive a reload or identify a learner.
*/
const state = {
code: readLocalText(STORAGE_KEYS.source) ?? DEFAULT_DSA_CODE,
editor: null,
editorPreferences: loadEditorPreferences(),
activeView: loadActiveView(),
activeFilter: "All programs",
searchQuery: "",
// Preview selection is temporary catalog navigation, not learner progress.
previewProgramId: "",
activeProgram: null,
preparedInputs: loadPreparedInputs(),
worker: null,
workerReadyPromise: null,
workerReadyResolve: null,
workerReadyReject: null,
runId: 0,
runTimer: null,
running: false,
trace: [],
loops: [],
conditions: [],
error: null,
output: "",
inputLog: [],
learningComments: [],
currentStep: 0,
playbackTimer: null,
automaticCommentsVisible: false,
comparisonRuns: [],
// The exact queue sent to the current worker run supports honest run comparison.
activeRunInputs: "",
toastTimer: null,
suppressEditorInvalidation: false,
// The optional Data reference graph exists only while its view is mounted.
referenceGraphLibrary: null,
referenceGraph: null,
referenceGraphRenderId: 0,
// Algorithm Path uses a separate Cytoscape instance and the same audited library.
algorithmPathGraph: null,
algorithmPathGraphRenderId: 0,
// A reviewed origin identifies the learner's selected question, not progress.
selectedProgramId: readLocalText(STORAGE_KEYS.selectedProgram) || "",
};
/**
* Restores validated editor preferences so malformed storage cannot break setup.
*
* @returns {{wrap: boolean, fontSize: number}} Safe presentation choices.
*/
function loadEditorPreferences() {
try {
const stored = JSON.parse(readLocalText(STORAGE_KEYS.editorPreferences) || "null");
return {
wrap: typeof stored?.wrap === "boolean" ? stored.wrap : DEFAULT_EDITOR_PREFERENCES.wrap,
fontSize: EDITOR_FONT_SIZES.includes(Number(stored?.fontSize))
? Number(stored.fontSize)
: DEFAULT_EDITOR_PREFERENCES.fontSize,
};
} catch (error) {
console.warn("Code Explorer could not parse DSA editor preferences.", error);
return { ...DEFAULT_EDITOR_PREFERENCES };
}
}
/** Saves only wrapping and font size to same-origin storage. */
function saveEditorPreferences() {
writeLocalText(STORAGE_KEYS.editorPreferences, JSON.stringify(state.editorPreferences));
}
/**
* Restores one approved view id or falls back to Algorithm Story.
*
* @returns {string} Valid view id.
*/
function loadActiveView() {
const stored = readLocalText(STORAGE_KEYS.activeView);
return DSA_VIEWS.some((view) => view.id === stored) ? stored : DSA_VIEWS[0].id;
}
/**
* Restores prepared input as bounded plain text.
*
* @returns {string} Locally saved input lines.
*/
function loadPreparedInputs() {
return (readLocalText(STORAGE_KEYS.preparedInputs) || "").slice(0, LIMITS.preparedInputCharacters);
}
/**
* Creates one element without interpreting learner text as HTML.
*
* @param {string} tag HTML tag name.
* @param {string} className Optional CSS classes.
* @param {string} text Optional plain text.
* @returns {HTMLElement} New detached element.
*/
function makeElement(tag, className = "", text = "") {
const element = document.createElement(tag);
if (className) element.className = className;
if (text) element.textContent = text;
return element;
}
/** Shows a temporary accessible status without stealing keyboard focus. */
function showToast(message, isError = false) {
window.clearTimeout(state.toastTimer);
els.toast.textContent = message;
els.toast.classList.toggle("error", isError);
els.toast.classList.add("visible");
state.toastTimer = window.setTimeout(() => els.toast.classList.remove("visible"), 4500);
}
/**
* Updates visible runtime text and non-color readiness state together.
*
* @param {string} text Learner-facing state.
* @param {"idle"|"ready"|"running"|"error"} mode Styling state.
*/
function setRuntimeStatus(text, mode = "idle") {
els.runtimeLabel.textContent = text;
els.runtimeStatus.classList.toggle("ready", mode === "ready");
els.runtimeStatus.classList.toggle("running", mode === "running");
els.runtimeStatus.classList.toggle("error", mode === "error");
}
/** Finds a reviewed record only when the complete source matches exactly. */
function matchingProgram(code = state.editor?.getCode() ?? state.code) {
return DSA_IMPLEMENTED_PROGRAMS.find((program) => program.code === code) || null;
}
/** Returns the locally remembered reviewed question origin when it remains valid. */
function selectedQuestionProgram() {
return DSA_IMPLEMENTED_PROGRAMS.find((program) => program.id === state.selectedProgramId) || null;
}
/**
* Shows the reviewed title and objective above the editor.
*
* The origin survives ordinary edits so the learner does not lose the
* exercise prompt while solving it. Paste and full-document transformations
* clear the origin before this renderer runs.
*/
function renderSelectedProgramQuestion() {
const program = selectedQuestionProgram();
const visible = Boolean(program);
els.dsaSelectedProgramQuestion.classList.toggle("hidden", !visible);
els.dsaEditorPanel.classList.toggle("has-selected-question", visible);
if (!program) {
els.dsaSelectedProgramQuestionTitle.textContent = "";
els.dsaSelectedProgramQuestionDescription.textContent = "";
return;
}
els.dsaSelectedProgramQuestionTitle.textContent = program.title;
els.dsaSelectedProgramQuestionDescription.textContent = program.objective;
}
/** Updates line and character counts from original editable source only. */
function updateCodeStats() {
const code = state.editor?.getCode() ?? state.code;
const lines = code ? code.split("\n").length : 0;
els.dsaCodeStats.textContent = `${lines} line${lines === 1 ? "" : "s"} · ${code.length} chars`;
}
/** Applies wrapping and font size without changing source or trace evidence. */
function applyEditorPreferences() {
els.dsaWrapButton.textContent = state.editorPreferences.wrap ? "Wrap on" : "Wrap off";
els.dsaWrapButton.setAttribute("aria-pressed", String(state.editorPreferences.wrap));
els.dsaWrapButton.title = state.editorPreferences.wrap
? "Turn editor text wrapping off"
: "Turn editor text wrapping on";
els.dsaFontSizeSelect.value = String(state.editorPreferences.fontSize);
state.editor?.applyPreferences(state.editorPreferences);
}
/** Toggles editor wrapping and persists the presentation choice locally. */
function toggleEditorWrapping() {
state.editorPreferences.wrap = !state.editorPreferences.wrap;
saveEditorPreferences();
applyEditorPreferences();
}
/** Applies only one font size exposed by the toolbar. */
function changeEditorFontSize(requestedSize) {
const fontSize = Number(requestedSize);
if (!EDITOR_FONT_SIZES.includes(fontSize)) return;
state.editorPreferences.fontSize = fontSize;
saveEditorPreferences();
applyEditorPreferences();
}
/**
* Copies text with a selection fallback when modern clipboard writing is absent.
*
* @param {string} text Complete text requested by the learner.
* @returns {boolean} Whether the browser reported success.
*/
function copyTextFallback(text) {
const previousFocus = document.activeElement;
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.setAttribute("aria-hidden", "true");
textarea.tabIndex = -1;
textarea.style.position = "fixed";
textarea.style.opacity = "0";
document.body.append(textarea);
textarea.select();
let copied = false;
try {
copied = document.execCommand("copy");
} catch (error) {
console.warn("Code Explorer DSA clipboard fallback failed.", error);
}
textarea.remove();
previousFocus?.focus?.({ preventScroll: true });
return copied;
}
/** Writes requested text after an explicit learner action. */
async function copyText(text, successMessage) {
try {
if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(text);
else if (!copyTextFallback(text)) throw new Error("Clipboard writing is unavailable.");
showToast(successMessage);
} catch (error) {
if (copyTextFallback(text)) {
showToast(successMessage);
return;
}
console.warn("Code Explorer could not copy DSA text.", error);
showToast("Copy was blocked. Select the text and use Ctrl+C instead.", true);
}
}
/** Copies the complete original editor source even when study comments are visible. */
async function copyCompleteEditor() {
const code = state.editor.getCode();
if (!code) {
showToast("The editor is empty. There is nothing to copy.");
return;
}
await copyText(code, `Copied the complete program (${code.split("\n").length} lines).`);
}
/** Replaces the document after the learner deliberately presses Paste. */
async function pasteCompleteEditor() {
try {
if (!navigator.clipboard?.readText) throw new Error("Clipboard reading is unavailable.");
const clipboardText = await navigator.clipboard.readText();
if (!clipboardText) {
showToast("The clipboard contains no text to paste.");
return;
}
replaceEditorSource(clipboardText);
state.editor.focus();
showToast(`Pasted a complete program (${clipboardText.split("\n").length} lines).`);
} catch (error) {
console.warn("Code Explorer could not read DSA clipboard text.", error);
window.alert(
"Clipboard permission is blocked.\n\nAllow clipboard access for this site and try Paste again. You can also focus the editor and press Ctrl+V.",
);
showToast("Paste permission was blocked. Focus the editor and use Ctrl+V instead.", true);
}
}
/**
* Stops playback without changing the selected trace step.
*
* Cytoscape graphs intentionally remain still during automatic playback. A
* deliberate pause or natural completion refreshes the active graph once,
* while source invalidation and new runs suppress the unnecessary refresh.
*
* @param {boolean} [refreshGraphView] Whether a paused graph view should rebuild.
*/
function stopPlayback(refreshGraphView = true) {
const wasPlaying = Boolean(state.playbackTimer);
if (state.playbackTimer) window.clearInterval(state.playbackTimer);
state.playbackTimer = null;
els.dsaPlayButton.textContent = "▶";
els.dsaPlayButton.setAttribute("aria-label", "Play DSA trace");
const graphViews = ["references", "algorithm-path"];
if (wasPlaying && refreshGraphView && graphViews.includes(state.activeView) && state.trace.length) {
window.requestAnimationFrame(() => {
if (!state.playbackTimer && graphViews.includes(state.activeView) && state.trace.length) renderActiveView();
});
}
}
/** Clears trace evidence whenever visible source no longer matches the recording. */
function invalidateTrace() {
stopPlayback(false);
state.trace = [];
state.loops = [];
state.conditions = [];
state.error = null;
state.output = "";
state.inputLog = [];
state.learningComments = [];
state.currentStep = 0;
state.automaticCommentsVisible = false;
renderAutomaticComments();
updatePlaybackControls();
renderActiveView();
resetViewStageScroll();
renderConsole();
}
/** Handles an actual document change from CodeMirror or the fallback editor. */
function handleSourceChange(code) {
state.code = code;
writeLocalText(STORAGE_KEYS.source, code);
state.activeProgram = matchingProgram(code);
updateCodeStats();
if (!state.suppressEditorInvalidation) invalidateTrace();
}
/**
* Replaces source for an explicit catalog, paste, or study-copy action.
*
* @param {string} code Complete replacement source.
* @param {object|null} program Reviewed catalog origin, or null for custom source.
*/
function replaceEditorSource(code, program = null) {
state.suppressEditorInvalidation = true;
state.editor.setCode(code);
state.suppressEditorInvalidation = false;
state.code = code;
writeLocalText(STORAGE_KEYS.source, code);
state.activeProgram = matchingProgram(code);
state.selectedProgramId = program?.id || "";
writeLocalText(STORAGE_KEYS.selectedProgram, state.selectedProgramId);
renderSelectedProgramQuestion();
invalidateTrace();
updateCodeStats();
}
/** Returns the active approved view contract. */
function activeView() {
return DSA_VIEWS.find((view) => view.id === state.activeView) || DSA_VIEWS[0];
}
/**
* Returns a newly selected or newly populated view to its orientation header.
*
* Playback deliberately does not call this helper because a learner comparing
* long state cards should not lose their reading position on every step.
*/
function resetViewStageScroll() {
els.dsaViewStage.scrollTop = 0;
els.dsaViewStage.scrollLeft = 0;
}
/** Selects one approved view and preserves only its id locally. */
function selectView(viewId) {
if (!DSA_VIEWS.some((view) => view.id === viewId)) return;
state.activeView = viewId;
writeLocalText(STORAGE_KEYS.activeView, viewId);
renderAreaNavigation();
renderViewTabs();
renderActiveView();
resetViewStageScroll();
}
/** Renders the four stable areas and their pressed state. */
function renderAreaNavigation() {
const currentArea = activeView().area;
els.dsaAreaNav.replaceChildren(
...DSA_AREAS.map((area) => {
const button = makeElement("button", `learning-mode ${area.id === currentArea ? "active" : ""}`, area.label);
button.type = "button";
button.title = area.question;
button.setAttribute("aria-pressed", String(area.id === currentArea));
button.addEventListener("click", () => {
const firstView = DSA_VIEWS.find((view) => view.area === area.id);
selectView(firstView.id);
});
return button;
}),
);
}
/** Renders only views belonging to the selected learning area. */
function renderViewTabs() {
const current = activeView();
const tabs = DSA_VIEWS.filter((view) => view.area === current.area).map((view) => {
const button = makeElement("button", `panel-tab ${view.id === current.id ? "active" : ""}`, view.label);
button.type = "button";
button.id = `dsa-tab-${view.id}`;
button.setAttribute("role", "tab");
button.setAttribute("aria-selected", String(view.id === current.id));
button.addEventListener("click", () => selectView(view.id));
return button;
});
els.dsaViewTabs.replaceChildren(...tabs);
els.dsaViewStage.setAttribute("aria-labelledby", `dsa-tab-${current.id}`);
}
/** Creates an evidence badge whose text makes color-independent status clear. */
function evidenceBadge(labelKey) {
const label = DSA_EVIDENCE_LABELS[labelKey];
return makeElement("span", `evidence-badge ${labelKey}`, label);
}
/** Shows a stable empty state for a view without sufficient evidence. */
function renderUnavailable(title, text) {
const article = makeElement("article", "dsa-view-preview");
article.append(evidenceBadge("unavailable"));
article.append(makeElement("h2", "", title));
article.append(makeElement("p", "", text));
els.dsaViewStage.replaceChildren(article);
}
/** Returns the selected step or null when no runtime snapshot exists. */
function selectedStep() {
return state.trace[state.currentStep] || null;
}
/**
* Returns the safest learner-facing program name for a Trace view.
*
* Exact reviewed context is intentionally required before a catalog title can
* appear inside a runtime explanation. The separately persisted selected
* question may survive edits for orientation, but it must not restore reviewed
* evidence after the source changes.
*
* @returns {string} Exact reviewed title or an honest custom-source label.
*/
function traceProgramLabel() {
return state.activeProgram?.title || "Edited or pasted program";
}
/**
* Builds the shared orientation header used by all five redesigned Trace views.
*
* This helper owns only presentation. Callers still decide which evidence may
* be shown. The returned body remains empty so each view can use a visual
* grammar appropriate to its own teaching question.
*
* @param {object} options Trace-view presentation options.
* @param {string} options.viewId Stable view identifier used by scoped CSS.
* @param {string} options.title Learner-facing view title.
* @param {string} options.question Short question the view helps answer.
* @param {object|null} [options.step] Recorded step represented by the view.
* @param {number} [options.stepIndex] Zero-based index for the represented step.
* @param {string} [options.eventLabel] Optional normalized event or state.
* @param {"observed"|"curriculum"|"unavailable"} [options.evidence] Evidence badge.
* @returns {{article: HTMLElement, body: HTMLElement}} View shell and content mount.
*/
function createTraceViewShell({
viewId,
title,
question,
step = selectedStep(),
stepIndex = state.currentStep,
eventLabel = "",
evidence = "observed",
}) {
const article = makeElement("article", `dsa-runtime-view dsa-trace-view dsa-trace-${viewId}`);
const hero = makeElement("header", "dsa-trace-hero");
const identity = makeElement("div", "dsa-trace-identity");
const eyebrow = makeElement("div", "dsa-trace-eyebrow");
eyebrow.append(evidenceBadge(evidence));
eyebrow.append(makeElement("span", "", `TRACE / ${title.toUpperCase()}`));
identity.append(eyebrow);
identity.append(makeElement("h2", "", title));
identity.append(makeElement("p", "", question));
hero.append(identity);
if (step) {
const context = makeElement("section", "dsa-trace-context");
const contextFacts = [
["Program", traceProgramLabel()],
["Recorded step", `${stepIndex + 1} of ${state.trace.length}`],
["Source line", String(step.line)],
];
if (eventLabel) contextFacts.push(["Event", eventLabel]);
contextFacts.forEach(([label, value]) => {
const fact = makeElement("div", "dsa-trace-context-fact");
fact.append(makeElement("span", "", label));
fact.append(makeElement("strong", "", value));
context.append(fact);
});
hero.append(context);
hero.append(makeElement("code", "dsa-trace-source", step.source.trim()));
}
const body = makeElement("div", "dsa-trace-body");
article.append(hero, body);
return { article, body };
}
/**
* Renders a designed pre-run or unavailable state for one Trace view.
*
* @param {object} options Empty-state content.
* @param {string} options.viewId Stable view identifier.
* @param {string} options.glyph Compact technical symbol hidden from assistive technology.
* @param {string} options.title View title.
* @param {string} options.question Question the view will answer after a run.
* @param {string} options.reason Honest reason evidence is unavailable.
* @param {Array<string>} options.steps Safe learner actions.
*/
function renderTraceUnavailable({ viewId, glyph, title, question, reason, steps }) {
const { article, body } = createTraceViewShell({
viewId,
title,
question,
step: null,
evidence: "unavailable",
});
const empty = makeElement("section", "dsa-trace-empty-state");
const mark = makeElement("span", "dsa-trace-empty-glyph", glyph);
mark.setAttribute("aria-hidden", "true");
empty.append(mark);
empty.append(makeElement("h3", "", reason));
const list = makeElement("ol", "dsa-trace-next-steps");
steps.forEach((step) => list.append(makeElement("li", "", step)));
empty.append(list);
body.append(empty);
els.dsaViewStage.replaceChildren(article);
}
/**
* Classifies a trace step using only the adjacent recorded snapshot.
*
* @param {number} index Zero-based trace index.
* @returns {{changes: Array<object>, event: {type: string, explanation: string}}} Evidence pair.
*/
function storyEvidenceAt(index) {
const current = state.trace[index];
const previous = state.trace[index - 1] || null;
const changes = variableChanges(previous, current);
return { changes, event: classifyDsaEvent(current, changes) };
}
/** Renders Algorithm Story as a navigable recorded timeline plus reviewed map. */
function renderAlgorithmStory() {
const step = selectedStep();
if (!step) {
renderTraceUnavailable({
viewId: "story",
glyph: "01",
title: "Algorithm Story",
question: "What did Python do, and where are we in the recorded journey?",
reason: "Run a trace to turn executed lines into a visual story.",
steps: [
"Choose a reviewed example or keep your own source.",
"Run the program locally in the browser.",
"Use playback to move through the recorded story.",
],
});
return;
}
const { changes, event } = storyEvidenceAt(state.currentStep);
const { article, body } = createTraceViewShell({
viewId: "story",
title: "Algorithm Story",
question: "What did Python do, and where are we in the recorded journey?",
eventLabel: event.type,
});
/*
Five entries provide immediate chronological context without rendering the
complete trace. Later entries are already recorded evidence, but their
labels avoid implying that Python has not executed them yet.
*/
const storyStart = Math.max(0, state.currentStep - 2);
const storyEnd = Math.min(state.trace.length, state.currentStep + 3);
const timeline = makeElement("ol", "dsa-story-timeline");
for (let index = storyStart; index < storyEnd; index += 1) {
const timelineStep = state.trace[index];
const timelineEvidence = storyEvidenceAt(index);
const item = makeElement("li", `dsa-story-entry ${index === state.currentStep ? "current" : ""}`);
const jump = makeElement("button", "", "");
jump.type = "button";
if (index === state.currentStep) jump.setAttribute("aria-current", "step");
jump.setAttribute("aria-label", `Go to recorded step ${index + 1}, line ${timelineStep.line}`);
const marker = makeElement("span", "dsa-story-marker", String(index + 1).padStart(2, "0"));
const copy = makeElement("span", "dsa-story-entry-copy");
copy.append(makeElement("strong", "", timelineEvidence.event.type.replaceAll("_", " ")));
copy.append(makeElement("code", "", timelineStep.source.trim()));
const position = index < state.currentStep
? "Earlier recorded step"
: index > state.currentStep
? "Later recorded step"
: "Selected step";
copy.append(makeElement("span", "", `Line ${timelineStep.line} · ${position}`));
jump.append(marker, copy);
jump.addEventListener("click", () => selectStep(index));
item.append(jump);
timeline.append(item);
}
const observed = makeElement("section", "dsa-story-observation");
const observationHeading = makeElement("div", "dsa-trace-section-heading");
observationHeading.append(makeElement("span", "", "CURRENT OBSERVATION"));
observationHeading.append(makeElement("strong", "", event.type.replaceAll("_", " ")));
observed.append(observationHeading);
observed.append(makeElement("p", "", event.explanation));
if (changes.length) {
const changeList = makeElement("div", "dsa-story-change-list");
changes.forEach((change) => {
const changeItem = makeElement("div", `dsa-story-change ${change.kind}`);
changeItem.append(makeElement("span", "", change.kind));
changeItem.append(makeElement("strong", "", change.name));
changeItem.append(makeElement(
"code",
"",
`${serializedLabel(change.before)} → ${serializedLabel(change.after)}`,
));
changeList.append(changeItem);
});
observed.append(changeList);
} else {
observed.append(makeElement("p", "dsa-trace-quiet-note", "No visible serialized value changed after this line."));
}
const observedGrid = makeElement("div", "dsa-story-grid");
observedGrid.append(timeline, observed);
body.append(observedGrid);
if (state.activeProgram) {
const context = makeElement("section", "dsa-story-curriculum");
const curriculumHeading = makeElement("div", "dsa-trace-section-heading");
curriculumHeading.append(evidenceBadge("curriculum"));
curriculumHeading.append(makeElement("strong", "", state.activeProgram.algorithm));
context.append(curriculumHeading);
context.append(makeElement("p", "", state.activeProgram.objective));
const phases = makeElement("ol", "dsa-story-phase-map");
state.activeProgram.phases.forEach((phase, index) => {
const phaseItem = makeElement("li", "");
phaseItem.append(makeElement("span", "", String(index + 1).padStart(2, "0")));
phaseItem.append(makeElement("p", "", phase));
phases.append(phaseItem);
});
context.append(phases);
context.append(makeElement("p", "dsa-trace-boundary", "This is the reviewed full-program map. Code Explorer does not guess which named phase owns the selected line."));
body.append(context);
} else {
const boundary = makeElement("section", "dsa-trace-boundary-card");
boundary.append(evidenceBadge("unavailable"));
boundary.append(makeElement("strong", "", "Named algorithm unavailable"));
boundary.append(makeElement("p", "", "The executed line and value changes are observed. A reviewed algorithm name and phase are unavailable because this source is not an unchanged catalog program."));
body.append(boundary);
}
els.dsaViewStage.replaceChildren(article);
}
/**
* Renders the complete visible variable state around the selected trace step.
*
* The list is intentionally cumulative rather than limited to values changed by
* one line. As playback advances, names enter or leave the vertical list when
* they enter or leave the recorded scope. This mirrors the state-reading model
* in the Python workspace and lets a learner keep positional context between
* steps. The change classification still comes only from adjacent snapshots.
*/
function renderBeforeAfter() {
const step = selectedStep();
if (!step) {
renderTraceUnavailable({
viewId: "before-after",
glyph: "↕",
title: "Before and After",
question: "Which visible values existed before this line, and what was recorded after it?",
reason: "Run a trace to compare adjacent recorded states.",
steps: [
"Run a program that creates or changes a value.",
"Move one step at a time with playback.",
"Read each variable from Before down to After.",
],
});
return;
}
const previous = state.trace[state.currentStep - 1] || null;
const comparisons = variableComparisons(previous, step);
const { article, body } = createTraceViewShell({
viewId: "before-after",
title: "Before and After",
question: "Which visible values existed before this line, and what was recorded after it?",
eventLabel: "STATE COMPARISON",
});
const kinds = ["created", "changed", "removed", "unchanged"];
const summary = makeElement("section", "dsa-state-summary");
kinds.forEach((kind) => {
const metric = makeElement("div", `dsa-state-metric ${kind}`);
metric.append(makeElement("strong", "", String(comparisons.filter((item) => item.kind === kind).length)));
metric.append(makeElement("span", "", kind));
summary.append(metric);
});
body.append(summary);
if (!comparisons.length) {
const empty = makeElement("section", "dsa-trace-inline-empty");
empty.append(makeElement("strong", "", "No visible variables at this step"));
empty.append(makeElement("p", "", "The line executed, but no serialized learner variable is visible in the recorded scopes."));
body.append(empty);
} else {
const grid = makeElement("div", "dsa-change-grid");
comparisons.forEach((change) => {
// The pure helper retains unchanged values so playback keeps positional context.
const card = makeElement("section", `dsa-change-card ${change.kind}`);
const header = makeElement("div", "dsa-change-card-header");
header.append(makeElement("strong", "", change.name));
header.append(makeElement("span", "dsa-change-kind", change.kind));
const before = makeElement("div", "dsa-change-state before");
before.append(makeElement("span", "", "Before"));
before.append(makeElement("code", "", serializedLabel(change.before)));
const direction = makeElement("span", "dsa-change-direction", "↓");
direction.setAttribute("aria-hidden", "true");
const after = makeElement("div", "dsa-change-state after");
after.append(makeElement("span", "", "After"));
after.append(makeElement("code", "", serializedLabel(change.after)));
card.append(header, before, direction, after);
const visibleType = change.after?.type || change.before?.type;
if (visibleType) card.append(makeElement("span", "dsa-change-type", `Recorded type: ${visibleType}`));
grid.append(card);
});
body.append(grid);
}
els.dsaViewStage.replaceChildren(article);
}
/** Renders the nearest observed branch route without reevaluating its expression. */
function renderDecisions() {
if (!state.trace.length) {
renderTraceUnavailable({
viewId: "decisions",
glyph: "?",
title: "Decisions",
question: "Which recorded route followed a condition or while check?",
reason: "Run a condition or while loop to reveal an observed route.",
steps: [
"Run a program containing if, elif, or while.",
"Move playback beyond the condition.",
"Inspect the result and next recorded source line.",
],
});
return;
}
const found = nearestCondition(state.trace, state.currentStep, state.conditions, state.loops);
if (!found) {
renderTraceUnavailable({
viewId: "decisions",
glyph: "?",
title: "Decisions",
question: "Which recorded route followed a condition or while check?",
reason: "No condition has been reached by the selected step.",
steps: [
"Continue playback until Python reaches a condition.",
"Look for an if, elif, or while line in the editor.",
"Return here when the selected trace prefix includes that line.",
],
});
return;
}
const outcome = observedConditionOutcome(found.step, state.conditions, state.loops);
const decisionIndex = state.trace.lastIndexOf(found.step);
const conditionSource = found.metadata.source || found.step.source.trim();
const resultLabel = outcome === null ? "Result unavailable" : outcome ? "True" : "False";
const nextLine = found.step.nextLine || null;
const nextSource = nextLine ? state.code.split("\n")[nextLine - 1]?.trim() : "";
const { article, body } = createTraceViewShell({
viewId: "decisions",
title: "Decisions",
question: "Which recorded route followed a condition or while check?",
step: found.step,
stepIndex: decisionIndex,
eventLabel: "CONDITION CHECK",
});
const route = makeElement("section", "dsa-decision-route");
const conditionNode = makeElement("div", "dsa-decision-node condition");
conditionNode.append(makeElement("span", "", "CONDITION"));
conditionNode.append(makeElement("code", "", conditionSource));
const connectorOne = makeElement("div", "dsa-decision-connector", "↓");
connectorOne.setAttribute("aria-hidden", "true");
const resultNode = makeElement(
"div",
`dsa-decision-node result ${outcome === true ? "true" : outcome === false ? "false" : "unknown"}`,
);
resultNode.append(makeElement("span", "", "OBSERVED RESULT"));
resultNode.append(makeElement("strong", "", resultLabel));
const connectorTwo = makeElement("div", "dsa-decision-connector", "↓");
connectorTwo.setAttribute("aria-hidden", "true");
const destination = makeElement("div", "dsa-decision-node destination");
destination.append(makeElement("span", "", "NEXT RECORDED LINE"));
destination.append(makeElement("strong", "", nextLine ? `Line ${nextLine}` : "Could not isolate safely"));
if (nextSource) destination.append(makeElement("code", "", nextSource));
route.append(conditionNode, connectorOne, resultNode, connectorTwo, destination);
body.append(route);
const visibleValues = Object.entries(variablesForStep(found.step))
.filter(([, value]) => !["function", "module", "type"].includes(value?.type))
.slice(0, 6);
const evidence = makeElement("section", "dsa-decision-evidence");
const evidenceHeading = makeElement("div", "dsa-trace-section-heading");
evidenceHeading.append(makeElement("span", "", "VISIBLE VALUES AT THE CHECK"));
evidenceHeading.append(makeElement("strong", "", `${visibleValues.length} shown`));
evidence.append(evidenceHeading);
if (visibleValues.length) {
const values = makeElement("div", "dsa-decision-values");
visibleValues.forEach(([name, value]) => {
const item = makeElement("div", "");
item.append(makeElement("span", "", name));
item.append(makeElement("code", "", serializedLabel(value)));
values.append(item);
});
evidence.append(values);
} else {
evidence.append(makeElement("p", "dsa-trace-quiet-note", "No serialized learner value was visible at this check."));
}
evidence.append(makeElement("p", "dsa-trace-boundary", "These values were visible in scope. Code Explorer does not claim that every value shown was an operand in the condition."));
body.append(evidence);
els.dsaViewStage.replaceChildren(article);
}
/** Renders the recorded user-code frame stack and return evidence. */
function renderCalls() {
const step = selectedStep();
if (!step) {
renderTraceUnavailable({
viewId: "calls",
glyph: "ƒ",
title: "Calls and Recursion",
question: "Which function frames exist, and which frame is active now?",
reason: "Run a program with a function to reveal its recorded call stack.",
steps: [
"Choose a function or recursion example.",
"Run the trace and move into the function body.",
"Watch frames appear and disappear as playback moves.",
],
});
return;
}
const frames = step.frames || [];
const activeFrame = frames.at(-1) || null;
const { article, body } = createTraceViewShell({
viewId: "calls",
title: "Calls and Recursion",
question: "Which function frames exist, and which frame is active now?",
eventLabel: step.event === "return" ? "RETURN" : "FRAME SNAPSHOT",
});
const metrics = makeElement("section", "dsa-call-metrics");
const depthMetric = makeElement("div", "");
depthMetric.append(makeElement("strong", "", String(Math.max(0, frames.length - 1))));
depthMetric.append(makeElement("span", "", "function depth"));
const activeMetric = makeElement("div", "");