monacoCreator.js 22 KB

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