monacoCreator.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /**
  2. * This JS file is for Monaco management
  3. */
  4. class MonacoCreator {
  5. constructor(parent) {
  6. this.parent = parent;
  7. this.jsEditor = null;
  8. this.diffEditor = null;
  9. this.diffNavigator = null;
  10. this.monacoMode = "javascript";
  11. this.blockEditorChange = false;
  12. this.definitionWorker = null;
  13. this.deprecatedCandidates = [];
  14. this.compilerTriggerTimeoutID = null;
  15. }
  16. // ACCESSORS
  17. get JsEditor() {
  18. return this.jsEditor;
  19. };
  20. getCode() {
  21. if (this.jsEditor) return this.jsEditor.getValue();
  22. else return "";
  23. };
  24. setCode(value) {
  25. this.jsEditor.setValue(value);
  26. };
  27. get MonacoMode() {
  28. return this.monacoMode;
  29. };
  30. set MonacoMode(mode) {
  31. if (this.monacoMode != "javascript"
  32. && this.monacoMode != "typescript")
  33. console.warn("Error while defining Monaco Mode");
  34. this.monacoMode = mode;
  35. };
  36. get BlockEditorChange() {
  37. return this.blockEditorChange;
  38. };
  39. set BlockEditorChange(value) {
  40. this.blockEditorChange = value;
  41. };
  42. // FUNCTIONS
  43. /**
  44. * Load the Monaco Node module.
  45. */
  46. async loadMonaco(typings) {
  47. let response = await fetch(typings || "https://preview.babylonjs.com/babylon.d.ts");
  48. if (!response.ok) {
  49. return;
  50. }
  51. let libContent = await response.text();
  52. if (!typings) {
  53. response = await fetch(typings || "https://preview.babylonjs.com/gui/babylon.gui.d.ts");
  54. if (!response.ok) {
  55. return;
  56. }
  57. libContent += await response.text();
  58. }
  59. this.setupDefinitionWorker(libContent);
  60. require.config({ paths: { 'vs': '/node_modules/monaco-editor/dev/vs' } });
  61. require(['vs/editor/editor.main'], () => {
  62. this.setupMonacoCompilationPipeline(libContent);
  63. this.setupMonacoColorProvider();
  64. require(['vs/language/typescript/languageFeatures'], module => {
  65. this.hookMonacoCompletionProvider(module.SuggestAdapter);
  66. });
  67. this.parent.main.run();
  68. });
  69. };
  70. setupDefinitionWorker(libContent) {
  71. // This worker can be initialized differently.
  72. // Its main job is to analyze the code and return an array of deprecated functions
  73. this.definitionWorker = new Worker('/js/definitionWorker.js');
  74. this.definitionWorker.addEventListener('message', ({ data }) => {
  75. this.deprecatedCandidates = data.result;
  76. this.analyzeCode();
  77. });
  78. this.definitionWorker.postMessage({ code: libContent });
  79. // this.deprecatedCandidates = [
  80. // "FromFloatArray",
  81. // "FromFloatArrayToRef",
  82. // "getStrideSize",
  83. // "getStrideSize",
  84. // "getOffset",
  85. // "rgb",
  86. // "xy",
  87. // "xyz",
  88. // "fieldOfView"
  89. // ];
  90. }
  91. isDeprecatedEntry(details) {
  92. return details
  93. && details.tags
  94. && details.tags.find(this.isDeprecatedTag);
  95. }
  96. isDeprecatedTag(tag) {
  97. return tag
  98. && tag.name == "deprecated";
  99. }
  100. async analyzeCode() {
  101. // if the definition worker is very fast, this can be called out of context
  102. if (!this.jsEditor)
  103. return;
  104. const model = this.jsEditor.getModel();
  105. if (!model)
  106. return;
  107. const uri = model.uri;
  108. let worker = null;
  109. if (this.parent.settingsPG.ScriptLanguage == "JS")
  110. worker = await monaco.languages.typescript.getJavaScriptWorker();
  111. else
  112. worker = await monaco.languages.typescript.getTypeScriptWorker();
  113. const languageService = await worker(uri);
  114. const source = '[deprecated members]';
  115. monaco.editor.setModelMarkers(model, source, []);
  116. const markers = [];
  117. for (const candidate of this.deprecatedCandidates) {
  118. const matches = model.findMatches(candidate, null, false, true, null, false);
  119. for (const match of matches) {
  120. const position = { lineNumber: match.range.startLineNumber, column: match.range.startColumn };
  121. const wordInfo = model.getWordAtPosition(position);
  122. const offset = model.getOffsetAt(position);
  123. // continue if we already found an issue here
  124. if (markers.find(m => m.startLineNumber == position.lineNumber && m.startColumn == position.column))
  125. continue;
  126. // the following is time consuming on all suggestions, that's why we precompute deprecated candidate names in the definition worker to filter calls
  127. const details = await languageService.getCompletionEntryDetails(uri.toString(), offset, wordInfo.word);
  128. if (this.isDeprecatedEntry(details)) {
  129. const deprecatedInfo = details.tags.find(this.isDeprecatedTag);
  130. markers.push({
  131. startLineNumber: match.range.startLineNumber,
  132. endLineNumber: match.range.endLineNumber,
  133. startColumn: wordInfo.startColumn,
  134. endColumn: wordInfo.endColumn,
  135. message: deprecatedInfo.text,
  136. severity: monaco.MarkerSeverity.Warning,
  137. source: source,
  138. });
  139. }
  140. }
  141. }
  142. monaco.editor.setModelMarkers(model, source, markers);
  143. }
  144. hookMonacoCompletionProvider(provider) {
  145. const provideCompletionItems = provider.prototype.provideCompletionItems;
  146. const owner = this;
  147. provider.prototype.provideCompletionItems = async function (model, position, context, token) {
  148. // reuse 'this' to preserve context through call (using apply)
  149. const result = await provideCompletionItems.apply(this, [model, position, context, token]);
  150. if (!result || !result.suggestions)
  151. return result;
  152. const suggestions = result.suggestions.filter(item => !item.label.startsWith("_"));
  153. for (const suggestion of suggestions) {
  154. if (owner.deprecatedCandidates.includes(suggestion.label)) {
  155. // the following is time consuming on all suggestions, that's why we precompute deprecated candidate names in the definition worker to filter calls
  156. const uri = suggestion.uri;
  157. const worker = await this._worker(uri);
  158. const model = monaco.editor.getModel(uri);
  159. const details = await worker.getCompletionEntryDetails(uri.toString(), model.getOffsetAt(position), suggestion.label)
  160. if (owner.isDeprecatedEntry(details)) {
  161. suggestion.tags = [monaco.languages.CompletionItemTag.Deprecated];
  162. }
  163. }
  164. }
  165. // preserve incomplete flag or force it when the definition is not yet analyzed
  166. const incomplete = (result.incomplete && result.incomplete == true) || owner.deprecatedCandidates.length == 0;
  167. return {
  168. suggestions: suggestions,
  169. incomplete: incomplete
  170. };
  171. }
  172. }
  173. setupMonacoCompilationPipeline(libContent) {
  174. const typescript = monaco.languages.typescript;
  175. if (this.monacoMode === "javascript") {
  176. typescript.javascriptDefaults.setCompilerOptions({
  177. noLib: false,
  178. allowNonTsExtensions: true // required to prevent Uncaught Error: Could not find file: 'inmemory://model/1'.
  179. });
  180. typescript.javascriptDefaults.addExtraLib(libContent, 'babylon.d.ts');
  181. } else {
  182. typescript.typescriptDefaults.setCompilerOptions({
  183. module: typescript.ModuleKind.AMD,
  184. target: typescript.ScriptTarget.ESNext,
  185. noLib: false,
  186. strict: false,
  187. alwaysStrict: false,
  188. strictFunctionTypes: false,
  189. suppressExcessPropertyErrors: false,
  190. suppressImplicitAnyIndexErrors: true,
  191. noResolve: true,
  192. suppressOutputPathCheck: true,
  193. allowNonTsExtensions: true // required to prevent Uncaught Error: Could not find file: 'inmemory://model/1'.
  194. });
  195. typescript.typescriptDefaults.addExtraLib(libContent, 'babylon.d.ts');
  196. }
  197. }
  198. setupMonacoColorProvider() {
  199. monaco.languages.registerColorProvider(this.monacoMode, {
  200. provideColorPresentations: (model, colorInfo) => {
  201. const color = colorInfo.color;
  202. const precision = 100.0;
  203. const converter = (n) => Math.round(n * precision) / precision;
  204. let label;
  205. if (color.alpha === undefined || color.alpha === 1.0) {
  206. label = `(${converter(color.red)}, ${converter(color.green)}, ${converter(color.blue)})`;
  207. } else {
  208. label = `(${converter(color.red)}, ${converter(color.green)}, ${converter(color.blue)}, ${converter(color.alpha)})`;
  209. }
  210. return [{ label: label }];
  211. },
  212. provideDocumentColors: (model) => {
  213. const digitGroup = "\\s*(\\d*(?:\\.\\d+)?)\\s*";
  214. // we add \n{0} to workaround a Monaco bug, when setting regex options on their side
  215. const regex = `BABYLON\\.Color(?:3|4)\\s*\\(${digitGroup},${digitGroup},${digitGroup}(?:,${digitGroup})?\\)\\n{0}`;
  216. const matches = model.findMatches(regex, null, true, true, null, true);
  217. const converter = (g) => g === undefined ? undefined : Number(g);
  218. return matches.map(match => ({
  219. color: {
  220. red: converter(match.matches[1]),
  221. green: converter(match.matches[2]),
  222. blue: converter(match.matches[3]),
  223. alpha: converter(match.matches[4])
  224. },
  225. range: {
  226. startLineNumber: match.range.startLineNumber,
  227. startColumn: match.range.startColumn + match.matches[0].indexOf("("),
  228. endLineNumber: match.range.startLineNumber,
  229. endColumn: match.range.endColumn
  230. }
  231. }));
  232. }
  233. });
  234. }
  235. /**
  236. * Function to (re)create the editor
  237. */
  238. createMonacoEditor() {
  239. var oldCode = "";
  240. if (this.jsEditor) {
  241. oldCode = this.jsEditor.getValue();
  242. this.jsEditor.dispose();
  243. }
  244. var editorOptions = {
  245. value: "",
  246. language: this.monacoMode,
  247. lineNumbers: true,
  248. tabSize: "auto",
  249. insertSpaces: "auto",
  250. roundedSelection: true,
  251. automaticLayout: true,
  252. scrollBeyondLastLine: false,
  253. readOnly: false,
  254. theme: this.parent.settingsPG.vsTheme,
  255. contextmenu: false,
  256. folding: true,
  257. showFoldingControls: "always",
  258. renderIndentGuides: true,
  259. minimap: {
  260. enabled: true
  261. }
  262. };
  263. editorOptions.minimap.enabled = document.getElementById("minimapToggle1280").classList.contains('checked');
  264. this.jsEditor = monaco.editor.create(document.getElementById('jsEditor'), editorOptions);
  265. this.jsEditor.setValue(oldCode);
  266. const analyzeCodeDebounced = this.parent.utils.debounceAsync((async) => this.analyzeCode(), 500);
  267. this.jsEditor.onDidChangeModelContent(function () {
  268. this.parent.utils.markDirty();
  269. analyzeCodeDebounced();
  270. }.bind(this));
  271. };
  272. detectLanguage(text) {
  273. return text && text.indexOf("class Playground") >= 0 ? "typescript" : "javascript";
  274. }
  275. createDiff(left, right, diffView) {
  276. const language = this.detectLanguage(left);
  277. let leftModel = monaco.editor.createModel(left, language);
  278. let rightModel = monaco.editor.createModel(right, language);
  279. const diffOptions = {
  280. contextmenu: false,
  281. lineNumbers: true,
  282. readOnly: true,
  283. theme: this.parent.settingsPG.vsTheme,
  284. contextmenu: false,
  285. fontSize: this.parent.settingsPG.fontSize
  286. }
  287. this.diffEditor = monaco.editor.createDiffEditor(diffView, diffOptions);
  288. this.diffEditor.setModel({
  289. original: leftModel,
  290. modified: rightModel
  291. });
  292. this.diffNavigator = monaco.editor.createDiffNavigator(this.diffEditor, {
  293. followsCaret: true,
  294. ignoreCharChanges: true
  295. });
  296. const menuPG = this.parent.menuPG;
  297. const main = this.parent.main;
  298. const monacoCreator = this;
  299. this.diffEditor.addCommand(monaco.KeyCode.Escape, function () { main.toggleDiffEditor(monacoCreator, menuPG); });
  300. // Adding default VSCode bindinds for previous/next difference
  301. this.diffEditor.addCommand(monaco.KeyMod.Alt | monaco.KeyCode.F5, function () { main.navigateToNext(); });
  302. this.diffEditor.addCommand(monaco.KeyMod.Shift | monaco.KeyMod.Alt | monaco.KeyCode.F5, function () { main.navigateToPrevious(); });
  303. this.diffEditor.focus();
  304. }
  305. disposeDiff() {
  306. if (!this.diffEditor)
  307. return;
  308. // We need to properly dispose, else the monaco script editor will use those models in the editor compilation pipeline!
  309. let model = this.diffEditor.getModel();
  310. let leftModel = model.original;
  311. let rightModel = model.modified;
  312. leftModel.dispose();
  313. rightModel.dispose();
  314. this.diffNavigator.dispose();
  315. this.diffEditor.dispose();
  316. this.diffNavigator = null;
  317. this.diffEditor = null;
  318. }
  319. /**
  320. * Format the code in the editor
  321. */
  322. formatCode() {
  323. this.jsEditor.getAction('editor.action.formatDocument').run();
  324. };
  325. /**
  326. * Toggle the minimap
  327. */
  328. toggleMinimap() {
  329. var minimapToggle = document.getElementById("minimapToggle1280");
  330. if (minimapToggle.classList.contains('checked')) {
  331. this.jsEditor.updateOptions({ minimap: { enabled: false } });
  332. this.parent.utils.setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-square" aria-hidden="true"></i>');
  333. } else {
  334. this.jsEditor.updateOptions({ minimap: { enabled: true } });
  335. this.parent.utils.setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-check-square" aria-hidden="true"></i>');
  336. }
  337. minimapToggle.classList.toggle('checked');
  338. };
  339. /**
  340. * Get the code in the editor
  341. */
  342. async getRunCode() {
  343. var parent = this.parent;
  344. if (parent.settingsPG.ScriptLanguage == "JS")
  345. return this.jsEditor.getValue();
  346. else if (parent.settingsPG.ScriptLanguage == "TS") {
  347. const model = this.jsEditor.getModel();
  348. const uri = model.uri;
  349. const worker = await monaco.languages.typescript.getTypeScriptWorker();
  350. const languageService = await worker(uri);
  351. const uriStr = uri.toString();
  352. const result = await languageService.getEmitOutput(uriStr);
  353. const diagnostics = await Promise.all([languageService.getSyntacticDiagnostics(uriStr), languageService.getSemanticDiagnostics(uriStr)]);
  354. diagnostics.forEach(function (diagset) {
  355. if (diagset.length) {
  356. const diagnostic = diagset[0];
  357. const position = model.getPositionAt(diagnostic.start);
  358. const error = new EvalError(diagnostic.messageText);
  359. error.lineNumber = position.lineNumber;
  360. error.columnNumber = position.column;
  361. throw error;
  362. }
  363. });
  364. const output = result.outputFiles[0].text;
  365. const stub = "var createScene = function() { return Playground.CreateScene(engine, engine.getRenderingCanvas()); }";
  366. return output + stub;
  367. }
  368. };
  369. };