monacoManager.ts 25 KB

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