diff --git a/README.md b/README.md index 9d5dfaf..ef46467 100644 --- a/README.md +++ b/README.md @@ -180,6 +180,8 @@ Add shortcuts for your favorite Minecraft commands. ##### Script Profiler After setting a local path for saving captures, use `Start Profiler` and `Stop Profiler` to create performance captures of your actively running add-on. +Use `Open Folder` beside the captures path to open that folder in your system file explorer (File Explorer on Windows). +While the home panel is visible, the Captures list automatically updates when `.cpuprofile` files are added to or removed from the selected folder, including changes made outside VS Code. #### Diagnostics Window When attatched to a game server running Minecraft 1.21.10 or above, the debugger can display high level statistics to help diagnose performance issues. diff --git a/src/extension.ts b/src/extension.ts index 21c43c5..b870017 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -20,7 +20,10 @@ export function activate(context: vscode.ExtensionContext): void { // home view const homeViewProvider = new HomeViewProvider(context.extensionUri, eventEmitter); - context.subscriptions.push(vscode.window.registerWebviewViewProvider(HomeViewProvider.viewType, homeViewProvider)); + context.subscriptions.push( + homeViewProvider, + vscode.window.registerWebviewViewProvider(HomeViewProvider.viewType, homeViewProvider), + ); // register a configuration provider for the 'minecraft-js' debug type const configProvider = new ConfigProvider(); diff --git a/src/panels/home-view-provider.test.ts b/src/panels/home-view-provider.test.ts new file mode 100644 index 0000000..efbb444 --- /dev/null +++ b/src/panels/home-view-provider.test.ts @@ -0,0 +1,382 @@ +// Copyright (C) Microsoft Corporation. All rights reserved. + +import { EventEmitter } from 'stream'; +import * as path from 'path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { HomeViewProvider } from './home-view-provider'; + +const mocks = vi.hoisted(() => ({ + readdir: vi.fn<(path: string, callback: (error: NodeJS.ErrnoException | null, files: string[]) => void) => void>(), + unlink: vi.fn<(path: string, callback: (error: NodeJS.ErrnoException | null) => void) => void>(), + createWatcher: vi.fn<() => vscode.FileSystemWatcher>(), + stat: vi.fn<(path: string) => Promise<{ isDirectory: () => boolean }>>(), + openExternal: vi.fn<(uri: vscode.Uri) => Promise>(), + showErrorMessage: vi.fn(), +})); + +vi.mock('fs', () => ({ + readdir: mocks.readdir, + unlink: mocks.unlink, + promises: { stat: mocks.stat }, +})); + +vi.mock('vscode', () => ({ + Disposable: class { + constructor(private readonly callback: () => void) {} + dispose() { + this.callback(); + } + }, + RelativePattern: class { + constructor(readonly base: string, readonly pattern: string) {} + }, + Uri: { + file: (fsPath: string) => ({ fsPath }), + }, + workspace: { + createFileSystemWatcher: mocks.createWatcher, + }, + env: { openExternal: mocks.openExternal }, + window: { showErrorMessage: mocks.showErrorMessage }, +})); + +vi.mock('../utilities/getUri', () => ({ + getUri: () => 'test-resource', +})); + +function createEvent() { + const listeners = new Set<(value: T) => void>(); + const event = vi.fn>((listener, thisArgs, disposables) => { + const callback = (value: T) => listener.call(thisArgs, value); + listeners.add(callback); + const disposable = new vscode.Disposable(() => listeners.delete(callback)); + disposables?.push(disposable); + return disposable; + }); + return { + event, + fire: (value: T) => listeners.forEach(listener => listener(value)), + clear: () => listeners.clear(), + }; +} + +function createWatcher() { + const created = createEvent(); + const deleted = createEvent(); + const changed = createEvent(); + const watcher = { + ignoreCreateEvents: false, + ignoreChangeEvents: true, + ignoreDeleteEvents: false, + onDidCreate: created.event, + onDidDelete: deleted.event, + onDidChange: changed.event, + dispose: vi.fn(() => { + created.clear(); + deleted.clear(); + changed.clear(); + }), + } satisfies vscode.FileSystemWatcher; + return { watcher, created, deleted }; +} + +function createView() { + let visible = true; + const received = createEvent(); + const visibility = createEvent(); + const disposed = createEvent(); + const postMessage = vi.fn(() => Promise.resolve(true)); + const view = { + get visible() { return visible; }, + viewType: HomeViewProvider.viewType, + show: vi.fn(), + onDidChangeVisibility: visibility.event, + onDidDispose: disposed.event, + webview: { + html: '', + options: {}, + cspSource: 'test', + postMessage, + asWebviewUri: vi.fn((uri: vscode.Uri) => uri), + onDidReceiveMessage: received.event, + }, + } satisfies vscode.WebviewView; + return { + view, + received, + disposed, + postMessage, + setVisible(value: boolean) { + visible = value; + visibility.fire(); + }, + }; +} + +describe('HomeViewProvider capture watching', () => { + const capturesPath = path.resolve('captures'); + const otherPath = path.resolve('other-captures'); + let provider: HomeViewProvider; + let emitter: EventEmitter; + let ui: ReturnType; + let watchers: ReturnType[]; + + function setCapturesPath(capturesBasePath: string) { + ui.received.fire({ type: 'refresh-captures', capturesBasePath }); + } + + beforeEach(() => { + vi.useFakeTimers(); + vi.clearAllMocks(); + watchers = []; + mocks.createWatcher.mockImplementation(() => { + const watcher = createWatcher(); + watchers.push(watcher); + return watcher.watcher; + }); + mocks.readdir.mockImplementation((_path, callback) => { + callback(null, ['initial.cpuprofile', 'notes.txt']); + }); + mocks.stat.mockResolvedValue({ isDirectory: () => true }); + mocks.openExternal.mockResolvedValue(true); + emitter = new EventEmitter(); + provider = new HomeViewProvider(vscode.Uri.file(path.resolve('extension')), emitter); + ui = createView(); + provider.resolveWebviewView(ui.view); + }); + + afterEach(() => { + provider.dispose(); + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + describe('opening the captures folder', () => { + async function openFolder(capturesBasePath: unknown) { + const [handler] = ui.received.event.mock.calls[0]; + await handler({ type: 'open-captures-folder', capturesBasePath }); + } + + it('reports an inaccessible or missing folder', async () => { + mocks.stat.mockRejectedValue(new Error('Directory is unavailable')); + await openFolder(capturesPath); + + expect(mocks.openExternal).not.toHaveBeenCalled(); + expect(mocks.showErrorMessage).toHaveBeenCalledWith( + 'Unable to open the captures folder: Directory is unavailable', + ); + }); + + it('rejects a captures path that points to a file', async () => { + mocks.stat.mockResolvedValue({ isDirectory: () => false }); + await openFolder(capturesPath); + + expect(mocks.openExternal).not.toHaveBeenCalled(); + expect(mocks.showErrorMessage).toHaveBeenCalledWith( + 'Unable to open the captures folder: The captures path is not a folder.', + ); + }); + + it('reports when the system file explorer cannot be opened', async () => { + mocks.openExternal.mockResolvedValue(false); + await openFolder(capturesPath); + + expect(mocks.showErrorMessage).toHaveBeenCalledWith( + 'Unable to open the captures folder: The system file explorer could not be opened.', + ); + }); + + it('reports errors opening the system file explorer', async () => { + mocks.openExternal.mockRejectedValue(new Error('Access denied')); + await openFolder(capturesPath); + + expect(mocks.showErrorMessage).toHaveBeenCalledWith('Unable to open the captures folder: Access denied'); + }); + }); + + it('does not watch or read an unset captures path', () => { + setCapturesPath(''); + + expect(mocks.createWatcher).not.toHaveBeenCalled(); + expect(mocks.readdir).not.toHaveBeenCalled(); + }); + + it('watches only profile additions and deletions and immediately lists existing captures', () => { + setCapturesPath(capturesPath); + + expect(mocks.createWatcher).toHaveBeenCalledWith( + expect.objectContaining({ base: capturesPath, pattern: '*.cpuprofile' }), + false, + true, + false, + ); + expect(ui.postMessage).toHaveBeenLastCalledWith({ + type: 'capture-files-refreshed', + allCaptureFileNames: ['initial.cpuprofile'], + newCaptureFileName: undefined, + }); + }); + + it.each(['created', 'deleted'] as const)('refreshes after a profile is %s externally', event => { + setCapturesPath(capturesPath); + const files = event === 'created' ? ['initial.cpuprofile', 'external.cpuprofile'] : []; + mocks.readdir.mockImplementation((_path, callback) => callback(null, files)); + + watchers[0][event].fire(vscode.Uri.file(path.join(capturesPath, 'external.cpuprofile'))); + vi.advanceTimersByTime(999); + expect(mocks.readdir).toHaveBeenCalledOnce(); + vi.advanceTimersByTime(1); + + expect(ui.postMessage).toHaveBeenLastCalledWith({ + type: 'capture-files-refreshed', + allCaptureFileNames: files, + newCaptureFileName: undefined, + }); + }); + + it('debounces bursts of create and delete events', () => { + setCapturesPath(capturesPath); + const uri = vscode.Uri.file(path.join(capturesPath, 'capture.cpuprofile')); + watchers[0].created.fire(uri); + vi.advanceTimersByTime(50); + watchers[0].deleted.fire(uri); + vi.advanceTimersByTime(999); + expect(mocks.readdir).toHaveBeenCalledTimes(1); + + vi.advanceTimersByTime(1); + expect(mocks.readdir).toHaveBeenCalledTimes(2); + }); + + it('replaces the watcher and discards reads from the old captures path', () => { + mocks.readdir.mockImplementation(() => undefined); + setCapturesPath(capturesPath); + setCapturesPath(otherPath); + + expect(watchers[0].watcher.dispose).toHaveBeenCalledOnce(); + expect(watchers).toHaveLength(2); + expect(mocks.readdir).toHaveBeenLastCalledWith(otherPath, expect.any(Function)); + + mocks.readdir.mock.calls[1][1](null, ['current.cpuprofile']); + mocks.readdir.mock.calls[0][1](null, ['stale.cpuprofile']); + expect(ui.postMessage).toHaveBeenCalledOnce(); + expect(ui.postMessage).toHaveBeenLastCalledWith({ + type: 'capture-files-refreshed', + allCaptureFileNames: ['current.cpuprofile'], + newCaptureFileName: undefined, + }); + }); + + it('stops watching and cancels pending refreshes when the captures path is cleared', () => { + setCapturesPath(capturesPath); + watchers[0].created.fire(vscode.Uri.file(path.join(capturesPath, 'capture.cpuprofile'))); + setCapturesPath(''); + vi.advanceTimersByTime(1000); + + expect(watchers[0].watcher.dispose).toHaveBeenCalledOnce(); + expect(mocks.createWatcher).toHaveBeenCalledOnce(); + expect(mocks.readdir).toHaveBeenCalledOnce(); + expect(vi.getTimerCount()).toBe(0); + }); + + it('stops watching while hidden and refreshes changes made while hidden on reopening', () => { + setCapturesPath(capturesPath); + watchers[0].created.fire(vscode.Uri.file(path.join(capturesPath, 'capture.cpuprofile'))); + ui.setVisible(false); + vi.advanceTimersByTime(1000); + + expect(watchers[0].watcher.dispose).toHaveBeenCalledOnce(); + expect(mocks.readdir).toHaveBeenCalledOnce(); + + mocks.readdir.mockImplementation((_path, callback) => callback(null, ['added-while-hidden.cpuprofile'])); + ui.setVisible(true); + + expect(watchers).toHaveLength(2); + expect(ui.postMessage).toHaveBeenLastCalledWith({ + type: 'capture-files-refreshed', + allCaptureFileNames: ['added-while-hidden.cpuprofile'], + newCaptureFileName: undefined, + }); + }); + + it('does not start watching a path restored while the view is hidden until it becomes visible', () => { + ui.setVisible(false); + setCapturesPath(capturesPath); + expect(mocks.createWatcher).not.toHaveBeenCalled(); + expect(mocks.readdir).not.toHaveBeenCalled(); + + ui.setVisible(true); + expect(mocks.createWatcher).toHaveBeenCalledOnce(); + expect(mocks.readdir).toHaveBeenCalledOnce(); + }); + + it.each(['view', 'provider'] as const)('cleans up watchers, timers, reads and listeners on %s disposal', target => { + mocks.readdir.mockImplementation(() => undefined); + setCapturesPath(capturesPath); + watchers[0].created.fire(vscode.Uri.file(path.join(capturesPath, 'capture.cpuprofile'))); + + if (target === 'view') { + ui.disposed.fire(); + } else { + provider.dispose(); + } + mocks.readdir.mock.calls[0][1](null, ['stale.cpuprofile']); + vi.advanceTimersByTime(1000); + setCapturesPath(otherPath); + + expect(watchers[0].watcher.dispose).toHaveBeenCalledOnce(); + expect(emitter.listenerCount('new-profiler-capture')).toBe(0); + expect(vi.getTimerCount()).toBe(0); + expect(mocks.readdir).toHaveBeenCalledOnce(); + expect(mocks.createWatcher).toHaveBeenCalledOnce(); + expect(ui.postMessage).not.toHaveBeenCalled(); + }); + + it('ignores new-capture events for other folders', () => { + setCapturesPath(capturesPath); + emitter.emit('new-profiler-capture', otherPath, 'other.cpuprofile'); + + expect(mocks.readdir).toHaveBeenCalledOnce(); + expect(ui.postMessage).toHaveBeenCalledOnce(); + }); + + it('retains new-capture selection while hidden until the view is shown', () => { + setCapturesPath(capturesPath); + ui.setVisible(false); + emitter.emit('new-profiler-capture', capturesPath, 'new.cpuprofile'); + expect(mocks.readdir).toHaveBeenCalledOnce(); + + mocks.readdir.mockImplementation((_path, callback) => callback(null, ['new.cpuprofile'])); + ui.setVisible(true); + + expect(ui.postMessage).toHaveBeenLastCalledWith({ + type: 'capture-files-refreshed', + allCaptureFileNames: ['new.cpuprofile'], + newCaptureFileName: 'new.cpuprofile', + }); + }); + + it('reports read failures explicitly so an inaccessible folder does not leave stale captures', () => { + const error = new Error('Directory is unavailable'); + const log = vi.spyOn(console, 'error').mockImplementation(() => undefined); + mocks.readdir.mockImplementation((_path, callback) => callback(error, [])); + setCapturesPath(capturesPath); + + expect(log).toHaveBeenCalledWith('Error reading captures directory:', error); + expect(ui.postMessage).toHaveBeenLastCalledWith({ type: 'capture-files-refresh-failed' }); + }); + + it('still refreshes after a capture is deleted through the UI', () => { + setCapturesPath(capturesPath); + mocks.unlink.mockImplementation((_path, callback) => callback(null)); + mocks.readdir.mockImplementation((_path, callback) => callback(null, [])); + ui.received.fire({ type: 'delete-capture-file', capturesBasePath: capturesPath, fileName: 'initial.cpuprofile' }); + + expect(mocks.unlink).toHaveBeenCalledWith(path.join(capturesPath, 'initial.cpuprofile'), expect.any(Function)); + expect(ui.postMessage).toHaveBeenLastCalledWith({ + type: 'capture-files-refreshed', + allCaptureFileNames: [], + newCaptureFileName: undefined, + }); + }); +}); diff --git a/src/panels/home-view-provider.ts b/src/panels/home-view-provider.ts index 55ee401..c9582ec 100644 --- a/src/panels/home-view-provider.ts +++ b/src/panels/home-view-provider.ts @@ -8,12 +8,18 @@ import { getUri } from '../utilities/getUri'; import { EventEmitter } from 'stream'; import { MinecraftCapabilities } from '../session'; -export class HomeViewProvider implements vscode.WebviewViewProvider { +export class HomeViewProvider implements vscode.WebviewViewProvider, vscode.Disposable { public static readonly viewType = 'minecraft-debugger-home-panel'; private readonly _extensionUri: vscode.Uri; private _eventEmitter: EventEmitter; private _view?: vscode.WebviewView; + private _disposables: vscode.Disposable[] = []; + private _capturesBasePath = ''; + private _capturesWatcher?: vscode.FileSystemWatcher; + private _capturesRefreshTimer?: ReturnType; + private _capturesRefreshId = 0; + private _newCaptureFileName?: string; constructor(extensionUri: vscode.Uri, eventEmitter: EventEmitter) { this._extensionUri = extensionUri; @@ -39,6 +45,7 @@ export class HomeViewProvider implements vscode.WebviewViewProvider { } public resolveWebviewView(webviewView: vscode.WebviewView): void { + this.dispose(); this._view = webviewView; this._view.webview.options = { @@ -49,9 +56,18 @@ export class HomeViewProvider implements vscode.WebviewViewProvider { this._view.webview.html = this._getHtmlForWebview(this._view.webview, this._extensionUri); // listen for events from the debugger Session - this._eventEmitter.on('new-profiler-capture', (captureBasePath: string, newCaptureFileName: string) => { - this._refreshProfilerCaptures(captureBasePath, newCaptureFileName); - }); + const onNewProfilerCapture = (captureBasePath: string, newCaptureFileName: string) => { + if (captureBasePath === this._capturesBasePath) { + this._refreshProfilerCaptures(newCaptureFileName); + } + }; + this._eventEmitter.on('new-profiler-capture', onNewProfilerCapture); + this._disposables.push(new vscode.Disposable(() => { + this._eventEmitter.off('new-profiler-capture', onNewProfilerCapture); + })); + + this._view.onDidChangeVisibility(() => this._updateCapturesWatcher(), null, this._disposables); + this._view.onDidDispose(() => this.dispose(), null, this._disposables); // listen for events from the home panel webview this._view.webview.onDidReceiveMessage(async message => { @@ -88,7 +104,11 @@ export class HomeViewProvider implements vscode.WebviewViewProvider { break; } case 'refresh-captures': { - this._refreshProfilerCaptures(message.capturesBasePath); + if (this._capturesBasePath !== message.capturesBasePath) { + this._newCaptureFileName = undefined; + } + this._capturesBasePath = message.capturesBasePath; + this._updateCapturesWatcher(); break; } case 'request-debugger-status': { @@ -99,6 +119,10 @@ export class HomeViewProvider implements vscode.WebviewViewProvider { await this._browseCapturesBasePath(); break; } + case 'open-captures-folder': { + await this._openCapturesFolder(message.capturesBasePath); + break; + } case 'open-capture-file': { this._openCaptureFile(message.capturesBasePath, message.fileName); break; @@ -108,7 +132,18 @@ export class HomeViewProvider implements vscode.WebviewViewProvider { break; } } - }); + }, null, this._disposables); + } + + public dispose(): void { + this._stopCapturesWatcher(); + for (const disposable of this._disposables) { + disposable.dispose(); + } + this._disposables = []; + this._view = undefined; + this._capturesBasePath = ''; + this._newCaptureFileName = undefined; } private async _browseCapturesBasePath() { @@ -122,27 +157,93 @@ export class HomeViewProvider implements vscode.WebviewViewProvider { } } + private async _openCapturesFolder(capturesBasePath: string): Promise { + if (typeof capturesBasePath !== 'string' || capturesBasePath.trim() === '') { + vscode.window.showErrorMessage('Set a captures path before opening the folder.'); + return; + } + + try { + const stats = await fs.promises.stat(capturesBasePath); + if (!stats.isDirectory()) { + throw new Error('The captures path is not a folder.'); + } + if (!await vscode.env.openExternal(vscode.Uri.file(capturesBasePath))) { + throw new Error('The system file explorer could not be opened.'); + } + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + vscode.window.showErrorMessage(`Unable to open the captures folder: ${detail}`); + } + } + private _openCaptureFile(capturesBasePath: string, fileName: string) { const fullPath = path.join(capturesBasePath, fileName); const uri = vscode.Uri.file(fullPath); vscode.commands.executeCommand('vscode.open', uri); } - private _refreshProfilerCaptures(capturesBasePath: string, newCaptureFileName?: string) { - if (!capturesBasePath) { + private _updateCapturesWatcher(): void { + this._stopCapturesWatcher(); + if (!this._view?.visible || !this._capturesBasePath) { + return; + } + + this._capturesWatcher = vscode.workspace.createFileSystemWatcher( + new vscode.RelativePattern(this._capturesBasePath, '*.cpuprofile'), + false, + true, + false, + ); + const refreshCaptures = () => { + if (this._capturesRefreshTimer !== undefined) { + clearTimeout(this._capturesRefreshTimer); + } + this._capturesRefreshTimer = setTimeout(() => { + this._capturesRefreshTimer = undefined; + this._refreshProfilerCaptures(); + }, 1000); + }; + this._capturesWatcher.onDidCreate(refreshCaptures); + this._capturesWatcher.onDidDelete(refreshCaptures); + this._refreshProfilerCaptures(); + } + + private _stopCapturesWatcher(): void { + this._capturesWatcher?.dispose(); + this._capturesWatcher = undefined; + if (this._capturesRefreshTimer !== undefined) { + clearTimeout(this._capturesRefreshTimer); + this._capturesRefreshTimer = undefined; + } + ++this._capturesRefreshId; + } + + private _refreshProfilerCaptures(newCaptureFileName?: string) { + if (newCaptureFileName) { + this._newCaptureFileName = newCaptureFileName; + } + const view = this._view; + if (!view?.visible || !this._capturesBasePath) { return; } - fs.readdir(capturesBasePath, (err, files) => { + const refreshId = ++this._capturesRefreshId; + fs.readdir(this._capturesBasePath, (err, files) => { + if (refreshId !== this._capturesRefreshId) { + return; + } if (err) { console.error('Error reading captures directory:', err); + view.webview.postMessage({ type: 'capture-files-refresh-failed' }); return; } const allCaptureFileNames = files.filter(file => path.extname(file) === '.cpuprofile'); - this._view?.webview.postMessage({ + view.webview.postMessage({ type: 'capture-files-refreshed', allCaptureFileNames: allCaptureFileNames, - newCaptureFileName: newCaptureFileName, + newCaptureFileName: this._newCaptureFileName, }); + this._newCaptureFileName = undefined; }); } @@ -153,7 +254,9 @@ export class HomeViewProvider implements vscode.WebviewViewProvider { console.error('Error deleting capture file:', err); return; } - this._refreshProfilerCaptures(capturesBasePath); + if (capturesBasePath === this._capturesBasePath) { + this._refreshProfilerCaptures(); + } }); } diff --git a/webview-ui/src/home_panel/App.css b/webview-ui/src/home_panel/App.css index 2f5e4c2..17b014b 100644 --- a/webview-ui/src/home_panel/App.css +++ b/webview-ui/src/home_panel/App.css @@ -145,9 +145,15 @@ .capture-path-input { flex: 1; + min-width: 0; margin-right: 10px; } +.open-captures-folder-button { + flex-shrink: 0; + margin-left: 6px; +} + .capture-scrolling-list-box { max-height: 200px; overflow-y: auto; diff --git a/webview-ui/src/home_panel/App.tsx b/webview-ui/src/home_panel/App.tsx index efee20d..09aed74 100644 --- a/webview-ui/src/home_panel/App.tsx +++ b/webview-ui/src/home_panel/App.tsx @@ -57,6 +57,7 @@ const App = () => { selectedCaptureItem, setSelectedCaptureItem, onCaptureBasePathEdited, + onOpenCapturesFolder, onSelectCaptureItem, onDeleteCaptureItem, onStartProfiler, @@ -100,6 +101,8 @@ const App = () => { if (message.newCaptureFileName) { setSelectedCaptureItem({ fileName: message.newCaptureFileName }); } + } else if (message.type === 'capture-files-refresh-failed') { + setCaptureItems([]); } else if (message.type === 'debugger-status') { if (!message.isConnected) { setProfilerCapturing(false); @@ -140,6 +143,7 @@ const App = () => { capturesBasePath={capturesBasePath} onCaptureBasePathBrowseButtonPressed={onCaptureBasePathBrowseButtonPressed} onCaptureBasePathEdited={onCaptureBasePathEdited} + onOpenCapturesFolder={onOpenCapturesFolder} scrollingListRef={scrollingListRef} captureItems={captureItems} selectedCaptureItem={selectedCaptureItem} diff --git a/webview-ui/src/home_panel/controls/ProfilerSection.tsx b/webview-ui/src/home_panel/controls/ProfilerSection.tsx index a388e31..fb65a32 100644 --- a/webview-ui/src/home_panel/controls/ProfilerSection.tsx +++ b/webview-ui/src/home_panel/controls/ProfilerSection.tsx @@ -7,6 +7,7 @@ import { CaptureItem } from '../handlers/ProfilerHandlers'; interface ProfilerSectionProps { capturesBasePath: string; onCaptureBasePathBrowseButtonPressed: () => void; + onOpenCapturesFolder: () => void; onCaptureBasePathEdited: (event: React.ChangeEvent) => void; scrollingListRef: React.RefObject; captureItems: CaptureItem[]; @@ -23,6 +24,7 @@ interface ProfilerSectionProps { const ProfilerSection: React.FC = ({ capturesBasePath, onCaptureBasePathBrowseButtonPressed, + onOpenCapturesFolder, onCaptureBasePathEdited, scrollingListRef, captureItems, @@ -49,6 +51,14 @@ const ProfilerSection: React.FC = ({ Browse + + Open Folder +
void; // callbacks onCaptureBasePathEdited: (event: React.ChangeEvent) => void; + onOpenCapturesFolder: () => void; onSelectCaptureItem: (captureItem: CaptureItem) => void; onDeleteCaptureItem: (toDelete: CaptureItem) => void; onStartProfiler: () => void; @@ -41,8 +42,11 @@ export const getProfilerHandlers = (vscode: WebviewApi): ProfilerHandle vscode.postMessage({ type: 'refresh-captures', capturesBasePath: capturesBasePath }); }, [capturesBasePath]); - // update the scrolling list when captures are refreshed + // update the scrolling list and selection when captures are refreshed useEffect(() => { + setSelectedCaptureItem(selected => + captureItems.some(item => item.fileName === selected?.fileName) ? selected : undefined + ); if (scrollingListRef.current) { scrollingListRef.current.scrollTop = 0; } @@ -53,6 +57,10 @@ export const getProfilerHandlers = (vscode: WebviewApi): ProfilerHandle setCapturesBasePath(event.target.value); }, []); + const onOpenCapturesFolder = useCallback(() => { + vscode.postMessage({ type: 'open-captures-folder', capturesBasePath }); + }, [capturesBasePath]); + // when a capture file is selected from the list const onSelectCaptureItem = useCallback((captureItem: CaptureItem) => { setSelectedCaptureItem(captureItem); @@ -99,6 +107,7 @@ export const getProfilerHandlers = (vscode: WebviewApi): ProfilerHandle selectedCaptureItem, setSelectedCaptureItem, onCaptureBasePathEdited, + onOpenCapturesFolder, onSelectCaptureItem, onDeleteCaptureItem, onStartProfiler,