monacoCreator.js 15 KB

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