-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathindex.ts
387 lines (295 loc) · 10.3 KB
/
index.ts
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
import type { Files, Lesson } from '@tutorialkit/types';
import type { WebContainer } from '@webcontainer/api';
import { atom, type ReadableAtom } from 'nanostores';
import { LessonFilesFetcher } from '../lesson-files.js';
import { newTask, type Task } from '../tasks.js';
import { TutorialRunner } from '../tutorial-runner.js';
import type { ITerminal } from '../utils/terminal.js';
import { bootStatus, unblockBoot, type BootStatus } from '../webcontainer/on-demand-boot.js';
import type { PreviewInfo } from '../webcontainer/preview-info.js';
import { StepsController } from '../webcontainer/steps.js';
import type { TerminalConfig } from '../webcontainer/terminal-config.js';
import { EditorStore, type EditorDocument, type EditorDocuments, type ScrollPosition } from './editor.js';
import { PreviewsStore } from './previews.js';
import { TerminalStore } from './terminal.js';
interface StoreOptions {
webcontainer: Promise<WebContainer>;
/**
* Whether or not authentication is used for the WebContainer API.
*/
useAuth: boolean;
/**
* The base path to use when fetching files.
*/
basePathname?: string;
}
export class TutorialStore {
private _webcontainer: Promise<WebContainer>;
private _runner: TutorialRunner;
private _previewsStore: PreviewsStore;
private _editorStore: EditorStore;
private _terminalStore: TerminalStore;
private _stepController = new StepsController();
private _lessonFilesFetcher: LessonFilesFetcher;
private _lessonTask: Task<unknown> | undefined;
private _lesson: Lesson | undefined;
private _ref: number = 1;
private _themeRef = atom(1);
/** Files from lesson's `_files` directory */
private _lessonFiles: Files | undefined;
/** Files from lesson's `_solution` directory */
private _lessonSolution: Files | undefined;
/** All files from `template` directory */
private _lessonTemplate: Files | undefined;
/** Files from `template` directory that match `template.visibleFiles` patterns */
private _visibleTemplateFiles: Files | undefined;
/**
* Whether or not the current lesson is fully loaded in WebContainer
* and in every stores.
*/
readonly lessonFullyLoaded = atom<boolean>(false);
constructor({ useAuth, webcontainer, basePathname }: StoreOptions) {
this._webcontainer = webcontainer;
this._editorStore = new EditorStore();
this._lessonFilesFetcher = new LessonFilesFetcher(basePathname);
this._previewsStore = new PreviewsStore(this._webcontainer);
this._terminalStore = new TerminalStore(this._webcontainer, useAuth);
this._runner = new TutorialRunner(this._webcontainer, this._terminalStore, this._stepController);
/**
* By having this code under `import.meta.hot`, it gets:
* - ignored on server side where it shouldn't run
* - discarded when doing a production build
*/
if (import.meta.hot) {
import.meta.hot.on('tk:refresh-wc-files', async (hotFilesRefs: string[]) => {
let shouldUpdate = false;
for (const filesRef of hotFilesRefs) {
const result = await this._lessonFilesFetcher.invalidate(filesRef);
switch (result.type) {
case 'none': {
break;
}
case 'files': {
if (this._lesson?.files[0] === filesRef) {
shouldUpdate = true;
this._lesson.files[1] = Object.keys(result.files).sort();
this._lessonFiles = result.files;
}
break;
}
case 'solution': {
if (this._lesson?.solution[0] === filesRef) {
shouldUpdate = true;
this._lesson.solution[1] = Object.keys(result.files).sort();
this._lessonSolution = result.files;
}
break;
}
case 'template': {
shouldUpdate = true;
this._lessonTemplate = result.files;
break;
}
}
}
if (shouldUpdate && this._lesson) {
this._lessonTask?.cancel();
const files = this._lessonFiles ?? {};
const template = this._lessonTemplate;
this._lessonTask = newTask(
async (signal) => {
const preparePromise = this._runner.prepareFiles({ template, files, signal });
this._runner.runCommands();
this._editorStore.setDocuments(files);
await preparePromise;
},
{ ignoreCancel: true },
);
}
});
}
}
setLesson(lesson: Lesson, options: { ssr?: boolean } = {}) {
if (lesson === this._lesson) {
return;
}
this._lessonTask?.cancel();
this._ref += 1;
this._lesson = lesson;
this.lessonFullyLoaded.set(false);
this._previewsStore.setPreviews(lesson.data.previews ?? true);
this._terminalStore.setTerminalConfiguration(lesson.data.terminal);
this._runner.setCommands(lesson.data);
this._editorStore.setDocuments(lesson.files);
if (options.ssr) {
return;
}
this._lessonTask = newTask(
async (signal) => {
const templatePromise = this._lessonFilesFetcher.getLessonTemplate(lesson);
const filesPromise = this._lessonFilesFetcher.getLessonFiles(lesson);
const preparePromise = this._runner.prepareFiles({ template: templatePromise, files: filesPromise, signal });
this._runner.runCommands();
const [template, solution, files] = await Promise.all([
templatePromise,
this._lessonFilesFetcher.getLessonSolution(lesson),
filesPromise,
]);
signal.throwIfAborted();
this._lessonFiles = files;
this._lessonSolution = solution;
this._lessonTemplate = template;
this._visibleTemplateFiles = pick(template, lesson.files[1]);
const editorFiles = { ...this._visibleTemplateFiles, ...this._lessonFiles };
this._editorStore.setDocuments(editorFiles);
if (lesson.data.focus === undefined) {
this._editorStore.setSelectedFile(undefined);
} else if (editorFiles[lesson.data.focus] !== undefined) {
this._editorStore.setSelectedFile(lesson.data.focus);
}
await preparePromise;
signal.throwIfAborted();
this.lessonFullyLoaded.set(true);
},
{ ignoreCancel: true },
);
}
get previews(): ReadableAtom<PreviewInfo[]> {
return this._previewsStore.previews;
}
get terminalConfig(): ReadableAtom<TerminalConfig> {
return this._terminalStore.terminalConfig;
}
get currentDocument(): ReadableAtom<EditorDocument | undefined> {
return this._editorStore.currentDocument;
}
get bootStatus(): ReadableAtom<BootStatus> {
return bootStatus;
}
get documents(): ReadableAtom<EditorDocuments> {
return this._editorStore.documents;
}
get template(): Files | undefined {
return this._lessonTemplate;
}
get selectedFile(): ReadableAtom<string | undefined> {
return this._editorStore.selectedFile;
}
get lesson(): Readonly<Lesson> | undefined {
return this._lesson;
}
get ref(): unknown {
return this._ref;
}
get themeRef(): ReadableAtom<unknown> {
return this._themeRef;
}
/**
* Steps that the runner is or will be executing.
*/
get steps() {
return this._stepController.steps;
}
hasFileTree(): boolean {
if (!this._lesson) {
return false;
}
const { editor } = this._lesson.data;
return editor === undefined || editor === true || (editor !== false && editor?.fileTree !== false);
}
hasEditor(): boolean {
if (!this._lesson) {
return false;
}
const { editor } = this._lesson.data;
return editor !== false;
}
hasPreviews(): boolean {
if (!this._lesson) {
return false;
}
const { previews } = this._lesson.data;
return previews !== false;
}
hasTerminalPanel(): boolean {
return this._terminalStore.hasTerminalPanel();
}
hasSolution(): boolean {
return !!this._lesson && Object.keys(this._lesson.solution[1]).length >= 1;
}
unblockBoot() {
unblockBoot();
}
reset() {
const isReady = this.lessonFullyLoaded.value;
if (!isReady || !this._lessonFiles) {
return;
}
const files = { ...this._visibleTemplateFiles, ...this._lessonFiles };
this._editorStore.setDocuments(files);
this._runner.updateFiles(files);
}
solve() {
const isReady = this.lessonFullyLoaded.value;
if (!isReady || !this._lessonSolution) {
return;
}
const files = { ...this._visibleTemplateFiles, ...this._lessonFiles, ...this._lessonSolution };
this._editorStore.setDocuments(files);
this._runner.updateFiles(files);
}
setSelectedFile(filePath: string | undefined) {
this._editorStore.setSelectedFile(filePath);
}
updateFile(filePath: string, content: string) {
const hasChanged = this._editorStore.updateFile(filePath, content);
if (hasChanged) {
this._runner.updateFile(filePath, content);
}
}
updateFiles(files: Files) {
this._runner.updateFiles(files);
}
setCurrentDocumentContent(newContent: string) {
const filePath = this.currentDocument.get()?.filePath;
if (!filePath) {
return;
}
this.updateFile(filePath, newContent);
}
setCurrentDocumentScrollPosition(position: ScrollPosition) {
const editorDocument = this.currentDocument.get();
if (!editorDocument) {
return;
}
const { filePath } = editorDocument;
this._editorStore.updateScrollPosition(filePath, position);
}
attachTerminal(id: string, terminal: ITerminal) {
this._terminalStore.attachTerminal(id, terminal);
}
onTerminalResize(cols: number, rows: number) {
if (cols && rows) {
this._terminalStore.onTerminalResize(cols, rows);
this._runner.onTerminalResize(cols, rows);
}
}
onDocumentChanged(filePath: string, callback: (document: Readonly<EditorDocument>) => void) {
return this._editorStore.onDocumentChanged(filePath, callback);
}
refreshStyles() {
this._themeRef.set(this._themeRef.get() + 1);
}
takeSnapshot() {
return this._runner.takeSnapshot();
}
}
function pick<T>(obj: Record<string, T>, entries: string[]) {
const result: Record<string, T> = {};
for (const entry of entries) {
if (entry in obj) {
result[entry] = obj[entry];
}
}
return result;
}