monacoCreator.js 12 KB

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