diff --git a/gui/package-lock.json b/gui/package-lock.json index 60e460a8e..7b3a6eaf8 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -13,6 +13,7 @@ "@monaco-editor/react": "^4.6.0", "@reduxjs/toolkit": "^1.9.3", "@tiptap/extension-mention": "^2.1.13", + "@tiptap/extension-placeholder": "^2.1.13", "@tiptap/pm": "^2.1.13", "@tiptap/react": "^2.1.13", "@tiptap/starter-kit": "^2.1.13", @@ -1479,6 +1480,19 @@ "@tiptap/core": "^2.0.0" } }, + "node_modules/@tiptap/extension-placeholder": { + "version": "2.1.13", + "resolved": "https://registry.npmjs.org/@tiptap/extension-placeholder/-/extension-placeholder-2.1.13.tgz", + "integrity": "sha512-vIY7y7UbqsrAW/y8bDE9eRenbQEU16kNHB5Wri8RU1YiUZpkPgdXP/pLqyjIIq95SwP/vdTIHjHoQ77VLRl1hA==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "^2.0.0", + "@tiptap/pm": "^2.0.0" + } + }, "node_modules/@tiptap/extension-strike": { "version": "2.1.13", "resolved": "https://registry.npmjs.org/@tiptap/extension-strike/-/extension-strike-2.1.13.tgz", @@ -6888,6 +6902,12 @@ "integrity": "sha512-cEoZBJrsQn69FPpUMePXG/ltGXtqKISgypj70PEHXt5meKDjpmMVSY4/8cXvFYEYsI9GvIwyAK0OrfAHiSoROA==", "requires": {} }, + "@tiptap/extension-placeholder": { + "version": "2.1.13", + "resolved": "https://registry.npmjs.org/@tiptap/extension-placeholder/-/extension-placeholder-2.1.13.tgz", + "integrity": "sha512-vIY7y7UbqsrAW/y8bDE9eRenbQEU16kNHB5Wri8RU1YiUZpkPgdXP/pLqyjIIq95SwP/vdTIHjHoQ77VLRl1hA==", + "requires": {} + }, "@tiptap/extension-strike": { "version": "2.1.13", "resolved": "https://registry.npmjs.org/@tiptap/extension-strike/-/extension-strike-2.1.13.tgz", diff --git a/gui/package.json b/gui/package.json index 0c29b464d..25783bbe4 100644 --- a/gui/package.json +++ b/gui/package.json @@ -14,6 +14,7 @@ "@monaco-editor/react": "^4.6.0", "@reduxjs/toolkit": "^1.9.3", "@tiptap/extension-mention": "^2.1.13", + "@tiptap/extension-placeholder": "^2.1.13", "@tiptap/pm": "^2.1.13", "@tiptap/react": "^2.1.13", "@tiptap/starter-kit": "^2.1.13", diff --git a/gui/src/components/index.ts b/gui/src/components/index.ts index b6991b7bf..08e546658 100644 --- a/gui/src/components/index.ts +++ b/gui/src/components/index.ts @@ -11,6 +11,7 @@ export const secondaryDark = "var(--vscode-input-background, rgb(45 45 45))"; // export const vscBackground = "var(--vscode-editor-background, rgb(30 30 30))"; export const vscBackground = "var(--vscode-sideBar-background, rgb(30 30 30))"; export const vscForeground = "var(--vscode-editor-foreground, #fff)"; +export const vscButtonBackground = "var(--vscode-button-background, #1bbe84)"; if (typeof document !== "undefined") { const cachedForeground = localStorage.getItem("--vscode-editor-foreground"); diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 5b8c50f1f..4556dbc54 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -1,21 +1,8 @@ -import { useEffect, useRef, useState } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useSelector } from "react-redux"; import styled, { keyframes } from "styled-components"; -import { - buttonColor, - defaultBorderRadius, - lightGray, - secondaryDark, - vscBackground, - vscForeground, -} from ".."; +import { defaultBorderRadius, vscBackground } from ".."; import { RootStore } from "../../redux/store"; -import { getFontSize } from "../../util"; -import InputDropdown from "./InputDropdown"; -import InputToolbar from "./InputToolbar"; -import { ComboBoxItem, DropdownState } from "./types"; - -const mainInputFontSize = getFontSize(); +import TipTapEditor from "./TipTapEditor"; const gradient = keyframes` 0% { @@ -57,50 +44,13 @@ const GradientBorder = styled.div<{ margin-top: 8px; `; -const InputBoxDiv = styled.div<{ - inQueryForDynamicProvider: boolean; - fontSize?: number; -}>` - resize: none; - - padding: 8px; - padding-bottom: 24px; - 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; -`; - interface ContinueInputBoxProps { isLastUserInput: boolean; isMainInput?: boolean; + onEnter: (input: string) => void; } function ContinueInputBox(props: ContinueInputBoxProps) { - const dispatch = useDispatch(); - const active = useSelector((store: RootStore) => store.state.active); const availableSlashCommands = useSelector( (state: RootStore) => @@ -115,97 +65,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { (store: RootStore) => store.state.config.contextProviders ); - const [inputFocused, setInputFocused] = useState(false); - const [dropdownState, setDropdownState] = useState("closed"); - const [dropdownQuery, setDropdownQuery] = useState(""); - const [dropdownItems, setDropdownItems] = useState([]); - const [highlightedIndex, setHighlightedIndex] = useState(0); - - const inputBoxRef = useRef(null); - - // State transitions - useEffect(() => { - switch (dropdownState) { - case "closed": - setDropdownQuery(""); - break; - case "contextProviders": - setDropdownQuery(""); - break; - case "slashCommands": - setDropdownQuery(""); - break; - case "files": - break; - default: - break; - } - }, [dropdownState]); - - // Filter dropdown items - useEffect(() => { - switch (dropdownState) { - case "closed": - setDropdownItems([]); - break; - case "contextProviders": - const filteredItems = - availableContextProviders - ?.filter( - (provider) => - provider.description.title - .toLowerCase() - .startsWith(dropdownQuery.toLowerCase()) || - provider.description.displayTitle - .toLowerCase() - .startsWith(dropdownQuery.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)) || []; - setDropdownItems(filteredItems); - break; - case "slashCommands": - const filteredSlashCommands = - availableSlashCommands?.filter((slashCommand) => { - const sc = slashCommand.title.toLowerCase().substring(1); - const iv = dropdownQuery.toLowerCase(); - return sc.startsWith(iv); - }) || []; - setDropdownItems(filteredSlashCommands); - break; - case "files": - break; - default: - break; - } - }, [dropdownQuery, dropdownState]); - - const selectItem = (item: ComboBoxItem) => { - if (dropdownState === "closed" || !inputBoxRef.current) return; - - switch (dropdownState) { - case "contextProviders": - // Delete everything after @ - const text = inputBoxRef.current.innerText; - const beforeAt = text.substring(0, text.lastIndexOf("@")); - inputBoxRef.current.innerText = beforeAt; - break; - case "slashCommands": - break; - case "files": - break; - default: - break; - } - - setDropdownState("closed"); - }; - return (
- {/** Input Box */}
- { - setInputFocused(true); - }} - onBlur={(e) => { - setInputFocused(false); - setDropdownState("closed"); - }} - onInput={(e) => { - if (!inputBoxRef.current) return; - - switch (dropdownState) { - case "closed": - if (inputBoxRef.current.innerText.endsWith("@")) { - setDropdownState("contextProviders"); - } else if (inputBoxRef.current.innerText.endsWith("/")) { - setDropdownState("slashCommands"); - } - break; - case "contextProviders": - const text = inputBoxRef.current.innerText; - const afterAt = text.substring(text.lastIndexOf("@") + 1); - if (afterAt === "") { - setDropdownState("closed"); - } else { - setDropdownQuery(afterAt); - } - break; - case "slashCommands": - const text2 = inputBoxRef.current.innerText; - const afterSlash = text2.substring( - text2.lastIndexOf("/") + 1 - ); - if (afterSlash === "") { - setDropdownState("closed"); - } else { - setDropdownQuery(afterSlash); - } - break; - case "files": - break; - default: - break; - } - }} - ref={inputBoxRef} - onKeyDown={(e) => { - if (dropdownState !== "closed") { - // Handle key presses within dropdown - if (e.key === "Escape") { - setDropdownState("closed"); - } else if (e.key === "ArrowDown") { - setHighlightedIndex((prev) => - Math.min(prev + 1, dropdownItems.length - 1) - ); - } else if (e.key === "ArrowUp") { - setHighlightedIndex((prev) => Math.max(prev - 1, 0)); - } else if (e.key === "Enter") { - selectItem(dropdownItems[highlightedIndex]); - e.preventDefault(); - } - } - }} - > - -
); diff --git a/gui/src/components/mainInput/InputDropdown.tsx b/gui/src/components/mainInput/InputDropdown.tsx deleted file mode 100644 index 352cbb703..000000000 --- a/gui/src/components/mainInput/InputDropdown.tsx +++ /dev/null @@ -1,250 +0,0 @@ -import { - ArrowLeftIcon, - ArrowUpOnSquareIcon, - BeakerIcon, - Cog6ToothIcon, - CommandLineIcon, - ExclamationCircleIcon, - FolderIcon, - FolderOpenIcon, - GlobeAltIcon, - HashtagIcon, - MagnifyingGlassIcon, - PaintBrushIcon, - PlusIcon, - SparklesIcon, - TrashIcon, -} from "@heroicons/react/24/outline"; -import { useRef } from "react"; -import styled from "styled-components"; -import { - buttonColor, - defaultBorderRadius, - lightGray, - secondaryDark, - vscBackground, - vscForeground, -} from ".."; -import { getFontSize } from "../../util"; -import FileIcon from "../FileIcon"; -import { ComboBoxItem, DropdownState } from "./types"; - -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 ; -} - -const mainInputFontSize = getFontSize(); -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; - isLastItem: boolean; -}>` - background-color: ${({ highlighted }) => - highlighted ? buttonColor + "66" : "transparent"}; - 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; -`; - -interface InputDropdownProps { - isMainInput: boolean; - showAbove: boolean; - items: ComboBoxItem[]; - dropdownState: DropdownState; - highlightedIndex: number; - - subMenuTitle?: string; - exitSubMenu?: () => void; - selectItem?: (item: ComboBoxItem) => () => void; -} - -function InputDropdown(props: InputDropdownProps) { - const stickyDropdownHeaderDiv = useRef(null); - - return ( - - ); -} - -export default InputDropdown; diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 6ea792bd6..9654d46f1 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -5,9 +5,9 @@ const StyledDiv = styled.div` position: absolute; display: flex; gap: 4px; - right: 12px; + right: 4px; bottom: 4px; - width: calc(100% - 28px); + width: calc(100% - 10px); background-color: ${secondaryDark}; align-items: center; diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx new file mode 100644 index 000000000..fc1caa400 --- /dev/null +++ b/gui/src/components/mainInput/MentionList.tsx @@ -0,0 +1,188 @@ +import { + ArrowUpOnSquareIcon, + AtSymbolIcon, + BeakerIcon, + Cog6ToothIcon, + CommandLineIcon, + ExclamationCircleIcon, + FolderIcon, + FolderOpenIcon, + GlobeAltIcon, + HashtagIcon, + MagnifyingGlassIcon, + PaintBrushIcon, + PlusIcon, + SparklesIcon, + TrashIcon, +} from "@heroicons/react/24/outline"; +import { forwardRef, useEffect, useImperativeHandle, useState } from "react"; +import styled from "styled-components"; +import { + buttonColor, + defaultBorderRadius, + secondaryDark, + vscForeground, +} from ".."; +import FileIcon from "../FileIcon"; +import { ComboBoxItem } from "./types"; + +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 ( + + ); + } + return ; +} + +const ItemsDiv = styled.div` + border-radius: ${defaultBorderRadius}; + box-shadow: + 0 0 0 1px rgba(0, 0, 0, 0.05), + 0px 10px 20px rgba(0, 0, 0, 0.1); + font-size: 0.9rem; + overflow: hidden; + padding: 0.2rem; + position: relative; + + background-color: ${secondaryDark}; + /* backdrop-filter: blur(12px); */ +`; + +const ItemDiv = styled.div` + background: transparent; + border: 1px solid transparent; + border-radius: 0.4rem; + display: block; + margin: 0; + padding: 0.2rem 0.4rem; + text-align: left; + width: 100%; + color: ${vscForeground}; + cursor: pointer; + + &.is-selected { + background-color: ${buttonColor}33; + } +`; + +interface MentionListProps { + items: ComboBoxItem[]; + command: (item: ComboBoxItem) => void; + subMenuTitle?: string; +} + +const MentionList = forwardRef((props: MentionListProps, ref) => { + const [selectedIndex, setSelectedIndex] = useState(0); + + const selectItem = (index) => { + const item = props.items[index]; + + if (item) { + props.command(item); + } + }; + + const upHandler = () => { + setSelectedIndex( + (selectedIndex + props.items.length - 1) % props.items.length + ); + }; + + const downHandler = () => { + setSelectedIndex((selectedIndex + 1) % props.items.length); + }; + + const enterHandler = () => { + selectItem(selectedIndex); + }; + + useEffect(() => setSelectedIndex(0), [props.items]); + + useImperativeHandle(ref, () => ({ + onKeyDown: ({ event }) => { + if (event.key === "ArrowUp") { + upHandler(); + return true; + } + + if (event.key === "ArrowDown") { + downHandler(); + return true; + } + + if (event.key === "Enter") { + enterHandler(); + return true; + } + + return false; + }, + })); + + return ( + + {props.items.length ? ( + props.items.map((item, index) => ( + selectItem(index)} + onMouseEnter={() => setSelectedIndex(index)} + > + +
+ {props.subMenuTitle && ( + + )} + {/* */} + + {item.title} + {" "} +
+ + {item.description} + +
+
+ )) + ) : ( + No result + )} +
+ ); +}); +export default MentionList; diff --git a/gui/src/components/mainInput/TipTapEditor.css b/gui/src/components/mainInput/TipTapEditor.css new file mode 100644 index 000000000..86808287e --- /dev/null +++ b/gui/src/components/mainInput/TipTapEditor.css @@ -0,0 +1,16 @@ +.mention { + background-color: #bfe2b6; + border-radius: 3px; + color: #000; + font-size: 0.9em; + padding: 0.05em 0.15em; + transition: background-color 0.2s ease-in-out; +} + +.tiptap p.is-editor-empty:first-child::before { + color: #646464; /* lightGray */ + content: attr(data-placeholder); + float: left; + height: 0; + pointer-events: none; +} diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index c4712731a..89b0608f6 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -1,147 +1,195 @@ import Document from "@tiptap/extension-document"; +import History from "@tiptap/extension-history"; import Mention from "@tiptap/extension-mention"; import Paragraph from "@tiptap/extension-paragraph"; +import Placeholder from "@tiptap/extension-placeholder"; import Text from "@tiptap/extension-text"; -import { EditorContent, ReactRenderer, useEditor } from "@tiptap/react"; -import tippy from "tippy.js"; +import { EditorContent, useEditor } from "@tiptap/react"; +import { IContextProvider } from "core"; +import { useState } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import styled from "styled-components"; +import { + defaultBorderRadius, + lightGray, + secondaryDark, + vscForeground, +} from ".."; +import useHistory from "../../hooks/useHistory"; +import { RootStore } from "../../redux/store"; +import InputToolbar from "./InputToolbar"; +import "./TipTapEditor.css"; +import resolveEditorContent from "./collectInput"; +import getSuggestion from "./getMentionSuggestion"; +import { ComboBoxItem } from "./types"; -function MentionList(props) { - const { options, selectedIndex, ...rest } = props; +const InputBoxDiv = styled.div` + resize: none; + + padding: 8px; + padding-bottom: 24px; + font-family: inherit; + border-radius: ${defaultBorderRadius}; + margin: 0; + height: auto; + width: 100%; + background-color: ${secondaryDark}; + color: ${vscForeground}; + z-index: 1; + border: 0.5px solid ${lightGray}; + outline: none; + font-size: 14px; + + &:focus { + outline: none; + } + + &::placeholder { + color: ${lightGray}cc; + } + + position: relative; +`; + +interface TipTapEditorProps { + availableContextProviders: IContextProvider[]; + availableSlashCommands: ComboBoxItem[]; + isMainInput: boolean; + onEnter: (input: string) => void; +} + +function TipTapEditor(props: TipTapEditorProps) { + const dispatch = useDispatch(); + + const historyLength = useSelector( + (store: RootStore) => store.state.history.length + ); + + const contextProviders = useSelector( + (state: RootStore) => state.state.config.contextProviders || [] + ); + + const { saveSession } = useHistory(dispatch); + + const editor = useEditor( + { + extensions: [ + Document, + History, + Placeholder.configure({ + placeholder: + historyLength === 0 + ? "Ask a question, '/' for slash commands, '@' to add context" + : "Ask a follow-up", + }), + Paragraph.extend({ + addKeyboardShortcuts() { + return { + // Enter: () => + // this.editor.commands.first(({ commands }) => [ + // () => { + // props.onEnter(collectInput(editor)); + // return true; + // }, + // ]), + + "Shift-Enter": () => + this.editor.commands.first(({ commands }) => [ + () => commands.newlineInCode(), + () => commands.createParagraphNear(), + () => commands.liftEmptyBlock(), + () => commands.splitBlock(), + ]), + }; + }, + }).configure({ + HTMLAttributes: { + class: "my-1", + }, + }), + Text, + Mention.configure({ + HTMLAttributes: { + class: "mention", + }, + suggestion: getSuggestion(props.availableContextProviders), + renderLabel: (props) => { + return `@${props.node.attrs.label || props.node.attrs.id}`; + }, + }), + ], + content: "", + editorProps: { + attributes: { + class: "outline-none -mt-1 overflow-hidden", + style: "font-size: 14px;", + }, + }, + }, + [props.availableContextProviders] + ); + + const [inputFocused, setInputFocused] = useState(false); + + // useEffect(() => { + // if (!editor) return; + + // if (props.isMainInput) { + // editor.commands.focus(); + // } + // const handler = (event: any) => { + // if (event.data.type === "focusContinueInput") { + // editor.commands.focus(); + // if (historyLength > 0) { + // saveSession(); + // } + // dispatch(setTakenActionTrue(null)); + // } else if (event.data.type === "focusContinueInputWithEdit") { + // editor.commands.focus(); + // if (historyLength > 0) { + // saveSession(); + // } + + // if (!editor.getText().startsWith("/edit")) { + // editor.commands.insertContentAt(0, "/edit "); + // } + // dispatch(setTakenActionTrue(null)); + // } else if (event.data.type === "focusContinueInputWithNewSession") { + // saveSession(); + // dispatch(setTakenActionTrue(null)); + // } + // }; + // window.addEventListener("message", handler); + // return () => { + // window.removeEventListener("message", handler); + // }; + // }, [editor, props.isMainInput, historyLength]); return ( -
- test - {options.map((option, index) => ( -
- {option.label} -
- ))} -
+ + { + setInputFocused(true); + }} + onBlur={(e) => { + setInputFocused(false); + }} + /> + ); } -const suggestion = { - items: ({ query }) => { - return [ - "Lea Thompson", - "Cyndi Lauper", - "Tom Cruise", - "Madonna", - "Jerry Hall", - "Joan Collins", - "Winona Ryder", - "Christina Applegate", - "Alyssa Milano", - "Molly Ringwald", - "Ally Sheedy", - "Debbie Harry", - "Olivia Newton-John", - "Elton John", - "Michael J. Fox", - "Axl Rose", - "Emilio Estevez", - "Ralph Macchio", - "Rob Lowe", - "Jennifer Grey", - "Mickey Rourke", - "John Cusack", - "Matthew Broderick", - "Justine Bateman", - "Lisa Bonet", - ] - .filter((item) => item.toLowerCase().startsWith(query.toLowerCase())) - .slice(0, 5); - }, - - render: () => { - let component; - let popup; - - return { - onStart: (props) => { - component = new ReactRenderer(MentionList, { - props, - editor: props.editor, - }); - - if (!props.clientRect) { - return; - } - - popup = tippy("body", { - getReferenceClientRect: props.clientRect, - appendTo: () => document.body, - content: component.element, - showOnCreate: true, - interactive: true, - trigger: "manual", - placement: "bottom-start", - }); - }, - - onUpdate(props) { - component.updateProps(props); - - if (!props.clientRect) { - return; - } - - popup[0].setProps({ - getReferenceClientRect: props.clientRect, - }); - }, - - onKeyDown(props) { - if (props.event.key === "Escape") { - popup[0].hide(); - - return true; - } - - return component.ref?.onKeyDown(props); - }, - - onExit() { - popup[0].destroy(); - component.destroy(); - }, - }; - }, -}; - -export default () => { - const limit = 280; - - const editor = useEditor({ - extensions: [ - Document, - Paragraph, - Text, - Mention.configure({ - HTMLAttributes: { - class: "", - }, - suggestion, - renderLabel: ({ options }) => { - return "test"; - }, - }), - ], - content: ` -

