Elffuss BraidHub

kikocis/continue public

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