From 0d214371da2c42e4d6275db8931aa8d2daba6cfa Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 10 Nov 2024 15:05:30 -0800 Subject: [PATCH] find widget cleanup --- extensions/vscode/src/commands.ts | 1134 ++++++++++++------------ gui/src/components/find/FindWidget.tsx | 337 ++++--- gui/src/hooks/useWindowSize.ts | 43 - 3 files changed, 715 insertions(+), 799 deletions(-) delete mode 100644 gui/src/hooks/useWindowSize.ts diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index ad8dc0b3b..c33d71aea 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -226,608 +226,608 @@ const commandsMap: ( core, editDecorationManager, ) => { - /** - * Streams an inline edit to the vertical diff manager. - * - * This function retrieves the configuration, determines the appropriate model title, - * increments the FTC count, and then streams an edit to the - * vertical diff manager. - * - * @param promptName - The key for the prompt in the context menu configuration. - * @param fallbackPrompt - The prompt to use if the configured prompt is not available. - * @param [onlyOneInsertion] - Optional. If true, only one insertion will be made. - * @param [range] - Optional. The range to edit if provided. - * @returns - */ - async function streamInlineEdit( - promptName: keyof ContextMenuConfig, - fallbackPrompt: string, - onlyOneInsertion?: boolean, - range?: vscode.Range, - ) { - const config = await configHandler.loadConfig(); + /** + * Streams an inline edit to the vertical diff manager. + * + * This function retrieves the configuration, determines the appropriate model title, + * increments the FTC count, and then streams an edit to the + * vertical diff manager. + * + * @param promptName - The key for the prompt in the context menu configuration. + * @param fallbackPrompt - The prompt to use if the configured prompt is not available. + * @param [onlyOneInsertion] - Optional. If true, only one insertion will be made. + * @param [range] - Optional. The range to edit if provided. + * @returns + */ + async function streamInlineEdit( + promptName: keyof ContextMenuConfig, + fallbackPrompt: string, + onlyOneInsertion?: boolean, + range?: vscode.Range, + ) { + const config = await configHandler.loadConfig(); - const defaultModelTitle = await sidebar.webviewProtocol.request( - "getDefaultModelTitle", + const defaultModelTitle = await sidebar.webviewProtocol.request( + "getDefaultModelTitle", + undefined, + ); + + const modelTitle = + getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle; + + sidebar.webviewProtocol.request("incrementFtc", undefined); + + await verticalDiffManager.streamEdit( + config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, + modelTitle, + undefined, + onlyOneInsertion, + undefined, + range, + ); + } + + return { + "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { + captureCommandTelemetry("acceptDiff"); + + let fullPath = newFilepath; + + if (fullPath instanceof vscode.Uri) { + fullPath = fullPath.fsPath; + } else if (fullPath) { + fullPath = getFullyQualifiedPath(ide, fullPath); + } else { + console.warn(`Unable to resolve filepath: ${newFilepath}`); + } + + verticalDiffManager.clearForFilepath(fullPath, true); + await diffManager.acceptDiff(fullPath); + await sidebar.webviewProtocol.request("setEditStatus", { + status: "done", + }); + }, + "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { + captureCommandTelemetry("rejectDiff"); + + let fullPath = newFilepath; + + if (fullPath instanceof vscode.Uri) { + fullPath = fullPath.fsPath; + } else if (fullPath) { + fullPath = getFullyQualifiedPath(ide, fullPath); + } else { + console.warn(`Unable to resolve filepath: ${newFilepath}`); + } + + verticalDiffManager.clearForFilepath(fullPath, false); + await diffManager.rejectDiff(fullPath); + await sidebar.webviewProtocol.request("setEditStatus", { + status: "done", + }); + }, + "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { + captureCommandTelemetry("acceptVerticalDiffBlock"); + verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index); + }, + "continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => { + captureCommandTelemetry("rejectVerticalDiffBlock"); + verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index); + }, + "continue.quickFix": async ( + range: vscode.Range, + diagnosticMessage: string, + ) => { + captureCommandTelemetry("quickFix"); + + const prompt = `Please explain the cause of this error and how to solve it: ${diagnosticMessage}`; + + addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + }, + // Passthrough for telemetry purposes + "continue.defaultQuickAction": async (args: QuickEditShowParams) => { + captureCommandTelemetry("defaultQuickAction"); + vscode.commands.executeCommand("continue.quickEdit", args); + }, + "continue.customQuickActionSendToChat": async ( + prompt: string, + range: vscode.Range, + ) => { + captureCommandTelemetry("customQuickActionSendToChat"); + + addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + }, + "continue.customQuickActionStreamInlineEdit": async ( + prompt: string, + range: vscode.Range, + ) => { + captureCommandTelemetry("customQuickActionStreamInlineEdit"); + + streamInlineEdit("docstring", prompt, false, range); + }, + "continue.codebaseForceReIndex": async () => { + core.invoke("index/forceReIndex", undefined); + }, + "continue.rebuildCodebaseIndex": async () => { + core.invoke("index/forceReIndex", { shouldClearIndexes: true }); + }, + "continue.docsIndex": async () => { + core.invoke("context/indexDocs", { reIndex: false }); + }, + "continue.docsReIndex": async () => { + core.invoke("context/indexDocs", { reIndex: true }); + }, + "continue.focusContinueInput": async () => { + const historyLength = await sidebar.webviewProtocol.request( + "getWebviewHistoryLength", + undefined, + ); + const isContinueInputFocused = await sidebar.webviewProtocol.request( + "isContinueInputFocused", undefined, ); - const modelTitle = - getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle; - - sidebar.webviewProtocol.request("incrementFtc", undefined); - - await verticalDiffManager.streamEdit( - config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, - modelTitle, - undefined, - onlyOneInsertion, - undefined, - range, - ); - } - - return { - "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { - captureCommandTelemetry("acceptDiff"); - - let fullPath = newFilepath; - - if (fullPath instanceof vscode.Uri) { - fullPath = fullPath.fsPath; - } else if (fullPath) { - fullPath = getFullyQualifiedPath(ide, fullPath); - } else { - console.warn(`Unable to resolve filepath: ${newFilepath}`); - } - - verticalDiffManager.clearForFilepath(fullPath, true); - await diffManager.acceptDiff(fullPath); - await sidebar.webviewProtocol.request("setEditStatus", { - status: "done", - }); - }, - "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { - captureCommandTelemetry("rejectDiff"); - - let fullPath = newFilepath; - - if (fullPath instanceof vscode.Uri) { - fullPath = fullPath.fsPath; - } else if (fullPath) { - fullPath = getFullyQualifiedPath(ide, fullPath); - } else { - console.warn(`Unable to resolve filepath: ${newFilepath}`); - } - - verticalDiffManager.clearForFilepath(fullPath, false); - await diffManager.rejectDiff(fullPath); - await sidebar.webviewProtocol.request("setEditStatus", { - status: "done", - }); - }, - "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { - captureCommandTelemetry("acceptVerticalDiffBlock"); - verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index); - }, - "continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => { - captureCommandTelemetry("rejectVerticalDiffBlock"); - verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index); - }, - "continue.quickFix": async ( - range: vscode.Range, - diagnosticMessage: string, - ) => { - captureCommandTelemetry("quickFix"); - - const prompt = `Please explain the cause of this error and how to solve it: ${diagnosticMessage}`; - - addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - }, - // Passthrough for telemetry purposes - "continue.defaultQuickAction": async (args: QuickEditShowParams) => { - captureCommandTelemetry("defaultQuickAction"); - vscode.commands.executeCommand("continue.quickEdit", args); - }, - "continue.customQuickActionSendToChat": async ( - prompt: string, - range: vscode.Range, - ) => { - captureCommandTelemetry("customQuickActionSendToChat"); - - addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - }, - "continue.customQuickActionStreamInlineEdit": async ( - prompt: string, - range: vscode.Range, - ) => { - captureCommandTelemetry("customQuickActionStreamInlineEdit"); - - streamInlineEdit("docstring", prompt, false, range); - }, - "continue.codebaseForceReIndex": async () => { - core.invoke("index/forceReIndex", undefined); - }, - "continue.rebuildCodebaseIndex": async () => { - core.invoke("index/forceReIndex", { shouldClearIndexes: true }); - }, - "continue.docsIndex": async () => { - core.invoke("context/indexDocs", { reIndex: false }); - }, - "continue.docsReIndex": async () => { - core.invoke("context/indexDocs", { reIndex: true }); - }, - "continue.focusContinueInput": async () => { - const historyLength = await sidebar.webviewProtocol.request( - "getWebviewHistoryLength", - undefined, - ); - const isContinueInputFocused = await sidebar.webviewProtocol.request( - "isContinueInputFocused", - undefined, - ); - - if (isContinueInputFocused) { - if (historyLength === 0) { - hideGUI(); - } else { - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - } - } else { - focusGUI(); - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - await addHighlightedCodeToContext(sidebar.webviewProtocol); - } - }, - "continue.focusContinueInputWithoutClear": async () => { - const isContinueInputFocused = await sidebar.webviewProtocol.request( - "isContinueInputFocused", - undefined, - ); - - if (isContinueInputFocused) { + if (isContinueInputFocused) { + if (historyLength === 0) { hideGUI(); - } else { - focusGUI(); - - sidebar.webviewProtocol?.request( - "focusContinueInputWithoutClear", - undefined, - ); - - await addHighlightedCodeToContext(sidebar.webviewProtocol); - } - }, - "continue.edit": async () => { - captureCommandTelemetry("edit"); - focusGUI(); - - const editor = vscode.window.activeTextEditor; - if (!editor) { - return; - } - - const existingDiff = await verticalDiffManager.getHandlerForFile( - editor.document.fileName, - ); - if (!existingDiff) { - // If there's a diff currently being applied, then we just toggle focus back to the input - editDecorationManager.setDecoration( - editor, - new vscode.Range(editor.selection.start, editor.selection.end), - ); - - const highlightedCode = getCurrentlyHighlightedCode(true)!; - await sidebar.webviewProtocol?.request("startEditMode", { - highlightedCode, - }); - - // Un-select the current selection - editor.selection = new vscode.Selection( - editor.selection.anchor, - editor.selection.anchor, - ); - - setTimeout(() => { - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - }, 30); } else { sidebar.webviewProtocol?.request("focusContinueInput", undefined); } - }, - "continue.exitEditMode": async () => { - captureCommandTelemetry("exitEditMode"); - await sidebar.webviewProtocol?.request("exitEditMode", undefined); - }, - "continue.quickEdit": async (args: QuickEditShowParams) => { - let linesOfCode = undefined; - if (args.range) { - linesOfCode = args.range.end.line - args.range.start.line; - } - captureCommandTelemetry("quickEdit", { - linesOfCode, - }); - quickEdit.show(args); - }, - "continue.writeCommentsForCode": async () => { - captureCommandTelemetry("writeCommentsForCode"); + } else { + focusGUI(); + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + await addHighlightedCodeToContext(sidebar.webviewProtocol); + } + }, + "continue.focusContinueInputWithoutClear": async () => { + const isContinueInputFocused = await sidebar.webviewProtocol.request( + "isContinueInputFocused", + undefined, + ); - streamInlineEdit( - "comment", - "Write comments for this code. Do not change anything about the code itself.", - ); - }, - "continue.writeDocstringForCode": async () => { - captureCommandTelemetry("writeDocstringForCode"); - - streamInlineEdit( - "docstring", - "Write a docstring for this code. Do not change anything about the code itself.", - true, - ); - }, - "continue.fixCode": async () => { - captureCommandTelemetry("fixCode"); - - streamInlineEdit( - "fix", - "Fix this code. If it is already 100% correct, simply rewrite the code.", - ); - }, - "continue.optimizeCode": async () => { - captureCommandTelemetry("optimizeCode"); - streamInlineEdit("optimize", "Optimize this code"); - }, - "continue.fixGrammar": async () => { - captureCommandTelemetry("fixGrammar"); - streamInlineEdit( - "fixGrammar", - "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.", - ); - }, - "continue.viewLogs": async () => { - captureCommandTelemetry("viewLogs"); - - // Open ~/.continue/continue.log - const logFile = path.join(os.homedir(), ".continue", "continue.log"); - // Make sure the file/directory exist - if (!fs.existsSync(logFile)) { - fs.mkdirSync(path.dirname(logFile), { recursive: true }); - fs.writeFileSync(logFile, ""); - } - - const uri = vscode.Uri.file(logFile); - await vscode.window.showTextDocument(uri); - }, - "continue.debugTerminal": async () => { - captureCommandTelemetry("debugTerminal"); - - const terminalContents = await ide.getTerminalContents(); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - - sidebar.webviewProtocol?.request("userInput", { - input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`, - }); - }, - "continue.hideInlineTip": () => { - vscode.workspace - .getConfiguration(EXTENSION_NAME) - .update("showInlineTip", false, vscode.ConfigurationTarget.Global); - }, - - // Commands without keyboard shortcuts - "continue.addModel": () => { - captureCommandTelemetry("addModel"); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webviewProtocol?.request("addModel", undefined); - }, - "continue.openSettingsUI": () => { - vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webviewProtocol?.request("openSettings", undefined); - }, - "continue.sendMainUserInput": (text: string) => { - sidebar.webviewProtocol?.request("userInput", { - input: text, - }); - }, - "continue.selectRange": (startLine: number, endLine: number) => { - if (!vscode.window.activeTextEditor) { - return; - } - vscode.window.activeTextEditor.selection = new vscode.Selection( - startLine, - 0, - endLine, - 0, - ); - }, - "continue.foldAndUnfold": ( - foldSelectionLines: number[], - unfoldSelectionLines: number[], - ) => { - vscode.commands.executeCommand("editor.unfold", { - selectionLines: unfoldSelectionLines, - }); - vscode.commands.executeCommand("editor.fold", { - selectionLines: foldSelectionLines, - }); - }, - "continue.sendToTerminal": (text: string) => { - captureCommandTelemetry("sendToTerminal"); - ide.runCommand(text); - }, - "continue.newSession": () => { - sidebar.webviewProtocol?.request("newSession", undefined); - }, - "continue.viewHistory": () => { - sidebar.webviewProtocol?.request("viewHistory", undefined); - }, - "continue.focusContinueSessionId": async ( - sessionId: string | undefined, - ) => { - if (!sessionId) { - sessionId = await vscode.window.showInputBox({ - prompt: "Enter the Session ID", - }); - } - sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); - }, - "continue.applyCodeFromChat": () => { - sidebar.webviewProtocol.request("applyCodeFromChat", undefined); - }, - "continue.toggleFullScreen": () => { + if (isContinueInputFocused) { + hideGUI(); + } else { focusGUI(); - // Check if full screen is already open by checking open tabs - const fullScreenTab = getFullScreenTab(); - - if (fullScreenTab && fullScreenPanel) { - // Full screen open, but not focused - focus it - fullScreenPanel.reveal(); - return; - } - - // Full screen not open - open it - captureCommandTelemetry("openFullScreen"); - - // Create the full screen panel - let panel = vscode.window.createWebviewPanel( - "continue.continueGUIView", - "Continue", - vscode.ViewColumn.One, - { - retainContextWhenHidden: true, - }, - ); - fullScreenPanel = panel; - - // Add content to the panel - panel.webview.html = sidebar.getSidebarContent( - extensionContext, - panel, + sidebar.webviewProtocol?.request( + "focusContinueInputWithoutClear", undefined, - undefined, - true, ); - // When panel closes, reset the webview and focus - panel.onDidDispose( - () => { - sidebar.resetWebviewProtocolWebview(); - vscode.commands.executeCommand("continue.focusContinueInput"); - }, - null, - extensionContext.subscriptions, + await addHighlightedCodeToContext(sidebar.webviewProtocol); + } + }, + "continue.edit": async () => { + captureCommandTelemetry("edit"); + focusGUI(); + + const editor = vscode.window.activeTextEditor; + if (!editor) { + return; + } + + const existingDiff = await verticalDiffManager.getHandlerForFile( + editor.document.fileName, + ); + if (!existingDiff) { + // If there's a diff currently being applied, then we just toggle focus back to the input + editDecorationManager.setDecoration( + editor, + new vscode.Range(editor.selection.start, editor.selection.end), ); - vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow"); - }, - "continue.openConfigJson": () => { - ide.openFile(getConfigJsonPath()); - }, - "continue.selectFilesAsContext": async ( - firstUri: vscode.Uri, - uris: vscode.Uri[], - ) => { - if (uris === undefined) { - throw new Error("No files were selected"); - } + const highlightedCode = getCurrentlyHighlightedCode(true)!; + await sidebar.webviewProtocol?.request("startEditMode", { + highlightedCode, + }); - vscode.commands.executeCommand("continue.continueGUIView.focus"); + // Un-select the current selection + editor.selection = new vscode.Selection( + editor.selection.anchor, + editor.selection.anchor, + ); - for (const uri of uris) { - // If it's a folder, add the entire folder contents recursively by using walkDir (to ignore ignored files) - const isDirectory = await vscode.workspace.fs - .stat(uri) - ?.then((stat) => stat.type === vscode.FileType.Directory); - if (isDirectory) { - for await (const filepath of walkDirAsync(uri.fsPath, ide)) { - addEntireFileToContext( - uriFromFilePath(filepath), - false, - sidebar.webviewProtocol, - ); - } - } else { - addEntireFileToContext(uri, false, sidebar.webviewProtocol); + setTimeout(() => { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + }, 30); + } else { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + } + }, + "continue.exitEditMode": async () => { + captureCommandTelemetry("exitEditMode"); + await sidebar.webviewProtocol?.request("exitEditMode", undefined); + }, + "continue.quickEdit": async (args: QuickEditShowParams) => { + let linesOfCode = undefined; + if (args.range) { + linesOfCode = args.range.end.line - args.range.start.line; + } + captureCommandTelemetry("quickEdit", { + linesOfCode, + }); + quickEdit.show(args); + }, + "continue.writeCommentsForCode": async () => { + captureCommandTelemetry("writeCommentsForCode"); + + streamInlineEdit( + "comment", + "Write comments for this code. Do not change anything about the code itself.", + ); + }, + "continue.writeDocstringForCode": async () => { + captureCommandTelemetry("writeDocstringForCode"); + + streamInlineEdit( + "docstring", + "Write a docstring for this code. Do not change anything about the code itself.", + true, + ); + }, + "continue.fixCode": async () => { + captureCommandTelemetry("fixCode"); + + streamInlineEdit( + "fix", + "Fix this code. If it is already 100% correct, simply rewrite the code.", + ); + }, + "continue.optimizeCode": async () => { + captureCommandTelemetry("optimizeCode"); + streamInlineEdit("optimize", "Optimize this code"); + }, + "continue.fixGrammar": async () => { + captureCommandTelemetry("fixGrammar"); + streamInlineEdit( + "fixGrammar", + "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.", + ); + }, + "continue.viewLogs": async () => { + captureCommandTelemetry("viewLogs"); + + // Open ~/.continue/continue.log + const logFile = path.join(os.homedir(), ".continue", "continue.log"); + // Make sure the file/directory exist + if (!fs.existsSync(logFile)) { + fs.mkdirSync(path.dirname(logFile), { recursive: true }); + fs.writeFileSync(logFile, ""); + } + + const uri = vscode.Uri.file(logFile); + await vscode.window.showTextDocument(uri); + }, + "continue.debugTerminal": async () => { + captureCommandTelemetry("debugTerminal"); + + const terminalContents = await ide.getTerminalContents(); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + + sidebar.webviewProtocol?.request("userInput", { + input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`, + }); + }, + "continue.hideInlineTip": () => { + vscode.workspace + .getConfiguration(EXTENSION_NAME) + .update("showInlineTip", false, vscode.ConfigurationTarget.Global); + }, + + // Commands without keyboard shortcuts + "continue.addModel": () => { + captureCommandTelemetry("addModel"); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + sidebar.webviewProtocol?.request("addModel", undefined); + }, + "continue.openSettingsUI": () => { + vscode.commands.executeCommand("continue.continueGUIView.focus"); + sidebar.webviewProtocol?.request("openSettings", undefined); + }, + "continue.sendMainUserInput": (text: string) => { + sidebar.webviewProtocol?.request("userInput", { + input: text, + }); + }, + "continue.selectRange": (startLine: number, endLine: number) => { + if (!vscode.window.activeTextEditor) { + return; + } + vscode.window.activeTextEditor.selection = new vscode.Selection( + startLine, + 0, + endLine, + 0, + ); + }, + "continue.foldAndUnfold": ( + foldSelectionLines: number[], + unfoldSelectionLines: number[], + ) => { + vscode.commands.executeCommand("editor.unfold", { + selectionLines: unfoldSelectionLines, + }); + vscode.commands.executeCommand("editor.fold", { + selectionLines: foldSelectionLines, + }); + }, + "continue.sendToTerminal": (text: string) => { + captureCommandTelemetry("sendToTerminal"); + ide.runCommand(text); + }, + "continue.newSession": () => { + sidebar.webviewProtocol?.request("newSession", undefined); + }, + "continue.viewHistory": () => { + sidebar.webviewProtocol?.request("viewHistory", undefined); + }, + "continue.focusContinueSessionId": async ( + sessionId: string | undefined, + ) => { + if (!sessionId) { + sessionId = await vscode.window.showInputBox({ + prompt: "Enter the Session ID", + }); + } + sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); + }, + "continue.applyCodeFromChat": () => { + sidebar.webviewProtocol.request("applyCodeFromChat", undefined); + }, + "continue.toggleFullScreen": () => { + focusGUI(); + + // Check if full screen is already open by checking open tabs + const fullScreenTab = getFullScreenTab(); + + if (fullScreenTab && fullScreenPanel) { + // Full screen open, but not focused - focus it + fullScreenPanel.reveal(); + return; + } + + // Full screen not open - open it + captureCommandTelemetry("openFullScreen"); + + // Create the full screen panel + let panel = vscode.window.createWebviewPanel( + "continue.continueGUIView", + "Continue", + vscode.ViewColumn.One, + { + retainContextWhenHidden: true, + }, + ); + fullScreenPanel = panel; + + // Add content to the panel + panel.webview.html = sidebar.getSidebarContent( + extensionContext, + panel, + undefined, + undefined, + true, + ); + + // When panel closes, reset the webview and focus + panel.onDidDispose( + () => { + sidebar.resetWebviewProtocolWebview(); + vscode.commands.executeCommand("continue.focusContinueInput"); + }, + null, + extensionContext.subscriptions, + ); + + vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow"); + }, + "continue.openConfigJson": () => { + ide.openFile(getConfigJsonPath()); + }, + "continue.selectFilesAsContext": async ( + firstUri: vscode.Uri, + uris: vscode.Uri[], + ) => { + if (uris === undefined) { + throw new Error("No files were selected"); + } + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + + for (const uri of uris) { + // If it's a folder, add the entire folder contents recursively by using walkDir (to ignore ignored files) + const isDirectory = await vscode.workspace.fs + .stat(uri) + ?.then((stat) => stat.type === vscode.FileType.Directory); + if (isDirectory) { + for await (const filepath of walkDirAsync(uri.fsPath, ide)) { + addEntireFileToContext( + uriFromFilePath(filepath), + false, + sidebar.webviewProtocol, + ); } + } else { + addEntireFileToContext(uri, false, sidebar.webviewProtocol); } - }, - "continue.logAutocompleteOutcome": ( - completionId: string, - completionProvider: CompletionProvider, - ) => { - completionProvider.accept(completionId); - }, - "continue.toggleTabAutocompleteEnabled": () => { - captureCommandTelemetry("toggleTabAutocompleteEnabled"); + } + }, + "continue.logAutocompleteOutcome": ( + completionId: string, + completionProvider: CompletionProvider, + ) => { + completionProvider.accept(completionId); + }, + "continue.toggleTabAutocompleteEnabled": () => { + captureCommandTelemetry("toggleTabAutocompleteEnabled"); - const config = vscode.workspace.getConfiguration(EXTENSION_NAME); - const enabled = config.get("enableTabAutocomplete"); - const pauseOnBattery = config.get( - "pauseTabAutocompleteOnBattery", + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + const enabled = config.get("enableTabAutocomplete"); + const pauseOnBattery = config.get( + "pauseTabAutocompleteOnBattery", + ); + if (!pauseOnBattery || battery.isACConnected()) { + config.update( + "enableTabAutocomplete", + !enabled, + vscode.ConfigurationTarget.Global, ); - if (!pauseOnBattery || battery.isACConnected()) { + } else { + if (enabled) { + const paused = getStatusBarStatus() === StatusBarStatus.Paused; + if (paused) { + setupStatusBar(StatusBarStatus.Enabled); + } else { + config.update( + "enableTabAutocomplete", + false, + vscode.ConfigurationTarget.Global, + ); + } + } else { + setupStatusBar(StatusBarStatus.Paused); config.update( "enableTabAutocomplete", - !enabled, + true, vscode.ConfigurationTarget.Global, ); - } else { - if (enabled) { - const paused = getStatusBarStatus() === StatusBarStatus.Paused; - if (paused) { - setupStatusBar(StatusBarStatus.Enabled); - } else { - config.update( - "enableTabAutocomplete", - false, - vscode.ConfigurationTarget.Global, - ); - } - } else { - setupStatusBar(StatusBarStatus.Paused); - config.update( - "enableTabAutocomplete", - true, - vscode.ConfigurationTarget.Global, - ); - } } - }, - "continue.openTabAutocompleteConfigMenu": async () => { - captureCommandTelemetry("openTabAutocompleteConfigMenu"); + } + }, + "continue.openTabAutocompleteConfigMenu": async () => { + captureCommandTelemetry("openTabAutocompleteConfigMenu"); - const config = vscode.workspace.getConfiguration(EXTENSION_NAME); - const quickPick = vscode.window.createQuickPick(); - const autocompleteModels = - (await configHandler.loadConfig())?.tabAutocompleteModels ?? []; + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + const quickPick = vscode.window.createQuickPick(); + const autocompleteModels = + (await configHandler.loadConfig())?.tabAutocompleteModels ?? []; - let selected = new GlobalContext().get("selectedTabAutocompleteModel"); - if ( - !selected || - !autocompleteModels.some((model) => model.title === selected) - ) { - selected = autocompleteModels[0].title; - } + let selected = new GlobalContext().get("selectedTabAutocompleteModel"); + if ( + !selected || + !autocompleteModels.some((model) => model.title === selected) + ) { + selected = autocompleteModels[0].title; + } - // Toggle between Disabled, Paused, and Enabled - const pauseOnBattery = - config.get("pauseTabAutocompleteOnBattery") && - !battery.isACConnected(); - const currentStatus = getStatusBarStatus(); + // Toggle between Disabled, Paused, and Enabled + const pauseOnBattery = + config.get("pauseTabAutocompleteOnBattery") && + !battery.isACConnected(); + const currentStatus = getStatusBarStatus(); - let targetStatus: StatusBarStatus | undefined; - if (pauseOnBattery) { - // Cycle from Disabled -> Paused -> Enabled - targetStatus = - currentStatus === StatusBarStatus.Paused - ? StatusBarStatus.Enabled - : currentStatus === StatusBarStatus.Disabled - ? StatusBarStatus.Paused - : StatusBarStatus.Disabled; - } else { - // Toggle between Disabled and Enabled - targetStatus = - currentStatus === StatusBarStatus.Disabled - ? StatusBarStatus.Enabled + let targetStatus: StatusBarStatus | undefined; + if (pauseOnBattery) { + // Cycle from Disabled -> Paused -> Enabled + targetStatus = + currentStatus === StatusBarStatus.Paused + ? StatusBarStatus.Enabled + : currentStatus === StatusBarStatus.Disabled + ? StatusBarStatus.Paused : StatusBarStatus.Disabled; - } - quickPick.items = [ - { - label: "$(question) Open help center", - }, - { - label: "$(comment) Open chat (Cmd+L)", - }, - { - label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", - }, - { - label: quickPickStatusText(targetStatus), - }, - { - label: "$(gear) Configure autocomplete options", - }, - { - label: "$(feedback) Give feedback", - }, - { - kind: vscode.QuickPickItemKind.Separator, - label: "Switch model", - }, - ...autocompleteModels.map((model) => ({ - label: getAutocompleteStatusBarTitle(selected, model), - description: getAutocompleteStatusBarDescription(selected, model), - })), - ]; - quickPick.onDidAccept(() => { - const selectedOption = quickPick.selectedItems[0].label; - const targetStatus = - getStatusBarStatusFromQuickPickItemLabel(selectedOption); + } else { + // Toggle between Disabled and Enabled + targetStatus = + currentStatus === StatusBarStatus.Disabled + ? StatusBarStatus.Enabled + : StatusBarStatus.Disabled; + } + quickPick.items = [ + { + label: "$(question) Open help center", + }, + { + label: "$(comment) Open chat (Cmd+L)", + }, + { + label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", + }, + { + label: quickPickStatusText(targetStatus), + }, + { + label: "$(gear) Configure autocomplete options", + }, + { + label: "$(feedback) Give feedback", + }, + { + kind: vscode.QuickPickItemKind.Separator, + label: "Switch model", + }, + ...autocompleteModels.map((model) => ({ + label: getAutocompleteStatusBarTitle(selected, model), + description: getAutocompleteStatusBarDescription(selected, model), + })), + ]; + quickPick.onDidAccept(() => { + const selectedOption = quickPick.selectedItems[0].label; + const targetStatus = + getStatusBarStatusFromQuickPickItemLabel(selectedOption); - if (targetStatus !== undefined) { - setupStatusBar(targetStatus); - config.update( - "enableTabAutocomplete", - targetStatus === StatusBarStatus.Enabled, - vscode.ConfigurationTarget.Global, - ); - } else if ( - selectedOption === "$(gear) Configure autocomplete options" - ) { - ide.openFile(getConfigJsonPath()); - } else if ( - autocompleteModels.some((model) => model.title === selectedOption) - ) { - new GlobalContext().update( - "selectedTabAutocompleteModel", - selectedOption, - ); - configHandler.reloadConfig(); - } else if (selectedOption === "$(feedback) Give feedback") { - vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); - } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { - vscode.commands.executeCommand("continue.focusContinueInput"); - } else if ( - selectedOption === - "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" - ) { - vscode.commands.executeCommand("continue.toggleFullScreen"); - } else if (selectedOption === "$(question) Open help center") { - focusGUI(); - vscode.commands.executeCommand("continue.navigateTo", "/more"); - } - quickPick.dispose(); - }); - quickPick.show(); - }, - "continue.giveAutocompleteFeedback": async () => { - const feedback = await vscode.window.showInputBox({ - ignoreFocusOut: true, - prompt: - "Please share what went wrong with the last completion. The details of the completion as well as this message will be sent to the Continue team in order to improve.", - }); - if (feedback) { - const client = await continueServerClientPromise; - const completionsPath = getDevDataFilePath("autocomplete"); - - const lastLines = await readLastLines.read(completionsPath, 2); - client.sendFeedback(feedback, lastLines); + if (targetStatus !== undefined) { + setupStatusBar(targetStatus); + config.update( + "enableTabAutocomplete", + targetStatus === StatusBarStatus.Enabled, + vscode.ConfigurationTarget.Global, + ); + } else if ( + selectedOption === "$(gear) Configure autocomplete options" + ) { + ide.openFile(getConfigJsonPath()); + } else if ( + autocompleteModels.some((model) => model.title === selectedOption) + ) { + new GlobalContext().update( + "selectedTabAutocompleteModel", + selectedOption, + ); + configHandler.reloadConfig(); + } else if (selectedOption === "$(feedback) Give feedback") { + vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); + } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { + vscode.commands.executeCommand("continue.focusContinueInput"); + } else if ( + selectedOption === + "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" + ) { + vscode.commands.executeCommand("continue.toggleFullScreen"); + } else if (selectedOption === "$(question) Open help center") { + focusGUI(); + vscode.commands.executeCommand("continue.navigateTo", "/more"); } - }, - "continue.navigateTo": (path: string) => { - sidebar.webviewProtocol?.request("navigateTo", { path }); - focusGUI(); - }, - }; + quickPick.dispose(); + }); + quickPick.show(); + }, + "continue.giveAutocompleteFeedback": async () => { + const feedback = await vscode.window.showInputBox({ + ignoreFocusOut: true, + prompt: + "Please share what went wrong with the last completion. The details of the completion as well as this message will be sent to the Continue team in order to improve.", + }); + if (feedback) { + const client = await continueServerClientPromise; + const completionsPath = getDevDataFilePath("autocomplete"); + + const lastLines = await readLastLines.read(completionsPath, 2); + client.sendFeedback(feedback, lastLines); + } + }, + "continue.navigateTo": (path: string) => { + sidebar.webviewProtocol?.request("navigateTo", { path }); + focusGUI(); + }, }; +}; export function registerAllCommands( context: vscode.ExtensionContext, diff --git a/gui/src/components/find/FindWidget.tsx b/gui/src/components/find/FindWidget.tsx index bc4f3f7ef..f7f0d6101 100644 --- a/gui/src/components/find/FindWidget.tsx +++ b/gui/src/components/find/FindWidget.tsx @@ -1,8 +1,7 @@ -import React, { useRef, useEffect, useState, RefObject, useCallback } from 'react'; +import React, { useRef, useEffect, useState, RefObject, useCallback, useMemo } from 'react'; import { RootState } from '../../redux/store'; import { useSelector } from 'react-redux'; import { Button, HeaderButton, Input } from '..'; -import useWindowSize from '../../hooks/useWindowSize'; import ButtonWithTooltip from '../ButtonWithTooltip'; import { ArrowDownIcon, ArrowUpIcon, XMarkIcon } from '@heroicons/react/24/outline'; @@ -13,6 +12,7 @@ interface SearchMatch { } const SEARCH_DEBOUNCE = 500 +const RESIZE_DEBOUNCE = 200 interface Rectangle { top: number; @@ -43,85 +43,22 @@ const HighlightOverlay = (props: HighlightOverlayProps) => { ) } +/* + useFindWidget takes a container ref and returns + 1. A widget that can be placed anywhere to search the contents of that container + 2. Search results and state + 3. Highlight components to be overlayed over the container + + Container must have relative positioning +*/ export const useFindWidget = (searchRef: RefObject) => { - // Search input - const [currentMatch, setCurrentMatch] = useState(); + // Used to disable search when chat is loading + const active = useSelector((state: RootState) => state.state.active); - - - - // Handle container resizing - const [isResizing, setIsResizing] = useState(false); - useEffect(() => { - let timeoutId: NodeJS.Timeout | null = null; - const handleResize = () => { - if (timeoutId) { - clearTimeout(timeoutId); - } - setIsResizing(true); - timeoutId = setTimeout(() => { - setIsResizing(false) - }, 200); - }; - - window.addEventListener('resize', handleResize); - return () => { - if (timeoutId) { - clearTimeout(timeoutId); - } - window.removeEventListener('resize', handleResize); - }; - }, [200]); - - // useEffect(() => { - // if (!searchRef.current) return - // let timeoutId: NodeJS.Timeout | null = null; - - // // const handleResize = () => { - // // if (timeoutId) { - // // clearTimeout(timeoutId); - // // } - // // setIsMutating(true); - - // // timeoutId = setTimeout(() => { - // // setIsMutating(false) - // // }, 200); - // // }; - // const observer = new MutationObserver(mutations => { - // if (timeoutId) { - // clearTimeout(timeoutId); - // } - // setIsMutating(true); - - // timeoutId = setTimeout(() => { - // setIsMutating(false) - // }, 200); - // // mutations.forEach(mutation => { - - // // }); - // }); - // observer.observe(searchRef.current, { - // // characterData: true, - // // childList: true, - // attributes: true - // }) - // return () => { - // if (timeoutId) { - // clearTimeout(timeoutId); - // } - // observer.disconnect(); - // }; - // }, [searchRef.current]); - - - - - - - const inputRef = useRef(null) as RefObject; + // Search input, debounced const [input, setInput] = useState(""); - const [debouncedInput, setDebouncedInput] = useState(""); + const inputRef = useRef(null) as RefObject; const lastUpdateRef = useRef(0); useEffect(() => { @@ -140,15 +77,22 @@ export const useFindWidget = (searchRef: RefObject) => { } }, [input]); - + // Widget open/closed state const [open, setOpen] = useState(false); + const openWidget = useCallback(() => { + setOpen(true); + inputRef?.current.select() + }, [setOpen, inputRef]) + + // Search settings and results const [caseSensitive, setCaseSensitive] = useState(false); const [useRegex, setUseRegex] = useState(false); - const active = useSelector((state: RootState) => state.state.active); - const [matches, setMatches] = useState([]); + const [currentMatch, setCurrentMatch] = useState(); + // Navigating between search results + // The "current" search result is highlighted a different color const scrollToMatch = useCallback((match: SearchMatch) => { setCurrentMatch(match) searchRef.current.scrollTo({ @@ -158,6 +102,72 @@ export const useFindWidget = (searchRef: RefObject) => { }) }, [searchRef.current]) + const nextMatch = useCallback(() => { + if (matches.length === 0) return + const newIndex = (currentMatch.index + 1) % matches.length; + const newMatch = matches[newIndex] + scrollToMatch(newMatch) + }, [scrollToMatch, currentMatch, matches]) + + const previousMatch = useCallback(() => { + if (matches.length === 0) return + const newIndex = currentMatch.index === 0 ? matches.length - 1 : currentMatch.index - 1 + const newMatch = matches[newIndex] + scrollToMatch(newMatch) + }, [scrollToMatch, currentMatch, matches]) + + // Handle keyboard shortcuts for navigation + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + if (event.metaKey && event.key.toLowerCase() === 'f') { + event.preventDefault(); + event.stopPropagation(); + openWidget(); + } else if (document.activeElement === inputRef.current) { + if (event.key === 'Escape') { + event.preventDefault(); + event.stopPropagation(); + setOpen(false); + } else if (event.key === 'Enter') { + event.preventDefault(); + event.stopPropagation(); + if (event.shiftKey) previousMatch() + else nextMatch() + } + } + } + + document.addEventListener('keydown', handleKeyDown); + return () => { + document.removeEventListener('keydown', handleKeyDown); + }; + }, [inputRef, matches, nextMatch]); + + // Handle container resize changes - highlight positions must adjust + const [isResizing, setIsResizing] = useState(false); + useEffect(() => { + let timeoutId: NodeJS.Timeout | null = null; + const handleResize = () => { + if (timeoutId) { + clearTimeout(timeoutId); + } + setIsResizing(true); + timeoutId = setTimeout(() => { + setIsResizing(false) + }, RESIZE_DEBOUNCE); + }; + + window.addEventListener('resize', handleResize); + return () => { + if (timeoutId) { + clearTimeout(timeoutId); + } + window.removeEventListener('resize', handleResize); + }; + }, []); + + // The bread and butter: + // const loadHighlights = useCallback((_query: string | undefined, scrollTo: 'first' | 'closest' | 'none' = 'none') => { if (!searchRef.current || !_query) { setMatches([]); @@ -166,7 +176,6 @@ export const useFindWidget = (searchRef: RefObject) => { const query = caseSensitive ? _query : _query.toLowerCase() const textNodes: Text[] = []; - const start = Date.now() const walker = document.createTreeWalker( searchRef.current, NodeFilter.SHOW_ALL, @@ -233,11 +242,11 @@ export const useFindWidget = (searchRef: RefObject) => { } index++; - startIndex += query.length; // Move past this match + startIndex += query.length; range.detach(); } }); - console.log(`Found ${textNodes.length} nodes in ${Date.now() - start}ms`); + setMatches(newMatches); if (query.length > 1 && newMatches.length) { if (scrollTo === 'first') { @@ -249,124 +258,74 @@ export const useFindWidget = (searchRef: RefObject) => { } }, [searchRef.current, caseSensitive, useRegex, scrollToMatch]) + // Trigger searches or clearing results on state changes useEffect(() => { if (active || !open || isResizing) setMatches([]) else loadHighlights(debouncedInput, 'closest'); }, [debouncedInput, loadHighlights, active, open, isResizing]); - - // Widget settings - - - // Manage widget opened/close state - const openWidget = useCallback(() => { - setOpen(true); - inputRef?.current.select() - }, [setOpen, inputRef]) - - const nextMatch = useCallback(() => { - if (matches.length === 0) return - const newIndex = (currentMatch.index + 1) % matches.length; - const newMatch = matches[newIndex] - scrollToMatch(newMatch) - }, [scrollToMatch, currentMatch, matches]) - - const previousMatch = useCallback(() => { - if (matches.length === 0) return - const newIndex = currentMatch.index === 0 ? matches.length - 1 : currentMatch.index - 1 - const newMatch = matches[newIndex] - scrollToMatch(newMatch) - }, [scrollToMatch, currentMatch, matches]) - - useEffect(() => { - const handleKeyDown = (event: KeyboardEvent) => { - if (event.metaKey && event.key.toLowerCase() === 'f') { - event.preventDefault(); - event.stopPropagation(); - openWidget(); - } else if (document.activeElement === inputRef.current) { - if (event.key === 'Escape') { - event.preventDefault(); - event.stopPropagation(); - setOpen(false); - } else if (event.key === 'Enter') { - event.preventDefault(); - event.stopPropagation(); - if (event.shiftKey) previousMatch() - else nextMatch() - } - } - } - - document.addEventListener('keydown', handleKeyDown); - return () => { - document.removeEventListener('keydown', handleKeyDown); - }; - }, [inputRef, matches, nextMatch]); - - const widget = ( -
- { - setInput(e.target.value); - }} - placeholder="Search..." - /> -

- {matches.length === 0 ? "No results" : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`} -

-
+ // Find widget component + const widget = useMemo(() => { + return ( +
+ { + setInput(e.target.value); + }} + placeholder="Search..." + /> +

+ {matches.length === 0 ? "No results" : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`} +

+
+ + + + + + +
setCaseSensitive(curr => !curr)} + className='h-4 w-4 text-xs' > - + Aa - setOpen(false)} > - - + +
- setCaseSensitive(curr => !curr)} - className='h-4 w-4 text-xs' - > + ) + }, [open, input, inputRef, caseSensitive, matches, currentMatch, previousMatch, nextMatch]) - Aa - - - {/* */} - setOpen(false)} - > - - -
- ) - - const highlights = matches.map(match => ) + // Generate the highlight overlay elements + const highlights = useMemo(() => { + return matches.map(match => ) + }, [matches, currentMatch]) return { matches, diff --git a/gui/src/hooks/useWindowSize.ts b/gui/src/hooks/useWindowSize.ts deleted file mode 100644 index 64e85f37e..000000000 --- a/gui/src/hooks/useWindowSize.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { useState, useEffect } from 'react'; - -function useWindowSize(debounce = 50) { - const [isResizing, setIsResizing] = useState(false); - const [windowSize, setWindowSize] = useState({ - width: window.innerWidth, - height: window.innerHeight, - }); - - useEffect(() => { - let timeoutId: NodeJS.Timeout | null = null; - - const handleResize = () => { - if (timeoutId) { - clearTimeout(timeoutId); - } - setIsResizing(true); - - timeoutId = setTimeout(() => { - setWindowSize({ - width: window.innerWidth, - height: window.innerHeight, - }) - setIsResizing(false) - }, debounce); - }; - - window.addEventListener('resize', handleResize); - return () => { - if (timeoutId) { - clearTimeout(timeoutId); - } - window.removeEventListener('resize', handleResize); - }; - }, [debounce]); - - return { - windowSize, - isResizing - }; -} - -export default useWindowSize;