diff --git a/gui/src/components/gui/StepContainer.tsx b/gui/src/components/gui/StepContainer.tsx index c8ed3bb12..0a85810d5 100644 --- a/gui/src/components/gui/StepContainer.tsx +++ b/gui/src/components/gui/StepContainer.tsx @@ -3,7 +3,7 @@ import { HandThumbUpIcon, } from "@heroicons/react/24/outline"; import { ChatHistoryItem } from "core"; -import { useEffect, useRef, useState } from "react"; +import { useState } from "react"; import { useSelector } from "react-redux"; import styled from "styled-components"; import { @@ -60,24 +60,10 @@ const ContentDiv = styled.div<{ isUserInput: boolean; fontSize?: number }>` function StepContainer(props: StepContainerProps) { const [isHovered, setIsHovered] = useState(false); - const naturalLanguageInputRef = useRef(null); - const userInputRef = useRef(null); const isUserInput = props.item.message.role === "user"; const sessionHistory = useSelector((store: RootStore) => store.state.history); const active = useSelector((store: RootStore) => store.state.active); - useEffect(() => { - if (userInputRef?.current) { - userInputRef.current.focus(); - } - }, [userInputRef]); - - useEffect(() => { - if (isHovered) { - naturalLanguageInputRef.current?.focus(); - } - }, [isHovered]); - const [feedback, setFeedback] = useState(undefined); const sendFeedback = (feedback: boolean) => { diff --git a/gui/src/components/mainInput/ComboBox.tsx b/gui/src/components/mainInput/ComboBox.tsx deleted file mode 100644 index 588f02274..000000000 --- a/gui/src/components/mainInput/ComboBox.tsx +++ /dev/null @@ -1,1642 +0,0 @@ -import { - ArrowLeftIcon, - ArrowRightIcon, - ArrowUpOnSquareIcon, - BeakerIcon, - ChevronDownIcon, - ChevronRightIcon, - Cog6ToothIcon, - CommandLineIcon, - ExclamationCircleIcon, - ExclamationTriangleIcon, - FolderIcon, - FolderOpenIcon, - GlobeAltIcon, - HashtagIcon, - MagnifyingGlassIcon, - PaintBrushIcon, - PlusIcon, - SparklesIcon, - TrashIcon, -} from "@heroicons/react/24/outline"; -import { ContextItemWithId } from "core"; -import { useCombobox } from "downshift"; -import React, { - useCallback, - useContext, - useEffect, - useImperativeHandle, - useLayoutEffect, - useState, -} from "react"; -import { useDispatch, useSelector } from "react-redux"; -import styled, { keyframes } from "styled-components"; -import { - buttonColor, - defaultBorderRadius, - lightGray, - secondaryDark, - vscBackground, - vscForeground, -} from ".."; -import { SearchContext } from "../../App"; -import useContextProviders from "../../hooks/useContextProviders"; -import useHistory from "../../hooks/useHistory"; -import { contextLengthSelector } from "../../redux/selectors/modelSelectors"; -import { setTakenActionTrue } from "../../redux/slices/miscSlice"; -import { - addContextItems, - addContextItemsAtIndex, - deleteContextWithIds, - setInactive, -} from "../../redux/slices/stateSlice"; -import { setBottomMessage } from "../../redux/slices/uiStateSlice"; -import { RootStore } from "../../redux/store"; -import { - getFontSize, - getMarkdownLanguageTagForFile, - getMetaKeyLabel, - getPlatform, -} from "../../util"; -import { isJetBrains, postToIde } from "../../util/ide"; -import { - handleKeyDownJetBrains, - handleKeyDownJetBrainsMac, -} from "../../util/jetbrains"; -import FileIcon from "../FileIcon"; -import HeaderButtonWithText from "../HeaderButtonWithText"; -import RingLoader from "../loaders/RingLoader"; -import CodeSnippetPreview from "../markdown/CodeSnippetPreview"; -import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; -import PillButton from "./PillButton"; - -const ICONS_FOR_DROPDOWN: { [key: string]: any } = { - file: FolderIcon, - terminal: CommandLineIcon, - diff: PlusIcon, - search: MagnifyingGlassIcon, - url: GlobeAltIcon, - open: FolderOpenIcon, - "/edit": PaintBrushIcon, - "/clear": TrashIcon, - "/test": BeakerIcon, - "/config": Cog6ToothIcon, - "/comment": HashtagIcon, - "/share": ArrowUpOnSquareIcon, - "/cmd": CommandLineIcon, - "/codebase": SparklesIcon, - "/so": GlobeAltIcon, - "/issue": ExclamationCircleIcon, -}; - -function DropdownIcon(props: { provider: string; className?: string }) { - const Icon = ICONS_FOR_DROPDOWN[props.provider]; - if (!Icon) { - return null; - } - return ; -} - -// #region styled components - -const gradient = keyframes` - 0% { - background-position: 0px 0; - } - 100% { - background-position: 100em 0; - } -`; - -const GradientBorder = styled.div<{ - borderRadius?: string; - borderColor?: string; - isFirst: boolean; - isLast: boolean; - loading: boolean; -}>` - border-radius: ${(props) => props.borderRadius || "0"}; - padding: 1px; - background: ${(props) => - props.borderColor - ? props.borderColor - : `repeating-linear-gradient( - 101.79deg, - #1BBE84 0%, - #331BBE 16%, - #BE1B55 33%, - #A6BE1B 55%, - #BE1B55 67%, - #331BBE 85%, - #1BBE84 99% - )`}; - animation: ${(props) => (props.loading ? gradient : "")} 6s linear infinite; - background-size: 200% 200%; - width: 100%; - display: flex; - flex-direction: row; - align-items: center; - margin-top: 8px; -`; - -const HiddenHeaderButtonWithText = styled.button<{ pinVisible: boolean }>` - opacity: ${({ pinVisible }) => (pinVisible ? 1 : 0)}; - background-color: transparent; - border: none; - outline: none; - color: ${vscForeground}; - cursor: pointer; - display: flex; - align-items: center; - justify-content: center; - height: 0; - aspect-ratio: 1; - padding: 0; - margin-left: -8px; - - border-radius: ${defaultBorderRadius}; - - &:focus { - margin-left: 1px; - height: fit-content; - padding: 3px; - opacity: 1; - outline: 1px solid ${lightGray}; - } -`; - -const mainInputFontSize = getFontSize(); - -const MainTextInput = styled.textarea<{ - inQueryForDynamicProvider: boolean; - fontSize?: number; -}>` - resize: none; - - padding: 8px; - font-size: ${(props) => props.fontSize || mainInputFontSize}px; - font-family: inherit; - border-radius: ${defaultBorderRadius}; - margin: 0; - height: auto; - width: 100%; - background-color: ${secondaryDark}; - color: ${vscForeground}; - z-index: 1; - border: 0.5px solid - ${(props) => (props.inQueryForDynamicProvider ? buttonColor : lightGray)}; - outline: none; - - &:focus { - border: 0.5px solid - ${(props) => (props.inQueryForDynamicProvider ? buttonColor : lightGray)}; - outline: none; - background-color: ${(props) => - props.inQueryForDynamicProvider ? `${buttonColor}22` : secondaryDark}; - } - - &::placeholder { - color: ${lightGray}cc; - } - - position: relative; -`; - -const InputToolbar = styled.div` - position: absolute; - display: flex; - gap: 4px; - right: 12px; - bottom: 4px; - width: calc(100% - 28px); - background-color: ${secondaryDark}; - - align-items: center; - z-index: 50; - font-size: 10px; - - cursor: text; - - & > * { - flex: 0 0 auto; - } -`; - -const EnterButton = styled.div<{ offFocus: boolean }>` - padding: 2px 4px; - display: flex; - align-items: center; - - background-color: ${(props) => - props.offFocus ? undefined : lightGray + "33"}; - border-radius: ${defaultBorderRadius}; - color: #fff8; - - &:hover { - background-color: #cf313199; - color: white; - } - - cursor: pointer; -`; - -const NewSessionButton = styled.div` - width: fit-content; - margin-right: auto; - margin-left: 8px; - margin-top: 4px; - - font-size: 12px; - - border-radius: ${defaultBorderRadius}; - padding: 2px 8px; - color: ${lightGray}; - - &:hover { - background-color: ${lightGray}33; - color: ${vscForeground}; - } - - cursor: pointer; -`; - -const DeleteButtonDiv = styled.div` - position: absolute; - top: 14px; - right: 12px; - background-color: ${secondaryDark}; - border-radius: ${defaultBorderRadius}; - z-index: 50; -`; - -const DynamicQueryTitleDiv = styled.div` - position: absolute; - right: 0px; - top: 0px; - height: fit-content; - padding: 2px 4px; - border-radius: ${defaultBorderRadius}; - z-index: 2; - color: white; - font-size: 12px; - - background-color: ${buttonColor}; -`; - -const UlMaxHeight = 300; -const Ul = styled.ul<{ - hidden: boolean; - showAbove: boolean; - ulHeightPixels: number; - inputBoxHeight?: string; - fontSize?: number; - isMainInput: boolean; -}>` - ${(props) => - props.showAbove - ? `transform: translateY(-${props.ulHeightPixels + 8}px);` - : `transform: translateY(${ - (props.isMainInput ? 5 : 4) * (props.fontSize || mainInputFontSize) - - (props.isMainInput ? 2 : 4) - - 6 - }px);`} - position: absolute; - /* background: ${vscBackground}; */ - background-color: transparent; - backdrop-filter: blur(12px); - - color: ${vscForeground}; - max-height: ${UlMaxHeight}px; - margin-left: 1px; - width: calc(100% - 18px); - overflow-y: scroll; - overflow-x: hidden; - padding: 0; - ${({ hidden }) => hidden && "display: none;"} - border-radius: ${defaultBorderRadius}; - outline: 0.5px solid ${lightGray}; - -ms-overflow-style: none; - font-size: ${(props) => props.fontSize || mainInputFontSize}px; - - scrollbar-width: none; /* Firefox */ - z-index: 500; - - /* Hide scrollbar for Chrome, Safari and Opera */ - &::-webkit-scrollbar { - display: none; - } -`; - -const Li = styled.li<{ - highlighted: boolean; - selected: boolean; - isLastItem: boolean; -}>` - background-color: ${({ highlighted }) => - highlighted ? buttonColor + "66" : "transparent"}; - ${({ selected }) => selected && "font-weight: bold;"} - padding: 0.35rem 0.5rem; - display: flex; - flex-direction: row; - align-items: center; - ${({ isLastItem }) => isLastItem && "border-bottom: 1px solid gray;"} - cursor: pointer; - z-index: 500; -`; - -// #endregion - -interface ComboBoxItem { - title: string; - description: string; - id?: string; - content?: string; -} -interface ComboBoxProps { - onInputValueChange?: (inputValue: string) => void; - disabled?: boolean; - onEnter?: (e?: React.KeyboardEvent, value?: string) => void; - onToggleAddContext?: () => void; - - isMainInput: boolean; - isLastUserInput: boolean; - value?: string; - isToggleOpen?: boolean; - index?: number; - onDelete?: () => void; -} - -const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => { - const [miniSearch, firstResults] = useContext(SearchContext); - - const dispatch = useDispatch(); - const state = useSelector((state: RootStore) => state.state); - - const [history, setHistory] = React.useState([]); - // The position of the current command you are typing now, so the one that will be appended to history once you press enter - const [positionInHistory, setPositionInHistory] = React.useState(0); - const [items, setItems] = React.useState([]); - - const inputRef = React.useRef(null); - - useEffect(() => { - if (!inputRef.current) return; - inputRef.current.style.height = "auto"; - inputRef.current.style.height = - Math.min(inputRef.current.scrollHeight, 300) + "px"; - }, [ - inputRef.current?.scrollHeight, - inputRef.current?.clientHeight, - inputRef.current?.value, - ]); - - // Whether the current input follows an '@' and should be treated as context query - const [currentlyInContextQuery, setCurrentlyInContextQuery] = useState(false); - const [nestedContextProvider, setNestedContextProvider] = useState< - any | undefined - >(undefined); - const [inQueryForContextProvider, setInQueryForContextProvider] = useState< - any | undefined - >(undefined); - - const availableSlashCommands = useSelector( - (state: RootStore) => - state.state.config.slashCommands?.map((cmd) => { - return { - title: `/${cmd.name}`, - description: cmd.description, - }; - }) || [] - ); - const selectedContextItems = useSelector((state: RootStore) => { - if (typeof props.index !== "undefined") { - return state.state.history[props.index].contextItems; - } else { - return state.state.contextItems; - } - }); - - const active = useSelector((state: RootStore) => state.state.active); - - useEffect(() => { - if (!currentlyInContextQuery) { - setNestedContextProvider(undefined); - setInQueryForContextProvider(undefined); - } - }, [currentlyInContextQuery]); - - const contextProviders = useSelector( - (store: RootStore) => store.state.config.contextProviders - ); - - const goBackToContextProviders = () => { - setCurrentlyInContextQuery(false); - setNestedContextProvider(undefined); - setInQueryForContextProvider(undefined); - downshiftProps.setInputValue("@"); - }; - - useEffect(() => { - if (!nestedContextProvider) { - setItems( - contextProviders - ?.map((provider) => ({ - title: provider.description.displayTitle, - description: provider.description.description, - id: provider.description.title, - })) - .sort((c, _) => (c.id === "file" ? -1 : 1)) || [] - ); - } - }, [nestedContextProvider]); - - const [prevInputValue, setPrevInputValue] = useState(""); - - const { getContextItems } = useContextProviders(); - - const selectContextItem = useCallback( - async (id: string, query: string) => { - const timeout = setTimeout(() => { - setWaitingForContextItem(true); - }, 0.1); - const contextItems = await getContextItems(id, query); - clearTimeout(timeout); - setWaitingForContextItem(false); - if (props.isMainInput) { - dispatch(addContextItems(contextItems)); - } else if (typeof props.index !== "undefined") { - dispatch(addContextItemsAtIndex({ contextItems, index: props.index })); - } - }, - [props.index, getContextItems] - ); - - const onInputValueChangeCallback = useCallback( - ({ inputValue, highlightedIndex }: any) => { - // Clear the input - if (!inputValue) { - setItems([]); - setNestedContextProvider(undefined); - setCurrentlyInContextQuery(false); - return; - } - - // Hacky way of stopping bug where first context provider title is injected into input - if ( - prevInputValue === "" && - contextProviders?.some((p) => p.description.displayTitle === inputValue) - ) { - downshiftProps.setInputValue(""); - setPrevInputValue(""); - return; - } - setPrevInputValue(inputValue); - - if ( - inQueryForContextProvider && - !inputValue.startsWith(`@${inQueryForContextProvider.title}`) - ) { - setInQueryForContextProvider(undefined); - } - - props.onInputValueChange?.(inputValue); - - // Handle context selection - if (inputValue.endsWith("@") || currentlyInContextQuery) { - const segs = inputValue?.split("@") || []; - - if (segs.length > 1) { - // Get search results and return - setCurrentlyInContextQuery(true); - const providerAndQuery = segs[segs.length - 1] || ""; - - if (nestedContextProvider && !inputValue.endsWith("@")) { - // Search only within this specific context provider - const spaceSegs = providerAndQuery.split(" "); - getFilteredContextItemsForProvider( - nestedContextProvider.title, - spaceSegs.length > 1 ? spaceSegs[1] : "" - ).then((res) => { - setItems(res); - }); - } else { - // Search through the list of context providers - const filteredItems = - contextProviders - ?.filter( - (provider) => - `@${provider.description.title}` - .toLowerCase() - .startsWith(inputValue.toLowerCase()) || - `@${provider.description.displayTitle}` - .toLowerCase() - .startsWith(inputValue.toLowerCase()) - ) - .map((provider) => ({ - name: provider.description.displayTitle, - description: provider.description.description, - id: provider.description.title, - title: provider.description.displayTitle, - })) - .sort((c, _) => (c.id === "file" ? -1 : 1)) || []; - setItems(filteredItems.map((item) => item)); - setCurrentlyInContextQuery(true); - } - return; - } else { - // Exit the '@' context menu - setCurrentlyInContextQuery(false); - setNestedContextProvider(undefined); - } - } - - setNestedContextProvider(undefined); - - // Handle slash commands - setItems( - availableSlashCommands?.filter((slashCommand) => { - const sc = slashCommand.title.toLowerCase(); - const iv = inputValue.toLowerCase(); - return sc.startsWith(iv) && sc !== iv; - }) || [] - ); - - if (inputValue.startsWith("/") || inputValue.startsWith("@")) { - dispatch(setTakenActionTrue(null)); - } - }, - [ - availableSlashCommands, - currentlyInContextQuery, - nestedContextProvider, - inQueryForContextProvider, - ] - ); - - const getFilteredContextItemsForProvider = async ( - provider: string, - query: string - ) => { - try { - let res: any[] = miniSearch.search(query.trim() === "" ? "/" : query, { - prefix: true, - fuzzy: 1, - }); - if (res.length === 0) { - res = firstResults; - } - return ( - res?.slice(0, 20).map((hit) => { - const item: ComboBoxItem = { - title: hit.basename, - description: hit.basename, - id: hit.id, - content: hit.id, - }; - return item; - }) || [] - ); - } catch (e) { - console.log("Error searching context items", e); - return []; - } - }; - - const { getInputProps, ...downshiftProps } = useCombobox({ - onInputValueChange: onInputValueChangeCallback, - items, - itemToString(item) { - return item ? item.title : ""; - }, - initialInputValue: props.value || undefined, - }); - - const [waitingForContextItem, setWaitingForContextItem] = useState(false); - - useEffect(() => { - if (downshiftProps.highlightedIndex < 0) { - downshiftProps.setHighlightedIndex(0); - } - }, [downshiftProps.inputValue]); - - const divRef = React.useRef(null); - const ulRef = React.useRef(null); - const showAbove = () => { - return ( - (divRef.current?.getBoundingClientRect().top || Number.MAX_SAFE_INTEGER) > - UlMaxHeight - ); - }; - - useImperativeHandle(ref, () => downshiftProps, [downshiftProps]); - - const contextItemsDivRef = React.useRef(null); - const handleTabPressed = useCallback(() => { - setShowContextItemsIfNotMain(true); - // Set the focus to the next item in the context items div - if (!contextItemsDivRef.current) { - return; - } - const focusableItems = contextItemsDivRef.current.querySelectorAll( - `.pill-button-${props.index || "main"}` - ); - const focusableItemsArray = Array.from(focusableItems); - const focusedItemIndex = focusableItemsArray.findIndex( - (item) => item === document.activeElement - ); - if (focusedItemIndex === focusableItemsArray.length - 1) { - inputRef.current?.focus(); - } else if (focusedItemIndex !== -1) { - const nextItem = - focusableItemsArray[ - (focusedItemIndex + 1) % focusableItemsArray.length - ]; - (nextItem as any)?.focus(); - } else { - const firstItem = focusableItemsArray[0]; - (firstItem as any)?.focus(); - } - }, [props.index]); - - useEffect(() => { - if (inputRef.current) { - const listener = (e: any) => { - if (e.key === "Tab") { - e.preventDefault(); - handleTabPressed(); - } - }; - inputRef.current.addEventListener("keydown", listener); - return () => { - inputRef.current?.removeEventListener("keydown", listener); - }; - } - }, [inputRef.current]); - - useEffect(() => { - if (props.value) { - downshiftProps.setInputValue(props.value); - } - }, [props.value, downshiftProps.setInputValue]); - - const [isHovered, setIsHovered] = useState(false); - - useLayoutEffect(() => { - if (!ulRef.current) { - return; - } - downshiftProps.setHighlightedIndex(0); - }, [items, downshiftProps.setHighlightedIndex, ulRef.current]); - - const [metaKeyPressed, setMetaKeyPressed] = useState(false); - const [inputFocused, setInputFocused] = useState(false); - useEffect(() => { - const handleKeyDown = (e: KeyboardEvent) => { - if (e.key === "Meta") { - setMetaKeyPressed(true); - } - }; - const handleKeyUp = (e: KeyboardEvent) => { - if (e.key === "Meta") { - setMetaKeyPressed(false); - } - }; - window.addEventListener("keydown", handleKeyDown); - window.addEventListener("keyup", handleKeyUp); - return () => { - window.removeEventListener("keydown", handleKeyDown); - window.removeEventListener("keyup", handleKeyUp); - }; - }, []); - - const { saveSession } = useHistory(dispatch); - - useEffect(() => { - if (!inputRef.current || !props.isMainInput) { - return; - } - if (props.isMainInput) { - inputRef.current.focus(); - } - const handler = (event: any) => { - if (event.data.type === "focusContinueInput") { - inputRef.current!.focus(); - if (state.history.length > 0) { - saveSession(); - } - dispatch(setTakenActionTrue(null)); - } else if (event.data.type === "focusContinueInputWithoutClear") { - inputRef.current!.focus(); - dispatch(setTakenActionTrue(null)); - } else if (event.data.type === "focusContinueInputWithNewSession") { - saveSession(); - dispatch(setTakenActionTrue(null)); - } - }; - window.addEventListener("message", handler); - return () => { - window.removeEventListener("message", handler); - }; - }, [inputRef.current, props.isMainInput, state.history.length]); - - const deleteButtonDivRef = React.useRef(null); - const stickyDropdownHeaderDiv = React.useRef(null); - - const selectContextItemFromDropdown = useCallback( - (event: any) => { - const newItem = items[downshiftProps.highlightedIndex]; - const newProviderName = newItem?.title; - const newProvider = contextProviders.find( - (provider) => provider.description.displayTitle === newProviderName - ); - - if (!newProvider) { - if (nestedContextProvider && newItem.id) { - // Tell server the context item was selected - selectContextItem("file", newItem.id); - - // Clear the input - downshiftProps.setInputValue(""); - setCurrentlyInContextQuery(false); - setNestedContextProvider(undefined); - setInQueryForContextProvider(undefined); - (event.nativeEvent as any).preventDownshiftDefault = true; - event.preventDefault(); - return; - } - // This is a slash command - (event.nativeEvent as any).preventDownshiftDefault = true; - event.preventDefault(); - return; - } else if ( - newProvider.description.dynamic && - newProvider.description.requiresQuery - ) { - // This is a dynamic context provider that requires a query, like URL / Search - setInQueryForContextProvider(newProvider); - downshiftProps.setInputValue(`@${newProvider.description.title} `); - (event.nativeEvent as any).preventDownshiftDefault = true; - event.preventDefault(); - return; - } else if (newProvider.description.dynamic) { - // This is a normal dynamic context provider like Diff or Terminal - if (!newItem.id) return; - - // Get the query from the input value - const segs = downshiftProps.inputValue.split("@"); - const query = segs[segs.length - 1]; - - // Tell server the context item was selected - selectContextItem(newItem.id, query); - if (downshiftProps.inputValue.includes("@")) { - const selectedNestedContextProvider = contextProviders.find( - (provider) => provider.description.title === newItem.id - ); - if ( - !nestedContextProvider && - !selectedNestedContextProvider?.description.dynamic - ) { - downshiftProps.setInputValue(`@${newItem.id} `); - setNestedContextProvider(selectedNestedContextProvider.description); - } else { - downshiftProps.setInputValue(""); - } - } - - // Clear the input - downshiftProps.setInputValue(""); - setCurrentlyInContextQuery(false); - setNestedContextProvider(undefined); - setInQueryForContextProvider(undefined); - (event.nativeEvent as any).preventDownshiftDefault = true; - event.preventDefault(); - return; - } - - setNestedContextProvider(newProvider.description); - downshiftProps.setInputValue(`@${newProvider.description.title} `); - (event.nativeEvent as any).preventDownshiftDefault = true; - event.preventDefault(); - getFilteredContextItemsForProvider( - newProvider.description.title, - "" - ).then((items) => setItems(items)); - }, - [ - items, - downshiftProps.highlightedIndex, - contextProviders, - nestedContextProvider, - downshiftProps.inputValue, - selectContextItem, - ] - ); - - const [contextLengthFillPercentage, setContextLengthFillPercentage] = - useState(0); - - const contextLength = useSelector(contextLengthSelector); - - useEffect(() => { - let tokenEstimate = selectedContextItems.reduce((acc, item) => { - return acc + item.content.length / Math.E; // Just an estimate of tokens / char - }, 0); - tokenEstimate += downshiftProps.inputValue.length / Math.E; - setContextLengthFillPercentage( - tokenEstimate / Math.max(1, contextLength - 600) - ); - }, [selectedContextItems.length, contextLength]); - - const [isComposing, setIsComposing] = useState(false); - - const [showContextToggleOn, setShowContextToggleOn] = useState(false); - - const [previewingContextItem, setPreviewingContextItem] = useState< - ContextItemWithId | undefined - >(undefined); - - const [focusedContextItem, setFocusedContextItem] = useState< - ContextItemWithId | undefined - >(undefined); - - const topRef = React.useRef(null); - - const [showContextItemsIfNotMain, setShowContextItemsIfNotMain] = - useState(false); - - useEffect(() => { - if (!inputFocused) { - setShowContextItemsIfNotMain(false); - } - }, [inputFocused]); - - useEffect(() => { - if (selectedContextItems.length > 0) { - setShowContextItemsIfNotMain(true); - } - }, [selectedContextItems]); - - return ( -
- {selectedContextItems.length === 0 && props.isMainInput && ( -
- {downshiftProps.inputValue?.startsWith("/edit") && ( - <> - Inserting at cursor -
- - )} -
- )} - - {props.isMainInput || - (selectedContextItems.length > 0 && showContextItemsIfNotMain) ? ( -
- {selectedContextItems.length > 0 && ( -
{ - setShowContextToggleOn((prev) => !prev); - }} - tabIndex={0} - id="toggle-context-div" - > - {showContextToggleOn ? ( - - ) : ( - - )} -
- )} - - = 8} - className={ - selectedContextItems.length > 0 - ? `pill-button-${props.index || "main"}` - : "" - } - onClick={() => { - dispatch( - deleteContextWithIds({ - ids: selectedContextItems.map((item) => item.id), - index: props.index, - }) - ); - inputRef.current?.focus(); - setPreviewingContextItem(undefined); - setFocusedContextItem(undefined); - }} - onKeyDown={(e: any) => { - if (e.key === "Backspace") { - dispatch( - deleteContextWithIds({ - ids: selectedContextItems.map((item) => item.id), - index: props.index, - }) - ); - inputRef.current?.focus(); - setPreviewingContextItem(undefined); - setFocusedContextItem(undefined); - } - }} - > - - - {selectedContextItems.length < 8 ? ( - <> - {selectedContextItems.map((item, idx) => { - return ( - 1} - key={`${item.id.itemId}${idx}`} - item={item} - editing={ - item.editing && - (inputRef.current as any)?.value?.startsWith("/edit") - } - editingAny={(inputRef.current as any)?.value?.startsWith( - "/edit" - )} - stepIndex={props.index} - index={idx} - onDelete={() => { - dispatch( - deleteContextWithIds({ - ids: [item.id], - index: props.index, - }) - ); - inputRef.current?.focus(); - if ( - (item.id.itemId === focusedContextItem?.id.itemId && - focusedContextItem?.id.providerTitle === - item.id.providerTitle) || - (item.id.itemId === previewingContextItem?.id.itemId && - previewingContextItem?.id.providerTitle === - item.id.providerTitle) - ) { - setPreviewingContextItem(undefined); - setFocusedContextItem(undefined); - } - }} - onClick={(e) => { - if ( - item.id.itemId === focusedContextItem?.id.itemId && - focusedContextItem?.id.providerTitle === - item.id.providerTitle - ) { - setFocusedContextItem(undefined); - } else { - setFocusedContextItem(item); - } - }} - onBlur={() => { - setFocusedContextItem(undefined); - }} - toggleViewContent={() => { - setPreviewingContextItem((prev) => { - if (!prev) return item; - if ( - prev.id.itemId === item.id.itemId && - prev.id.providerTitle === item.id.providerTitle - ) { - return undefined; - } else { - return item; - } - }); - }} - previewing={ - item.id.itemId === previewingContextItem?.id.itemId && - previewingContextItem?.id.providerTitle === - item.id.providerTitle - } - focusing={ - item.id.itemId === focusedContextItem?.id.itemId && - focusedContextItem?.id.providerTitle === - item.id.providerTitle - } - prefixInputWithEdit={(should) => { - if ( - !should && - inputRef.current?.value.startsWith("/edit") - ) { - downshiftProps.setInputValue( - inputRef.current?.value.replace("/edit ", "") - ); - } - if (downshiftProps.inputValue.startsWith("/edit")) return; - downshiftProps.setInputValue( - `/edit ${downshiftProps.inputValue}` - ); - inputRef.current?.focus(); - }} - /> - ); - })} - {waitingForContextItem && ( - - )} - {contextLengthFillPercentage > 1 && ( - - - - )} - - ) : ( -
{ - if (props.isMainInput) { - setShowContextToggleOn((prev) => !prev); - } else { - inputRef.current?.focus(); - setShowContextItemsIfNotMain(true); - } - }} - id="snippets-selected-div" - style={{ - color: lightGray, - backgroundColor: vscBackground, - fontSize: "12px", - alignItems: "center", - display: "flex", - height: "100%", - cursor: "pointer", - }} - > - {selectedContextItems.length} snippets selected -
- )} -
- ) : ( - selectedContextItems.length > 0 && ( -
{ - inputRef.current?.focus(); - setShowContextItemsIfNotMain(true); - }} - style={{ - color: lightGray, - fontSize: "10px", - backgroundColor: vscBackground, - paddingLeft: "12px", - cursor: "default", - paddingTop: getFontSize(), - width: "fit-content", - }} - > - {active ? "Using" : "Used"} {selectedContextItems.length} context - item - {selectedContextItems.length === 1 ? "" : "s"} -
- ) - )} - {previewingContextItem && ( -
-          
-        
- )} - {showContextToggleOn && selectedContextItems.length > 0 && ( -
- {selectedContextItems.map((item) => ( - - ))} -
- )} -
- - { - inputRef.current?.focus(); - }} - onMouseEnter={() => setIsHovered(true)} - onMouseLeave={(e) => { - if ( - e.relatedTarget === deleteButtonDivRef.current || - (e.relatedTarget instanceof Node && - deleteButtonDivRef.current?.contains(e.relatedTarget as Node)) - ) { - return; - } - setIsHovered(false); - }} - rows={props.isMainInput ? undefined : 1} - inQueryForDynamicProvider={ - typeof inQueryForContextProvider !== "undefined" - } - fontSize={getFontSize()} - disabled={props.disabled} - placeholder={ - state.history.length === 0 - ? `Ask a question, '/' for slash commands, '@' to add context` - : `Ask a follow-up` - } - {...getInputProps({ - onCompositionStart: () => setIsComposing(true), - onCompositionEnd: () => setIsComposing(false), - onChange: (e) => {}, - onFocus: (e) => { - setInputFocused(true); - dispatch(setBottomMessage(undefined)); - }, - onBlur: (e) => { - if ( - topRef.current?.contains(e.relatedTarget as Node) || - document - .getElementById("toggle-context-div") - ?.contains(e.relatedTarget as Node) || - document - .getElementById("snippets-selected-div") - ?.contains(e.relatedTarget as Node) - ) { - return; - } - setInputFocused(false); - }, - onKeyDown: (event) => { - // Prevent duplicate calls to keyDown events due to IME. - if (isComposing) { - return; - } - dispatch(setBottomMessage(undefined)); - if (event.key === "Enter" && event.shiftKey) { - // Prevent Downshift's default 'Enter' behavior. - (event.nativeEvent as any).preventDownshiftDefault = true; - setCurrentlyInContextQuery(false); - } else if ( - event.key === "Enter" && - (!downshiftProps.isOpen || items.length === 0) && - !isComposing - ) { - const value = downshiftProps.inputValue; - if (inQueryForContextProvider) { - const segs = value.split("@"); - selectContextItem( - inQueryForContextProvider.title, - segs[segs.length - 1] - ); - setCurrentlyInContextQuery(false); - downshiftProps.setInputValue(""); - return; - } else { - if (value !== "") { - setPositionInHistory(history.length + 1); - setHistory([...history, value]); - } - // Prevent Downshift's default 'Enter' behavior. - (event.nativeEvent as any).preventDownshiftDefault = true; - - if (props.onEnter) { - props.onEnter(event, value); - } - } - setCurrentlyInContextQuery(false); - } else if (event.key === "Enter" && currentlyInContextQuery) { - // Handle "Enter" for Context Providers - selectContextItemFromDropdown(event); - } else if ( - event.key === "Tab" && - downshiftProps.isOpen && - items.length > 0 && - items[downshiftProps.highlightedIndex]?.title.startsWith("/") - ) { - downshiftProps.setInputValue(items[0].title); - } else if (event.key === "Tab") { - (event.nativeEvent as any).preventDownshiftDefault = true; - } else if ( - (event.key === "ArrowUp" || event.key === "ArrowDown") && - items.length > 0 - ) { - return; - } else if (event.key === "ArrowUp") { - // Only go back in history if selectionStart is 0 - // (i.e. the cursor is at the beginning of the input) - if ( - positionInHistory == 0 || - event.currentTarget.selectionStart !== 0 - ) { - (event.nativeEvent as any).preventDownshiftDefault = true; - return; - } else if ( - positionInHistory == history.length && - (history.length === 0 || - history[history.length - 1] !== event.currentTarget.value) - ) { - setHistory([...history, event.currentTarget.value]); - } - downshiftProps.setInputValue(history[positionInHistory - 1]); - setPositionInHistory((prev) => prev - 1); - setCurrentlyInContextQuery(false); - } else if (event.key === "ArrowDown") { - if ( - positionInHistory === history.length || - event.currentTarget.selectionStart !== - event.currentTarget.value.length - ) { - (event.nativeEvent as any).preventDownshiftDefault = true; - return; - } - - if (positionInHistory < history.length) { - downshiftProps.setInputValue( - history[positionInHistory + 1] - ); - } - setPositionInHistory((prev) => - Math.min(prev + 1, history.length) - ); - setCurrentlyInContextQuery(false); - } else if (event.key === "Escape") { - if (nestedContextProvider) { - goBackToContextProviders(); - (event.nativeEvent as any).preventDownshiftDefault = true; - return; - } else if (inQueryForContextProvider) { - goBackToContextProviders(); - (event.nativeEvent as any).preventDownshiftDefault = true; - return; - } - - setCurrentlyInContextQuery(false); - if (downshiftProps.isOpen && items.length > 0) { - downshiftProps.closeMenu(); - (event.nativeEvent as any).preventDownshiftDefault = true; - } else { - (event.nativeEvent as any).preventDownshiftDefault = true; - // Remove focus from the input - inputRef.current?.blur(); - // Move cursor back over to the editor - postToIde("focusEditor", {}); - } - } - // Home and end keys - else if (event.key === "Home") { - (event.nativeEvent as any).preventDownshiftDefault = true; - } else if (event.key === "End") { - (event.nativeEvent as any).preventDownshiftDefault = true; - } else if (localStorage.getItem("ide") === "jetbrains") { - if (getPlatform() === "mac") { - handleKeyDownJetBrainsMac( - event, - downshiftProps.inputValue, - downshiftProps.setInputValue - ); - } else { - handleKeyDownJetBrains( - event, - downshiftProps.inputValue, - downshiftProps.setInputValue - ); - } - } - }, - onClick: () => { - dispatch(setBottomMessage(undefined)); - }, - ref: inputRef, - })} - /> - - {(inputFocused || props.isMainInput) && ( - - { - downshiftProps.setInputValue("@"); - inputRef.current?.focus(); - }} - className="hover:underline cursor-pointer mr-auto" - > - + Add Context - - { - const inputValue = downshiftProps.inputValue; - if (inputValue?.startsWith("/codebase")) { - downshiftProps.setInputValue( - inputValue.replace("/codebase ", "") - ); - } else { - downshiftProps.setInputValue("/codebase " + inputValue); - } - inputRef.current?.focus(); - }} - className={"hover:underline cursor-pointer float-right"} - > - {/* {downshiftProps.inputValue?.startsWith("/codebase") - ? "Using Codebase" - : `${getMetaKeyLabel()} ⏎ Use Codebase`} */} - - - { - if (active) { - dispatch(setInactive()); - } else { - props.onEnter?.(undefined); - } - }} - > - ⏎ Enter - - - )} - {props.isMainInput || ( - - {isHovered && ( -
- <> - {/* {timeline - .filter( - (h, i: number) => - props.groupIndices?.includes(i) && h.logs - ) - .some((h) => h.logs!.length > 0) && ( - { - e.stopPropagation(); - if (props.groupIndices) { - const content = - "This is the exact prompt sent to the LLM: \n\n" + - timeline - .filter((_, i) => { - return props.groupIndices?.includes(i); - }) - .flatMap((s) => s.logs || []) - .join("\n"); - postToIde("showVirtualFile", { - name: "inspect_prompt.md", - content, - }); - } - }} - text="Inspect Prompt" - > - - - )} */} - {/* { - e.stopPropagation(); - if (props.active && props.groupIndices) { - client?.stopSession(); - } else { - props.onDelete?.(); - } - }} - text={ - props.active ? `Stop (${getMetaKeyLabel()}⌫)` : "Delete" - } - > - {props.active ? null : ( - // - - )} - */} - -
- )} -
- )} -
- {inQueryForContextProvider && ( - - Enter {inQueryForContextProvider.display_title} Query - - )} - - -
- {props.isMainInput && - (active ? ( - <> -
-
- - ) : state.history.length > 0 ? ( - { - saveSession(); - }} - className="mr-auto" - > - New Session ({getMetaKeyLabel()} {isJetBrains() ? "J" : "M"}) - - ) : null)} -
- ); -}); - -export default ComboBox; diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index 5191e5428..135473dfc 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -157,6 +157,8 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { if (event.key === "Enter") { enterHandler(); + event.stopPropagation(); + event.preventDefault(); return true; } diff --git a/gui/src/components/mainInput/PillButton.tsx b/gui/src/components/mainInput/PillButton.tsx deleted file mode 100644 index 8b4e61567..000000000 --- a/gui/src/components/mainInput/PillButton.tsx +++ /dev/null @@ -1,327 +0,0 @@ -import { - ExclamationTriangleIcon, - PaintBrushIcon, - TrashIcon, -} from "@heroicons/react/24/outline"; -import { ContextItemWithId } from "core"; -import { useCallback, useEffect, useRef, useState } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import styled from "styled-components"; -import { - StyledTooltip, - defaultBorderRadius, - lightGray, - secondaryDark, - vscForeground, -} from ".."; -import { setEditingAtIds } from "../../redux/slices/stateSlice"; -import { RootStore } from "../../redux/store"; -import { getFontSize } from "../../util"; -import { postToIde } from "../../util/ide"; -import FileIcon from "../FileIcon"; -import HeaderButtonWithText from "../HeaderButtonWithText"; - -const Button = styled.button<{ fontSize?: number }>` - border: none; - color: ${vscForeground}; - background-color: ${secondaryDark}; - border-radius: ${defaultBorderRadius}; - padding: 3.5px; - padding-left: 3px; - padding-right: 5px; - overflow: hidden; - font-size: ${(props) => props.fontSize || getFontSize()}px; - - cursor: pointer; -`; - -const GridDiv = styled.div` - position: absolute; - left: 0px; - top: 0px; - width: 100%; - height: 100%; - display: grid; - grid-gap: 0; - align-items: center; - border-radius: ${defaultBorderRadius}; - - background-color: ${secondaryDark}; -`; - -const ButtonDiv = styled.div<{ backgroundColor: string }>` - background-color: ${secondaryDark}; - height: 100%; - display: flex; - align-items: center; - - &:hover { - background-color: ${(props) => props.backgroundColor}; - } -`; - -const CircleDiv = styled.div` - position: absolute; - top: -10px; - right: -10px; - width: 20px; - height: 20px; - border-radius: 50%; - background-color: red; - color: white; - display: flex; - align-items: center; - justify-content: center; - padding: 2px; -`; - -interface PillButtonProps { - onHover?: (arg0: boolean) => void; - item: ContextItemWithId; - editing: boolean; - editingAny: boolean; - index: number; - inputIndex: number; // index of the ComboBox - areMultipleItems?: boolean; - onDelete?: (index?: number) => void; - onClick?: (e: React.MouseEvent) => void; - stepIndex?: number; - previewing?: boolean; - toggleViewContent?: () => void; - onBlur?: () => void; - focusing?: boolean; - prefixInputWithEdit?: (should: boolean) => void; -} - -interface StyledButtonProps { - borderColor?: string; - editing?: boolean; -} - -const Container = styled.div<{ previewing?: boolean }>` - border-radius: ${defaultBorderRadius}; - background-color: ${secondaryDark}; - display: flex; - align-items: center; - justify-content: center; -`; - -const StyledButton = styled(Button)` - position: relative; - border-color: ${(props) => props.borderColor || "transparent"}; - border-width: 1px; - border-style: solid; - - &:focus { - outline: none; - /* border-color: ${lightGray}; */ - text-decoration: underline; - } -`; - -const HoverableInsidePillButton = styled(HeaderButtonWithText)<{ - color: string; -}>` - &:hover { - background-color: ${(props) => props.color}; - } -`; - -const ClickableInsidePillButton = styled(HeaderButtonWithText)<{ - color: string; - selected: boolean; -}>` - ${(props) => - props.selected && - ` - background-color: ${props.color}; - - &:hover { - background-color: ${props.color}; - } - `} -`; - -const PillButton = (props: PillButtonProps) => { - const [isHovered, setIsHovered] = useState(false); - const dispatch = useDispatch(); - - const [warning, setWarning] = useState(undefined); - - useEffect(() => { - if (props.editing && props.item.content.length > 4000) { - setWarning("Editing such a large range may be slow"); - } else { - setWarning(undefined); - } - }, [props.editing, props.item]); - - const setEditing = useCallback(() => { - if (!props.editing) { - dispatch( - setEditingAtIds({ - ids: [props.item.id], - index: props.inputIndex, - }) - ); - } - if (!props.editingAny) { - props.prefixInputWithEdit?.(true); - } - if (props.editingAny && props.editing) { - props.prefixInputWithEdit?.(false); - } - }, [props.editing, props.editingAny, props.item, props.inputIndex]); - - const pillContainerRef = useRef(null); - const buttonRef = useRef(null); - - const selectedContextItems = useSelector( - (store: RootStore) => store.state.contextItems - ); - - return ( -
- - { - setIsHovered(true); - if (props.onHover) { - props.onHover(true); - } - }} - onMouseLeave={() => { - setIsHovered(false); - if (props.onHover) { - props.onHover(false); - } - }} - className={`pill-button-${props.stepIndex || "main"}`} - onKeyDown={(e) => { - if (e.key === "Backspace") { - props.onDelete?.(props.stepIndex); - } else if (e.key === "v") { - props.toggleViewContent?.(); - } else if (e.key === "e") { - setEditing(); - } - }} - onClick={(e) => { - props.onClick?.(e); - if (props.item.id.providerTitle === "file") { - postToIde("showFile", { - filepath: props.item.description, - }); - } else if (props.item.id.providerTitle === "code") { - const lines = props.item.name - .split("(")[1] - .split(")")[0] - .split("-"); - postToIde("showLines", { - filepath: props.item.description, - start: parseInt(lines[0]) - 1, - end: parseInt(lines[1]) - 1, - }); - } else { - postToIde("showVirtualFile", { - name: props.item.name, - content: props.item.content, - }); - } - }} - onBlur={(e) => { - if (!pillContainerRef.current?.contains(e.relatedTarget as any)) { - // props.onBlur?.(); - } else { - e.preventDefault(); - buttonRef.current?.focus(); - } - }} - > - - {["file", "code", "open"].includes(props.item.id.providerTitle) && ( - - )} - {props.item.name} - - - {(props.editingAny || - (props.focusing && props.item.editable) || - (props.editing && props.editingAny)) && ( - <> - - - - - Editing this range - - - )} - {/* {(props.focusing || props.previewing) && ( - props.toggleViewContent?.()} - tabIndex={-1} - color="#ff04" - selected={props.previewing || false} - > - - - )} */} - {props.focusing && ( - props.onDelete?.(props.stepIndex)} - tabIndex={-1} - color="#f004" - > - - - )} - - - {props.item.editing - ? "Editing this section (with entire file as context)" - : "Edit this section"} - - Delete - {props.editing && warning && ( - <> - - - - - {warning} - - - )} -
- ); -}; - -export default PillButton; diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index e15da78fd..dc7626210 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -81,6 +81,7 @@ function TipTapEditor(props: TipTapEditorProps) { const { saveSession } = useHistory(dispatch); const inSubmenu = useRef(false); + const inDropdown = useRef(false); const enterSubmenu = async (editor: Editor) => { const contents = editor.getText(); @@ -105,6 +106,11 @@ function TipTapEditor(props: TipTapEditorProps) { const onClose = () => { inSubmenu.current = false; + inDropdown.current = false; + }; + + const onOpen = () => { + inDropdown.current = true; }; const editor = useEditor( @@ -121,14 +127,19 @@ function TipTapEditor(props: TipTapEditorProps) { Paragraph.extend({ addKeyboardShortcuts() { return { - // Enter: () => - // this.editor.commands.first(({ commands }) => [ - // () => { - // props.onEnter(this.editor.getJSON()); - // return true; - // }, - // ]), - // Enter: () => true, + Enter: () => { + if (inDropdown.current) { + return false; + } + + props.onEnter(this.editor.getJSON()); + return true; + }, + + "Cmd-Enter": () => { + props.onEnter(this.editor.getJSON()); + return true; + }, "Shift-Enter": () => this.editor.commands.first(({ commands }) => [ @@ -155,6 +166,7 @@ function TipTapEditor(props: TipTapEditorProps) { firstResults, enterSubmenu, onClose, + onOpen, inSubmenu ), renderLabel: (props) => { @@ -165,7 +177,11 @@ function TipTapEditor(props: TipTapEditorProps) { HTMLAttributes: { class: "mention", }, - suggestion: getCommandSuggestion(props.availableSlashCommands), + suggestion: getCommandSuggestion( + props.availableSlashCommands, + onClose, + onOpen + ), renderLabel: (props) => { return props.node.attrs.label; }, @@ -180,7 +196,13 @@ function TipTapEditor(props: TipTapEditorProps) { }, content: props.editorState || props.content || "", }, - [props.availableContextProviders, historyLength, miniSearch, firstResults] + [ + props.availableContextProviders, + historyLength, + miniSearch, + firstResults, + inDropdown, + ] ); // This is a mechanism for overriding the IDE keyboard shortcut when inside of the webview @@ -221,17 +243,18 @@ function TipTapEditor(props: TipTapEditorProps) { editor.commands.insertContent(input); props.onEnter(editor.getJSON()); } else if (event.data.type === "focusContinueInput") { - editor.commands.focus(); if (historyLength > 0) { saveSession(); } dispatch(setTakenActionTrue(null)); + editor.commands.focus("end"); } else if (event.data.type === "focusContinueInputWithoutClear") { - editor.commands.focus(); + editor.commands.focus("end"); dispatch(setTakenActionTrue(null)); } else if (event.data.type === "focusContinueInputWithNewSession") { saveSession(); dispatch(setTakenActionTrue(null)); + editor.commands.focus("end"); } else if (event.data.type === "highlightedCode") { if (!ignoreHighlightedCode) { const rif: RangeInFile & { contents: string } = @@ -276,11 +299,6 @@ function TipTapEditor(props: TipTapEditorProps) { onBlur={() => { setInputFocused(false); }} - // onKeyDown={(e) => { - // if (e.key === "Enter") { - // props.onEnter(editor.getJSON()); - // } - // }} />