-
Notifications
You must be signed in to change notification settings - Fork 479
/
feedback.js
1949 lines (1794 loc) · 62.5 KB
/
feedback.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
// Globals used in this file:
// Blockly
import $ from 'jquery';
import {getStore} from './redux';
import React from 'react';
import {Provider} from 'react-redux';
import ReactDOM from 'react-dom';
import msg from '@cdo/locale';
import dom from './dom';
import LegacyDialog from './code-studio/LegacyDialog';
import ChallengeDialog from './templates/ChallengeDialog';
import project from './code-studio/initApp/project';
import FeedbackBlocks from './feedbackBlocks';
import puzzleRatingUtils from './puzzleRatingUtils';
import DialogButtons from './templates/DialogButtons';
import CodeWritten from './templates/feedback/CodeWritten';
import GeneratedCode from './templates/feedback/GeneratedCode';
import {dataURIToBlob} from './imageUtils';
import trackEvent from './util/trackEvent';
import {getValidatedResult} from './containedLevels';
import PublishDialog from './templates/projects/publishDialog/PublishDialog';
import DownloadReplayVideoButton from './code-studio/components/DownloadReplayVideoButton';
import {
showPublishDialog,
PUBLISH_REQUEST,
PUBLISH_SUCCESS,
PUBLISH_FAILURE,
} from './templates/projects/publishDialog/publishDialogRedux';
import {createHiddenPrintWindow} from './utils';
import testImageAccess from './code-studio/url_test';
import {TestResults, KeyCodes} from './constants';
import QRCode from 'qrcode.react';
import copyToClipboard from '@cdo/apps/util/copyToClipboard';
import color from '@cdo/apps/util/color';
import analyticsReporter from '@cdo/apps/lib/util/AnalyticsReporter';
import {EVENTS} from '@cdo/apps/lib/util/AnalyticsConstants';
// Types of blocks that do not count toward displayed block count. Used
// by FeedbackUtils.blockShouldBeCounted_
const UNCOUNTED_BLOCK_TYPES = ['draw_colour', 'alpha', 'comment'];
/**
* Bag of utility functions related to building and displaying feedback
* to students.
* @class
* @param {StudioApp} studioApp A studioApp instance used to pull
* configuration and perform operations.
*/
var FeedbackUtils = function (studioApp) {
this.studioApp_ = studioApp;
};
module.exports = FeedbackUtils;
/**
* @typedef {Object} FeedbackOptions
* @property {LiveMilestoneResponse} response
* @property {TestResult} feedbackType
* @property {string} message
* @property {Level} level
* @property {boolean} showingSharing
* @property {Object<string, string>} appStrings
* @property {string} feedbackImage
* @property {boolean} defaultToContinue
* @property {boolean} preventDialog
* @property {ExecutionError} executionError
* @property {boolean} hideXButton
* @property {string} shareLink
*/
/**
* @typedef {{ err, lineNumber: number}} ExecutionError
*/
/**
* @typedef {Object} TestableBlock
* @property {string|function} test - A test whether the block is
* present, either:
* - A string, in which case the string is searched for in
* the generated code.
* - A single-argument function is called on each user-added
* block individually. If any call returns true, the block
* is deemed present. "User-added" blocks are ones that are
* neither disabled or undeletable.
* @property {string} type - The type of block to be produced for
* display to the user if the test failed.
* @property {Object<string,string>} [titles] - A dictionary, where, for each
* KEY-VALUE pair, this is added to the block definition:
* <title name="KEY">VALUE</title>.
* @property {Object<string,string>} [value] - A dictionary, where, for each
* KEY-VALUE pair, this is added to the block definition:
* <value name="KEY">VALUE</value>
* @property {string} [extra] - A string that should be blacked
* between the "block" start and end tags.
* @property {string} blockDisplayXML - XML string representing the block.
*/
/**
* @param {FeedbackOptions} options
* @param {!TestableBlock[]} requiredBlocks The blocks that are required to be used in
* the solution to this level.
* @param {number} maxRequiredBlocksToFlag The number of required blocks to
* give hints about at any one time. Set this to Infinity to show all.
* @param {!TestableBlock[]} recommendedBlocks The blocks that are recommended to be used in
* the solution to this level.
* @param {number} maxRecommendedBlocksToFlag The number of recommended blocks to
* give hints about at any one time. Set this to Infinity to show all.
*/
FeedbackUtils.prototype.displayFeedback = function (
options,
requiredBlocks,
maxRequiredBlocksToFlag,
recommendedBlocks,
maxRecommendedBlocksToFlag
) {
options.level = options.level || {};
const {onContinue, shareLink} = options;
const hadShareFailure = options.response && options.response.share_failure;
const showingSharing =
options.showingSharing && !hadShareFailure && shareLink;
var canContinue = this.canContinueToNextLevel(options.feedbackType);
var displayShowCode =
this.studioApp_.enableShowCode &&
this.studioApp_.enableShowLinesCount &&
canContinue &&
!showingSharing;
var feedback = document.createElement('div');
var sharingDiv =
canContinue && showingSharing ? this.createSharingDiv(options) : null;
var showCode = displayShowCode ? this.getShowCodeElement_(options) : null;
var shareFailureDiv = hadShareFailure ? this.getShareFailure_(options) : null;
var feedbackBlocks;
if (this.studioApp_.isUsingBlockly()) {
feedbackBlocks = new FeedbackBlocks(
options,
this.getMissingBlocks_(requiredBlocks, maxRequiredBlocksToFlag),
this.getMissingBlocks_(recommendedBlocks, maxRecommendedBlocksToFlag)
);
}
// feedbackMessage must be initialized after feedbackBlocks
// because FeedbackBlocks can mutate options.response.hint.
var feedbackMessage = this.getFeedbackMessageElement_(options);
if (feedbackMessage) {
feedback.appendChild(feedbackMessage);
}
if (feedbackBlocks && feedbackBlocks.div) {
feedback.appendChild(feedbackBlocks.div);
}
if (sharingDiv) {
feedback.appendChild(sharingDiv);
}
if (showingSharing) {
var shareCodeSpacer = document.createElement('div');
shareCodeSpacer.className = 'share-code-spacer';
feedback.appendChild(shareCodeSpacer);
}
if (shareFailureDiv) {
feedback.appendChild(shareFailureDiv);
}
if (showCode) {
feedback.appendChild(showCode);
}
if (options.level.isK1) {
feedback.className += ' k1';
}
if (options.appDiv) {
feedback.appendChild(options.appDiv);
}
feedback.className += canContinue ? ' win-feedback' : ' failure-feedback';
feedback.appendChild(
this.getFeedbackButtons_({
feedbackType: options.feedbackType,
tryAgainText: options.tryAgainText,
hideTryAgain: options.hideTryAgain,
keepPlayingText: options.keepPlayingText,
continueText: options.continueText,
isK1: options.level.isK1,
freePlay: options.level.freePlay,
finalLevel: options.level.isLastLevelInLesson,
})
);
var againButton = feedback.querySelector('#again-button');
var hintRequestButton = feedback.querySelector('#hint-request-button');
var continueButton = feedback.querySelector('#continue-button');
// Don't show the continue button on share pages.
if (this.studioApp_.share) {
continueButton.style.display = 'none';
}
const onlyContinue = continueButton && !againButton;
const defaultContinue = onlyContinue || options.defaultToContinue;
/**
* get the topmost missing recommended block, if it exists, to be
* added to the queue of contextual hints. If the user views the block
* in the dialog, mark it as seen and add it to the list as such.
* @type !BlockHint[]
*/
var missingRecommendedBlockHints = this.getMissingBlockHints(
recommendedBlocks,
options.level.isK1
);
var markContextualHintsAsSeen = function () {
missingRecommendedBlockHints
.filter(function (hint) {
return (
feedbackBlocks &&
feedbackBlocks.xml &&
feedbackBlocks.xml.indexOf(hint.blockDisplayXML) > -1
);
})
.forEach(function (hint) {
hint.alreadySeen = true;
});
};
// If we're showing a share link, fire-and-forget a project save right before showing the dialog
// so that any changes made since the last Run are reflected in the shared project.
if (showingSharing) {
project.saveIfSourcesChanged();
}
// onHidden is called when the dialog is closed: only do something extra
// if there are hints for missing blocks.
let onHidden = function () {
if (!continueButton) {
this.studioApp_.displayMissingBlockHints(missingRecommendedBlockHints);
}
}.bind(this);
var icon;
if (!options.hideIcon) {
if (
canContinue &&
(!this.studioApp_.hasContainedLevels || getValidatedResult())
) {
icon = this.studioApp_.winIcon;
} else {
icon = this.studioApp_.failureIcon;
}
}
const defaultBtnSelector = defaultContinue
? '#continue-button'
: '#again-button';
const actualBlocks = this.getNumCountableBlocks();
const idealBlocks = this.studioApp_.IDEAL_BLOCK_NUM;
const isPerfect = actualBlocks <= idealBlocks;
const showPuzzleRatingButtons =
options.response && options.response.puzzle_ratings_enabled;
if (getStore().getState().pageConstants.isChallengeLevel) {
const container = document.createElement('div');
document.body.appendChild(container);
let onChallengeContinue = onContinue;
if (showPuzzleRatingButtons) {
onChallengeContinue = () => {
puzzleRatingUtils.cachePuzzleRating(container, {
script_id: options.response.script_id,
level_id: options.response.level_id,
});
onContinue();
};
}
ReactDOM.render(
<ChallengeDialog
title={
isPerfect
? msg.challengeLevelPerfectTitle()
: msg.challengeLevelPassTitle()
}
avatar={icon}
text={isPerfect ? null : msg.challengeLevelPassText({idealBlocks})}
complete={isPerfect}
handlePrimary={onChallengeContinue}
primaryButtonLabel={msg.continue()}
cancelButtonLabel={msg.tryAgain()}
showPuzzleRatingButtons={showPuzzleRatingButtons}
>
{displayShowCode && this.getShowCodeComponent_(options, true)}
</ChallengeDialog>,
container
);
return;
}
$('#feedback-dialog').remove();
var feedbackDialog = this.createModalDialog({
contentDiv: feedback,
icon: icon,
defaultBtnSelector: defaultBtnSelector,
onHidden: onHidden,
id: 'feedback-dialog',
showXButton: !options.hideXButton,
});
if (againButton) {
dom.addClickTouchEvent(againButton, function () {
feedbackDialog.hide();
});
}
// If there is a hint request button, hide the hint that would ordinarily
// be shown (including any feedback blocks), and add code to restore the
// hint if the button gets pressed.
if (hintRequestButton) {
var alreadySeen =
options.response &&
options.response.hint_view_requests &&
options.response.hint_view_requests.some(function (request) {
var requestMatchesFeedback =
request.feedback_type === options.feedbackType;
if (feedbackBlocks && feedbackBlocks.xml) {
requestMatchesFeedback =
requestMatchesFeedback &&
request.feedback_xml === feedbackBlocks.xml;
}
return requestMatchesFeedback;
});
if (alreadySeen) {
// Remove "Show hint" button. Making it invisible isn't enough,
// because it will still take up space.
hintRequestButton.parentNode.removeChild(hintRequestButton);
// mark the corresponding block hint as seen
markContextualHintsAsSeen();
} else {
// Generate a generic feedback message to display when we show the
// feedback block
var genericFeedback = this.getFeedbackMessageElement_({
message: msg.tryBlocksBelowFeedback(),
});
// If there are feedback blocks, temporarily hide them.
if (feedbackBlocks && feedbackBlocks.div) {
feedbackBlocks.hide();
}
// If the user requests the hint...
dom.addClickTouchEvent(hintRequestButton, function () {
// mark the corresponding block hint as seen
markContextualHintsAsSeen();
// Swap out the specific feedback message with a generic one.
var parentNode = feedbackMessage.parentNode;
parentNode.replaceChild(genericFeedback, feedbackMessage);
// Remove "Show hint" button. Making it invisible isn't enough,
// because it will still take up space.
hintRequestButton.parentNode.removeChild(hintRequestButton);
// Restore feedback blocks, if present.
if (feedbackBlocks && feedbackBlocks.div) {
feedbackBlocks.show();
}
// Report hint request to server.
if (options.response.hint_view_request_url) {
$.ajax({
url: options.response.hint_view_request_url,
type: 'POST',
data: {
script_id: options.response.script_id,
level_id: options.response.level_id,
feedback_type: options.feedbackType,
feedback_xml: feedbackBlocks ? feedbackBlocks.xml : undefined,
},
});
}
});
}
}
if (continueButton) {
if (options.response && options.response.puzzle_ratings_enabled) {
feedback.appendChild(puzzleRatingUtils.buildPuzzleRatingButtons());
}
dom.addClickTouchEvent(continueButton, function () {
feedbackDialog.hide();
recordFinishShare(
'FINISH_BUTTON_CERTIFICATE',
project.getStandaloneApp()
);
if (options.response && options.response.puzzle_ratings_enabled) {
puzzleRatingUtils.cachePuzzleRating(feedback, {
script_id: options.response.script_id,
level_id: options.response.level_id,
});
}
options.onContinue();
});
}
// Remember the project between when we save and when we publish
// while the dialog is open, but not between dialog openings.
let projectId = null;
let projectType = null;
const saveButtonSelector = '#save-to-project-gallery-button';
const saveButton = feedback.querySelector(saveButtonSelector);
if (saveButton) {
dom.addClickTouchEvent(saveButton, () => {
$(saveButtonSelector).prop('disabled', true).text(msg.addingToProjects());
project
.copy(project.getNewProjectName())
.then(() => FeedbackUtils.saveThumbnail(options.feedbackImage))
.then(() => {
projectId = project.getCurrentId();
projectType = project.getStandaloneApp();
$(saveButtonSelector)
.prop('disabled', true)
.text(msg.addedToProjects());
})
.catch(err => console.log(err));
});
}
const publishButtonSelector = '#publish-to-project-gallery-button';
const publishButton = feedback.querySelector(publishButtonSelector);
if (publishButton) {
dom.addClickTouchEvent(publishButton, () => {
// Hide the current dialog since we're about to show the publish dialog
recordFinishShare('FINISH_SHARING_PUBLISH', project.getStandaloneApp());
feedbackDialog.hide();
const store = getStore();
if (projectId && projectType) {
// The user previously saved and is now publishing. Publish the project
// which we just saved, rather than creating a new one and publishing it.
store.dispatch(showPublishDialog(projectId, projectType));
let publishDialog = FeedbackUtils.getPublishDialogElement();
ReactDOM.render(
<Provider store={store}>
<PublishDialog afterPublish={() => showFeedbackDialog(true)} />
</Provider>,
publishDialog
);
return;
}
// project.copy relies on state not in redux, and we want to keep this
// badness out of our redux code. Therefore, define what happens when
// publish dialog publish button is clicked here, outside of the publish
// dialog redux.
//
// Once project.js is moved onto redux, the remix-and-publish operation
// should be moved inside the publish dialog redux.
FeedbackUtils.showConfirmPublishDialog(() => {
store.dispatch({type: PUBLISH_REQUEST});
let didPublish = false;
project
.copy(project.getNewProjectName(), {shouldPublish: true})
.then(() => FeedbackUtils.saveThumbnail(options.feedbackImage))
.then(() => {
store.dispatch({type: PUBLISH_SUCCESS});
didPublish = true;
})
.catch(err => {
console.log(err);
store.dispatch({type: PUBLISH_FAILURE});
})
.then(() => {
if (didPublish) {
// Only show feedback dialog again if publishing succeeded,
// because we keep the publish dialog open if it failed.
showFeedbackDialog(true);
}
});
});
});
}
var printButton = feedback.querySelector('#print-button');
if (printButton) {
dom.addClickTouchEvent(printButton, function () {
createHiddenPrintWindow(options.feedbackImage);
});
}
function showFeedbackDialog(isPublished) {
feedbackDialog.show({
backdrop:
getStore().getState().pageConstants.appType === 'flappy'
? 'static'
: true,
});
if (isPublished) {
$(publishButtonSelector).prop('disabled', true).text(msg.published());
$(saveButtonSelector).prop('disabled', true).text(msg.savedToGallery());
}
}
showFeedbackDialog();
if (feedbackBlocks && feedbackBlocks.div) {
feedbackBlocks.render();
}
};
function recordFinishShare(type, appType) {
if (EVENTS[type]) {
analyticsReporter.sendEvent(EVENTS[type], {
lab_type: appType,
});
}
}
FeedbackUtils.showConfirmPublishDialog = onConfirmPublish => {
const store = getStore();
store.dispatch(showPublishDialog());
let publishDialog = FeedbackUtils.getPublishDialogElement();
ReactDOM.render(
<Provider store={store}>
<PublishDialog onConfirmPublishOverride={onConfirmPublish} />
</Provider>,
publishDialog
);
};
FeedbackUtils.getPublishDialogElement = function () {
let publishDialog = document.getElementById('legacy-share-publish-dialog');
if (!publishDialog) {
publishDialog = document.createElement('div');
publishDialog.id = 'legacy-share-publish-dialog';
document.body.appendChild(publishDialog);
}
return publishDialog;
};
/**
* Converts the image data uri to a blob, then saves it to the server as the
* thumbnail for the current project.
* @param {string} image Image encoded as a data URI.
* @returns {Promise} A promise which resolves if successful.
*/
FeedbackUtils.saveThumbnail = function (image) {
if (!image) {
return Promise.resolve();
}
return dataURIToBlob(image)
.then(project.saveThumbnail)
.then(() => project.saveIfSourcesChanged());
};
/**
* Counts the number of blocks used. Blocks are only counted if they are
* not disabled, are deletable.
* @return {number} Number of blocks used.
*/
FeedbackUtils.prototype.getNumBlocksUsed = function () {
if (this.studioApp_.editCode) {
var codeLines = 0;
// quick and dirty method to count non-blank lines that don't start with //
var lines = this.getGeneratedCodeString_().split('\n');
for (var i = 0; i < lines.length; i++) {
if (lines[i].length > 1 && (lines[i][0] !== '/' || lines[i][1] !== '/')) {
codeLines++;
}
}
return codeLines;
} else if (this.studioApp_.isUsingBlockly()) {
return this.getUserBlocks_().length;
} else {
return 0;
}
};
/**
* Counts the total number of blocks. Blocks are only counted if they are
* not disabled.
* @return {number} Total number of blocks.
*/
FeedbackUtils.prototype.getNumCountableBlocks = function () {
var i;
if (getStore().getState().pageConstants.isBramble) {
return 0;
} else if (this.studioApp_.editCode) {
var codeLines = 0;
// quick and dirty method to count non-blank lines that don't start with //
var lines = this.getGeneratedCodeString_().split('\n');
for (i = 0; i < lines.length; i++) {
if (lines[i].length > 1 && (lines[i][0] !== '/' || lines[i][1] !== '/')) {
codeLines++;
}
}
return codeLines;
} else {
return this.getCountableBlocks_().length;
}
};
/**
*
*/
FeedbackUtils.prototype.getFeedbackButtons_ = function (options) {
var buttons = document.createElement('div');
buttons.id = 'feedbackButtons';
let tryAgainText = undefined;
if (!options.hideTryAgain) {
if (options.tryAgainText) {
tryAgainText = options.tryAgainText;
} else if (this.studioApp_.hasContainedLevels) {
tryAgainText = msg.reviewCode();
} else if (options.feedbackType === TestResults.FREE_PLAY) {
tryAgainText = msg.keepPlaying();
} else if (options.feedbackType === TestResults.FREE_PLAY_UNCHANGED_FAIL) {
tryAgainText = msg.keepWorking();
} else if (options.feedbackType < TestResults.MINIMUM_OPTIMAL_RESULT) {
tryAgainText = msg.tryAgain();
} else {
tryAgainText = msg.replayButton();
}
}
ReactDOM.render(
<DialogButtons
tryAgain={tryAgainText}
continueText={
options.continueText ||
(options.finalLevel ? msg.finish() : msg.continue())
}
nextLevel={this.canContinueToNextLevel(options.feedbackType)}
shouldPromptForHint={this.shouldPromptForHint(options.feedbackType)}
isK1={options.isK1}
assetUrl={this.studioApp_.assetUrl}
freePlay={options.freePlay}
/>,
buttons
);
return buttons;
};
/**
*
*/
FeedbackUtils.prototype.getShareFailure_ = function (options) {
var shareFailure = options.response.share_failure;
var shareFailureDiv = document.createElement('div');
shareFailureDiv.innerHTML = require('./templates/shareFailure.html.ejs')({
shareFailure: shareFailure,
});
return shareFailureDiv;
};
/**
* Generates an appropriate feedback message
* The message will be one of the following, from highest to lowest precedence:
* 0. Failure override message specified on level (options.level.failureMessageOverride)
* 1. Message passed in by caller (options.message).
* 2. Header message due to dashboard text check fail (options.response.share_failure).
* 3. Level-specific message (e.g., options.level.emptyBlocksErrorMsg) for
* specific result type (e.g., TestResults.EMPTY_BLOCK_FAIL).
* 4. System-wide message (e.g., msg.emptyBlocksErrorMsg()) for specific
* result type (e.g., TestResults.EMPTY_BLOCK_FAIL).
* @param {FeedbackOptions} options
* @return {string} message
*/
FeedbackUtils.prototype.getFeedbackMessage = function (options) {
var message;
// If a message was explicitly passed in, use that.
if (
options.feedbackType < TestResults.ALL_PASS &&
options.level?.failureMessageOverride
) {
message = options.level.failureMessageOverride;
} else if (options.message) {
message = options.message;
} else if (options.response?.share_failure) {
message = msg.shareFailure();
} else {
// Otherwise, the message will depend on the test result.
switch (options.feedbackType) {
case TestResults.FREE_PLAY_UNCHANGED_FAIL:
message = options.useDialog
? msg.freePlayUnchangedFail()
: msg.freePlayUnchangedFailInline();
break;
case TestResults.RUNTIME_ERROR_FAIL:
message = msg.runtimeErrorMsg({
lineNumber: options.executionError.lineNumber,
});
break;
case TestResults.SYNTAX_ERROR_FAIL:
message = msg.syntaxErrorMsg({
lineNumber: options.executionError.lineNumber,
});
break;
case TestResults.EMPTY_BLOCK_FAIL:
message =
options.level.emptyBlocksErrorMsg || msg.emptyBlocksErrorMsg();
break;
case TestResults.EMPTY_FUNCTION_BLOCK_FAIL:
if (options.level.emptyFunctionBlocksErrorMsg) {
message = options.level.emptyFunctionBlocksErrorMsg;
} else if (
Blockly.useContractEditor ||
Blockly.useModalFunctionEditor
) {
message = msg.errorEmptyFunctionBlockModal();
} else {
message = msg.emptyFunctionBlocksErrorMsg();
}
break;
case TestResults.TOO_FEW_BLOCKS_FAIL:
// This should be replaced by the LEVEL_INCOMPLETE_FAIL case, but some
// levels still override tooFewBlocksMsg.
message =
options.level.tooFewBlocksMsg ||
options.level.levelIncompleteError ||
msg.levelIncompleteError();
break;
case TestResults.LEVEL_INCOMPLETE_FAIL:
case TestResults.LOG_CONDITION_FAIL:
message =
options.level.levelIncompleteError || msg.levelIncompleteError();
break;
case TestResults.EXTRA_TOP_BLOCKS_FAIL:
var hasWhenRun = Blockly.mainBlockSpace
.getTopBlocks()
.some(function (block) {
return block.type === 'when_run' && block.isUserVisible();
});
var defaultMessage = hasWhenRun
? msg.extraTopBlocksWhenRun()
: msg.extraTopBlocks();
message = options.level.extraTopBlocks || defaultMessage;
break;
case TestResults.APP_SPECIFIC_FAIL:
message = options.level.appSpecificFailError;
break;
case TestResults.GENERIC_LINT_FAIL:
message = msg.errorGenericLintError();
break;
case TestResults.UNUSED_PARAM:
message = msg.errorUnusedParam();
break;
case TestResults.UNUSED_FUNCTION:
message = msg.errorUnusedFunction();
break;
case TestResults.PARAM_INPUT_UNATTACHED:
message = msg.errorParamInputUnattached();
break;
case TestResults.INCOMPLETE_BLOCK_IN_FUNCTION:
message = msg.errorIncompleteBlockInFunction();
break;
case TestResults.QUESTION_MARKS_IN_NUMBER_FIELD:
message = msg.errorQuestionMarksInNumberField();
break;
case TestResults.BLOCK_LIMIT_FAIL:
var exceededBlockType = this.hasExceededLimitedBlocks_();
var limit = Blockly.cdoUtils.getBlockLimit(exceededBlockType);
var block = `<xml><block type='${exceededBlockType}'></block></xml>`;
message = msg.errorExceededLimitedBlocks({limit}) + block;
break;
case TestResults.TOO_MANY_BLOCKS_FAIL:
// Allow apps to override the "too many blocks" failure message
// Passed as a msg function to allow the parameters to be passed in.
var messageFunction =
(options.appStrings &&
options.appStrings.tooManyBlocksFailMsgFunction) ||
msg.numBlocksNeeded;
message = messageFunction({
numBlocks: this.studioApp_.IDEAL_BLOCK_NUM,
puzzleNumber: options.level.puzzle_number || 0,
});
break;
case TestResults.APP_SPECIFIC_ACCEPTABLE_FAIL:
message = options.level.appSpecificAcceptableFailError;
break;
case TestResults.EDIT_BLOCKS:
message = options.level.edit_blocks_success;
break;
case TestResults.MISSING_BLOCK_UNFINISHED:
/* fallthrough */
case TestResults.MISSING_BLOCK_FINISHED:
message =
options.level.missingRequiredBlocksErrorMsg ||
msg.missingRequiredBlocksErrorMsg();
break;
case TestResults.MISSING_RECOMMENDED_BLOCK_UNFINISHED:
message = msg.missingRecommendedBlocksErrorMsg();
break;
case TestResults.MISSING_RECOMMENDED_BLOCK_FINISHED:
var numEnabledBlocks = this.getNumCountableBlocks();
if (
this.studioApp_.IDEAL_BLOCK_NUM &&
numEnabledBlocks > this.studioApp_.IDEAL_BLOCK_NUM
) {
message = msg.numBlocksNeeded({
numBlocks: this.studioApp_.IDEAL_BLOCK_NUM,
puzzleNumber: options.level.puzzle_number || 0,
});
} else {
message = msg.completedWithoutRecommendedBlock({
puzzleNumber: options.level.puzzle_number || 0,
});
}
break;
case TestResults.NESTED_FOR_SAME_VARIABLE:
message = msg.nestedForSameVariable();
break;
// Success.
case TestResults.ALL_PASS:
case TestResults.FREE_PLAY:
case TestResults.BETTER_THAN_IDEAL:
case TestResults.PASS_WITH_EXTRA_TOP_BLOCKS:
var finalLevel = options.level?.isLastLevelInLesson;
// End of lesson in CSD/CSP/CSA
if (finalLevel && options.level?.showEndOfLessonMsgs) {
message = msg.endOfLesson();
break;
}
var lessonCompleted = null;
if (options.response?.lesson_changing) {
lessonCompleted = options.response.lesson_changing.previous.name;
}
var msgParams = {
lessonNumber: 0, // TODO: remove once localized strings have been fixed
stageName: lessonCompleted,
puzzleNumber: options.level.puzzle_number || 0,
};
if (
TestResults.FREE_PLAY === options.feedbackType &&
!options.level.disableSharing
) {
var reinfFeedbackMsg = options.appStrings?.reinfFeedbackMsg || '';
if (options.level.disableFinalLessonMessage) {
message = reinfFeedbackMsg;
} else {
message = finalLevel ? msg.finalStage(msgParams) + ' ' : '';
message = message + reinfFeedbackMsg;
}
} else {
var nextLevelMsg =
options.appStrings?.nextLevelMsg || msg.nextLevel(msgParams);
message = finalLevel
? msg.finalStage(msgParams)
: lessonCompleted
? msg.nextStage(msgParams)
: nextLevelMsg;
}
break;
}
}
return message;
};
/**
* @returns {element} a document element with the appropriate feedback message.
* @see FeedbackUtils.prototype.getFeedbackMessage
*/
FeedbackUtils.prototype.getFeedbackMessageElement_ = function (options) {
var feedback = document.createElement('p');
feedback.className = 'congrats';
let message = this.getFeedbackMessage(options);
$(feedback).text(message);
return feedback;
};
/**
* @param {Object} options
* @param {MilestoneResponse} options.response
*/
FeedbackUtils.prototype.createSharingDiv = function (options) {
// TODO: this bypasses the config encapsulation to ensure we have the most up-to-date value.
if (
this.studioApp_.disableSocialShare ||
window.appOptions.disableSocialShare ||
options.disableSocialShare
) {
// Clear out our urls so that we don't display any of our social share links
options.twitterUrl = undefined;
options.facebookUrl = undefined;
} else {
// set up the twitter share url
var twitterUrl =
'https://twitter.com/intent/tweet?url=' + options.shareLink;
if (options.twitter && options.twitter.text !== undefined) {
twitterUrl += '&text=' + encodeURI(options.twitter.text);
} else {
twitterUrl +=
'&text=' + encodeURI(msg.defaultTwitterText() + ' @codeorg');
}
if (options.twitter && options.twitter.hashtag !== undefined) {
twitterUrl += '&hashtags=' + options.twitter.hashtag;
} else {
twitterUrl += '&hashtags=' + 'HourOfCode';
}
if (options.twitter && options.twitter.related !== undefined) {
twitterUrl += '&related=' + options.twitter.related;
} else {
twitterUrl += '&related=codeorg';
}
options.twitterUrl = twitterUrl;
// set up the facebook share url
var facebookUrl =
'https://www.facebook.com/sharer/sharer.php?u=' + options.shareLink;
options.facebookUrl = facebookUrl;
}
options.assetUrl = this.studioApp_.assetUrl;
// An early optimization; only render the container for
// DownloadReplayVideoButton if we think we're actually going to use it.
// @see DownloadReplayVideoButton.hasReplayVideo
options.downloadReplayVideo =
getStore().getState().pageConstants.appType === 'dance' &&
window.appOptions.signedReplayLogUrl;
var sharingDiv = document.createElement('div');
sharingDiv.setAttribute('id', 'sharing');
sharingDiv.innerHTML = require('./templates/sharing.html.ejs')({
options: options,
});
// Note: We have a dependency on dashboard here. This dependency has always
// been here (we used to mysteriously just always bubble clicks on body to
// a.popup-window if it existed), but it is now more explicit
if (window.dashboard && window.dashboard.popupWindow) {
$(sharingDiv).find('a.popup-window').click(window.dashboard.popupWindow);
}
var sharingCopyButton = sharingDiv.querySelector(
'#sharing-dialog-copy-button'
);
if (sharingCopyButton) {
dom.addClickTouchEvent(sharingCopyButton, function () {
recordFinishShare('FINISH_SHARING_LINK_COPY', project.getStandaloneApp());
copyToClipboard(options.shareLink, () => {
sharingCopyButton.className = 'sharing-dialog-copy-button-shared';
});
});
}
const twitterButtonSelector = '#twitter-button';
const twitterButton = sharingDiv.querySelector(twitterButtonSelector);
if (twitterButton) {
dom.addClickTouchEvent(twitterButton, () => {
recordFinishShare('FINISH_SHARING_TWITTER', project.getStandaloneApp());
});
}
const facebookButtonSelector = '#facebook-button';
const facebookButton = sharingDiv.querySelector(facebookButtonSelector);
if (facebookButton) {
dom.addClickTouchEvent(facebookButton, () => {
recordFinishShare('FINISH_SHARING_FB', project.getStandaloneApp());
});
}
var sharingFacebook = sharingDiv.querySelector('#sharing-facebook');
if (sharingFacebook) {
testImageAccess(
'https://facebook.com/favicon.ico' + '?' + Math.random(),
() => $(sharingFacebook).show()
);
}
var sharingTwitter = sharingDiv.querySelector('#sharing-twitter');
if (sharingTwitter) {
testImageAccess(
'https://twitter.com/favicon.ico' + '?' + Math.random(),
() => $(sharingTwitter).show()
);
}
// QR Code & SMS-to-phone feature
var sharingPhone = sharingDiv.querySelector('#sharing-phone');
dom.addClickTouchEvent(sharingPhone, function () {
recordFinishShare(
'FINISH_SHARING_LINK_SEND_TO_PHONE',
project.getStandaloneApp()
);