monacoManager.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. import * as monaco from "monaco-editor/esm/vs/editor/editor.api";
  2. // import 'monaco-editor/esm/vs/basic-languages/typescript/typescript.contribution';
  3. // import 'monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution';
  4. import * as languageFeatures from "monaco-editor/esm/vs/language/typescript/languageFeatures";
  5. import { GlobalState } from "../globalState";
  6. import { Utilities } from "./utilities";
  7. import { CompilationError } from "../components/errorDisplayComponent";
  8. declare type IStandaloneCodeEditor = import("monaco-editor/esm/vs/editor/editor.api").editor.IStandaloneCodeEditor;
  9. declare type IStandaloneEditorConstructionOptions = import("monaco-editor/esm/vs/editor/editor.api").editor.IStandaloneEditorConstructionOptions;
  10. //declare var monaco: any;
  11. export class MonacoManager {
  12. private _editor: IStandaloneCodeEditor;
  13. private _definitionWorker: Worker;
  14. private _deprecatedCandidates: string[];
  15. private _hostElement: HTMLDivElement;
  16. private _templates: {
  17. label: string;
  18. language: string;
  19. kind: number;
  20. sortText: string;
  21. insertTextRules: number;
  22. }[];
  23. private _isDirty = false;
  24. public constructor(public globalState: GlobalState) {
  25. window.addEventListener("beforeunload", (evt) => {
  26. if (this._isDirty && Utilities.ReadBoolFromStore("safe-mode", false)) {
  27. var message = "Are you sure you want to leave. You have unsaved work.";
  28. evt.preventDefault();
  29. evt.returnValue = message;
  30. }
  31. });
  32. globalState.onNewRequiredObservable.add(() => {
  33. if (Utilities.CheckSafeMode("Are you sure you want to create a new playground?")) {
  34. this._setNewContent();
  35. this._isDirty = true;
  36. }
  37. });
  38. globalState.onClearRequiredObservable.add(() => {
  39. if (Utilities.CheckSafeMode("Are you sure you want to remove all your code?")) {
  40. this._editor?.setValue("");
  41. location.hash = "";
  42. this._isDirty = true;
  43. }
  44. });
  45. globalState.onNavigateRequiredObservable.add((position) => {
  46. this._editor?.revealPositionInCenter(position, monaco.editor.ScrollType.Smooth);
  47. this._editor?.setPosition(position);
  48. });
  49. globalState.onSavedObservable.add(() => {
  50. this._isDirty = false;
  51. });
  52. globalState.onCodeLoaded.add((code) => {
  53. if (!code) {
  54. this._setDefaultContent();
  55. return;
  56. }
  57. if (this._editor) {
  58. this._editor?.setValue(code);
  59. this._isDirty = false;
  60. this.globalState.onRunRequiredObservable.notifyObservers();
  61. } else {
  62. this.globalState.currentCode = code;
  63. }
  64. });
  65. globalState.onFormatCodeRequiredObservable.add(() => {
  66. this._editor?.getAction("editor.action.formatDocument").run();
  67. });
  68. globalState.onMinimapChangedObservable.add((value) => {
  69. this._editor?.updateOptions({
  70. minimap: {
  71. enabled: value,
  72. },
  73. });
  74. });
  75. globalState.onFontSizeChangedObservable.add((value) => {
  76. this._editor?.updateOptions({
  77. fontSize: parseInt(Utilities.ReadStringFromStore("font-size", "14")),
  78. });
  79. });
  80. globalState.onLanguageChangedObservable.add(async () => {
  81. await this.setupMonacoAsync(this._hostElement);
  82. });
  83. globalState.onThemeChangedObservable.add(() => {
  84. this._createEditor();
  85. });
  86. // Register a global observable for inspector to request code changes
  87. let pgConnect = {
  88. onRequestCodeChangeObservable: new BABYLON.Observable(),
  89. };
  90. pgConnect.onRequestCodeChangeObservable.add((options: any) => {
  91. let code = this._editor?.getValue() || "";
  92. code = code.replace(options.regex, options.replace);
  93. this._editor?.setValue(code);
  94. });
  95. (window as any).Playground = pgConnect;
  96. }
  97. private _setNewContent() {
  98. this._createEditor();
  99. if(this.globalState.language === "JS"){
  100. this._editor?.setValue(`// You have to create a function called createScene. This function must return a BABYLON.Scene object
  101. // You can reference the following variables: engine, canvas
  102. // You must at least define a camera
  103. var createScene = function() {
  104. var scene = new BABYLON.Scene(engine);
  105. //var camera = new BABYLON.ArcRotateCamera("Camera", -Math.PI / 2, Math.PI / 2, 12, BABYLON.Vector3.Zero(), scene);
  106. var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);
  107. // This targets the camera to scene origin
  108. camera.setTarget(BABYLON.Vector3.Zero());
  109. // This attaches the camera to the canvas
  110. camera.attachControl(canvas, true);
  111. return scene;
  112. };`);
  113. } else {
  114. this._editor?.setValue(`// You have to create a class called Playground. This class must provide a static function named CreateScene(engine, canvas) which must return a Scene object
  115. // You must at least define a camera inside the CreateScene function
  116. class Playground {
  117. public static CreateScene(engine: BABYLON.Engine, canvas: HTMLCanvasElement): BABYLON.Scene {
  118. var scene = new BABYLON.Scene(engine);
  119. //var camera = new BABYLON.ArcRotateCamera("Camera", -Math.PI / 2, Math.PI / 2, 12, BABYLON.Vector3.Zero(), scene);
  120. var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);
  121. // This targets the camera to scene origin
  122. camera.setTarget(BABYLON.Vector3.Zero());
  123. // This attaches the camera to the canvas
  124. camera.attachControl(canvas, true);
  125. return scene;
  126. }
  127. }`);
  128. }
  129. this.globalState.onRunRequiredObservable.notifyObservers();
  130. location.hash = "";
  131. if (location.pathname.indexOf("pg/") !== -1) {
  132. // reload to create a new pg if in full-path playground mode.
  133. window.location.pathname = "";
  134. }
  135. }
  136. private _createEditor() {
  137. if (this._editor) {
  138. this._editor.dispose();
  139. }
  140. var editorOptions: IStandaloneEditorConstructionOptions = {
  141. value: "",
  142. language: this.globalState.language === "JS" ? "javascript" : "typescript",
  143. lineNumbers: "on",
  144. roundedSelection: true,
  145. automaticLayout: true,
  146. scrollBeyondLastLine: false,
  147. readOnly: false,
  148. theme: Utilities.ReadStringFromStore("theme", "Light") === "Dark" ? "vs-dark" : "vs-light",
  149. contextmenu: false,
  150. folding: true,
  151. showFoldingControls: "always",
  152. fontSize: parseInt(Utilities.ReadStringFromStore("font-size", "14")),
  153. renderIndentGuides: true,
  154. minimap: {
  155. enabled: Utilities.ReadBoolFromStore("minimap", true),
  156. },
  157. };
  158. this._editor = monaco.editor.create(this._hostElement, editorOptions as any);
  159. this._editor.onDidChangeModelContent(() => {
  160. let newCode = this._editor.getValue();
  161. if (this.globalState.currentCode !== newCode) {
  162. this.globalState.currentCode = newCode;
  163. this._isDirty = true;
  164. }
  165. });
  166. if (this.globalState.currentCode) {
  167. this._editor!.setValue(this.globalState.currentCode);
  168. }
  169. this.globalState.getCompiledCode = () => this._getRunCode();
  170. if (this.globalState.currentCode) {
  171. this.globalState.onRunRequiredObservable.notifyObservers();
  172. }
  173. }
  174. public async setupMonacoAsync(hostElement: HTMLDivElement, initialCall = false) {
  175. this._hostElement = hostElement;
  176. let response = await fetch("https://preview.babylonjs.com/babylon.d.ts");
  177. if (!response.ok) {
  178. return;
  179. }
  180. let libContent = await response.text();
  181. response = await fetch("https://preview.babylonjs.com/gui/babylon.gui.d.ts");
  182. if (!response.ok) {
  183. return;
  184. }
  185. libContent += await response.text();
  186. this._createEditor();
  187. // Definition worker
  188. this._setupDefinitionWorker(libContent);
  189. // Setup the Monaco compilation pipeline, so we can reuse it directly for our scrpting needs
  190. this._setupMonacoCompilationPipeline(libContent);
  191. // This is used for a vscode-like color preview for ColorX types
  192. this._setupMonacoColorProvider();
  193. if (initialCall) {
  194. // Load code templates
  195. response = await fetch("templates.json");
  196. if (response.ok) {
  197. this._templates = await response.json();
  198. }
  199. // enhance templates with extra properties
  200. for (const template of this._templates) {
  201. (template.kind = monaco.languages.CompletionItemKind.Snippet), (template.sortText = "!" + template.label); // make sure templates are on top of the completion window
  202. template.insertTextRules = monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet;
  203. }
  204. this._hookMonacoCompletionProvider();
  205. }
  206. if (!this.globalState.loadingCodeInProgress) {
  207. this._setDefaultContent();
  208. }
  209. }
  210. private _setDefaultContent() {
  211. if (this.globalState.language === "JS") {
  212. this._editor.setValue(`var createScene = function () {
  213. // This creates a basic Babylon Scene object (non-mesh)
  214. var scene = new BABYLON.Scene(engine);
  215. // This creates and positions a free camera (non-mesh)
  216. var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);
  217. // This targets the camera to scene origin
  218. camera.setTarget(BABYLON.Vector3.Zero());
  219. // This attaches the camera to the canvas
  220. camera.attachControl(canvas, true);
  221. // This creates a light, aiming 0,1,0 - to the sky (non-mesh)
  222. var light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0, 1, 0), scene);
  223. // Default intensity is 1. Let's dim the light a small amount
  224. light.intensity = 0.7;
  225. // Our built-in 'sphere' shape.
  226. var sphere = BABYLON.MeshBuilder.CreateSphere("sphere", {diameter: 2, segments: 32}, scene);
  227. // Move the sphere upward 1/2 its height
  228. sphere.position.y = 1;
  229. // Our built-in 'ground' shape.
  230. var ground = BABYLON.MeshBuilder.CreateGround("ground", {width: 6, height: 6}, scene);
  231. return scene;
  232. };`);
  233. } else {
  234. this._editor.setValue(`class Playground {
  235. public static CreateScene(engine: BABYLON.Engine, canvas: HTMLCanvasElement): BABYLON.Scene {
  236. // This creates a basic Babylon Scene object (non-mesh)
  237. var scene = new BABYLON.Scene(engine);
  238. // This creates and positions a free camera (non-mesh)
  239. var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);
  240. // This targets the camera to scene origin
  241. camera.setTarget(BABYLON.Vector3.Zero());
  242. // This attaches the camera to the canvas
  243. camera.attachControl(canvas, true);
  244. // This creates a light, aiming 0,1,0 - to the sky (non-mesh)
  245. var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene);
  246. // Default intensity is 1. Let's dim the light a small amount
  247. light.intensity = 0.7;
  248. // Our built-in 'sphere' shape. Params: name, subdivs, size, scene
  249. var sphere = BABYLON.Mesh.CreateSphere("sphere1", 16, 2, scene);
  250. // Move the sphere upward 1/2 its height
  251. sphere.position.y = 1;
  252. // Our built-in 'ground' shape. Params: name, width, depth, subdivs, scene
  253. var ground = BABYLON.Mesh.CreateGround("ground1", 6, 6, 2, scene);
  254. return scene;
  255. }
  256. }`);
  257. }
  258. this._isDirty = false;
  259. this.globalState.onRunRequiredObservable.notifyObservers();
  260. }
  261. // Provide an adornment for BABYLON.ColorX types: color preview
  262. protected _setupMonacoColorProvider() {
  263. monaco.languages.registerColorProvider(this.globalState.language == "JS" ? "javascript" : "typescript", {
  264. provideColorPresentations: (model: any, colorInfo: any) => {
  265. const color = colorInfo.color;
  266. const precision = 100.0;
  267. const converter = (n: number) => Math.round(n * precision) / precision;
  268. let label;
  269. if (color.alpha === undefined || color.alpha === 1.0) {
  270. label = `(${converter(color.red)}, ${converter(color.green)}, ${converter(color.blue)})`;
  271. } else {
  272. label = `(${converter(color.red)}, ${converter(color.green)}, ${converter(color.blue)}, ${converter(color.alpha)})`;
  273. }
  274. return [
  275. {
  276. label: label,
  277. },
  278. ];
  279. },
  280. provideDocumentColors: (model: any) => {
  281. const digitGroup = "\\s*(\\d*(?:\\.\\d+)?)\\s*";
  282. // we add \n{0} to workaround a Monaco bug, when setting regex options on their side
  283. const regex = `BABYLON\\.Color(?:3|4)\\s*\\(${digitGroup},${digitGroup},${digitGroup}(?:,${digitGroup})?\\)\\n{0}`;
  284. const matches = model.findMatches(regex, false, true, true, null, true);
  285. const converter = (g: string) => (g === undefined ? undefined : Number(g));
  286. return matches.map((match: any) => ({
  287. color: {
  288. red: converter(match.matches![1])!,
  289. green: converter(match.matches![2])!,
  290. blue: converter(match.matches![3])!,
  291. alpha: converter(match.matches![4])!,
  292. },
  293. range: {
  294. startLineNumber: match.range.startLineNumber,
  295. startColumn: match.range.startColumn + match.matches![0].indexOf("("),
  296. endLineNumber: match.range.startLineNumber,
  297. endColumn: match.range.endColumn,
  298. },
  299. }));
  300. },
  301. });
  302. }
  303. // Setup both JS and TS compilation pipelines to work with our scripts.
  304. protected _setupMonacoCompilationPipeline(libContent: string) {
  305. var typescript = monaco.languages.typescript;
  306. if (this.globalState.language === "JS") {
  307. typescript.javascriptDefaults.setCompilerOptions({
  308. noLib: false,
  309. allowNonTsExtensions: true, // required to prevent Uncaught Error: Could not find file: 'inmemory://model/1'.
  310. });
  311. typescript.javascriptDefaults.addExtraLib(libContent, "babylon.d.ts");
  312. } else {
  313. typescript.typescriptDefaults.setCompilerOptions({
  314. module: typescript.ModuleKind.AMD,
  315. target: typescript.ScriptTarget.ESNext,
  316. noLib: false,
  317. strict: false,
  318. alwaysStrict: false,
  319. strictFunctionTypes: false,
  320. suppressExcessPropertyErrors: false,
  321. suppressImplicitAnyIndexErrors: true,
  322. noResolve: true,
  323. suppressOutputPathCheck: true,
  324. allowNonTsExtensions: true, // required to prevent Uncaught Error: Could not find file: 'inmemory://model/1'.
  325. });
  326. typescript.typescriptDefaults.addExtraLib(libContent, "babylon.d.ts");
  327. }
  328. }
  329. protected _setupDefinitionWorker(libContent: string) {
  330. this._definitionWorker = new Worker("workers/definitionWorker.js");
  331. this._definitionWorker.addEventListener("message", ({ data }) => {
  332. this._deprecatedCandidates = data.result;
  333. this._analyzeCodeAsync();
  334. });
  335. this._definitionWorker.postMessage({
  336. code: libContent,
  337. });
  338. }
  339. // This will make sure that all members marked with a deprecated jsdoc attribute will be marked as such in Monaco UI
  340. // We use a prefiltered list of deprecated candidates, because the effective call to getCompletionEntryDetails is slow.
  341. // @see setupDefinitionWorker
  342. private async _analyzeCodeAsync() {
  343. // if the definition worker is very fast, this can be called out of context. @see setupDefinitionWorker
  344. if (!this._editor) {
  345. return;
  346. }
  347. const model = this._editor.getModel();
  348. if (!model) {
  349. return;
  350. }
  351. const uri = model.uri;
  352. let worker = null;
  353. if (this.globalState.language === "JS") {
  354. worker = await monaco.languages.typescript.getJavaScriptWorker();
  355. } else {
  356. worker = await monaco.languages.typescript.getTypeScriptWorker();
  357. }
  358. const languageService = await worker(uri);
  359. const source = "[deprecated members]";
  360. monaco.editor.setModelMarkers(model, source, []);
  361. const markers: {
  362. startLineNumber: number;
  363. endLineNumber: number;
  364. startColumn: number;
  365. endColumn: number;
  366. message: string;
  367. severity: number;
  368. source: string;
  369. }[] = [];
  370. for (const candidate of this._deprecatedCandidates) {
  371. const matches = model.findMatches(candidate, false, false, true, null, false);
  372. for (const match of matches) {
  373. const position = {
  374. lineNumber: match.range.startLineNumber,
  375. column: match.range.startColumn,
  376. };
  377. const wordInfo = model.getWordAtPosition(position);
  378. const offset = model.getOffsetAt(position);
  379. if (!wordInfo) {
  380. continue;
  381. }
  382. // continue if we already found an issue here
  383. if (markers.find((m) => m.startLineNumber == position.lineNumber && m.startColumn == position.column)) {
  384. continue;
  385. }
  386. // the following is time consuming on all suggestions, that's why we precompute deprecated candidate names in the definition worker to filter calls
  387. // @see setupDefinitionWorker
  388. const details = await languageService.getCompletionEntryDetails(uri.toString(), offset, wordInfo.word);
  389. if (this._isDeprecatedEntry(details)) {
  390. const deprecatedInfo = details.tags.find(this._isDeprecatedTag);
  391. markers.push({
  392. startLineNumber: match.range.startLineNumber,
  393. endLineNumber: match.range.endLineNumber,
  394. startColumn: wordInfo.startColumn,
  395. endColumn: wordInfo.endColumn,
  396. message: deprecatedInfo.text,
  397. severity: monaco.MarkerSeverity.Warning,
  398. source: source,
  399. });
  400. }
  401. }
  402. }
  403. monaco.editor.setModelMarkers(model, source, markers);
  404. }
  405. // This is our hook in the Monaco suggest adapter, we are called everytime a completion UI is displayed
  406. // So we need to be super fast.
  407. private async _hookMonacoCompletionProvider() {
  408. const oldProvideCompletionItems = languageFeatures.SuggestAdapter.prototype.provideCompletionItems;
  409. // tslint:disable-next-line:no-this-assignment
  410. const owner = this;
  411. languageFeatures.SuggestAdapter.prototype.provideCompletionItems = async function (model: any, position: any, context: any, token: any) {
  412. // reuse 'this' to preserve context through call (using apply)
  413. const result = await oldProvideCompletionItems.apply(this, [model, position, context, token]);
  414. if (!result || !result.suggestions) {
  415. return result;
  416. }
  417. const suggestions = result.suggestions.filter((item: any) => !item.label.startsWith("_"));
  418. for (const suggestion of suggestions) {
  419. if (owner._deprecatedCandidates.includes(suggestion.label)) {
  420. // the following is time consuming on all suggestions, that's why we precompute deprecated candidate names in the definition worker to filter calls
  421. // @see setupDefinitionWorker
  422. const uri = suggestion.uri;
  423. const worker = await this._worker(uri);
  424. const model = monaco.editor.getModel(uri);
  425. const details = await worker.getCompletionEntryDetails(uri.toString(), model!.getOffsetAt(position), suggestion.label);
  426. if (owner._isDeprecatedEntry(details)) {
  427. suggestion.tags = [monaco.languages.CompletionItemTag.Deprecated];
  428. }
  429. }
  430. }
  431. // add our own templates when invoked without context
  432. if (context.triggerKind == monaco.languages.CompletionTriggerKind.Invoke) {
  433. let language = owner.globalState.language === "JS" ? "javascript" : "typescript";
  434. for (const template of owner._templates) {
  435. if (template.language && language !== template.language) {
  436. continue;
  437. }
  438. suggestions.push(template);
  439. }
  440. }
  441. // preserve incomplete flag or force it when the definition is not yet analyzed
  442. const incomplete = (result.incomplete && result.incomplete == true) || owner._deprecatedCandidates.length == 0;
  443. return {
  444. suggestions: suggestions,
  445. incomplete: incomplete,
  446. };
  447. };
  448. }
  449. private _isDeprecatedEntry(details: any) {
  450. return details && details.tags && details.tags.find(this._isDeprecatedTag);
  451. }
  452. private _isDeprecatedTag(tag: any) {
  453. return tag && tag.name == "deprecated";
  454. }
  455. private async _getRunCode() {
  456. if (this.globalState.language == "JS") {
  457. return this._editor.getValue();
  458. } else {
  459. const model = this._editor.getModel()!;
  460. const uri = model.uri;
  461. const worker = await monaco.languages.typescript.getTypeScriptWorker();
  462. const languageService = await worker(uri);
  463. const uriStr = uri.toString();
  464. const result = await languageService.getEmitOutput(uriStr);
  465. const diagnostics = await Promise.all([languageService.getSyntacticDiagnostics(uriStr), languageService.getSemanticDiagnostics(uriStr)]);
  466. diagnostics.forEach(function (diagset) {
  467. if (diagset.length) {
  468. const diagnostic = diagset[0];
  469. const position = model.getPositionAt(diagnostic.start!);
  470. const err = new CompilationError();
  471. err.message = diagnostic.messageText as string;
  472. err.lineNumber = position.lineNumber;
  473. err.columnNumber = position.column;
  474. throw err;
  475. }
  476. });
  477. const output = result.outputFiles[0].text;
  478. const stub = "var createScene = function() { return Playground.CreateScene(engine, engine.getRenderingCanvas()); }";
  479. return output + stub;
  480. }
  481. }
  482. }