monacoCreator.js 20 KB

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