Repository navigation
Expand file tree
/
Copy pathopt-frontend.ts
More file actions
680 lines (573 loc) · 24.6 KB
/
Copy pathopt-frontend.ts
File metadata and controls
680 lines (573 loc) · 24.6 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
// Python Tutor: https://github.com/pgbovine/OnlinePythonTutor/
// Copyright (C) Philip Guo (philip@pgbovine.net)
// LICENSE: https://github.com/pgbovine/OnlinePythonTutor/blob/master/LICENSE.txt
/* TODO:
- parse Java viz_options in users' java code:
https://github.com/daveagp/java_visualize/blob/1489078712310eda44391f09405e0f71b2b190c9/jv-frontend.js#L101
- implement other missing Java functionality while i'm at it :0
- also implement these options and stdin support too:
var optionNames = ['showStringsAsObjects', 'showAllFields', 'disableNesting'];
- we're referring to top-level CSS selectors on the page; maybe use a
this.domRoot pattern like in pytutor.ts?
*/
// for TypeScript
declare var initCodeopticon: any; // FIX later when porting Codeopticon
declare var codeopticonUsername: string; // FIX later when porting Codeopticon
declare var codeopticonSession: string; // FIX later when porting Codeopticon
require('./lib/jquery-3.0.0.min.js');
// just punt and use global script dependencies
require("script!./lib/ace/src-min-noconflict/ace.js");
require('script!./lib/ace/src-min-noconflict/mode-python.js');
require('script!./lib/ace/src-min-noconflict/mode-javascript.js');
require('script!./lib/ace/src-min-noconflict/mode-typescript.js');
require('script!./lib/ace/src-min-noconflict/mode-c_cpp.js');
require('script!./lib/ace/src-min-noconflict/mode-java.js');
require('script!./lib/ace/src-min-noconflict/mode-ruby.js');
require('script!./lib/socket.io-client/socket.io.js');
// need to directly import the class for type checking to work
import {AbstractBaseFrontend, generateUUID, supports_html5_storage} from './opt-frontend-common.ts';
import {ExecutionVisualizer, assert, htmlspecialchars} from './pytutor.ts';
require('../css/opt-frontend.css');
require('../css/opt-testcases.css');
const JAVA_BLANK_TEMPLATE = 'public class YourClassNameHere {\n\
public static void main(String[] args) {\n\
\n\
}\n\
}'
const CPP_BLANK_TEMPLATE = 'int main() {\n\
\n\
return 0;\n\
}'
const CODE_SNAPSHOT_DEBOUNCE_MS = 1000;
const SUBMIT_UPDATE_HISTORY_INTERVAL_MS = 1000 * 60;
export class OptFrontend extends AbstractBaseFrontend {
originFrontendJsFile: string = 'opt-frontend.js';
pyInputAceEditor = undefined; // Ace editor object that contains the user's code
preseededCurInstr: number = undefined;
constructor(params={}) {
super(params);
$('#genEmbedBtn').bind('click', () => {
var mod = this.appMode;
assert(mod == 'display' || mod == 'visualize' /* deprecated */);
var myArgs = this.getAppState();
delete myArgs.mode;
(myArgs as any).codeDivWidth = ExecutionVisualizer.DEFAULT_EMBEDDED_CODE_DIV_WIDTH;
(myArgs as any).codeDivHeight = ExecutionVisualizer.DEFAULT_EMBEDDED_CODE_DIV_HEIGHT;
var domain = "http://pythontutor.com/"; // for deployment
var embedUrlStr = $.param.fragment(domain + "iframe-embed.html", myArgs, 2 /* clobber all */);
embedUrlStr = embedUrlStr.replace(/\)/g, '%29') // replace ) with %29 so that links embed well in Markdown
var iframeStr = '<iframe width="800" height="500" frameborder="0" src="' + embedUrlStr + '"> </iframe>';
$('#embedCodeOutput').val(iframeStr);
});
this.initAceEditor(420);
// for some weird reason, jQuery doesn't work here:
// $(window).bind("hashchange"
window.addEventListener("hashchange", (e) => {
// if you've got some preseeded code, then parse the entire query
// string from scratch just like a page reload
if ($.bbq.getState('code')) {
this.parseQueryString();
} else {
// otherwise just do an incremental update
var newMode = $.bbq.getState('mode');
this.updateAppDisplay(newMode);
}
});
// also fires when you resize the jQuery UI slider, interesting!
$(window).resize(this.redrawConnectors.bind(this));
$('#genUrlBtn').bind('click', () => {
var myArgs = this.getAppState();
var urlStr = $.param.fragment(window.location.href, myArgs, 2); // 2 means 'override'
urlStr = urlStr.replace(/\)/g, '%29') // replace ) with %29 so that links embed well in Markdown
$('#urlOutput').val(urlStr);
});
// first initialize options from HTML LocalStorage. very important
// that this code runs FIRST so that options get overridden by query
// string options and anything else the user wants to override with.
if (supports_html5_storage() && !(params as any).disableLocalStorageToggles) {
var lsKeys = ['cumulative',
'heapPrimitives',
'py',
'textReferences'];
// restore toggleState if available
var lsOptions = {};
$.each(lsKeys, function(i, k) {
var v = localStorage.getItem(k);
if (v) {
lsOptions[k] = v;
}
});
this.setToggleOptions(lsOptions);
// store in localStorage whenever user explicitly changes any toggle option:
$('#cumulativeModeSelector,#heapPrimitivesSelector,#textualMemoryLabelsSelector,#pythonVersionSelector').change(() => {
var ts = this.getToggleState();
$.each(ts, function(k, v) {
localStorage.setItem(k, v);
});
});
}
// when you leave or reload the page, submit an updateHistoryJSON if you
// have one. beforeunload seems to work better than unload(), but it's
// still a bit flaky ... TODO: investigate :(
$(window).on('beforeunload', () => {
this.submitUpdateHistory('beforeunload');
// don't return anything, or a modal dialog box might pop up
});
// just do this as well, even though it might be hella redundant
$(window).on('unload', () => {
this.submitUpdateHistory('unload');
// don't return anything, or a modal dialog box might pop up
});
// periodically do submitUpdateHistory() to handle the case when
// someone is simply idle on the page without reloading it or
// re-editing code; that way, we can still get some signals rather
// than nothing.
var lastSubmittedUpdateHistoryLength = 0;
setInterval(() => {
if (this.myVisualizer) {
var uh = this.myVisualizer.updateHistory;
// don't submit identical entries repeatedly since that's redundant
if (uh && (uh.length != lastSubmittedUpdateHistoryLength)) {
lastSubmittedUpdateHistoryLength = uh.length;
this.submitUpdateHistory('periodic');
}
}
}, SUBMIT_UPDATE_HISTORY_INTERVAL_MS);
this.parseQueryString(); // do this at the end after Ace editor initialized
}
// Compress updateHistory before encoding and sending to
// the server so that it takes up less room in the URL. Have each
// entry except for the first be a delta from the FIRST entry.
compressUpdateHistoryList() {
assert(this.myVisualizer);
var uh = this.myVisualizer.updateHistory;
var encodedUh = [];
if (uh) {
encodedUh.push(uh[0]);
var firstTs = uh[0][1];
for (var i = 1; i < uh.length; i++) {
var e = uh[i];
encodedUh.push([e[0], e[1] - firstTs]);
}
// finally push a final entry with the current timestamp delta
var curTs = new Date().getTime();
encodedUh.push([this.myVisualizer.curInstr, curTs - firstTs]);
}
return encodedUh;
}
// this feature was deployed on 2015-09-17, so check logs for
// viz_interaction.py
submitUpdateHistory(why) {
if (this.myVisualizer) {
var encodedUh = this.compressUpdateHistoryList();
var encodedUhJSON = JSON.stringify(encodedUh);
var myArgs: any = {session_uuid: this.sessionUUID,
user_uuid: this.userUUID,
updateHistoryJSON: encodedUhJSON};
if (why) {
myArgs.why = why;
}
$.get('viz_interaction.py', myArgs, (dat) => {});
}
}
initAceEditor(height: number) {
assert(!this.pyInputAceEditor);
this.pyInputAceEditor = ace.edit('codeInputPane');
var s = this.pyInputAceEditor.getSession();
// tab -> 4 spaces
s.setTabSize(4);
s.setUseSoftTabs(true);
// disable extraneous indicators:
s.setFoldStyle('manual'); // no code folding indicators
s.getDocument().setNewLineMode('unix'); // canonicalize all newlines to unix format
this.pyInputAceEditor.setHighlightActiveLine(false);
this.pyInputAceEditor.setShowPrintMargin(false);
this.pyInputAceEditor.setBehavioursEnabled(false);
this.pyInputAceEditor.$blockScrolling = Infinity; // kludgy to shut up weird warnings
// auto-grow height as fit
this.pyInputAceEditor.setOptions({minLines: 18, maxLines: 1000});
$('#codeInputPane').css('width', '700px');
$('#codeInputPane').css('height', height + 'px'); // VERY IMPORTANT so that it works on I.E., ugh!
this.initDeltaObj();
this.pyInputAceEditor.on('change', (e) => {
$.doTimeout('pyInputAceEditorChange', CODE_SNAPSHOT_DEBOUNCE_MS, this.snapshotCodeDiff.bind(this)); // debounce
this.clearFrontendError();
s.clearAnnotations();
});
// don't do real-time syntax checks:
// https://github.com/ajaxorg/ace/wiki/Syntax-validation
s.setOption("useWorker", false);
this.setAceMode();
this.pyInputAceEditor.focus();
}
setAceMode() {
var selectorVal = $('#pythonVersionSelector').val();
var mod;
var tabSize = 2;
var editorVal = $.trim(this.pyInputGetValue());
if (editorVal === JAVA_BLANK_TEMPLATE || editorVal === CPP_BLANK_TEMPLATE) {
editorVal = '';
this.pyInputSetValue(editorVal);
}
if (selectorVal === 'java') {
mod = 'java';
if (editorVal === '') {
this.pyInputSetValue(JAVA_BLANK_TEMPLATE);
}
} else if (selectorVal === 'js') {
mod = 'javascript';
} else if (selectorVal === 'ts') {
mod = 'typescript';
} else if (selectorVal === 'ruby') {
mod = 'ruby';
} else if (selectorVal === 'c' || selectorVal == 'cpp') {
mod = 'c_cpp';
if (editorVal === '') {
this.pyInputSetValue(CPP_BLANK_TEMPLATE);
}
} else {
assert(selectorVal === '2' || selectorVal == '3')
mod = 'python';
tabSize = 4; // PEP8 style standards
}
assert(mod);
var s = this.pyInputAceEditor.getSession();
s.setMode("ace/mode/" + mod);
s.setTabSize(tabSize);
s.setUseSoftTabs(true);
// clear all error displays when switching modes
var s = this.pyInputAceEditor.getSession();
s.clearAnnotations();
if (selectorVal === 'java') {
$("#javaOptionsPane").show();
} else {
$("#javaOptionsPane").hide();
}
if (selectorVal === 'c' || selectorVal === 'cpp') {
$("#cppOptionsPane").show();
} else {
$("#cppOptionsPane").hide();
}
if (selectorVal === 'js' || selectorVal === '2' || selectorVal === '3') {
$("#liveModeBtn").show();
} else {
$("#liveModeBtn").hide();
}
this.clearFrontendError();
}
pyInputGetValue() {
return this.pyInputAceEditor.getValue();
}
pyInputSetValue(dat) {
this.pyInputAceEditor.setValue(dat.rtrim() /* kill trailing spaces */,
-1 /* do NOT select after setting text */);
$('#urlOutput,#embedCodeOutput').val('');
this.clearFrontendError();
// also scroll to top to make the UI more usable on smaller monitors
// TODO: this has a global impact on the document, so breaks modularity?
$(document).scrollTop(0);
}
pyInputGetScrollTop() {
return this.pyInputAceEditor.getSession().getScrollTop();
}
pyInputSetScrollTop(st) {
this.pyInputAceEditor.getSession().setScrollTop(st);
}
executeCodeFromScratch() {
// don't execute empty string:
if (this.pyInputAceEditor && $.trim(this.pyInputGetValue()) == '') {
this.setFronendError(["Type in some code to visualize."]);
return;
}
super.executeCodeFromScratch();
}
executeCode(forceStartingInstr=0, forceRawInputLst=undefined) {
// if you're in display mode, kick back into edit mode before executing
// or else the display might not refresh properly ... ugh krufty
if (this.appMode != 'edit') {
this.enterEditMode();
}
if (forceRawInputLst !== undefined && forceRawInputLst !== null) {
this.rawInputLst = forceRawInputLst;
}
var backendOptionsObj = this.getBaseBackendOptionsObj();
var frontendOptionsObj = this.getBaseFrontendOptionsObj();
frontendOptionsObj.startingInstruction = forceStartingInstr;
this.snapshotCodeDiff(); // do ONE MORE snapshot before we execute, or else
// we'll miss a diff if the user hits Visualize Execution
// very shortly after finishing coding
if (this.deltaObj) {
this.deltaObj.executeTime = new Date().getTime();
}
this.executeCodeAndCreateViz(this.pyInputGetValue(),
$('#pythonVersionSelector').val(),
backendOptionsObj,
frontendOptionsObj,
'pyOutputPane');
this.initDeltaObj(); // clear deltaObj to start counting over again
}
finishSuccessfulExecution() {
this.enterDisplayMode(); // do this first!
if (this.myVisualizer) {
this.myVisualizer.add_pytutor_hook("end_updateOutput", (args) => {
// TODO: implement for codeopticon
// debounce to compress a bit ... 250ms feels "right"
$.doTimeout('updateOutputLogEvent', 250, () => {
var obj: any = {type: 'updateOutput', step: args.myViz.curInstr,
curline: args.myViz.curLineNumber,
prevline: args.myViz.prevLineNumber};
// optional fields
if (args.myViz.curLineExceptionMsg) {
obj.exception = args.myViz.curLineExceptionMsg;
}
if (args.myViz.curLineIsReturn) {
obj.curLineIsReturn = true;
}
if (args.myViz.prevLineIsReturn) {
obj.prevLineIsReturn = true;
}
this.logEventCodeopticon(obj);
});
// 2014-05-25: implemented more detailed tracing for surveys
if (args.myViz.creationTime) {
var curTs = new Date().getTime();
var uh = args.myViz.updateHistory;
assert(uh.length > 0); // should already be seeded with an initial value
if (uh.length > 1) { // don't try to "compress" the very first entry
var lastTs = uh[uh.length - 1][1];
// (debounce entries that are less than 1 second apart to
// compress the logs a bit when there's rapid scrubbing or scrolling)
if ((curTs - lastTs) < 1000) {
uh.pop(); // get rid of last entry before pushing a new entry
}
}
uh.push([args.myViz.curInstr, curTs]);
}
return [false]; // pass through to let other hooks keep handling
});
}
// 2014-05-25: implemented more detailed tracing for surveys
this.myVisualizer.creationTime = new Date().getTime();
// each element will be a two-element list consisting of:
// [step number, timestamp]
// (debounce entries that are less than 1 second apart to
// compress the logs a bit when there's rapid scrubbing or scrolling)
//
// the first entry has a THIRD field:
// [step number, timestamp, total # steps]
//
// subsequent entries don't need it since it will always be the same.
// the invariant is that step number < total # steps (since it's
// zero-indexed
this.myVisualizer.updateHistory = [];
this.myVisualizer.updateHistory.push([this.myVisualizer.curInstr,
this.myVisualizer.creationTime,
this.myVisualizer.curTrace.length]);
}
handleUncaughtException(trace) {
if (trace.length == 1 && trace[0].line) {
var errorLineNo = trace[0].line - 1; /* Ace lines are zero-indexed */
if (errorLineNo !== undefined && errorLineNo != NaN) {
// highlight the faulting line
var s = this.pyInputAceEditor.getSession();
s.setAnnotations([{row: errorLineNo,
column: null, /* for TS typechecking */
type: 'error',
text: trace[0].exception_msg}]);
this.pyInputAceEditor.gotoLine(errorLineNo + 1 /* one-indexed */);
// if we have both a line and column number, then move over to
// that column. (going to the line first prevents weird
// highlighting bugs)
if (trace[0].col !== undefined) {
this.pyInputAceEditor.moveCursorTo(errorLineNo, trace[0].col);
}
this.pyInputAceEditor.focus();
}
}
}
ignoreAjaxError(settings) {
// other idiosyncratic errors to ignore
if ((settings.url.indexOf('syntax_err_survey.py') > -1) ||
(settings.url.indexOf('viz_interaction.py') > -1)) {
return true;
}
return false;
}
initDeltaObj() {
assert(this.pyInputAceEditor);
// v is the version number
// 1 (version 1 was released on 2014-11-05)
// 2 (version 2 was released on 2015-09-16, added a startTime field)
this.deltaObj = {start: this.pyInputGetValue(), deltas: [], v: 2,
startTime: new Date().getTime()};
}
snapshotCodeDiff() {
assert(this.deltaObj);
var newCode = this.pyInputGetValue();
var timestamp = new Date().getTime();
if (this.curCode != newCode) {
var diff = this.dmp.diff_toDelta(this.dmp.diff_main(this.curCode, newCode));
//var patch = this.dmp.patch_toText(this.dmp.patch_make(this.curCode, newCode));
var delta = {t: timestamp, d: diff};
this.deltaObj.deltas.push(delta);
this.curCode = newCode;
this.logEditDelta(delta);
}
}
logEditDelta(delta) {
this.logEventCodeopticon({type: 'editCode', delta: delta});
}
enterDisplayMode() {
this.updateAppDisplay('display');
}
enterEditMode() {
this.updateAppDisplay('edit');
}
// try to make this function as idempotent as possible, so that
// repeated calls with same params don't do anything bad
updateAppDisplay(newAppMode) {
this.appMode = newAppMode;
if (this.appMode === undefined || this.appMode == 'edit' ||
!this.myVisualizer /* subtle -- if no visualizer, default to edit mode */) {
this.appMode = 'edit'; // canonicalize
$("#pyInputPane").show();
$("#pyOutputPane,#embedLinkDiv").hide();
// Potentially controversial: when you enter edit mode, DESTROY any
// existing visualizer object. note that this simplifies the app's
// conceptual model but breaks the browser's expected Forward and
// Back button flow
$("#pyOutputPane").empty();
// right before destroying, submit the visualizer's updateHistory
this.submitUpdateHistory('editMode');
this.myVisualizer = null; // yikes!
$(document).scrollTop(0); // scroll to top to make UX better on small monitors
var s: any = { mode: 'edit' };
// keep these persistent so that they survive page reloads
// keep these persistent so that they survive page reloads
if (typeof codeopticonSession !== "undefined") {s.cosession = codeopticonSession;}
if (typeof codeopticonUsername !== "undefined") {s.couser = codeopticonUsername;}
$.bbq.pushState(s, 2 /* completely override other hash strings to keep URL clean */);
} else if (this.appMode == 'display' || this.appMode == 'visualize' /* 'visualize' is deprecated */) {
assert(this.myVisualizer);
this.appMode = 'display'; // canonicalize
$("#pyInputPane").hide();
$("#pyOutputPane,#embedLinkDiv").show();
this.doneExecutingCode();
// do this AFTER making #pyOutputPane visible, or else
// jsPlumb connectors won't render properly
this.myVisualizer.updateOutput();
// use .off() to remove all handlers first, to prevent accidental
// multiple attaches ...
// customize edit button click functionality AFTER rendering myVisualizer
$('#pyOutputPane #editCodeLinkDiv').show();
$('#pyOutputPane #editBtn').off().click(() => {
this.enterEditMode();
});
var v = $('#pythonVersionSelector').val();
if (v === 'js' || v === '2' || v === '3') {
var myArgs = this.getAppState();
var urlStr = $.param.fragment('live.html', myArgs, 2 /* clobber all */);
$("#pyOutputPane #liveModeSpan").show();
$('#pyOutputPane #editLiveModeBtn').off().click(this.openLiveModeUrl.bind(this));
} else {
$("#pyOutputPane #liveModeSpan").hide();
}
$(document).scrollTop(0); // scroll to top to make UX better on small monitors
var s: any = { mode: 'display' };
// keep these persistent so that they survive page reloads
if (typeof codeopticonSession !== "undefined") {s.cosession = codeopticonSession;}
if (typeof codeopticonUsername !== "undefined") {s.couser = codeopticonUsername;}
$.bbq.pushState(s, 2 /* completely override other hash strings to keep URL clean */);
} else {
assert(false);
}
$('#urlOutput,#embedCodeOutput').val(''); // clear to avoid stale values
// log at the end after appMode gets canonicalized
this.logEventCodeopticon({type: 'updateAppDisplay', mode: this.appMode, appState: this.getAppState()});
assert(this.appMode === 'edit' || this.appMode === 'display'); // postcondition
}
openLiveModeUrl() {
var myArgs = this.getAppState();
var urlStr = $.param.fragment('live.html', myArgs, 2 /* clobber all */);
window.open(urlStr); // open in new tab
return false; // to prevent default "a href" click action
}
appStateAugmenter(x) { }; // NOP
// get the ENTIRE current state of the app
getAppState() {
assert(this.originFrontendJsFile);
var ret = {code: this.pyInputGetValue(),
mode: this.appMode,
origin: this.originFrontendJsFile,
cumulative: $('#cumulativeModeSelector').val(),
heapPrimitives: $('#heapPrimitivesSelector').val(),
textReferences: $('#textualMemoryLabelsSelector').val(),
py: $('#pythonVersionSelector').val(),
/* ALWAYS JSON serialize rawInputLst, even if it's empty! */
rawInputLstJSON: JSON.stringify(this.rawInputLst),
curInstr: this.myVisualizer ? this.myVisualizer.curInstr : undefined};
// keep this really clean by avoiding undefined values
if (ret.cumulative === undefined)
delete ret.cumulative;
if (ret.heapPrimitives === undefined)
delete ret.heapPrimitives;
if (ret.textReferences === undefined)
delete ret.textReferences;
if (ret.py === undefined)
delete ret.py;
if (ret.rawInputLstJSON === undefined)
delete ret.rawInputLstJSON;
if (ret.curInstr === undefined)
delete ret.curInstr;
// frontends can optionally AUGMENT the app state with custom fields
this.appStateAugmenter(ret);
return ret;
}
// strip it down to the bare minimum
getToggleState() {
var x = this.getAppState();
delete x.code;
delete x.mode;
delete x.rawInputLstJSON;
delete x.curInstr;
return x;
}
setToggleOptions(dat) {
// ugh, ugly tristate due to the possibility of each being undefined
if (dat.py !== undefined) {
$('#pythonVersionSelector').val(dat.py);
}
if (dat.cumulative !== undefined) {
$('#cumulativeModeSelector').val(dat.cumulative);
}
if (dat.heapPrimitives !== undefined) {
$('#heapPrimitivesSelector').val(dat.heapPrimitives);
}
if (dat.textReferences !== undefined) {
$('#textualMemoryLabelsSelector').val(dat.textReferences);
}
}
parseQueryString() {
var queryStrOptions = this.getQueryStringOptions();
this.setToggleOptions(queryStrOptions);
if (queryStrOptions.preseededCode) {
this.pyInputSetValue(queryStrOptions.preseededCode);
}
this.rawInputLst = queryStrOptions.rawInputLst ? queryStrOptions.rawInputLst : [];
this.preseededCurInstr = queryStrOptions.preseededCurInstr;
if (isNaN(this.preseededCurInstr)) {
this.preseededCurInstr = undefined;
}
if (queryStrOptions.codeopticonSession) {
assert(false); // TODO: this won't currently work with Webpack, so fix it later
codeopticonSession = queryStrOptions.codeopticonSession; // GLOBAL defined in codeopticon-learner.js
codeopticonUsername = queryStrOptions.codeopticonUsername; // GLOBAL defined in codeopticon-learner.js
}
if ((queryStrOptions.appMode == 'display' ||
queryStrOptions.appMode == 'visualize' /* deprecated */) &&
queryStrOptions.preseededCode /* jump to 'display' mode only with preseeded code */) {
this.executeCode(this.preseededCurInstr); // will switch to 'display' mode
}
$.bbq.removeState(); // clean up the URL no matter what
}
} // END class OptFrontend