monacoCreator.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. /**
  2. * This JS file is for Monaco management
  3. * This file is quite technical, please make sure that you understand all parts before making changes.
  4. * Please also make sure that the following is still working before submitting a PR:
  5. * - autocompletion.
  6. * - deprecated members marking.
  7. * - compilation and proper error reporting for both JS and TS.
  8. * - private/internal member filtering (we should not see members starting with an underscore).
  9. * - dedicated adornments, like the one used for previewing colors for BABYLON.ColorX types.
  10. * - diff support.
  11. * - minimap support.
  12. */
  13. class MonacoCreator {
  14. constructor(parent) {
  15. this.parent = parent;
  16. this.jsEditor = null;
  17. this.diffEditor = null;
  18. this.diffNavigator = null;
  19. this.monacoMode = "javascript";
  20. this.blockEditorChange = false;
  21. this.definitionWorker = null;
  22. this.deprecatedCandidates = [];
  23. this.compilerTriggerTimeoutID = null;
  24. }
  25. // ACCESSORS
  26. get JsEditor() {
  27. return this.jsEditor;
  28. };
  29. getCode() {
  30. if (this.jsEditor) return this.jsEditor.getValue();
  31. else return "";
  32. };
  33. setCode(value) {
  34. this.jsEditor.setValue(value);
  35. };
  36. get MonacoMode() {
  37. return this.monacoMode;
  38. };
  39. set MonacoMode(mode) {
  40. if (this.monacoMode != "javascript"
  41. && this.monacoMode != "typescript")
  42. console.warn("Error while defining Monaco Mode");
  43. this.monacoMode = mode;
  44. };
  45. get BlockEditorChange() {
  46. return this.blockEditorChange;
  47. };
  48. set BlockEditorChange(value) {
  49. this.blockEditorChange = value;
  50. };
  51. // FUNCTIONS
  52. /**
  53. * Load the Monaco Node module.
  54. */
  55. async loadMonaco(typings) {
  56. let response = await fetch(typings || "https://preview.babylonjs.com/babylon.d.ts");
  57. if (!response.ok) {
  58. return;
  59. }
  60. let libContent = await response.text();
  61. if (!typings) {
  62. response = await fetch(typings || "https://preview.babylonjs.com/gui/babylon.gui.d.ts");
  63. if (!response.ok) {
  64. return;
  65. }
  66. libContent += await response.text();
  67. }
  68. this.setupDefinitionWorker(libContent);
  69. // WARNING !!! We need the 'dev' version of Monaco, as we use monkey-patching to hook into the suggestion adapter
  70. require.config({ paths: { 'vs': '/node_modules/monaco-editor/dev/vs' } });
  71. require(['vs/editor/editor.main'], () => {
  72. // Setup the Monaco compilation pipeline, so we can reuse it directly for our scrpting needs
  73. this.setupMonacoCompilationPipeline(libContent);
  74. // This is used for a vscode-like color preview for ColorX types
  75. this.setupMonacoColorProvider();
  76. // As explained above, we need the 'dev' version of Monaco to access this adapter!
  77. require(['vs/language/typescript/languageFeatures'], module => {
  78. this.hookMonacoCompletionProvider(module.SuggestAdapter);
  79. });
  80. this.parent.main.run();
  81. });
  82. };
  83. // > This worker will analyze the syntaxtree and return an array of deprecated functions (but the goal is to do more in the future!)
  84. // We need to do this because:
  85. // - checking extended properties during completion is time consuming, so we need to prefilter potential candidates
  86. // - we don't want to maintain a static list of deprecated members or to instrument this work on the CI
  87. // - we have more plans involving syntaxtree analysis
  88. // > This worker was carefully crafted to work even if the processing is super fast or super long.
  89. // In both cases the deprecation filter will start working after the worker is done.
  90. // We will also need this worker in the future to compute Intellicode scores for completion using dedicated attributes.
  91. setupDefinitionWorker(libContent) {
  92. this.definitionWorker = new Worker('/js/definitionWorker.js');
  93. this.definitionWorker.addEventListener('message', ({ data }) => {
  94. this.deprecatedCandidates = data.result;
  95. this.analyzeCode();
  96. });
  97. this.definitionWorker.postMessage({ code: libContent });
  98. }
  99. isDeprecatedEntry(details) {
  100. return details
  101. && details.tags
  102. && details.tags.find(this.isDeprecatedTag);
  103. }
  104. isDeprecatedTag(tag) {
  105. return tag
  106. && tag.name == "deprecated";
  107. }
  108. // This will make sure that all members marked with a deprecated jsdoc attribute will be marked as such in Monaco UI
  109. // We use a prefiltered list of deprecated candidates, because the effective call to getCompletionEntryDetails is slow.
  110. // @see setupDefinitionWorker
  111. async analyzeCode() {
  112. // if the definition worker is very fast, this can be called out of context. @see setupDefinitionWorker
  113. if (!this.jsEditor)
  114. return;
  115. const model = this.jsEditor.getModel();
  116. if (!model)
  117. return;
  118. const uri = model.uri;
  119. let worker = null;
  120. if (this.parent.settingsPG.ScriptLanguage == "JS")
  121. worker = await monaco.languages.typescript.getJavaScriptWorker();
  122. else
  123. worker = await monaco.languages.typescript.getTypeScriptWorker();
  124. const languageService = await worker(uri);
  125. const source = '[deprecated members]';
  126. monaco.editor.setModelMarkers(model, source, []);
  127. const markers = [];
  128. for (const candidate of this.deprecatedCandidates) {
  129. const matches = model.findMatches(candidate, null, false, true, null, false);
  130. for (const match of matches) {
  131. const position = { lineNumber: match.range.startLineNumber, column: match.range.startColumn };
  132. const wordInfo = model.getWordAtPosition(position);
  133. const offset = model.getOffsetAt(position);
  134. // continue if we already found an issue here
  135. if (markers.find(m => m.startLineNumber == position.lineNumber && m.startColumn == position.column))
  136. continue;
  137. // the following is time consuming on all suggestions, that's why we precompute deprecated candidate names in the definition worker to filter calls
  138. // @see setupDefinitionWorker
  139. const details = await languageService.getCompletionEntryDetails(uri.toString(), offset, wordInfo.word);
  140. if (this.isDeprecatedEntry(details)) {
  141. const deprecatedInfo = details.tags.find(this.isDeprecatedTag);
  142. markers.push({
  143. startLineNumber: match.range.startLineNumber,
  144. endLineNumber: match.range.endLineNumber,
  145. startColumn: wordInfo.startColumn,
  146. endColumn: wordInfo.endColumn,
  147. message: deprecatedInfo.text,
  148. severity: monaco.MarkerSeverity.Warning,
  149. source: source,
  150. });
  151. }
  152. }
  153. }
  154. monaco.editor.setModelMarkers(model, source, markers);
  155. }
  156. // This is our hook in the Monaco suggest adapter, we are called everytime a completion UI is displayed
  157. // So we need to be super fast.
  158. // We need the 'dev' version of Monaco, as we use monkey-patching to hook into this suggestion adapter
  159. hookMonacoCompletionProvider(provider) {
  160. const provideCompletionItems = provider.prototype.provideCompletionItems;
  161. const owner = this;
  162. provider.prototype.provideCompletionItems = async function (model, position, context, token) {
  163. // reuse 'this' to preserve context through call (using apply)
  164. const result = await provideCompletionItems.apply(this, [model, position, context, token]);
  165. if (!result || !result.suggestions)
  166. return result;
  167. const suggestions = result.suggestions.filter(item => !item.label.startsWith("_"));
  168. for (const suggestion of suggestions) {
  169. if (owner.deprecatedCandidates.includes(suggestion.label)) {
  170. // the following is time consuming on all suggestions, that's why we precompute deprecated candidate names in the definition worker to filter calls
  171. // @see setupDefinitionWorker
  172. const uri = suggestion.uri;
  173. const worker = await this._worker(uri);
  174. const model = monaco.editor.getModel(uri);
  175. const details = await worker.getCompletionEntryDetails(uri.toString(), model.getOffsetAt(position), suggestion.label)
  176. if (owner.isDeprecatedEntry(details)) {
  177. suggestion.tags = [monaco.languages.CompletionItemTag.Deprecated];
  178. }
  179. }
  180. }
  181. // preserve incomplete flag or force it when the definition is not yet analyzed
  182. const incomplete = (result.incomplete && result.incomplete == true) || owner.deprecatedCandidates.length == 0;
  183. return {
  184. suggestions: suggestions,
  185. incomplete: incomplete
  186. };
  187. }
  188. }
  189. // Setup both JS and TS compilation pipelines to work with our scripts.
  190. setupMonacoCompilationPipeline(libContent) {
  191. const typescript = monaco.languages.typescript;
  192. if (this.monacoMode === "javascript") {
  193. typescript.javascriptDefaults.setCompilerOptions({
  194. noLib: false,
  195. allowNonTsExtensions: true // required to prevent Uncaught Error: Could not find file: 'inmemory://model/1'.
  196. });
  197. typescript.javascriptDefaults.addExtraLib(libContent, 'babylon.d.ts');
  198. } else {
  199. typescript.typescriptDefaults.setCompilerOptions({
  200. module: typescript.ModuleKind.AMD,
  201. target: typescript.ScriptTarget.ESNext,
  202. noLib: false,
  203. strict: false,
  204. alwaysStrict: false,
  205. strictFunctionTypes: false,
  206. suppressExcessPropertyErrors: false,
  207. suppressImplicitAnyIndexErrors: true,
  208. noResolve: true,
  209. suppressOutputPathCheck: true,
  210. allowNonTsExtensions: true // required to prevent Uncaught Error: Could not find file: 'inmemory://model/1'.
  211. });
  212. typescript.typescriptDefaults.addExtraLib(libContent, 'babylon.d.ts');
  213. }
  214. }
  215. // Provide an adornment for BABYLON.ColorX types: color preview
  216. setupMonacoColorProvider() {
  217. monaco.languages.registerColorProvider(this.monacoMode, {
  218. provideColorPresentations: (model, colorInfo) => {
  219. const color = colorInfo.color;
  220. const precision = 100.0;
  221. const converter = (n) => Math.round(n * precision) / precision;
  222. let label;
  223. if (color.alpha === undefined || color.alpha === 1.0) {
  224. label = `(${converter(color.red)}, ${converter(color.green)}, ${converter(color.blue)})`;
  225. } else {
  226. label = `(${converter(color.red)}, ${converter(color.green)}, ${converter(color.blue)}, ${converter(color.alpha)})`;
  227. }
  228. return [{ label: label }];
  229. },
  230. provideDocumentColors: (model) => {
  231. const digitGroup = "\\s*(\\d*(?:\\.\\d+)?)\\s*";
  232. // we add \n{0} to workaround a Monaco bug, when setting regex options on their side
  233. const regex = `BABYLON\\.Color(?:3|4)\\s*\\(${digitGroup},${digitGroup},${digitGroup}(?:,${digitGroup})?\\)\\n{0}`;
  234. const matches = model.findMatches(regex, null, true, true, null, true);
  235. const converter = (g) => g === undefined ? undefined : Number(g);
  236. return matches.map(match => ({
  237. color: {
  238. red: converter(match.matches[1]),
  239. green: converter(match.matches[2]),
  240. blue: converter(match.matches[3]),
  241. alpha: converter(match.matches[4])
  242. },
  243. range: {
  244. startLineNumber: match.range.startLineNumber,
  245. startColumn: match.range.startColumn + match.matches[0].indexOf("("),
  246. endLineNumber: match.range.startLineNumber,
  247. endColumn: match.range.endColumn
  248. }
  249. }));
  250. }
  251. });
  252. }
  253. /**
  254. * Function to (re)create the editor
  255. */
  256. createMonacoEditor() {
  257. var oldCode = "";
  258. if (this.jsEditor) {
  259. oldCode = this.jsEditor.getValue();
  260. this.jsEditor.dispose();
  261. }
  262. var editorOptions = {
  263. value: "",
  264. language: this.monacoMode,
  265. lineNumbers: true,
  266. tabSize: "auto",
  267. insertSpaces: "auto",
  268. roundedSelection: true,
  269. automaticLayout: true,
  270. scrollBeyondLastLine: false,
  271. readOnly: false,
  272. theme: this.parent.settingsPG.vsTheme,
  273. contextmenu: false,
  274. folding: true,
  275. showFoldingControls: "always",
  276. renderIndentGuides: true,
  277. minimap: {
  278. enabled: true
  279. }
  280. };
  281. editorOptions.minimap.enabled = document.getElementById("minimapToggle1280").classList.contains('checked');
  282. this.jsEditor = monaco.editor.create(document.getElementById('jsEditor'), editorOptions);
  283. this.jsEditor.setValue(oldCode);
  284. // We cannot call 'analyzeCode' on every keystroke, that's time consuming
  285. // So use a debounced version to prevent over processing.
  286. // Be careful to keep the proper context for the effective call (this).
  287. const analyzeCodeDebounced = this.parent.utils.debounceAsync((async) => this.analyzeCode(), 500);
  288. this.jsEditor.onDidChangeModelContent(function () {
  289. this.parent.utils.markDirty();
  290. analyzeCodeDebounced();
  291. }.bind(this));
  292. };
  293. detectLanguage(text) {
  294. return text && text.indexOf("class Playground") >= 0 ? "typescript" : "javascript";
  295. }
  296. createDiff(left, right, diffView) {
  297. const language = this.detectLanguage(left);
  298. let leftModel = monaco.editor.createModel(left, language);
  299. let rightModel = monaco.editor.createModel(right, language);
  300. const diffOptions = {
  301. contextmenu: false,
  302. lineNumbers: true,
  303. readOnly: true,
  304. theme: this.parent.settingsPG.vsTheme,
  305. contextmenu: false,
  306. fontSize: this.parent.settingsPG.fontSize
  307. }
  308. this.diffEditor = monaco.editor.createDiffEditor(diffView, diffOptions);
  309. this.diffEditor.setModel({
  310. original: leftModel,
  311. modified: rightModel
  312. });
  313. this.diffNavigator = monaco.editor.createDiffNavigator(this.diffEditor, {
  314. followsCaret: true,
  315. ignoreCharChanges: true
  316. });
  317. const menuPG = this.parent.menuPG;
  318. const main = this.parent.main;
  319. const monacoCreator = this;
  320. this.diffEditor.addCommand(monaco.KeyCode.Escape, function () { main.toggleDiffEditor(monacoCreator, menuPG); });
  321. // Adding default VSCode bindinds for previous/next difference
  322. this.diffEditor.addCommand(monaco.KeyMod.Alt | monaco.KeyCode.F5, function () { main.navigateToNext(); });
  323. this.diffEditor.addCommand(monaco.KeyMod.Shift | monaco.KeyMod.Alt | monaco.KeyCode.F5, function () { main.navigateToPrevious(); });
  324. this.diffEditor.focus();
  325. }
  326. disposeDiff() {
  327. if (!this.diffEditor)
  328. return;
  329. // We need to properly dispose, else the monaco script editor will use those models in the editor compilation pipeline!
  330. let model = this.diffEditor.getModel();
  331. let leftModel = model.original;
  332. let rightModel = model.modified;
  333. leftModel.dispose();
  334. rightModel.dispose();
  335. this.diffNavigator.dispose();
  336. this.diffEditor.dispose();
  337. this.diffNavigator = null;
  338. this.diffEditor = null;
  339. }
  340. /**
  341. * Format the code in the editor
  342. */
  343. formatCode() {
  344. this.jsEditor.getAction('editor.action.formatDocument').run();
  345. };
  346. /**
  347. * Toggle the minimap
  348. */
  349. toggleMinimap() {
  350. var minimapToggle = document.getElementById("minimapToggle1280");
  351. if (minimapToggle.classList.contains('checked')) {
  352. this.jsEditor.updateOptions({ minimap: { enabled: false } });
  353. this.parent.utils.setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-square" aria-hidden="true"></i>');
  354. } else {
  355. this.jsEditor.updateOptions({ minimap: { enabled: true } });
  356. this.parent.utils.setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-check-square" aria-hidden="true"></i>');
  357. }
  358. minimapToggle.classList.toggle('checked');
  359. };
  360. /**
  361. * Get the code in the editor
  362. */
  363. async getRunCode() {
  364. var parent = this.parent;
  365. if (parent.settingsPG.ScriptLanguage == "JS")
  366. return this.jsEditor.getValue();
  367. else if (parent.settingsPG.ScriptLanguage == "TS") {
  368. const model = this.jsEditor.getModel();
  369. const uri = model.uri;
  370. const worker = await monaco.languages.typescript.getTypeScriptWorker();
  371. const languageService = await worker(uri);
  372. const uriStr = uri.toString();
  373. const result = await languageService.getEmitOutput(uriStr);
  374. const diagnostics = await Promise.all([languageService.getSyntacticDiagnostics(uriStr), languageService.getSemanticDiagnostics(uriStr)]);
  375. diagnostics.forEach(function (diagset) {
  376. if (diagset.length) {
  377. const diagnostic = diagset[0];
  378. const position = model.getPositionAt(diagnostic.start);
  379. const error = new EvalError(diagnostic.messageText);
  380. error.lineNumber = position.lineNumber;
  381. error.columnNumber = position.column;
  382. throw error;
  383. }
  384. });
  385. const output = result.outputFiles[0].text;
  386. const stub = "var createScene = function() { return Playground.CreateScene(engine, engine.getRenderingCanvas()); }";
  387. return output + stub;
  388. }
  389. };
  390. };