Elffuss BraidHub

kikocis/continue public

627d7d0d1f85 · 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 ? "File exceeds context length" : "Can't load the file",
249 {
250 modal: true,
251 detail:
252 fileSize > 0
253 ? `'${item.title}' is ${formatFileSize(fileSize)} which exceeds the allowed context length and cannot be processed by the model`
254 : `'${item.title}' could not be loaded. Please check if the file exists and has the correct permissions.`,
255 },
256 );
257 } else {
258 props.command({ ...item, itemType: item.type });
259 }
260 }
261
262 useEffect(() => {
263 const items = [...props.items];
264 if (subMenuTitle === "Type to search docs") {
265 items.push({
266 title: "Add Docs",
267 type: "action",
268 action: () => {
269 dispatch(setShowDialog(true));
270 dispatch(setDialogMessage(<AddDocsDialog />));
271
272 // Delete back to last '@'
273 const { tr } = props.editor.view.state;
274 const text = tr.doc.textBetween(0, tr.selection.from);
275 const start = text.lastIndexOf("@");
276 props.editor.view.dispatch(
277 tr.delete(start, tr.selection.from).scrollIntoView(),
278 );
279 },
280 description: "",
281 });
282 } else if (subMenuTitle === ".prompt files") {
283 items.push({
284 title: "New .prompt file",
285 type: "action",
286 action: () => {
287 ideMessenger.post("config/newPromptFile", undefined);
288 const { tr } = props.editor.view.state;
289 const text = tr.doc.textBetween(0, tr.selection.from);
290 const start = text.lastIndexOf("@");
291 if (start !== -1) {
292 props.editor.view.dispatch(
293 tr.delete(start, tr.selection.from).scrollIntoView(),
294 );
295 }
296 props.onClose(); // Escape the mention list after creating a new prompt file
297 },
298 description: "Create a new .prompt file",
299 });
300 } else if (subMenuTitle === "Mention rules files") {
301 items.push({
302 title: "Add new rule",
303 type: "action",
304 action: () => {
305 void ideMessenger.request("config/addLocalWorkspaceBlock", {
306 blockType: "rules",
307 });
308 const { tr } = props.editor.view.state;
309 const text = tr.doc.textBetween(0, tr.selection.from);
310 const start = text.lastIndexOf("@");
311 if (start !== -1) {
312 props.editor.view.dispatch(
313 tr.delete(start, tr.selection.from).scrollIntoView(),
314 );
315 }
316 props.onClose(); // Escape the mention list after creating a new rule
317 },
318 description: "Creates a rule file",
319 });
320 }
321 setLoadingSubmenuItem(items.find((item) => item.id === "loading"));
322 setAllItems(items.filter((item) => item.id !== "loading"));
323 }, [subMenuTitle, props.items, props.editor]);
324
325 const queryInputRef = useRef<HTMLTextAreaElement>(null);
326
327 useEffect(() => {
328 if (queryInputRef.current) {
329 queryInputRef.current.focus();
330 }
331 }, [querySubmenuItem, queryInputRef]);
332
333 const selectItem = (index: number) => {
334 const item = allItems[index];
335
336 if (item.type === "action" && item.action) {
337 item.action();
338 return;
339 }
340
341 if (
342 item.type === "contextProvider" &&
343 item.contextProvider?.type === "submenu"
344 ) {
345 setSubMenuTitle(item.description);
346 if (item.id) {
347 props.enterSubmenu?.(props.editor, item.id);
348 }
349 return;
350 }
351
352 if (item.contextProvider?.type === "query") {
353 // update editor to complete context provider title
354 const { tr } = props.editor.view.state;
355 const text = tr.doc.textBetween(0, tr.selection.from);
356 const partialText = text.slice(text.lastIndexOf("@") + 1);
357 const remainingText = item.title.slice(partialText.length);
358 props.editor.view.dispatch(
359 tr.insertText(remainingText, tr.selection.from),
360 );
361
362 setSubMenuTitle(item.description);
363 setQuerySubmenuItem(item);
364 return;
365 }
366
367 if (item) {
368 if (item.type === "file" && item.query) {
369 isItemTooBig(item.type, item.query).then(([fileExceeds, fileSize]) =>
370 handleItemTooBig(fileExceeds, fileSize, item),
371 );
372 } else {
373 props.command({ ...item, itemType: item.type });
374 }
375 }
376 };
377
378 const totalItems = allItems.length;
379
380 const itemRefs = useRef<Array<HTMLButtonElement | null>>([]);
381
382 const upHandler = () => {
383 setSelectedIndex((prevIndex) => {
384 const newIndex = prevIndex - 1 >= 0 ? prevIndex - 1 : 0;
385 itemRefs.current[newIndex]?.scrollIntoView({
386 behavior: "instant" as ScrollBehavior,
387 block: "nearest",
388 });
389 return newIndex;
390 });
391 };
392
393 const downHandler = () => {
394 setSelectedIndex((prevIndex) => {
395 const newIndex = prevIndex + 1 < totalItems ? prevIndex + 1 : prevIndex;
396 itemRefs.current[newIndex]?.scrollIntoView({
397 behavior: "instant" as ScrollBehavior,
398 block: "nearest",
399 });
400 return newIndex;
401 });
402 };
403
404 const enterHandler = () => {
405 selectItem(selectedIndex);
406 };
407
408 useEffect(() => setSelectedIndex(0), [allItems]);
409
410 useImperativeHandle(ref, () => ({
411 onKeyDown: ({ event }: { event: KeyboardEvent }) => {
412 if (event.key === "ArrowUp") {
413 upHandler();
414 return true;
415 }
416
417 if (event.key === "ArrowDown") {
418 downHandler();
419 return true;
420 }
421
422 if (event.key === "Enter" || event.key === "Tab") {
423 enterHandler();
424 event.stopPropagation();
425 event.preventDefault();
426 return true;
427 }
428
429 if (event.key === "Escape") {
430 event.preventDefault();
431 event.stopPropagation();
432 return true;
433 }
434
435 if (event.key === " ") {
436 if (allItems.length === 1) {
437 enterHandler();
438 return true;
439 }
440 }
441
442 return false;
443 },
444 }));
445
446 const showFileIconForItem = (item: ComboBoxItem) => {
447 return ["file", "code"].includes(item.type);
448 };
449
450 useEffect(() => {
451 itemRefs.current = itemRefs.current.slice(0, allItems.length);
452 }, [allItems]);
453
454 return (
455 <ItemsDiv>
456 {querySubmenuItem ? (
457 <QueryInput
458 onClick={(e) => {
459 e.stopPropagation();
460 }}
461 rows={1}
462 ref={queryInputRef}
463 placeholder={querySubmenuItem.description}
464 onKeyDown={(e) => {
465 if (!queryInputRef.current) {
466 return;
467 }
468 if (e.key === "Enter") {
469 if (e.shiftKey) {
470 queryInputRef.current.innerText += "\n";
471 } else {
472 props.command({
473 ...querySubmenuItem,
474 itemType: querySubmenuItem.type,
475 query: queryInputRef.current.value,
476 label: `${querySubmenuItem.label}: ${queryInputRef.current.value}`,
477 });
478 }
479 } else if (e.key === "Escape") {
480 setQuerySubmenuItem(undefined);
481 setSubMenuTitle(undefined);
482 }
483 }}
484 />
485 ) : (
486 <>
487 {subMenuTitle && <ItemDiv className="mb-2">{subMenuTitle}</ItemDiv>}
488 {loadingSubmenuItem && (
489 <ItemDiv>
490 <span className="flex w-full items-center justify-between">
491 <div className="flex items-center justify-center">
492 <DropdownIcon item={loadingSubmenuItem} className="mr-2" />
493 <span>{loadingSubmenuItem.title}</span>
494 {" "}
495 </div>
496 <span
497 style={{
498 color: lightGray,
499 float: "right",
500 textAlign: "right",
501 minWidth: "30px",
502 }}
503 className="ml-2 flex items-center overflow-hidden overflow-ellipsis whitespace-nowrap"
504 >
505 {loadingSubmenuItem.description}
506 </span>
507 </span>
508 </ItemDiv>
509 )}
510 {allItems.length ? (
511 allItems.map((item, index) => {
512 const isSelected = index === selectedIndex;
513 return (
514 <ItemDiv
515 as="button"
516 ref={(el) => (itemRefs.current[index] = el)}
517 className={`item cursor-pointer ${isSelected ? "is-selected" : ""}`}
518 key={index}
519 onClick={(e) => {
520 e.stopPropagation();
521 selectItem(index);
522 }}
523 onMouseEnter={() => setSelectedIndex(index)}
524 data-testid="context-provider-dropdown-item"
525 >
526 <span className="flex w-full items-center justify-between">
527 <div className="flex items-center justify-center">
528 {showFileIconForItem(item) ? (
529 <FileIcon
530 height="20px"
531 width="20px"
532 filename={item.description}
533 />
534 ) : (
535 <DropdownIcon item={item} className="mr-2" />
536 )}
537 <span title={item.id} className="whitespace-nowrap">
538 {item.title}
539 </span>
540 {" "}
541 </div>
542 <span
543 style={{
544 color: lightGray,
545 float: "right",
546 textAlign: "right",
547 opacity:
548 subMenuTitle || item.type !== "contextProvider"
549 ? 1
550 : isSelected
551 ? 1
552 : 0,
553 minWidth: "30px",
554 }}
555 className="ml-2 flex items-center overflow-hidden overflow-ellipsis whitespace-nowrap"
556 >
557 {item.description}
558 {item.type === "contextProvider" &&
559 item.contextProvider?.type === "submenu" && (
560 <ArrowRightIcon
561 className="ml-2 flex-shrink-0"
562 width="1.2em"
563 height="1.2em"
564 />
565 )}
566 {item.subActions?.map((subAction) => {
567 const Icon = getIconFromDropdownItem(
568 subAction.icon,
569 "action",
570 );
571 return (
572 <HeaderButtonWithToolTip
573 onClick={(e) => {
574 subAction.action(item);
575 e.stopPropagation();
576 e.preventDefault();
577 props.onClose();
578 }}
579 text={undefined}
580 >
581 <Icon width="1.2em" height="1.2em" />
582 </HeaderButtonWithToolTip>
583 );
584 })}
585 </span>
586 </span>
587 </ItemDiv>
588 );
589 })
590 ) : (
591 <ItemDiv className="item whitespace-nowrap">No results</ItemDiv>
592 )}
593 </>
594 )}
595 </ItemsDiv>
596 );
597});
598export default AtMentionDropdown;