-
Notifications
You must be signed in to change notification settings - Fork 752
Expand file tree
/
Copy patheditor-mosaic.ts
More file actions
405 lines (338 loc) · 11.7 KB
/
editor-mosaic.ts
File metadata and controls
405 lines (338 loc) · 11.7 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
import { action, computed, makeObservable, observable, reaction } from 'mobx';
import * as MonacoType from 'monaco-editor';
import { MosaicDirection, MosaicNode, getLeaves } from 'react-mosaic-component';
import {
compareEditors,
getEmptyContent,
isMainEntryPoint,
isSupportedFile,
monacoLanguage,
} from './utils/editor-utils';
import { EditorId, EditorValues, PACKAGE_NAME } from '../interfaces';
export type Editor = MonacoType.editor.IStandaloneCodeEditor;
export enum EditorPresence {
/** The file is known to us but we've chosen not to show it, either
because the content was boring or because hide() was called.
Its contents are cached offscreen. */
Hidden,
/** Space has been allocated for this file in the mosaic but the
monaco editor has not mounted in React yet. This is an interim
state before the editor is Visible. */
Pending,
/** The file is visible in one of the mosaic's monaco editors */
Visible,
}
interface EditorBackup {
model: MonacoType.editor.ITextModel;
viewState?: MonacoType.editor.ICodeEditorViewState | null;
}
export class EditorMosaic {
public mainEntryPoint: EditorId | null = null;
public isEdited = false;
public focusedFile: EditorId | null = null;
public get files() {
const files = new Map<EditorId, EditorPresence>();
const { backups, editors, mosaic } = this;
for (const id of backups.keys()) files.set(id, EditorPresence.Hidden);
for (const id of getLeaves(mosaic)) files.set(id, EditorPresence.Pending);
for (const id of editors.keys()) files.set(id, EditorPresence.Visible);
return files;
}
public get numVisible() {
return getLeaves(this.mosaic).length;
}
// You probably want EditorMosaic.files instead.
// This is only public because components/editors.tsx needs it
public mosaic: MosaicNode<EditorId> | null = null;
private readonly backups = new Map<EditorId, EditorBackup>();
private readonly editors = new Map<EditorId, Editor>();
constructor() {
makeObservable<
EditorMosaic,
'backups' | 'editors' | 'addFile' | 'setVisible' | 'setEditorFromBackup'
>(this, {
isEdited: observable,
focusedFile: observable,
files: computed,
numVisible: computed,
mosaic: observable,
backups: observable,
editors: observable,
mainEntryPoint: observable,
setFocusedFile: action,
resetLayout: action,
set: action,
addFile: action,
show: action,
setVisible: action,
toggle: action,
hide: action,
setMainEntryPoint: action,
remove: action,
addEditor: action,
setEditorFromBackup: action,
addNewFile: action,
renameFile: action,
});
// whenever the mosaics are changed,
// update the editor layout
reaction(
() => this.mosaic,
() => this.layout(),
);
// whenever isEdited is set, stop or start listening to edits again.
reaction(
() => this.isEdited,
() => {
if (this.isEdited) {
this.ignoreAllEdits();
} else {
this.observeAllEdits();
}
},
);
}
/** File is visible, focus file content */
/** File is hidden, show the file and focus the file content */
public setFocusedFile(id: EditorId) {
this.focusedFile = id;
if (this.files.get(this.focusedFile) === EditorPresence.Hidden) {
this.show(this.focusedFile);
}
this.editors.get(id)?.focus();
}
/** Reset the layout to the initial layout we had when set() was called */
resetLayout = () => {
this.set(this.values());
};
/// set / add / get the files in the model
/** Set the contents of the mosaic */
public set(valuesIn: EditorValues) {
// set() clears out the previous Fiddle, so clear our previous state
// except for this.editors -- we recycle editors below in setFile()
this.backups.clear();
this.mosaic = null;
// add the files to the mosaic, recycling existing editors when possible.
const values = new Map(Object.entries(valuesIn)) as Map<EditorId, string>;
for (const [id, value] of values) this.addFile(id, value);
for (const id of this.editors.keys()) {
if (!values.has(id)) this.editors.delete(id);
}
this.isEdited = false;
}
/** Add a file. If we already have a file with that name, replace it. */
private addFile(id: EditorId, value: string) {
if (
id.endsWith('.json') &&
[PACKAGE_NAME, 'package-lock.json'].includes(id)
) {
throw new Error(
`Cannot add ${PACKAGE_NAME} or package-lock.json as custom files`,
);
}
if (!isSupportedFile(id)) {
throw new Error(
`Cannot add file "${id}": Must be .cjs, .js, .mjs, .html, .css, or .json`,
);
}
// create a monaco model with the file's contents
const { monaco } = window;
const language = monacoLanguage(id);
const model = monaco.editor.createModel(value, language);
model.updateOptions({ tabSize: 2 });
// if we have an editor available, use the monaco model now.
// otherwise, save the file in `this.backups` for future use.
const backup: EditorBackup = { model };
const editor = this.editors.get(id);
if (editor) {
this.setEditorFromBackup(editor, backup);
} else {
this.backups.set(id, backup);
}
// only show the file if it has nontrivial content
if (value.length && value !== getEmptyContent(id)) {
this.show(id);
} else {
this.hide(id);
}
this.isEdited = true;
}
/// show or hide files in the view
/** Show the specified file's editor */
public show(id: EditorId) {
this.setVisible([...getLeaves(this.mosaic), id]);
}
private setVisible(visible: EditorId[]) {
// Sort the files and remove duplicates
visible = [...new Set(visible)].sort(compareEditors);
// Decide what layout would be good for this set of files
const mosaic = EditorMosaic.createMosaic(visible);
// Use that new layout. Note: if there are new files in `visible`,
// setting `this.mosaic` here is what triggers new Monaco editors to
// be created for them in React, via components/editors.tsx's use of
// this.mosaic in its render() function. After they mount,
// editors.tsx will call addEditor() to tell us about them. The same
// holds true for removing editors; setting this.mosaic is what will
// trigger their removal from React.
this.mosaic = mosaic;
}
private static createMosaic(
input: EditorId[],
direction: MosaicDirection = 'row',
): MosaicNode<EditorId> {
// Return single editor or undefined.
if (input.length < 2) return input[0];
// This cuts out the first half of input. Input becomes the second half.
const secondHalf = [...input];
const firstHalf = secondHalf.splice(0, Math.floor(secondHalf.length / 2));
return {
direction,
first: EditorMosaic.createMosaic(firstHalf, 'column'),
second: EditorMosaic.createMosaic(secondHalf, 'column'),
};
}
/** Helper to toggle visibility of the specified file's editor */
public toggle(id: EditorId) {
if (this.files.get(id) === EditorPresence.Hidden) {
this.show(id);
} else {
this.hide(id);
}
}
/** Hide the specified file's editor */
public hide(id: EditorId) {
const editor = this.editors.get(id);
if (editor) {
this.editors.delete(id);
this.backups.set(id, {
model: editor.getModel()!,
viewState: editor.saveViewState(),
});
}
this.setVisible(getLeaves(this.mosaic).filter((v) => v !== id));
}
/** Remove the specified file and its editor */
public remove(id: EditorId) {
this.editors.delete(id);
this.backups.delete(id);
this.setVisible(getLeaves(this.mosaic).filter((v) => v !== id));
this.isEdited = true;
}
/** Wire up a newly-mounted Monaco editor */
public addEditor(id: EditorId, editor: Editor) {
const backup = this.backups.get(id);
if (!backup) throw new Error(`added Editor for unexpected file "${id}"`);
this.backups.delete(id);
this.editors.set(id, editor);
this.setEditorFromBackup(editor, backup);
}
/** Populate a MonacoEditor with the file's contents */
private setEditorFromBackup(editor: Editor, backup: EditorBackup) {
this.ignoreEdits(editor); // pause this so that isEdited doesn't get set
if (backup.viewState) editor.restoreViewState(backup.viewState);
editor.setModel(backup.model);
this.observeEdits(editor); // resume
}
/** Add a new file to the mosaic */
public addNewFile(id: EditorId, value: string = getEmptyContent(id)) {
if (this.files.has(id)) {
throw new Error(`Cannot add file "${id}": File already exists`);
}
const entryPoint = this.mainEntryPointFile();
if (isMainEntryPoint(id) && entryPoint) {
throw new Error(
`Cannot add file "${id}": Main entry point ${entryPoint} exists`,
);
}
this.addFile(id, value);
}
/** Rename a file in the mosaic */
public renameFile(oldId: EditorId, newId: EditorId) {
if (!this.files.has(oldId)) {
throw new Error(`Cannot rename file "${oldId}": File doesn't exist`);
}
if (this.files.has(newId)) {
throw new Error(`Cannot rename file to "${newId}": File already exists`);
}
const entryPoint = this.mainEntryPointFile();
if (isMainEntryPoint(newId) && entryPoint !== oldId) {
throw new Error(
`Cannot rename file to "${newId}": Main entry point ${entryPoint} exists`,
);
}
this.addFile(newId, this.value(oldId).trim());
this.remove(oldId);
}
/** Get the contents of a single file. */
public value(id: EditorId): string {
const { backups, editors } = this;
return (
editors.get(id)?.getValue() || backups.get(id)?.model.getValue() || ''
);
}
/** Get the contents of all files. */
public values(): EditorValues {
return Object.fromEntries(
[...this.files].map(([id]) => [id, this.value(id)]),
);
}
/// misc utilities
private layoutDebounce: ReturnType<typeof setTimeout> | undefined;
public layout = () => {
const DEBOUNCE_MSEC = 50;
if (!this.layoutDebounce) {
this.layoutDebounce = setTimeout(() => {
for (const editor of this.editors.values()) editor.layout();
delete this.layoutDebounce;
}, DEBOUNCE_MSEC);
}
};
public focusedEditor(): Editor | undefined {
return [...this.editors.values()].find((editor) => editor.hasTextFocus());
}
public updateOptions(options: MonacoType.editor.IEditorOptions) {
for (const editor of this.editors.values()) editor.updateOptions(options);
}
public mainEntryPointFile(): EditorId | undefined {
if (!this.mainEntryPoint || !this.files.get(this.mainEntryPoint)) {
const entryPoint = Array.from(this.files.keys()).find((id) =>
isMainEntryPoint(id),
);
if (entryPoint) this.mainEntryPoint = entryPoint;
return entryPoint;
}
return this.mainEntryPoint;
}
public setMainEntryPoint(id: EditorId): void {
if (!this.files.has(id)) {
throw new Error(
`Cannot set main entry point to "${id}": File does not exist`,
);
}
if (!isMainEntryPoint(id)) {
throw new Error(
`Cannot set main entry point to "${id}": Not a valid main entry point file`,
);
}
this.mainEntryPoint = id;
this.isEdited = true;
}
//=== Listen for user edits
private ignoreAllEdits() {
for (const editor of this.editors.values()) this.ignoreEdits(editor);
}
private ignoreEdits(editor: Editor) {
editor.onDidChangeModelContent(() => {
// no-op
});
}
private observeAllEdits() {
for (const editor of this.editors.values()) this.observeEdits(editor);
}
private observeEdits(editor: Editor) {
const disposable = editor.onDidChangeModelContent(() => {
this.isEdited ||= true;
disposable.dispose();
});
}
}