monacoCreator.js 21 KB

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