monacoCreator.js 22 KB

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