-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathactivecode.js
More file actions
405 lines (327 loc) · 12.1 KB
/
activecode.js
File metadata and controls
405 lines (327 loc) · 12.1 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
/**
* Created by bmiller on 3/19/15.
*/
function RunestoneBase() {
}
RunestoneBase.prototype.logBookEvent = function(info) {
console.log("logging event " + this.divid);
};
RunestoneBase.prototype.logRunEvent = function(info) {
console.log("running " + this.divid);
};
var edList = {};
ActiveCode.prototype = new RunestoneBase();
// separate into constructor and init
function ActiveCode(opts) {
if (opts) {
this.init(opts);
}
}
ActiveCode.prototype.init = function(opts) {
RunestoneBase.apply( this, arguments ); // call parent constructor
var _this = this;
var suffStart = -1;
var orig = opts.orig
this.origElem = orig;
this.divid = orig.id;
this.code = $(orig).text();
this.language = $(orig).data('lang');
this.timelimit = $(orig).data('timelimit');
this.includes = $(orig).data('include');
this.runButton = null;
this.saveButton = null;
this.loadButton = null;
this.outerDiv = null;
this.output = null; // create pre for output
this.graphics = null; // create div for turtle graphics
if(this.includes !== undefined) {
this.includes = this.includes.split(/\s+/);
}
suffStart = this.code.indexOf('====');
if (suffStart > -1) {
this.suffix = this.code.substring(suffStart+5);
this.code = this.code.substring(0,suffStart);
}
this.createEditor();
this.createOutput();
this.createControls();
}
ActiveCode.prototype.createEditor = function (index) {
var newdiv = document.createElement('div');
$(newdiv).addClass("ac_section alert alert-warning");
var codeDiv = document.createElement("div");
$(codeDiv).addClass("ac_code_div col-md-12");
this.codeDiv = codeDiv;
newdiv.id = this.divid;
newdiv.lang = this.language;
this.outerDiv = newdiv;
$(this.origElem).replaceWith(newdiv);
newdiv.appendChild(codeDiv);
var editor = CodeMirror(codeDiv, {value: this.code, lineNumbers: true, mode: newdiv.lang});
// 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 () {
if (editor.acEditEvent == false || editor.acEditEvent === undefined) {
$(editor.getWrapperElement()).css('border-top', '2px solid #b43232');
$(editor.getWrapperElement()).css('border-bottom', '2px solid #b43232');
this.logBookEvent({'event': 'activecode', 'act': 'edit', 'div_id': this.divid});
}
editor.acEditEvent = true;
}).bind(this)); // use bind to preserve *this* inside the on handler.
this.editor = editor;
};
ActiveCode.prototype.createControls = function () {
var ctrlDiv = document.createElement("div");
$(ctrlDiv).addClass("ac_actions");
// Run
var butt = document.createElement("button");
$(butt).text("Run");
$(butt).addClass("btn btn-success");
ctrlDiv.appendChild(butt);
this.runButton = butt;
$(butt).click(this.runProg.bind(this));
// Save
butt = document.createElement("button");
$(butt).addClass("ac_opt btn btn-default");
$(butt).text("Save");
$(butt).css("margin-left","10px");
this.saveButton = butt;
ctrlDiv.appendChild(butt);
// Load
butt = document.createElement("button");
$(butt).addClass("ac_opt btn btn-default");
$(butt).text("Load");
$(butt).css("margin-left","10px");
this.loadButton = butt;
ctrlDiv.appendChild(butt);
$(this.outerDiv).prepend(ctrlDiv);
};
ActiveCode.prototype.createOutput = function () {
// 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-6");
this.outDiv = outDiv;
this.output = document.createElement('pre');
this.graphics = document.createElement('div');
$(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(e) {
$(this.graphics).addClass("visible-ac-canvas")
}).bind(this));
outDiv.appendChild(this.output);
outDiv.appendChild(this.graphics);
this.outerDiv.appendChild(outDiv);
clearDiv = document.createElement("div");
$(clearDiv).css("clear","both"); // needed to make parent div resize properly
this.outerDiv.appendChild(clearDiv);
};
ActiveCode.prototype.saveEditor = function () {
};
ActiveCode.prototype.loadEditor = function () {
};
ActiveCode.prototype.showCodeCoach = function () {
};
ActiveCode.prototype.showCodeLens = function () {
};
ActiveCode.prototype.toggleEditorVisibility = function () {
};
ActiveCode.prototype.addErrorMessage = function (err) {
//logRunEvent({'div_id': this.divid, 'code': this.prog, 'errinfo': err.toString()}); // Log the run event
console.log(err.toString());
};
ActiveCode.prototype.setTimeLimit = function (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 ||
this.code.indexOf('onkey') > -1 ||
this.code.indexOf('setDelay') > -1 ) {
Sk.execLimit = null;
} else {
if (timelimit === "off") {
Sk.execLimit = null;
} else if (timelimit) {
Sk.execLimit = timelimit;
} else {
Sk.execLimit = 25000;
}
}
};
ActiveCode.prototype.builtinRead = function (x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
throw "File not found: '" + x + "'";
return Sk.builtinFiles["files"][x];
};
ActiveCode.prototype.outputfun = function(text) {
// bnm python 3
var x = text;
if (x.charAt(0) == '(') {
x = x.slice(1, -1);
x = '[' + x + ']';
try {
var xl = eval(x);
xl = xl.map(pyStr);
x = xl.join(' ');
} catch (err) {
}
}
text = x;
text = text.replace(/</g, "<").replace(/>/g, ">").replace(/\n/g, "<br/>");
$(this.output).append(text);
};
ActiveCode.prototype.buildProg = function() {
// assemble code from prefix, suffix, and editor for running.
var pretext;
var prog = this.editor.getValue();
if (this.includes !== undefined) {
// iterate over the includes, in-order prepending to prog
pretext = "";
for (var x=0; x < this.includes.length; x++) {
pretext = pretext + edList[this.includes[x]].editor.getValue();
}
prog = pretext + prog
}
if(this.suffix) {
prog = prog + this.suffix;
}
return prog;
};
ActiveCode.prototype.runProg = function() {
var prog = this.buildProg()
$(this.output).text('');
Sk.configure({output : this.outputfun.bind(this),
read : this.builtinRead,
python3: true,
imageProxy : 'http://image.runestone.academy:8080/320x'
});
this.setTimeLimit();
(Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = this.graphics;
$(this.runButton).attr('disabled', 'disabled');
$(this.codeDiv).switchClass("col-md-12","col-md-6",{duration:500,queue:false});
$(this.outDiv).show({duration:700,queue:false});
var myPromise = Sk.misceval.asyncToPromise(function() {
return Sk.importMainWithBody("<stdin>", false, prog, true);
});
myPromise.then((function(mod) { // success
$(this.runButton).removeAttr('disabled');
this.logRunEvent({'div_id': this.id, 'code': prog, 'errinfo': 'success'}); // Log the run event
}).bind(this),
function(err) { // fail
this.addErrorMessage(err)
});
if (typeof(allVisualizers) != "undefined") {
$.each(allVisualizers, function (i, e) {
e.redrawConnectors();
});
}
};
JSActiveCode.prototype = new ActiveCode();
function JSActiveCode(opts) {
if (opts) {
this.init(opts)
}
}
JSActiveCode.prototype.init = function(opts) {
ActiveCode.prototype.init.apply(this,arguments)
}
JSActiveCode.prototype.outputfun = function (a) {
var str = "["
if (typeof(a) == "object" && a.length) {
for (var i = 0; i < a.length; i++)
if (typeof(a[i]) == "object" && a[i].length) {
str += (i == 0 ? "" : " ") + "["
for (var j = 0; j < a[i].length; j++)
str += a[i][j] + (j == a[i].length - 1 ?
"]" + (i == a.length - 1 ? "]" : ",") + "\n" : ", ");
} else str += a[i] + (i == a.length - 1 ? "]" : ", ");
} else {
try {
str = JSON.stringify(a);
} catch (e) {
str = a;
}
}
return str;
}
JSActiveCode.prototype.runProg = function() {
var _this = this;
var prog = this.buildProg();
var write = function(str) {
_this.output.innerHTML += _this.outputfun(str);
};
var writeln = function(str) {
if (!str) str="";
_this.output.innerHTML += _this.outputfun(str)+"<br />";
};
$(this.output).text('')
$(this.codeDiv).switchClass("col-md-12","col-md-6",{duration:500,queue:false});
$(this.outDiv).show({duration:700,queue:false});
try {
eval(prog)
} catch(e) {
this.addErrorMessage(e);
}
};
HTMLActiveCode.prototype = new ActiveCode();
function HTMLActiveCode (opts) {
if (opts) {
this.init(opts);
}
}
HTMLActiveCode.prototype.runProg = function () {
var prog = this.buildProg();
// $('#'+myDiv+'_iframe').remove();
// $('#'+myDiv+'_htmlout').show();
// $('#'+myDiv+'_htmlout').append('<iframe class="activehtml" id="' + myDiv + '_iframe" srcdoc="' +
// prog.replace(/"/g,"'") + '">' + '</iframe>');
$(this.output).text('');
$(this.codeDiv).switchClass("col-md-12","col-md-6",{duration:500,queue:false});
$(this.outDiv).show({duration:700,queue:false});
$(this.output).html(prog)
};
HTMLActiveCode.prototype.init = function(opts) {
ActiveCode.prototype.init.apply(this,arguments)
this.code = $(this.origElem).html();
this.editor.setValue(this.code);
};
HTMLActiveCode.prototype.createOutput = function () {
// 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.
console.log("creating html output")
var outDiv = document.createElement("div");
$(outDiv).addClass("ac_output col-md-6");
this.outDiv = outDiv;
this.output = document.createElement('div');
$(this.output).css("background-color","white");
outDiv.appendChild(this.output);
this.outerDiv.appendChild(outDiv);
clearDiv = document.createElement("div");
$(clearDiv).css("clear","both"); // needed to make parent div resize properly
this.outerDiv.appendChild(clearDiv);
};
$(document).ready(function() {
$('[data-component=activecode]').each( function(index ) {
if ($(this).data('lang') === "javascript") {
edList[this.id] = new JSActiveCode({'orig': this});
} else if ($(this).data('lang') === 'htmlmixed') {
edList[this.id] = new HTMLActiveCode({'orig': this});
} else { // default is python
edList[this.id] = new ActiveCode({'orig': this});
}
});
});