TypscriptLanguageExtension.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. //
  2. // Copyright (c) 2014-2016 THUNDERBEAST GAMES LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. import * as EditorEvents from "../../editor/EditorEvents";
  23. /**
  24. * Default compiler options to use for compilation. If there
  25. * is a compiler option block in a tsconfig.json located in the project,
  26. * then the one in the project will overwrite these
  27. * @type {ts.CompilerOptions}
  28. */
  29. const defaultCompilerOptions = {
  30. noEmitOnError: true,
  31. noImplicitAny: false,
  32. target: "es5",
  33. module: "commonjs",
  34. declaration: false,
  35. inlineSourceMap: false,
  36. removeComments: false,
  37. noLib: true,
  38. allowNonTsExtensions: false,
  39. allowJs: false
  40. };
  41. const defaultCompilerOptionsJs = {
  42. noEmitOnError: true,
  43. noImplicitAny: false,
  44. target: "es5",
  45. module: "commonjs",
  46. declaration: false,
  47. inlineSourceMap: false,
  48. removeComments: false,
  49. noLib: true,
  50. allowNonTsExtensions: true,
  51. allowJs: true
  52. };
  53. /**
  54. * Resource extension that supports the web view typescript extension
  55. */
  56. export default class TypescriptLanguageExtension implements Editor.HostExtensions.ResourceServicesEventListener, Editor.HostExtensions.ProjectServicesEventListener {
  57. name: string = "HostTypeScriptLanguageExtension";
  58. description: string = "This service supports the typscript webview extension.";
  59. /**
  60. * Indicates if this project contains typescript files.
  61. * @type {Boolean}
  62. */
  63. private isTypescriptProject = false;
  64. private serviceRegistry: Editor.HostExtensions.HostServiceLocator = null;
  65. private menuCreated = false;
  66. /** Reference to the compileOnSaveMenuItem */
  67. private compileOnSaveMenuItem: Atomic.UIMenuItem;
  68. /**
  69. * Determines if the file name/path provided is something we care about
  70. * @param {string} path
  71. * @return {boolean}
  72. */
  73. private isValidFiletype(path: string): boolean {
  74. const ext = Atomic.getExtension(path);
  75. if (ext == ".ts" || ext == ".js") {
  76. return true;
  77. }
  78. }
  79. /**
  80. * Build an in-memory config file to be sent down to the web view client. This will scan the resources directory
  81. * and generate a file list
  82. */
  83. private buildTsConfig(): any {
  84. // only build out a tsconfig.atomic if we actually have typescript files in the project
  85. let projectFiles: Array<string> = [];
  86. //scan all the files in the project for any typescript files and add them to the project
  87. Atomic.fileSystem.scanDir(ToolCore.toolSystem.project.resourcePath, "*.ts", Atomic.SCAN_FILES, true).forEach(filename => {
  88. projectFiles.push(Atomic.addTrailingSlash(ToolCore.toolSystem.project.resourcePath) + filename);
  89. if (!this.isTypescriptProject) {
  90. this.isTypescriptProject = true;
  91. }
  92. });
  93. let compilerOptions = defaultCompilerOptions;
  94. if (!this.isTypescriptProject) {
  95. compilerOptions = defaultCompilerOptionsJs;
  96. }
  97. Atomic.fileSystem.scanDir(ToolCore.toolSystem.project.resourcePath, "*.js", Atomic.SCAN_FILES, true).forEach(filename => {
  98. let fn = Atomic.addTrailingSlash(ToolCore.toolSystem.project.resourcePath) + filename;
  99. // only add .js files that don't match .ts files
  100. if (projectFiles.indexOf(fn.replace(/\.js$/, ".ts")) == -1) {
  101. projectFiles.push(Atomic.addTrailingSlash(ToolCore.toolSystem.project.resourcePath) + filename);
  102. }
  103. });
  104. // First we need to load in a copy of the lib.core.d.ts that is necessary for the hosted typescript compiler
  105. projectFiles.push(Atomic.addTrailingSlash(Atomic.addTrailingSlash(ToolCore.toolEnvironment.toolDataDir) + "TypeScriptSupport") + "lib.core.d.ts");
  106. const slashedProjectPath = Atomic.addTrailingSlash(ToolCore.toolSystem.project.projectPath);
  107. const tsconfigFn = Atomic.addTrailingSlash(ToolCore.toolSystem.project.projectPath) + "tsconfig.json";
  108. // Let's look for a tsconfig.json file in the project root and add any additional files
  109. if (Atomic.fileSystem.fileExists(tsconfigFn)) {
  110. // load up the tsconfig file and parse out the files block and compare it to what we have
  111. // in resources
  112. const file = new Atomic.File(tsconfigFn, Atomic.FILE_READ);
  113. try {
  114. const savedTsConfig = JSON.parse(file.readText());
  115. if (savedTsConfig["files"]) {
  116. savedTsConfig["files"].forEach((file: string) => {
  117. let newFile = Atomic.addTrailingSlash(ToolCore.toolSystem.project.projectPath) + file;
  118. let exists = false;
  119. if (Atomic.fileSystem.fileExists(newFile)) {
  120. exists = true;
  121. file = newFile;
  122. } else if (Atomic.fileSystem.exists(file)) {
  123. exists = true;
  124. }
  125. if (exists && projectFiles.indexOf(file) == -1) {
  126. projectFiles.push(file);
  127. }
  128. });
  129. }
  130. // override the default options if the tsconfig contains them
  131. if (savedTsConfig["compilerOptions"]) {
  132. compilerOptions = savedTsConfig["compilerOptions"];
  133. }
  134. } finally {
  135. file.close();
  136. }
  137. };
  138. // Then see if we have a copy of Atomic.d.ts in the project directory. If we don't then we should load it up from the tool environment
  139. let found = false;
  140. projectFiles.forEach((file) => {
  141. if (file.toLowerCase().indexOf("atomic.d.ts") != -1) {
  142. found = true;
  143. }
  144. });
  145. if (!found) {
  146. // Load up the Atomic.d.ts from the tool core
  147. projectFiles.push(Atomic.addTrailingSlash(Atomic.addTrailingSlash(ToolCore.toolEnvironment.toolDataDir) + "TypeScriptSupport") + "Atomic.d.ts");
  148. }
  149. let tsConfig = {
  150. compilerOptions: compilerOptions,
  151. files: projectFiles
  152. };
  153. return tsConfig;
  154. }
  155. /**
  156. * Configures the project to be a Typescript Project
  157. * @return {[type]}
  158. */
  159. private configureTypescriptProjectMenu() {
  160. if (this.isTypescriptProject && !this.menuCreated) {
  161. const isCompileOnSave = this.serviceRegistry.projectServices.getUserPreference(this.name, "CompileOnSave", false);
  162. // Build the menu - First build up an empty menu then manually add the items so we can have reference to them
  163. const menu = this.serviceRegistry.uiServices.createPluginMenuItemSource("TypeScript", {});
  164. this.compileOnSaveMenuItem = new Atomic.UIMenuItem(`Compile on Save: ${isCompileOnSave ? "On" : "Off"}`, `${this.name}.compileonsave`);
  165. menu.addItem(this.compileOnSaveMenuItem);
  166. menu.addItem(new Atomic.UIMenuItem("Compile Project", `${this.name}.compileproject`));
  167. this.menuCreated = true;
  168. }
  169. }
  170. /**
  171. * Inject this language service into the registry
  172. * @return {[type]} True if successful
  173. */
  174. initialize(serviceLocator: Editor.HostExtensions.HostServiceLocator) {
  175. // We care about both resource events as well as project events
  176. serviceLocator.resourceServices.register(this);
  177. serviceLocator.projectServices.register(this);
  178. serviceLocator.uiServices.register(this);
  179. this.serviceRegistry = serviceLocator;
  180. }
  181. /**
  182. * Handle when a new file is loaded and we have not yet configured the editor for TS.
  183. * This could be when someone adds a TS file to a vanilla project
  184. * @param {Editor.EditorEvents.EditResourceEvent} ev
  185. */
  186. edit(ev: Editor.EditorEvents.EditResourceEvent) {
  187. if (this.isValidFiletype(ev.path)) {
  188. // update ts config in case we have a new resource
  189. let tsConfig = this.buildTsConfig();
  190. this.setTsConfigOnWebView(tsConfig);
  191. if (this.isTypescriptProject) {
  192. this.configureTypescriptProjectMenu();
  193. }
  194. }
  195. }
  196. /**
  197. * Handle the delete. This should delete the corresponding javascript file
  198. * @param {Editor.EditorEvents.DeleteResourceEvent} ev
  199. */
  200. delete(ev: Editor.EditorEvents.DeleteResourceEvent) {
  201. if (this.isValidFiletype(ev.path)) {
  202. // console.log(`${this.name}: received a delete resource event`);
  203. // Delete the corresponding js file
  204. let jsFile = ev.path.replace(/\.ts$/, ".js");
  205. let jsFileAsset = ToolCore.assetDatabase.getAssetByPath(jsFile);
  206. if (jsFileAsset) {
  207. console.log(`${this.name}: deleting corresponding .js file`);
  208. ToolCore.assetDatabase.deleteAsset(jsFileAsset);
  209. let eventData: EditorEvents.DeleteResourceEvent = {
  210. path: jsFile
  211. };
  212. this.setTsConfigOnWebView(this.buildTsConfig());
  213. this.serviceRegistry.sendEvent(EditorEvents.DeleteResourceNotification, eventData);
  214. }
  215. }
  216. }
  217. /**
  218. * Handle the rename. Should rename the corresponding .js file
  219. * @param {Editor.EditorEvents.RenameResourceEvent} ev
  220. */
  221. rename(ev: Editor.EditorEvents.RenameResourceEvent) {
  222. if (this.isValidFiletype(ev.path)) {
  223. // console.log(`${this.name}: received a rename resource event`);
  224. // Rename the corresponding js file
  225. let jsFile = ev.path.replace(/\.ts$/, ".js");
  226. let jsFileNew = ev.newPath.replace(/\.ts$/, ".js"); // rename doesn't want extension
  227. let jsFileAsset = ToolCore.assetDatabase.getAssetByPath(jsFile);
  228. if (jsFileAsset) {
  229. console.log(`${this.name}: renaming corresponding .js file`);
  230. jsFileAsset.rename(ev.newName);
  231. let eventData: EditorEvents.RenameResourceEvent = {
  232. path: jsFile,
  233. newPath: jsFileNew,
  234. newName: ev.newName,
  235. asset: jsFileAsset
  236. };
  237. this.setTsConfigOnWebView(this.buildTsConfig());
  238. this.serviceRegistry.sendEvent(EditorEvents.RenameResourceNotification, eventData);
  239. }
  240. }
  241. }
  242. /**
  243. * Handles the save event and detects if a typescript file has been added to a non-typescript project
  244. * @param {Editor.EditorEvents.SaveResourceEvent} ev
  245. * @return {[type]}
  246. */
  247. save(ev: Editor.EditorEvents.SaveResourceEvent) {
  248. // let's check to see if we have created a typescript file
  249. if (!this.isTypescriptProject) {
  250. if (Atomic.getExtension(ev.path) == ".ts") {
  251. this.isTypescriptProject = true;
  252. this.setTsConfigOnWebView(this.buildTsConfig());
  253. }
  254. }
  255. }
  256. /*** ProjectService implementation ****/
  257. /**
  258. * Called when the project is being loaded to allow the typscript language service to reset and
  259. * possibly compile
  260. */
  261. projectLoaded(ev: Editor.EditorEvents.LoadProjectEvent) {
  262. // got a load, we need to reset the language service
  263. this.isTypescriptProject = false;
  264. //scan all the files in the project for any typescript files so we can determine if this is a typescript project
  265. if (Atomic.fileSystem.scanDir(ToolCore.toolSystem.project.resourcePath, "*.ts", Atomic.SCAN_FILES, true).length > 0) {
  266. this.isTypescriptProject = true;
  267. this.configureTypescriptProjectMenu();
  268. };
  269. }
  270. /**
  271. * Called when the project is unloaded
  272. */
  273. projectUnloaded() {
  274. // Clean up
  275. this.serviceRegistry.uiServices.removePluginMenuItemSource("TypeScript");
  276. this.compileOnSaveMenuItem = null;
  277. this.menuCreated = false;
  278. this.isTypescriptProject = false;
  279. }
  280. /*** UIService implementation ***/
  281. /**
  282. * Called when a plugin menu item is clicked
  283. * @param {string} refId
  284. * @return {boolean}
  285. */
  286. menuItemClicked(refId: string): boolean {
  287. let [extension, action] = refId.split(".");
  288. if (extension == this.name) {
  289. switch (action) {
  290. case "compileonsave":
  291. let isCompileOnSave = this.serviceRegistry.projectServices.getUserPreference(this.name, "CompileOnSave", false);
  292. // Toggle
  293. isCompileOnSave = !isCompileOnSave;
  294. this.serviceRegistry.projectServices.setUserPreference(this.name, "CompileOnSave", isCompileOnSave);
  295. this.compileOnSaveMenuItem.string = `Compile on Save: ${isCompileOnSave ? "On" : "Off"}`;
  296. return true;
  297. case "compileproject":
  298. this.doFullCompile();
  299. return true;
  300. }
  301. }
  302. }
  303. /**
  304. * Handle messages that are submitted via Atomic.Query from within a web view editor.
  305. * @param message The message type that was submitted to be used to determine what the data contains if present
  306. * @param data any additional data that needs to be submitted with the message
  307. */
  308. handleWebMessage(messageType: string, data: any) {
  309. switch (messageType) {
  310. case "TypeScript.DisplayCompileResults":
  311. this.displayCompileResults(data);
  312. break;
  313. }
  314. }
  315. setTsConfigOnWebView(tsConfig: any) {
  316. WebView.WebBrowserHost.setGlobalStringProperty("TypeScriptLanguageExtension", "tsConfig", JSON.stringify(tsConfig));
  317. }
  318. /**
  319. * Perform a full compile of the TypeScript
  320. */
  321. doFullCompile() {
  322. const editor = this.serviceRegistry.uiServices.getCurrentResourceEditor();
  323. if (editor && editor.typeName == "JSResourceEditor" && this.isValidFiletype(editor.fullPath)) {
  324. const jsEditor = <Editor.JSResourceEditor>editor;
  325. jsEditor.webView.webClient.executeJavaScript(`TypeScript_DoFullCompile();`);
  326. } else {
  327. this.serviceRegistry.uiServices.showModalError("TypeScript Compilation", "Please open a TypeScript file in the editor before attempting to do a full compile.");
  328. }
  329. // Ideally, we would want to either launch up a background web view, or shell out to node or something and not
  330. // need to have an editor open. Still researching this
  331. /*
  332. const url = `atomic://${ToolCore.toolEnvironment.toolDataDir}CodeEditor/Editor.html`;
  333. const webClient = new WebView.WebClient();
  334. this.webClient = webClient;
  335. //this.webClient.loadURL(url);
  336. const webTexture = new WebView.WebTexture2D();
  337. webClient.webRenderHandler = webTexture;
  338. // doesn't work because atomicquery doesn't seem to be exposed to WebView.WebClient instances
  339. webClient.subscribeToEvent(EditorEvents.WebMessage, (data) => {
  340. switch (data.message) {
  341. case "editorLoadComplete":
  342. webClient.unsubscribeFromEvent(EditorEvents.WebMessage);
  343. webClient.executeJavaScript(`TypeScript_DoFullCompile();`);
  344. break;
  345. }
  346. });
  347. webClient.createBrowser(url, 1, 1);
  348. */
  349. }
  350. /**
  351. * Display the results of the compilation step
  352. * @param {any[]} annotations
  353. */
  354. displayCompileResults(results: {
  355. annotations: any[],
  356. compilerOptions: any,
  357. duration: number
  358. }) {
  359. // get the name of the resources directory without preceding path
  360. let resourceDir = ToolCore.toolSystem.project.resourcePath.replace(Atomic.addTrailingSlash(ToolCore.toolSystem.project.projectPath), "");
  361. let messageArray = results.annotations.filter(result => {
  362. // If we are compiling the lib.d.ts or some other built-in library and it was successful, then
  363. // we really don't need to display that result since it's just noise. Only display it if it fails
  364. if (result.type == "success") {
  365. return result.file.indexOf(ToolCore.toolSystem.project.projectPath) == 0;
  366. }
  367. return true;
  368. }).map(result => {
  369. // Clean up the path for display
  370. let file = result.file.replace(ToolCore.toolSystem.project.projectPath, "");
  371. let message = `<color #888888>${file}: </color>`;
  372. if (result.type == "success") {
  373. message += `<color #00ff00>${result.text}</color>`;
  374. } else {
  375. message += `<color #e3e02b>${result.text} at line ${result.row} col ${result.column}</color>`;
  376. }
  377. return message;
  378. }).join("\n");
  379. if (messageArray.length == 0) {
  380. messageArray = "Success";
  381. }
  382. let message = [
  383. "Compiler Options: ",
  384. JSON.stringify(results.compilerOptions, null, 2),
  385. "",
  386. messageArray,
  387. "",
  388. `Compilation Completed in ${results.duration}ms`
  389. ].join("\n");
  390. this.serviceRegistry.uiServices.showModalError("TypeScript Compilation Results", message);
  391. }
  392. }