Elffuss BraidHub

kikocis/continue public

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