monacoManager.ts 23 KB

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