-
-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathAppViewer.tsx
More file actions
204 lines (174 loc) · 5.5 KB
/
AppViewer.tsx
File metadata and controls
204 lines (174 loc) · 5.5 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
import * as React from 'react';
import { WebContainer } from '@webcontainer/api';
import { Box, CircularProgress, SxProps, Typography, styled } from '@mui/material';
import { Files } from 'create-toolpad-app';
const Root = styled('div')({
width: '100%',
height: '100%',
position: 'relative',
});
const AppFrame = styled('iframe')(({ theme }) => ({
border: `1px solid ${theme.vars.palette.divider}`,
borderRadius: theme.vars.shape.borderRadius,
overflow: 'hidden',
width: '100%',
height: '100%',
}));
function ensureFolder(folders: string[], containingFolder: Record<string, any>) {
if (folders.length <= 0) {
return containingFolder;
}
const [first, ...rest] = folders;
let folder = containingFolder[first];
if (!folder) {
folder = { directory: {} };
containingFolder[first] = folder;
}
return ensureFolder(rest, folder.directory);
}
type WebcontainerFolder = Record<
string,
| { directory: WebcontainerFolder; file?: undefined }
| { directory?: undefined; file: { contents: string } }
>;
// TODO: generate types for create-toolpad-app API
function createWebcontainerFiles(flatFiles: Files): WebcontainerFolder {
const files: WebcontainerFolder = {};
for (const [name, { content }] of flatFiles) {
const segments = name.split('/');
const folders = segments.slice(0, segments.length - 1);
const folder = ensureFolder(folders, files);
const file = segments[segments.length - 1];
folder[file] = { file: { contents: content } };
}
return files;
}
async function installDependencies(instance: WebContainer) {
// Install dependencies
const installProcess = await instance.spawn('npm', ['install', '--force']);
installProcess.output.pipeTo(
new WritableStream({
write(data) {
// eslint-disable-next-line no-console
console.log(data);
},
}),
);
// Wait for install command to exit
return installProcess.exit;
}
export interface AppViewerProps {
sx?: SxProps;
files?: Files;
}
export default function AppViewer({ sx, files = new Map() }: AppViewerProps) {
const frameRef = React.useRef<HTMLIFrameElement>(null);
const webcontainerPromiseRef = React.useRef<Promise<WebContainer> | null>(null);
const [loading, setLoading] = React.useState(true);
const [rebuilding, setRebuilding] = React.useState(false);
const isRebuildingRef = React.useRef(rebuilding);
React.useEffect(() => {
isRebuildingRef.current = rebuilding;
}, [rebuilding]);
const webcontainerFiles = React.useMemo(() => createWebcontainerFiles(files), [files]);
const bootFilesref = React.useRef(webcontainerFiles);
React.useEffect(() => {
bootFilesref.current = webcontainerFiles;
}, [webcontainerFiles]);
React.useEffect(() => {
if (!frameRef.current) {
throw new Error('Frame not found');
}
const frame = frameRef.current;
const webcontainerPromise = Promise.resolve(webcontainerPromiseRef.current).then(async () =>
WebContainer.boot(),
);
setLoading(true);
webcontainerPromiseRef.current = webcontainerPromise;
webcontainerPromise.then(async (instance) => {
if (webcontainerPromiseRef.current !== webcontainerPromise) {
return;
}
await instance.mount(bootFilesref.current);
const exitCode = await installDependencies(instance);
if (exitCode !== 0) {
throw new Error('Installation failed');
}
// Run `npm run dev` to start the next.js dev server
const devProcess = await instance.spawn('npm', ['run', 'dev']);
devProcess.output.pipeTo(
new WritableStream({
write(data) {
// eslint-disable-next-line no-console
console.log(data);
if (data.includes('Compiled /page')) {
setLoading(false);
}
if (isRebuildingRef.current && data.includes('Compiled in')) {
setRebuilding(false);
}
},
}),
);
// Wait for `server-ready` event
instance.on('server-ready', (port, url) => {
frame.src = `${url}/page`;
});
});
return () => {
if (!webcontainerPromiseRef.current) {
return;
}
webcontainerPromiseRef.current.then((instance) => {
instance.teardown();
});
};
}, []);
const prevFiles = React.useRef(files);
React.useEffect(() => {
const changes = new Map();
for (const [name, { content }] of files) {
if (prevFiles.current.get(name)?.content !== content) {
changes.set(name, { content });
}
}
prevFiles.current = files;
if (changes.size <= 0) {
return;
}
Promise.resolve(webcontainerPromiseRef.current).then(async (instance) => {
if (!instance) {
throw new Error('Instance not found');
}
for (const [name, { content }] of changes) {
instance.fs.writeFile(name, content);
}
setRebuilding(true);
});
}, [files]);
return (
<Root sx={sx}>
{loading || rebuilding ? (
<Box
sx={{
position: 'absolute',
inset: '0 0 0 0',
display: 'flex',
flexDirection: 'column',
gap: 2,
alignItems: 'center',
justifyContent: 'center',
}}
>
<CircularProgress />
<Typography>{'// TODO: show progress. (check the console for now)'}</Typography>
</Box>
) : null}
<AppFrame
ref={frameRef}
title="Application"
style={{ display: 'block', width: '100%', height: '100%' }}
/>
</Root>
);
}