diff --git a/tabs-api-sample/package.json b/tabs-api-sample/package.json index 7755e002..edc7585e 100644 --- a/tabs-api-sample/package.json +++ b/tabs-api-sample/package.json @@ -19,6 +19,17 @@ ], "main": "./out/extension.js", "contributes": { + "configuration":{ + "title": "Tabs API Sample", + "id": "tabsSample", + "properties": { + "tabs.maxInactiveTime": { + "default": 30, + "description": "The number of seconds before closing inactive tabs", + "type": "number" + } + } + } }, "scripts": { "vscode:prepublish": "npm run compile", diff --git a/tabs-api-sample/src/extension.ts b/tabs-api-sample/src/extension.ts index 44c97871..a5837d83 100644 --- a/tabs-api-sample/src/extension.ts +++ b/tabs-api-sample/src/extension.ts @@ -7,24 +7,36 @@ export function activate(context: vscode.ExtensionContext) { * You can use proposed API here. `vscode.` should start auto complete * Proposed API as defined in vscode.proposed..d.ts. */ + const activityMap: Map = new Map(); + const disposables: vscode.Disposable[] = []; - // Whenever a tab is opened close it - let timeout: NodeJS.Timeout | undefined = undefined; - const disposable = vscode.window.tabGroups.onDidChangeTabs(tabs => { - if (timeout) { - timeout.refresh(); - } else { - timeout = setTimeout(async () => { - try { - await vscode.window.tabGroups.close(vscode.window.tabGroups.groups.map(group => group.tabs).flat(1)); - vscode.window.showErrorMessage('Productivity is not allowed on fridays.', {modal: true}); - } catch { - // No op - } - timeout = undefined; - }, 700); + disposables.push(vscode.window.tabGroups.onDidChangeTabGroups(() => { + const tabs = vscode.window.tabGroups.groups.map(group => group.tabs).flat(1); + activityMap.clear(); + // Update activity map saying everything is active + tabs.forEach(t => activityMap.set(t, Date.now())); + })); + disposables.push(vscode.window.tabGroups.onDidChangeTabs(tabs => { + for (const tab of tabs) { + // Reset the timer for the tabs last activity + activityMap.set(tab, Date.now()); } - }); - - context.subscriptions.push(disposable); + })); + // Check every second for inactive tabs + setInterval(() => { + const activeTab = vscode.window.tabGroups.activeTabGroup.activeTab; + if (activeTab) { + // Update the activity map for the active tab, since it's still being used. + activityMap.set(activeTab, Date.now()); + } + const inactiveTime = (vscode.workspace.getConfiguration().get('tabs.maxInactiveTime') ?? 30) * 1000; + // Check if any tabs have been inactive for more than 30 seconds + const inactiveTabs = Array.from(activityMap.entries()).filter(([tab, lastActive]) => Date.now() - lastActive > inactiveTime && vscode.window.tabGroups.activeTabGroup.activeTab !== tab && !tab.isDirty); + inactiveTabs.forEach(async ([tab]) => { + // Close the tab + await vscode.window.tabGroups.close(tab); + activityMap.delete(tab); + }); + }, 1000); + disposables.forEach(d => context.subscriptions.push(d)); }