This repository has been archived by the owner on May 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 866
/
interface.js
1263 lines (1090 loc) · 44.6 KB
/
interface.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(csilvers): fix these lint errors (http://eslint.org/docs/rules): */
/* eslint-disable comma-dangle, indent, max-len, no-undef, no-var, one-var, space-after-keywords, space-before-function-paren */
/* To fix, remove an entry above, run ka-lint, and fix errors. */
/**
* Interface glue to handle events from 'Exercises' and talk to 'Khan' or some
* Perseus object, whichever is appropriate for the current exercise.
*
* Specifically, this module does three things:
* - listen for DOM click events on various buttons.
*
* In the mobile context, some of these are triggered programmatically by
* `mobile-client-webview-resources/javascript/
* exercises-package/mobile-exercises.js`.
*
* - check answer
* - skip question
* - opt out
* - show next hint
* - show worked example
* - next question
* - toggle scratchpad
*
* - trigger events for khan-exercises / perseus on the global `Exercises`
* event bus.
* - send network requests.
*
* In general, khan-exercises and perseus will want to trigger events on
* Exercises but only listen to their own events.
*/
(function() {
function hideProblemUIOnError(statusText) {
// Hide the page so users don't continue, then warn the user about the
// problem and encourage reloading the page
$("#problem-and-answer").css("visibility", "hidden");
if (statusText === "timeout") {
// TODO(david): Instead of throwing up this error message, try
// retrying the request or something. See more details in
// comment in request().
$(Exercises).trigger("warning",
i18n._("Uh oh, it looks like a network request timed out! " +
"You'll need to " +
"<a href='%(refresh)s'>refresh</a> to continue. " +
"If you think this is a mistake, " +
"<a href='http://www.khanacademy.org/reportissue?" +
"type=Defect'>tell us</a>.",
{refresh: _.escape(window.location.href)}
)
);
} else {
$(Exercises).trigger("warning",
i18n._("This page is out of date. You need to " +
"<a href='%(refresh)s'>refresh</a>, but don't " +
"worry, you haven't lost progress. If you think " +
"this is a mistake, " +
"<a href='http://www.khanacademy.org/reportissue?" +
"type=Defect'>tell us</a>.",
{refresh: _.escape(window.location.href)}
)
);
}
}
/**
* Make an HTTP request with the given parameters, retrying on failure
* according to the retry strategy provided, and returning a Promise that
* resolves or rejects with the results of the request.
*
* params -- the parameters of the HTTP request
* determineWhetherRequestShouldRetry -- a function that takes a retry index
* and returns a Promise that resolves to `true` if the request should be
* retried, and `false` if not. The default strategy is to never retry.
*/
function requestForParamsWithRetry(params,
determineWhetherRequestShouldRetry) {
// Given a function `f`, which returns a Promise, attempt to
// resolve the returned Promise, retrying on failure based on
// the responses of `determineWhetherRequestShouldRetry`.
function retry(f, retryIndex) {
retryIndex = retryIndex || 0;
return f().catch(function(error) {
if (determineWhetherRequestShouldRetry) {
return determineWhetherRequestShouldRetry(
retryIndex, error
).then(
function(shouldRetry) {
if (shouldRetry) {
return retry(f, retryIndex + 1);
} else {
throw error;
}
}
);
} else {
throw error;
}
});
}
function makeRequest() {
var request = $.kaOauthAjax(params);
// Convert the jQuery.Deferred object to a true Promise, which
// can only take one value on resolution or rejection.
return new Promise(function(resolve, reject) {
request.done(function(data, textStatus, jqXHR) {
resolve({
data: data,
textStatus: textStatus,
jqXHR: jqXHR
});
});
request.fail(function(jqXHR, textStatus, errorThrown) {
reject({
jqXHR: jqXHR,
textStatus: textStatus,
errorThrown: errorThrown
});
});
});
}
return retry(makeRequest);
}
function saveAttemptToServer(url, attemptData, onError,
determineWhetherRequestShouldRetry) {
var requestForParams = function(params) {
return requestForParamsWithRetry(
params, determineWhetherRequestShouldRetry
);
};
// Save the problem results to the server
var requestProm = request(url, attemptData, requestForParams).catch(
function(error) {
// Alert any listeners of the error before reload
$(Exercises).trigger("attemptError");
if (inUnload) {
// This path gets called when there is a broken pipe during
// page unload- browser navigating away during ajax request
// See http://stackoverflow.com/a/1370383.
return;
}
// Trigger any custom callbacks.
onError && onError(error.statusText);
// Also log this failure to a bunch of places so we can see
// how frequently this occurs, and if it's similar to the frequency
// that we used to get for the endless spinner at end of task card
// logs.
var logMessage = "[" + (+new Date()) + "] request to " +
url + " failed (" + error.jqXHR.status + ", " +
error.statusText + ") " + "with " +
(Exercises.pendingAPIRequests - 1) +
" other pending API requests: " +
attemptOrHintQueueUrls +
" (in khan-exercises/interface.js:handleAttempt)";
// Log to app engine logs... hopefully.
$.post("/sendtolog", {message: logMessage, with_user: 1});
// Also log to Sentry via Raven, just for some redundancy in case
// the above request doesn't make it to our server somehow.
if (window.Raven) {
window.Raven.captureMessage(
logMessage, {tags: {ipaddebugging: true}});
}
}
);
return requestProm;
}
/**
* An offline-available record of the hints the user has taken.
*
* Whenever the user takes a hint, we note the exercise and problem number in
* this record, who then saves it to local storage. This is done so that we can
* detect the case of a user taking a hint offline, then reconnecting.
*/
var OfflineHintRecord = {
// The local storage key we'll use to store the set
LS_KEY: "khan-exercises-interface-persistent-hint-set",
/**
* Creates an item to store in the set for a given problem.
*
* This function assumes that its arguments are valid (see _areArgsValid
* for the definition of "valid").
*/
_makeItem: function(userExercise, problemNumber) {
return (
userExercise.user + ":" +
userExercise.exerciseModel.name + ":" +
problemNumber);
},
/**
* Returns true if the parameters are valid.
*
* This is used to make sure we have all the data we need when checking the
* hint record, and when we store things in the hint record.
*/
_areArgsValid: function(userExercise, problemNumber) {
return (
// If we have a unique way to identify the exercise
userExercise && userExercise.exerciseModel.name &&
// If the problem number is useable
_.isNumber(problemNumber) &&
// If we have a unique way to identify the user
userExercise && userExercise.user);
},
/**
* Returns whether the user has taken a hint for a given problem.
*
* This accesses information stored in local storage by saveHintTakenForLS.
*
* Note that if local storage is unavailable, this function will *always*
* return false, even if there is a hint on screen right now.
*/
hasTakenHintFor: function(userExercise, problemNumber) {
if (!OfflineHintRecord._areArgsValid(userExercise, problemNumber)) {
return false;
}
var raw = null;
try {
raw = localStorage.getItem(OfflineHintRecord.LS_KEY);
} catch (e) { /* ignore */ }
// If we couldn't get anything useful out of local storage, just return
// false.
if (!raw) {
return false;
}
var list = JSON.parse(raw);
if (!list) {
return false;
}
return _.contains(list, OfflineHintRecord._makeItem(userExercise,
problemNumber));
},
/**
* Marks that a user has taken a hint for a given problem.
*
* This stores information in local storage, to be retrieved later by
* hasTakenHintFor.
*
* Note that if local storage is unavailable, this will fail silently.
*/
saveHintTakenFor: function(userExercise, problemNumber) {
if (!OfflineHintRecord._areArgsValid(userExercise, problemNumber)) {
return false;
}
var raw = null;
try {
raw = localStorage.getItem(OfflineHintRecord.LS_KEY);
} catch (e) { /* ignore */ }
var list = [];
if (raw) {
list = JSON.parse(raw) || [];
}
list.push(OfflineHintRecord._makeItem(userExercise, problemNumber));
// Make sure the list doesn't get too big and make sure all of its
// items are unique (this is done as a cheap method of compression).
list = _.last(_.unique(list), 40);
try {
localStorage.setItem(OfflineHintRecord.LS_KEY,
JSON.stringify(list));
} catch(e) { /* ignore */ }
},
};
// If any of these properties have already been defined, then leave them --
// this happens in local mode
_.defaults(Exercises, {
khanExercisesUrlBase: "/khan-exercises/",
requestTimeoutMillis: 30000
});
_.extend(Exercises, {
guessLog: undefined,
userActivityLog: undefined,
interactiveAPI: {
checkAnswer: handleCheckAnswerEvent,
goToNextProblem: triggerNextProblem,
skipQuestion: handleSkipEvent,
showHint: onHintButtonClicked,
initReportIssueLink: Khan.initReportIssueLink,
},
// These functions allow a client to interact imperatively with the
// exercises machinery, instead of simulating button clicks, listening for
// events, etc.
imperativeAPI: {
handleAttempt: handleAttempt,
showHint: showHint,
// TODO(charlie): When iOS adopts the ProblemViewController API,
// deprecate this endpoint in favor of `showHint`.
showNextHint: showNextHint,
},
});
// The iOS app doesn't use cookies, so we need to send this as an oauth request
// (while letting the webapp send its AJAX request as before).
$.kaOauthAjax = function (options) {
if ($.oauth) {
return $.oauth(options);
} else {
return $.ajax(options);
}
};
var PerseusBridge = Exercises.PerseusBridge,
EMPTY_MESSAGE = i18n._("There are still more parts of this question to answer."),
// Store these here so that they're hard to change after the fact via
// bookmarklet, etc.
previewingItem,
originalCheckAnswerText,
userExercise,
problemNum,
interfaceFunctions,
canAttempt,
hintsAreFree,
attempts,
numHints,
hintsUsed,
lastAttemptOrHint,
lastAttemptContent;
$(Exercises)
.bind("problemTemplateRendered", problemTemplateRendered)
.bind("newProblem", newProblem)
.bind("hintShown", onHintShown)
.bind("readyForNextProblem", readyForNextProblem)
.bind("warning", warning)
.bind("upcomingExercise", upcomingExercise)
.bind("gotoNextProblem", gotoNextProblem)
.bind("updateUserExercise", updateUserExercise)
.bind("subhintExpand", subhintExpand)
.bind("clearExistingProblem", clearExistingProblem)
.bind("showOptOut", showOptOut);
function problemTemplateRendered(e, data) {
previewingItem = Exercises.previewingItem;
if (!data || !data.skipDOMManipulation) {
// Setup appropriate img URLs
$("#issue-throbber").attr("src",
Exercises.khanExercisesUrlBase + "css/images/throbber.gif");
$("#positive-reinforcement").hide();
// 'Check Answer' or 'Submit Answer'
originalCheckAnswerText = $("#check-answer-button").val();
// Solution submission
$("#check-answer-button").click(handleCheckAnswerEvent);
$("#answerform").submit(handleCheckAnswerEvent);
$("#skip-question-button").click(handleSkipEvent);
$("#opt-out-button").click(handleOptOutEvent);
// Hint button
$("#hint").click(onHintButtonClicked);
// Worked example button
$("#worked-example-button").click(onShowExampleClicked);
// Next question button
$("#next-question-button").click(function() {
triggerNextProblem();
// Disable next question button until next time
// TODO(alpert): Why? Is blurring not enough?
$(this)
.attr("disabled", true)
.addClass("buttonDisabled");
});
// If happy face is clicked, pass click on through.
$("#positive-reinforcement").click(function() {
$("#next-question-button").click();
});
// Let users close the warning bar when appropriate
$("#warning-bar-close a").click(function(e) {
e.preventDefault();
$("#warning-bar").fadeOut("slow");
});
// Scratchpad toggle
$("#scratchpad-show").click(function(e) {
e.preventDefault();
Khan.scratchpad.toggle();
if (userExercise.user) {
LocalStore.set("scratchpad:" + userExercise.user,
Khan.scratchpad.isVisible());
}
});
$(Khan).trigger("problemTemplateRendered");
}
// These shouldn't interfere...
$(PerseusBridge).trigger("problemTemplateRendered", [Khan.mathJaxLoaded]);
}
function triggerNextProblem() {
if (interfaceFunctions) {
interfaceFunctions.setAttemptMessage("", "unanswered");
}
$(Exercises).trigger("gotoNextProblem");
}
// TODO(charlie): As soon as assessment mode is removed, all calls to this
// method should be replaced with calls to triggerNextProblem.
function triggerNextProblemWithAssessmentGuard() {
// Skipping should pull up the next card immediately - but, if we're in
// assessment mode, we don't know what the next card will be yet, so
// wait for the special assessment mode triggers to fire instead.
if (Exercises.assessmentMode) {
// Tell the assessment queue that the current question has been
// answered so that it can serve up the next question when its ready
// Set a small timeout to give the browser a chance to show the
// disabled check-answer button. Otherwise in chrome it doesn't show
// Please wait...
setTimeout(function() {
Exercises.AssessmentQueue.answered(score.correct);
}, 10);
} else {
triggerNextProblem();
}
}
function newProblem(e, data) {
Exercises.guessLog = [];
Exercises.userActivityLog = [];
canAttempt = true;
hintsAreFree = false;
attempts = data.userExercise ? data.userExercise.lastAttemptNumber : 0;
numHints = data.numHints;
hintsUsed = data.userExercise ? data.userExercise.lastCountHints : 0;
lastAttemptOrHint = new Date().getTime();
lastAttemptContent = null;
$("#problem-and-answer").addClass("framework-perseus");
if (interfaceFunctions) {
interfaceFunctions.setHintsRemaining(numHints - hintsUsed, hintsUsed);
// TODO(oliver): maybe also enable the check answer?
} else {
// Enable/disable the get hint button
$(".hint-box").toggle(numHints !== 0);
updateHintButtonText();
$("#hint").attr("disabled", hintsUsed >= numHints);
enableCheckAnswer();
}
if (typeof KA !== "undefined" && KA.language === "en-PT" &&
previewingItem) {
// On translate.ka.org when previewing the exercise, we want to open up
// all the hints to make it easy to translate immediately.
while (hintsUsed < numHints) {
showNextHint();
}
}
// Check whether the user has taken hints offline that we don't already
// know about (note that the call to hasTakenHintFor will validate its
// args and return false if there's no userExercise or the problemNum is
// non-numeric).
if (hintsUsed === 0 && numHints > 0 &&
OfflineHintRecord.hasTakenHintFor(data.userExercise, problemNum)) {
showNextHint();
}
// Render related videos, unless we're on the final stage of mastery or in
// a skill check.
if (Exercises.RelatedVideos && data.userExercise) {
var userExercise = data.userExercise;
var nearMastery = userExercise.exerciseProgress.level === "mastery2" ||
userExercise.exerciseProgress.level === "mastery3";
var task = Exercises.learningTask;
var hideRelatedVideos = (task && task.isMasteryTask() && nearMastery ||
userExercise.isSkillCheck);
var relatedVideos = data.userExercise.exerciseModel.relatedVideos;
// We have per-problem-type related videos for Perseus
var problemTypeName = PerseusBridge.getSeedInfo().problem_type;
// Filter out related videos that correspond to other problem types
var problemTypes = data.userExercise.exerciseModel.problemTypes;
var otherProblemTypes = _.filter(problemTypes, function(type) {
return type.name !== problemTypeName;
});
relatedVideos = _.filter(relatedVideos, function(video) {
return _.all(otherProblemTypes, function(problemType) {
// Note: we have to cast IDs to strings for backwards
// compatability as older videos have pure integer IDs.
var stringIDs = _.map(problemType.relatedVideos,
function(id) {
return "" + id;
});
return !_.contains(stringIDs, "" + video.id);
});
});
if (hideRelatedVideos) {
Exercises.RelatedVideos.render([]);
} else {
Exercises.RelatedVideos.render(relatedVideos);
}
}
}
// NOTE(jared): The return value of handleAttempt was added to accommodate
// an imperative (as opposed to event-based) API. These event-suffixed methods
// are used to respond to DOM events, and so return `false` to cancel the
// events.
// NOTE(charlie): These event handlers are meant to be used by web clients.
// As such, in response to API errors, they'll want to hide the problem UI.
// On mobile, we use imperativeAPI.handleAttempt directly and override the
// onNetworkError callback, since we handle these errors ourselves (e.g.,
// by overlaying a modal over the problem UI, rather than hiding it).
function handleCheckAnswerEvent() {
handleAttempt({skipped: false}, hideProblemUIOnError);
return false;
}
function handleSkipEvent() {
var result = handleAttempt({skipped: true}, hideProblemUIOnError);
if (result.status === "normal") {
triggerNextProblemWithAssessmentGuard();
}
return false;
}
function handleOptOutEvent() {
Exercises.AssessmentQueue.end();
var result = handleAttempt(
{skipped: true, optOut: true}, hideProblemUIOnError
);
if (result.status === "normal") {
triggerNextProblemWithAssessmentGuard();
}
return false;
}
function handleAttempt(data, onNetworkError,
determineWhetherRequestShouldRetry) {
var skipped = data.skipped;
var optOut = data.optOut;
var score;
var itemId;
// Score the attempt
score = PerseusBridge.scoreInput();
itemId = PerseusBridge.getSeedInfo().seed;
if (!canAttempt) {
// Just don't allow further submissions once a correct answer or skip
// has been called or sometimes the server gets confused.
return {
status: "problem-already-answered",
};
}
var isAnswerEmpty = score.empty && !skipped;
var attemptMessage = null;
// When the user answers incorrectly, we might show a message in response.
// It might encourage the user to think about their answer's format (eg.
// simplify the fraction) or it might explain to the user why the answer
// was wrong (these are referred to as clues in code, though in
// conversation we call them rationales). We show nothing at all if that
// content doesn't exist.
if (score.message != null) {
attemptMessage = score.message;
} else if (isAnswerEmpty) {
attemptMessage = EMPTY_MESSAGE;
}
// We need to alert the user when the given answer is incorrect
if (!attemptMessage && !(score.correct || skipped)) {
attemptMessage = i18n._("Not correct yet, please try again.");
}
if (interfaceFunctions) {
var answerStatus = score.correct ? "correct" : "incorrect";
interfaceFunctions.setAttemptMessage(attemptMessage, answerStatus);
} else {
var $attemptMessage = $("#check-answer-results > p");
if (attemptMessage) {
// NOTE(jeresig): If the message is identical to the message that
// was there before then the ARIA alert is not triggered. We add in
// an extra space to force the alert to trigger.
var isIdentical = attemptMessage === $attemptMessage.text();
$attemptMessage
.html(attemptMessage + (isIdentical ? " " : "")).show().tex();
$(Exercises).trigger("attemptMessageShown", attemptMessage);
} else {
$attemptMessage.hide();
}
}
// Stop if the user didn't try to skip the question and also didn't yet
// enter a response
if (isAnswerEmpty) {
return {
status: "incomplete-answer",
data: {
attemptMessage: attemptMessage,
},
};
}
if (score.correct || skipped) {
// Once we receive a correct answer or a skip, that's it; further
// attempts are disallowed.
canAttempt = false;
}
var curTime = new Date().getTime();
var millisTaken = curTime - lastAttemptOrHint;
var timeTaken = Math.round(millisTaken / 1000);
var stringifiedGuess = JSON.stringify(score.guess);
lastAttemptOrHint = curTime;
// If user hasn't changed their answer and is resubmitting w/in one second
// of last attempt, don't allow this attempt. They're probably just
// smashing Enter.
if (!skipped &&
stringifiedGuess === lastAttemptContent && millisTaken < 1000) {
return {
status: "too-fast",
data: {
attemptMessage: attemptMessage,
},
};
}
lastAttemptContent = stringifiedGuess;
Exercises.guessLog.push(score.guess);
Exercises.userActivityLog.push([
score.correct ? "correct-activity" : "incorrect-activity",
stringifiedGuess, timeTaken]);
var isDone = score.correct || skipped;
if (isDone) {
$(Exercises).trigger("problemDone", {
card: Exercises.currentCard,
attempts: attempts
});
}
var checkAnswerData = {
attemptMessage: attemptMessage,
isDone: isDone,
attempts: attempts,
correct: score.correct,
item: itemId,
card: Exercises.currentCard,
optOut: optOut,
// Determine if this attempt qualifies as fast completion
fast: userExercise.secondsPerFastProblem >= timeTaken,
// Used by mobile for skipping problems in a mastery task
skipped: skipped
};
$(Exercises).trigger("checkAnswer", checkAnswerData);
// Update interface corresponding to correctness
if (skipped || Exercises.assessmentMode) {
disableCheckAnswer();
} else if (score.correct) {
// Correct answer, so show the next question button.
var nextButtonText;
if (Exercises.learningTask && Exercises.learningTask.isComplete()) {
nextButtonText = i18n._("Awesome! Show points...");
} else {
nextButtonText = i18n._("Correct! Next question...");
}
if (interfaceFunctions) {
interfaceFunctions.showNextQuestionButton();
} else {
$("#check-answer-button").hide();
$("#next-question-button")
.prop("disabled", false)
.removeClass("buttonDisabled")
.val(nextButtonText)
.show()
.focus();
$("#positive-reinforcement").show();
$("#skip-question-button").prop("disabled", true);
$("#opt-out-button").prop("disabled", true);
}
} else {
// Wrong answer. Enable all the input elements
// NOTE(jeresig): The wrong answer wiggling has been disabled as
// it causes a re-focus on the answer button to occur, making it
// impossible to hear what the effect of the press was in a
// screen reader.
//$("#check-answer-button")
//.parent() // .check-answer-wrapper makes shake behave
//.effect("shake", {times: 3, distance: 5}, 480);
// TODO(alpert): trigger something?
}
if (!hintsAreFree) {
hintsAreFree = true;
if (interfaceFunctions) {
interfaceFunctions.setHintsAreFree();
} else {
$(".hint-box")
.css("position", "relative")
.animate({top: -10}, 250)
.find(".info-box-header")
.slideUp(250)
.end()
.find("#hint")
.removeClass("orange")
.addClass("green");
updateHintButtonText();
}
}
if (Exercises.currentCard.get("preview")) {
// Skip the server; just pretend we have success
return {
status: "skip-server",
data: checkAnswerData,
};
}
if (previewingItem) {
if (interfaceFunctions) {
interfaceFunctions.setPreviewingItem();
} else {
$("#next-question-button").prop("disabled", true);
}
// Skip the server; just pretend we have success
return {
status: "previewing",
data: checkAnswerData,
};
}
// If we're in a practice task but not at the end of it (so the
// user will be doing another question next), let's make the
// request on the multithreaded module: we don't care that much
// how long the request takes (it happens while the user is trying
// the next question) and it's cheaper.
var useMultithreadedModule = (
!score.correct ||
(Exercises.learningTask && !Exercises.learningTask.isComplete()));
var url = fullUrl(
"problems/" + problemNum + "/attempt", useMultithreadedModule);
// This needs to be after all updates to Exercises.currentCard (such as the
// "problemDone" event) or it will send incorrect data to the server
var attemptData = buildAttemptData(
score.correct, ++attempts, stringifiedGuess, timeTaken, skipped,
optOut);
saveAttemptToServer(url, attemptData, onNetworkError,
determineWhetherRequestShouldRetry);
return {
status: "normal",
data: checkAnswerData,
};
}
/**
* Handle the even when a user wants to see a worked example.
* Currently only works on some Perseus problems.
*/
function onShowExampleClicked() {
$(PerseusBridge).trigger("showWorkedExample");
}
/**
* Show a hint
*
* In order to make this call idempotent, the client supplies how many hints
* it hints are left. If correct (are there are actually hints left), a new
* hint is shown.
*
* Returns the new number of hints left.
*/
function showHint(hintsLeft, determineWhetherRequestShouldRetry) {
if (hintsLeft <= 0) {
return 0;
}
var realHintsLeft = numHints - hintsUsed;
if (hintsLeft !== realHintsLeft) {
return realHintsLeft;
}
// TODO(jared): refactor such that showNextHint can return the newnumber of
// hints left. Right now, there are event passing things (that are
// nevertheless synchronous), so it's not possible.
showNextHint(determineWhetherRequestShouldRetry);
return hintsLeft - 1;
}
/**
* Handle the event when a user clicks to use a hint.
*
* Note that we can't use `showNextHint` directly, or else we'll pass the DOM
* event up as the `determineWhetherRequestShouldRetry` parameter.
*/
function onHintButtonClicked() {
showNextHint(null /* never retry */);
}
/**
* Reveal the next hint.
*
* This deals with the internal work to do things like sending the event up
* to the server, as well as triggering the external event "hintUsed" so that
* other parts of the UI may update first. It's separated into two events so
* that the XHR can be sent after the other items have a chance to respond.
*/
function showNextHint(determineWhetherRequestShouldRetry) {
var curTime = new Date().getTime();
var timeTaken = Math.round((curTime - lastAttemptOrHint) / 1000);
lastAttemptOrHint = curTime;
var logEntry = ["hint-activity", "0", timeTaken];
Exercises.userActivityLog.push(logEntry);
if (!previewingItem && !userExercise.readOnly &&
!Exercises.currentCard.get("preview") && canAttempt) {
// buildAttemptData reads the number of hints we have taken
// from hintsUsed. However, we haven't updated that yet since
// we haven't gotten a response back, from, you guessed it,
// this request itself. So we increment hintsUsed while
// forming this request so that it gets the number of hints
// that will have been used when this request returns
// successfully.
hintsUsed++;
// Always put hints on the (cheaper) multithreaded module,
// since we don't care what the API call returns so we don't
// care how slow it is.
var url = fullUrl("problems/" + problemNum + "/hint", true);
var attemptData = buildAttemptData(false, attempts, "hint",
timeTaken, false, false);
var requestForParams = function(params) {
return requestForParamsWithRetry(
params, determineWhetherRequestShouldRetry
);
};
request(url, attemptData, requestForParams);
hintsUsed--;
}
// Save the fact that the user has taken a hint for this problem in local
// storage to help with cheating (note that the args are validated in the
// function and this will no-op if there's no userExercise or the problem
// num is non-numeric).
OfflineHintRecord.saveHintTakenFor(userExercise, problemNum);
$(PerseusBridge).trigger("showHint");
}
function onHintShown(e, data) {
// TODO(jared): it looks like this code depends on `onHintShown` being
// called *synchronously* by ke and perseus, even though the flow control
// is handled by events. This feels very prone to breakage, but I'm not
// sure how to fix it well without dealing with the global state in this
// file in a more comprehensive way. We could change the flow control such
// that `showNextHint` calls PerseusBridge.showHint() (or something)
// directly, and then calls `onHintShown`.
hintsUsed++;
$(Exercises).trigger("hintUsed", data);
if (interfaceFunctions) {
interfaceFunctions.setHintsRemaining(numHints - hintsUsed, hintsUsed);
} else {
// Grow the scratchpad to cover the new hint
Khan.scratchpad.resize();
updateHintButtonText();
// If there aren't any more hints, disable the get hint button
if (hintsUsed === numHints) {
$("#hint").attr("disabled", true);
}
}
// When a hint is shown, clear the "last attempt content" that is used to
// detect duplicate, repeated attempts. Once the user clicks on a hint, we
// consider their next attempt to be unique and legitimate even if it's the
// same answer they attempted previously.
lastAttemptContent = null;
}
function updateHintButtonText() {
var $hintButton = $("#hint");
var hintsLeft = numHints - hintsUsed;
if (hintsAreFree) {
$hintButton.val(hintsUsed ?
i18n._("Show next hint (%(hintsLeft)s left)", {hintsLeft: hintsLeft}) :
i18n._("Show hints (%(hintsLeft)s available)", {hintsLeft: hintsLeft}));
} else {
$hintButton.val(hintsUsed ?
i18n.ngettext("I'd like another hint (1 hint left)",
"I'd like another hint (%(num)s hints left)",
hintsLeft) :
i18n._("I'd like a hint"));
}
}
// Build the data to pass to the server
function buildAttemptData(correct, attemptNum, attemptContent, timeTaken,
skipped, optOut) {
var data;
data = PerseusBridge.getSeedInfo();
_.extend(data, {
// Ask for camel casing in returned response
casing: "camel",
// Whether we're moving to the next problem (i.e., correctness)
complete: (correct || skipped) ? 1 : 0,
count_hints: hintsUsed,
time_taken: timeTaken,
// How many times the problem was attempted
attempt_number: attemptNum,
// The answer the user gave
attempt_content: attemptContent,
// If working in the context of a LearningTask (on the new learning
// dashboard), supply the task ID.
// TODOX(laura): The web view in the iOS app doesn't have a learningTask
// object on Exercises. To simplify this line, add getTaskId to
// Exercises on the webapp as well.
task_id: (Exercises.getTaskId && Exercises.getTaskId()) ||
(Exercises.learningTask && Exercises.learningTask.get("id")),
task_generation_time: (Exercises.learningTask &&
Exercises.learningTask.get("generationTime")),
user_mission_id: Exercises.userMissionId,
// The current topic, if any
topic_slug: Exercises.topicSlug,
// The user assessment key if in assessmentMode
user_assessment_key: Exercises.userAssessmentKey,
// Whether the user is skipping the question
skipped: skipped ? 1 : 0,
// Whether the user is opting out of the task
opt_out: optOut ? 1 : 0,
// The client-reported datetime in local time (not UTC!).
// Used by streaks.
// NOTE(jeresig): We should always use a locale of 'en' here to ensure
// that the formatting of the date matches our expectations. Namely
// some locales use non-latin characters to represent numbers, such as
// Bengali and Nepalese. This change shouldn't have a negative impact
// as `.format()` only returns a string that looks like this:
// `"2016-02-22T16:34:51-05:00"`.
client_dt: moment().locale("en").format()
});