Elffuss BraidHub

kikocis/continue public

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