monacoCreator.js 18 KB

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