-
Notifications
You must be signed in to change notification settings - Fork 183
/
live-editor.js
1635 lines (1377 loc) · 59.1 KB
/
live-editor.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
// TODO(kevinb) remove after challenges have been converted to use i18n._
$._ = i18n._;
window.LiveEditor = Backbone.View.extend({
dom: {
DRAW_CANVAS: ".scratchpad-draw-canvas",
DRAW_COLOR_BUTTONS: "#draw-widgets a.draw-color-button",
CANVAS_WRAP: ".scratchpad-canvas-wrap",
EDITOR: ".scratchpad-editor",
CANVAS_LOADING: ".scratchpad-canvas-loading",
BIG_PLAY_LOADING: ".scratchpad-editor-bigplay-loading",
BIG_PLAY_BUTTON: ".scratchpad-editor-bigplay-button",
PLAYBAR: ".scratchpad-playbar",
PLAYBAR_AREA: ".scratchpad-playbar-area",
PLAYBAR_OPTIONS: ".scratchpad-playbar-options",
PLAYBAR_LOADING: ".scratchpad-playbar .loading-msg",
PLAYBAR_PROGRESS: ".scratchpad-playbar-progress",
PLAYBAR_PLAY: ".scratchpad-playbar-play",
PLAYBAR_TIMELEFT: ".scratchpad-playbar-timeleft",
PLAYBAR_UI: ".scratchpad-playbar-play, .scratchpad-playbar-progress",
OUTPUT_FRAME: "#output-frame",
OUTPUT_DIV: "#output",
ALL_OUTPUT: "#output, #output-frame",
RESTART_BUTTON: "#restart-code",
GUTTER_ERROR: ".ace_error",
ERROR_BUDDY_HAPPY: ".error-buddy-happy",
ERROR_BUDDY_THINKING: ".error-buddy-thinking",
},
mouseCommands: ["move", "over", "out", "down", "up"],
colors: ["black", "red", "orange", "green", "blue", "lightblue", "violet"],
defaultOutputWidth: 400,
defaultOutputHeight: 400,
editors: {},
initialize: function(options) {
this.workersDir = this._qualifyURL(options.workersDir);
this.externalsDir = this._qualifyURL(options.externalsDir);
this.imagesDir = this._qualifyURL(options.imagesDir);
this.soundsDir = options.soundsDir;
this.execFile = options.execFile ? this._qualifyURL(options.execFile) : "";
this.jshintFile = this._qualifyURL(options.jshintFile ||
this.externalsDir + "jshint/jshint.js");
this.redirectUrl = options.redirectUrl;
this.outputType = options.outputType || "";
this.editorType = options.editorType || _.keys(this.editors)[0];
this.editorHeight = options.editorHeight;
this.initialCode = options.code;
this.initialVersion = options.version;
this.settings = options.settings;
this.validation = options.validation;
this.recordingCommands = options.recordingCommands;
this.recordingMP3 = options.recordingMP3;
this.recordingInit = options.recordingInit || {
code: this.initialCode,
version: this.initialVersion
};
this.transloaditTemplate = options.transloaditTemplate;
this.transloaditAuthKey = options.transloaditAuthKey;
this.render();
this.config = new ScratchpadConfig({
version: options.version
});
this.record = new ScratchpadRecord();
// Set up the Canvas drawing area
this.drawCanvas = new ScratchpadDrawCanvas({
el: this.dom.DRAW_CANVAS,
record: this.record
});
this.drawCanvas.on({
// Drawing has started
drawStarted: function() {
// Activate the canvas
this.$el.find(this.dom.DRAW_CANVAS).show();
}.bind(this),
// Drawing has ended
drawEnded: function() {
// Hide the canvas
this.$el.find(this.dom.DRAW_CANVAS).hide();
}.bind(this),
// A color has been chosen
colorSet: function(color) {
// Deactivate all the color buttons
this.$el.find(this.dom.DRAW_COLOR_BUTTONS)
.removeClass("ui-state-active");
// If a new color has actually been chosen
if (color !== null) {
// Select that color and activate the button
this.$el.find("#" + color).addClass("ui-state-active");
}
}.bind(this)
});
// TEMP: Set up a query param for testing the new error experience
// Looks to see if "new_error_experience=yes" is in the url,
// if it is, then we use the new error buddy behaviour.
this.newErrorExperience = options.newErrorExperience;
if (window.location.search.indexOf("new_error_experience=yes") !== -1) {
this.newErrorExperience = true;
}
if (options.enableLoopProtect != null) {
this.enableLoopProtect = options.enableLoopProtect;
} else {
this.enableLoopProtect = true;
}
// Set up the editor
this.editor = new this.editors[this.editorType]({
el: this.dom.EDITOR,
code: this.initialCode,
autoFocus: options.autoFocus,
config: this.config,
record: this.record,
imagesDir: this.imagesDir,
soundsDir: this.soundsDir,
externalsDir: this.externalsDir,
workersDir: this.workersDir,
type: this.editorType
});
var tooltipEngine = this.config.editor.tooltipEngine;
if (tooltipEngine.setEnabledStatus) {
// Looks to see if "autosuggestToggle=yes" is in the url,
// if it is, then we disable the live autosuggestions.
if (window.location.search.indexOf("autosuggestToggle=yes") !== -1) {
// Overrides whatever is in localStorage.
// TODO (anyone) remove this when the URL param is removed.
window.localStorage["autosuggest"] = "true";
// Allows toggling of the autosuggestions.
this.editor.editor.commands.addCommand({
name: 'toggleAutosuggest',
bindKey: {
win: 'Ctrl+Alt+A',
mac: 'Command+Option+A'
},
exec: function(editor) {
var status = window.localStorage["autosuggest"] === "true";
tooltipEngine.setEnabledStatus(status !== true);
window.localStorage.setItem("autosuggest", String(status !== true));
}
});
} else {
// since we load the enabled value from localStorage...
tooltipEngine.setEnabledStatus("true");
}
}
// linting in the webpage environment generates slowparseResults which
// is used in the runCode step so skipping linting won't work in that
// environment without some more work
if (this.editorType === "ace_pjs") {
this.noLint = false;
this.editor.on("scrubbingStarted", function() {
this.noLint = true;
}.bind(this));
this.editor.on("scrubbingEnded", function() {
this.noLint = false;
}.bind(this));
}
this.tipbar = new TipBar({
el: this.$(this.dom.OUTPUT_DIV),
liveEditor: this
});
var code = options.code;
// Load the text into the editor
if (code !== undefined) {
this.editor.text(code);
this.editor.originalCode = code;
}
// Focus on the editor
this.editor.focus();
if (options.cursor) {
// Restore the cursor position
this.editor.setCursor(options.cursor);
} else {
// Set an initial starting selection point
this.editor.setSelection({
start: {row: 0, column: 0},
end: {row: 0, column: 0}
});
}
// Hide the overlay
this.$el.find("#page-overlay").hide();
// Change the width and height of the output frame if it's been
// changed by the user, via the query string, or in the settings
this.updateCanvasSize(options.width, options.height);
if (this.canRecord()) {
this.$el.find("#record").show();
}
this.bind();
this.setupAudio();
},
render: function() {
this.$el.html(Handlebars.templates["live-editor"]({
execFile: this.execFile,
imagesDir: this.imagesDir,
colors: this.colors
}));
},
bind: function() {
var self = this;
var $el = this.$el;
var dom = this.dom;
// Make sure that disabled buttons can't still be used
$el.delegate(".simple-button.disabled, .ui-state-disabled", "click", function(e) {
e.stopImmediatePropagation();
return false;
});
// Handle the restart button
$el.delegate(this.dom.RESTART_BUTTON, "click",
this.restartCode.bind(this));
this.handleMessagesBound = this.handleMessages.bind(this);
$(window).on("message", this.handleMessagesBound);
// Whenever the user changes code, execute the code
this.editor.on("change", () => {
this.markDirty();
});
this.editor.on("userChangedCode", () => {
if (!this.record.recording && !this.record.playing) {
this.trigger("userChangedCode");
}
});
this.on("runDone", this.runDone.bind(this));
// This function will fire once after each synchrynous block which changes the cursor
// or the current selection. We use it for tag highlighting in webpages.
var cursorDirty = function() {
if (self.outputState !== "clean" ) {
// This will fire after markDirty() itself gets a chance to start a new run
// So it will just keep resetting itself until one run comes back and there are
// no changes waiting
self.once("runDone", cursorDirty);
} else {
setTimeout(function() {
if (self.editor.getSelectionIndices) {
self.postFrame({
setCursor: self.editor.getSelectionIndices()
});
}
self.editor.once("changeCursor", cursorDirty);
}, 0);
}
// This makes sure that we pop up the error
// if the user changed the cursor to a new line
setTimeout(function() {
self.maybeShowErrors();
}, 0);
};
this.editor.once("changeCursor", cursorDirty);
this.config.on("versionSwitched", function(e, version) {
// Re-run the code after a version switch
this.markDirty();
// Run the JSHint config
this.config.runVersion(version, "jshint");
}.bind(this));
if (this.hasAudio()) {
$el.find(".overlay").show();
$el.find(dom.BIG_PLAY_LOADING).show();
$el.find(dom.PLAYBAR).show();
}
// Set up color button handling
$el.find(dom.DRAW_COLOR_BUTTONS).each(function() {
$(this).addClass("ui-button")
.children().css("background", this.id);
});
// Set up toolbar buttons
if (jQuery.fn.buttonize) {
$el.buttonize();
}
// Handle color button clicks during recording
$el.on("buttonClick", "a.draw-color-button", function() {
self.drawCanvas.setColor(this.id);
self.editor.focus();
});
// If the user clicks the disable overlay (which is laid over
// the editor and canvas on playback) then pause playback.
$el.on("click", ".disable-overlay", function() {
self.record.pausePlayback();
});
// Set up the playback progress bar
$el.find(dom.PLAYBAR_PROGRESS).slider({
range: "min",
value: 0,
min: 0,
max: 100,
// Bind events to the progress playback bar
// When a user has started dragging the slider
start: function() {
// Prevent slider manipulation while recording
if (self.record.recording) {
return false;
}
self.record.seeking = true;
// Pause playback and remember if we were playing or were paused
self.wasPlaying = self.record.playing;
self.record.pausePlayback();
},
// While the user is dragging the slider
slide: function(e, ui) {
// Slider position is set in seconds
var sliderPos = ui.value * 1000;
// Seek the player and update the time indicator
// Ignore values that match endTime - sometimes the
// slider jumps and we should ignore those jumps
// It's ok because endTime is still captured on 'change'
if (sliderPos !== self.record.endTime()) {
self.updateTimeLeft(sliderPos);
self.seekTo(sliderPos);
}
},
// When the sliding has stopped
stop: function(e, ui) {
self.record.seeking = false;
self.updateTimeLeft(ui.value * 1000);
// If we were playing when we started sliding, resume playing
if (self.wasPlaying) {
// Set the timeout to give time for the events to catch up
// to the present -- if we start before the events have
// finished, the scratchpad editor code will be in a bad
// state. Wait roughly a second for events to settle down.
setTimeout(function() {
self.record.play();
}, 1000);
}
}
});
var handlePlayClick = function() {
if (self.record.playing) {
self.record.pausePlayback();
} else {
self.record.play();
}
};
// Handle the play button
$el.find(dom.PLAYBAR_PLAY)
.off("click.play-button")
.on("click.play-button", handlePlayClick);
var handlePlayButton = function() {
// Show the playback bar and hide the loading message
$el.find(dom.PLAYBAR_LOADING).hide();
$el.find(dom.PLAYBAR_AREA).show();
// Handle the big play button click event
$el.find(dom.BIG_PLAY_BUTTON)
.off("click.big-play-button")
.on("click.big-play-button", function() {
$el.find(dom.BIG_PLAY_BUTTON).hide();
handlePlayClick();
});
$el.find(dom.PLAYBAR_PLAY).on("click", function() {
$el.find(dom.BIG_PLAY_BUTTON).hide();
});
// Hide upon interaction with the editor
$el.find(dom.EDITOR).on("click", function() {
$el.find(dom.BIG_PLAY_BUTTON).hide();
});
// Switch from loading to play
$el.find(dom.BIG_PLAY_LOADING).hide();
$el.find(dom.BIG_PLAY_BUTTON).show();
self.off("readyToPlay", handlePlayButton);
};
// Set up all the big play button interactions
this.on("readyToPlay", handlePlayButton);
// Handle the clear button click during recording
$el.on("buttonClick", "#draw-clear-button", function() {
self.drawCanvas.clear();
self.drawCanvas.endDraw();
self.editor.focus();
});
// Handle the restart button
$el.on("click", this.dom.RESTART_BUTTON, function() {
self.record.log("restart");
});
// Handle clicks on the thinking Error Buddy
$el.on("click", this.dom.ERROR_BUDDY_THINKING, function() {
self.setErrorPosition(0);
});
// Bind the handler to start a new recording
$el.find("#record").on("click", function() {
self.recordHandler(function(err) {
if (err) {
// TODO: Change this:
console.error(err);
}
});
});
// Load the recording playback commands as well, if applicable
if (this.recordingCommands) {
// Check the filename to see if a multiplier is specified,
// of the form audio_x1.3.mp3, which means it's 1.3x as slow
var url = this.recordingMP3;
var matches = /_x(1.\d+).mp3/.exec(url);
var multiplier = parseFloat(matches && matches[1]) || 1;
this.record.loadRecording({
init: this.recordingInit,
commands: this.recordingCommands,
multiplier: multiplier
});
}
},
remove: function() {
$(window).off("message", this.handleMessagesBound);
this.editor.remove();
},
canRecord: function() {
return this.transloaditAuthKey && this.transloaditTemplate;
},
hasAudio: function() {
return !!this.recordingMP3;
},
setupAudio: function() {
if (!this.hasAudio()) {
return;
}
var self = this;
var rebootTimer;
soundManager.setup({
url: this.externalsDir + "SoundManager2/swf/",
debugMode: false,
// Un-comment this to test Flash on FF:
// debugFlash: true, preferFlash: true, useHTML5Audio: false,
// See sm2-container in play-page.handlebars and flashblock.css
useFlashBlock: true,
// Sometimes when Flash is blocked or the browser is slower,
// soundManager will fail to initialize at first,
// claiming no response from the Flash file.
// To handle that, we attempt a reboot 3 seconds after each
// timeout, clearing the timer if we get an onready during
// that time (which happens if user un-blocks flash).
onready: function() {
window.clearTimeout(rebootTimer);
self.audioInit();
},
ontimeout: function(error) {
// The onready event comes pretty soon after the user
// clicks the flashblock, but not instantaneous, so 3
// seconds seems a good amount of time to give them the
// chance to click it before we remove it. It's possible
// they may have to click twice sometimes
// (but the second time time will work).
window.clearTimeout(rebootTimer);
rebootTimer = window.setTimeout(function() {
// Clear flashblocker divs
self.$el.find("#sm2-container div").remove();
soundManager.reboot();
}, 3000);
}
});
soundManager.beginDelayedInit();
this.bindRecordHandlers();
},
audioInit: function() {
if (!this.hasAudio()) {
return;
}
var self = this;
var record = this.record;
// Reset the wasPlaying tracker
this.wasPlaying = undefined;
// Start the play head at 0
record.time = 0;
this.player = soundManager.createSound({
// SoundManager errors if no ID is passed in,
// even though we don't use it
// The ID should be a string starting with a letter.
id: "sound" + (new Date()).getTime(),
url: this.recordingMP3,
// Load the audio automatically
autoLoad: true,
// While the audio is playing update the position on the progress
// bar and update the time indicator
whileplaying: function() {
self.updateTimeLeft(record.currentTime());
if (!record.seeking) {
// Slider takes values in seconds
self.$el.find(self.dom.PLAYBAR_PROGRESS)
.slider("option", "value", record.currentTime() / 1000);
}
record.trigger("playUpdate");
}.bind(this),
// Hook audio playback into Record command playback
// Define callbacks rather than sending the function directly so
// that the scope in the Record methods is correct.
onplay: function() {
record.play();
},
onresume: function() {
record.play();
},
onpause: function() {
record.pausePlayback();
},
onload: function() {
record.durationEstimate = record.duration = this.duration;
record.trigger("loaded");
},
whileloading: function() {
record.duration = null;
record.durationEstimate = this.durationEstimate;
record.trigger("loading");
},
// When audio playback is complete, notify everyone listening
// that playback is officially done
onfinish: function() {
record.stopPlayback();
record.trigger("playEnded");
},
onsuspend: function() {
// Suspend happens when the audio can't be loaded automatically
// (such is the case on iOS devices). Thus we trigger a
// readyToPlay event anyway and let the load happen when the
// user clicks the play button later on.
self.trigger("readyToPlay");
}
});
// Wait to start playback until we at least have some
// bytes from the server (otherwise the player breaks)
var checkStreaming = setInterval(function() {
// We've loaded enough to start playing
if (self.audioReadyToPlay()) {
clearInterval(checkStreaming);
self.trigger("readyToPlay");
}
}, 16);
this.bindPlayerHandlers();
},
audioReadyToPlay: function() {
// NOTE(pamela): We can't just check bytesLoaded,
// because IE reports null for that
// (it seems to not get the progress event)
// So we've changed it to also check loaded.
// If we need to, we can reach inside the HTML5 audio element
// and check the ranges of the buffered property
return this.player &&
(this.player.bytesLoaded > 0 || this.player.loaded);
},
bindPlayerHandlers: function() {
var self = this;
var record = this.record;
// Bind events to the Record object, to track when playback events occur
this.record.bind({
loading: function() {
self.updateDurationDisplay();
},
loaded: function() {
// Add an empty command to force the Record playback to
// keep playing until the audio track finishes playing
var commands = record.commands;
if (commands) {
commands.push([
Math.max(record.endTime(),
commands[commands.length - 1][0]), "seek"]);
}
self.updateDurationDisplay();
},
// When play has started
playStarted: function() {
// If the audio player is paused, resume playing
if (self.player.paused) {
self.player.resume();
// Otherwise we can assume that we need to start playing from the top
} else if (self.player.playState === 0) {
self.player.play();
}
},
// Pause when recording playback pauses
playPaused: function() {
self.player.pause();
}
});
},
bindRecordHandlers: function() {
var self = this;
var record = this.record;
/*
* Bind events to Record (for recording and playback)
* and to ScratchpadCanvas (for recording and playback)
*/
record.bind({
// Playback of a recording has begun
playStarted: function(e, resume) {
// Re-init if the recording version is different from
// the scratchpad's normal version
self.config.switchVersion(record.getVersion());
// We're starting over so reset the editor and
// canvas to its initial state
if (!record.recording && !resume) {
// Reset the editor
self.editor.reset(record.initData.code, false);
// Clear and hide the drawing area
self.drawCanvas.clear(true);
self.drawCanvas.endDraw();
}
if (!record.recording) {
// Disable the record button during playback
self.$el.find("#record").addClass("disabled");
}
// During playback disable the restart button
self.$el.find(self.dom.RESTART_BUTTON).addClass("disabled");
if (!record.recording) {
// Turn on playback-related styling
$("html").addClass("playing");
// Show an invisible overlay that blocks interactions with
// the editor and canvas areas (preventing the user from
// being able to disturb playback)
self.$el.find(".disable-overlay").show();
}
self.editor.unfold();
// Activate the play button
self.$el.find(self.dom.PLAYBAR_PLAY)
.find("span")
.removeClass("glyphicon-play icon-play")
.addClass("glyphicon-pause icon-pause");
},
playEnded: function() {
// Re-init if the recording version is different from
// the scratchpad's normal version
self.config.switchVersion(this.initialVersion);
},
// Playback of a recording has been paused
playPaused: function() {
// Turn off playback-related styling
$("html").removeClass("playing");
// Disable the blocking overlay
self.$el.find(".disable-overlay").hide();
// Allow the user to restart the code again
self.$el.find(self.dom.RESTART_BUTTON).removeClass("disabled");
// Re-enable the record button after playback
self.$el.find("#record").removeClass("disabled");
// Deactivate the play button
self.$el.find(self.dom.PLAYBAR_PLAY)
.find("span")
.addClass("glyphicon-play icon-play")
.removeClass("glyphicon-pause icon-pause");
},
// Recording has begun
recordStarted: function() {
// Let the output know that recording has begun
self.postFrame({ recording: true });
self.$el.find("#draw-widgets").removeClass("hidden").show();
// Hides the invisible overlay that blocks interactions with the
// editor and canvas areas (preventing the user from being able
// to disturb the recording)
self.$el.find(".disable-overlay").hide();
// Allow the editor to be changed
self.editor.setReadOnly(false);
// Turn off playback-related styling
// (hides hot numbers, for example)
$("html").removeClass("playing");
// Reset the canvas to its initial state only if this is the
// very first chunk we are recording.
if (record.hasNoChunks()) {
self.drawCanvas.clear(true);
self.drawCanvas.endDraw();
}
// Disable the save button
self.$el.find("#save-button, #fork-button")
.addClass("disabled");
// Activate the recording button
self.$el.find("#record").addClass("toggled");
},
// Recording has ended
recordEnded: function() {
// Let the output know that recording has ended
self.postFrame({ recording: false });
if (record.recordingAudio) {
self.recordView.stopRecordingAudio();
}
// Re-enable the save button
self.$el.find("#save-button, #fork-button")
.removeClass("disabled");
// Enable playbar UI
self.$el.find(self.dom.PLAYBAR_UI)
.removeClass("ui-state-disabled");
// Return the recording button to normal
self.$el.find("#record").removeClass("toggled disabled");
// Stop any sort of user playback
record.stopPlayback();
// Show an invisible overlay that blocks interactions with the
// editor and canvas areas (preventing the user from being able
// to disturb the recording)
self.$el.find(".disable-overlay").show();
// Turn on playback-related styling (hides hot numbers, for
// example)
$("html").addClass("playing");
// Prevent the editor from being changed
self.editor.setReadOnly(true);
self.$el.find("#draw-widgets").addClass("hidden").hide();
// Because we are recording in chunks, do not reset the canvas
// to its initial state.
self.drawCanvas.endDraw();
}
});
// ScratchpadCanvas mouse events to track
// Tracking: mousemove, mouseover, mouseout, mousedown, and mouseup
_.each(this.mouseCommands, function(name) {
// Handle the command during playback
record.handlers[name] = function(x, y) {
self.postFrame({
mouseAction: {
name: name,
x: x,
y: y
}
});
};
});
// When a restart occurs during playback, restart the output
record.handlers.restart = function() {
var $restart = self.$el.find(self.dom.RESTART_BUTTON);
if (!$restart.hasClass("hilite")) {
$restart.addClass("hilite green");
setTimeout(function() {
$restart.removeClass("hilite green");
}, 300);
}
self.postFrame({restart: true});
};
// Force the recording to sync to the current time of the audio playback
record.currentTime = function() {
return self.player ?
self.player.position : 0;
};
// Create a function for retreiving the track end time
// Note that duration will be set to the duration estimate while
// the track is still loading, and only set to actual duration
// once its loaded.
record.endTime = function() {
return this.duration || this.durationEstimate;
};
},
recordHandler: function(callback) {
// If we're already recording, stop
if (this.record.recording) {
// Note: We should never hit this case when recording chunks.
this.recordView.stopRecordingCommands();
return;
}
var saveCode = this.editor.text();
// You must have some code in the editor before you start recording
// otherwise the student will be starting with a blank editor,
// which is confusing
if (!saveCode) {
callback({error: "empty"});
} else if (this.config.curVersion() !== this.config.latestVersion()) {
callback({error: "outdated"});
} else if (this.canRecord() && !this.hasAudio()) {
this.startRecording();
this.editor.focus();
} else {
callback({error: "exists"});
}
},
startRecording: function() {
this.bindRecordHandlers();
if (!this.recordView) {
var $el = this.$el;
// NOTE(jeresig): Unfortunately we need to do this to make sure
// that we load the web worker from the same domain as the rest
// of the site (instead of the domain that the "exec" page is on).
// This is dumb and a KA-specific bit of functionality that we
// should change, somehow.
var workersDir = this.workersDir.replace(/^https?:\/\/[^\/]*/, "");
this.recordView = new ScratchpadRecordView({
el: $el.find(".scratchpad-dev-record-row"),
recordButton: $el.find("#record"),
saveButton: $el.find("#save-button"),
record: this.record,
editor: this.editor,
config: this.config,
workersDir: workersDir,
drawCanvas: this.drawCanvas,
transloaditTemplate: this.transloaditTemplate,
transloaditAuthKey: this.transloaditAuthKey
});
}
this.recordView.initializeRecordingAudio();
},
saveRecording: function(callback, steps) {
// If no command or audio recording was made, just save the results
if (!this.record.recorded || !this.record.recordingAudio) {
return callback();
}
var transloadit = new TransloaditXhr({
authKey: this.transloaditAuthKey,
templateId: this.transloaditTemplate,
steps: steps,
successCb: function(results) {
this.recordingMP3 =
results.mp3[0].url.replace(/^http:/, "https:");
callback(null, this.recordingMP3);
}.bind(this),
errorCb: callback
});
this.recordView.getFinalAudioRecording(function(combined) {
transloadit.uploadFile(combined.wav);
});
},
// We call this function multiple times, because the
// endTime value may change as we load the file
updateDurationDisplay: function() {
// Do things that are dependent on knowing duration
// This gets called if we're loading while we're playing,
// so we need to update with the current time
this.updateTimeLeft(this.record.currentTime());
// Set the duration of the progress bar based upon the track duration
// Slider position is set in seconds
this.$el.find(this.dom.PLAYBAR_PROGRESS).slider("option", "max",
this.record.endTime() / 1000);
},
// Update the time left in playback of the track
updateTimeLeft: function(time) {
// Update the time indicator with a nicely formatted time
this.$el.find(".scratchpad-playbar-timeleft").text(
"-" + this.formatTime(this.record.endTime() - time));
},
// Utility method for formatting time in minutes/seconds
formatTime: function(time) {
var seconds = time / 1000,
min = Math.floor(seconds / 60),
sec = Math.floor(seconds % 60);
if (min < 0 || sec < 0) {
min = 0;
sec = 0;
}
return min + ":" + (sec < 10 ? "0" : "") + sec;
},
// Seek the player to a particular time
seekTo: function(timeMS) {
// Don't update the slider position when seeking
// (since this triggers an event on the #progress element)
if (!this.record.seeking) {
this.$el.find(this.dom.PLAYBAR_PROGRESS)
.slider("option", "value", timeMS / 1000);
}
// Move the recording and player positions
if (this.record.seekTo(timeMS) !== false) {
this.player.setPosition(timeMS);
}
},
handleMessages: function(e) {