-
Notifications
You must be signed in to change notification settings - Fork 239
/
tutorial.js
1734 lines (1402 loc) · 49.7 KB
/
tutorial.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
/* Tutorial construction and initialization */
$(document).ready(function() {
var tutorial = new Tutorial();
// register autocompletion if available
if (typeof TutorialCompleter !== "undefined")
tutorial.$completer = new TutorialCompleter(tutorial);
// register diagnostics if available
if (typeof TutorialDiagnostics !== "undefined")
tutorial.$diagnostics = new TutorialDiagnostics(tutorial);
window.tutorial = tutorial;
});
// this var lets us know if the Shiny server is ready to handle http requests
var tutorial_isServerAvailable = false;
function Tutorial() {
// Alias this
var thiz = this;
// Init timing log
this.$initTimingLog();
// API: provide init event
this.onInit = function(handler) {
this.$initCallbacks.add(handler);
};
// API: provide progress events
this.onProgress = function(handler) {
this.$progressCallbacks.add(handler);
};
// API: Start the tutorial over
this.startOver = function() {
thiz.$removeState(function() {
thiz.$serverRequest("remove_state", null, function() {
window.location.replace(window.location.origin + window.location.pathname);
});
});
};
// API: Skip a section
this.skipSection = function(sectionId) {
// wait for shiny config to be available (required for $serverRequest)
if (tutorial_isServerAvailable)
thiz.$serverRequest("section_skipped", { sectionId: sectionId }, null);
};
// API: scroll an element into view
this.scrollIntoView = function(element) {
element = $(element);
var rect = element[0].getBoundingClientRect();
if (rect.top < 0 || rect.bottom > $(window).height()) {
if (element[0].scrollIntoView) {
element[0].scrollIntoView(false);
document.body.scrollTop += 20;
}
}
};
// Initialization
thiz.$initializeVideos();
thiz.$initializeExercises();
thiz.$initializeServer();
}
/* Utilities */
Tutorial.prototype.$initTimingLog = function() {
try {
if (performance.mark !== undefined) {
performance.mark("tutorial-start-mark");
}
} catch(e) {
console.log("Error initializing log timing: " + e.message);
}
};
Tutorial.prototype.$logTiming = function(name) {
try {
if (performance.mark !== undefined &&
performance.measure !== undefined &&
performance.getEntriesByName !== undefined &&
this.queryVar('log-timings') === '1') {
performance.mark(name + "-mark");
performance.measure(name, "tutorial-start-mark", name + "-mark");
var entries = performance.getEntriesByName(name);
console.log("(Timing) " + name + ": " + Math.round(entries[0].duration) + "ms");
}
} catch(e) {
console.log("Error logging timing: " + e.message);
}
};
Tutorial.prototype.queryVar = function(name) {
return decodeURI(window.location.search.replace(
new RegExp("^(?:.*[&\\?]" +
encodeURI(name).replace(/[\.\+\*]/g, "\\$&") +
"(?:\\=([^&]*))?)?.*$", "i"),
"$1"));
};
Tutorial.prototype.$idSelector = function(id) {
return "#" + id.replace( /(:|\.|\[|\]|,|=|@)/g, "\\$1" );
};
// static method to trigger MathJax
Tutorial.triggerMathJax = function() {
if (window.MathJax) {
MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
}
}
/* Init callbacks */
Tutorial.prototype.$initCallbacks = $.Callbacks();
Tutorial.prototype.$fireInit = function() {
// Alias this
var thiz = this;
// fire event
try {
thiz.$initCallbacks.fire();
} catch (e) {
console.log(e);
}
};
/* Progress callbacks */
Tutorial.prototype.$progressCallbacks = $.Callbacks();
Tutorial.prototype.$progressEvents = [];
Tutorial.prototype.$hasCompletedProgressEvent = function(element) {
var thiz = this;
for (var e = 0; e<thiz.$progressEvents.length; e++) {
var event = thiz.$progressEvents[e];
if ($(event.element).is($(element))) {
if (event.completed)
return true;
}
}
return false;
};
Tutorial.prototype.$fireProgress = function(event) {
// record it
this.$progressEvents.push(event);
// fire event
try {
this.$progressCallbacks.fire(event);
} catch (e) {
console.log(e);
}
};
Tutorial.prototype.$fireSectionCompleted = function(element) {
// Alias this
var thiz = this;
// helper function to fire section completed
function fireCompleted(el) {
var event = {
element: el,
event: "section_completed"
};
thiz.$fireProgress(event);
}
// find closest containing section (bail if there is none)
var section = $(element).parent().closest('.section');
if (section.length === 0)
return;
// get all interactive components in the section
var components = section.find('.tutorial-exercise, .tutorial-question, .tutorial-video');
// are they all completed?
var allCompleted = true;
for (var c = 0; c<components.length; c++) {
var component = components.get(c);
if (!thiz.$hasCompletedProgressEvent(component)) {
allCompleted = false;
break;
}
}
// if they are then fire event
if (allCompleted) {
// fire the event
fireCompleted($(section).get(0));
// fire for preceding siblings if they have no interactive components
var previousSections = section.prevAll('.section');
previousSections.each(function() {
var components = $(this).find('.tutorial-exercise, .tutorial-question');
if (components.length === 0)
fireCompleted(this);
});
// if there is another section above us then process it
var parentSection = section.parent().closest('.section');
if (parentSection.length > 0)
this.$fireSectionCompleted(section);
}
};
Tutorial.prototype.$removeConflictingProgressEvents = function(progressEvent) {
// Alias this
var thiz = this;
var event;
// work backwords as to avoid skipping a position caused by removing an element
for (var i = thiz.$progressEvents.length - 1; i >= 0; i--) {
event = thiz.$progressEvents[i];
if (event.event === "question_submission") {
if (
event.data.label === progressEvent.data.label &
progressEvent.data.label !== undefined
) {
// remove the item from existing progress events
thiz.$progressEvents.splice(i, 1)
return;
}
}
}
}
Tutorial.prototype.$fireProgressEvent = function(event, data) {
// Alias this
var thiz = this;
// progress event to fire
var progressEvent = { event: event, data: data };
// determine element and completed status
if (event == "exercise_submission" || event == "question_submission") {
var element = $('.tutorial-exercise[data-label="' + data.label + '"]').add(
'.tutorial-question[data-label="' + data.label + '"]');
if (element.length > 0) {
progressEvent.element = element;
if (event == "exercise_submission") {
// any progress event for an exercise is to complete only
progressEvent.completed = true;
} else {
// question_submission
// questions may be reset with "try again", and not in a completed state
progressEvent.completed = (data.answer !== null);
}
}
}
else if (event == "section_skipped") {
var exerciseElement = $(thiz.$idSelector(data.sectionId));
progressEvent.element = exerciseElement;
progressEvent.completed = false;
}
else if (event == "video_progress") {
var videoElement = $('iframe[src="' + data.video_url + '"]');
if (videoElement.length > 0) {
progressEvent.element = videoElement;
progressEvent.completed = (2*data.time) > data.total_time;
}
}
// remove any prior forms of this progressEvent
this.$removeConflictingProgressEvents(progressEvent)
// fire it if we found an element
if (progressEvent.element) {
// fire event
this.$fireProgress(progressEvent);
// synthesize higher level section completed events
thiz.$fireSectionCompleted(progressEvent.element);
}
};
Tutorial.prototype.$initializeProgress = function(progress_events) {
// Alias this
var thiz = this;
// replay progress messages from previous state
for (var i = 0; i<progress_events.length; i++) {
// get event
var progress = progress_events[i];
var progressEvent = progress.event;
// determine data
var progressEventData = {};
if (progressEvent == "exercise_submission") {
progressEventData.label = progress.data.label;
progressEventData.correct = progress.data.correct;
}
else if (progressEvent == "question_submission") {
progressEventData.label = progress.data.label;
progressEventData.answer = progress.data.answer;
}
else if (progressEvent == "section_skipped") {
progressEventData.sectionId = progress.data.sectionId;
}
else if (progressEvent == "video_progress") {
progressEventData.video_url = progress.data.video_url;
progressEventData.time = progress.data.time;
progressEventData.total_time = progress.data.total_time;
}
thiz.$fireProgressEvent(progressEvent, progressEventData);
}
// handle susequent progress messages
Shiny.addCustomMessageHandler("tutorial.progress_event", function(progress) {
thiz.$fireProgressEvent(progress.event, progress.data);
});
};
/* Shared utility functions */
Tutorial.prototype.$serverRequest = function (type, data, success, error) {
return $.ajax({
type: "POST",
url: "session/" + Shiny.shinyapp.config.sessionId +
"/dataobj/" + type + "?w=" + Shiny.shinyapp.config.workerId,
contentType: "application/json",
data: JSON.stringify(data),
dataType: "json",
success: success,
error: error
});
};
// Record an event
Tutorial.prototype.$recordEvent = function(label, event, data) {
var params = {
label: label,
event: event,
data: data
};
this.$serverRequest("record_event", params, null);
};
Tutorial.prototype.$countLines = function(str) {
return str.split(/\r\n|\r|\n/).length;
};
Tutorial.prototype.$injectScript = function(src, onload) {
var script = document.createElement('script');
script.src = src;
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(script, firstScriptTag);
$(script).on("load", onload);
};
Tutorial.prototype.$debounce = function(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
/* Videos */
Tutorial.prototype.$initializeVideos = function() {
// regexes for video types
var youtubeRegex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var vimeoRegex = /(?:vimeo)\.com.*(?:videos|video|channels|)\/([\d]+)/i;
// check a url for video typtes
function isYouTubeVideo(src) {
return src.match(youtubeRegex);
}
function isVimeoVideo(src) {
return src.match(vimeoRegex);
}
function isVideo(src) {
return isYouTubeVideo(src) || isVimeoVideo(src);
}
// function to normalize a video src url (web view -> embed)
function normalizeVideoSrc(src) {
// youtube
var youtubeMatch = src.match(youtubeRegex);
if (youtubeMatch)
return "https://www.youtube.com/embed/" + youtubeMatch[2] + "?enablejsapi=1";
// vimeo
var vimeoMatch = src.match(vimeoRegex);
if (vimeoMatch)
return "https://player.vimeo.com/video/" + vimeoMatch[1];
// default to reflecting src back
return src;
}
// function to set the width and height for the container conditioned on
// any user-specified height and width
function setContainerSize(container, width, height) {
// default ratio
var aspectRatio = 9 / 16;
// default width to 100% if not specified
if (!width)
width = "100%";
// percentage based width
if (width.slice(-1) == "%") {
container.css('width', width);
if (!height) {
height = 0;
var paddingBottom = (parseFloat(width) * aspectRatio) + '%';
container.css('padding-bottom', paddingBottom);
}
container.css('height', height);
}
// other width unit
else {
// add 'px' if necessary
if ($.isNumeric(width))
width = width + "px";
container.css('width', width);
if (!height)
height = (parseFloat(width) * aspectRatio) + 'px';
container.css('height', height);
}
}
// inspect all images to see if they contain videos
$("img").each(function() {
// skip if this isn't a video
var videoSrc = $(this).attr('src');
if (!isVideo(videoSrc))
return;
// hide while we process
$(this).css('display', 'none');
// collect various attributes
var width = $(this).get(0).style.width;
var height = $(this).get(0).style.height;
$(this).css('width', '').css('height', '');
var attrs = {};
$.each(this.attributes, function(idex, attr) {
if (attr.nodeName == "width")
width = String(attr.nodeValue);
else if (attr.nodeName == "height")
height = String(attr.nodeValue);
else if (attr.nodeName == "src")
attrs.src = normalizeVideoSrc(attr.nodeValue);
else
attrs[attr.nodeName] = attr.nodeValue;
});
// replace the image with the iframe inside a video container
$(this).replaceWith(function() {
var iframe = $('<iframe/>', attrs);
iframe.addClass('tutorial-video');
if (isYouTubeVideo(videoSrc))
iframe.addClass('tutorial-video-youtube');
else if (isVimeoVideo(videoSrc))
iframe.addClass('tutorial-video-vimeo');
iframe.attr('allowfullscreen', '');
iframe.css('display', '');
var container = $('<div class="tutorial-video-container"></div>');
setContainerSize(container, width, height);
container.append(iframe);
return container;
});
});
// we'll initialize video player APIs off of $restoreState
this.$logTiming("initialized-videos");
};
Tutorial.prototype.$initializeVideoPlayers = function(video_progress) {
// don't interact with video player APIs in Qt
if (/\bQt\//.test(window.navigator.userAgent))
return;
this.$initializeYouTubePlayers(video_progress);
this.$initializeVimeoPlayers(video_progress);
};
Tutorial.prototype.$videoPlayerRestoreTime = function(src, video_progress) {
// find a restore time for this video
for (var v = 0; v<video_progress.length; v++) {
var id = video_progress[v].id;
if (src == id) {
var time = video_progress[v].data.time;
var total_time = video_progress[v].data.total_time;
// don't return a restore time if we are within 10 seconds of the beginning
// or the end of the video.
if (time > 10 && ((total_time - time) > 10))
return time;
}
}
// no time to restore, return 0
return 0;
};
Tutorial.prototype.$initializeYouTubePlayers = function(video_progress) {
// YouTube JavaScript API
// https://developers.google.com/youtube/iframe_api_reference
// alias this
var thiz = this;
// attach to youtube videos
var videos = $('iframe.tutorial-video-youtube');
if (videos.length > 0) {
this.$injectScript('https://www.youtube.com/iframe_api', function() {
YT.ready(function() {
videos.each(function() {
// video and player
var video = $(this);
var videoUrl = video.attr('src');
var player = null;
var lastState = -1;
// helper to report progress to the server
function reportProgress() {
thiz.$reportVideoProgress(videoUrl,
player.getCurrentTime(),
player.getDuration());
}
// helper to restore video time. attempt to restore to 10 seconds prior
// to the last save point (to recapture frame of reference)
function restoreTime() {
var restoreTime = thiz.$videoPlayerRestoreTime(videoUrl, video_progress);
if (restoreTime > 0) {
player.mute();
player.playVideo();
setTimeout(function() {
player.pauseVideo();
player.seekTo(restoreTime, true);
player.unMute();
}, 2000);
}
}
// function to call onReady
function onReady() {
restoreTime();
}
// function to call on state changed
function onStateChange() {
// get current state
var state = player.getPlayerState();
// don't report for unstarted & queued
if (state == -1 || state == YT.PlayerState.CUED) {
}
// always report progress for playing
else if (state == YT.PlayerState.PLAYING) {
reportProgress();
}
// report for other states as long as they aren't duplicates
else if (state != lastState) {
reportProgress();
}
// update last state
lastState = state;
}
// create the player
player = new YT.Player(this, { events: {
'onReady': onReady,
'onStateChange': onStateChange
}
});
// poll for state change every 5 seconds
window.setInterval(onStateChange, 5000);
});
});
});
}
};
Tutorial.prototype.$initializeVimeoPlayers = function(video_progress) {
// alias this
var thiz = this;
// Vimeo JavaScript API
// https://github.com/vimeo/player.js
var videos = $('iframe.tutorial-video-vimeo');
if (videos.length > 0) {
this.$injectScript('https://player.vimeo.com/api/player.js', function() {
videos.each(function() {
// video and player
var video = $(this)
var videoUrl = video.attr('src');
var player = new Vimeo.Player(this);
var lastReportedTime = null;
// restore time if we can
player.ready().then(function() {
var restoreTime = thiz.$videoPlayerRestoreTime(videoUrl, video_progress);
if (restoreTime > 0) {
player.getVolume().then(function(volume) {
player.setCurrentTime(restoreTime).then(function() {
player.pause().then(function() {
player.setVolume(volume);
});
});
});
}
});
// helper function to report progress
function reportProgress(data, throttle) {
// default throttle to false
if (throttle === undefined)
throttle = false;
// if we are throttling then don't report if the last
// reported time is within 5 seconds
if (throttle && (lastReportedTime != null) &&
((data.seconds - lastReportedTime) < 5)) {
return;
}
// report progress
thiz.$reportVideoProgress(videoUrl, data.seconds, data.duration);
lastReportedTime = data.seconds;
}
// report progress on various events
player.on('play', reportProgress);
player.on('pause', reportProgress);
player.on('ended', reportProgress);
player.on('timeupdate', function(data) {
reportProgress(data, true);
});
});
});
}
};
Tutorial.prototype.$reportVideoProgress = function(video_url, time, total_time) {
this.$serverRequest("video_progress", {
"video_url": video_url,
"time": time,
"total_time": total_time
});
};
/* Exercise initialization and shared utility functions */
Tutorial.prototype.$initializeExercises = function() {
this.$initializeExerciseEditors();
this.$initializeExerciseSolutions();
this.$initializeExerciseEvaluation();
this.$logTiming("initialized-exercises");
};
Tutorial.prototype.$exerciseForLabel = function(label) {
return $('.tutorial-exercise[data-label="' + label + '"]');
};
Tutorial.prototype.$forEachExercise = function(operation) {
return $(".tutorial-exercise").each(function() {
var exercise = $(this);
operation(exercise);
});
};
Tutorial.prototype.$exerciseSupportCode = function(label) {
var selector = '.tutorial-exercise-support[data-label="' + label + '"]';
var code = $(selector).children('pre').children('code');
if (code.length > 0)
return code.text();
else
return null;
};
Tutorial.prototype.$exerciseSolutionCode = function(label) {
return this.$exerciseSupportCode(label + "-solution");
};
Tutorial.prototype.$exerciseCheckCode = function(label) {
return this.$exerciseSupportCode(label + "-check");
};
Tutorial.prototype.$exerciseHintDiv = function(label) {
// look for a div w/ hint id
var id = "section-" + label + "-hint";
var hintDiv = $('div#' + id);
// ensure it isn't a section then return
if (hintDiv.length > 0 && !hintDiv.hasClass('section'))
return hintDiv;
else
return null;
};
Tutorial.prototype.$exerciseHintsCode = function(label) {
// look for a single hint
var hint = this.$exerciseSupportCode(label + "-hint");
if (hint !== null)
return [hint];
// look for a sequence of hints
var hints = [];
var index = 1;
while(true) {
var hintLabel = label + "-hint-" + index++;
hint = this.$exerciseSupportCode(hintLabel);
if (hint !== null)
hints.push(hint);
else
break;
}
// return what we have (null if empty)
if (hints.length > 0)
return hints;
else
return null;
};
// get the exercise container of an element
Tutorial.prototype.$exerciseContainer = function(el) {
return $(el).closest(".tutorial-exercise");
};
// show progress for exercise
Tutorial.prototype.$showExerciseProgress = function(label, button, show) {
// references to various UI elements
var exercise = this.$exerciseForLabel(label);
var outputFrame = exercise.children('.tutorial-exercise-output-frame');
var runButtons = exercise.find('.btn-tutorial-run');
// if the button is "run" then use the run button
if (button === "run")
button = exercise.find('.btn-tutorial-run').last();
// show/hide progress UI
var spinner = 'fa-spinner fa-spin fa-fw';
if (show) {
outputFrame.addClass('recalculating');
runButtons.addClass('disabled');
if (button !== null) {
var runIcon = button.children('i');
runIcon.removeClass(button.attr('data-icon'));
runIcon.addClass(spinner);
}
}
else {
outputFrame.removeClass('recalculating');
runButtons.removeClass('disabled');
runButtons.each(function() {
var button = $(this);
var runIcon = button.children('i');
runIcon.addClass(button.attr('data-icon'));
runIcon.removeClass(spinner);
});
}
};
// behavior constants
Tutorial.prototype.kMinLines = 3;
// edit code within an ace editor
Tutorial.prototype.$attachAceEditor = function(target, code) {
var editor = ace.edit(target);
editor.setHighlightActiveLine(false);
editor.setShowPrintMargin(false);
editor.setShowFoldWidgets(false);
editor.setBehavioursEnabled(true);
editor.renderer.setDisplayIndentGuides(false);
editor.setTheme("ace/theme/textmate");
editor.$blockScrolling = Infinity;
editor.session.setMode("ace/mode/r");
editor.session.getSelection().clearSelection();
editor.setValue(code, -1);
return editor;
};
/* Exercise editor */
Tutorial.prototype.$exerciseEditor = function(label) {
return this.$exerciseForLabel(label).find('.tutorial-exercise-code-editor');
};
Tutorial.prototype.$initializeExerciseEditors = function() {
// alias this
var thiz = this;
this.$forEachExercise(function(exercise) {
// capture label and caption
var label = exercise.attr('data-label');
var caption = exercise.attr('data-caption');
// helper to create an id
function create_id(suffix) {
return "tutorial-exercise-" + label + "-" + suffix;
}
// when we receive focus hide solutions in other exercises
exercise.on('focusin', function() {
$('.btn-tutorial-solution').each(function() {
if (exercise.has($(this)).length === 0)
thiz.$removeSolution(thiz.$exerciseContainer($(this)));
});
});
// get all <pre class='text'> elements, get their code, then remove them
var code = '';
var code_blocks = exercise.children('pre.text, pre.lang-text');
code_blocks.each(function() {
var code_element = $(this).children('code');
if (code_element.length > 0)
code = code + code_element.text();
else
code = code + $(this).text();
});
code_blocks.remove();
// ensure a minimum of 3 lines
var lines = code.split(/\r\n|\r|\n/).length;
for (var i=lines; i<thiz.kMinLines;i++)
code = code + "\n";
// get the knitr options script block and detach it (will move to input div)
var options_script = exercise.children('script[data-opts-chunk="1"]').detach();
// wrap the remaining elements in an output frame div
exercise.wrapInner('<div class="tutorial-exercise-output-frame"></div>');
var output_frame = exercise.children('.tutorial-exercise-output-frame');
// create input div
var input_div = $('<div class="tutorial-exercise-input panel panel-default"></div>');
input_div.attr('id', create_id('input'));
// creating heading
var panel_heading = $('<div class="panel-heading tutorial-panel-heading"></div>');
panel_heading.text(caption);
input_div.append(panel_heading);
// create body
var panel_body = $('<div class="panel-body"></div>');
input_div.append(panel_body);
// function to add a submit button
function add_submit_button(icon, style, text, check) {
var button = $('<a class="btn ' + style + ' btn-xs btn-tutorial-run ' +
'pull-right"></a>');
button.append($('<i class="fa ' + icon + '"></i>'));
button.attr('type', 'button');
button.append(' ' + text);
var isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
var title = text;
if (!check)
title = title + " (" + (isMac ? "Cmd" : "Ctrl") + "+Shift+Enter)";
button.attr('title', title);
if (check)
button.attr('data-check', '1');
button.attr('data-icon', icon);
button.on('click', function() {
thiz.$removeSolution(exercise);
thiz.$showExerciseProgress(label, button, true);
});
panel_heading.append(button);
return button;
}
// create submit answer button if checks are enabled
if (thiz.$exerciseCheckCode(label) !== null)
add_submit_button("fa-check-square-o", "btn-primary", "Submit Answer", true);
// create run button
var run_button = add_submit_button("fa-play", "btn-success", "Run Code", false);
// create code div and add it to the input div
var code_div = $('<div class="tutorial-exercise-code-editor"></div>');
var code_id = create_id('code-editor');
code_div.attr('id', code_id);
panel_body.append(code_div);
// add the knitr options script to the input div
panel_body.append(options_script);
// prepend the input div to the exercise container
exercise.prepend(input_div);
// create an output div and append it to the output_frame
var output_div = $('<div class="tutorial-exercise-output"></div>');
output_div.attr('id', create_id('output'));
output_frame.append(output_div);
// activate the ace editor
var editor = thiz.$attachAceEditor(code_id, code);
// get setup_code (if any)
var setup_code = null;
var chunk_options = options_script.length == 1 ? JSON.parse(options_script.text()) : {};
if (chunk_options["exercise.setup"])
setup_code = thiz.$exerciseSupportCode(chunk_options["exercise.setup"]);
else
setup_code = thiz.$exerciseSupportCode(label + "-setup");
// use code completion
var completion = exercise.attr('data-completion') === "1";
var diagnostics = exercise.attr('data-diagnostics') === "1";
// support startover
var startover_code = exercise.attr('data-startover') === "1" ? code : null;
// set tutorial options/data
editor.tutorial = {
label: label,
setup_code: setup_code,
completion: completion,
diagnostics: diagnostics,
startover_code: startover_code
};
// bind execution keys
function bindExecutionKey(name, key) {
var macKey = key.replace("Ctrl+", "Command+");
editor.commands.addCommand({
name: name,
bindKey: {win: key, mac: macKey},
exec: function(editor) {
run_button.trigger('click');
}
});
}
bindExecutionKey("execute1", "Ctrl+Enter");
bindExecutionKey("execute2", "Ctrl+Shift+Enter");
// re-focus the editor on run button click
run_button.on('click', function() {