monacoCreator.js 9.7 KB

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