monacoCreator.js 21 KB

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