Elffuss BraidHub

kikocis/continue public

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