- What do you all think about the new movie? -

- `, - }); - - return ( -
- -
- ); -}; +export default TipTapEditor; diff --git a/gui/src/components/mainInput/collectInput.ts b/gui/src/components/mainInput/collectInput.ts new file mode 100644 index 000000000..b5774af4c --- /dev/null +++ b/gui/src/components/mainInput/collectInput.ts @@ -0,0 +1,56 @@ +import { Editor, JSONContent } from "@tiptap/react"; +import { IContextProvider } from "core"; +import { getContextItems } from "../../hooks/useContextProviders"; + +/** + * This function converts the input from the editor to a string, resolving any context items + * Context items are appended to the top of the prompt and then referenced within the input + * @param editor + * @returns string representation of the input + */ + +async function resolveEditorContent( + editor: Editor, + contextProviders: IContextProvider[] +): Promise { + const content = editor.getJSON(); + let paragraphs = []; + let contextItems = []; + for (const p of content?.content) { + if (p.type === "paragraph") { + const [text, ctxItems] = resolveParagraph(p); + paragraphs.push(text); + contextItems.push(...ctxItems); + } else { + console.warn("Unexpected content type", p.type); + } + } + + let contextItemsText = ""; + for (const item of contextItems) { + contextItemsText += `@${item.id} ${item.title}\n`; + contextItemsText += getContextItems(contextProviders, item, ""); // TODO: query for context providers + } + + return contextItemsText + "\n\n" + paragraphs.join("\n"); +} + +function resolveParagraph(p: JSONContent) { + let text = ""; + const contextItems = []; + for (const child of p.content) { + if (child.type === "text") { + text += child.text; + } else if (child.type === "mention") { + text += child.attrs.id; + contextItems.push(child.attrs.id); + } else if (child.type === "command") { + text += child.attrs.id; + } else { + console.warn("Unexpected child type", child.type); + } + } + return [text, contextItems]; +} + +export default resolveEditorContent; diff --git a/gui/src/components/mainInput/getMentionSuggestion.ts b/gui/src/components/mainInput/getMentionSuggestion.ts new file mode 100644 index 000000000..6b1cfe60d --- /dev/null +++ b/gui/src/components/mainInput/getMentionSuggestion.ts @@ -0,0 +1,89 @@ +import { ReactRenderer } from "@tiptap/react"; +import { IContextProvider } from "core"; +import tippy from "tippy.js"; +import MentionList from "./MentionList"; + +function getSuggestion(availableContextProviders: IContextProvider[]) { + return { + items: ({ query }) => { + return ( + availableContextProviders + ?.filter( + (provider) => + provider.description.title + .toLowerCase() + .startsWith(query.toLowerCase()) || + provider.description.displayTitle + .toLowerCase() + .startsWith(query.toLowerCase()) + ) + .map((provider) => ({ + name: provider.description.displayTitle, + description: provider.description.description, + id: provider.description.title, + title: provider.description.displayTitle, + label: provider.description.displayTitle, + })) + .sort((c, _) => (c.id === "file" ? -1 : 1)) || [] + ); + }, + + render: () => { + let component; + let popup; + + return { + onStart: (props) => { + component = new ReactRenderer(MentionList, { + props, + editor: props.editor, + }); + + if (!props.clientRect) { + console.log("no client rect"); + return; + } + + popup = tippy("body", { + getReferenceClientRect: props.clientRect, + appendTo: () => document.body, + content: component.element, + showOnCreate: true, + interactive: true, + trigger: "manual", + placement: "bottom-start", + }); + }, + + onUpdate(props) { + component.updateProps(props); + + if (!props.clientRect) { + return; + } + + popup[0].setProps({ + getReferenceClientRect: props.clientRect, + }); + }, + + onKeyDown(props) { + if (props.event.key === "Escape") { + popup[0].hide(); + + return true; + } + + return component.ref?.onKeyDown(props); + }, + + onExit() { + popup[0]?.destroy(); + component.destroy(); + }, + }; + }, + }; +} + +export default getSuggestion; diff --git a/gui/src/hooks/useContextProviders.ts b/gui/src/hooks/useContextProviders.ts index fd8269589..63eb0af4f 100644 --- a/gui/src/hooks/useContextProviders.ts +++ b/gui/src/hooks/useContextProviders.ts @@ -1,36 +1,43 @@ -import { ContextItemId, ContextItemWithId } from "core"; +import { ContextItemId, ContextItemWithId, IContextProvider } from "core"; import { useSelector } from "react-redux"; import { v4 } from "uuid"; import { RootStore } from "../redux/store"; import { errorPopup } from "../util/ide"; +export async function getContextItems( + contextProviders: IContextProvider[], + name: string, + query: string +): Promise { + const provider = contextProviders.find((p) => p.description.title === name); + if (!provider) { + errorPopup( + `Unknown provider ${name}. Existing providers: ${contextProviders + .map((p) => p.description.title) + .join(", ")}` + ); + } + try { + const id: ContextItemId = { + providerTitle: provider.description.title, + itemId: v4(), + }; + const items = await provider.getContextItems(query); + return items.map((item) => ({ ...item, id })); + } catch (e) { + errorPopup(`Error getting context items from ${name}: ${e.message}`); + return []; + } +} function useContextProviders() { const contextProviders = useSelector( (state: RootStore) => state.state.config.contextProviders || [] ); - async function getContextItems( - name: string, - query: string - ): Promise { - const provider = contextProviders.find((p) => p.description.title === name); - if (!provider) { - errorPopup(`Unknown provider ${name}`); - } - try { - const id: ContextItemId = { - providerTitle: provider.description.title, - itemId: v4(), - }; - const items = await provider.getContextItems(query); - return items.map((item) => ({ ...item, id })); - } catch (e) { - errorPopup(`Error getting context items from ${name}: ${e.message}`); - return []; - } - } - - return { getContextItems }; + return { + getContextItems: (name, query) => + getContextItems(contextProviders, name, query), + }; } export default useContextProviders; diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui.tsx index 2e008153c..263e8511e 100644 --- a/gui/src/pages/gui.tsx +++ b/gui/src/pages/gui.tsx @@ -26,9 +26,7 @@ import FTCDialog from "../components/dialogs/FTCDialog"; import ErrorStepContainer from "../components/gui/ErrorStepContainer"; import StepContainer from "../components/gui/StepContainer"; import TimelineItem from "../components/gui/TimelineItem"; -import ComboBox from "../components/mainInput/ComboBox"; import ContinueInputBox from "../components/mainInput/ContinueInputBox"; -import TipTapEditor from "../components/mainInput/TipTapEditor"; import useChatHandler from "../hooks/useChatHandler"; import useHistory from "../hooks/useHistory"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; @@ -130,7 +128,6 @@ function GUI(props: GUIProps) { const defaultModel = useSelector(defaultModelSelector); - const sessionTitle = useSelector((state: RootStore) => state.state.title); const active = useSelector((state: RootStore) => state.state.active); // #endregion @@ -147,10 +144,8 @@ function GUI(props: GUIProps) { // #endregion - // #region Refs const mainTextInputRef = useRef(null); const topGuiDivRef = useRef(null); - // #endregion // #region Effects @@ -362,28 +357,6 @@ function GUI(props: GUIProps) { return () => window.removeEventListener("message", eventListener); }, [sendInput]); - const onMainTextInput = (event?: any) => { - if (mainTextInputRef.current) { - let input = (mainTextInputRef.current as any).inputValue; - - if (input.trim() === "") return; - - if (input.startsWith("#") && (input.length === 7 || input.length === 4)) { - localStorage.setItem("continueButtonColor", input); - (mainTextInputRef.current as any).setInputValue(""); - return; - } - - // cmd+enter to /codebase - // if (event && isMetaEquivalentKeyPressed(event)) { - // input = `/codebase ${input}`; - // } - (mainTextInputRef.current as any).setInputValue(""); - - sendInput(input); - } - }; - const isLastUserInput = useCallback( (index: number): boolean => { let foundLaterUserInput = false; @@ -398,26 +371,9 @@ function GUI(props: GUIProps) { [state.history] ); - useEffect(() => { - if (sessionTitle) { - setSessionTitleInput(sessionTitle); - } - }, [sessionTitle]); - - const [sessionTitleInput, setSessionTitleInput] = useState( - sessionTitle || "New Session" - ); - return ( <> - { - if (e.key === "Enter" && e.ctrlKey) { - onMainTextInput(); - } - }} - > +
{state.history.map((item, index: number) => { @@ -430,27 +386,14 @@ function GUI(props: GUIProps) { }} > {item.message.role === "user" ? ( - { - if (value) { - dispatch( - resubmitAtIndex({ index, content: value }) - ); - streamResponse(value, index); - } - e?.stopPropagation(); - e?.preventDefault(); + { + dispatch(resubmitAtIndex({ index, content: value })); + streamResponse(value, index); }} - isToggleOpen={ - typeof stepsOpen[index] === "undefined" - ? true - : stepsOpen[index]! - } - index={index} - /> + isLastUserInput={isLastUserInput(index)} + isMainInput={false} + > ) : ( )} - {/*
*/} ); @@ -514,25 +456,12 @@ function GUI(props: GUIProps) {
{active || ( - { - onMainTextInput(e); - e?.stopPropagation(); - e?.preventDefault(); - }} - onInputValueChange={() => {}} - onToggleAddContext={() => {}} - /> + > )} -
-
- -
-
-
{active && (