monacoCreator.js 9.7 KB

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