Repository navigation
Expand file tree
/
Copy pathopt-shared-sessions.ts
More file actions
480 lines (399 loc) · 17.5 KB
/
Copy pathopt-shared-sessions.ts
File metadata and controls
480 lines (399 loc) · 17.5 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
// Python Tutor: https://github.com/pgbovine/OnlinePythonTutor/
// Copyright (C) Philip Guo (philip@pgbovine.net)
// LICENSE: https://github.com/pgbovine/OnlinePythonTutor/blob/master/LICENSE.txt
// Implements shared sessions (a.k.a. Codechella)
// VERY IMPORTANT to grab the value of togetherjsInUrl before loading
// togetherjs-min.js, since loading that file deletes #togetherjs from URL
// NB: kinda gross global
var togetherjsInUrl = !!(window.location.hash.match(/^#togetherjs/)); // turn into bool
if (togetherjsInUrl) {
console.log("togetherjsInUrl!");
}
require('script!./lib/togetherjs/togetherjs-min.js');
export var TogetherJS = (window as any).TogetherJS;
import {supports_html5_storage} from './opt-frontend-common.ts';
import {OptFrontend} from './opt-frontend.ts';
import {assert} from './pytutor.ts';
export class OptFrontendSharedSessions extends OptFrontend {
executeCodeSignalFromRemote = false;
togetherjsSyncRequested = false;
pendingCodeOutputScrollTop = null;
updateOutputSignalFromRemote = false;
constructor(params={}) {
super(params);
this.initTogetherJS();
this.pyInputAceEditor.getSession().on("change", (e) => {
// unfortunately, Ace doesn't detect whether a change was caused
// by a setValue call
if (TogetherJS.running) {
TogetherJS.send({type: "codemirror-edit"});
}
});
// NB: don't sync changeScrollTop for Ace since I can't get it working yet
//this.pyInputAceEditor.getSession().on('changeScrollTop', () => {
// if (typeof TogetherJS !== 'undefined' && TogetherJS.running) {
// $.doTimeout('codeInputScroll', 100, function() { // debounce
// // note that this will send a signal back and forth both ways
// // (there's no easy way to prevent this), but it shouldn't keep
// // bouncing back and forth indefinitely since no the second signal
// // causes no additional scrolling
// TogetherJS.send({type: "codeInputScroll",
// scrollTop: pyInputGetScrollTop()});
// });
// }
//});
// add an additional listener in addition to whatever the superclass/ added
window.addEventListener("hashchange", (e) => {
if (TogetherJS.running && !this.isExecutingCode) {
TogetherJS.send({type: "hashchange",
appMode: this.appMode,
codeInputScrollTop: this.pyInputGetScrollTop(),
myAppState: this.getAppState()});
}
});
}
// important overrides to inject in pieces of TogetherJS functionality
ignoreAjaxError(settings) {
if (settings.url.indexOf('togetherjs') > -1) {
return true;
} else {
return super.ignoreAjaxError(settings);
}
}
logEditDelta(delta) {
super.logEditDelta(delta);
if (TogetherJS.running) {
TogetherJS.send({type: "editCode", delta: delta});
}
}
startExecutingCode(startingInstruction=0) {
if (TogetherJS.running && !this.executeCodeSignalFromRemote) {
TogetherJS.send({type: "executeCode",
myAppState: this.getAppState(),
forceStartingInstr: startingInstruction,
rawInputLst: this.rawInputLst});
}
super.startExecutingCode(startingInstruction);
}
updateAppDisplay(newAppMode) {
super.updateAppDisplay(newAppMode); // do this first!
// now this.appMode should be canonicalized to either 'edit' or 'display'
if (this.appMode === 'edit') {
// pass
} else if (this.appMode === 'display') {
assert(this.myVisualizer);
if (!TogetherJS.running) {
$("#surveyHeader").show();
}
if (this.pendingCodeOutputScrollTop) {
this.myVisualizer.domRoot.find('#pyCodeOutputDiv').scrollTop(this.pendingCodeOutputScrollTop);
this.pendingCodeOutputScrollTop = null;
}
$.doTimeout('pyCodeOutputDivScroll'); // cancel any prior scheduled calls
// TODO: this might interfere with experimentalPopUpSyntaxErrorSurvey (2015-04-19)
this.myVisualizer.domRoot.find('#pyCodeOutputDiv').scroll(function(e) {
var elt = $(this);
// debounce
$.doTimeout('pyCodeOutputDivScroll', 100, function() {
// note that this will send a signal back and forth both ways
if (TogetherJS.running) {
// (there's no easy way to prevent this), but it shouldn't keep
// bouncing back and forth indefinitely since no the second signal
// causes no additional scrolling
TogetherJS.send({type: "pyCodeOutputDivScroll",
scrollTop: elt.scrollTop()});
}
});
});
} else {
assert(false);
}
}
finishSuccessfulExecution() {
assert (this.myVisualizer);
this.myVisualizer.add_pytutor_hook("end_updateOutput", (args) => {
if (this.updateOutputSignalFromRemote) {
return [true]; // die early; no more hooks should run after this one!
}
if (TogetherJS.running && !this.isExecutingCode) {
TogetherJS.send({type: "updateOutput", step: args.myViz.curInstr});
}
return [false]; // pass through to let other hooks keep handling
});
// do this late since we want the hook in this function to be installed
// FIRST so that it can run before the hook installed by our superclass
super.finishSuccessfulExecution();
// VERY SUBTLE -- reinitialize TogetherJS at the END so that it can detect
// and sync any new elements that are now inside myVisualizer
if (TogetherJS.running) {
TogetherJS.reinitialize();
}
}
initTogetherJS() {
assert(TogetherJS);
if (togetherjsInUrl) { // kinda gross global
$("#ssDiv,#surveyHeader,#adHeader").hide(); // hide ASAP!
$("#togetherjsStatus").html("Please wait ... loading shared session");
}
// clear your name from the cache every time to prevent privacy leaks
if (supports_html5_storage()) {
localStorage.removeItem('togetherjs.settings.name');
}
// This event triggers when you first join a session and say 'hello',
// and then one of your peers says hello back to you. If they have the
// exact same name as you, then change your own name to avoid ambiguity.
// Remember, they were here first (that's why they're saying 'hello-back'),
// so they keep their own name, but you need to change yours :)
TogetherJS.hub.on("togetherjs.hello-back", (msg) => {
if (!msg.sameUrl) return; // make sure we're on the same page
var p = TogetherJS.require("peers");
var peerNames = p.getAllPeers().map(e => e.name);
if (msg.name == p.Self.name) {
var newName = undefined;
var toks = msg.name.split(' ');
var count = Number(toks[1]);
// make sure the name is truly unique, incrementing count as necessary
do {
if (!isNaN(count)) {
newName = toks[0] + ' ' + String(count + 1); // e.g., "Tutor 3"
count++;
}
else {
// the original name was something like "Tutor", so make
// newName into, say, "Tutor 2"
newName = p.Self.name + ' 2';
count = 2;
}
} while ($.inArray(newName, peerNames) >= 0); // i.e., is newName in peerNames?
p.Self.update({name: newName}); // change our own name
}
});
TogetherJS.hub.on("updateOutput", (msg) => {
if (!msg.sameUrl) return; // make sure we're on the same page
if (this.isExecutingCode) {
return;
}
if (this.myVisualizer) {
// to prevent this call to updateOutput from firing its own TogetherJS event
this.updateOutputSignalFromRemote = true;
try {
this.myVisualizer.renderStep(msg.step);
}
finally {
this.updateOutputSignalFromRemote = false;
}
}
});
TogetherJS.hub.on("executeCode", (msg) => {
if (!msg.sameUrl) return; // make sure we're on the same page
if (this.isExecutingCode) {
return;
}
this.executeCodeSignalFromRemote = true;
try {
this.executeCode(msg.forceStartingInstr, msg.rawInputLst);
}
finally {
this.executeCodeSignalFromRemote = false;
}
});
TogetherJS.hub.on("hashchange", (msg) => {
if (!msg.sameUrl) return; // make sure we're on the same page
if (this.isExecutingCode) {
return;
}
console.log("TogetherJS RECEIVE hashchange", msg.appMode);
if (msg.appMode != this.appMode) {
this.updateAppDisplay(msg.appMode);
if (this.appMode == 'edit' && msg.codeInputScrollTop !== undefined &&
this.pyInputGetScrollTop() != msg.codeInputScrollTop) {
// hack: give it a bit of time to settle first ...
$.doTimeout('pyInputCodeMirrorInit', 200, () => {
this.pyInputSetScrollTop(msg.codeInputScrollTop);
});
}
}
});
TogetherJS.hub.on("codemirror-edit", (msg) => {
if (!msg.sameUrl) return; // make sure we're on the same page
$("#codeInputWarnings").hide();
$("#someoneIsTypingDiv").show();
$.doTimeout('codeMirrorWarningTimeout', 500, () => { // debounce
$("#codeInputWarnings").show();
$("#someoneIsTypingDiv").hide();
});
});
TogetherJS.hub.on("requestSync", (msg) => {
// DON'T USE msg.sameUrl check here since it doesn't work properly, eek!
TogetherJS.send({type: "myAppState",
myAppState: this.getAppState(),
codeInputScrollTop: this.pyInputGetScrollTop(),
pyCodeOutputDivScrollTop: this.myVisualizer ?
this.myVisualizer.domRoot.find('#pyCodeOutputDiv').scrollTop() :
undefined});
});
TogetherJS.hub.on("myAppState", (msg) => {
// DON'T USE msg.sameUrl check here since it doesn't work properly, eek!
// if we didn't explicitly request a sync, then don't do anything
if (!this.togetherjsSyncRequested) {
return;
}
this.togetherjsSyncRequested = false;
var learnerAppState = msg.myAppState;
if (learnerAppState.mode == 'display') {
if (OptFrontendSharedSessions.appStateEq(this.getAppState(), learnerAppState)) {
// update curInstr only
console.log("on:myAppState - app states equal, renderStep", learnerAppState.curInstr);
this.myVisualizer.renderStep(learnerAppState.curInstr);
if (msg.pyCodeOutputDivScrollTop !== undefined) {
this.myVisualizer.domRoot.find('#pyCodeOutputDiv').scrollTop(msg.pyCodeOutputDivScrollTop);
}
} else if (!this.isExecutingCode) { // if already executing from a prior signal, ignore
console.log("on:myAppState - app states unequal, executing", learnerAppState);
this.syncAppState(learnerAppState);
this.executeCodeSignalFromRemote = true;
try {
if (msg.pyCodeOutputDivScrollTop !== undefined) {
this.pendingCodeOutputScrollTop = msg.pyCodeOutputDivScrollTop;
}
this.executeCode(learnerAppState.curInstr);
}
finally {
this.executeCodeSignalFromRemote = false;
}
}
} else {
assert(learnerAppState.mode == 'edit');
if (!OptFrontendSharedSessions.appStateEq(this.getAppState(), learnerAppState)) {
console.log("on:myAppState - edit mode sync");
this.syncAppState(learnerAppState);
this.enterEditMode();
}
}
if (msg.codeInputScrollTop !== undefined) {
// give pyInputAceEditor a bit of time to settle with
// its new value. this is hacky; ideally we have a callback for
// when setValue() completes.
$.doTimeout('pyInputCodeMirrorInit', 200, () => {
this.pyInputSetScrollTop(msg.codeInputScrollTop);
});
}
});
TogetherJS.hub.on("syncAppState", (msg) => {
if (!msg.sameUrl) return; // make sure we're on the same page
this.syncAppState(msg.myAppState);
});
TogetherJS.hub.on("codeInputScroll", (msg) => {
if (!msg.sameUrl) return; // make sure we're on the same page
// don't sync for Ace editor since I can't get it working properly yet
});
TogetherJS.hub.on("pyCodeOutputDivScroll", (msg) => {
if (!msg.sameUrl) return; // make sure we're on the same page
if (this.myVisualizer) {
this.myVisualizer.domRoot.find('#pyCodeOutputDiv').scrollTop(msg.scrollTop);
}
});
$("#sharedSessionBtn").click(this.startSharedSession.bind(this));
$("#stopTogetherJSBtn").click(TogetherJS); // toggles off
// fired when TogetherJS is activated. might fire on page load if there's
// already an open session from a prior page load in the recent past.
TogetherJS.on("ready", () => {
console.log("TogetherJS ready");
$("#sharedSessionDisplayDiv").show();
$("#adInfo,#ssDiv,#adHeader,#testCasesParent").hide();
// send this to the server for the purposes of logging, but other
// clients shouldn't do anything with this data
if (TogetherJS.running) {
TogetherJS.send({type: "initialAppState",
myAppState: this.getAppState(),
user_uuid: this.userUUID,
// so that you can tell whether someone else
// shared a TogetherJS URL with you to invite you
// into this shared session:
togetherjsInUrl: togetherjsInUrl}); // kinda gross global
}
this.requestSync(); // immediately try to sync upon startup so that if
// others are already in the session, we will be
// synced up. and if nobody is here, then this is a NOP.
this.TogetherjsReadyHandler();
this.redrawConnectors(); // update all arrows at the end
});
// emitted when TogetherJS is closed. This is not emitted when the
// webpage simply closes or navigates elsewhere, ONLY when TogetherJS
// is explicitly stopped via a call to TogetherJS()
TogetherJS.on("close", () => {
console.log("TogetherJS close");
$("#togetherjsStatus").html(''); // clear it
$("#sharedSessionDisplayDiv").hide();
$("#adInfo,#ssDiv,#adHeader,#testCasesParent").show();
this.TogetherjsCloseHandler();
this.redrawConnectors(); // update all arrows at the end
});
}
requestSync() {
if (TogetherJS.running) {
this.togetherjsSyncRequested = true;
TogetherJS.send({type: "requestSync"});
}
}
syncAppState(appState) {
this.setToggleOptions(appState);
// VERY VERY subtle -- temporarily prevent TogetherJS from sending
// form update events while we set the input value. otherwise
// this will send an incorrect delta to the other end and screw things
// up because the initial states of the two forms aren't equal.
var orig = TogetherJS.config.get('ignoreForms');
TogetherJS.config('ignoreForms', true);
this.pyInputSetValue(appState.code);
TogetherJS.config('ignoreForms', orig);
if (appState.rawInputLst) {
this.rawInputLst = $.parseJSON(appState.rawInputLstJSON);
} else {
this.rawInputLst = [];
}
}
TogetherjsReadyHandler() {
$("#surveyHeader").hide();
this.populateTogetherJsShareUrl();
}
TogetherjsCloseHandler() {
if (this.appMode === "display") {
$("#surveyHeader").show();
}
}
startSharedSession() {
$("#ssDiv,#surveyHeader,#adHeader").hide(); // hide ASAP!
$("#togetherjsStatus").html("Please wait ... loading shared session");
TogetherJS();
}
// return whether two states match, except don't worry about curInstr
static appStateEq(s1, s2) {
assert(s1.origin == s2.origin); // sanity check!
return (s1.code == s2.code &&
s1.mode == s2.mode &&
s1.cumulative == s2.cumulative &&
s1.heapPrimitives == s1.heapPrimitives &&
s1.textReferences == s2.textReferences &&
s1.py == s2.py &&
s1.rawInputLstJSON == s2.rawInputLstJSON);
}
populateTogetherJsShareUrl() {
// without anything after the '#' in the hash
var cleanUrl = $.param.fragment(location.href, {}, 2); // 2 means 'override'
var shareId = TogetherJS.shareId();
assert(shareId); // make sure we're not attempting to access shareId before it's set
var urlToShare = cleanUrl + 'togetherjs=' + shareId;
$("#togetherjsStatus").html('<div>\
Send the URL below to invite someone to join this shared session:\
</div>\
<input type="text" style="font-size: 10pt; \
font-weight: bold; padding: 4px;\
margin-top: 3pt; \
margin-bottom: 6pt;" \
id="togetherjsURL" size="80" readonly="readonly"/>');
var extraHtml = '<div style="margin-top: 3px; margin-bottom: 10px; font-size: 8pt;">For best results, do not click or move around too quickly, and press "Force sync" if you get out of sync: <button id="syncBtn" type="button">Force sync</button><br/><a href="https://docs.google.com/forms/d/126ZijTGux_peoDusn1F9C1prkR226897DQ0MTTB5Q4M/viewform" target="_blank">Report bugs and feedback</a> on this shared sessions feature.</div>'
$("#togetherjsStatus").append(extraHtml);
$("#togetherjsURL").val(urlToShare).attr('size', urlToShare.length + 20);
$("#syncBtn").click(this.requestSync.bind(this));
}
} // END class OptFrontendSharedSessions