✨ TipTap editor

This commit is contained in:
Nate Sesti 2023-12-22 16:55:21 -05:00
parent 186b5e4201
commit bbfadf7dc4
13 changed files with 609 additions and 738 deletions

20
gui/package-lock.json generated
View file

@ -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",

View file

@ -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",

View file

@ -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");

View file

@ -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<DropdownState>("closed");
const [dropdownQuery, setDropdownQuery] = useState("");
const [dropdownItems, setDropdownItems] = useState<ComboBoxItem[]>([]);
const [highlightedIndex, setHighlightedIndex] = useState(0);
const inputBoxRef = useRef<HTMLDivElement>(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 (
<div
style={{
@ -213,7 +72,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
backgroundColor: vscBackground,
}}
>
{/** Input Box */}
<div
className="flex px-2 relative"
style={{
@ -229,105 +87,13 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
}
borderRadius={defaultBorderRadius}
>
<InputBoxDiv
inQueryForDynamicProvider={false}
fontSize={mainInputFontSize}
contentEditable="true"
placeholder="Ask anything"
onFocus={() => {
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();
}
}
}}
></InputBoxDiv>
<InputToolbar
hidden={!(inputFocused || props.isMainInput)}
onAddContextItem={() => {
if (inputBoxRef.current) {
if (!inputBoxRef.current.innerText.endsWith("@")) {
inputBoxRef.current.innerText += "@";
}
if (dropdownState === "contextProviders") {
setDropdownState("closed");
} else {
setDropdownState("contextProviders");
}
// move cursor to end
const range = document.createRange();
const sel = window.getSelection();
range.setStart(inputBoxRef.current, 1);
range.collapse(true);
sel?.removeAllRanges();
sel?.addRange(range);
}
}}
/>
<TipTapEditor
onEnter={props.onEnter}
isMainInput={props.isMainInput}
availableContextProviders={availableContextProviders}
availableSlashCommands={availableSlashCommands}
></TipTapEditor>
</GradientBorder>
<InputDropdown
isMainInput={props.isMainInput || false}
showAbove={false}
dropdownState={dropdownState}
items={dropdownItems}
highlightedIndex={highlightedIndex}
/>
</div>
</div>
);

View file

@ -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 <Icon className={props.className} height="1.2em" width="1.2em" />;
}
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<HTMLDivElement>(null);
return (
<Ul
isMainInput={props.isMainInput}
showAbove={props.showAbove}
ulHeightPixels={
// ulRef.current?.getBoundingClientRect().height || 0
0
}
fontSize={getFontSize()}
hidden={props.dropdownState === "closed"}
>
{props.subMenuTitle && (
<div
ref={stickyDropdownHeaderDiv}
style={{
backgroundColor: secondaryDark,
borderBottom: `0.5px solid ${lightGray}`,
display: "flex",
gap: "4px",
position: "sticky",
top: "0px",
}}
className="py-2 px-4 my-0"
>
<ArrowLeftIcon
width="1.4em"
height="1.4em"
className="cursor-pointer"
onClick={props.exitSubMenu}
/>
{props.subMenuTitle}
</div>
)}
<div
style={{
maxHeight: `${
UlMaxHeight - (stickyDropdownHeaderDiv.current?.clientHeight || 50)
}px`,
overflow: "auto",
}}
>
{props.dropdownState !== "closed" &&
props.items.map((item, index) => (
<Li
style={{
borderTop: index === 0 ? "none" : `0.5px solid ${lightGray}`,
}}
key={`${item.title}${index}`}
highlighted={props.highlightedIndex === index}
onClick={() => props.selectItem(item)}
isLastItem={index === props.items.length - 1}
>
<span className="flex justify-between w-full items-center">
<div className="flex items-center justify-center">
{props.subMenuTitle && (
<FileIcon
height="20px"
width="20px"
filename={item.title}
></FileIcon>
)}
<DropdownIcon provider={item.title} className="mr-2" />
<DropdownIcon provider={item.id} className="mr-2" />
{item.title}
{" "}
</div>
<span
style={{
color: vscForeground,
float: "right",
textAlign: "right",
}}
hidden={props.highlightedIndex !== index}
className="whitespace-nowrap overflow-hidden overflow-ellipsis ml-2"
>
{item.description}
</span>
</span>
{/* {contextProviders
?.filter(
(provider) =>
!provider.description.dynamic ||
provider.description.requiresQuery
)
.find((provider) => provider.description.title === item.id) && (
<ArrowRightIcon
width="1.2em"
height="1.2em"
color={vscForeground}
className="ml-2 flex-shrink-0"
/>
)} */}
</Li>
))}
{props.dropdownState !== "closed" && props.items.length === 0 && (
<Li key="empty-items-li" highlighted={false} isLastItem={false}>
<span
style={{
color: lightGray,
float: "right",
textAlign: "right",
display: "flex",
width: "100%",
cursor: "default",
}}
>
No items found
</span>
</Li>
)}
</div>
</Ul>
);
}
export default InputDropdown;

