monacoCreator.js 12 KB

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