monacoCreator.js 16 KB

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