extension.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. // The module 'vscode' contains the VS Code extensibility API
  2. // Import the module and reference it with the alias vscode in your code below
  3. const vscode = require('vscode');
  4. const openFilesAndURLs = require('./openFilesAndUrls.js')
  5. // const path = require('path');
  6. // This method is called when your extension is activated
  7. // Your extension is activated the very first time the command is executed
  8. /**
  9. *
  10. * @param {vscode.ExtensionContext} context
  11. */
  12. console.log("ITK LOGS!!!!!")
  13. let treeView;
  14. let _context;
  15. function activate(context) {
  16. console.log('Congratulations, your extension "itk" is now active!');
  17. initTreeView(context);
  18. initCmdInVsCodeTerminal(context)
  19. initOpenChromeUrl(context)
  20. initCloseTabs(context)
  21. initHtml(context, getTemplate())
  22. initWelcome(context)
  23. initTests(context)
  24. initGetTabs(context)
  25. startAction(context);
  26. }
  27. async function startAction(context) {
  28. _context = context;
  29. updateCount(127)
  30. openFilesAndURLs({beforeFn: closeAllTabs})
  31. // openHtml()
  32. // openWelcomeFrame()
  33. // openTestsFrame()
  34. setTimeout(() => {
  35. getTabs();
  36. })
  37. // openTabsDirectly()
  38. // openUrlInChrome();
  39. }
  40. async function openStartTabs(groups) {
  41. const openPromises = [];
  42. const workspaceFolder = vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders[0];
  43. let columnIndex = 1; // Start from the first column
  44. groups.forEach((group, index) => {
  45. group.forEach((file) => {
  46. if (file.url) {
  47. // If the object contains a URL, open it in a Webview (iframe)
  48. // openPromises.push( runFrame(file));
  49. runFrame(file, columnIndex + index)
  50. } else if (file.relPath) {
  51. // Resolve the file path relative to the workspace folder
  52. const filePath = vscode.Uri.joinPath(workspaceFolder.uri, file.relPath);
  53. // Open the file in a new tab (in a new column, if needed)
  54. openPromises.push(vscode.workspace.openTextDocument(filePath)
  55. .then(doc => {
  56. // If it's the first file of a group, open it in the first column
  57. const columnToUse = columnIndex + index;
  58. // Show the document in the appropriate column
  59. vscode.window.showTextDocument(doc, { viewColumn: columnToUse, preview: false });
  60. // Move to the next column after opening each file
  61. }));
  62. }
  63. });
  64. });
  65. }
  66. function initGetTabs(context) {
  67. let disposable = vscode.commands.registerCommand('itk.getTabs', () => {
  68. getTabs()
  69. });
  70. // Add to your extension's subscriptions
  71. context.subscriptions.push(disposable);
  72. }
  73. function getTabs() {
  74. const tabGroups = vscode.window.tabGroups.all;
  75. if (tabGroups.length === 0) {
  76. vscode.window.showInformationMessage('No open tabs found.');
  77. return;
  78. }
  79. let tabInfo = [];
  80. tabGroups.forEach((group, index) => {
  81. group.tabs.forEach(tab => {
  82. let filePath = "Unknown";
  83. // Check if the tab is a text file and extract its full path
  84. if (tab.input instanceof vscode.TabInputText) {
  85. filePath = tab.input.uri.fsPath;
  86. }
  87. tabInfo.push(`Group ${index + 1}: ${tab.label} - ${filePath}`);
  88. });
  89. });
  90. vscode.window.showInformationMessage(`Opened Tabs:\n${tabInfo.join('\n')}`);
  91. console.log('tabInfo', tabInfo)
  92. return tabGroups;
  93. }
  94. function initOpenChromeUrl(context) {
  95. let disposable = vscode.commands.registerCommand('itk.openUrlInBrowser', async () => {
  96. openUrlInChrome()
  97. });
  98. context.subscriptions.push(disposable);
  99. }
  100. async function openUrlInChrome() {
  101. let url = 'https://new.csb.app';
  102. // if (url) {
  103. // try {
  104. // new URL(url); // Validate URL
  105. // } catch (error) {
  106. // vscode.window.showErrorMessage("Invalid URL: " + error.message);
  107. // return;
  108. // }
  109. // // Dynamic import:
  110. // try {
  111. // const open = await import('open'); // Correct way to import ES module
  112. // await open.default(url); // Use open.default to call the function
  113. // } catch (error) {
  114. // vscode.window.showErrorMessage("Could not open URL: " + error.message);
  115. // console.error("Open URL Error:", error);
  116. // }
  117. // }
  118. }
  119. function initCloseTabs(context) {
  120. let disposable = vscode.commands.registerCommand('itk.closeAllTabs', () => {
  121. // Call your close all tabs logic here (the code from above)
  122. closeAllTabs()
  123. });
  124. context.subscriptions.push(disposable);
  125. }
  126. async function closeAllTabs() {
  127. try {
  128. await vscode.commands.executeCommand('workbench.action.closeAllEditors');
  129. } catch (e) {
  130. vscode.window.showInformationMessage("Tabs Closing Error");
  131. }
  132. }
  133. function initHtml(context, defaultUrl) {
  134. context.subscriptions.push(
  135. vscode.commands.registerCommand('itk.openWelcome', () => {
  136. openHtml(context, defaultUrl);
  137. })
  138. );
  139. }
  140. function openHtml(context, html) {
  141. context = context || _context;
  142. html = html || getTemplate();
  143. const panel = vscode.window.createWebviewPanel(
  144. 'HTML ITK', // Identifies the webview
  145. 'ITK HTML', // Title of the panel
  146. vscode.ViewColumn.One, // Show in the first column
  147. {
  148. enableScripts: true, // Allows JavaScript execution
  149. }
  150. );
  151. // Set HTML content for the Webview
  152. panel.webview.html = html
  153. panel.webview.onDidReceiveMessage(message => {
  154. console.log('message', message, message.command)
  155. switch (message.command) {
  156. case 'buttonClicked':
  157. vscode.window.showInformationMessage('Button clicked!' + new Date().getTime());
  158. return;
  159. }
  160. }, undefined, context.subscriptions);
  161. }
  162. function initWelcome(context, defaultUrl) {
  163. context.subscriptions.push(
  164. vscode.commands.registerCommand('itk.openWelcomeFrame', () => {
  165. openWelcomeFrame();
  166. })
  167. );
  168. }
  169. function initTests(context, defaultUrl) {
  170. context.subscriptions.push(
  171. vscode.commands.registerCommand('itk.openTests', () => {
  172. openTestsFrame();
  173. })
  174. );
  175. }
  176. function openWelcomeFrame() {
  177. runFrame({ url: 'https://itrum.ru', name: 'ITK Welcome Frame', id: 'itkWelcomeFrame' })
  178. }
  179. function openTestsFrame() {
  180. runFrame({ url: 'https://itrum.ru', name: 'ITK Tests', id: 'itkTests' })
  181. }
  182. function runFrame({ url, name, id} , groupId) {
  183. const panel = vscode.window.createWebviewPanel(
  184. id, // Identifies the webview
  185. name, // Title of the panel
  186. vscode.ViewColumn.One, // Show in the first column
  187. {
  188. enableScripts: true, // Allows JavaScript execution
  189. localResourceRoots: [] // Define where local resources can be loaded from (if needed)
  190. }
  191. );
  192. panel.reveal(vscode.ViewColumn.One + groupId - 1);
  193. console.log('groupId', groupId)
  194. // Set HTML content for the Webview
  195. panel.webview.html = getWebviewContent(url);
  196. function getWebviewContent(url) {
  197. return `<!DOCTYPE html>
  198. <html lang="en">
  199. <head>
  200. <meta charset="UTF-8">
  201. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  202. <title>ITK Academy</title>
  203. <style>
  204. body { margin: 0; padding: 0; display: flex; height: 100vh; }
  205. iframe { width: 100%; height: 100%; border: none; }
  206. </style>
  207. </head>
  208. <body>
  209. <iframe src="${url}"></iframe>
  210. </body>
  211. </html>`;
  212. }
  213. }
  214. function updateCount(newMessagesCount) {
  215. treeView.badge = {
  216. value: newMessagesCount,
  217. tooltip: `You have ${newMessagesCount} new documentation`
  218. };
  219. }
  220. function initCmdInVsCodeTerminal(context) {
  221. const disposable = vscode.commands.registerCommand('itk.openTabs', () => openTabsDirectly());
  222. context.subscriptions.push(disposable);
  223. }
  224. function initTreeView(context) {
  225. const view = vscode.window.createTreeView('itk.mainView', {
  226. treeDataProvider: new TabSaverTreeDataProvider(['HTML', 'Preview', 'Close Tabs'])
  227. });
  228. context.subscriptions.push(view);
  229. treeView = view;
  230. const view2 = vscode.window.createTreeView('itk.runView', {
  231. treeDataProvider: new TabSaverTreeDataProvider(['Run Tests', 'Close Tabs'])
  232. });
  233. context.subscriptions.push(view);
  234. context.subscriptions.push(view2);
  235. console.log('view', view)
  236. view.onDidChangeSelection((event) => treeClickHandler(event, context));
  237. view2.onDidChangeSelection((event) => treeClickHandler(event, context));
  238. }
  239. function treeClickHandler(event, context) {
  240. if (event.selection.length > 0) {
  241. const selectedItem = event.selection[0];
  242. console.log(`Clicked on: ${selectedItem}`); // Log the clicked item's label
  243. let cmds = {
  244. Preview: openWelcomeFrame,
  245. HTML: () => openHtml(null, '<h1>asdfasdf</h1>'),
  246. 'Run Tests': openTestsFrame,
  247. 'Close Tabs': closeAllTabs
  248. }
  249. let fn = cmds[selectedItem];
  250. fn && fn();
  251. }
  252. }
  253. class TabSaverTreeDataProvider {
  254. constructor(tabs) {
  255. this.tabs = tabs;
  256. }
  257. getTreeItem(element) {
  258. console.log('element', element);
  259. return new vscode.TreeItem(element);
  260. }
  261. getChildren(element) {
  262. console.log('element', element);
  263. // If no element is provided, return the root elements (tabs)
  264. if (!element) {
  265. return Promise.resolve(this.tabs);
  266. }
  267. // If an element is provided, you can handle it accordingly
  268. return Promise.resolve([]);
  269. }
  270. }
  271. function openTabsDirectly(tabs) {
  272. setTimeout(() => {
  273. if (tabs.length === 0) {
  274. vscode.window.showInformationMessage('No tabs saved yet.');
  275. return;
  276. }
  277. // JSON.parse(fs.readFileSync(saveFilePath, 'utf-8')); // No need for "as string[]"
  278. console.log("tabssssss", tabs)
  279. tabs.forEach(tabPath => {
  280. const uri = vscode.Uri.file(tabPath); // Create a Uri object
  281. vscode.workspace.openTextDocument(uri).then(doc => {
  282. vscode.window.showTextDocument(doc, { viewColumn: vscode.ViewColumn.Beside }); // Open beside
  283. }, error => {
  284. console.error(`Error opening ${tabPath}: ${error}`);
  285. vscode.window.showErrorMessage(`Error opening ${tabPath}: ${error}`);
  286. });
  287. });
  288. vscode.window.showInformationMessage('Hello World from itk!');
  289. }, 500)
  290. }
  291. function getTemplate() {
  292. return `<!DOCTYPE html>
  293. <html lang="en">
  294. <head>
  295. <meta charset="UTF-8">
  296. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  297. <title>Cat Coding</title>
  298. </head>
  299. <body>
  300. <h1>Welcome to ITK.academy!!!!!</h1>
  301. <p>This is a custom welcome view.</p>
  302. <p>You can add your own HTML content here.</p>
  303. <button id="myButton">Click Me</button>
  304. <script>
  305. const vscode = acquireVsCodeApi();
  306. document.getElementById('myButton').addEventListener('click', () => {
  307. vscode.postMessage({ command: 'buttonClicked' });
  308. });
  309. </script>
  310. </body>
  311. </html>`;
  312. }
  313. // This method is called when your extension is deactivated
  314. function deactivate() {
  315. console.log("ITK DEACTIVE")
  316. }
  317. module.exports = {
  318. activate,
  319. deactivate
  320. }