Elffuss BraidHub

kikocis/continue public

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