-
Notifications
You must be signed in to change notification settings - Fork 193
Expand file tree
/
Copy pathPlayground.tsx
More file actions
1084 lines (1001 loc) · 39.2 KB
/
Playground.tsx
File metadata and controls
1084 lines (1001 loc) · 39.2 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
import { Classes } from '@blueprintjs/core';
import { IconNames } from '@blueprintjs/icons';
import { type HotkeyItem, useHotkeys } from '@mantine/hooks';
import type { AnyAction, Dispatch } from '@reduxjs/toolkit';
import type { SharedbAceUser } from '@sourceacademy/sharedb-ace/types';
import { Ace, Range } from 'ace-builds';
import type { FSModule } from 'browserfs/dist/node/core/FS';
import classNames from 'classnames';
import { Chapter, Variant } from 'js-slang/dist/langs';
import { isEqual } from 'lodash';
import { decompressFromEncodedURIComponent } from 'lz-string';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useDispatch, useStore } from 'react-redux';
import { useLocation, useNavigate } from 'react-router';
import InterpreterActions from 'src/commons/application/actions/InterpreterActions';
import SessionActions from 'src/commons/application/actions/SessionActions';
import {
setEditorSessionId,
setSessionDetails,
setSharedbConnected,
} from 'src/commons/collabEditing/CollabEditingActions';
import ControlBarExecutionTime from 'src/commons/controlBar/ControlBarExecutionTime';
import makeCseMachineTabFrom from 'src/commons/sideContent/content/SideContentCseMachine';
import makeDataVisualizerTabFrom from 'src/commons/sideContent/content/SideContentDataVisualizer';
import makeHtmlDisplayTabFrom from 'src/commons/sideContent/content/SideContentHtmlDisplay';
import makeUploadTabFrom from 'src/commons/sideContent/content/SideContentUpload';
import { changeSideContentHeight } from 'src/commons/sideContent/SideContentActions';
import { useSideContent } from 'src/commons/sideContent/SideContentHelper';
import { useResponsive, useTypedSelector } from 'src/commons/utils/Hooks';
import {
showFullJSWarningOnUrlLoad,
showFulTSWarningOnUrlLoad,
showHTMLDisclaimer,
} from 'src/commons/utils/WarningDialogHelper';
import WorkspaceActions from 'src/commons/workspace/WorkspaceActions';
import type { WorkspaceLocation } from 'src/commons/workspace/WorkspaceTypes';
import CseMachine from 'src/features/cseMachine/CseMachine';
import GithubActions from 'src/features/github/GitHubActions';
import PersistenceActions from 'src/features/persistence/PersistenceActions';
import {
generateLzString,
playgroundConfigLanguage,
shortenURL,
updateShortURL,
} from 'src/features/playground/PlaygroundActions';
import Messages, { sendToWebview } from 'src/features/vscode/messages';
import {
getDefaultFilePath,
getLanguageConfig,
isCseVariant,
isSourceLanguage,
type OverallState,
type ResultOutput,
type SALanguage,
} from '../../commons/application/ApplicationTypes';
import { ExternalLibraryName } from '../../commons/application/types/ExternalTypes';
import ControlBarAutorunButtons from '../../commons/controlBar/ControlBarAutorunButtons';
import ControlBarChapterSelect from '../../commons/controlBar/ControlBarChapterSelect';
import ControlBarClearButton from '../../commons/controlBar/ControlBarClearButton';
import ControlBarEvalButton from '../../commons/controlBar/ControlBarEvalButton';
import ControlBarGoogleDriveButtons from '../../commons/controlBar/ControlBarGoogleDriveButtons';
import ControlBarSessionButtons from '../../commons/controlBar/ControlBarSessionButton';
import ControlBarShareButton from '../../commons/controlBar/ControlBarShareButton';
import ControlBarStepLimit from '../../commons/controlBar/ControlBarStepLimit';
import ControlBarToggleFolderModeButton from '../../commons/controlBar/ControlBarToggleFolderModeButton';
import ControlBarGitHubButtons from '../../commons/controlBar/github/ControlBarGitHubButtons';
import {
convertEditorTabStateToProps,
type NormalEditorContainerProps,
} from '../../commons/editor/EditorContainer';
import type { Position } from '../../commons/editor/EditorTypes';
import { overwriteFilesInWorkspace } from '../../commons/fileSystem/utils';
import FileSystemView from '../../commons/fileSystemView/FileSystemView';
import MobileWorkspace, {
type MobileWorkspaceProps,
} from '../../commons/mobileWorkspace/MobileWorkspace';
import type { SideBarTab } from '../../commons/sideBar/SideBar';
import { type SideContentTab, SideContentType } from '../../commons/sideContent/SideContentTypes';
import Constants, { Links } from '../../commons/utils/Constants';
import { generateLanguageIntroduction } from '../../commons/utils/IntroductionHelper';
import { convertParamToBoolean, convertParamToInt } from '../../commons/utils/ParamParseHelper';
import { type IParsedQuery, parseQuery } from '../../commons/utils/QueryHelper';
import Workspace, { type WorkspaceProps } from '../../commons/workspace/Workspace';
import { initSession, log } from '../../features/eventLogging';
import type {
CodeDelta,
Input,
SelectionRange,
} from '../../features/eventLogging/EventLoggingTypes';
import { WORKSPACE_BASE_PATHS } from '../fileSystem/createInBrowserFileSystem';
import {
desktopOnlyTabIds,
makeIntroductionTabFrom,
makeRemoteExecutionTabFrom,
makeSessionManagementTabFrom,
makeSubstVisualizerTabFrom,
mobileOnlyTabIds,
} from './PlaygroundTabs';
export type PlaygroundProps = {
isSicpEditor?: boolean;
initialEditorValueHash?: string;
prependLength?: number;
handleCloseEditor?: () => void;
};
export async function handleHash(
hash: string,
handlers: {
handleChapterSelect: (chapter: Chapter, variant: Variant) => void;
handleChangeExecTime: (execTime: number) => void;
},
workspaceLocation: WorkspaceLocation,
dispatch: Dispatch<AnyAction>,
fileSystem: FSModule | null,
) {
// Make the parsed query string object a Partial because we might access keys which are not set.
const qs: Partial<IParsedQuery> = parseQuery(hash);
const chapter = convertParamToInt(qs.chap) ?? undefined;
if (chapter === Chapter.FULL_JS) {
showFullJSWarningOnUrlLoad();
} else if (chapter === Chapter.FULL_TS) {
showFulTSWarningOnUrlLoad();
} else {
if (chapter === Chapter.HTML) {
const continueToHtml = await showHTMLDisclaimer();
if (!continueToHtml) {
return;
}
}
// For backward compatibility with old share links - 'prgrm' is no longer used.
const program = qs.prgrm === undefined ? '' : decompressFromEncodedURIComponent(qs.prgrm);
// By default, create just the default file.
const defaultFilePath = getDefaultFilePath(workspaceLocation);
const files: Record<string, string> =
qs.files === undefined
? {
[defaultFilePath]: program,
}
: parseQuery(decompressFromEncodedURIComponent(qs.files));
if (fileSystem !== null) {
await overwriteFilesInWorkspace(workspaceLocation, fileSystem, files);
}
// BrowserFS does not provide a way of listening to changes in the file system, which makes
// updating the file system view troublesome. To force the file system view to re-render
// (and thus display the updated file system), we first disable Folder mode.
dispatch(WorkspaceActions.setFolderMode(workspaceLocation, false));
const isFolderModeEnabled = convertParamToBoolean(qs.isFolder) ?? false;
// If Folder mode should be enabled, enabling it after disabling it earlier will cause the
// newly-added files to be shown. Note that this has to take place after the files are
// already added to the file system.
dispatch(WorkspaceActions.setFolderMode(workspaceLocation, isFolderModeEnabled));
// By default, open a single editor tab containing the default playground file.
const editorTabFilePaths = qs.tabs?.split(',').map(decompressFromEncodedURIComponent) ?? [
defaultFilePath,
];
// Remove all editor tabs before populating with the ones from the query string.
dispatch(
WorkspaceActions.removeEditorTabsForDirectory(
workspaceLocation,
WORKSPACE_BASE_PATHS[workspaceLocation],
),
);
// Add editor tabs from the query string.
editorTabFilePaths.forEach(filePath =>
// Fall back on the empty string if the file contents do not exist.
dispatch(WorkspaceActions.addEditorTab(workspaceLocation, filePath, files[filePath] ?? '')),
);
// By default, use the first editor tab.
const activeEditorTabIndex = convertParamToInt(qs.tabIdx) ?? 0;
dispatch(WorkspaceActions.updateActiveEditorTabIndex(workspaceLocation, activeEditorTabIndex));
if (chapter) {
// TODO: To migrate the state logic away from playgroundSourceChapter
// and playgroundSourceVariant into the language config instead
const languageConfig = getLanguageConfig(chapter, qs.variant as Variant);
handlers.handleChapterSelect(chapter, languageConfig.variant);
// Hardcoded for Playground only for now, while we await workspace refactoring
// to decouple the SicpWorkspace from the Playground.
dispatch(playgroundConfigLanguage(languageConfig));
}
const execTime = Math.max(convertParamToInt(qs.exec || '1000') || 1000, 1000);
if (execTime) {
handlers.handleChangeExecTime(execTime);
}
}
}
const Playground: React.FC<PlaygroundProps> = props => {
const { isSicpEditor } = props;
const workspaceLocation: WorkspaceLocation = isSicpEditor ? 'sicp' : 'playground';
const { isMobileBreakpoint } = useResponsive();
const isVscode = useTypedSelector(state => state.vscode.isVscode);
const [deviceSecret, setDeviceSecret] = useState<string | undefined>();
const location = useLocation();
const navigate = useNavigate();
const store = useStore<OverallState>();
const searchParams = new URLSearchParams(location.search);
const shouldAddDevice = searchParams.get('add_device');
// Selectors and handlers migrated over from deprecated withRouter implementation
const {
editorTabs,
editorSessionId,
sessionDetails,
stepLimit,
execTime,
isEditorAutorun,
isRunning,
isDebugging,
output,
replValue,
sharedbConnected,
usingSubst,
usingCse,
isFolderModeEnabled,
activeEditorTabIndex,
context: { chapter: playgroundSourceChapter, variant: playgroundSourceVariant },
} = useTypedSelector(state => state.workspaces[workspaceLocation]);
const fileSystem = useTypedSelector(state => state.fileSystem.inBrowserFileSystem);
const { queryString, shortURL, persistenceFile, githubSaveInfo } = useTypedSelector(
state => state.playground,
);
const {
sourceChapter: courseSourceChapter,
sourceVariant: courseSourceVariant,
googleUser: persistenceUser,
githubOctokitObject,
} = useTypedSelector(state => state.session);
const dispatch = useDispatch();
const {
handleChangeExecTime,
handleChapterSelect,
handleEditorValueChange,
handleSetEditorBreakpoints,
handleReplEval,
handleReplOutputClear,
handleUsingSubst,
} = useMemo(() => {
return {
handleChangeExecTime: (execTime: number) =>
dispatch(WorkspaceActions.changeExecTime(execTime, workspaceLocation)),
handleChapterSelect: (chapter: Chapter, variant: Variant) =>
dispatch(WorkspaceActions.chapterSelect(chapter, variant, workspaceLocation)),
handleEditorValueChange: (editorTabIndex: number, newEditorValue: string) =>
dispatch(
WorkspaceActions.updateEditorValue(workspaceLocation, editorTabIndex, newEditorValue),
),
handleSetEditorBreakpoints: (editorTabIndex: number, newBreakpoints: string[]) =>
dispatch(
WorkspaceActions.setEditorBreakpoint(workspaceLocation, editorTabIndex, newBreakpoints),
),
handleReplEval: () => dispatch(WorkspaceActions.evalRepl(workspaceLocation)),
handleReplOutputClear: () => dispatch(WorkspaceActions.clearReplOutput(workspaceLocation)),
handleUsingSubst: (usingSubst: boolean) =>
dispatch(WorkspaceActions.toggleUsingSubst(usingSubst, workspaceLocation)),
};
}, [dispatch, workspaceLocation]);
// Hide search query from URL to maintain an illusion of security. The device secret
// is still exposed via the 'Referer' header when requesting external content (e.g. Google API fonts)
if (shouldAddDevice && !deviceSecret) {
setDeviceSecret(shouldAddDevice);
navigate(location.pathname, { replace: true });
}
const [lastEdit, setLastEdit] = useState(new Date());
const { alerts, selectedTab, setSelectedTab } = useSideContent(
workspaceLocation,
shouldAddDevice ? SideContentType.remoteExecution : SideContentType.introduction,
);
const showStepperPrompt = alerts.includes(SideContentType.substVisualizer);
const hasAnyBreakpoints = useMemo(
() => editorTabs.some(tab => tab.breakpoints.some(Boolean)),
[editorTabs],
);
const [sessionId, setSessionId] = useState(() =>
initSession('playground', {
// TODO: Hardcoded to make use of the first editor tab. Rewrite after editor tabs are added.
editorValue: editorTabs[0]?.value ?? '',
chapter: playgroundSourceChapter,
}),
);
const [users, setUsers] = useState<Record<string, SharedbAceUser>>({});
// Playground hotkeys
const [isGreen, setIsGreen] = useState(false);
const playgroundHotkeyBindings: HotkeyItem[] = useMemo(
() => [['ctrl+alt+h', () => setIsGreen(v => !v)]],
[setIsGreen],
);
useHotkeys(playgroundHotkeyBindings);
useEffect(() => {
CseMachine.clearCachedLayouts();
window.requestAnimationFrame(() => CseMachine.redraw());
}, [isGreen]);
const remoteExecutionTab: SideContentTab = useMemo(
() => makeRemoteExecutionTabFrom(deviceSecret, setDeviceSecret),
[deviceSecret],
);
const sessionManagementTab: SideContentTab = useMemo(() => {
return makeSessionManagementTabFrom(users, editorSessionId, sessionDetails?.readOnly || false);
}, [users, editorSessionId, sessionDetails?.readOnly]);
const usingRemoteExecution =
useTypedSelector(state => !!state.session.remoteExecutionSession) && !isSicpEditor;
// this is still used by remote execution (EV3)
// specifically, for the editor Ctrl+B to work
const externalLibraryName = useTypedSelector(
state => state.workspaces.playground.externalLibrary,
);
useEffect(() => {
// When the editor session Id changes, then treat it as a new session.
setSessionId(
initSession('playground', {
// TODO: Hardcoded to make use of the first editor tab. Rewrite after editor tabs are added.
editorValue: editorTabs[0]?.value ?? '',
chapter: playgroundSourceChapter,
}),
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [editorSessionId]);
const hash = isSicpEditor ? props.initialEditorValueHash : location.hash;
useEffect(() => {
if (!hash) {
// If not a accessing via shared link, use the Source chapter and variant in the current course
if (courseSourceChapter && courseSourceVariant) {
handleChapterSelect(courseSourceChapter, courseSourceVariant);
// TODO: To migrate the state logic away from playgroundSourceChapter
// and playgroundSourceVariant into the language config instead
const languageConfig = getLanguageConfig(courseSourceChapter, courseSourceVariant);
// Hardcoded for Playground only for now, while we await workspace refactoring
// to decouple the SicpWorkspace from the Playground.
dispatch(playgroundConfigLanguage(languageConfig));
// Disable Folder mode when forcing the Source chapter and variant to follow the current course's.
// This is because Folder mode only works in Source 2+.
dispatch(WorkspaceActions.setFolderMode(workspaceLocation, false));
}
return;
}
handleHash(
hash,
{ handleChangeExecTime, handleChapterSelect },
workspaceLocation,
dispatch,
fileSystem,
);
}, [
dispatch,
fileSystem,
hash,
courseSourceChapter,
courseSourceVariant,
workspaceLocation,
handleChapterSelect,
handleChangeExecTime,
]);
/**
* Handles toggling of relevant SideContentTabs when mobile breakpoint it hit
*/
useEffect(() => {
if (!selectedTab) return;
if (!isVscode && isMobileBreakpoint && desktopOnlyTabIds.includes(selectedTab)) {
setSelectedTab(SideContentType.mobileEditor);
} else if (!isMobileBreakpoint && mobileOnlyTabIds.includes(selectedTab)) {
setSelectedTab(SideContentType.introduction);
}
}, [isMobileBreakpoint, isVscode, selectedTab, setSelectedTab]);
const onEditorValueChange = useCallback(
(editorTabIndex: number, newEditorValue: string) => {
setLastEdit(new Date());
handleEditorValueChange(editorTabIndex, newEditorValue);
},
[handleEditorValueChange],
);
useEffect(() => {
// Only the playground is expected to work with VSC for now
if (workspaceLocation === 'sicp') {
return;
}
const initialCode = editorTabs[0]?.value ?? '';
const breakpoints = editorTabs[0]?.breakpoints ?? [];
sendToWebview(
Messages.NewEditor(
workspaceLocation,
'playground',
1,
playgroundSourceChapter,
'',
initialCode,
breakpoints,
),
);
// We don't want to re-send this message even when the variables change
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const pushLog = useCallback(
(newInput: Input) => {
log(sessionId, newInput);
},
[sessionId],
);
const autorunButtonHandlers = useMemo(() => {
return {
handleEditorEval: () => {
const wasCenterAligned = CseMachine.getCenterAlignment();
CseMachine.clearCachedLayouts();
if (wasCenterAligned) {
CseMachine.toggleCenterAlignment();
}
// reset stepper before evaluation
dispatch(WorkspaceActions.updateCurrentStep(-1, workspaceLocation));
dispatch(WorkspaceActions.updateStepsTotal(0, workspaceLocation));
dispatch(WorkspaceActions.toggleUpdateCse(true, workspaceLocation));
if (playgroundSourceChapter <= Chapter.SOURCE_2) {
const shouldUseSubst =
selectedTab === SideContentType.substVisualizer || hasAnyBreakpoints;
handleUsingSubst(shouldUseSubst);
}
dispatch(WorkspaceActions.evalEditor(workspaceLocation));
CseMachine.setClearDeadFrames(false);
if (wasCenterAligned) {
CseMachine.toggleCenterAlignment();
}
},
handleInterruptEval: () =>
dispatch(InterpreterActions.beginInterruptExecution(workspaceLocation)),
handleToggleEditorAutorun: () =>
dispatch(WorkspaceActions.toggleEditorAutorun(workspaceLocation)),
handleDebuggerPause: () => dispatch(InterpreterActions.beginDebuggerPause(workspaceLocation)),
handleDebuggerReset: () => dispatch(InterpreterActions.debuggerReset(workspaceLocation)),
handleDebuggerResume: () => dispatch(InterpreterActions.debuggerResume(workspaceLocation)),
};
}, [
dispatch,
workspaceLocation,
playgroundSourceChapter,
selectedTab,
hasAnyBreakpoints,
handleUsingSubst,
]);
const languageConfig: SALanguage = useTypedSelector(state => state.playground.languageConfig);
const autorunButtons = useMemo(() => {
return (
<ControlBarAutorunButtons
isEntrypointFileDefined={activeEditorTabIndex !== null}
isDebugging={isDebugging}
isEditorAutorun={isEditorAutorun}
isRunning={isRunning}
key="autorun"
autorunDisabled={usingRemoteExecution}
sourceChapter={languageConfig.chapter}
// Disable pause for non-Source languages since they cannot be paused
pauseDisabled={usingRemoteExecution || !isSourceLanguage(languageConfig.chapter)}
{...autorunButtonHandlers}
/>
);
}, [
activeEditorTabIndex,
isDebugging,
isEditorAutorun,
isRunning,
languageConfig.chapter,
autorunButtonHandlers,
usingRemoteExecution,
]);
const chapterSelectHandler = useCallback(
(sublanguage: SALanguage, e: any) => {
const { chapter, variant } = sublanguage;
if ((chapter <= 2 && hasAnyBreakpoints) || selectedTab === SideContentType.substVisualizer) {
handleUsingSubst(true);
}
if (chapter > 2) {
handleReplOutputClear();
handleUsingSubst(false);
}
const input: Input = {
time: Date.now(),
type: 'chapterSelect',
data: chapter,
};
pushLog(input);
sendToWebview(Messages.ChangeChapter('playground', 1, chapter, variant));
handleChapterSelect(chapter, variant);
// Hardcoded for Playground only for now, while we await workspace refactoring
// to decouple the SicpWorkspace from the Playground.
dispatch(playgroundConfigLanguage(sublanguage));
},
[
dispatch,
hasAnyBreakpoints,
selectedTab,
pushLog,
handleReplOutputClear,
handleUsingSubst,
handleChapterSelect,
],
);
const chapterSelectButton = useMemo(
() => (
<ControlBarChapterSelect
handleChapterSelect={chapterSelectHandler}
isFolderModeEnabled={isFolderModeEnabled}
sourceChapter={languageConfig.chapter}
sourceVariant={languageConfig.variant}
key="chapter"
disabled={usingRemoteExecution}
/>
),
[
chapterSelectHandler,
isFolderModeEnabled,
languageConfig.chapter,
languageConfig.variant,
usingRemoteExecution,
],
);
const clearButton = useMemo(
() =>
selectedTab === SideContentType.substVisualizer ? null : (
<ControlBarClearButton handleReplOutputClear={handleReplOutputClear} key="clear_repl" />
),
[handleReplOutputClear, selectedTab],
);
const evalButton = useMemo(
() =>
selectedTab === SideContentType.substVisualizer ? null : (
<ControlBarEvalButton
handleReplEval={handleReplEval}
isRunning={isRunning}
key="eval_repl"
/>
),
[handleReplEval, isRunning, selectedTab],
);
// Compute this here to avoid re-rendering the button every keystroke
const persistenceIsDirty =
persistenceFile && (!persistenceFile.lastSaved || persistenceFile.lastSaved < lastEdit);
const persistenceButtons = useMemo(() => {
return (
<ControlBarGoogleDriveButtons
isFolderModeEnabled={isFolderModeEnabled}
currentFile={persistenceFile}
loggedInAs={persistenceUser}
isDirty={persistenceIsDirty}
key="googledrive"
onClickSaveAs={() => dispatch(PersistenceActions.persistenceSaveFileAs())}
onClickOpen={() => dispatch(PersistenceActions.persistenceOpenPicker())}
onClickSave={
persistenceFile
? () => dispatch(PersistenceActions.persistenceSaveFile(persistenceFile))
: undefined
}
onClickLogOut={() => dispatch(SessionActions.logoutGoogle())}
onPopoverOpening={() => dispatch(PersistenceActions.persistenceInitialise())}
/>
);
}, [isFolderModeEnabled, persistenceFile, persistenceUser, persistenceIsDirty, dispatch]);
const githubPersistenceIsDirty =
githubSaveInfo && (!githubSaveInfo.lastSaved || githubSaveInfo.lastSaved < lastEdit);
const githubButtons = useMemo(() => {
return (
<ControlBarGitHubButtons
key="github"
isFolderModeEnabled={isFolderModeEnabled}
loggedInAs={githubOctokitObject.octokit}
githubSaveInfo={githubSaveInfo}
isDirty={githubPersistenceIsDirty}
onClickOpen={() => dispatch(GithubActions.githubOpenFile())}
onClickSaveAs={() => dispatch(GithubActions.githubSaveFileAs())}
onClickSave={() => dispatch(GithubActions.githubSaveFile())}
onClickLogIn={() => dispatch(SessionActions.loginGitHub())}
onClickLogOut={() => dispatch(SessionActions.logoutGitHub())}
/>
);
}, [
dispatch,
githubOctokitObject.octokit,
githubPersistenceIsDirty,
githubSaveInfo,
isFolderModeEnabled,
]);
const executionTime = useMemo(
() => (
<ControlBarExecutionTime
execTime={execTime}
handleChangeExecTime={handleChangeExecTime}
key="execution_time"
/>
),
[execTime, handleChangeExecTime],
);
const stepperStepLimit = useMemo(
() => (
<ControlBarStepLimit
stepLimit={stepLimit}
stepSize={usingSubst ? 2 : 1}
handleChangeStepLimit={limit => {
dispatch(WorkspaceActions.changeStepLimit(limit, workspaceLocation));
if (usingCse) {
dispatch(WorkspaceActions.toggleUpdateCse(true, workspaceLocation));
}
}}
handleOnBlurAutoScale={limit => {
if (limit % 2 === 0 || !usingSubst) {
dispatch(WorkspaceActions.changeStepLimit(limit, workspaceLocation));
} else {
dispatch(WorkspaceActions.changeStepLimit(limit + 1, workspaceLocation));
}
if (usingCse) {
dispatch(WorkspaceActions.toggleUpdateCse(true, workspaceLocation));
}
}}
key="step_limit"
/>
),
[dispatch, stepLimit, usingSubst, usingCse, workspaceLocation],
);
const getEditorValue = useCallback(
// TODO: Hardcoded to make use of the first editor tab. Rewrite after editor tabs are added.
() => store.getState().workspaces[workspaceLocation].editorTabs[0].value,
[store, workspaceLocation],
);
const handleSetEditorSessionId = useCallback(
(id: string) => dispatch(setEditorSessionId(workspaceLocation, id)),
[dispatch, workspaceLocation],
);
const handleSetSessionDetails = useCallback(
(details: { docId: string; readOnly: boolean; owner: boolean } | null) =>
dispatch(setSessionDetails(workspaceLocation, details)),
[dispatch, workspaceLocation],
);
const sessionButtons = useMemo(
() => (
<ControlBarSessionButtons
isFolderModeEnabled={isFolderModeEnabled}
editorSessionId={editorSessionId}
getEditorValue={getEditorValue}
handleSetEditorSessionId={handleSetEditorSessionId}
handleSetSessionDetails={handleSetSessionDetails}
sharedbConnected={sharedbConnected}
key="session"
/>
),
[
isFolderModeEnabled,
editorSessionId,
getEditorValue,
handleSetEditorSessionId,
handleSetSessionDetails,
sharedbConnected,
],
);
const shareButton = useMemo(() => {
const qs = isSicpEditor ? Links.playground + '#' + props.initialEditorValueHash : queryString;
return (
<ControlBarShareButton
handleGenerateLz={() => dispatch(generateLzString())}
handleShortenURL={s => dispatch(shortenURL(s))}
handleUpdateShortURL={s => dispatch(updateShortURL(s))}
queryString={qs}
shortURL={shortURL}
isSicp={isSicpEditor}
key="share"
/>
);
}, [dispatch, isSicpEditor, props.initialEditorValueHash, queryString, shortURL]);
const toggleFolderModeButton = useMemo(() => {
return (
<ControlBarToggleFolderModeButton
isFolderModeEnabled={isFolderModeEnabled}
isSessionActive={editorSessionId !== ''}
isPersistenceActive={persistenceFile !== undefined || githubSaveInfo.repoName !== ''}
toggleFolderMode={() => dispatch(WorkspaceActions.toggleFolderMode(workspaceLocation))}
key="folder"
/>
);
}, [
dispatch,
githubSaveInfo.repoName,
isFolderModeEnabled,
persistenceFile,
editorSessionId,
workspaceLocation,
]);
useEffect(() => {
// TODO: To migrate the state logic away from playgroundSourceChapter
// and playgroundSourceVariant into the language config instead
const languageConfigToSet = getLanguageConfig(playgroundSourceChapter, playgroundSourceVariant);
// Hardcoded for Playground only for now, while we await workspace refactoring
// to decouple the SicpWorkspace from the Playground.
dispatch(playgroundConfigLanguage(languageConfigToSet));
}, [dispatch, playgroundSourceChapter, playgroundSourceVariant]);
const shouldShowDataVisualizer = languageConfig.supports.dataVisualizer;
const shouldShowCseMachine = languageConfig.supports.cseMachine;
const shouldShowSubstVisualizer = languageConfig.supports.substVisualizer;
const playgroundIntroductionTab: SideContentTab = useMemo(
() => makeIntroductionTabFrom(generateLanguageIntroduction(languageConfig)),
[languageConfig],
);
const tabs = useMemo(() => {
const tabs: SideContentTab[] = [playgroundIntroductionTab];
const currentLang = languageConfig.chapter;
if (currentLang === Chapter.HTML) {
// For HTML Chapter, HTML Display tab is added only after code is run
if (output.length > 0 && output[0].type === 'result') {
tabs.push(
makeHtmlDisplayTabFrom(
output[0] as ResultOutput,
errorMsg => dispatch(WorkspaceActions.addHtmlConsoleError(errorMsg, workspaceLocation)),
workspaceLocation,
),
);
}
return tabs;
}
if (currentLang === Chapter.FULL_JAVA && process.env.NODE_ENV === 'development') {
tabs.push(
makeUploadTabFrom(files =>
dispatch(WorkspaceActions.uploadFiles(files, workspaceLocation)),
),
);
}
if (!usingRemoteExecution) {
// Don't show the following when using remote execution
if (shouldShowDataVisualizer) {
tabs.push(makeDataVisualizerTabFrom(workspaceLocation));
}
if (shouldShowCseMachine) {
tabs.push(makeCseMachineTabFrom(workspaceLocation));
}
if (shouldShowSubstVisualizer) {
tabs.push(makeSubstVisualizerTabFrom(workspaceLocation, output));
}
}
if (!isSicpEditor && !Constants.playgroundOnly) {
tabs.push(remoteExecutionTab);
if (editorSessionId !== '') {
tabs.push(sessionManagementTab);
}
}
return tabs;
}, [
playgroundIntroductionTab,
languageConfig.chapter,
usingRemoteExecution,
isSicpEditor,
output,
workspaceLocation,
dispatch,
shouldShowDataVisualizer,
shouldShowCseMachine,
shouldShowSubstVisualizer,
remoteExecutionTab,
editorSessionId,
sessionManagementTab,
]);
// Remove Intro and Remote Execution tabs for mobile
const mobileTabs = [...tabs].filter(({ id }) => !(id && desktopOnlyTabIds.includes(id)));
const onLoadMethod = useCallback(
(editor: Ace.Editor) => {
const addFold = () => {
editor.getSession().addFold(' ', new Range(1, 0, props.prependLength!, 0));
editor.renderer.off('afterRender', addFold);
};
editor.renderer.on('afterRender', addFold);
},
[props.prependLength],
);
const onChangeMethod = useCallback(
(newCode: string, delta: CodeDelta) => {
const input: Input = {
time: Date.now(),
type: 'codeDelta',
data: delta,
};
pushLog(input);
dispatch(WorkspaceActions.toggleUpdateCse(true, workspaceLocation));
dispatch(WorkspaceActions.setEditorHighlightedLines(workspaceLocation, 0, []));
},
[pushLog, dispatch, workspaceLocation],
);
const onCursorChangeMethod = useCallback(
(selection: any) => {
const input: Input = {
time: Date.now(),
type: 'cursorPositionChange',
data: selection.getCursor(),
};
pushLog(input);
},
[pushLog],
);
const onSelectionChangeMethod = useCallback(
(selection: any) => {
const range: SelectionRange = selection.getRange();
const isBackwards: boolean = selection.isBackwards();
if (!isEqual(range.start, range.end)) {
const input: Input = {
time: Date.now(),
type: 'selectionRangeData',
data: { range, isBackwards },
};
pushLog(input);
}
},
[pushLog],
);
const handleEditorUpdateBreakpoints = useCallback(
(editorTabIndex: number, breakpoints: string[]) => {
const hasBreakpointsInTab = breakpoints.some(Boolean);
const hasAnyBreakpointsAfterUpdate = editorTabs.some((tab, index) =>
index === editorTabIndex ? hasBreakpointsInTab : tab.breakpoints.some(Boolean),
);
if (hasAnyBreakpointsAfterUpdate && playgroundSourceChapter <= Chapter.SOURCE_2) {
handleUsingSubst(true);
}
if (!hasAnyBreakpointsAfterUpdate && selectedTab !== SideContentType.substVisualizer) {
handleReplOutputClear();
handleUsingSubst(false);
}
handleSetEditorBreakpoints(editorTabIndex, breakpoints);
dispatch(WorkspaceActions.toggleUpdateCse(true, workspaceLocation));
},
[
editorTabs,
selectedTab,
dispatch,
workspaceLocation,
handleSetEditorBreakpoints,
handleReplOutputClear,
handleUsingSubst,
playgroundSourceChapter,
],
);
const replDisabled = !languageConfig.supports.repl || usingRemoteExecution;
const editorContainerHandlers = useMemo(() => {
return {
handleDeclarationNavigate: (cursorPosition: Position) =>
dispatch(WorkspaceActions.navigateToDeclaration(workspaceLocation, cursorPosition)),
handlePromptAutocomplete: (row: number, col: number, callback: any) =>
dispatch(WorkspaceActions.promptAutocomplete(workspaceLocation, row, col, callback)),
handleSendReplInputToOutput: (code: string) =>
dispatch(WorkspaceActions.sendReplInputToOutput(code, workspaceLocation)),
handleSetSharedbConnected: (connected: boolean) =>
dispatch(setSharedbConnected(workspaceLocation, connected)),
setActiveEditorTabIndex: (activeEditorTabIndex: number | null) =>
dispatch(
WorkspaceActions.updateActiveEditorTabIndex(workspaceLocation, activeEditorTabIndex),
),
removeEditorTabByIndex: (editorTabIndex: number) =>
dispatch(WorkspaceActions.removeEditorTab(workspaceLocation, editorTabIndex)),
};
}, [dispatch, workspaceLocation]);
const editorContainerProps: NormalEditorContainerProps = {
editorSessionId,
sessionDetails,
isEditorAutorun,
editorVariant: 'normal',
baseFilePath: WORKSPACE_BASE_PATHS[workspaceLocation],
isFolderModeEnabled,
activeEditorTabIndex,
setActiveEditorTabIndex: editorContainerHandlers.setActiveEditorTabIndex,
removeEditorTabByIndex: editorContainerHandlers.removeEditorTabByIndex,
editorTabs: editorTabs.map(convertEditorTabStateToProps),
handleDeclarationNavigate: editorContainerHandlers.handleDeclarationNavigate,
handleEditorEval: autorunButtonHandlers.handleEditorEval,
handlePromptAutocomplete: editorContainerHandlers.handlePromptAutocomplete,
handleSendReplInputToOutput: editorContainerHandlers.handleSendReplInputToOutput,
handleSetSharedbConnected: editorContainerHandlers.handleSetSharedbConnected,
onChange: onChangeMethod,
onCursorChange: onCursorChangeMethod,
onSelectionChange: onSelectionChangeMethod,
onLoad: isSicpEditor && props.prependLength ? onLoadMethod : undefined,
sourceChapter: languageConfig.chapter,
externalLibraryName,
sourceVariant: languageConfig.variant,
handleEditorValueChange: onEditorValueChange,
handleEditorUpdateBreakpoints: handleEditorUpdateBreakpoints,
setUsers,
updateLanguageCallback: chapterSelectHandler,
};
const replHandlers = useMemo(() => {
return {
handleBrowseHistoryDown: () =>
dispatch(WorkspaceActions.browseReplHistoryDown(workspaceLocation)),
handleBrowseHistoryUp: () =>
dispatch(WorkspaceActions.browseReplHistoryUp(workspaceLocation)),
handleReplValueChange: (newValue: string) =>
dispatch(WorkspaceActions.updateReplValue(newValue, workspaceLocation)),
};
}, [dispatch, workspaceLocation]);
const replProps = {
output,
replValue,
handleReplEval,
usingSubst,
showStepperPrompt,
handleBrowseHistoryDown: replHandlers.handleBrowseHistoryDown,
handleBrowseHistoryUp: replHandlers.handleBrowseHistoryUp,
handleReplValueChange: replHandlers.handleReplValueChange,
sourceChapter: languageConfig.chapter,
sourceVariant: languageConfig.variant,
externalLibrary: ExternalLibraryName.NONE, // temporary placeholder as we phase out libraries
hidden:
selectedTab === SideContentType.substVisualizer || selectedTab === SideContentType.cseMachine,
inputHidden: replDisabled,
replButtons: [replDisabled ? null : evalButton, clearButton],
disableScrolling: isSicpEditor,
};
const sideBarProps: { tabs: SideBarTab[] } = useMemo(() => {
// The sidebar is rendered if and only if there is at least one tab present.
// Because whether the sidebar is rendered or not affects the sidebar resizing
// logic, we cannot defer the decision on which sidebar tabs should be rendered
// to the sidebar as it would be too late - the sidebar resizing logic in the
// workspace would not be able to act on that information. Instead, we need to
// determine which sidebar tabs should be rendered here.
return {
tabs: [
...(isFolderModeEnabled
? [
{
label: 'Folder',
body: (
<FileSystemView
workspaceLocation="playground"
basePath={WORKSPACE_BASE_PATHS[workspaceLocation]}
/>
),
iconName: IconNames.FOLDER_CLOSE,
id: SideContentType.folder,