Elffuss BraidHub

kikocis/continue public

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