| 1 | import { ChevronDownIcon } from "@heroicons/react/24/outline"; |
| 2 | import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; |
| 3 | import { useContext, useEffect, useMemo, useState } from "react"; |
| 4 | import styled from "styled-components"; |
| 5 | import { |
| 6 | defaultBorderRadius, |
| 7 | vscCommandCenterInactiveBorder, |
| 8 | vscEditorBackground, |
| 9 | } from "../.."; |
| 10 | import { IdeMessengerContext } from "../../../context/IdeMessenger"; |
| 11 | import { useIdeMessengerRequest } from "../../../hooks/useIdeMessengerRequest"; |
| 12 | import { useWebviewListener } from "../../../hooks/useWebviewListener"; |
| 13 | import { useAppSelector } from "../../../redux/hooks"; |
| 14 | import { selectCurrentToolCallApplyState } from "../../../redux/selectors/selectCurrentToolCall"; |
| 15 | import { selectApplyStateByStreamId } from "../../../redux/slices/sessionSlice"; |
| 16 | import { getFontSize } from "../../../util"; |
| 17 | import Spinner from "../../gui/Spinner"; |
| 18 | import { isTerminalCodeBlock } from "../utils"; |
| 19 | import { ApplyActions } from "./ApplyActions"; |
| 20 | import { CopyButton } from "./CopyButton"; |
| 21 | import { CreateFileButton } from "./CreateFileButton"; |
| 22 | import { FileInfo } from "./FileInfo"; |
| 23 | import { InsertButton } from "./InsertButton"; |
| 24 | import { RunInTerminalButton } from "./RunInTerminalButton"; |
| 25 | |
| 26 | const TopDiv = styled.div` |
| 27 | display: flex; |
| 28 | flex-direction: column; |
| 29 | outline: 1px solid ${vscCommandCenterInactiveBorder}; |
| 30 | outline-offset: -0.5px; |
| 31 | border-radius: ${defaultBorderRadius}; |
| 32 | margin-bottom: 8px !important; |
| 33 | margin-top: 8px !important; |
| 34 | background-color: ${vscEditorBackground}; |
| 35 | min-width: 0; |
| 36 | `; |
| 37 | |
| 38 | const ToolbarDiv = styled.div<{ isExpanded: boolean }>` |
| 39 | display: flex; |
| 40 | justify-content: space-between; |
| 41 | align-items: center; |
| 42 | font-size: ${getFontSize() - 2}px; |
| 43 | padding: 4px 6px; |
| 44 | margin: 0; |
| 45 | border-bottom: ${({ isExpanded }) => |
| 46 | isExpanded ? `1px solid ${vscCommandCenterInactiveBorder}` : "inherit"}; |
| 47 | `; |
| 48 | |
| 49 | export interface StepContainerPreToolbarProps { |
| 50 | codeBlockContent: string; |
| 51 | language: string | null; |
| 52 | relativeFilepath?: string; |
| 53 | itemIndex?: number; |
| 54 | codeBlockIndex: number; // To track which codeblock we are applying |
| 55 | isLastCodeblock: boolean; |
| 56 | codeBlockStreamId: string; |
| 57 | range?: string; |
| 58 | children: any; |
| 59 | expanded?: boolean; |
| 60 | disableManualApply?: boolean; |
| 61 | } |
| 62 | |
| 63 | export function StepContainerPreToolbar({ |
| 64 | codeBlockContent, |
| 65 | language, |
| 66 | relativeFilepath, |
| 67 | itemIndex, |
| 68 | codeBlockIndex, |
| 69 | isLastCodeblock, |
| 70 | codeBlockStreamId, |
| 71 | range, |
| 72 | children, |
| 73 | expanded, |
| 74 | disableManualApply, |
| 75 | }: StepContainerPreToolbarProps) { |
| 76 | const ideMessenger = useContext(IdeMessengerContext); |
| 77 | const history = useAppSelector((state) => state.session.history); |
| 78 | const [isExpanded, setIsExpanded] = useState(expanded ?? true); |
| 79 | |
| 80 | const [relativeFilepathUri, setRelativeFilepathUri] = useState<string | null>( |
| 81 | null, |
| 82 | ); |
| 83 | |
| 84 | const fileExistsInput = useMemo( |
| 85 | () => (relativeFilepathUri ? { filepath: relativeFilepathUri } : null), |
| 86 | [relativeFilepathUri], |
| 87 | ); |
| 88 | |
| 89 | const { |
| 90 | result: fileExists, |
| 91 | refresh: refreshFileExists, |
| 92 | isLoading: isLoadingFileExists, |
| 93 | } = useIdeMessengerRequest("fileExists", fileExistsInput); |
| 94 | |
| 95 | const nextCodeBlockIndex = useAppSelector( |
| 96 | (state) => state.session.codeBlockApplyStates.curIndex, |
| 97 | ); |
| 98 | |
| 99 | const applyState = useAppSelector((state) => |
| 100 | selectApplyStateByStreamId(state, codeBlockStreamId), |
| 101 | ); |
| 102 | const currentToolCallApplyState = useAppSelector( |
| 103 | selectCurrentToolCallApplyState, |
| 104 | ); |
| 105 | |
| 106 | /** |
| 107 | * In the case where `relativeFilepath` is defined, this will just be `relativeFilepathUri`. |
| 108 | * However, if no `relativeFilepath` is defined, then this will |
| 109 | * be the URI of the currently open file at the time the user clicks "Apply". |
| 110 | */ |
| 111 | const [appliedFileUri, setAppliedFileUri] = useState<string | undefined>( |
| 112 | undefined, |
| 113 | ); |
| 114 | |
| 115 | const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex; |
| 116 | const hasFileExtension = |
| 117 | relativeFilepath && /\.[0-9a-z]+$/i.test(relativeFilepath); |
| 118 | |
| 119 | const isStreaming = useAppSelector((store) => store.session.isStreaming); |
| 120 | |
| 121 | const isLastItem = useMemo(() => { |
| 122 | return itemIndex === history.length - 1; |
| 123 | }, [history.length, itemIndex]); |
| 124 | |
| 125 | const isGeneratingCodeBlock = isLastItem && isLastCodeblock && isStreaming; |
| 126 | |
| 127 | // If we are creating a file, we already render that in the button |
| 128 | // so we don't want to dispaly it twice here |
| 129 | const displayFilepath = relativeFilepath ?? appliedFileUri; |
| 130 | |
| 131 | // TODO: This logic should be moved to a thunk |
| 132 | // Handle apply keyboard shortcut |
| 133 | useWebviewListener( |
| 134 | "applyCodeFromChat", |
| 135 | async () => onClickApply(), |
| 136 | [isNextCodeBlock, codeBlockContent], |
| 137 | !isNextCodeBlock, |
| 138 | ); |
| 139 | |
| 140 | useEffect(() => { |
| 141 | const getRelativeFilepathUri = async () => { |
| 142 | if (relativeFilepath) { |
| 143 | const resolvedUri = await inferResolvedUriFromRelativePath( |
| 144 | relativeFilepath, |
| 145 | ideMessenger.ide, |
| 146 | ); |
| 147 | setRelativeFilepathUri(resolvedUri); |
| 148 | } |
| 149 | }; |
| 150 | getRelativeFilepathUri(); |
| 151 | }, [relativeFilepath, ideMessenger.ide]); |
| 152 | |
| 153 | async function getFileUriToApplyTo() { |
| 154 | // If we've already resolved a file URI (from clicking apply), use that |
| 155 | if (appliedFileUri) { |
| 156 | return appliedFileUri; |
| 157 | } |
| 158 | |
| 159 | // If we have the `relativeFilepathUri`, use that |
| 160 | if (relativeFilepathUri) { |
| 161 | return relativeFilepathUri; |
| 162 | } |
| 163 | |
| 164 | // If no filepath was provided, get the current file |
| 165 | const currentFile = await ideMessenger.ide.getCurrentFile(); |
| 166 | if (currentFile) { |
| 167 | return currentFile.path; |
| 168 | } |
| 169 | |
| 170 | return undefined; |
| 171 | } |
| 172 | |
| 173 | async function onClickApply() { |
| 174 | const fileUri = await getFileUriToApplyTo(); |
| 175 | if (!fileUri) { |
| 176 | ideMessenger.ide.showToast( |
| 177 | "error", |
| 178 | "Could not resolve filepath to apply changes", |
| 179 | ); |
| 180 | return; |
| 181 | } |
| 182 | |
| 183 | // applyToFile will create the file if it doesn't exist |
| 184 | ideMessenger.post("applyToFile", { |
| 185 | streamId: codeBlockStreamId, |
| 186 | filepath: fileUri, |
| 187 | text: codeBlockContent, |
| 188 | }); |
| 189 | |
| 190 | setAppliedFileUri(fileUri); |
| 191 | refreshFileExists(); |
| 192 | } |
| 193 | |
| 194 | function onClickInsertAtCursor() { |
| 195 | ideMessenger.post("insertAtCursor", { text: codeBlockContent }); |
| 196 | } |
| 197 | |
| 198 | async function handleDiffAction(action: "accept" | "reject") { |
| 199 | const filepath = await getFileUriToApplyTo(); |
| 200 | if (!filepath) { |
| 201 | ideMessenger.ide.showToast( |
| 202 | "error", |
| 203 | `Could not resolve filepath to ${action} changes`, |
| 204 | ); |
| 205 | return; |
| 206 | } |
| 207 | |
| 208 | ideMessenger.post(`${action}Diff`, { |
| 209 | filepath, |
| 210 | streamId: codeBlockStreamId, |
| 211 | }); |
| 212 | |
| 213 | setAppliedFileUri(undefined); |
| 214 | } |
| 215 | |
| 216 | async function onClickFilename() { |
| 217 | if (appliedFileUri) { |
| 218 | ideMessenger.post("showFile", { |
| 219 | filepath: appliedFileUri, |
| 220 | }); |
| 221 | } |
| 222 | |
| 223 | if (relativeFilepath) { |
| 224 | const filepath = await inferResolvedUriFromRelativePath( |
| 225 | relativeFilepath, |
| 226 | ideMessenger.ide, |
| 227 | ); |
| 228 | |
| 229 | ideMessenger.post("showFile", { |
| 230 | filepath, |
| 231 | }); |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | const renderActionButtons = () => { |
| 236 | const isPendingToolCall = |
| 237 | currentToolCallApplyState && |
| 238 | currentToolCallApplyState.streamId === applyState?.streamId && |
| 239 | currentToolCallApplyState.status === "not-started"; |
| 240 | |
| 241 | if (isGeneratingCodeBlock || isPendingToolCall) { |
| 242 | const numLines = codeBlockContent.split("\n").length; |
| 243 | const plural = numLines === 1 ? "" : "s"; |
| 244 | if (isGeneratingCodeBlock) { |
| 245 | return ( |
| 246 | <span className="text-lightgray inline-flex items-center gap-2 text-right"> |
| 247 | {!isExpanded ? `${numLines} line${plural}` : "Generating"}{" "} |
| 248 | <div> |
| 249 | <Spinner /> |
| 250 | </div> |
| 251 | </span> |
| 252 | ); |
| 253 | } else { |
| 254 | return ( |
| 255 | <span className="text-lightgray inline-flex items-center gap-2 text-right"> |
| 256 | {`${numLines} line${plural} pending`} |
| 257 | </span> |
| 258 | ); |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | if (isTerminalCodeBlock(language, codeBlockContent)) { |
| 263 | return <RunInTerminalButton command={codeBlockContent} />; |
| 264 | } |
| 265 | |
| 266 | if (isLoadingFileExists) { |
| 267 | return null; |
| 268 | } |
| 269 | |
| 270 | if (fileExists || !relativeFilepath) { |
| 271 | return ( |
| 272 | <ApplyActions |
| 273 | disableManualApply={disableManualApply} |
| 274 | applyState={applyState} |
| 275 | onClickApply={onClickApply} |
| 276 | onClickAccept={() => handleDiffAction("accept")} |
| 277 | onClickReject={() => handleDiffAction("reject")} |
| 278 | /> |
| 279 | ); |
| 280 | } |
| 281 | |
| 282 | return <CreateFileButton onClick={onClickApply} />; |
| 283 | }; |
| 284 | |
| 285 | // We wait until there is an extension in the filepath to avoid rendering |
| 286 | // an incomplete filepath |
| 287 | if (relativeFilepath && !hasFileExtension) { |
| 288 | return children; |
| 289 | } |
| 290 | |
| 291 | return ( |
| 292 | <TopDiv> |
| 293 | <ToolbarDiv isExpanded={isExpanded} className="find-widget-skip gap-3"> |
| 294 | <div className="max-w-[50% flex flex-row items-center"> |
| 295 | <ChevronDownIcon |
| 296 | onClick={() => setIsExpanded(!isExpanded)} |
| 297 | className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer hover:brightness-125 ${ |
| 298 | isExpanded ? "rotate-0" : "-rotate-90" |
| 299 | }`} |
| 300 | /> |
| 301 | {displayFilepath ? ( |
| 302 | <FileInfo |
| 303 | filepath={displayFilepath} |
| 304 | range={range} |
| 305 | onClick={fileExists ? onClickFilename : undefined} |
| 306 | /> |
| 307 | ) : ( |
| 308 | <span className="text-lightgray ml-2 select-none capitalize"> |
| 309 | {language} |
| 310 | </span> |
| 311 | )} |
| 312 | </div> |
| 313 | |
| 314 | <div className="flex items-center gap-2.5"> |
| 315 | {!isGeneratingCodeBlock && ( |
| 316 | <div className="xs:flex hidden items-center gap-2.5"> |
| 317 | <InsertButton onInsert={onClickInsertAtCursor} /> |
| 318 | <CopyButton text={codeBlockContent} /> |
| 319 | </div> |
| 320 | )} |
| 321 | |
| 322 | {renderActionButtons()} |
| 323 | </div> |
| 324 | </ToolbarDiv> |
| 325 | |
| 326 | {isExpanded && ( |
| 327 | <div className="overflow-hidden overflow-y-auto">{children}</div> |
| 328 | )} |
| 329 | </TopDiv> |
| 330 | ); |
| 331 | } |