forked from RunestoneInteractive/RunestoneComponents
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathactivecode.js
executable file
·1440 lines (1386 loc) · 53.1 KB
/
activecode.js
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
/**
*
* Created by bmiller on 3/19/15.
*/
/* Define global variables for ESLint */
/* global Sk */
"use strict";
import RunestoneBase from "../../common/js/runestonebase.js";
import AudioTour from "./audiotour.js";
import "./activecode-i18n.en.js";
import "./activecode-i18n.pt-br.js";
import "./activecode-i18n.sr-Cyrl.js";
import CodeMirror from "codemirror";
import "codemirror/mode/python/python.js";
import "codemirror/mode/css/css.js";
import "codemirror/mode/htmlmixed/htmlmixed.js";
import "codemirror/mode/xml/xml.js";
import "codemirror/mode/javascript/javascript.js";
import "codemirror/mode/sql/sql.js";
import "codemirror/mode/clike/clike.js";
import "codemirror/mode/octave/octave.js";
import "./../css/activecode.css";
import "codemirror/lib/codemirror.css";
import "./skulpt.min.js";
import "./skulpt-stdlib.js";
// Used by Skulpt.
import embed from "vega-embed";
// Adapt for use outside webpack -- see https://github.com/vega/vega-embed.
window.vegaEmbed = embed;
var isMouseDown = false;
document.onmousedown = function () {
isMouseDown = true;
};
document.onmouseup = function () {
isMouseDown = false;
};
window.edList = {};
var socket, connection, doc;
var chatcodesServer = "chat.codes";
// separate into constructor and init
export class ActiveCode extends RunestoneBase {
constructor(opts) {
super(opts);
var suffStart;
var orig = $(opts.orig).find("textarea")[0];
this.containerDiv = opts.orig;
this.useRunestoneServices = opts.useRunestoneServices;
this.python3 = opts.python3;
this.alignVertical = opts.vertical;
this.origElem = orig;
this.origText = this.origElem.textContent;
this.divid = opts.orig.id;
this.code = $(orig).text() || "\n\n\n\n\n";
this.language = $(orig).data("lang");
this.timelimit = $(orig).data("timelimit");
this.includes = $(orig).data("include");
this.hidecode = $(orig).data("hidecode");
this.chatcodes = $(orig).data("chatcodes");
this.hidehistory = $(orig).data("hidehistory");
this.question = $(opts.orig).find(`#${this.divid}_question`)[0];
this.tie = $(orig).data("tie");
this.dburl = $(orig).data("dburl");
this.python3_interpreter = $(orig).data("python3_interpreter");
this.runButton = null;
this.enabledownload = $(orig).data("enabledownload");
this.downloadButton = null;
this.resetButton = null;
this.saveButton = null;
this.loadButton = null;
this.outerDiv = null;
this.partner = "";
this.logResults = true;
if (!eBookConfig.allow_pairs || $(orig).data("nopair")) {
this.enablePartner = false;
} else {
this.enablePartner = true;
}
this.output = null; // create pre for output
this.graphics = null; // create div for turtle graphics
this.codecoach = null;
this.codelens = null;
this.controlDiv = null;
this.historyScrubber = null;
this.timestamps = ["Original"];
this.autorun = $(orig).data("autorun");
if (this.chatcodes && eBookConfig.enable_chatcodes) {
if (!socket) {
socket = new WebSocket("wss://" + chatcodesServer);
}
if (!connection) {
connection = new window.sharedb.Connection(socket);
}
if (!doc) {
doc = connection.get("chatcodes", "channels");
}
}
if (this.graderactive || this.isTimed) {
this.hidecode = false;
}
if (this.includes) {
this.includes = this.includes.split(/\s+/);
}
let prefixEnd = this.code.indexOf("^^^^");
if (prefixEnd > -1) {
this.prefix = this.code.substring(0, prefixEnd);
this.code = this.code.substring(prefixEnd + 5);
}
suffStart = this.code.indexOf("====");
if (suffStart > -1) {
this.suffix = this.code.substring(suffStart + 5);
this.code = this.code.substring(0, suffStart);
}
this.history = [this.code];
this.createEditor();
this.createOutput();
this.createControls();
if ($(orig).data("caption")) {
this.caption = $(orig).data("caption");
} else {
this.caption = "ActiveCode";
}
this.addCaption("runestone");
setTimeout(
function () {
this.editor.refresh();
}.bind(this),
1000
);
if (this.autorun) {
// Simulate pressing the run button, since this will also prevent the user from clicking it until the initial run is complete, and also help the user understand why they're waiting.
$(document).ready(this.runButtonHandler.bind(this));
}
this.indicate_component_ready();
}
createEditor(index) {
this.outerDiv = document.createElement("div");
var linkdiv = document.createElement("div");
linkdiv.id = this.divid.replace(/_/g, "-").toLowerCase(); // :ref: changes _ to - so add this as a target
$(this.outerDiv).addClass("ac_section alert alert-warning");
var codeDiv = document.createElement("div");
$(codeDiv).addClass("ac_code_div col-md-12");
this.codeDiv = codeDiv;
this.outerDiv.lang = this.language;
$(this.origElem).replaceWith(this.outerDiv);
if (linkdiv.id !== this.divid) {
// Don't want the 'extra' target if they match.
this.outerDiv.appendChild(linkdiv);
}
this.outerDiv.appendChild(codeDiv);
var edmode = this.outerDiv.lang;
if (edmode === "sql") {
edmode = "text/x-sql";
} else if (edmode === "java") {
edmode = "text/x-java";
} else if (edmode === "cpp") {
edmode = "text/x-c++src";
} else if (edmode === "c") {
edmode = "text/x-csrc";
} else if (edmode === "python3") {
edmode = "python";
} else if (edmode === "octave" || edmode === "MATLAB") {
edmode = "text/x-octave";
}
if(localStorage.getItem(this.divid) !== null)
this.code = localStorage.getItem(this.divid);
var opts = {
value: this.code,
lineNumbers: true,
mode: edmode,
indentUnit: 4,
matchBrackets: true,
autoMatchParens: true,
extraKeys: {
Tab: "indentMore",
"Shift-Tab": "indentLess",
},
}
var editor = CodeMirror(codeDiv,opts );
// Make the editor resizable
$(editor.getWrapperElement()).resizable({
resize: function () {
editor.setSize($(this).width(), $(this).height());
editor.refresh();
},
});
// give the user a visual cue that they have changed but not saved
editor.on(
"change",
function (ev) {
if (
editor.acEditEvent == false ||
editor.acEditEvent === undefined
) {
// change events can come before any real changes for various reasons, some unknown
// this avoids unneccsary log events and updates to the activity counter
if (this.origText === editor.getValue()) {
return;
}
$(editor.getWrapperElement()).css(
"border-top",
"2px solid #b43232"
);
$(editor.getWrapperElement()).css(
"border-bottom",
"2px solid #b43232"
);
this.isAnswered = true;
this.logBookEvent({
event: "activecode",
act: "edit",
div_id: this.divid,
});
}
editor.acEditEvent = true;
}.bind(this)
); // use bind to preserve *this* inside the on handler.
//Solving Keyboard Trap of ActiveCode: If user use tab for navigation outside of ActiveCode, then change tab behavior in ActiveCode to enable tab user to tab out of the textarea
$(window).keydown(function (e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 9 && $("textarea:focus").length === 0) {
editor.setOption("extraKeys", {
Tab: function (cm) {
$(document.activeElement)
.closest(".tab-content")
.nextSibling.focus();
},
"Shift-Tab": function (cm) {
$(document.activeElement)
.closest(".tab-content")
.previousSibling.focus();
},
});
}
});
this.editor = editor;
if (this.hidecode) {
$(this.codeDiv).css("display", "none");
}
}
async runButtonHandler() {
// Disable the run button until the run is finished.
this.runButton.disabled = true;
try {
await this.runProg();
} catch (e) {
console.log(`there was an error ${e} running the code`);
}
if (this.logResults) {
this.logCurrentAnswer();
}
this.renderFeedback();
// The run is finished; re-enable the button.
this.runButton.disabled = false;
}
createControls() {
var ctrlDiv = document.createElement("div");
var butt;
$(ctrlDiv).addClass("ac_actions");
$(ctrlDiv).addClass("col-md-12");
// Run
butt = document.createElement("button");
$(butt).text($.i18n("msg_activecode_run_code"));
$(butt).addClass("btn btn-success run-button");
ctrlDiv.appendChild(butt);
this.runButton = butt;
console.log("adding click function for run");
this.runButton.onclick = this.runButtonHandler.bind(this);
$(butt).attr("type", "button");
this.addResetButton(ctrlDiv);
if (this.enabledownload || eBookConfig.downloadsEnabled) {
this.addDownloadButton(ctrlDiv);
}
if (!this.hidecode && !this.hidehistory) {
this.addHistoryButton(ctrlDiv);
}
if ($(this.origElem).data("gradebutton") && !this.graderactive) {
this.addFeedbackButton(ctrlDiv);
}
// Show/Hide Code
if (this.hidecode) {
this.enableHideShow(ctrlDiv);
}
// CodeLens
if ($(this.origElem).data("codelens") && !this.graderactive) {
this.enableCodeLens(ctrlDiv);
}
// Audio Tour
if ($(this.origElem).data("audio")) {
this.enableAudioTours(ctrlDiv);
}
if (eBookConfig.isInstructor) {
this.enableInstructorSharing(ctrlDiv);
}
if (this.enablePartner) {
this.setupPartner(ctrlDiv);
}
if (this.chatcodes && eBookConfig.enable_chatcodes) {
this.enableChatCodes(ctrlDiv);
}
$(this.outerDiv).prepend(ctrlDiv);
if (this.question) {
if ($(this.question).html().match(/^\s+$/)) {
$(this.question).remove();
} else {
$(this.outerDiv).prepend(this.question);
}
}
this.controlDiv = ctrlDiv;
}
addFeedbackButton(ctrlDiv) {
let butt = document.createElement("button");
$(butt).addClass("ac_opt btn btn-default");
$(butt).text($.i18n("msg_activecode_show_feedback"));
$(butt).css("margin-left", "10px");
$(butt).attr("type", "button");
this.gradeButton = butt;
ctrlDiv.appendChild(butt);
$(butt).click(this.createGradeSummary.bind(this));
}
addHistoryButton(ctrlDiv) {
let butt = document.createElement("button");
$(butt).text($.i18n("msg_activecode_load_history"));
$(butt).addClass("btn btn-default");
$(butt).attr("type", "button");
ctrlDiv.appendChild(butt);
this.histButton = butt;
$(butt).click(this.addHistoryScrubber.bind(this));
if (this.graderactive) {
this.addHistoryScrubber(true);
}
}
addDownloadButton(ctrlDiv) {
let butt = document.createElement("button");
$(butt).text("Download");
$(butt).addClass("btn save-button");
ctrlDiv.appendChild(butt);
this.downloadButton = butt;
$(butt).click(this.downloadFile.bind(this, this.language));
$(butt).attr("type", "button");
}
addResetButton(ctrlDiv) {
let butt = document.createElement("button");
$(butt).text("Reset");
$(butt).addClass("btn btn-default");
$(butt).attr("type", "button");
ctrlDiv.appendChild(butt);
this.resetButton = butt;
$(butt).click(this.resetCode.bind(this));
}
enableHideShow(ctrlDiv) {
$(this.runButton).attr("disabled", "disabled");
let butt = document.createElement("button");
$(butt).addClass("ac_opt btn btn-default");
$(butt).text($.i18n("msg_activecode_show_code"));
$(butt).css("margin-left", "10px");
$(butt).attr("type", "button");
this.showHideButt = butt;
ctrlDiv.appendChild(butt);
$(butt).click(
function () {
$(this.codeDiv).toggle();
if (this.historyScrubber == null) {
this.addHistoryScrubber(true);
} else {
$(this.historyScrubber.parentElement).toggle();
}
if (
$(this.showHideButt).text() ==
$.i18n("msg_activecode_show_code")
) {
$(this.showHideButt).text(
$.i18n("msg_activecode_hide_code")
);
} else {
$(this.showHideButt).text(
$.i18n("msg_activecode_show_code")
);
}
if ($(this.runButton).attr("disabled")) {
$(this.runButton).removeAttr("disabled");
} else {
$(this.runButton).attr("disabled", "disabled");
}
}.bind(this)
);
}
enableCodeLens(ctrlDiv) {
let butt = document.createElement("button");
$(butt).addClass("ac_opt btn btn-default");
$(butt).text($.i18n("msg_activecode_show_codelens"));
$(butt).css("margin-left", "10px");
this.clButton = butt;
ctrlDiv.appendChild(butt);
$(butt).click(this.showCodelens.bind(this));
}
enableAudioTours(ctrlDiv) {
let butt = document.createElement("button");
$(butt).addClass("ac_opt btn btn-default");
$(butt).text($.i18n("msg_activecode_audio_tour"));
$(butt).css("margin-left", "10px");
this.atButton = butt;
ctrlDiv.appendChild(butt);
$(butt).click(
function () {
new AudioTour(
this.divid,
this.code,
1,
$(this.origElem).data("audio")
);
}.bind(this)
);
}
enableInstructorSharing(ctrlDiv) {
let butt = document.createElement("button");
$(butt).addClass("btn btn-info");
$(butt).text("Share Code");
$(butt).css("margin-left", "10px");
this.shareButt = butt;
ctrlDiv.appendChild(butt);
$(butt).click(
async function () {
if (
!confirm(
"You are about to share this code with ALL of your students. Are you sure you want to continue?"
)
) {
return;
}
let data = {
divid: this.divid,
code: this.editor.getValue(),
lang: this.language,
};
let request = new Request(
eBookConfig.ajaxURL + "broadcast_code.json",
{
method: "POST",
headers: this.jsonHeaders,
body: JSON.stringify(data),
}
);
let post_promise = await fetch(request);
let status = await post_promise.json();
if (status.mess === "success") {
alert(`Shared Code with ${status.share_count} students`);
} else {
alert("Sharing Failed");
}
}.bind(this)
);
}
setupPartner(ctrlDiv) {
var checkPartner = document.createElement("input");
checkPartner.type = "checkbox";
checkPartner.id = `${this.divid}_part`;
ctrlDiv.appendChild(checkPartner);
var plabel = document.createElement("label");
plabel.for = `${this.divid}_part`;
$(plabel).text("Pair?");
ctrlDiv.appendChild(plabel);
$(checkPartner).click(
function () {
if (this.partner) {
this.partner = false;
$(partnerTextBox).hide();
this.partner = "";
partnerTextBox.value = "";
$(plabel).text("Pair?");
} else {
let didAgree = localStorage.getItem("partnerAgree");
if (!didAgree) {
didAgree = confirm(
"Pair Programming should only be used with the consent of your instructor." +
"Your partner must be a registered member of the class and have agreed to pair with you." +
"By clicking OK you certify that both of these conditions have been met."
);
if (didAgree) {
localStorage.setItem("partnerAgree", "true");
} else {
return;
}
}
this.partner = true;
$(plabel).text("with: ");
$(partnerTextBox).show();
}
}.bind(this)
);
var partnerTextBox = document.createElement("input");
partnerTextBox.type = "text";
ctrlDiv.appendChild(partnerTextBox);
$(partnerTextBox).hide();
$(partnerTextBox).change(
function () {
this.partner = partnerTextBox.value;
}.bind(this)
);
}
// This is probably obsolete. Not sure if anyone at Michigan will come back
// to working on this again.
enableChatCodes(ctrlDiv) {
var chatBar = document.createElement("div");
var channels = document.createElement("span");
var topic = window.location.host + "-" + this.divid;
ctrlDiv.appendChild(chatBar);
$(chatBar).text("Chat: ");
$(chatBar).append(channels);
let butt = document.createElement("a");
$(butt).addClass("ac_opt btn btn-default");
$(butt).text("Create Channel");
$(butt).css("margin-left", "10px");
$(butt).attr("type", "button");
$(butt).attr("target", "_blank");
$(butt).attr(
"href",
"http://" +
chatcodesServer +
"/new?" +
$.param({
topic: window.location.host + "-" + this.divid,
code: this.editor.getValue(),
lang: "Python",
})
);
this.chatButton = butt;
chatBar.appendChild(butt);
var updateChatCodesChannels = function () {
var data = doc.data;
var i = 1;
$(channels).html("");
data["channels"].forEach(function (channel) {
if (!channel.archived && topic === channel.topic) {
var link = $("<a />");
var href =
"http://" + chatcodesServer + "/" + channel.channelName;
link.attr({
href: href,
target: "_blank",
});
link.text(" " + channel.channelName + "(" + i + ") ");
$(channels).append(link);
i++;
}
});
if (i === 1) {
$(channels).text("(no active converstations on this problem)");
}
};
doc.subscribe(updateChatCodesChannels);
doc.on("op", updateChatCodesChannels);
}
enableSaveLoad() {
$(this.runButton).text($.i18n("msg_activecode_save_run"));
}
// Activecode -- If the code has not changed wrt the scrubber position value then don't save the code or reposition the scrubber
// -- still call runlog, but add a parameter to not save the code
// add an initial load history button
// if there is no edit then there is no append to_save (True/False)
async addHistoryScrubber(pos_last) {
let response;
var reqData = {
acid: this.divid,
};
if (this.sid !== undefined) {
reqData["sid"] = this.sid;
}
console.log("before get hist");
if (
eBookConfig.practice_mode ||
(this.isTimed && !this.assessmentTaken)
) {
// If this is timed and already taken we should restore history info
this.renderScrubber();
} else {
let request = new Request(eBookConfig.ajaxURL + "gethist.json", {
method: "POST",
headers: this.jsonHeaders,
body: JSON.stringify(reqData),
});
try {
response = await fetch(request);
let data = await response.json();
if (data.history !== undefined) {
this.history = this.history.concat(data.history);
for (let t in data.timestamps) {
this.timestamps.push(
new Date(data.timestamps[t]).toLocaleString()
);
}
}
} catch (e) {
console.log("unable to fetch history");
}
this.renderScrubber(pos_last);
}
return "success";
}
renderScrubber(pos_last) {
console.log("making a new scrubber");
var scrubberDiv = document.createElement("div");
$(scrubberDiv).css("display", "inline-block");
$(scrubberDiv).css("margin-left", "10px");
$(scrubberDiv).css("margin-right", "10px");
$(scrubberDiv).css({
"min-width": "200px",
"max-width": "300px",
});
var scrubber = document.createElement("div");
this.timestampP = document.createElement("span");
this.slideit = function () {
this.editor.setValue(this.history[$(scrubber).slider("value")]);
var curVal = this.timestamps[$(scrubber).slider("value")];
let pos = $(scrubber).slider("value");
let outOf = this.history.length;
$(this.timestampP).text(`${curVal} - ${pos + 1} of ${outOf}`);
this.logBookEvent({
event: "activecode",
act: "slide:" + curVal,
div_id: this.divid,
});
};
$(scrubber).slider({
max: this.history.length - 1,
value: this.history.length - 1,
});
$(scrubber).css("margin", "10px");
$(scrubber).on("slide", this.slideit.bind(this));
$(scrubber).on("slidechange", this.slideit.bind(this));
scrubberDiv.appendChild(scrubber);
scrubberDiv.appendChild(this.timestampP);
// If there is a deadline set then position the scrubber at the last submission
// prior to the deadline
if (this.deadline) {
let i = 0;
let done = false;
while (i < this.history.length && !done) {
if (new Date(this.timestamps[i]) > this.deadline) {
done = true;
} else {
i += 1;
}
}
i = i - 1;
scrubber.value = Math.max(i, 0);
this.editor.setValue(this.history[scrubber.value]);
$(scrubber).slider("value", scrubber.value);
} else if (pos_last) {
scrubber.value = this.history.length - 1;
this.editor.setValue(this.history[scrubber.value]);
} else {
scrubber.value = 0;
}
let pos = $(scrubber).slider("value");
let outOf = this.history.length;
let ts = this.timestamps[$(scrubber).slider("value")];
$(this.timestampP).text(`${ts} - ${pos + 1} of ${outOf}`);
$(this.histButton).remove();
this.histButton = null;
this.historyScrubber = scrubber;
$(scrubberDiv).insertAfter(this.runButton);
} // end definition of helper
createOutput() {
// Create a parent div with two elements: pre for standard output and a div
// to hold turtle graphics output. We use a div in case the turtle changes from
// using a canvas to using some other element like svg in the future.
var outDiv = document.createElement("div");
$(outDiv).addClass("ac_output col-md-12");
this.outDiv = outDiv;
this.output = document.createElement("pre");
this.output.id = this.divid + "_stdout";
$(this.output).css("visibility", "hidden");
this.graphics = document.createElement("div");
this.graphics.id = this.divid + "_graphics";
$(this.graphics).addClass("ac-canvas");
// This bit of magic adds an event which waits for a canvas child to be created on our
// newly created div. When a canvas child is added we add a new class so that the visible
// canvas can be styled in CSS. Which a the moment means just adding a border.
$(this.graphics).on(
"DOMNodeInserted",
"canvas",
function () {
$(this.graphics).addClass("visible-ac-canvas");
}.bind(this)
);
var clearDiv = document.createElement("div");
$(clearDiv).css("clear", "both"); // needed to make parent div resize properly
this.outerDiv.appendChild(clearDiv);
outDiv.appendChild(this.output);
outDiv.appendChild(this.graphics);
this.outerDiv.appendChild(outDiv);
var lensDiv = document.createElement("div");
lensDiv.id = `${this.divid}_codelens`;
$(lensDiv).addClass("col-md-12");
$(lensDiv).css("display", "none");
this.codelens = lensDiv;
this.outerDiv.appendChild(lensDiv);
var coachDiv = document.createElement("div");
$(coachDiv).addClass("col-md-12");
$(coachDiv).css("display", "none");
this.codecoach = coachDiv;
this.outerDiv.appendChild(coachDiv);
clearDiv = document.createElement("div");
$(clearDiv).css("clear", "both"); // needed to make parent div resize properly
this.outerDiv.appendChild(clearDiv);
}
disableSaveLoad() {
$(this.saveButton).addClass("disabled");
$(this.saveButton).attr("title", "Login to save your code");
$(this.loadButton).addClass("disabled");
$(this.loadButton).attr("title", "Login to load your code");
}
downloadFile(lang) {
var fnb = this.divid;
var d = new Date();
var fileName =
fnb +
"_" +
d
.toJSON()
.substring(0, 10) // reverse date format
.split("-")
.join("") +
"." +
languageExtensions[lang];
var code = this.editor.getValue();
if ("Blob" in window) {
var textToWrite = code.replace(/\n/g, "\r\n");
var textFileAsBlob = new Blob([textToWrite], {
type: "text/plain",
});
if ("msSaveOrOpenBlob" in navigator) {
navigator.msSaveOrOpenBlob(textFileAsBlob, fileName);
} else {
var downloadLink = document.createElement("a");
downloadLink.download = fileName;
downloadLink.innerHTML = "Download File";
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
} else {
alert("Your browser does not support the HTML5 Blob.");
}
}
resetCode() {
localStorage.removeItem(this.divid);
window.location.reload();
}
async createGradeSummary() {
// get grade and comments for this assignment
// get summary of all grades for this student
// display grades in modal window
var data = {
div_id: this.divid,
};
let request = new Request(eBookConfig.ajaxURL + "getassignmentgrade", {
method: "POST",
headers: this.jsonHeaders,
body: JSON.stringify(data),
});
let response = await fetch(request);
let report = await response.json();
var body;
// check for report['message']
if (report) {
if (report["version"] == 2) {
// new version; would be better to embed this in HTML for the activecode
body =
"<h4>Grade Report</h4>" +
"<p>This question: " +
report["grade"];
if (report["released"]) {
body += " out of " + report["max"];
}
body += "</p> <p>";
if (report["released"] == false) {
body += "Preliminary Comments: ";
}
body += report["comment"] + "</p>";
} else {
body =
"<h4>Grade Report</h4>" +
"<p>This assignment: " +
report["grade"] +
"</p>" +
"<p>" +
report["comment"] +
"</p>" +
"<p>Number of graded assignments: " +
report["count"] +
"</p>" +
"<p>Average score: " +
report["avg"] +
"</p>";
}
} else {
body = "<h4>The server did not return any grade information</h4>";
}
var html = `<div class="modal fade">
<div class="modal-dialog compare-modal">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Assignment Feedback</h4>
</div>
<div class="modal-body">
${body}
</div>
</div>
</div>
</div>`;
var el = $(html);
el.modal();
return response;
}
async showCodelens() {
if (this.codelens.style.display == "none") {
this.codelens.style.display = "block";
this.clButton.innerText = $.i18n("msg_activecode_hide_codelens");
} else {
this.codelens.style.display = "none";
this.clButton.innerText = $.i18n("msg_activecode_show_in_codelens");
return;
}
var cl = this.codelens.firstChild;
if (cl) {
this.codelens.removeChild(cl);
}
var code = await this.buildProg(false);
var myVars = {};
myVars.code = code;
myVars.origin = "opt-frontend.js";
myVars.cumulative = false;
myVars.heapPrimitives = false;
myVars.drawParentPointers = false;
myVars.textReferences = false;
myVars.showOnlyOutputs = false;
myVars.rawInputLstJSON = JSON.stringify([]);
if (this.language == "python") {
if (this.python3) {
myVars.py = 3;
} else {
myVars.py = 2;
}
} else if (this.langauge == "javascript") {
myVars.py = "js";
} else {
myVars.py = this.language;
}
myVars.curInstr = 0;
myVars.codeDivWidth = 350;
myVars.codeDivHeight = 400;
var srcURL = "https://pythontutor.com/iframe-embed.html";
var srcVars = $.param(myVars);
var embedUrlStr = `${srcURL}#${srcVars}`;
var myIframe = document.createElement("iframe");
myIframe.setAttribute("id", this.divid + "_codelens");
myIframe.setAttribute("width", "800");
myIframe.setAttribute("height", "500");
myIframe.setAttribute("style", "display:block");
myIframe.style.background = "#fff";
//myIframe.setAttribute("src",srcURL)
myIframe.src = embedUrlStr;
this.codelens.appendChild(myIframe);
this.logBookEvent({
event: "codelens",
act: "view",
div_id: this.divid,
});
}
// <iframe id="%(divid)s_codelens" width="800" height="500" style="display:block"src="#">
// </iframe>
showCodeCoach() {
var myIframe;
var srcURL;
var cl;
var div_id = this.divid;
if (this.codecoach === null) {
this.codecoach = document.createElement("div");
this.codecoach.style.display = "block";
}
cl = this.codecoach.firstChild;
if (cl) {
this.codecoach.removeChild(cl);
}
srcURL = eBookConfig.app + "/admin/diffviewer?divid=" + div_id;
myIframe = document.createElement("iframe");
myIframe.setAttribute("id", div_id + "_coach");
myIframe.setAttribute("width", "800px");
myIframe.setAttribute("height", "500px");
myIframe.setAttribute("style", "display:block");
myIframe.style.background = "#fff";
myIframe.style.width = "100%";
myIframe.src = srcURL;
this.codecoach.appendChild(myIframe);
$(this.codecoach).show();
this.logBookEvent({
event: "coach",
act: "view",
div_id: this.divid,
});
}
toggleEditorVisibility() {}
addErrorMessage(err) {
// Add the error message
this.errLastRun = true;
var errHead = $("<h3>").html("Error");
this.eContainer = this.outerDiv.appendChild(
document.createElement("div")
);
this.eContainer.className = "error alert alert-danger";
this.eContainer.id = this.divid + "_errinfo";
this.eContainer.appendChild(errHead[0]);
var errText = this.eContainer.appendChild(
document.createElement("pre")
);
// But, adjust the line numbers. If the line number is <= pretextLines then it is in included code
// if it is greater than the number of included lines but less than the pretext + current editor then it is in the student code.
// adjust the line number we display by eliminating the pre-included code.
if (err.traceback.length >= 1) {
var errorLine = err.traceback[0].lineno;
if (errorLine <= this.pretextLines) {
errText.innerHTML =
"An error occurred in the hidden, included code. Sorry we can't give you a more helpful error message";
return;
} else if (errorLine > this.progLines + this.pretextLines) {
errText.innerHTML = `An error occurred after the end of your code.
One possible reason is that you have an unclosed parenthesis or string.
Another possibility is that there is an error in the hidden test code.
Yet another is that there is an internal error. The internal error message is: ${err.message}`;
return;
} else {
if (this.pretextLines > 0) {
err.traceback[0].lineno =
err.traceback[0].lineno - this.pretextLines + 1;
}
}
}
var errString = err.toString();
var to = errString.indexOf(":");
var errName = errString.substring(0, to);
errText.innerHTML = errString;
$(this.eContainer).append("<h3>Description</h3>");
var errDesc = this.eContainer.appendChild(document.createElement("p"));
errDesc.innerHTML = errorText[errName];
$(this.eContainer).append("<h3>To Fix</h3>");
var errFix = this.eContainer.appendChild(document.createElement("p"));
errFix.innerHTML = errorText[errName + "Fix"];
var moreInfo = "../ErrorHelp/" + errName.toLowerCase() + ".html";
//console.log("Runtime Error: " + err.toString());
}
setTimeLimit(timer) {
var timelimit = this.timelimit;
if (timer !== undefined) {
timelimit = timer;
}
// set execLimit in milliseconds -- for student projects set this to
// 25 seconds -- just less than Chrome's own timer.
if (
this.code.indexOf("ontimer") > -1 ||
this.code.indexOf("onclick") > -1 ||