monacoCreator.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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.ES5,
  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. var 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. /**
  146. * Format the code in the editor
  147. */
  148. formatCode () {
  149. this.jsEditor.getAction('editor.action.formatDocument').run();
  150. };
  151. /**
  152. * Toggle the minimap
  153. */
  154. toggleMinimap () {
  155. var minimapToggle = document.getElementById("minimapToggle1280");
  156. if (minimapToggle.classList.contains('checked')) {
  157. this.jsEditor.updateOptions({ minimap: { enabled: false } });
  158. this.parent.utils.setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-square" aria-hidden="true"></i>');
  159. } else {
  160. this.jsEditor.updateOptions({ minimap: { enabled: true } });
  161. this.parent.utils.setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-check-square" aria-hidden="true"></i>');
  162. }
  163. minimapToggle.classList.toggle('checked');
  164. };
  165. /**
  166. * Get the code in the editor
  167. */
  168. async getRunCode() {
  169. var parent = this.parent;
  170. if (parent.settingsPG.ScriptLanguage == "JS")
  171. return this.jsEditor.getValue();
  172. else if (parent.settingsPG.ScriptLanguage == "TS") {
  173. const model = this.jsEditor.getModel();
  174. const uri = model.uri;
  175. const worker = await monaco.languages.typescript.getTypeScriptWorker();
  176. const languageService = await worker(uri);
  177. const uriStr = uri.toString();
  178. const result = await languageService.getEmitOutput(uriStr);
  179. const diagnostics = await Promise.all([languageService.getSyntacticDiagnostics(uriStr), languageService.getSemanticDiagnostics(uriStr)]);
  180. diagnostics.forEach(function(diagset) {
  181. if (diagset.length) {
  182. const diagnostic = diagset[0];
  183. const position = model.getPositionAt(diagnostic.start);
  184. const error = new EvalError(diagnostic.messageText);
  185. error.lineNumber = position.lineNumber;
  186. error.columnNumber = position.column;
  187. throw error;
  188. }
  189. });
  190. const output = result.outputFiles[0].text;
  191. const stub = "var createScene = function() { return Playground.CreateScene(engine, engine.getRenderingCanvas()); }";
  192. return output + stub;
  193. }
  194. };
  195. };