-
Notifications
You must be signed in to change notification settings - Fork 330
/
Sandpack.tsx
376 lines (333 loc) · 10.6 KB
/
Sandpack.tsx
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
/* eslint-disable @typescript-eslint/ban-ts-comment */
import * as React from "react";
import type { CodeEditorProps } from "../components/CodeEditor";
import { SandpackCodeEditor } from "../components/CodeEditor";
import { SandpackConsole } from "../components/Console";
import { SandpackPreview } from "../components/Preview";
import { SandpackTests } from "../components/Tests";
import { SandpackStack } from "../components/common";
import { SandpackLayout } from "../components/common/Layout";
import { RoundedButton } from "../components/common/RoundedButton";
import { ConsoleIcon } from "../components/icons";
import { SandpackProvider } from "../contexts/sandpackContext";
import { css, THEME_PREFIX } from "../styles";
import { SANDBOX_TEMPLATES } from "../templates";
import type {
SandpackInternal,
SandpackInternalOptions,
TemplateFiles,
SandpackFiles,
SandpackPredefinedTemplate,
} from "../types";
import { useClassNames } from "../utils/classNames";
export const Sandpack: SandpackInternal = ({
options,
template,
customSetup,
files,
theme,
...props
}) => {
options ??= {};
options.resizablePanels ??= true;
options.editorWidthPercentage ??= 50;
options.showConsole ??= false;
const rtlLayout = options?.rtl ?? false;
const codeEditorOptions: CodeEditorProps = {
showTabs: options.showTabs,
showLineNumbers: options.showLineNumbers,
showInlineErrors: options.showInlineErrors,
wrapContent: options.wrapContent,
closableTabs: options.closableTabs,
initMode: options.initMode,
extensions: options.codeEditor?.extensions,
extensionsKeymap: options.codeEditor?.extensionsKeymap,
readOnly: options.readOnly,
showReadOnly: options.showReadOnly,
additionalLanguages: options.codeEditor?.additionalLanguages,
};
const providerOptions: SandpackInternalOptions<
SandpackFiles,
SandpackPredefinedTemplate
> = {
/**
* TS-why: Type 'string | number | symbol' is not assignable to type 'string'
*/
activeFile: options.activeFile as unknown as string,
visibleFiles: options.visibleFiles as unknown as string[],
recompileMode: options.recompileMode,
recompileDelay: options.recompileDelay,
autorun: options.autorun,
autoReload: options.autoReload,
bundlerURL: options.bundlerURL,
startRoute: options.startRoute,
skipEval: options.skipEval,
fileResolver: options.fileResolver,
initMode: options.initMode,
initModeObserverOptions: options.initModeObserverOptions,
externalResources: options.externalResources,
logLevel: options.logLevel,
classes: options.classes,
experimental_enableServiceWorker: options.experimental_enableServiceWorker,
experimental_enableStableServiceWorkerId:
options.experimental_enableStableServiceWorkerId,
};
/**
* Console
*/
const [consoleVisibility, setConsoleVisibility] = React.useState(
options.showConsole
);
const [counter, setCounter] = React.useState(0);
const hasRightColumn = options.showConsole || options.showConsoleButton;
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
const templateFiles = SANDBOX_TEMPLATES[template!] ?? {};
const mode = (
options?.layout
? options?.layout
: "mode" in templateFiles
? templateFiles.mode
: "preview"
) as typeof options.layout;
const actionsChildren = options.showConsoleButton ? (
<ConsoleCounterButton
counter={counter}
onClick={(): void => setConsoleVisibility((prev) => !prev)}
/>
) : undefined;
/**
* Resizable
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
const dragEventTargetRef = React.useRef<any>(null);
const [horizontalSize, setHorizontalSize] = React.useState(
options.editorWidthPercentage
);
const [verticalSize, setVerticalSize] = React.useState(70);
const RightColumn = hasRightColumn ? SandpackStack : React.Fragment;
const rightColumnStyle = {
flexGrow: 100 - horizontalSize,
flexShrink: 100 - horizontalSize,
flexBasis: 0,
width: 100 - horizontalSize + "%",
gap: consoleVisibility ? 1 : 0,
height: options.editorHeight, // use the original editor height
};
const topRowStyle = hasRightColumn
? {
flexGrow: verticalSize,
flexShrink: verticalSize,
flexBasis: 0,
overflow: "hidden",
}
: rightColumnStyle;
const onDragMove = (event: MouseEvent): void => {
if (!dragEventTargetRef.current) return;
const container = dragEventTargetRef.current.parentElement as
| HTMLDivElement
| undefined;
if (!container) return;
const direction = dragEventTargetRef.current.dataset.direction as
| "horizontal"
| "vertical";
const isHorizontal = direction === "horizontal";
const { left, top, height, width } = container.getBoundingClientRect();
const offset = isHorizontal
? ((event.clientX - left) / width) * 100
: ((event.clientY - top) / height) * 100;
const boundaries = Math.min(Math.max(offset, 25), 75);
if (isHorizontal) {
setHorizontalSize(rtlLayout ? 100 - boundaries : boundaries);
} else {
setVerticalSize(boundaries);
}
container.querySelectorAll(`.${THEME_PREFIX}-stack`).forEach((item) => {
(item as HTMLDivElement).style.pointerEvents = "none";
});
};
const stopDragging = (): void => {
const container = dragEventTargetRef.current?.parentElement as
| HTMLDivElement
| undefined;
if (!container) return;
container.querySelectorAll(`.${THEME_PREFIX}-stack`).forEach((item) => {
(item as HTMLDivElement).style.pointerEvents = "";
});
dragEventTargetRef.current = null;
};
React.useEffect(() => {
if (!options?.resizablePanels) return;
document.body.addEventListener("mousemove", onDragMove);
document.body.addEventListener("mouseup", stopDragging);
return (): void => {
document.body.removeEventListener("mousemove", onDragMove);
document.body.removeEventListener("mouseup", stopDragging);
};
}, [options]);
React.useEffect(() => {
setConsoleVisibility(options?.showConsole ?? false);
}, [options.showConsole]);
const rightColumnProps = hasRightColumn
? { className: THEME_PREFIX + "-preset-column", style: rightColumnStyle }
: {};
const classNames = useClassNames();
return (
<SandpackProvider
key={template}
customSetup={customSetup}
files={files as TemplateFiles<SandpackPredefinedTemplate>}
options={providerOptions}
template={template}
theme={theme}
{...props}
>
<SandpackLayout
className={
rtlLayout ? classNames("rtl-layout", [rtlLayoutClassName]) : ""
}
>
<SandpackCodeEditor
{...codeEditorOptions}
style={{
height: options.editorHeight, // use the original editor height
flexGrow: horizontalSize,
flexShrink: horizontalSize,
flexBasis: 0,
overflow: "hidden",
}}
/>
{options.resizablePanels && (
<div
className={classNames("resize-handler", [
dragHandler({ direction: "horizontal" }),
])}
data-direction="horizontal"
onMouseDown={(event): void => {
dragEventTargetRef.current = event.target;
}}
style={{
left: `calc(${
rtlLayout ? 100 - horizontalSize : horizontalSize
}% - 5px)`,
}}
/>
)}
{/* @ts-ignore */}
<RightColumn {...rightColumnProps}>
{mode === "preview" && (
<SandpackPreview
actionsChildren={actionsChildren}
showNavigator={options.showNavigator}
showRefreshButton={options.showRefreshButton}
style={topRowStyle}
/>
)}
{mode === "tests" && (
<SandpackTests
actionsChildren={actionsChildren}
style={topRowStyle}
/>
)}
{mode === "console" && (
<SandpackConsole
actionsChildren={actionsChildren}
style={topRowStyle}
standalone
/>
)}
{(options.showConsoleButton || consoleVisibility) && (
<>
{options.resizablePanels && consoleVisibility && (
<div
className={classNames("resize-handler", [
dragHandler({ direction: "vertical" }),
])}
data-direction="vertical"
onMouseDown={(event): void => {
dragEventTargetRef.current = event.target;
}}
style={{ top: `calc(${verticalSize}% - 5px)` }}
/>
)}
<div
className={classNames("console-wrapper", [consoleWrapper])}
style={{
flexGrow: consoleVisibility ? 100 - verticalSize : 0,
flexShrink: consoleVisibility ? 100 - verticalSize : 0,
flexBasis: 0,
}}
>
<SandpackConsole
onLogsChange={(logs): void => setCounter(logs.length)}
showHeader={false}
/>
</div>
</>
)}
</RightColumn>
</SandpackLayout>
</SandpackProvider>
);
};
const dragHandler = css({
position: "absolute",
zIndex: "$top",
variants: {
direction: {
vertical: {
right: 0,
left: 0,
height: 10,
cursor: "ns-resize",
},
horizontal: {
top: 0,
bottom: 0,
width: 10,
cursor: "ew-resize",
},
},
},
"@media screen and (max-width: 768px)": {
display: "none",
},
});
const ConsoleCounterButton: React.FC<{
onClick: () => void;
counter: number;
}> = ({ onClick, counter }) => {
return (
<RoundedButton className={buttonCounter.toString()} onClick={onClick}>
<ConsoleIcon />
{counter > 0 && <strong>{counter}</strong>}
</RoundedButton>
);
};
const buttonCounter = css({
position: "relative",
strong: {
background: "$colors$clickable",
color: "$colors$surface1",
minWidth: 12,
height: 12,
padding: "0 2px",
borderRadius: 12,
fontSize: 8,
lineHeight: "12px",
position: "absolute",
top: 0,
right: 0,
fontWeight: "normal",
},
});
const consoleWrapper = css({
width: "100%",
overflow: "hidden",
});
const rtlLayoutClassName = css({
flexDirection: "row-reverse",
"@media screen and (max-width: 768px)": {
flexFlow: "wrap-reverse !important",
flexDirection: "initial",
},
});