-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathPlayground.tsx
More file actions
543 lines (457 loc) · 13 KB
/
Playground.tsx
File metadata and controls
543 lines (457 loc) · 13 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
import {
ActionDispatch,
Suspense,
useCallback,
useDeferredValue,
useEffect,
useMemo,
useReducer,
useRef,
useState,
} from "react";
import { ErrorMessage, Header, setupMonaco, useTheme } from "shared";
import { FileHandle, Workspace } from "red_knot_wasm";
import { persist, persistLocal, restore } from "./Editor/persist";
import { loader } from "@monaco-editor/react";
import knotSchema from "../../../knot.schema.json";
import Chrome, { formatError } from "./Editor/Chrome";
export const SETTINGS_FILE_NAME = "knot.json";
export default function Playground() {
const [theme, setTheme] = useTheme();
const [version, setVersion] = useState<string>("0.0.0");
const [error, setError] = useState<string | null>(null);
const workspacePromiseRef = useRef<Promise<Workspace> | null>(null);
const [workspace, setWorkspace] = useState<Workspace | null>(null);
let workspacePromise = workspacePromiseRef.current;
if (workspacePromise == null) {
workspacePromiseRef.current = workspacePromise = startPlayground().then(
(fetched) => {
setVersion(fetched.version);
const workspace = new Workspace("/", {});
restoreWorkspace(workspace, fetched.workspace, dispatchFiles, setError);
setWorkspace(workspace);
return workspace;
},
);
}
const [files, dispatchFiles] = useReducer(filesReducer, INIT_FILES_STATE);
const fileName = useMemo(() => {
return (
files.index.find((file) => file.id === files.selected)?.name ?? "lib.py"
);
}, [files.index, files.selected]);
usePersistLocally(files);
const handleShare = useCallback(() => {
const serialized = serializeFiles(files);
if (serialized != null) {
persist(serialized).catch((error) => {
// eslint-disable-next-line no-console
console.error("Failed to share playground", error);
});
}
}, [files]);
const handleFileAdded = (workspace: Workspace, name: string) => {
let handle = null;
if (name === SETTINGS_FILE_NAME) {
updateOptions(workspace, "{}", setError);
} else {
handle = workspace.openFile(name, "");
}
dispatchFiles({ type: "add", name, handle, content: "" });
};
const handleFileChanged = (workspace: Workspace, content: string) => {
if (files.selected == null) {
return;
}
dispatchFiles({
type: "change",
id: files.selected,
content,
});
const handle = files.handles[files.selected];
if (handle != null) {
updateFile(workspace, handle, content, setError);
} else if (fileName === SETTINGS_FILE_NAME) {
updateOptions(workspace, content, setError);
}
};
const handleFileRenamed = (
workspace: Workspace,
file: FileId,
newName: string,
) => {
const handle = files.handles[file];
let newHandle: FileHandle | null = null;
if (handle == null) {
updateOptions(workspace, null, setError);
} else {
workspace.closeFile(handle);
}
if (newName === SETTINGS_FILE_NAME) {
updateOptions(workspace, files.contents[file], setError);
} else {
newHandle = workspace.openFile(newName, files.contents[file]);
}
dispatchFiles({ type: "rename", id: file, to: newName, newHandle });
};
const handleFileRemoved = (workspace: Workspace, file: FileId) => {
const handle = files.handles[file];
if (handle == null) {
updateOptions(workspace, null, setError);
} else {
workspace.closeFile(handle);
}
dispatchFiles({ type: "remove", id: file });
};
const handleFileSelected = useCallback((file: FileId) => {
dispatchFiles({ type: "selectFile", id: file });
}, []);
const handleReset = useCallback(() => {
if (workspace == null) {
return;
}
// Close all open files
for (const file of files.index) {
const handle = files.handles[file.id];
if (handle != null) {
try {
workspace.closeFile(handle);
} catch (e) {
setError(formatError(e));
}
}
}
dispatchFiles({ type: "reset" });
restoreWorkspace(workspace, DEFAULT_WORKSPACE, dispatchFiles, setError);
}, [files.handles, files.index, workspace]);
return (
<main className="flex flex-col h-full bg-ayu-background dark:bg-ayu-background-dark">
<Header
edit={files.revision}
theme={theme}
logo="astral"
version={version}
onChangeTheme={setTheme}
onShare={handleShare}
onReset={workspace == null ? undefined : handleReset}
/>
<Suspense fallback={<Loading />}>
<Chrome
files={files}
workspacePromise={workspacePromise}
theme={theme}
selectedFileName={fileName}
onAddFile={handleFileAdded}
onRenameFile={handleFileRenamed}
onRemoveFile={handleFileRemoved}
onSelectFile={handleFileSelected}
onChangeFile={handleFileChanged}
/>
</Suspense>
{error ? (
<div
style={{
position: "fixed",
left: "10%",
right: "10%",
bottom: "10%",
}}
>
<ErrorMessage>{error}</ErrorMessage>
</div>
) : null}
</main>
);
}
export const DEFAULT_SETTINGS = JSON.stringify(
{
environment: {
"python-version": "3.13",
},
rules: {
"division-by-zero": "error",
},
},
null,
4,
);
const DEFAULT_PROGRAM = `from typing import Literal
type Style = Literal["italic", "bold", "underline"]
# Add parameter annotations \`line: str, word: str, style: Style\` and a return
# type annotation \`-> str\` to see if you can find the mistakes in this program.
def with_style(line, word, style):
if style == "italic":
return line.replace(word, f"*{word}*")
elif style == "bold":
return line.replace(word, f"__{word}__")
position = line.find(word)
output = line + "\\n"
output += " " * position
output += "-" * len(word)
print(with_style("Red Knot is a fast type checker for Python.", "fast", "underlined"))
`;
const DEFAULT_WORKSPACE = {
files: {
"main.py": DEFAULT_PROGRAM,
"knot.json": DEFAULT_SETTINGS,
},
current: "main.py",
};
/**
* Persists the files to local storage. This is done deferred to avoid too frequent writes.
*/
function usePersistLocally(files: FilesState): void {
const deferredFiles = useDeferredValue(files);
useEffect(() => {
const serialized = serializeFiles(deferredFiles);
if (serialized != null) {
persistLocal(serialized);
}
}, [deferredFiles]);
}
export type FileId = number;
export type ReadonlyFiles = Readonly<FilesState>;
interface FilesState {
/**
* The currently selected file that is shown in the editor.
*/
selected: FileId | null;
/**
* The files in display order (ordering is sensitive)
*/
index: ReadonlyArray<{ id: FileId; name: string }>;
/**
* The database file handles by file id.
*
* Files without a file handle are well-known files that are only handled by the
* playground (e.g. knot.json)
*/
handles: Readonly<{ [id: FileId]: FileHandle | null }>;
/**
* The content per file indexed by file id.
*/
contents: Readonly<{ [id: FileId]: string }>;
/**
* The revision. Gets incremented every time files changes.
*/
revision: number;
/**
* Revision identifying this playground. Gets incremented every time the
* playground is reset.
*/
playgroundRevision: number;
nextId: FileId;
}
export type FileAction =
| {
type: "add";
handle: FileHandle | null;
/// The file name
name: string;
content: string;
}
| {
type: "change";
id: FileId;
content: string;
}
| { type: "rename"; id: FileId; to: string; newHandle: FileHandle | null }
| {
type: "remove";
id: FileId;
}
| { type: "selectFile"; id: FileId }
| { type: "selectFileByName"; name: string }
| { type: "reset" };
const INIT_FILES_STATE: ReadonlyFiles = {
index: [],
contents: Object.create(null),
handles: Object.create(null),
nextId: 0,
revision: 0,
selected: null,
playgroundRevision: 0,
};
function filesReducer(
state: Readonly<FilesState>,
action: FileAction,
): FilesState {
switch (action.type) {
case "add": {
const { handle, name, content } = action;
const id = state.nextId;
return {
...state,
selected: id,
index: [...state.index, { id, name }],
handles: { ...state.handles, [id]: handle },
contents: { ...state.contents, [id]: content },
nextId: state.nextId + 1,
revision: state.revision + 1,
};
}
case "change": {
const { id, content } = action;
return {
...state,
contents: { ...state.contents, [id]: content },
revision: state.revision + 1,
};
}
case "remove": {
const { id } = action;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { [id]: _content, ...contents } = state.contents;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { [id]: _handle, ...handles } = state.handles;
let selected = state.selected;
if (state.selected === id) {
const index = state.index.findIndex((file) => file.id === id);
selected =
index > 0 ? state.index[index - 1].id : state.index[index + 1].id;
}
return {
...state,
selected,
index: state.index.filter((file) => file.id !== id),
contents,
handles,
revision: state.revision + 1,
};
}
case "rename": {
const { id, to, newHandle } = action;
const index = state.index.findIndex((file) => file.id === id);
const newIndex = [...state.index];
newIndex.splice(index, 1, { id, name: to });
return {
...state,
index: newIndex,
handles: { ...state.handles, [id]: newHandle },
};
}
case "selectFile": {
const { id } = action;
return {
...state,
selected: id,
};
}
case "selectFileByName": {
const { name } = action;
const selected =
state.index.find((file) => file.name === name)?.id ?? null;
return {
...state,
selected,
};
}
case "reset": {
return {
...INIT_FILES_STATE,
playgroundRevision: state.playgroundRevision + 1,
revision: state.revision + 1,
};
}
}
}
function serializeFiles(files: FilesState): {
files: { [name: string]: string };
current: string;
} | null {
const serializedFiles = Object.create(null);
let selected = null;
for (const { id, name } of files.index) {
serializedFiles[name] = files.contents[id];
if (files.selected === id) {
selected = name;
}
}
if (selected == null) {
return null;
}
return { files: serializedFiles, current: selected };
}
export interface InitializedPlayground {
version: string;
workspace: { files: { [name: string]: string }; current: string };
}
// Run once during startup. Initializes monaco, loads the wasm file, and restores the previous editor state.
async function startPlayground(): Promise<InitializedPlayground> {
const red_knot = await import("../red_knot_wasm");
await red_knot.default();
const monaco = await loader.init();
setupMonaco(monaco, {
uri: "https://raw.githubusercontent.com/astral-sh/ruff/main/knot.schema.json",
fileMatch: ["knot.json"],
schema: knotSchema,
});
const restored = await restore();
const workspace = restored ?? DEFAULT_WORKSPACE;
return {
version: "0.0.0",
workspace,
};
}
function updateOptions(
workspace: Workspace | null,
content: string | null,
setError: (error: string | null) => void,
) {
content = content ?? DEFAULT_SETTINGS;
try {
const settings = JSON.parse(content);
workspace?.updateOptions(settings);
setError(null);
} catch (error) {
setError(`Failed to update 'knot.json' options: ${formatError(error)}`);
}
}
function updateFile(
workspace: Workspace,
handle: FileHandle,
content: string,
setError: (error: string | null) => void,
) {
try {
workspace.updateFile(handle, content);
setError(null);
} catch (error) {
setError(`Failed to update file: ${formatError(error)}`);
}
}
function Loading() {
return (
<div className="align-middle text-current text-center my-2 dark:text-white">
Loading...
</div>
);
}
function restoreWorkspace(
workspace: Workspace,
state: {
files: { [name: string]: string };
current: string;
},
dispatchFiles: ActionDispatch<[FileAction]>,
setError: (error: string | null) => void,
) {
let hasSettings = false;
for (const [name, content] of Object.entries(state.files)) {
let handle = null;
if (name === SETTINGS_FILE_NAME) {
updateOptions(workspace, content, setError);
hasSettings = true;
} else {
handle = workspace.openFile(name, content);
}
dispatchFiles({ type: "add", handle, content, name });
}
if (!hasSettings) {
updateOptions(workspace, null, setError);
}
dispatchFiles({
type: "selectFileByName",
name: state.current,
});
}