-
-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy pathWorkspace.svelte.ts
716 lines (572 loc) · 15.7 KB
/
Workspace.svelte.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
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
import type { CompileError, CompileResult } from 'svelte/compiler';
import { Compartment, EditorState, StateEffect, StateField } from '@codemirror/state';
import { compile_file } from './Compiler';
import { BROWSER } from 'esm-env';
import { basicSetup, EditorView } from 'codemirror';
import { javascript } from '@codemirror/lang-javascript';
import { html } from '@codemirror/lang-html';
import { svelte } from '@replit/codemirror-lang-svelte';
import { autocomplete_for_svelte } from '@sveltejs/site-kit/codemirror';
import { Decoration, keymap, type DecorationSet } from '@codemirror/view';
import { acceptCompletion } from '@codemirror/autocomplete';
import { indentWithTab } from '@codemirror/commands';
import { indentUnit } from '@codemirror/language';
import { theme } from './theme';
import { untrack } from 'svelte';
import type { Diagnostic } from '@codemirror/lint';
export interface File {
type: 'file';
name: string;
basename: string;
contents: string;
text: boolean;
}
export interface Directory {
type: 'directory';
name: string;
basename: string;
}
export type Item = File | Directory;
export interface Compiled {
error: CompileError | null;
result: CompileResult | null;
migration: {
code: string;
} | null;
}
function is_file(item: Item): item is File {
return item.type === 'file';
}
function is_svelte_file(file: File) {
return /\.svelte(\.|$)/.test(file.name);
}
function file_type(file: Item) {
return file.name.split('.').pop();
}
const set_highlight = StateEffect.define<{ start: number; end: number } | null>();
const highlight_field = StateField.define<DecorationSet>({
create() {
return Decoration.none;
},
update(highlights, tr) {
// Apply the effect
for (let effect of tr.effects) {
if (effect.is(set_highlight)) {
if (effect.value) {
const { start, end } = effect.value;
const deco = Decoration.mark({ class: 'highlight' }).range(start, end);
return Decoration.set([deco]);
} else {
// Clear highlight
return Decoration.none;
}
}
}
// Map decorations for document changes
return highlights.map(tr.changes);
},
provide: (field) => EditorView.decorations.from(field)
});
const tab_behaviour = new Compartment();
const vim_mode = new Compartment();
const default_extensions = [
basicSetup,
EditorState.tabSize.of(2),
tab_behaviour.of(keymap.of([{ key: 'Tab', run: acceptCompletion }])),
indentUnit.of('\t'),
theme,
vim_mode.of([]),
highlight_field
];
export interface ExposedCompilerOptions {
generate: 'client' | 'server';
dev: boolean;
modernAst: boolean;
}
export class Workspace {
// TODO this stuff should all be readonly
creating = $state.raw<{ parent: string; type: 'file' | 'directory' } | null>(null);
modified = $state<Record<string, boolean>>({});
#compiler_options = $state.raw<ExposedCompilerOptions>({
generate: 'client',
dev: false,
modernAst: true
});
compiled = $state<Record<string, Compiled>>({});
#svelte_version: string;
#readonly = false; // TODO do we need workspaces for readonly stuff?
#files = $state.raw<Item[]>([]);
#current = $state.raw() as File;
#vim = $state(false);
#tailwind = $state(false);
#handlers = {
hover: new Set<(pos: number | null) => void>(),
select: new Set<(from: number, to: number) => void>()
};
#onupdate: (file: File) => void;
#onreset: (items: Item[]) => void;
// CodeMirror stuff
states = new Map<string, EditorState>();
#view: EditorView | null = null;
diagnostics = $derived.by(() => {
const diagnostics: Diagnostic[] = [];
const error = this.current_compiled?.error;
const warnings = this.current_compiled?.result?.warnings ?? [];
if (error) {
diagnostics.push({
severity: 'error',
from: error.position![0],
to: error.position![1],
message: error.message,
renderMessage: () => {
let html = error.message
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/`(.+?)`/g, `<code>$1</code>`);
if (error.code) {
html += ` (<a href="/docs/svelte/compiler-errors#${error.code}">${error.code}</a>)`;
}
const span = document.createElement('span');
span.innerHTML = html;
return span;
}
});
}
for (const warning of warnings) {
diagnostics.push({
severity: 'warning',
from: warning.start!.character,
to: warning.end!.character,
message: warning.message,
renderMessage: () => {
const span = document.createElement('span');
span.innerHTML = `${warning.message
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(
/`(.+?)`/g,
`<code>$1</code>`
)} (<a href="/docs/svelte/compiler-warnings#${warning.code}">${warning.code}</a>)`;
return span;
}
});
}
return diagnostics;
});
constructor(
files: Item[],
{
svelte_version = 'latest',
initial,
readonly = false,
onupdate,
onreset
}: {
svelte_version?: string;
initial?: string;
readonly?: boolean;
onupdate?: (file: File) => void;
onreset?: (items: Item[]) => void;
} = {}
) {
this.#svelte_version = svelte_version;
this.#readonly = readonly;
this.set(files, initial);
this.#onupdate = onupdate ?? (() => {});
this.#onreset = onreset ?? (() => {});
this.#reset_diagnostics();
}
get files() {
return this.#files;
}
get compiler_options() {
return this.#compiler_options;
}
get current() {
return this.#current;
}
get current_compiled() {
if (this.#current.name in this.compiled) {
return this.compiled[this.#current.name];
}
return null;
}
add(item: Item) {
this.#create_directories(item);
this.#files = this.#files.concat(item);
if (is_file(item)) {
this.#select(item);
this.#onreset?.(this.#files);
this.modified[item.name] = true;
}
return item;
}
disable_tab_indent() {
this.#view?.dispatch({
effects: tab_behaviour.reconfigure(keymap.of([{ key: 'Tab', run: acceptCompletion }]))
});
}
enable_tab_indent() {
this.#view?.dispatch({
effects: tab_behaviour.reconfigure(
keymap.of([{ key: 'Tab', run: acceptCompletion }, indentWithTab])
)
});
}
focus() {
setTimeout(() => {
this.#view?.focus();
});
}
highlight_range(node: { start: number; end: number } | null, scroll = false) {
if (!this.#view) return;
const effects: StateEffect<any>[] = [set_highlight.of(node)];
if (scroll && node) {
effects.push(EditorView.scrollIntoView(node.start, { y: 'center' }));
}
this.#view.dispatch({
effects
});
}
mark_saved() {
this.modified = {};
}
async link(view: EditorView) {
if (this.#view) throw new Error('view is already linked');
this.#view = view;
untrack(() => {
view.setState(this.#get_state(untrack(() => this.#current)));
this.vim = localStorage.getItem('vim') === 'true';
});
}
move(from: Item, to: Item) {
const from_index = this.#files.indexOf(from);
const to_index = this.#files.indexOf(to);
this.#files.splice(from_index, 1);
this.#files = this.#files.slice(0, to_index).concat(from).concat(this.#files.slice(to_index));
}
onhover(fn: (pos: number | null) => void) {
$effect(() => {
this.#handlers.hover.add(fn);
return () => {
this.#handlers.hover.delete(fn);
};
});
}
onselect(fn: (from: number, to: number) => void) {
$effect(() => {
this.#handlers.select.add(fn);
return () => {
this.#handlers.select.delete(fn);
};
});
}
remove(item: Item) {
const index = this.#files.indexOf(item);
if (index === -1) {
throw new Error('Tried to remove a file that does not exist in the workspace');
}
let next = this.#current;
if (next === item) {
const file =
this.#files.slice(0, index).findLast(is_file) ?? this.#files.slice(index + 1).find(is_file);
if (!file) {
throw new Error('Cannot delete the only file');
}
next = file;
}
this.#files = this.#files.filter((f) => {
if (f === item) return false;
if (f.name.startsWith(item.name + '/')) return false;
return true;
});
this.#select(next);
this.#onreset?.(this.#files);
}
rename(previous: Item, name: string) {
const index = this.files.indexOf(previous);
const was_current = previous === this.#current;
const state = this.states.get(previous.name);
this.states.delete(previous.name);
const new_item: Item = {
...previous,
name,
basename: name.split('/').pop()!
};
this.#create_directories(new_item);
this.#files = this.#files.map((item, i) => {
if (i === index) return new_item;
if (previous.type === 'directory' && item.name.startsWith(previous.name + '/')) {
return {
...item,
name: item.name.replace(previous.name, name)
};
}
return item;
});
// preserve state, unless the language changed (in which case
// it's simpler to just create a new editor state)
if (state && file_type(previous) === file_type(new_item)) {
this.states.set(name, state);
}
if (was_current) {
this.#select(new_item as File);
}
if (this.modified[previous.name]) {
delete this.modified[previous.name];
this.modified[name] = true;
}
this.#onreset?.(this.#files);
}
reset(new_files: Item[], options: { tailwind: boolean }, selected?: string) {
this.states.clear();
this.set(new_files, selected);
this.mark_saved();
this.#tailwind = options.tailwind;
this.#onreset(new_files);
this.#reset_diagnostics();
}
select(name: string) {
const file = this.#files.find((file) => is_file(file) && file.name === name);
if (!file) {
throw new Error(`File ${name} does not exist in workspace`);
}
this.#select(file as File);
}
set(files: Item[], selected = this.#current?.name) {
const first = files.find(is_file);
if (!first) {
throw new Error('Workspace must have at least one file');
}
const matching_file = selected && files.find((file) => is_file(file) && file.name === selected);
if (matching_file) {
this.#select(matching_file as File);
} else {
this.#select(first);
}
this.#files = files;
for (const [name, state] of this.states) {
const file = files.find((file) => file.name === name) as File;
if (file) {
this.#update_state(file, state);
} else {
this.states.delete(name);
}
}
this.#onreset?.(this.files);
}
unlink(view: EditorView) {
if (this.#view !== view) throw new Error('Wrong editor view');
this.#view = null;
}
update_compiler_options(options: Partial<ExposedCompilerOptions>) {
this.#compiler_options = { ...this.#compiler_options, ...options };
this.#reset_diagnostics();
}
update_file(file: File) {
this.#update_file(file);
const state = this.states.get(file.name);
if (state) {
this.#update_state(file, state);
}
}
get tailwind() {
return this.#tailwind;
}
set tailwind(value) {
this.#tailwind = value;
this.#onupdate(this.#current);
}
get vim() {
return this.#vim;
}
set vim(value) {
this.#toggle_vim(value);
}
async #toggle_vim(value: boolean) {
this.#vim = value;
localStorage.setItem('vim', String(value));
// @ts-ignore jfc CodeMirror is a struggle
let vim_extension_index = default_extensions.findIndex((ext) => ext.compartment === vim_mode);
let extension: any = [];
if (value) {
const { vim } = await import('@replit/codemirror-vim');
extension = vim();
}
default_extensions[vim_extension_index] = vim_mode.of(extension);
this.#view?.dispatch({
effects: vim_mode.reconfigure(extension)
});
// update all the other states
for (const file of this.#files) {
if (file.type !== 'file') continue;
if (file === this.#current) continue;
this.states.set(file.name, this.#create_state(file));
}
}
#create_directories(item: Item) {
// create intermediate directories as necessary
const parts = item.name.split('/');
while (parts.length > 1) {
parts.pop();
const joined = parts.join('/');
if (this.files.find((file) => file.name === joined)) {
return;
}
this.#files.push({
type: 'directory',
name: joined,
basename: joined.split('/').pop()! // TODO get rid of this basename nonsense, it's infuriating
});
}
}
#get_state(file: File) {
return this.states.get(file.name) ?? this.#create_state(file);
}
#create_state(file: File) {
const extensions = [
...default_extensions,
EditorState.readOnly.of(this.#readonly),
EditorView.editable.of(!this.#readonly),
EditorView.updateListener.of((update) => {
const state = this.#view!.state!;
if (update.docChanged) {
this.#update_file({
...this.#current,
contents: state.doc.toString()
});
// preserve undo/redo across files
this.states.set(this.#current.name, state);
}
if (update.selectionSet) {
if (state.selection.ranges.length === 1) {
for (const handler of this.#handlers.select) {
const { from, to } = state.selection.ranges[0];
handler(from, to);
}
}
}
}),
EditorView.domEventObservers({
mousemove: (event, view) => {
const pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
if (pos !== null) {
for (const handler of this.#handlers.hover) {
handler(pos);
}
}
},
mouseleave: (event, view) => {
for (const handler of this.#handlers.hover) {
handler(null);
}
}
})
];
switch (file_type(file)) {
case 'js': // TODO autocomplete, including runes
case 'json':
extensions.push(javascript());
break;
case 'ts':
extensions.push(javascript({ typescript: true }));
break;
case 'html':
extensions.push(html());
break;
case 'svelte':
extensions.push(
svelte(),
...autocomplete_for_svelte(
() => this.current.name,
() =>
this.files
.filter((file) => {
if (file.type !== 'file') return false;
// TODO put autocomplete_filter on the workspace
// return autocomplete_filter(file);
return true;
})
.map((file) => file.name)
)
);
break;
}
const state = EditorState.create({
doc: file.contents,
extensions
});
this.states.set(file.name, state);
return state;
}
#reset_diagnostics() {
if (!BROWSER) return;
const keys = Object.keys(this.compiled);
const seen: string[] = [];
let files = this.#files;
// prioritise selected file
if (this.current) {
const i = this.#files.indexOf(this.current!);
files = [this.current, ...this.#files.slice(0, i), ...this.#files.slice(i + 1)];
}
for (const file of files) {
if (file.type !== 'file') continue;
if (!is_svelte_file(file)) continue;
seen.push(file.name);
compile_file(file, this.#svelte_version, this.compiler_options).then((compiled) => {
this.compiled[file.name] = compiled;
});
}
for (const key of keys) {
if (!seen.includes(key)) {
delete this.compiled[key];
}
}
}
#select(file: File) {
this.#current = file as File;
this.#view?.setState(this.#get_state(this.#current));
}
#update_file(file: File) {
if (file.name === this.#current.name) {
this.#current = file;
}
this.#files = this.#files.map((old) => {
if (old.name === file.name) {
return file;
}
return old;
});
this.modified[file.name] = true;
if (BROWSER && is_svelte_file(file)) {
compile_file(file, this.#svelte_version, this.compiler_options).then((compiled) => {
this.compiled[file.name] = compiled;
});
}
this.#onupdate(file);
}
#update_state(file: File, state: EditorState) {
const existing = state.doc.toString();
if (file.contents !== existing) {
const current_cursor_position = Math.min(
this.#view?.state.selection.ranges[0].from!,
file.contents.length
);
const transaction = state.update({
changes: {
from: 0,
to: existing.length,
insert: file.contents
},
selection: {
anchor: current_cursor_position,
head: current_cursor_position
}
});
this.states.set(file.name, transaction.state);
if (file === this.#current) {
this.#view?.setState(transaction.state);
}
}
}
}