-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathPlayground.tsx
More file actions
217 lines (194 loc) · 6.15 KB
/
Playground.tsx
File metadata and controls
217 lines (194 loc) · 6.15 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
import {
Classes,
Intent,
OverlayToaster,
type ToastProps
} from '@blueprintjs/core';
import classNames from 'classnames';
import {
SourceDocumentation,
getNames,
runInContext,
type Context
} from 'js-slang';
// Importing this straight from js-slang doesn't work for whatever reason
import createContext from 'js-slang/dist/createContext';
import { Chapter, Variant } from 'js-slang/dist/types';
import { stringify } from 'js-slang/dist/utils/stringify';
import React, { useCallback } from 'react';
import { HotKeys } from 'react-hotkeys';
import mockModuleContext from '../mockModuleContext';
import type { InterpreterOutput } from '../types';
import Workspace, { type WorkspaceProps } from './Workspace';
import { ControlBarClearButton } from './controlBar/ControlBarClearButton';
import { ControlBarRefreshButton } from './controlBar/ControlBarRefreshButton';
import { ControlBarRunButton } from './controlBar/ControlBarRunButton';
import testTabContent from './sideContent/TestTab';
import type { SideContentTab } from './sideContent/types';
import { getDynamicTabs } from './sideContent/utils';
const refreshSuccessToast: ToastProps = {
intent: Intent.SUCCESS,
message: 'Refresh Successful!'
};
const errorToast: ToastProps = {
intent: Intent.DANGER,
message: 'An error occurred!'
};
const evalSuccessToast: ToastProps = {
intent: Intent.SUCCESS,
message: 'Code evaluated successfully!'
};
const createContextHelper = () => {
const tempContext = createContext(Chapter.SOURCE_4, Variant.DEFAULT);
return tempContext;
};
const Playground: React.FC<{}> = () => {
const [dynamicTabs, setDynamicTabs] = React.useState<SideContentTab[]>([]);
const [selectedTabId, setSelectedTab] = React.useState(testTabContent.id);
const [codeContext, setCodeContext] = React.useState<Context>(
createContextHelper()
);
const [editorValue, setEditorValue] = React.useState(
localStorage.getItem('editorValue') ?? ''
);
const [replOutput, setReplOutput] = React.useState<InterpreterOutput | null>(
null
);
const [alerts, setAlerts] = React.useState<string[]>([]);
const toaster = React.useRef<OverlayToaster>(null);
const showToast = (props: ToastProps) => {
if (toaster.current) {
toaster.current.show({
...props,
timeout: 1500
});
}
};
const getAutoComplete = useCallback(
(row: number, col: number, callback: any) => {
getNames(editorValue, row, col, codeContext).then(
([editorNames, displaySuggestions]) => {
if (!displaySuggestions) {
callback();
return;
}
const editorSuggestions = editorNames.map((editorName: any) => ({
...editorName,
caption: editorName.name,
value: editorName.name,
score: editorName.score ? editorName.score + 1000 : 1000,
name: undefined
}));
const builtins: Record<string, any> =
SourceDocumentation.builtins[Chapter.SOURCE_4];
const builtinSuggestions = Object.entries(builtins).map(
([builtin, thing]) => ({
...thing,
caption: builtin,
value: builtin,
score: 100,
name: builtin,
docHTML: thing.description
})
);
callback(null, [...builtinSuggestions, ...editorSuggestions]);
}
);
},
[editorValue, codeContext]
);
const loadTabs = () =>
getDynamicTabs(codeContext)
.then((tabs) => {
setDynamicTabs(tabs);
const newIds = tabs.map(({ id }) => id);
// If the currently selected tab no longer exists,
// switch to the default test tab
if (!newIds.includes(selectedTabId)) {
setSelectedTab(testTabContent.id);
}
setAlerts(newIds);
})
.catch((error) => {
showToast(errorToast);
console.log(error);
});
const evalCode = () => {
codeContext.errors = [];
// eslint-disable-next-line no-multi-assign
codeContext.moduleContexts = mockModuleContext.moduleContexts = {};
runInContext(editorValue, codeContext).then((result) => {
if (codeContext.errors.length > 0) {
showToast(errorToast);
} else {
loadTabs().then(() => showToast(evalSuccessToast));
}
// TODO: Add support for console.log?
if (result.status === 'finished') {
setReplOutput({
type: 'result',
// code: editorValue,
consoleLogs: [],
value: stringify(result.value)
});
} else if (result.status === 'error') {
setReplOutput({
type: 'errors',
errors: codeContext.errors,
consoleLogs: []
});
}
});
};
const resetEditor = () => {
setCodeContext(createContextHelper());
setEditorValue('');
localStorage.setItem('editorValue', '');
setDynamicTabs([]);
setSelectedTab(testTabContent.id);
setReplOutput(null);
};
const onRefresh = () => {
loadTabs()
.then(() => showToast(refreshSuccessToast))
.catch(() => showToast(errorToast));
};
const workspaceProps: WorkspaceProps = {
controlBarProps: {
editorButtons: [
<ControlBarRunButton handleEditorEval={evalCode} key="eval" />,
<ControlBarClearButton onClick={resetEditor} key="clear" />,
<ControlBarRefreshButton onClick={onRefresh} key="refresh" />
]
},
replProps: {
output: replOutput
},
handlePromptAutocomplete: getAutoComplete,
handleEditorEval: evalCode,
handleEditorValueChange(newValue) {
setEditorValue(newValue);
localStorage.setItem('editorValue', newValue);
},
editorValue,
sideContentProps: {
dynamicTabs: [testTabContent, ...dynamicTabs],
selectedTabId,
onChange: useCallback(
(newId: string) => {
setSelectedTab(newId);
setAlerts(alerts.filter((id) => id !== newId));
},
[alerts]
),
alerts
}
};
return (
<HotKeys className={classNames('Playground', Classes.DARK)}>
<OverlayToaster ref={toaster} />
<Workspace {...workspaceProps} />
</HotKeys>
);
};
export default Playground;