-
Notifications
You must be signed in to change notification settings - Fork 179
Expand file tree
/
Copy pathdocument.ts
More file actions
440 lines (366 loc) · 14.6 KB
/
document.ts
File metadata and controls
440 lines (366 loc) · 14.6 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
import type { Observer } from '@playcanvas/observer';
import type * as Monaco from 'monaco-editor';
import { config } from '@/code-editor/config';
// TODO: Types
type ViewEntry = {
doc: any;
type: any;
asset: any;
view: Monaco.editor.ITextModel;
suppressChanges: boolean;
viewState: any;
};
editor.once('load', () => {
const panel = editor.call('layout.code');
const monacoEditor = editor.call('editor:monaco');
const viewIndex: Record<string, ViewEntry> = {};
let focusedView = null;
const modes = {
script: 'javascript',
json: 'json',
html: 'html',
css: 'css',
shader: 'glsl'
};
/**
* Converts an import entry to a Monaco-compatible path.
*
* @param entry - The import entry (key, path).
* @returns The adjusted key and an array containing the file:// path.
*/
function importEntryToMonacoPath([key, entry]: [string, unknown]): [string, string[]] {
const suffix = key.endsWith('/') ? '*' : '';
const newKey = key + suffix;
const path = `file://${entry}${suffix}`;
return [newKey, [path]];
}
/**
* Creates an array of module declarations for http imports.
*
* @example
* ```
* createModuleDeclarations([['external-lib', 'http://cdn.example.com/react']])
* // =? ['declare module "external-lib" { const Module: any; export default Module; export = Module; }']
* ```
*
* @param importEntries - The import entries (key, path).
* @returns The module declarations.
*/
function createModuleDeclarations(importEntries: [string, unknown][]): string[] {
const httpImports = importEntries
.filter(([_, path]) => path.startsWith('http://') || path.startsWith('https://'))
.map(([key]) => key);
const httpImportToTypeDeclaration = (key: string) => (
`declare module '${key}' {\nconst Module: any;\nexport default Module;\nexport = Module;\n}`
);
return httpImports.map(httpImportToTypeDeclaration);
}
function refreshReadonly() {
const readonly = editor.call('editor:isReadOnly');
const wasReadonly = monacoEditor.getOption('readOnly');
monacoEditor.updateOptions({ readOnly: readonly });
if (readonly !== wasReadonly) {
editor.emit('editor:readonly:change', readonly);
}
}
// Utility method that returns the import map if available
editor.method('editor:importMap', () => new Promise((resolve, reject) => {
const importMapId = config.project.settings.importMap;
if (!importMapId) {
resolve({ imports: {} });
}
const asset = editor.call('assets:get', importMapId);
if (!asset) {
resolve({ imports: {} });
} else {
editor.call('assets:contents:get', asset, (err: unknown, content: string) => {
if (err) {
reject(err);
}
resolve(JSON.parse(content));
});
}
}));
// when we select an asset
// if the asset is not loaded hide
// the code panel until it's loaded
editor.on('select:asset', (asset: Observer) => {
if (asset.get('type') === 'folder') {
return;
}
if (!viewIndex[asset.get('id')]) {
panel.toggleCode(false);
}
});
// When document is loaded create document
// and add entry to index
editor.on('documents:load', async (doc: { data: string }, asset: Observer) => {
const id = asset.get('id');
if (viewIndex[id]) {
return;
}
let mode;
const type = asset.get('type');
if (modes[type]) {
mode = modes[type];
} else {
mode = null;
}
const assetPath = asset.get('path');
const pathSegments = [];
for (const id of assetPath) {
const a = editor.call('assets:get', id);
if (!a) {
return;
}
pathSegments.push(a.get('name'));
}
const path = [...pathSegments, asset.get('file').filename].join('/');
const uri = monaco.Uri.parse(`${path}`);
const isModule = editor.call('assets:isModule', asset);
if (isModule && monaco.editor.getModel(uri)) {
editor.call('status:error', `Failed to open asset (${asset.get('id')}) from path ${path}. An asset with the same path is already open.`);
return;
}
const entry: ViewEntry = {
doc: doc,
type: type,
asset: asset,
view: monaco.editor.createModel(doc.data, mode, isModule ? uri : undefined),
suppressChanges: false,
viewState: null
};
// emit change event
entry.view.onDidChangeContent((evt: Monaco.editor.IModelContentChangedEvent) => {
if (entry.suppressChanges) {
return;
}
editor.emit('views:change', id, entry.view, evt);
});
viewIndex[id] = entry;
editor.emit('views:new', id, entry.view, type);
editor.emit(`views:new:${id}`, entry.view, type);
const { imports } = await editor.call('editor:importMap');
const importEntries = Object.entries(imports);
const importPaths = importEntries.map(importEntryToMonacoPath);
const monacoImportPaths = Object.fromEntries(importPaths);
// The import map can contain external imports ie "react": "https://esm.sh/react"
// We don't have type declarations for these, so we need to create pseudo ones for the editor for intellisense.
// Note: Replace this when we actually resolve real type declarations
const externalTypesDeclarations = createModuleDeclarations(importEntries);
monaco.languages.typescript.javascriptDefaults.addExtraLib(externalTypesDeclarations.join('\n'), 'external-imports.d.ts');
monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
allowJs: true,
checkJs: true,
allowNonTsExtensions: true,
esModuleInterop: true,
target: monaco.languages.typescript.ScriptTarget.ES2020,
lib: ['es2020', 'dom', 'dom.iterable'],
paths: {
'playcanvas': ['playcanvas.d.ts'],
...monacoImportPaths
}
});
});
// Focus document
editor.on('documents:focus', (id: string) => {
if (!viewIndex[id]) {
// This happens on some rare occasions not sure why yet...
console.warn('Requested to focus document that has no view yet', `Document ${id}`);
return;
}
// unhide code
panel.toggleCode(true);
// remember view state for the current view
// so we can restore it after switching back to it
if (focusedView) {
focusedView.viewState = monacoEditor.saveViewState();
}
if (focusedView && viewIndex[id] === focusedView) {
const content = focusedView.doc.data;
if (focusedView.view.getValue() === content) {
return;
}
// if the reloaded data are different
// than the current editor value then reset the contents
// of the editor - that can happen if a change has been rolled back
// by sharedb for example
focusedView.suppressChanges = true;
focusedView.view.setValue(content);
focusedView.suppressChanges = false;
} else {
focusedView = viewIndex[id];
// set doc to monaco
monacoEditor.setModel(focusedView.view);
const options = {
lineNumbers: true,
folding: focusedView.type !== 'text'
};
monacoEditor.updateOptions(options);
// only allow linting for script assets
const isScript = focusedView.type === 'script';
const isEsmScript = isScript && focusedView.asset.get('name').endsWith('.mjs');
monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
noSemanticValidation: !isEsmScript,
noSyntaxValidation: !isScript
});
monaco.languages.typescript.javascriptDefaults.setEagerModelSync(true);
// Enable TS like semantic type checking for ESM Scripts
}
refreshReadonly();
// focus editor
setTimeout(() => {
monacoEditor.focus();
// restore state
if (focusedView.viewState) {
monacoEditor.restoreViewState(focusedView.viewState);
}
});
});
// Close document
editor.on('documents:close', (id: string) => {
if (focusedView === viewIndex[id]) {
// clear code
// but suppress changes to the doc
// to avoid sending them to sharedb
focusedView.suppressChanges = true;
monacoEditor.setValue('');
panel.toggleCode(false);
focusedView = null;
}
const entry = viewIndex[id];
if (entry && entry.view) {
entry.view.dispose();
}
delete viewIndex[id];
});
// Returns the dependencies of an ESM Script Asset
const getDependenciesFromString = (content: string, importer = './') => {
const importRegex = /import\s[\w\s{},*]+\sfrom\s+['"]([^'"]+)['"]/g;
let match;
const paths: Set<string> = new Set();
while ((match = importRegex.exec(content)) !== null) {
// Get the full path relative to the importer
const path = new URL(match[1], `https://base${importer}`).pathname;
// Check if the asset exists
if (editor.call('assets:getByVirtualPath', path)) {
paths.add(path);
}
}
return paths;
};
editor.method('utils:deps-from-string', getDependenciesFromString);
const getDependenciesForAsset = (asset: Observer): Promise<Set<string>> => {
return new Promise((resolve, reject) => {
editor.call('assets:contents:get', asset, (err: unknown, content: string) => {
if (err) {
reject(err);
}
if (!asset.get('file.filename').endsWith('.mjs')) {
resolve(new Set([]));
}
const importer = editor.call('assets:virtualPath', asset);
if (!importer) {
resolve(new Set([]));
return;
}
const deps = getDependenciesFromString(content, importer);
resolve(deps);
});
});
};
editor.method('utils:deps-from-asset', (asset: Observer) => getDependenciesForAsset(asset));
editor.method('asset:update-dependencies', async (asset: Observer) => {
const filePath = editor.call('assets:virtualPath', asset);
if (!filePath) {
return;
}
// Fetch the dependencies for the asset
const deps = await getDependenciesForAsset(asset);
const openPaths = Object.values(viewIndex)
.map(({ view }) => view.uri.path) // ignore the schema
.filter(uri => uri.endsWith('.mjs')) // only esm files
.filter(uri => uri !== filePath); // exclude the current asset
// Create a set of the current files
const currentFiles = new Set(openPaths);
// Create a map of file paths to views. eg: { '/path/to/file.mjs': view }
const pathEntryMap = new Map(
Object.values(viewIndex).map(entry => [entry.view.uri.path, entry])
);
// get set of files that are not loaded
const newFiles = deps.difference(currentFiles);
// files to remove
const filesToRemove = currentFiles.difference(deps);
const openTabs = editor.call('tabs:list').map(tab => editor.call('assets:virtualPath', tab.asset)).filter(Boolean);
// Remove the views for the files that are no longer dependencies
filesToRemove.forEach((filePath: string) => {
// Don't remove the file if it's open in a tab
if (openTabs.includes(filePath)) {
return;
}
const entry = pathEntryMap.get(filePath);
if (entry) {
editor.emit('documents:close', entry.asset.get('id'));
}
});
// Find the associated asset for the file path, and load it
newFiles.forEach((file: string) => {
const asset = editor.call('assets:getByVirtualPath', file);
if (asset) {
editor.call('load:asset', asset, false);
}
});
// We must force the editor content to refresh for changes to take effect
const targetView = viewIndex[asset.get('id')];
if (!targetView) {
return;
}
targetView.suppressChanges = true;
const monacoEditor = editor.call('editor:monaco');
const position = monacoEditor.getPosition();
const contents = targetView.view.getValue();
targetView.view.setValue(contents);
monacoEditor.setPosition(position);
targetView.suppressChanges = false;
});
// unfocus
editor.on('documents:unfocus', () => {
// remember view state for the current view
// so we can restore it after switching back to it
if (focusedView) {
focusedView.viewState = monacoEditor.saveViewState();
}
focusedView = null;
});
// Get focused document
editor.method('editor:focusedView', () => {
return focusedView && focusedView.view;
});
editor.on('documents:error', () => {
refreshReadonly();
});
editor.on('documents:error:cleared', () => {
refreshReadonly();
});
editor.method('editor:isReadOnly', () => {
return !focusedView ||
!editor.call('permissions:write') ||
editor.call('errors:hasRealtime') ||
editor.call('documents:hasError', focusedView.asset.get('id'));
});
// set code editor to readonly if necessary
editor.on('permissions:writeState', refreshReadonly);
// Returns the monaco view for an id
editor.method('views:get', (id: string) => {
const entry = viewIndex[id];
return entry ? entry.view : null;
});
editor.method('view:asset', (modelId: string) => {
for (const key in viewIndex) {
if (viewIndex[key].view.id === modelId) {
return viewIndex[key].asset;
}
}
return null;
});
});