View file

@ -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;

View file

@ -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 (
<AtSymbolIcon className={props.className} height="1.2em" width="1.2em" />
);
}
return <Icon className={props.className} height="1.2em" width="1.2em" />;
}
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 (
<ItemsDiv>
{props.items.length ? (
props.items.map((item, index) => (
<ItemDiv
as="button"
className={`item ${index === selectedIndex ? "is-selected" : ""}`}
key={index}
onClick={() => selectItem(index)}
onMouseEnter={() => setSelectedIndex(index)}
>
<span className="flex justify-between w-full items-center">
<div className="flex items-center justify-center">
{props.subMenuTitle && (
<FileIcon
height="20px"
width="20px"
filename={item.title}
></FileIcon>
)}
{/* <DropdownIcon provider={item.title} className="mr-2" /> */}
<DropdownIcon provider={item.id} className="mr-2" />
{item.title}
{" "}
</div>
<span
style={{
color: vscForeground,
float: "right",
textAlign: "right",
opacity: index !== selectedIndex ? 0 : 1,
}}
className="whitespace-nowrap overflow-hidden overflow-ellipsis ml-2"
>
{item.description}
</span>
</span>
</ItemDiv>
))
) : (
<ItemDiv className="item">No result</ItemDiv>
)}
</ItemsDiv>
);
});
export default MentionList;

View file

@ -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;
}

View file

@ -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 (
<div className="mention-list" {...rest}>
test
{options.map((option, index) => (
<div
key={option.id}
className={`mention-list-item ${
index === selectedIndex ? "mention-list-item-selected" : ""
}`}
>
<span>{option.label}</span>
</div>
))}
</div>
<InputBoxDiv>
<EditorContent
editor={editor}
onFocus={() => {
setInputFocused(true);
}}
onBlur={(e) => {
setInputFocused(false);
}}
/>
<InputToolbar
hidden={!(inputFocused || props.isMainInput)}
onAddContextItem={() => {
if (editor.getText().endsWith("@")) {
} else {
editor.commands.insertContent("@");
}
}}
onEnter={async () => {
props.onEnter(await resolveEditorContent(editor, contextProviders));
}}
/>
</InputBoxDiv>
);
}
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: `
<p>
What do you all think about the new <span data-type="mention" data-id="Winona Ryder"></span> movie?
</p>
`,
});
return (
<div>
<EditorContent editor={editor} />
</div>
);
};
export default TipTapEditor;

View file

@ -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<string> {
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;

View file

@ -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;

View file

@ -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<ContextItemWithId[]> {
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<ContextItemWithId[]> {
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;

View file

@ -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<HTMLInputElement>(null);
const topGuiDivRef = useRef<HTMLDivElement>(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<string>(
sessionTitle || "New Session"
);
return (
<>
<TopGuiDiv
ref={topGuiDivRef}
onKeyDown={(e) => {
if (e.key === "Enter" && e.ctrlKey) {
onMainTextInput();
}
}}
>
<TopGuiDiv ref={topGuiDivRef}>
<div className="max-w-3xl m-auto">
<StepsDiv>
{state.history.map((item, index: number) => {
@ -430,27 +386,14 @@ function GUI(props: GUIProps) {
}}
>
{item.message.role === "user" ? (
<ComboBox
isMainInput={false}
value={item.message.content}
isLastUserInput={isLastUserInput(index)}
onEnter={(e, value) => {
if (value) {
dispatch(
resubmitAtIndex({ index, content: value })
);
streamResponse(value, index);
}
e?.stopPropagation();
e?.preventDefault();
<ContinueInputBox
onEnter={(value) => {
dispatch(resubmitAtIndex({ index, content: value }));
streamResponse(value, index);
}}
isToggleOpen={
typeof stepsOpen[index] === "undefined"
? true
: stepsOpen[index]!
}
index={index}
/>
isLastUserInput={isLastUserInput(index)}
isMainInput={false}
></ContinueInputBox>
) : (
<TimelineItem
item={item}
@ -505,7 +448,6 @@ function GUI(props: GUIProps) {
)}
</TimelineItem>
)}
{/* <div className="h-2"></div> */}
</ErrorBoundary>
</Fragment>
);
@ -514,25 +456,12 @@ function GUI(props: GUIProps) {
<div ref={aboveComboBoxDivRef} />
{active || (
<ComboBox
<ContinueInputBox
onEnter={sendInput}
isLastUserInput={false}
isMainInput={true}
ref={mainTextInputRef}
onEnter={(e, _) => {
onMainTextInput(e);
e?.stopPropagation();
e?.preventDefault();
}}
onInputValueChange={() => {}}
onToggleAddContext={() => {}}
/>
></ContinueInputBox>
)}
<br />
<br />
<ContinueInputBox isLastUserInput={false}></ContinueInputBox>
<br />
<br />
<TipTapEditor></TipTapEditor>
</div>
</TopGuiDiv>
{active && (