-
Notifications
You must be signed in to change notification settings - Fork 7.9k
Expand file tree
/
Copy pathPreview.tsx
More file actions
231 lines (204 loc) · 7.24 KB
/
Preview.tsx
File metadata and controls
231 lines (204 loc) · 7.24 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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*/
// eslint-disable-next-line react-compiler/react-compiler
/* eslint-disable react-hooks/exhaustive-deps */
import {useRef, useState, useEffect, useMemo, useId} from 'react';
import {useSandpack, SandpackStack} from '@codesandbox/sandpack-react/unstyled';
import cn from 'classnames';
import {ErrorMessage} from './ErrorMessage';
import {SandpackConsole} from './Console';
import type {LintDiagnostic} from './useSandpackLint';
import {CSSProperties} from 'react';
import {LoadingOverlay} from './LoadingOverlay';
type CustomPreviewProps = {
className?: string;
isExpanded: boolean;
lintErrors: LintDiagnostic;
};
function useDebounced(value: any): any {
const ref = useRef<any>(null);
const [saved, setSaved] = useState(value);
useEffect(() => {
clearTimeout(ref.current);
ref.current = setTimeout(() => {
setSaved(value);
}, 300);
}, [value]);
return saved;
}
export function Preview({
isExpanded,
className,
lintErrors,
}: CustomPreviewProps) {
const {sandpack, listen} = useSandpack();
const [bundlerIsReady, setBundlerIsReady] = useState(false);
const [showLoading, setShowLoading] = useState(false);
const [iframeComputedHeight, setComputedAutoHeight] = useState<number | null>(
null
);
let {error: rawError, registerBundler, unregisterBundler} = sandpack;
if (
rawError &&
rawError.message === '_csbRefreshUtils.prelude is not a function'
) {
// Work around a noisy internal error.
rawError = null;
}
// When throwing a new Error in Sandpack - we want to disable the dev error dialog
// to show the Error Boundary fallback
if (rawError && rawError.message.includes('Example Error:')) {
rawError = null;
}
// Memoized because it's fed to debouncing.
const firstLintError = useMemo(() => {
if (lintErrors.length === 0) {
return null;
} else {
const {line, column, message} = lintErrors[0];
return {
title: 'Lint Error',
message: `${line}:${column} - ${message}`,
};
}
}, [lintErrors]);
if (rawError == null || rawError.title === 'Runtime Exception') {
if (firstLintError !== null) {
rawError = firstLintError;
}
}
if (rawError != null && rawError.title === 'Runtime Exception') {
rawError.title = 'Runtime Error';
}
// It changes too fast, causing flicker.
const error = useDebounced(rawError);
const clientId = useId();
const iframeRef = useRef<HTMLIFrameElement | null>(null);
const sandpackIdle = sandpack.status === 'idle';
useEffect(function createBundler() {
const iframeElement = iframeRef.current!;
if (!iframeElement.dataset.registered) {
registerBundler(iframeElement, clientId);
iframeElement.dataset.registered = 'true';
}
return () => {
unregisterBundler(clientId);
iframeElement.dataset.registered = '';
};
}, []);
useEffect(
function bundlerListener() {
let timeout: ReturnType<typeof setTimeout>;
const unsubscribe = listen((message) => {
if (message.type === 'resize') {
setComputedAutoHeight(message.height);
} else if (message.type === 'start') {
if (message.firstLoad) {
setBundlerIsReady(false);
}
/**
* The spinner component transition might be longer than
* the bundler loading, so we only show the spinner if
* it takes more than 500s to load the bundler.
*/
timeout = setTimeout(() => {
setShowLoading(true);
}, 500);
} else if (message.type === 'done') {
setBundlerIsReady(true);
setShowLoading(false);
clearTimeout(timeout);
}
}, clientId);
return () => {
clearTimeout(timeout);
setBundlerIsReady(false);
setComputedAutoHeight(null);
unsubscribe();
};
},
[sandpackIdle]
);
// WARNING:
// The layout and styling here is convoluted and really easy to break.
// If you make changes to it, you need to test different cases:
// - Content -> (compile | runtime) error -> content editing flow should work.
// - Errors should expand parent height rather than scroll.
// - Long sandboxes should scroll unless "show more" is toggled.
// - Expanded sandboxes ("show more") have sticky previews and errors.
// - Sandboxes have autoheight based on content.
// - That autoheight should be measured correctly! (Check some long ones.)
// - You shouldn't see nested scrolls (that means autoheight is borked).
// - Ideally you shouldn't see a blank preview tile while recompiling.
// - Container shouldn't be horizontally scrollable (even while loading).
// - It should work on mobile.
// The best way to test it is to actually go through some challenges.
const hideContent = error || !iframeComputedHeight || !bundlerIsReady;
const iframeWrapperPosition = (): CSSProperties => {
if (hideContent) {
return {position: 'relative'};
}
if (isExpanded) {
return {position: 'sticky', top: 'calc(2em + 64px)'};
}
return {};
};
return (
<SandpackStack className={className}>
<div
className={cn(
'p-0 sm:p-2 md:p-4 lg:p-8 bg-card dark:bg-wash-dark h-full relative md:rounded-b-lg lg:rounded-b-none',
// Allow content to be scrolled if it's too high to fit.
// Note we don't want this in the expanded state
// because it breaks position: sticky (and isn't needed anyway).
!isExpanded && (error || bundlerIsReady) ? 'overflow-auto' : null
)}>
<div style={iframeWrapperPosition()}>
<iframe
ref={iframeRef}
className={cn(
'rounded-t-none bg-white md:shadow-md sm:rounded-lg w-full max-w-full transition-opacity',
// We can't *actually* hide content because that would
// break calculating the computed height in the iframe
// (which we're using for autosizing). This is noticeable
// if you make a compiler error and then fix it with code
// that expands the content. You want to measure that.
hideContent
? 'absolute opacity-0 pointer-events-none duration-75'
: 'opacity-100 duration-150'
)}
title="Sandbox Preview"
style={{
height: iframeComputedHeight || '15px',
zIndex: isExpanded ? 'initial' : -1,
}}
/>
</div>
{error && (
<div
className={cn(
'z-50',
// This isn't absolutely positioned so that
// the errors can also expand the parent height.
isExpanded ? 'sticky top-8 ' : null
)}>
<ErrorMessage error={error} />
</div>
)}
<LoadingOverlay
clientId={clientId}
dependenciesLoading={!bundlerIsReady && iframeComputedHeight === null}
forceLoading={showLoading}
/>
</div>
<SandpackConsole visible={!error} />
</SandpackStack>
);
}