forked from code-dot-org/code-dot-org
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStudioApp.js
More file actions
3556 lines (3180 loc) · 111 KB
/
Copy pathStudioApp.js
File metadata and controls
3556 lines (3180 loc) · 111 KB
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 Blockly, droplet */
import $ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import {EventEmitter} from 'events';
import _ from 'lodash';
import url from 'url';
import {Provider} from 'react-redux';
import trackEvent from './util/trackEvent';
// Make sure polyfills are available in all code studio apps and level tests.
import './polyfills';
import * as aceMode from './acemode/mode-javascript_codeorg';
import * as assetPrefix from './assetManagement/assetPrefix';
import * as assets from './code-studio/assets';
import * as blockUtils from './block_utils';
var codegen = require('./lib/tools/jsinterpreter/codegen');
import * as dom from './dom';
import * as dropletUtils from './dropletUtils';
import * as shareWarnings from './shareWarnings';
import * as utils from './utils';
import AbuseError from './code-studio/components/AbuseError';
import Alert from './templates/alert';
import AuthoredHints from './authoredHints';
import ChallengeDialog from './templates/ChallengeDialog';
import DialogButtons from './templates/DialogButtons';
import DialogInstructions from './templates/instructions/DialogInstructions';
import DropletTooltipManager from './blockTooltips/DropletTooltipManager';
import FeedbackUtils from './feedback';
import InstructionsDialogWrapper from './templates/instructions/InstructionsDialogWrapper';
import SmallFooter from './code-studio/components/SmallFooter';
import Sounds from './Sounds';
import VersionHistory from './templates/VersionHistory';
import WireframeButtons from './lib/ui/WireframeButtons';
import annotationList from './acemode/annotationList';
import color from './util/color';
import firehoseClient from './lib/util/firehose';
import getAchievements from './achievements';
import logToCloud from './logToCloud';
import msg from '@cdo/locale';
import project from './code-studio/initApp/project';
import puzzleRatingUtils from './puzzleRatingUtils';
import userAgentParser from './code-studio/initApp/userAgentParser';
import {
KeyCodes,
TestResults,
TOOLBOX_EDIT_MODE,
NOTIFICATION_ALERT_TYPE
} from './constants';
import {assets as assetsApi} from './clientApi';
import {
configCircuitPlayground,
configMicrobit
} from './lib/kits/maker/dropletConfig';
import {closeDialog as closeInstructionsDialog} from './redux/instructionsDialog';
import {getStore} from './redux';
import {getValidatedResult, initializeContainedLevel} from './containedLevels';
import {lockContainedLevelAnswers} from './code-studio/levels/codeStudioLevels';
import {parseElement as parseXmlElement} from './xml';
import {resetAniGif} from '@cdo/apps/utils';
import {setIsRunning, setIsEditWhileRun, setStepSpeed} from './redux/runState';
import {isEditWhileRun} from './lib/tools/jsdebugger/redux';
import {setPageConstants} from './redux/pageConstants';
import {setVisualizationScale} from './redux/layout';
import {createLibraryClosure} from '@cdo/apps/code-studio/components/libraries/libraryParser';
import {
setAchievements,
setBlockLimit,
setFeedbackData,
showFeedback
} from './redux/feedback';
import experiments from '@cdo/apps/util/experiments';
import {
determineInstructionsConstants,
setInstructionsConstants,
setFeedback
} from './redux/instructions';
import {addCallouts} from '@cdo/apps/code-studio/callouts';
import {queryParams} from '@cdo/apps/code-studio/utils';
import {RESIZE_VISUALIZATION_EVENT} from './lib/ui/VisualizationResizeBar';
import {userAlreadyReportedAbuse} from '@cdo/apps/reportAbuse';
import {setArrowButtonDisabled} from '@cdo/apps/templates/arrowDisplayRedux';
import {workspace_running_background, white} from '@cdo/apps/util/color';
import WorkspaceAlert from '@cdo/apps/code-studio/components/WorkspaceAlert';
var copyrightStrings;
/**
* The minimum width of a playable whole blockly game.
*/
const MIN_WIDTH = 1200;
const DEFAULT_MOBILE_NO_PADDING_SHARE_WIDTH = 400;
export const MAX_VISUALIZATION_WIDTH = 400;
export const MIN_VISUALIZATION_WIDTH = 200;
/**
* Treat mobile devices with screen.width less than the value below as phones.
*/
const MAX_PHONE_WIDTH = 500;
class StudioApp extends EventEmitter {
constructor() {
super();
this.feedback_ = new FeedbackUtils(this);
this.authoredHintsController_ = new AuthoredHints(this);
/**
* The parent directory of the apps. Contains common.js.
*/
this.BASE_URL = undefined;
this.enableShowCode = true;
this.editCode = false;
this.usingBlockly_ = true;
/**
* @type {?Droplet.Editor}
*/
this.editor = null;
/**
* @type {?DropletTooltipManager}
*/
this.dropletTooltipManager = null;
// @type {string} for all of these
this.icon = undefined;
this.winIcon = undefined;
this.failureIcon = undefined;
// The following properties get their non-default values set by the application.
/**
* Whether to alert user to empty blocks, short-circuiting all other tests.
* @member {boolean}
*/
this.checkForEmptyBlocks_ = false;
/**
* The ideal number of blocks to solve this level. Users only get 2
* stars if they use more than this number.
* @type {number}
*/
this.IDEAL_BLOCK_NUM = undefined;
/**
* @type {!TestableBlock[]}
*/
this.requiredBlocks_ = [];
/**
* The number of required blocks to give hints about at any one time.
* Set this to Infinity to show all.
* @type {number}
*/
this.maxRequiredBlocksToFlag_ = 1;
/**
* @type {!TestableBlock[]}
*/
this.recommendedBlocks_ = [];
/**
* The number of recommended blocks to give hints about at any one time.
* Set this to Infinity to show all.
* @type {number}
*/
this.maxRecommendedBlocksToFlag_ = 1;
/**
* The number of attempts (how many times the run button has been pressed)
* @type {?number}
*/
this.attempts = 0;
/**
* Stores the time at init. The delta to current time is used for logging
* and reporting to capture how long it took to arrive at an attempt.
* @type {?number}
*/
this.initTime = undefined;
/**
* The time the last milestone was recorded. Used for recording the time a
* student has spent on a level.
* @type {?number}
*/
this.milestoneStartTime = undefined;
/**
* Whether we've reported a milestone yet for this run/reset cycle
* @type {boolean}
*/
this.hasReported = false;
/**
* If true, we don't show blockspace. Used when viewing shared levels
*/
this.hideSource = false;
/**
* If true, we're viewing a shared level.
*/
this.share = false;
this.onAttempt = undefined;
this.onContinue = undefined;
this.onResetPressed = undefined;
this.backToPreviousLevel = undefined;
this.isUS = undefined;
this.enableShowBlockCount = true;
this.disableSocialShare = false;
this.noPadding = false;
this.MIN_WORKSPACE_HEIGHT = undefined;
/**
* Levelbuilder-defined helper libraries.
*/
this.libraries = {};
/*
* Stores the alert that appears if the user edits code while its running. It will be unmounted and set to undefined on reset.
*/
this.editDuringRunAlert = undefined;
/*
* Stores whether we should display the alert above. Will be set to false and stored in localStorage if the user has already dismissed this alert.
*/
this.showEditDuringRunAlert = true;
/*
* Stores the code at run. It's undefined if the code is not running.
*/
this.executingCode = undefined;
}
}
/**
* Configure StudioApp options
*/
StudioApp.prototype.configure = function(options) {
this.BASE_URL = options.baseUrl;
// NOTE: editCode (which currently implies droplet) and usingBlockly_ are
// currently mutually exclusive.
this.editCode = options.level && options.level.editCode;
this.usingBlockly_ = !this.editCode;
if (options.isEditorless) {
this.editCode = false;
this.usingBlockly_ = false;
}
// Bind assetUrl to the instance so that we don't need to depend on callers
// binding correctly as they pass this function around.
this.assetUrl = _.bind(this.assetUrl_, this);
this.maxVisualizationWidth =
options.maxVisualizationWidth || MAX_VISUALIZATION_WIDTH;
this.minVisualizationWidth =
options.minVisualizationWidth || MIN_VISUALIZATION_WIDTH;
// Set default speed
if (options.level) {
getStore().dispatch(setStepSpeed(options.level.sliderSpeed));
}
};
/**
* @param {AppOptionsConfig}
*/
StudioApp.prototype.hasInstructionsToShow = function(config) {
return !!(
config.level.shortInstructions ||
config.level.longInstructions ||
config.level.aniGifURL
);
};
/**
* Given the studio app config object, show shared app warnings.
*/
function showWarnings(config) {
shareWarnings.checkSharedAppWarnings({
channelId: config.channel,
isSignedIn: config.isSignedIn,
isTooYoung: config.isTooYoung,
isOwner: project.isOwner(),
hasDataAPIs: config.shareWarningInfo.hasDataAPIs,
onWarningsComplete: config.shareWarningInfo.onWarningsComplete,
onTooYoung: config.shareWarningInfo.onTooYoung
});
}
/**
* Common startup tasks for all blockly and droplet apps. Happens
* after configure.
* @param {AppOptionsConfig}
*/
StudioApp.prototype.init = function(config) {
if (!config) {
config = {};
}
this.config = config;
config.getCode = this.getCode.bind(this);
copyrightStrings = config.copyrightStrings;
if (config.legacyShareStyle && config.hideSource) {
$('body').addClass('legacy-share-view');
if (dom.isMobile()) {
$('body').addClass('legacy-share-view-mobile');
$('#main-logo').hide();
}
}
this.setConfigValues_(config);
this.configureDom(config);
if (!config.level.iframeEmbedAppAndCode) {
ReactDOM.render(
<Provider store={getStore()}>
<div>
<InstructionsDialogWrapper
showInstructionsDialog={autoClose => {
this.showInstructionsDialog_(config.level, autoClose);
}}
/>
</div>
</Provider>,
document.body.appendChild(document.createElement('div'))
);
}
if (config.usesAssets && config.channel) {
assetPrefix.init(config);
// Pre-populate asset list
assetsApi.getFiles(
result => {
assets.listStore.reset(result.files);
},
xhr => {
// Unable to load asset list
}
);
}
if (config.hideSource) {
this.handleHideSource_({
containerId: config.containerId,
embed: config.embed,
level: config.level,
noHowItWorks: config.noHowItWorks,
isLegacyShare: config.isLegacyShare,
legacyShareStyle: config.legacyShareStyle,
wireframeShare: config.wireframeShare
});
}
if (config.level.iframeEmbedAppAndCode) {
StudioApp.prototype.handleIframeEmbedAppAndCode_({
containerId: config.containerId,
embed: config.embed,
level: config.level,
noHowItWorks: config.noHowItWorks,
isLegacyShare: config.isLegacyShare,
legacyShareStyle: config.legacyShareStyle,
wireframeShare: config.wireframeShare
});
}
if (config.share) {
this.handleSharing_({
makeUrl: config.makeUrl,
makeString: config.makeString,
makeImage: config.makeImage,
makeYourOwn: config.makeYourOwn
});
}
if (!config.level.iframeEmbedAppAndCode) {
const hintsUsedIds = utils.valueOr(config.authoredHintsUsedIds, []);
this.authoredHintsController_.init(
config.level.authoredHints,
hintsUsedIds,
config.scriptId,
config.serverLevelId
);
}
if (config.authoredHintViewRequestsUrl && config.isSignedIn) {
this.authoredHintsController_.submitHints(
config.authoredHintViewRequestsUrl
);
}
if (config.puzzleRatingsUrl) {
puzzleRatingUtils.submitCachedPuzzleRatings(config.puzzleRatingsUrl);
}
// Record time at initialization.
this.initTime = new Date().getTime();
this.initTimeSpent();
// Fixes viewport for small screens.
var viewport = document.querySelector('meta[name="viewport"]');
if (viewport) {
this.fixViewportForSmallScreens_(viewport, config);
}
var blockCount = document.getElementById('blockCounter');
if (blockCount && !this.enableShowBlockCount) {
blockCount.style.display = 'none';
}
this.setIconsFromSkin(config.skin);
if (config.level.instructionsIcon) {
this.icon = config.skin[config.level.instructionsIcon];
this.winIcon = config.skin[config.level.instructionsIcon];
}
if (config.showInstructionsWrapper) {
config.showInstructionsWrapper(() => {});
}
var orientationHandler = function() {
window.scrollTo(0, 0); // Browsers like to mess with scroll on rotate.
};
window.addEventListener('orientationchange', orientationHandler);
orientationHandler();
if (config.loadAudio) {
config.loadAudio();
}
if (this.editCode) {
this.handleEditCode_(config);
}
if (this.isUsingBlockly()) {
this.handleUsingBlockly_(config);
} else {
// handleUsingBlockly_ already does an onResize. We still want that goodness
// if we're not blockly
utils.fireResizeEvent();
}
this.alertIfAbusiveProject();
this.alertIfProfaneOrPrivacyViolatingProject();
// make sure startIFrameEmbeddedApp has access to the config object
// so it can decide whether or not to show a warning.
this.startIFrameEmbeddedApp = this.startIFrameEmbeddedApp.bind(this, config);
// config.shareWarningInfo is set on a per app basis (in applab and gamelab)
// shared apps that are embedded in an iframe handle warnings in
// startIFrameEmbeddedApp since they don't become "active" until the user
// clicks on them.
if (config.shareWarningInfo && !config.level.iframeEmbed) {
showWarnings(config);
}
this.initProjectTemplateWorkspaceIconCallout();
this.alertIfCompletedWhilePairing(config);
// If we are in a non-english locale using our english-specific app
// (the Spelling Bee), display a warning.
if (config.locale !== 'en_us' && config.skinId === 'letters') {
this.displayWorkspaceAlert(
'error',
<div>
{msg.englishOnlyWarning({nextStage: config.lessonPosition + 1})}
</div>
);
}
window.addEventListener('resize', this.onResize.bind(this));
window.addEventListener(RESIZE_VISUALIZATION_EVENT, e => {
this.resizeVisualization(e.detail);
});
this.reset(true);
// Add display of blocks used.
this.setIdealBlockNumber_();
// TODO (cpirich): implement block count for droplet (for now, blockly only)
if (this.isUsingBlockly()) {
Blockly.mainBlockSpaceEditor.addUnusedBlocksHelpListener(function(e) {
utils.showUnusedBlockQtip(e.target);
});
// Store result so that we can cleanup later in tests
this.changeListener = Blockly.mainBlockSpaceEditor.addChangeListener(
_.bind(function() {
this.updateBlockCount();
}, this)
);
if (config.level.openFunctionDefinition) {
this.openFunctionDefinition_(config);
}
}
// Bind listener to 'Clear Puzzle' button
var hideIcon = utils.valueOr(config.skin.hideIconInClearPuzzle, false);
var clearPuzzleHeader = document.getElementById('clear-puzzle-header');
if (clearPuzzleHeader) {
dom.addClickTouchEvent(
clearPuzzleHeader,
function() {
this.feedback_.showClearPuzzleConfirmation(
hideIcon,
function() {
this.handleClearPuzzle(config);
}.bind(this)
);
}.bind(this)
);
}
this.initVersionHistoryUI(config);
if (this.isUsingBlockly() && Blockly.contractEditor) {
Blockly.contractEditor.registerTestsFailedOnCloseHandler(
function() {
this.feedback_.showSimpleDialog({
headerText: undefined,
bodyText: msg.examplesFailedOnClose(),
cancelText: msg.ignore(),
confirmText: msg.tryAgain(),
onConfirm: null,
onCancel: function() {
Blockly.contractEditor.hideIfOpen();
}
});
// return true to indicate to blockly-core that we'll own closing the
// contract editor
return true;
}.bind(this)
);
}
if (config.legacyShareStyle && config.hideSource) {
this.setupLegacyShareView();
}
if (config.isChallengeLevel) {
const startDialogDiv = document.createElement('div');
document.body.appendChild(startDialogDiv);
const progress = getStore().getState().progress;
const isComplete =
progress.levelResults[progress.currentLevelId] >=
TestResults.MINIMUM_OPTIMAL_RESULT;
ReactDOM.render(
<ChallengeDialog
isOpen={true}
avatar={this.icon}
handleCancel={() => {
this.skipLevel();
}}
cancelButtonLabel={msg.challengeLevelSkip()}
complete={isComplete}
isIntro={true}
primaryButtonLabel={msg.challengeLevelStart()}
text={msg.challengeLevelIntro()}
title={msg.challengeLevelTitle()}
/>,
startDialogDiv
);
}
if (!config.readonlyWorkspace) {
this.addChangeHandler(this.editDuringRunAlertHandler.bind(this));
}
this.emit('afterInit');
};
/*
* If the code has changed (other than whitespace at the beginning or end) and the code is running,
* tell redux the code has changed, disable block highlighting, and conditionally display an alert.
* Note: We trim the whitespace because droplet sometimes adds an extra newline when switching from block to code mode.
*/
StudioApp.prototype.editDuringRunAlertHandler = function() {
const hasEditedDuringRun =
this.isRunning() && this.getCode().trim() !== this.executingCode.trim();
if (!hasEditedDuringRun || this.editDuringRunAlert !== undefined) {
return;
}
getStore().dispatch(setIsEditWhileRun(true));
this.clearHighlighting();
// Check if the user has already dismissed this alert. Don't check localStorage again
// if showEditDuringRunAlert has already been set to false.
if (this.showEditDuringRunAlert) {
this.showEditDuringRunAlert =
utils.tryGetLocalStorage('hideEditDuringRunAlert', null) === null;
}
// Display the alert if the user hasn't previously dismissed it.
if (this.showEditDuringRunAlert) {
const onClose = () => {
utils.trySetLocalStorage('hideEditDuringRunAlert', true);
this.editDuringRunAlert = undefined;
this.showEditDuringRunAlert = false;
};
this.editDuringRunAlert = this.displayWorkspaceAlert(
'warning',
React.createElement('div', {}, msg.editDuringRunMessage()),
true /* bottom */,
onClose
);
}
};
StudioApp.prototype.initProjectTemplateWorkspaceIconCallout = function() {
if (getStore().getState().pageConstants.showProjectTemplateWorkspaceIcon) {
// The callouts can't appear until the DOM is 100% rendered by react. The
// safest method is to kick off a requestAnimationFrame from an async
// setTimeout()
setTimeout(() => {
requestAnimationFrame(() => {
addCallouts([
{
id: 'projectTemplateWorkspaceIconCallout',
element_id: '.projectTemplateWorkspaceIcon:visible',
localized_text: msg.workspaceProjectTemplateLevel(),
qtip_config: {
position: {
my: 'top center',
at: 'bottom center'
}
}
}
]);
});
}, 0);
}
};
StudioApp.prototype.alertIfCompletedWhilePairing = function(config) {
if (!!config.level.pairingDriver) {
this.displayWorkspaceAlert(
'warning',
<div>
{msg.pairingNavigatorWarning({driver: config.level.pairingDriver})}{' '}
{config.level.pairingAttempt && (
<a href={config.level.pairingAttempt}>{msg.pairingNavigatorLink()}</a>
)}
{config.level.pairingChannelId && (
<a href={project.getPathName('view', config.level.pairingChannelId)}>
{msg.pairingNavigatorLink()}
</a>
)}
</div>
);
}
};
StudioApp.prototype.getVersionHistoryHandler = function(config) {
return () => {
var contentDiv = document.createElement('div');
var dialog = this.createModalDialog({
contentDiv: contentDiv,
defaultBtnSelector: 'again-button',
id: 'showVersionsModal'
});
ReactDOM.render(
React.createElement(VersionHistory, {
handleClearPuzzle: this.handleClearPuzzle.bind(this, config),
isProjectTemplateLevel: !!config.level.projectTemplateLevelName,
useFilesApi: !!config.useFilesApi
}),
contentDiv
);
dialog.show();
};
};
StudioApp.prototype.initTimeSpent = function() {
this.milestoneStartTime = new Date().getTime();
this.debouncedSilentlyReport = _.debounce(
this.silentlyReport.bind(this),
1000
);
};
StudioApp.prototype.initVersionHistoryUI = function(config) {
// Bind listener to 'Version History' button
var versionsHeader = document.getElementById('versions-header');
if (versionsHeader) {
dom.addClickTouchEvent(
versionsHeader,
this.getVersionHistoryHandler(config)
);
}
};
StudioApp.prototype.startIFrameEmbeddedApp = function(config, onTooYoung) {
if (this.share && config.shareWarningInfo) {
config.shareWarningInfo.onTooYoung = onTooYoung;
showWarnings(config);
} else {
this.runButtonClick();
}
};
/**
* Create a phone frame and container. Scale shared content (everything currently inside the visualization column)
* to container width, fit container to the phone frame and add share footer.
*/
StudioApp.prototype.setupLegacyShareView = function() {
var vizContainer = document.createElement('div');
vizContainer.id = 'visualizationContainer';
var vizColumn = document.getElementById('visualizationColumn');
if (dom.isMobile()) {
$(vizContainer).width($(vizColumn).width());
}
$(vizContainer).append(vizColumn.children);
var phoneFrameScreen = document.createElement('div');
phoneFrameScreen.id = 'phoneFrameScreen';
$(phoneFrameScreen).append(vizContainer);
$(vizColumn).append(phoneFrameScreen);
this.renderShareFooter_(phoneFrameScreen);
if (dom.isMobile) {
// re-scale on resize events to adjust to orientation and navbar changes
$(window).resize(this.scaleLegacyShare);
}
this.scaleLegacyShare();
};
StudioApp.prototype.scaleLegacyShare = function() {
var vizContainer = document.getElementById('visualizationContainer');
var vizColumn = document.getElementById('visualizationColumn');
var phoneFrameScreen = document.getElementById('phoneFrameScreen');
var vizWidth = $(vizContainer).width();
// On mobile, scale up phone frame to full screen (portrait) as needed.
// Otherwise use given dimensions from css.
if (dom.isMobile()) {
const {clientHeight, clientWidth} = document.documentElement;
const screenWidth = Math.min(clientHeight, clientWidth);
const screenHeight = Math.max(clientWidth, clientHeight);
// Choose the larger of the document client size and the existing
// phoneFrameScreen size:
const newWidth = Math.max(screenWidth, $(phoneFrameScreen).width());
const newHeight = Math.max(screenHeight, $(phoneFrameScreen).height());
$(phoneFrameScreen).width(newWidth);
$(phoneFrameScreen).height(newHeight);
$(vizColumn).width(newWidth);
}
var frameWidth = $(phoneFrameScreen).width();
var scale = frameWidth / vizWidth;
if (scale !== 1) {
applyTransformOrigin(vizContainer, 'left top');
applyTransformScale(vizContainer, 'scale(' + scale + ')');
}
};
StudioApp.prototype.getCode = function(opt_showHidden) {
if (!this.editCode) {
return Blockly.getWorkspaceCode(opt_showHidden);
}
if (this.hideSource) {
return this.startBlocks_;
} else {
return this.editor.getValue();
}
};
StudioApp.prototype.setIconsFromSkin = function(skin) {
this.icon = skin.staticAvatar;
this.winIcon = skin.winAvatar;
this.failureIcon = skin.failureAvatar;
};
/**
* Reset the puzzle back to its initial state.
* Search aliases: "Start Over", startOver
* @param {AppOptionsConfig}- same config object passed to studioApp.init().
* @return {Promise} to express that the async operation is complete.
*/
StudioApp.prototype.handleClearPuzzle = function(config) {
var promise;
if (this.isUsingBlockly()) {
if (Blockly.functionEditor) {
Blockly.functionEditor.hideIfOpen();
}
Blockly.mainBlockSpace.clear();
this.setStartBlocks_(config, false);
if (config.level.openFunctionDefinition) {
this.openFunctionDefinition_(config);
}
} else if (this.editCode) {
var resetValue = '';
if (config.level.startBlocks) {
// Don't pass CRLF pairs to droplet until they fix CR handling:
resetValue = config.level.startBlocks.replace(/\r\n/g, '\n');
}
// This getValue() call is a workaround for a Droplet bug,
// See https://github.com/droplet-editor/droplet/issues/137
// Calling getValue() updates the cached ace editor value, which can be
// out-of-date in droplet and cause an incorrect early-out.
// Could remove this line once that bug is fixed and Droplet is updated.
this.editor.getValue();
this.editor.setValue(resetValue);
annotationList.clearRuntimeAnnotations();
}
if (config.afterClearPuzzle) {
promise = config.afterClearPuzzle(config);
}
if (!promise) {
// If a promise wasn't returned from config.afterClearPuzzle(), we create
// on here that returns immediately since the operation must have completed
// synchronously.
promise = new Promise(function(resolve, reject) {
resolve();
});
}
return promise;
};
/**
* TRUE if the current app uses blockly (as opposed to editCode or another
* editor)
* @return {boolean}
*/
StudioApp.prototype.isUsingBlockly = function() {
return this.usingBlockly_;
};
/**
*
*/
StudioApp.prototype.handleSharing_ = function(options) {
// 1. Move the buttons, 2. Hide the slider in the share page for mobile.
var belowVisualization = document.getElementById('belowVisualization');
if (dom.isMobile()) {
var sliderCell = document.getElementById('slider-cell');
if (sliderCell) {
sliderCell.style.display = 'none';
}
if (belowVisualization) {
var visualization = document.getElementById('visualization');
belowVisualization.style.display = 'none';
visualization.style.marginBottom = '0px';
}
}
// Show flappy upsale on desktop and mobile. Show learn upsale only on desktop
var upSale = document.createElement('div');
if (options.makeYourOwn) {
upSale.innerHTML = require('./templates/makeYourOwn.html.ejs')({
data: {
makeUrl: options.makeUrl,
makeString: options.makeString,
makeImage: options.makeImage
}
});
if (this.noPadding) {
upSale.style.marginLeft = '10px';
}
belowVisualization.appendChild(upSale);
} else if (typeof options.makeYourOwn === 'undefined') {
upSale.innerHTML = require('./templates/learn.html.ejs')({
assetUrl: this.assetUrl
});
belowVisualization.appendChild(upSale);
}
};
export function makeFooterMenuItems() {
const footerMenuItems = [
{
key: 'try-hoc',
text: msg.tryHourOfCode(),
link: 'https://code.org/learn',
newWindow: true
},
{
key: 'how-it-works',
text: msg.howItWorks(),
link: project.getProjectUrl('/edit'),
newWindow: false
},
{
key: 'report-abuse',
text: msg.reportAbuse(),
link: '/report_abuse',
newWindow: true
},
{
text: msg.copyright(),
link: 'javascript:void(0)',
copyright: true
},
{
text: msg.tos(),
link: 'https://code.org/tos',
newWindow: true
},
{
text: msg.privacyPolicy(),
link: 'https://code.org/privacy',
newWindow: true
}
];
//Removes 'Try-HOC' from only gamelab footer menu
if (project.getStandaloneApp() === 'gamelab') {
footerMenuItems.shift();
}
const channelId = project.getCurrentId();
const alreadyReportedAbuse = userAlreadyReportedAbuse(channelId);
if (alreadyReportedAbuse) {
_.remove(footerMenuItems, function(menuItem) {
return menuItem.key === 'report-abuse';
});
}
return footerMenuItems;
}
StudioApp.prototype.renderShareFooter_ = function(container) {
var footerDiv = document.createElement('div');
footerDiv.setAttribute('id', 'footerDiv');
container.appendChild(footerDiv);
var reactProps = {
i18nDropdown: '',
privacyPolicyInBase: false,
copyrightInBase: false,
copyrightStrings: copyrightStrings,
baseMoreMenuString: msg.builtOnCodeStudio(),
baseStyle: {
paddingLeft: 0,
width: $('#visualization').width()
},
className: 'dark',
menuItems: makeFooterMenuItems(),
phoneFooter: true,
channel: project.getCurrentId()
};
ReactDOM.render(<SmallFooter {...reactProps} />, footerDiv);
};
/**
* Get the url of path appended to BASE_URL
*/
StudioApp.prototype.assetUrl_ = function(path) {
if (this.BASE_URL === undefined) {
throw new Error(
'StudioApp BASE_URL has not been set. ' + 'Call configure() first'
);
}
return this.BASE_URL + path;
};
/**
* Reset the playing field to the start position and kill any pending
* animation tasks. This will typically be replaced by an application.
* @param {boolean} shouldPlayOpeningAnimation True if an opening animation is
* to be played.
*/
StudioApp.prototype.reset = function(shouldPlayOpeningAnimation) {
// Override in app subclass
};
/**
* Override to change run behavior.
*/
StudioApp.prototype.runButtonClick = function() {};
StudioApp.prototype.addChangeHandler = function(newHandler) {
if (!this.changeHandlers) {
this.changeHandlers = [];
}
this.changeHandlers.push(newHandler);
};
StudioApp.prototype.runChangeHandlers = function() {
if (!this.changeHandlers) {
return;
}
this.changeHandlers.forEach(handler => handler());
};