Elffuss BraidHub

kikocis/continue public

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