-
Notifications
You must be signed in to change notification settings - Fork 756
Expand file tree
/
Copy patheditor-mosaic.ts
More file actions
490 lines (410 loc) · 14.4 KB
/
editor-mosaic.ts
File metadata and controls
490 lines (410 loc) · 14.4 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
import { makeAutoObservable, observable, reaction, runInAction } from 'mobx';
import type * 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;
/**
* Editors in Electron Fiddle can be hidden from the current view, but
* still exist in memory and can be re-opened.
*/
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 focusedFile: EditorId | null = null;
/**
* A map of editors and the SHA-1 hashes of their contents
* when last saved.
*/
private savedHashes = new Map<EditorId, string>();
/**
* A map of editors and the SHA-1 hashes of their current contents.
*/
private currentHashes = new Map<EditorId, string>();
public get isEdited() {
// If we haven't processed the save state upon initial load yet, don't mark as edited
// (All editors need to be mounted into Fiddle first)
if (this.savedHashes.size === 0) {
return false;
}
if (this.savedHashes.size !== this.currentHashes.size) {
return true;
}
for (const [id, hash] of this.currentHashes) {
if (this.savedHashes.get(id) !== hash) return true;
}
return false;
}
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() {
makeAutoObservable(this);
// whenever the mosaics are changed,
// update the editor layout
reaction(
() => this.mosaic,
() => this.layout(),
);
this.layout = this.layout.bind(this);
// TODO: evaluate if we need to dispose of the listener when this class is
// destroyed via FinalizationRegistry
window.monaco.editor.onDidChangeMarkers(this.setSeverityLevels.bind(this));
}
/** 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 */
public async resetLayout() {
await this.set(this.values());
}
/// set / add / get the files in the model
/** Set the contents of the mosaic */
public async 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) {
await this.addFile(id, value);
}
for (const id of this.editors.keys()) {
if (!values.has(id)) this.editors.delete(id);
}
}
/** Add a file. If we already have a file with that name, replace it. */
private async 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);
// set a URI for each editor for stable identification for monaco features
const uri = monaco.Uri.parse(`inmemory://fiddle/${id}`);
let model: MonacoType.editor.ITextModel;
const maybeModel = monaco.editor.getModel(uri);
if (maybeModel) {
model = maybeModel;
model.setValue(value);
} else {
model = monaco.editor.createModel(value, language, uri);
}
// 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 };
this.backups.set(id, backup);
const editor = this.editors.get(id);
if (editor) {
this.setEditorFromBackup(editor, backup);
this.observeEdits(editor);
}
// only show the file if it has nontrivial content
if (value.length && value !== getEmptyContent(id)) {
this.show(id);
} else {
this.hide(id);
}
await this.updateCurrentHash();
}
/// 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 async remove(id: EditorId) {
this.editors.delete(id);
this.backups.delete(id);
this.setVisible(getLeaves(this.mosaic).filter((v) => v !== id));
await this.updateCurrentHash();
}
/** Wire up a newly-mounted Monaco editor */
public async 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.editorSeverityMap.set(id, window.monaco.MarkerSeverity.Hint);
this.setEditorFromBackup(editor, backup);
}
/** Populate a MonacoEditor with the file's contents */
private setEditorFromBackup(editor: Editor, backup: EditorBackup) {
if (backup.viewState) editor.restoreViewState(backup.viewState);
editor.setModel(backup.model);
this.observeEdits(editor); // resume
}
/** Add a new file to the mosaic */
public async addNewFile(id: EditorId, value: string = getEmptyContent(id)) {
if (this.files.has(id)) {
throw new Error(`Cannot add file "${id}": File already exists`);
}
if (id.includes('/') || id.includes('\\')) {
throw new Error(
`Invalid filename "${id}": filenames cannot include path separators`,
);
}
if (!isSupportedFile(id)) {
throw new Error(
`Invalid filename "${id}": Must be a file ending in .cjs, .js, .mjs, .html, .css, or .json`,
);
}
const entryPoint = this.mainEntryPointFile();
if (isMainEntryPoint(id) && entryPoint) {
throw new Error(
`Cannot add file "${id}": Main entry point ${entryPoint} exists`,
);
}
await this.addFile(id, value);
}
/** Rename a file in the mosaic */
public async 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`);
}
if (newId.includes('/') || newId.includes('\\')) {
throw new Error(
`Invalid filename "${newId}": filenames cannot include path separators`,
);
}
if (
newId.endsWith('.json') &&
[PACKAGE_NAME, 'package-lock.json'].includes(newId)
) {
throw new Error(
`Cannot add ${PACKAGE_NAME} or package-lock.json as custom files`,
);
}
if (!isSupportedFile(newId)) {
throw new Error(
`Invalid filename "${newId}": Must be a file ending in .cjs, .js, .mjs, .html, .css, or .json`,
);
}
const entryPoint = this.mainEntryPointFile();
if (isMainEntryPoint(newId) && entryPoint !== oldId) {
throw new Error(
`Cannot rename file to "${newId}": Main entry point ${entryPoint} exists`,
);
}
await this.addFile(newId, this.value(oldId).trim());
await 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() {
clearTimeout(this.layoutDebounce);
this.layoutDebounce = setTimeout(() => {
for (const editor of this.editors.values()) {
editor.layout();
}
}, 50);
}
public getAllEditorIds(): EditorId[] {
return [...this.editors.keys()];
}
public getAllEditors(): Editor[] {
return [...this.editors.values()];
}
public getFocusedEditor(): 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 {
return Array.from(this.files.keys()).find((id) => isMainEntryPoint(id));
}
private observeEdits(editor: Editor) {
editor.onDidChangeModelContent(async () => {
await this.updateCurrentHash();
});
}
private async updateCurrentHash() {
const hashes = await this.getAllHashes();
runInAction(() => {
this.currentHashes = hashes;
});
}
/**
* Generates a SHA-1 hash for each editor's contents. Visible editors are
* under `this.editors`, and hidden editors are under `this.backups`.
*/
private async getAllHashes() {
const hashes = new Map<EditorId, string>();
const encoder = new TextEncoder();
for (const [id, editor] of this.editors) {
const txt = editor.getModel()?.getValue();
const data = encoder.encode(txt);
const digest = await window.crypto.subtle.digest('SHA-1', data);
const hashArray = Array.from(new Uint8Array(digest));
const hash = hashArray
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
hashes.set(id, hash);
}
for (const [id, backup] of this.backups) {
const txt = backup.model.getValue();
const data = encoder.encode(txt);
const digest = await window.crypto.subtle.digest('SHA-1', data);
const hashArray = Array.from(new Uint8Array(digest));
const hash = hashArray
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
hashes.set(id, hash);
}
return hashes;
}
/**
* Marks the current state of all editors as saved.
*/
public async markAsSaved() {
const hashes = await this.getAllHashes();
runInAction(() => {
this.savedHashes = hashes;
// new map to clone
this.currentHashes = new Map(hashes);
});
}
/**
* Forces all editors to be marked as unsaved.
*/
public clearSaved() {
this.savedHashes.clear();
}
public editorSeverityMap = observable.map<
EditorId,
MonacoType.MarkerSeverity
>();
public setSeverityLevels() {
runInAction(() => {
for (const id of this.getAllEditorIds()) {
const markers = window.monaco.editor.getModelMarkers({
resource: window.monaco.Uri.parse(`inmemory://fiddle/${id}`),
});
const maxSeverity: MonacoType.MarkerSeverity = markers.reduce(
(max, marker) => {
return Math.max(max, marker.severity);
},
window.monaco.MarkerSeverity.Hint,
);
this.editorSeverityMap.set(id, maxSeverity);
}
});
}
}