monacoManager.ts 22 KB

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