Elffuss BraidHub

kikocis/continue public

d7c7c28e99d9 · 16.4 KiBRawPermalink
1import {
2 ArrowRightIcon,
3 AtSymbolIcon,
4 ChatBubbleLeftIcon,
5 PlusIcon,
6} from "@heroicons/react/24/outline";
7import type { Editor } from "@tiptap/react";
8import type { RangeInFile } from "core";
9import {
10 forwardRef,
11 useContext,
12 useEffect,
13 useImperativeHandle,
14 useRef,
15 useState,
16} from "react";
17import { useDispatch } from "react-redux";
18import styled from "styled-components";
19import {
20 defaultBorderRadius,
21 lightGray,
22 vscForeground,
23 vscListActiveBackground,
24 vscListActiveForeground,
25 vscQuickInputBackground,
26} from "../..";
27import { IdeMessengerContext } from "../../../context/IdeMessenger";
28import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice";
29import { fontSize } from "../../../util";
30import FileIcon from "../../FileIcon";
31import SafeImg from "../../SafeImg";
32import AddDocsDialog from "../../dialogs/AddDocsDialog";
33import HeaderButtonWithToolTip from "../../gui/HeaderButtonWithToolTip";
34import { NAMED_ICONS } from "../icons";
35import type { ComboBoxItem, ComboBoxItemType } from "../types";
36
37export function getIconFromDropdownItem(
38 id: string | undefined,
39 type: ComboBoxItemType,
40) {
41 const typeIcon =
42 type === "contextProvider" ? AtSymbolIcon : ChatBubbleLeftIcon;
43 return id ? (NAMED_ICONS[id] ?? typeIcon) : typeIcon;
44}
45
46function DropdownIcon(props: { className?: string; item: ComboBoxItem }) {
47 if (props.item.type === "action") {
48 return <PlusIcon className={props.className + " h-3 w-3"} />;
49 }
50
51 const provider =
52 props.item.type === "contextProvider" || props.item.type === "slashCommand"
53 ? props.item.id
54 : props.item.type;
55
56 const IconComponent = getIconFromDropdownItem(provider, props.item.type);
57
58 const fallbackIcon = (
59 <IconComponent
60 className={`${props.className} flex-shrink-0`}
61 height="1.2em"
62 width="1.2em"
63 />
64 );
65
66 if (!props.item.icon) {
67 return fallbackIcon;
68 }
69
70 return (
71 <SafeImg
72 className="flex-shrink-0 pr-2"
73 src={props.item.icon}
74 height="18em"
75 width="18em"
76 fallback={fallbackIcon}
77 />
78 );
79}
80
81const ItemsDiv = styled.div`
82 border-radius: ${defaultBorderRadius};
83 box-shadow:
84 0 0 0 1px rgba(0, 0, 0, 0.05),
85 0px 10px 20px rgba(0, 0, 0, 0.1);
86 font-size: ${fontSize(-2)};
87 overflow-x: hidden;
88 overflow-y: auto;
89 max-height: 330px;
90 padding: 0.2rem;
91 position: relative; // absolute to test tippy.js bug
92
93 background-color: ${vscQuickInputBackground};
94 /* backdrop-filter: blur(12px); */
95`;
96
97const ItemDiv = styled.div`
98 background: transparent;
99 border: 1px solid transparent;
100 border-radius: 0.4rem;
101 display: block;
102 margin: 0;
103 padding: 2px 4px;
104 text-align: left;
105 width: 100%;
106 color: ${vscForeground};
107 font-size: ${fontSize(-2)};
108
109 &.is-selected {
110 background-color: ${vscListActiveBackground};
111 color: ${vscListActiveForeground};
112 }
113`;
114
115const QueryInput = styled.textarea`
116 background-color: #fff1;
117 border: 1px solid ${lightGray};
118 border-radius: ${defaultBorderRadius};
119
120 padding: 0.2rem 0.4rem;
121 width: 240px;
122
123 color: ${vscForeground};
124
125 &:focus {
126 outline: none;
127 }
128
129 font-family: inherit;
130 resize: none;
131`;
132
133interface AtMentionDropdownProps {
134 items: ComboBoxItem[];
135 command: (item: any) => void;
136
137 editor: Editor;
138 enterSubmenu?: (editor: Editor, providerId: string) => void;
139 onClose: () => void;
140}
141
142const formatFileSize = (fileSize: number) => {
143 const KB = 1000;
144 const MB = 1000_000;
145 const GB = 1000_000_000;
146
147 if (fileSize > GB) {
148 return `${(fileSize / GB).toFixed(1)} GB`;
149 } else if (fileSize > MB) {
150 return `${(fileSize / MB).toFixed(1)} MB`;
151 } else if (fileSize > KB) {
152 return `${(fileSize / KB).toFixed(1)} KB`;
153 }
154
155 return `${fileSize} byte${fileSize > 1 ? "s" : ""}`;
156};
157
158const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
159 const dispatch = useDispatch();
160
161 const ideMessenger = useContext(IdeMessengerContext);
162
163 const [selectedIndex, setSelectedIndex] = useState(0);
164
165 const [subMenuTitle, setSubMenuTitle] = useState<string | undefined>(
166 undefined,
167 );
168 const [querySubmenuItem, setQuerySubmenuItem] = useState<
169 ComboBoxItem | undefined
170 >(undefined);
171 const [loadingSubmenuItem, setLoadingSubmenuItem] = useState<
172 ComboBoxItem | undefined
173 >(undefined);
174
175 const [allItems, setAllItems] = useState<ComboBoxItem[]>([]);
176
177 async function isItemTooBig(
178 name: string,
179 query: string,
180 ): Promise<[boolean, number]> {
181 const selectedCode: RangeInFile[] = [];
182 // Get context item from core
183 const contextResult = await ideMessenger.request(
184 "context/getContextItems",
185 {
186 name,
187 query,
188 fullInput: "",
189 selectedCode,
190 },
191 );
192
193 if (contextResult.status === "error") {
194 return [false, -1];
195 }
196
197 const item = contextResult.content[0];
198
199 // Check if the context item exceeds the context length of the selected model
200 const result = await ideMessenger.request("isItemTooBig", {
201 item,
202 });
203
204 if (result.status === "error") {
205 return [false, -1];
206 }
207
208 const size = new Blob([item.content]).size;
209
210 return [result.content, size];
211 }
212
213 function handleItemTooBig(
214 fileExceeds: boolean,
215 fileSize: number,
216 item: ComboBoxItem,
217 ) {
218 if (fileExceeds) {
219 props.editor
220 .chain()
221 .focus()
222 .command(({ tr, state }) => {
223 const text = state.doc.textBetween(
224 0,
225 state.selection.from,
226 "\n",
227 "\n",
228 ); // Get the text before the cursor
229 const lastAtIndex = text.lastIndexOf("@");
230
231 if (lastAtIndex !== -1) {
232 // Delete text after the last "@"
233 tr.delete(lastAtIndex + 1, state.selection.from);
234 return true;
235 }
236 return false;
237 })
238 .run();
239
240 // Trigger warning message
241 ideMessenger.ide.showToast(
242 "warning",
243 fileSize > 0 ? "File exceeds context length" : "Can't load the file",
244 {
245 modal: true,
246 detail:
247 fileSize > 0
248 ? `'${item.title}' is ${formatFileSize(fileSize)} which exceeds the allowed context length and cannot be processed by the model`
249 : `'${item.title}' could not be loaded. Please check if the file exists and has the correct permissions.`,
250 },
251 );
252 } else {
253 props.command({ ...item, itemType: item.type });
254 }
255 }
256
257 useEffect(() => {
258 const items = [...props.items];
259 if (subMenuTitle === "Type to search docs") {
260 items.push({
261 title: "Add Docs",
262 type: "action",
263 action: () => {
264 dispatch(setShowDialog(true));
265 dispatch(setDialogMessage(<AddDocsDialog />));
266
267 // Delete back to last '@'
268 const { tr } = props.editor.view.state;
269 const text = tr.doc.textBetween(0, tr.selection.from);
270 const start = text.lastIndexOf("@");
271 props.editor.view.dispatch(
272 tr.delete(start, tr.selection.from).scrollIntoView(),
273 );
274 },
275 description: "",
276 });
277 } else if (subMenuTitle === ".prompt files") {
278 items.push({
279 title: "New .prompt file",
280 type: "action",
281 action: () => {
282 ideMessenger.post("config/newPromptFile", undefined);
283 const { tr } = props.editor.view.state;
284 const text = tr.doc.textBetween(0, tr.selection.from);
285 const start = text.lastIndexOf("@");
286 if (start !== -1) {
287 props.editor.view.dispatch(
288 tr.delete(start, tr.selection.from).scrollIntoView(),
289 );
290 }
291 props.onClose(); // Escape the mention list after creating a new prompt file
292 },
293 description: "Create a new .prompt file",
294 });
295 }
296 setLoadingSubmenuItem(items.find((item) => item.id === "loading"));
297 setAllItems(items.filter((item) => item.id !== "loading"));
298 }, [subMenuTitle, props.items, props.editor]);
299
300 const queryInputRef = useRef<HTMLTextAreaElement>(null);
301
302 useEffect(() => {
303 if (queryInputRef.current) {
304 queryInputRef.current.focus();
305 }
306 }, [querySubmenuItem, queryInputRef]);
307
308 const selectItem = (index: number) => {
309 const item = allItems[index];
310
311 if (item.type === "action" && item.action) {
312 item.action();
313 return;
314 }
315
316 if (
317 item.type === "contextProvider" &&
318 item.contextProvider?.type === "submenu"
319 ) {
320 setSubMenuTitle(item.description);
321 if (item.id) {
322 props.enterSubmenu?.(props.editor, item.id);
323 }
324 return;
325 }
326
327 if (item.contextProvider?.type === "query") {
328 // update editor to complete context provider title
329 const { tr } = props.editor.view.state;
330 const text = tr.doc.textBetween(0, tr.selection.from);
331 const partialText = text.slice(text.lastIndexOf("@") + 1);
332 const remainingText = item.title.slice(partialText.length);
333 props.editor.view.dispatch(
334 tr.insertText(remainingText, tr.selection.from),
335 );
336
337 setSubMenuTitle(item.description);
338 setQuerySubmenuItem(item);
339 return;
340 }
341
342 if (item) {
343 if (item.type === "file" && item.query) {
344 isItemTooBig(item.type, item.query).then(([fileExceeds, fileSize]) =>
345 handleItemTooBig(fileExceeds, fileSize, item),
346 );
347 } else {
348 props.command({ ...item, itemType: item.type });
349 }
350 }
351 };
352
353 const totalItems = allItems.length;
354
355 const itemRefs = useRef<Array<HTMLButtonElement | null>>([]);
356
357 const upHandler = () => {
358 setSelectedIndex((prevIndex) => {
359 const newIndex = prevIndex - 1 >= 0 ? prevIndex - 1 : 0;
360 itemRefs.current[newIndex]?.scrollIntoView({
361 behavior: "instant" as ScrollBehavior,
362 block: "nearest",
363 });
364 return newIndex;
365 });
366 };
367
368 const downHandler = () => {
369 setSelectedIndex((prevIndex) => {
370 const newIndex = prevIndex + 1 < totalItems ? prevIndex + 1 : prevIndex;
371 itemRefs.current[newIndex]?.scrollIntoView({
372 behavior: "instant" as ScrollBehavior,
373 block: "nearest",
374 });
375 return newIndex;
376 });
377 };
378
379 const enterHandler = () => {
380 selectItem(selectedIndex);
381 };
382
383 useEffect(() => setSelectedIndex(0), [allItems]);
384
385 useImperativeHandle(ref, () => ({
386 onKeyDown: ({ event }: { event: KeyboardEvent }) => {
387 if (event.key === "ArrowUp") {
388 upHandler();
389 return true;
390 }
391
392 if (event.key === "ArrowDown") {
393 downHandler();
394 return true;
395 }
396
397 if (event.key === "Enter" || event.key === "Tab") {
398 enterHandler();
399 event.stopPropagation();
400 event.preventDefault();
401 return true;
402 }
403
404 if (event.key === "Escape") {
405 event.preventDefault();
406 event.stopPropagation();
407 return true;
408 }
409
410 if (event.key === " ") {
411 if (allItems.length === 1) {
412 enterHandler();
413 return true;
414 }
415 }
416
417 return false;
418 },
419 }));
420
421 const showFileIconForItem = (item: ComboBoxItem) => {
422 return ["file", "code"].includes(item.type);
423 };
424
425 useEffect(() => {
426 itemRefs.current = itemRefs.current.slice(0, allItems.length);
427 }, [allItems]);
428
429 return (
430 <ItemsDiv>
431 {querySubmenuItem ? (
432 <QueryInput
433 onClick={(e) => {
434 e.stopPropagation();
435 }}
436 rows={1}
437 ref={queryInputRef}
438 placeholder={querySubmenuItem.description}
439 onKeyDown={(e) => {
440 if (!queryInputRef.current) {
441 return;
442 }
443 if (e.key === "Enter") {
444 if (e.shiftKey) {
445 queryInputRef.current.innerText += "\n";
446 } else {
447 props.command({
448 ...querySubmenuItem,
449 itemType: querySubmenuItem.type,
450 query: queryInputRef.current.value,
451 label: `${querySubmenuItem.label}: ${queryInputRef.current.value}`,
452 });
453 }
454 } else if (e.key === "Escape") {
455 setQuerySubmenuItem(undefined);
456 setSubMenuTitle(undefined);
457 }
458 }}
459 />
460 ) : (
461 <>
462 {subMenuTitle && <ItemDiv className="mb-2">{subMenuTitle}</ItemDiv>}
463 {loadingSubmenuItem && (
464 <ItemDiv>
465 <span className="flex w-full items-center justify-between">
466 <div className="flex items-center justify-center">
467 <DropdownIcon item={loadingSubmenuItem} className="mr-2" />
468 <span>{loadingSubmenuItem.title}</span>
469 {" "}
470 </div>
471 <span
472 style={{
473 color: lightGray,
474 float: "right",
475 textAlign: "right",
476 minWidth: "30px",
477 }}
478 className="ml-2 flex items-center overflow-hidden overflow-ellipsis whitespace-nowrap"
479 >
480 {loadingSubmenuItem.description}
481 </span>
482 </span>
483 </ItemDiv>
484 )}
485 {allItems.length ? (
486 allItems.map((item, index) => {
487 const isSelected = index === selectedIndex;
488 return (
489 <ItemDiv
490 as="button"
491 ref={(el) => (itemRefs.current[index] = el)}
492 className={`item cursor-pointer ${isSelected ? "is-selected" : ""}`}
493 key={index}
494 onClick={(e) => {
495 e.stopPropagation();
496 selectItem(index);
497 }}
498 onMouseEnter={() => setSelectedIndex(index)}
499 data-testid="context-provider-dropdown-item"
500 >
501 <span className="flex w-full items-center justify-between">
502 <div className="flex items-center justify-center">
503 {showFileIconForItem(item) ? (
504 <FileIcon
505 height="20px"
506 width="20px"
507 filename={item.description}
508 />
509 ) : (
510 <DropdownIcon item={item} className="mr-2" />
511 )}
512 <span title={item.id} className="whitespace-nowrap">
513 {item.title}
514 </span>
515 {" "}
516 </div>
517 <span
518 style={{
519 color: lightGray,
520 float: "right",
521 textAlign: "right",
522 opacity:
523 subMenuTitle || item.type !== "contextProvider"
524 ? 1
525 : isSelected
526 ? 1
527 : 0,
528 minWidth: "30px",
529 }}
530 className="ml-2 flex items-center overflow-hidden overflow-ellipsis whitespace-nowrap"
531 >
532 {item.description}
533 {item.type === "contextProvider" &&
534 item.contextProvider?.type === "submenu" && (
535 <ArrowRightIcon
536 className="ml-2 flex-shrink-0"
537 width="1.2em"
538 height="1.2em"
539 />
540 )}
541 {item.subActions?.map((subAction) => {
542 const Icon = getIconFromDropdownItem(
543 subAction.icon,
544 "action",
545 );
546 return (
547 <HeaderButtonWithToolTip
548 onClick={(e) => {
549 subAction.action(item);
550 e.stopPropagation();
551 e.preventDefault();
552 props.onClose();
553 }}
554 text={undefined}
555 >
556 <Icon width="1.2em" height="1.2em" />
557 </HeaderButtonWithToolTip>
558 );
559 })}
560 </span>
561 </span>
562 </ItemDiv>
563 );
564 })
565 ) : (
566 <ItemDiv className="item whitespace-nowrap">No results</ItemDiv>
567 )}
568 </>
569 )}
570 </ItemsDiv>
571 );
572});
573export default AtMentionDropdown;