-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathExampleSimpleEditor.tsx
More file actions
288 lines (242 loc) · 7.46 KB
/
ExampleSimpleEditor.tsx
File metadata and controls
288 lines (242 loc) · 7.46 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
import type { EditorDocument, EditorUpdate, ScrollPosition } from '@tutorialkit/react/core';
import CodeMirrorEditor from '@tutorialkit/react/core/CodeMirrorEditor';
import FileTree from '@tutorialkit/react/core/FileTree';
import type { FileSystemTree, DirectoryNode } from '@webcontainer/api';
import type { Terminal as XTerm } from '@xterm/xterm';
import { Suspense, lazy, useEffect, useState } from 'react';
import { useTheme } from './hooks/useTheme';
import { useWebContainer } from './hooks/useWebcontainer';
const Terminal = lazy(() => import('@tutorialkit/react/core/Terminal'));
export default function ExampleSimpleEditor() {
const [domLoaded, setDomLoaded] = useState(false);
const theme = useTheme();
const { setTerminal, previewSrc, document, files, onChange, onScroll, selectedFile, setSelectedFile } =
useSimpleEditor();
useEffect(() => {
setDomLoaded(true);
}, []);
return (
<div className="mt-4 h-120 flex flex-col not-content react-example border border-[var(--ec-brdCol)] border-solid rounded overflow-hidden">
<div className="flex h-1/2">
<FileTree
className="w-1/4 flex-shrink-0 text-sm"
files={files}
hideRoot
selectedFile={selectedFile}
onFileSelect={setSelectedFile}
/>
<div className="w-px flex-shrink-0 h-full bg-[var(--ec-brdCol)]" />
<div className="flex-grow h-full max-w-[calc(75%-1px)] relative bg-[var(--cm-backgroundColor)]">
<CodeMirrorEditor
theme={theme}
doc={document}
onChange={onChange}
onScroll={onScroll}
className="h-full text-[13px]"
/>
<div className="absolute bottom-0 right-0 w-4 h-4 bg-[var(--cm-backgroundColor)]" />
</div>
</div>
<div className="h-px bg-[var(--ec-brdCol)]" />
<div className="flex p-0 m-0 h-1/2">
<div className="w-1/2 h-full">
{domLoaded && (
<Suspense>
<Terminal className="h-full" readonly={false} theme={theme} onTerminalReady={setTerminal} />
</Suspense>
)}
</div>
<div className="w-px flex-shrink-0 h-full bg-[var(--ec-brdCol)]" />
<div className="w-1/2 h-full">
<iframe className="bg-white border-none w-full h-full" src={previewSrc} />
</div>
</div>
</div>
);
}
function useSimpleEditor() {
const webcontainerPromise = useWebContainer();
const [terminal, setTerminal] = useState<XTerm | null>(null);
const [selectedFile, setSelectedFile] = useState('/src/index.js');
const [documents, setDocuments] = useState<Record<string, EditorDocument>>(FILES);
const [previewSrc, setPreviewSrc] = useState<string>('');
const document = documents[selectedFile];
async function onChange({ content }: EditorUpdate) {
setDocuments((prevDocuments) => ({
...prevDocuments,
[selectedFile]: {
...prevDocuments[selectedFile],
value: content,
},
}));
const webcontainer = await webcontainerPromise;
await webcontainer.fs.writeFile(selectedFile, content);
}
function onScroll(scroll: ScrollPosition) {
setDocuments((prevDocuments) => ({
...prevDocuments,
[selectedFile]: {
...prevDocuments[selectedFile],
scroll,
},
}));
}
useEffect(() => {
(async () => {
const webcontainer = await webcontainerPromise;
webcontainer.on('server-ready', (_port, url) => {
setPreviewSrc(url);
});
await webcontainer.mount(toFileTree(FILES));
})();
}, []);
useEffect(() => {
if (!terminal) {
return;
}
run(terminal);
async function run(terminal: XTerm) {
const webcontainer = await webcontainerPromise;
const process = await webcontainer.spawn('jsh', ['--osc'], {
terminal: {
cols: terminal.cols,
rows: terminal.rows,
},
});
let isInteractive = false;
let resolveReady!: () => void;
const jshReady = new Promise<void>((resolve) => {
resolveReady = resolve;
});
process.output.pipeTo(
new WritableStream({
write(data) {
if (!isInteractive) {
const [, osc] = data.match(/\x1b\]654;([^\x07]+)\x07/) || [];
if (osc === 'interactive') {
// wait until we see the interactive OSC
isInteractive = true;
resolveReady();
}
}
terminal.write(data);
},
}),
);
const shellWriter = process.input.getWriter();
terminal.onData((data) => {
if (isInteractive) {
shellWriter.write(data);
}
});
await jshReady;
shellWriter.write('npm install && npm start\n');
}
}, [terminal]);
return {
setTerminal,
previewSrc,
selectedFile,
setSelectedFile,
onChange,
onScroll,
document,
files: FILE_PATHS,
};
}
const FILES: Record<string, EditorDocument> = {
'/src/index.js': {
filePath: '/src/index.js',
loading: false,
value: stripIndent(`
document.body.innerHTML = '<h1>Hello, world!</h1>';
`),
},
'/src/index.html': {
filePath: '/src/index.html',
loading: false,
value: stripIndent(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello, world!</title>
</head>
<body>
<script src="./index.js"></script>
</body>
</html>
`),
},
'/src/assets/logo.svg': {
filePath: '/src/assets/logo.svg',
loading: false,
value: stripIndent(`
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<rect width="24" height="24" rx="15" />
</svg>
`),
},
'/package.json': {
filePath: '/package.json',
loading: false,
value: stripIndent(`
{
"name": "hello-world",
"version": "1.0.0",
"description": "Hello, world!",
"main": "index.js",
"scripts": {
"start": "servor src/ --reload"
},
"dependencies": {
"servor": "4.0.2"
}
}
`),
},
};
const FILE_PATHS = Object.keys(FILES).map((path) => ({ path, type: 'file' }) as const);
function stripIndent(string: string) {
const indent = minIndent(string.slice(1));
if (indent === 0) {
return string;
}
const regex = new RegExp(`^[ \\t]{${indent}}`, 'gm');
return string.replace(regex, '').trim();
}
function minIndent(string: string) {
const match = string.match(/^[ \t]*(?=\S)/gm);
if (!match) {
return 0;
}
return match.reduce((acc, curr) => Math.min(acc, curr.length), Infinity);
}
export function toFileTree(files: Record<string, EditorDocument>): FileSystemTree {
const root: FileSystemTree = {};
for (const filePath in files) {
const segments = filePath.split('/').filter((segment) => segment);
let currentTree: FileSystemTree = root;
for (let i = 0; i < segments.length; ++i) {
const name = segments[i];
if (i === segments.length - 1) {
currentTree[name] = {
file: {
contents: files[filePath].value,
},
};
} else {
let folder = currentTree[name] as DirectoryNode;
if (!folder) {
folder = {
directory: {},
};
currentTree[name] = folder;
}
currentTree = folder.directory;
}
}
}
return root;
}