monacoCreator.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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.compilerTriggerTimeoutID = null;
  13. }
  14. // ACCESSORS
  15. get JsEditor() {
  16. return this.jsEditor;
  17. };
  18. getCode() {
  19. if(this.jsEditor) return this.jsEditor.getValue();
  20. else return "";
  21. };
  22. setCode(value) {
  23. this.jsEditor.setValue(value);
  24. };
  25. get MonacoMode() {
  26. return this.monacoMode;
  27. };
  28. set MonacoMode(mode) {
  29. if (this.monacoMode != "javascript"
  30. && this.monacoMode != "typescript")
  31. console.warn("Error while defining Monaco Mode");
  32. this.monacoMode = mode;
  33. };
  34. get BlockEditorChange() {
  35. return this.blockEditorChange;
  36. };
  37. set BlockEditorChange(value) {
  38. this.blockEditorChange = value;
  39. };
  40. // FUNCTIONS
  41. /**
  42. * Load the Monaco Node module.
  43. */
  44. async loadMonaco(typings) {
  45. let response = await fetch(typings || "babylon.d.txt");
  46. if (!response.ok)
  47. return;
  48. const libContent = await response.text();
  49. require.config({ paths: { 'vs': 'node_modules/monaco-editor/dev/vs' } });
  50. require(['vs/editor/editor.main'], () => {
  51. this.setupMonacoCompilationPipeline(libContent);
  52. this.setupMonacoColorProvider();
  53. require(['vs/language/typescript/languageFeatures'], module => {
  54. this.hookMonacoCompletionProvider(module.SuggestAdapter);
  55. });
  56. this.parent.main.run();
  57. });
  58. };
  59. hookMonacoCompletionProvider(provider) {
  60. const hooked = provider.prototype.provideCompletionItems;
  61. const suggestionFilter = function(suggestion) {
  62. return !suggestion.label.startsWith("_");
  63. }
  64. provider.prototype.provideCompletionItems = function(model, position, context, token) {
  65. // reuse 'this' to preserve context through call (using apply)
  66. return hooked
  67. .apply(this, [model, position, context, token])
  68. .then(result => {
  69. return { suggestions: result.suggestions.filter(suggestionFilter)};
  70. });
  71. }
  72. }
  73. setupMonacoCompilationPipeline(libContent) {
  74. const typescript = monaco.languages.typescript;
  75. if (this.monacoMode === "javascript") {
  76. typescript.javascriptDefaults.setCompilerOptions({
  77. noLib: false,
  78. allowNonTsExtensions: true // required to prevent Uncaught Error: Could not find file: 'inmemory://model/1'.
  79. });
  80. typescript.javascriptDefaults.addExtraLib(libContent, 'babylon.d.ts');
  81. } else {
  82. typescript.typescriptDefaults.setCompilerOptions({
  83. module: typescript.ModuleKind.AMD,
  84. target: typescript.ScriptTarget.ESNext,
  85. noLib: false,
  86. strict: false,
  87. alwaysStrict: false,
  88. strictFunctionTypes: false,
  89. suppressExcessPropertyErrors: false,
  90. suppressImplicitAnyIndexErrors: true,
  91. noResolve: true,
  92. suppressOutputPathCheck: true,
  93. allowNonTsExtensions: true // required to prevent Uncaught Error: Could not find file: 'inmemory://model/1'.
  94. });
  95. typescript.typescriptDefaults.addExtraLib(libContent, 'babylon.d.ts');
  96. }
  97. }
  98. setupMonacoColorProvider() {
  99. monaco.languages.registerColorProvider(this.monacoMode, {
  100. provideColorPresentations: (model, colorInfo) => {
  101. const color = colorInfo.color;
  102. const precision = 100.0;
  103. const converter = (n) => Math.round(n * precision) / precision;
  104. let label;
  105. if (color.alpha === undefined || color.alpha === 1.0) {
  106. label = `(${converter(color.red)}, ${converter(color.green)}, ${converter(color.blue)})`;
  107. } else {
  108. label = `(${converter(color.red)}, ${converter(color.green)}, ${converter(color.blue)}, ${converter(color.alpha)})`;
  109. }
  110. return [ { label: label } ];
  111. },
  112. provideDocumentColors: (model) => {
  113. const digitGroup = "\\s*(\\d*(?:\\.\\d+)?)\\s*";
  114. // we add \n{0} to workaround a Monaco bug, when setting regex options on their side
  115. const regex = `BABYLON\\.Color(?:3|4)\\s*\\(${digitGroup},${digitGroup},${digitGroup}(?:,${digitGroup})?\\)\\n{0}`;
  116. const matches = model.findMatches(regex, null, true, true, null, true);
  117. const converter = (g) => g === undefined ? undefined : Number(g);
  118. return matches.map(match => ({
  119. color: {
  120. red: converter(match.matches[1]),
  121. green: converter(match.matches[2]),
  122. blue: converter(match.matches[3]),
  123. alpha: converter(match.matches[4])
  124. },
  125. range:{
  126. startLineNumber: match.range.startLineNumber,
  127. startColumn: match.range.startColumn + match.matches[0].indexOf("("),
  128. endLineNumber: match.range.startLineNumber,
  129. endColumn: match.range.endColumn
  130. }
  131. }));
  132. }
  133. });
  134. }
  135. /**
  136. * Function to (re)create the editor
  137. */
  138. createMonacoEditor() {
  139. var oldCode = "";
  140. if (this.jsEditor) {
  141. oldCode = this.jsEditor.getValue();
  142. this.jsEditor.dispose();
  143. }
  144. var editorOptions = {
  145. value: "",
  146. language: this.monacoMode,
  147. lineNumbers: true,
  148. tabSize: "auto",
  149. insertSpaces: "auto",
  150. roundedSelection: true,
  151. automaticLayout: true,
  152. scrollBeyondLastLine: false,
  153. readOnly: false,
  154. theme: this.parent.settingsPG.vsTheme,
  155. contextmenu: false,
  156. folding: true,
  157. showFoldingControls: "always",
  158. renderIndentGuides: true,
  159. minimap: {
  160. enabled: true
  161. }
  162. };
  163. editorOptions.minimap.enabled = document.getElementById("minimapToggle1280").classList.contains('checked');
  164. this.jsEditor = monaco.editor.create(document.getElementById('jsEditor'), editorOptions);
  165. this.jsEditor.setValue(oldCode);
  166. this.jsEditor.onKeyUp(function () {
  167. this.parent.utils.markDirty();
  168. }.bind(this));
  169. };
  170. detectLanguage(text) {
  171. return text && text.indexOf("class Playground") >= 0 ? "typescript" : "javascript";
  172. }
  173. createDiff(left, right, diffView) {
  174. const language = this.detectLanguage(left);
  175. let leftModel = monaco.editor.createModel(left, language);
  176. let rightModel = monaco.editor.createModel(right, language);
  177. const diffOptions = {
  178. contextmenu: false,
  179. lineNumbers: true,
  180. readOnly: true,
  181. theme: this.parent.settingsPG.vsTheme,
  182. contextmenu: false,
  183. fontSize: this.parent.settingsPG.fontSize
  184. }
  185. this.diffEditor = monaco.editor.createDiffEditor(diffView, diffOptions);
  186. this.diffEditor.setModel({
  187. original: leftModel,
  188. modified: rightModel
  189. });
  190. this.diffNavigator = monaco.editor.createDiffNavigator(this.diffEditor, {
  191. followsCaret: true,
  192. ignoreCharChanges: true
  193. });
  194. const menuPG = this.parent.menuPG;
  195. const main = this.parent.main;
  196. const monacoCreator = this;
  197. this.diffEditor.addCommand(monaco.KeyCode.Escape, function() { main.toggleDiffEditor(monacoCreator, menuPG); });
  198. // Adding default VSCode bindinds for previous/next difference
  199. this.diffEditor.addCommand(monaco.KeyMod.Alt | monaco.KeyCode.F5, function() { main.navigateToNext(); });
  200. this.diffEditor.addCommand(monaco.KeyMod.Shift | monaco.KeyMod.Alt | monaco.KeyCode.F5, function() { main.navigateToPrevious(); });
  201. this.diffEditor.focus();
  202. }
  203. disposeDiff() {
  204. if (!this.diffEditor)
  205. return;
  206. // We need to properly dispose, else the monaco script editor will use those models in the editor compilation pipeline!
  207. let model = this.diffEditor.getModel();
  208. let leftModel = model.original;
  209. let rightModel = model.modified;
  210. leftModel.dispose();
  211. rightModel.dispose();
  212. this.diffNavigator.dispose();
  213. this.diffEditor.dispose();
  214. this.diffNavigator = null;
  215. this.diffEditor = null;
  216. }
  217. /**
  218. * Format the code in the editor
  219. */
  220. formatCode () {
  221. this.jsEditor.getAction('editor.action.formatDocument').run();
  222. };
  223. /**
  224. * Toggle the minimap
  225. */
  226. toggleMinimap () {
  227. var minimapToggle = document.getElementById("minimapToggle1280");
  228. if (minimapToggle.classList.contains('checked')) {
  229. this.jsEditor.updateOptions({ minimap: { enabled: false } });
  230. this.parent.utils.setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-square" aria-hidden="true"></i>');
  231. } else {
  232. this.jsEditor.updateOptions({ minimap: { enabled: true } });
  233. this.parent.utils.setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-check-square" aria-hidden="true"></i>');
  234. }
  235. minimapToggle.classList.toggle('checked');
  236. };
  237. /**
  238. * Get the code in the editor
  239. */
  240. async getRunCode() {
  241. var parent = this.parent;
  242. if (parent.settingsPG.ScriptLanguage == "JS")
  243. return this.jsEditor.getValue();
  244. else if (parent.settingsPG.ScriptLanguage == "TS") {
  245. const model = this.jsEditor.getModel();
  246. const uri = model.uri;
  247. const worker = await monaco.languages.typescript.getTypeScriptWorker();
  248. const languageService = await worker(uri);
  249. const uriStr = uri.toString();
  250. const result = await languageService.getEmitOutput(uriStr);
  251. const diagnostics = await Promise.all([languageService.getSyntacticDiagnostics(uriStr), languageService.getSemanticDiagnostics(uriStr)]);
  252. diagnostics.forEach(function(diagset) {
  253. if (diagset.length) {
  254. const diagnostic = diagset[0];
  255. const position = model.getPositionAt(diagnostic.start);
  256. const error = new EvalError(diagnostic.messageText);
  257. error.lineNumber = position.lineNumber;
  258. error.columnNumber = position.column;
  259. throw error;
  260. }
  261. });
  262. const output = result.outputFiles[0].text;
  263. const stub = "var createScene = function() { return Playground.CreateScene(engine, engine.getRenderingCanvas()); }";
  264. return output + stub;
  265. }
  266. };
  267. };