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