forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.tsx
More file actions
652 lines (570 loc) · 17.1 KB
/
index.tsx
File metadata and controls
652 lines (570 loc) · 17.1 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
import {
actions,
dispatch,
listen,
registerFrame,
resetState,
} from 'codesandbox-api';
import debounce from 'lodash/debounce';
import React from 'react';
import { Spring } from 'react-spring/renderprops.cjs';
import { getModulePath } from '../../sandbox/modules';
import getTemplate from '../../templates';
import { generateFileFromSandbox } from '../../templates/configuration/package-json';
import { Module, Sandbox } from '../../types';
import track from '../../utils/analytics';
import { getSandboxName } from '../../utils/get-sandbox-name';
import { frameUrl, host } from '../../utils/url-generator';
import { Container, Loading, StyledFrame } from './elements';
import Navigator from './Navigator';
import { Settings } from './types';
export type Props = {
sandbox: Sandbox;
privacy?: number;
previewSecret?: string;
settings: Settings;
onInitialized?: (preview: BasePreview) => () => void; // eslint-disable-line no-use-before-define
extraModules?: { [path: string]: { code: string; path: string } };
currentModule?: Module;
initialPath?: string;
url?: string;
isInProjectView?: boolean;
onClearErrors?: () => void;
onAction?: (action: Object) => void;
onOpenNewWindow?: () => void;
onToggleProjectView?: () => void;
isResizing?: boolean;
onResize?: (height: number) => void;
showNavigation?: boolean;
inactive?: boolean;
dragging?: boolean;
hide?: boolean;
noPreview?: boolean;
alignDirection?: 'right' | 'bottom';
delay?: number;
className?: string;
onMount?: (preview: BasePreview) => () => void;
overlayMessage?: string;
/**
* Whether to show a screenshot in the preview as a "placeholder" while loading
* to reduce perceived loading time
*/
showScreenshotOverlay?: boolean;
};
type State = {
frameInitialized: boolean;
url: string;
urlInAddressBar: string;
back: boolean;
forward: boolean;
showScreenshot: boolean;
useFallbackDomain: boolean;
};
const sseDomain = process.env.STAGING_API
? 'codesandbox.stream'
: 'codesandbox.io';
const getSSEUrl = (sandbox?: Sandbox, initialPath: string = '') =>
`https://${sandbox ? `${sandbox.id}.` : ''}sse.${
process.env.NODE_ENV === 'development' || process.env.STAGING
? sseDomain
: host()
}${initialPath}`;
interface IModulesByPath {
[path: string]: { path: string; code: null | string; isBinary?: boolean };
}
class BasePreview extends React.Component<Props, State> {
serverPreview: boolean;
element: HTMLIFrameElement;
onUnmount: () => void;
constructor(props: Props) {
super(props);
// We have new behaviour in the preview for server templates, which are
// templates that are executed in a docker container.
this.serverPreview = getTemplate(props.sandbox.template).isServer;
const initialUrl = this.currentUrl();
this.state = {
frameInitialized: false,
urlInAddressBar: initialUrl,
url: initialUrl,
forward: false,
back: false,
showScreenshot: props.showScreenshotOverlay,
useFallbackDomain: false,
};
// we need a value that doesn't change when receiving `initialPath`
// from the query params, or the iframe will continue to be re-rendered
// when the user navigates the iframe app, which shows the loading screen
this.initialPath = props.initialPath;
if (this.serverPreview) {
setTimeout(() => {
// Remove screenshot after specific time, so the loading container spinner can still show
this.setState({ showScreenshot: false });
}, 100);
} else {
setTimeout(() => {
if (this.state.showScreenshot) {
this.setState({ showScreenshot: false });
}
}, 800);
}
this.listener = listen(this.handleMessage);
if (props.delay) {
this.executeCode = debounce(this.executeCode, 800);
}
(window as any).openNewWindow = this.openNewWindow;
this.testFallbackDomainIfNeeded();
}
UNSAFE_componentWillUpdate(nextProps: Props, nextState: State) {
if (
nextState.frameInitialized !== this.state.frameInitialized &&
nextState.frameInitialized
) {
this.handleRefresh();
}
}
componentDidMount() {
if (this.props.onMount) {
this.onUnmount = this.props.onMount(this);
}
}
/**
* We have a different domain for the preview (currently :id.csb.app), some corporate
* firewalls block calls to these domains. Which is why we ping the domain here, if it
* returns a bad response we fall back to using our main domain (:id.codesandbox.io).
*
* We use a different domain for the preview, since Chrome runs iframes from a different root
* domain in a different process, which means for us that we have a snappier editor
*/
testFallbackDomainIfNeeded = () => {
const TRACKING_NAME = 'Preview - Fallback URL';
const normalUrl = frameUrl(
this.props.sandbox,
this.props.initialPath || ''
);
const fallbackUrl = frameUrl(
this.props.sandbox,
this.props.initialPath || '',
{ useFallbackDomain: true }
);
const setFallbackDomain = () => {
this.setState(
{
useFallbackDomain: true,
urlInAddressBar: frameUrl(
this.props.sandbox,
this.props.initialPath || '',
{ useFallbackDomain: true }
),
},
() => {
requestAnimationFrame(() => {
this.sendUrl();
});
}
);
};
if (!this.props.url && normalUrl !== fallbackUrl) {
fetch(normalUrl, { mode: 'no-cors' })
.then(() => {
// Succeeded
track(TRACKING_NAME, { needed: false });
})
.catch(() => {
// Failed, use fallback
track(TRACKING_NAME, { needed: true });
setFallbackDomain();
});
}
};
currentUrl = () => {
const { url, sandbox } = this.props;
if (url && !url.startsWith('/')) {
// An absolute url is given, just return that
return url;
}
// url may be a relative path (/test), so start with that
const initialPath = url || this.props.initialPath || '';
return this.serverPreview
? getSSEUrl(sandbox, initialPath)
: frameUrl(sandbox, initialPath, {
useFallbackDomain: this.state && this.state.useFallbackDomain,
});
};
static defaultProps = {
showNavigation: true,
delay: true,
};
listener: () => void;
disposeInitializer: () => void;
initialPath: string;
componentWillUnmount() {
if (this.listener) {
this.listener();
}
if (this.disposeInitializer) {
this.disposeInitializer();
}
if (this.onUnmount) {
this.onUnmount();
}
}
componentDidUpdate(prevProps: Props) {
if (prevProps.privacy !== this.props.privacy) {
this.handlePrivacyChange();
}
if (prevProps.sandbox.id !== this.props.sandbox.id) {
this.handleSandboxChange();
}
}
openNewWindow = () => {
if (this.props.onOpenNewWindow) {
this.props.onOpenNewWindow();
}
window.open(this.state.urlInAddressBar, '_blank');
};
sendPreviewSecret = () => {
dispatch({
$type: 'preview-secret',
previewSecret: this.props.previewSecret,
});
};
handlePrivacyChange = () => {
this.sendPreviewSecret();
};
handleSandboxChange = () => {
this.serverPreview = getTemplate(this.props.sandbox.template).isServer;
resetState();
const url = this.currentUrl();
dispatch({ type: 'clear-console' });
if (this.serverPreview) {
setTimeout(() => {
// Remove screenshot after specific time, so the loading container spinner can still show
this.setState({ showScreenshot: false });
}, 800);
}
this.setState(
{
urlInAddressBar: url,
url,
showScreenshot: true,
},
() => this.handleRefresh()
);
};
updateAddressbarUrl() {
const url = this.currentUrl();
this.setState({
urlInAddressBar: url,
});
}
handleDependenciesChange = () => {
this.handleRefresh();
};
handleMessage = (data: any, source: any) => {
if (data && data.codesandbox) {
if (data.type === 'initialized' && source) {
registerFrame(source, this.currentUrl());
if (!this.state.frameInitialized && this.props.onInitialized) {
this.disposeInitializer = this.props.onInitialized(this);
}
this.sendPreviewSecret();
setTimeout(
() => {
// We show a screenshot of the sandbox (if available) on top of the preview if the frame
// hasn't loaded yet
this.setState({ showScreenshot: false });
},
this.serverPreview ? 0 : 600
);
this.executeCodeImmediately(true);
} else {
const { type } = data;
switch (type) {
case 'render': {
this.executeCodeImmediately();
break;
}
case 'urlchange': {
this.commitUrl(data.url, data.back, data.forward);
break;
}
case 'resize': {
if (this.props.onResize) {
this.props.onResize(data.height);
}
break;
}
case 'action': {
if (this.props.onAction) {
this.props.onAction({
...data,
sandboxId: this.props.sandbox.id,
});
}
break;
}
case 'done': {
this.setState({ showScreenshot: false });
break;
}
default: {
break;
}
}
}
}
};
executeCode = () => {
requestAnimationFrame(() => {
this.executeCodeImmediately();
});
};
getRenderedModule = () => {
const { sandbox, currentModule, isInProjectView } = this.props;
return isInProjectView
? '/' + sandbox.entry
: getModulePath(sandbox.modules, sandbox.directories, currentModule.id);
};
getModulesToSend = (): IModulesByPath => {
const modulesObject: IModulesByPath = {};
const { sandbox } = this.props;
sandbox.modules.forEach(m => {
const path = getModulePath(sandbox.modules, sandbox.directories, m.id);
if (path) {
modulesObject[path] = {
path,
code: m.code,
isBinary: m.isBinary,
};
}
});
const extraModules = this.props.extraModules || {};
const modulesToSend = { ...extraModules, ...modulesObject };
if (!modulesToSend['/package.json']) {
modulesToSend['/package.json'] = {
code: generateFileFromSandbox(sandbox),
path: '/package.json',
isBinary: false,
};
}
return modulesToSend;
};
executeCodeImmediately = (
initialRender: boolean = false,
showScreen = true
) => {
// We cancel the existing calls with executeCode to prevent concurrent calls,
// the only reason we do this is because executeCodeImmediately can be called
// directly as well
// @ts-ignore
this.executeCode.cancel();
const { settings } = this.props;
const { sandbox } = this.props;
if (
process.env.NODE_ENV !== 'development' &&
settings.clearConsoleEnabled &&
!this.serverPreview
) {
// @ts-ignore Chrome behaviour
console.clear('__internal__'); // eslint-disable-line no-console
dispatch({ type: 'clear-console' });
}
// Do it here so we can see the dependency fetching screen if needed
this.clearErrors();
if (settings.forceRefresh && !initialRender) {
this.handleRefresh();
} else {
if (!this.props.isInProjectView) {
dispatch({
type: 'evaluate',
command: `history.pushState({}, null, '/')`,
});
}
const modulesToSend = this.getModulesToSend();
if (!this.serverPreview) {
dispatch({
type: 'compile',
version: 3,
entry: this.getRenderedModule(),
modules: modulesToSend,
sandboxId: sandbox.id,
externalResources: sandbox.externalResources,
isModuleView: !this.props.isInProjectView,
template: sandbox.template,
hasActions: Boolean(this.props.onAction),
previewSecret: sandbox.previewSecret,
showScreen,
});
}
}
};
setIframeElement = (el: HTMLIFrameElement) => {
if (el) {
this.element = el;
}
};
clearErrors = () => {
// @ts-ignore
dispatch(actions.error.clear('*', 'browser'));
if (this.props.onClearErrors) {
this.props.onClearErrors();
}
};
updateUrl = (url: string) => {
this.setState({ urlInAddressBar: url });
};
sendUrl = () => {
const { urlInAddressBar } = this.state;
if (this.element) {
this.element.src = urlInAddressBar;
this.setState({
url: urlInAddressBar,
back: false,
forward: false,
});
}
};
handleRefresh = () => {
// Changed this from prioritizing URL. This is to make "smooth forking" work,
// but would expect the addressbar url to decide what is refreshed anyways?
const { urlInAddressBar, url } = this.state;
const urlToSet = urlInAddressBar || url;
if (this.element) {
this.element.src = urlToSet || this.currentUrl();
}
this.setState({
urlInAddressBar: urlToSet,
back: false,
forward: false,
});
};
handleBack = () => {
dispatch({
type: 'urlback',
});
};
handleForward = () => {
dispatch({
type: 'urlforward',
});
};
commitUrl = (url: string, back: boolean, forward: boolean) => {
this.setState({
urlInAddressBar: url,
back,
forward,
});
};
toggleProjectView = () => {
if (this.props.onToggleProjectView) {
this.props.onToggleProjectView();
}
};
render() {
const {
showNavigation,
inactive,
sandbox,
settings,
isInProjectView,
dragging,
hide,
noPreview,
className,
overlayMessage,
} = this.props;
const { urlInAddressBar, back, forward } = this.state;
const url = urlInAddressBar || this.currentUrl();
if (noPreview) {
// Means that preview is open in another tab definitely
return null;
}
// Weird TS typing bug
const AnySpring = Spring as any;
return (
<Container
className={className}
style={{
position: 'relative',
flex: 1,
display: hide ? 'none' : undefined,
}}
>
{showNavigation && (
<Navigator
url={url}
onChange={this.updateUrl}
onConfirm={this.sendUrl}
onBack={back ? this.handleBack : null}
onForward={forward ? this.handleForward : null}
onRefresh={this.handleRefresh}
isProjectView={isInProjectView}
toggleProjectView={
this.props.onToggleProjectView && this.toggleProjectView
}
openNewWindow={this.openNewWindow}
zenMode={settings.zenMode}
/>
)}
{overlayMessage && <Loading>{overlayMessage}</Loading>}
<AnySpring
from={{ opacity: this.props.showScreenshotOverlay ? 0 : 1 }}
to={{
opacity: this.state.showScreenshot ? 0 : 1,
}}
>
{(style: { opacity: number }) => (
<>
<StyledFrame
sandbox="allow-forms allow-scripts allow-same-origin allow-modals allow-popups allow-presentation"
allow="geolocation; microphone; camera;midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
src={this.state.url}
ref={this.setIframeElement}
title={getSandboxName(sandbox)}
id="sandbox-preview"
style={{
...style,
zIndex: 1,
backgroundColor: 'white',
pointerEvents:
dragging || inactive || this.props.isResizing
? 'none'
: 'initial',
}}
/>
{this.props.sandbox.screenshotUrl && style.opacity !== 1 && (
<div
style={{
overflow: 'hidden',
width: '100%',
position: 'absolute',
display: 'flex',
justifyContent: 'center',
left: 0,
right: 0,
bottom: 0,
top: showNavigation ? 35 : 0,
zIndex: 0,
}}
>
<div
style={{
width: '100%',
height: '100%',
filter: `blur(2px)`,
transform: 'scale(1.025, 1.025)',
backgroundImage: `url("${this.props.sandbox.screenshotUrl}")`,
backgroundRepeat: 'no-repeat',
backgroundPositionX: 'center',
}}
/>
</div>
)}
</>
)}
</AnySpring>
</Container>
);
}
}
export default BasePreview;