-
Notifications
You must be signed in to change notification settings - Fork 240
/
tutorial.js
1907 lines (1656 loc) · 55.5 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
/* global $,Shiny,ace,MathJax,Clipboard,YT,Vimeo,performance */
/* Tutorial construction and initialization */
import { TutorialDiagnostics } from './tutorial-diagnostics.mjs'
import { TutorialCompleter } from './tutorial-autocompletion.mjs'
$(document).ready(function () {
const 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
let TUTORIAL_IS_SERVER_AVAILABLE = false
function Tutorial () {
// Alias this
const 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_IS_SERVER_AVAILABLE) {
thiz.$serverRequest('section_skipped', { sectionId: sectionId }, null)
}
}
// API: scroll an element into view
this.scrollIntoView = function (element) {
element = $(element)
const 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')
const 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
const 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) {
const thiz = this
for (let e = 0; e < thiz.$progressEvents.length; e++) {
const 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
const thiz = this
// helper function to fire section completed
function fireCompleted (el) {
const event = {
element: el,
event: 'section_completed'
}
thiz.$fireProgress(event)
}
// find closest containing section (bail if there is none)
const section = $(element)
.parent()
.closest('.section')
if (section.length === 0) {
return
}
// get all interactive components in the section
const components = section.find(
'.tutorial-exercise, .tutorial-question, .tutorial-video'
)
// are they all completed?
let allCompleted = true
for (let c = 0; c < components.length; c++) {
const 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
const previousSections = section.prevAll('.section')
previousSections.each(function () {
const components = $(this).find('.tutorial-exercise, .tutorial-question')
if (components.length === 0) {
fireCompleted(this)
}
})
// if there is another section above us then process it
const parentSection = section.parent().closest('.section')
if (parentSection.length > 0) {
this.$fireSectionCompleted(section)
}
}
}
Tutorial.prototype.$removeConflictingProgressEvents = function (progressEvent) {
// Alias this
const thiz = this
let event
// work backwards as to avoid skipping a position caused by removing an element
for (let 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
const thiz = this
// progress event to fire
const progressEvent = { event: event, data: data }
// determine element and completed status
if (event === 'exercise_submission' || event === 'question_submission') {
const 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') {
// Exercise completion logic is determined by the default exercise_result
// event handler in the Shiny logic that emits an "exercise_submission" event.
// If the handler doesn't returned a completed flag, we assume `true`.
progressEvent.completed =
typeof data.completed !== 'undefined' ? data.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') {
const exerciseElement = $(thiz.$idSelector(data.sectionId))
progressEvent.element = exerciseElement
progressEvent.completed = false
} else if (event === 'video_progress') {
const 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 (progressEvents) {
// Alias this
const thiz = this
// replay progress messages from previous state
for (let i = 0; i < progressEvents.length; i++) {
// get event
const progress = progressEvents[i]
const progressEvent = progress.event
// determine data
const 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 subsequent 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) {
const { sessionId, workerId } = Shiny.shinyapp.config
return $.ajax({
type: 'POST',
url: `session/${sessionId}/dataobj/${type}?w=${workerId}`,
contentType: 'application/json',
data: JSON.stringify(data),
dataType: 'json',
success: success,
error: error
})
}
// Record an event
Tutorial.prototype.$recordEvent = function (label, event, data) {
const 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) {
const script = document.createElement('script')
script.src = src
const firstScriptTag = document.getElementsByTagName('script')[0]
firstScriptTag.parentNode.insertBefore(script, firstScriptTag)
$(script).on('load', onload)
}
Tutorial.prototype.$debounce = function (func, wait, immediate) {
let timeout
return function () {
const context = this
const args = arguments
const later = function () {
timeout = null
if (!immediate) func.apply(context, args)
}
const callNow = immediate && !timeout
clearTimeout(timeout)
timeout = setTimeout(later, wait)
if (callNow) func.apply(context, args)
}
}
/* Videos */
Tutorial.prototype.$initializeVideos = function () {
// regexes for video types
const youtubeRegex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/
const vimeoRegex = /(?:vimeo)\.com.*(?:videos|video|channels|)\/([\d]+)/i
// check a url for video types
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
const youtubeMatch = src.match(youtubeRegex)
if (youtubeMatch) {
return `https://www.youtube.com/embed/${youtubeMatch[2]}?enablejsapi=1`
}
// vimeo
const 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
const 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
const paddingBottom = parseFloat(width) * aspectRatio + '%'
container.css('padding-bottom', paddingBottom)
}
container.css('height', height)
} else {
// or another width unit, adding '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
const videoSrc = $(this).attr('src')
if (!isVideo(videoSrc)) {
return
}
// hide while we process
$(this).css('display', 'none')
// collect various attributes
let width = $(this).get(0).style.width
let height = $(this).get(0).style.height
$(this)
.css('width', '')
.css('height', '')
const attrs = {}
$.each(this.attributes, function (idex, attr) {
switch (attr.nodeName) {
case 'width': {
width = String(attr.nodeValue)
break
}
case 'height': {
height = String(attr.nodeValue)
break
}
case 'src': {
attrs.src = normalizeVideoSrc(attr.nodeValue)
break
}
default: {
attrs[attr.nodeName] = attr.nodeValue
}
}
})
// replace the image with the iframe inside a video container
$(this).replaceWith(function () {
const 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', '')
const 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 (videoProgress) {
// don't interact with video player APIs in Qt
if (/\bQt\//.test(window.navigator.userAgent)) {
return
}
this.$initializeYouTubePlayers(videoProgress)
this.$initializeVimeoPlayers(videoProgress)
}
Tutorial.prototype.$videoPlayerRestoreTime = function (src, videoProgress) {
// find a restore time for this video
for (let v = 0; v < videoProgress.length; v++) {
const id = videoProgress[v].id
if (src === id) {
const time = videoProgress[v].data.time
const totalTime = videoProgress[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 && totalTime - time > 10) {
return time
}
}
}
// no time to restore, return 0
return 0
}
Tutorial.prototype.$initializeYouTubePlayers = function (videoProgress) {
// YouTube JavaScript API
// https://developers.google.com/youtube/iframe_api_reference
// alias this
const thiz = this
// attach to youtube videos
const 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
const video = $(this)
const videoUrl = video.attr('src')
let player = null
let 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 () {
const restoreTime = thiz.$videoPlayerRestoreTime(
videoUrl,
videoProgress
)
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
const state = player.getPlayerState()
const isNotStarted = state === -1
const isCued = state === YT.PlayerState.CUED
const isPlaying = state === YT.PlayerState.PLAYING
const isDuplicate = state === lastState
// don't report for unstarted & queued
// otherwise report if playing or non-duplicate state
if (!(isNotStarted || isCued) && (isPlaying || isDuplicate)) {
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 (videoProgress) {
// alias this
const thiz = this
// Vimeo JavaScript API
// https://github.com/vimeo/player.js
const 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
const video = $(this)
const videoUrl = video.attr('src')
const player = new Vimeo.Player(this)
let lastReportedTime = null
// restore time if we can
player.ready().then(function () {
const restoreTime = thiz.$videoPlayerRestoreTime(
videoUrl,
videoProgress
)
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 (videoUrl, time, totalTime) {
this.$serverRequest('video_progress', {
video_url: videoUrl,
time: time,
total_time: totalTime
})
}
/* 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 () {
const exercise = $(this)
operation(exercise)
})
}
Tutorial.prototype.$exerciseSupportCode = function (label) {
const selector = '.tutorial-exercise-support[data-label="' + label + '"]'
const 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.$exerciseHintDiv = function (label) {
// look for a div w/ hint id
const id = 'section-' + label + '-hint'
const 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
let hint = this.$exerciseSupportCode(label + '-hint')
if (hint !== null) {
return [hint]
}
// look for a sequence of hints
const hints = []
let index = 1
while (true) {
const 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
const exercise = this.$exerciseForLabel(label)
const outputFrame = exercise.children('.tutorial-exercise-output-frame')
const 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
const spinner = 'fa-spinner fa-spin fa-fw'
if (show) {
outputFrame.addClass('recalculating')
runButtons.addClass('disabled')
if (button !== null) {
const runIcon = button.children('i')
runIcon.removeClass(button.attr('data-icon'))
runIcon.addClass(spinner)
}
} else {
outputFrame.removeClass('recalculating')
runButtons.removeClass('disabled')
runButtons.each(function () {
const button = $(this)
const 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) {
const 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
const thiz = this
this.$forEachExercise(function (exercise) {
// get the knitr options script block and detach it (will move to input div)
const optsScript = exercise.children('script[data-ui-opts="1"]').detach()
const optsChunk =
optsScript.length === 1 ? JSON.parse(optsScript.text()) : {}
// capture label and caption
const label = exercise.attr('data-label')
const caption = optsChunk.caption
// helper to create an id
function createId (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
let code = ''
const codeBlocks = exercise.children('pre.text, pre.lang-text')
codeBlocks.each(function () {
const codeElement = $(this).children('code')
if (codeElement.length > 0) {
code = code + codeElement.text()
} else {
code = code + $(this).text()
}
})
codeBlocks.remove()
// ensure a minimum of 3 lines
const lines = code.split(/\r\n|\r|\n/).length
for (let i = lines; i < thiz.kMinLines; i++) {
code = code + '\n'
}
// wrap the remaining elements in an output frame div
exercise.wrapInner('<div class="tutorial-exercise-output-frame"></div>')
const outputFrame = exercise.children('.tutorial-exercise-output-frame')
// create input div
const inputDiv = $(
'<div class="tutorial-exercise-input panel panel-default"></div>'
)
inputDiv.attr('id', createId('input'))
// creating heading
const panelHeading = $(
'<div class="panel-heading tutorial-panel-heading"></div>'
)
inputDiv.append(panelHeading)
const panelHeadingLeft = $(
'<div class="tutorial-panel-heading-left"></div>'
)
const panelHeadingRight = $(
'<div class="tutorial-panel-heading-right"></div>'
)
panelHeading.append(panelHeadingLeft)
panelHeading.append(panelHeadingRight)
panelHeadingLeft.html(caption)
// create body
const panelBody = $('<div class="panel-body"></div>')
inputDiv.append(panelBody)
// function to add a submit button
function addSubmitButton (icon, style, text, check, datai18n) {
const button = $(
'<button class="btn ' + style + ' btn-xs btn-tutorial-run"></button>'
)
button.append($('<i class="fa ' + icon + '"></i>'))
button.append(
' ' + '<span data-i18n="button.' + datai18n + '">' + text + '</span>'
)
const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0
let title = text
const kbdText = (isMac ? 'Cmd' : 'Ctrl') + '+Shift+Enter'
if (!check) {
title = title + ' (' + kbdText + ')'
button.attr('data-i18n-opts', '{"kbd": "' + kbdText + '"}')
}
button.attr('title', title)
button.attr('data-i18n', '')
button.attr('data-i18n-attr-title', 'button.' + datai18n + '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)
})
panelHeadingRight.append(button)
return button
}
// create run button
const runButton = addSubmitButton(
'fa-play',
'btn-success',
'Run Code',
false,
'runcode'
)
// create submit answer button if checks are enabled
if (optsChunk.has_checker) {
addSubmitButton(
'fa-check-square-o',
'btn-primary',
'Submit Answer',
true,
'submitanswer'
)
}
// create code div and add it to the input div
const codeDiv = $('<div class="tutorial-exercise-code-editor"></div>')
const codeDivId = createId('code-editor')
codeDiv.attr('id', codeDivId)
panelBody.append(codeDiv)
// add the knitr options script to the input div
panelBody.append(optsScript)
// prepend the input div to the exercise container