Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve autocomplete input #1152

Merged
merged 18 commits into from
Dec 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions client/src/components/Chat/ChatBody/AllCoversations/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ const AllConversations = ({
return (
<div className={`flex-1 flex flex-col overflow-auto`}>
{!openItem && (
<div className="flex flex-col gap-1 overflow-auto flex-1 pb-12">
<div className="flex flex-col gap-1 overflow-auto flex-1 pb-28">
{conversations.map((c) => (
<ConversationListItem
key={c.thread_id}
Expand All @@ -119,7 +119,7 @@ const AllConversations = ({
isHistory
repoName={repoName}
onMessageEdit={() => {}}
setInputValue={() => {}}
setInputValueImperatively={() => {}}
/>
</div>
)}
Expand Down
8 changes: 4 additions & 4 deletions client/src/components/Chat/ChatBody/Conversation.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { Dispatch, SetStateAction, useContext } from 'react';
import React, { useContext } from 'react';
import ScrollToBottom from 'react-scroll-to-bottom';
import {
ChatMessage,
Expand All @@ -17,7 +17,7 @@ type Props = {
isLoading?: boolean;
isHistory?: boolean;
onMessageEdit: (queryId: string, i: number) => void;
setInputValue: Dispatch<SetStateAction<string>>;
setInputValueImperatively: (s: string) => void;
};

const Conversation = ({
Expand All @@ -28,7 +28,7 @@ const Conversation = ({
isHistory,
repoName,
onMessageEdit,
setInputValue,
setInputValueImperatively,
}: Props) => {
const { navigatedItem } = useContext(AppNavigationContext);

Expand All @@ -37,7 +37,7 @@ const Conversation = ({
{!isHistory && (
<FirstMessage
repoName={repoName}
setInputValue={setInputValue}
setInputValueImperatively={setInputValueImperatively}
repoRef={repoRef}
isEmptyConversation={!conversation.length}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ type Props = {
const LangChip = ({ lang }: Props) => {
return (
<span
className={`inline-flex items-center bg-bg-base rounded-4 overflow-hidden
text-label-base border border-bg-border align-middle`}
className={`inline-flex items-center bg-chat-bg-base rounded-4 overflow-hidden
text-label-title align-middle h-6`}
>
<span className="flex gap-1 px-1 py-0.5 items-center code-s">
<FileIcon filename={getFileExtensionForLang(lang, true)} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ const PathChip = ({ path }: Props) => {
const isFolder = useMemo(() => path.endsWith('/'), [path]);
return (
<span
className={`inline-flex items-center bg-bg-base rounded-4 overflow-hidden
text-label-base border border-bg-border align-middle`}
className={`inline-flex items-center bg-chat-bg-base rounded-4 overflow-hidden
text-label-title align-middle h-6`}
>
<span className="flex gap-1 px-1 py-0.5 items-center code-s">
{isFolder ? (
Expand Down
14 changes: 4 additions & 10 deletions client/src/components/Chat/ChatBody/FirstMessage.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
import React, {
Dispatch,
memo,
SetStateAction,
useEffect,
useState,
} from 'react';
import React, { memo, useEffect, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { TutorialQuestionType } from '../../../types/api';
import { getTutorialQuestions } from '../../../services/api';
Expand All @@ -13,12 +7,12 @@ type Props = {
repoName: string;
repoRef: string;
isEmptyConversation: boolean;
setInputValue: Dispatch<SetStateAction<string>>;
setInputValueImperatively: (s: string) => void;
};

const FirstMessage = ({
repoName,
setInputValue,
setInputValueImperatively,
repoRef,
isEmptyConversation,
}: Props) => {
Expand Down Expand Up @@ -60,7 +54,7 @@ const FirstMessage = ({
className="px-3 py-1 rounded-full border border-chat-bg-divider bg-chat-bg-sub flex-shrink-0 caption text-label-base"
onClick={() => {
// setIsTutorialHidden(true);
setInputValue(t.question);
setInputValueImperatively(t.question);
}}
>
{t.tag}
Expand Down
6 changes: 3 additions & 3 deletions client/src/components/Chat/ChatBody/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type Props = {
hideMessagesFrom: null | number;
openHistoryItem: OpenChatHistoryItem | null;
setOpenHistoryItem: Dispatch<SetStateAction<OpenChatHistoryItem | null>>;
setInputValue: Dispatch<SetStateAction<string>>;
setInputValueImperatively: (s: string) => void;
};

const ChatBody = ({
Expand All @@ -29,7 +29,7 @@ const ChatBody = ({
hideMessagesFrom,
openHistoryItem,
setOpenHistoryItem,
setInputValue,
setInputValueImperatively,
}: Props) => {
useTranslation();
const { conversation, threadId } = useContext(ChatContext.Values);
Expand All @@ -54,7 +54,7 @@ const ChatBody = ({
isLoading={isLoading}
repoName={repoName}
onMessageEdit={onMessageEdit}
setInputValue={setInputValue}
setInputValueImperatively={setInputValueImperatively}
/>
)}
{!!queryIdToEdit && (
Expand Down
212 changes: 212 additions & 0 deletions client/src/components/Chat/ChatFooter/Input/InputCore.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { EditorState, Transaction } from 'prosemirror-state';
import { Schema } from 'prosemirror-model';
import { keymap } from 'prosemirror-keymap';
import { baseKeymap } from 'prosemirror-commands';
import {
NodeViewComponentProps,
ProseMirror,
react,
ReactNodeViewConstructor,
useNodeViews,
} from '@nytimes/react-prosemirror';
import { schema as basicSchema } from 'prosemirror-schema-basic';
import * as icons from 'file-icons-js';
import { useTranslation } from 'react-i18next';
import { getFileExtensionForLang, InputEditorContent } from '../../../../utils';
import {
ParsedQueryType,
ParsedQueryTypeEnum,
} from '../../../../types/general';
import { getMentionsPlugin } from './mentionPlugin';
import { addMentionNodes } from './utils';
import { placeholderPlugin } from './placeholderPlugin';

const schema = new Schema({
nodes: addMentionNodes(basicSchema.spec.nodes),
marks: basicSchema.spec.marks,
});

function Paragraph({ children }: NodeViewComponentProps) {
return <p>{children}</p>;
}

const reactNodeViews: Record<string, ReactNodeViewConstructor> = {
paragraph: () => ({
component: Paragraph,
dom: document.createElement('div'),
contentDOM: document.createElement('span'),
}),
};

type Props = {
getDataLang: (search: string) => Promise<{ id: string; display: string }[]>;
getDataPath: (search: string) => Promise<{ id: string; display: string }[]>;
initialValue?: Record<string, any> | null;
onChange: (contents: InputEditorContent[]) => void;
onSubmit?: (s: { parsed: ParsedQueryType[]; plain: string }) => void;
placeholder: string;
};

const InputCore = ({
getDataLang,
getDataPath,
initialValue,
onChange,
onSubmit,
placeholder,
}: Props) => {
const { t } = useTranslation();
const mentionPlugin = useMemo(
() =>
getMentionsPlugin({
delay: 10,
getSuggestions: async (
type: string,
text: string,
done: (s: Record<string, string>[]) => void,
) => {
const data = await Promise.all([
getDataPath(text),
getDataLang(text),
]);
done([...data[0], ...data[1]]);
},
getSuggestionsHTML: (items) => {
return (
'<div class="suggestion-item-list rounded-md border border-chat-bg-border p-1 shadow-high max-h-[500px] overflow-auto bg-chat-bg-shade">' +
items
.map(
(i) =>
`<div>${
i.isFirst
? `<div class="flex items-center gap-2 px-2 py-1 text-label-muted caption-strong cursor-default">
${t(
i.type === 'dir'
? 'Directories'
: i.type === 'lang'
? 'Languages'
: 'Files',
)}
</div>`
: ''
}<div class="suggestion-item cursor-pointer flex items-center justify-start rounded-6 gap-2 px-2 h-8 body-s text-label-title max-w-[600px] ellipsis">${
i.type === 'dir'
? `<svg viewBox="0 0 20 20" width="16" height="16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M2 5.5C2 4.39543 2.89543 3.5 4 3.5H7.17157C7.70201 3.5 8.21071 3.71071 8.58579 4.08579L9.41421 4.91421C9.78929 5.28929 10.298 5.5 10.8284 5.5H16C17.1046 5.5 18 6.39543 18 7.5V14.5C18 15.6046 17.1046 16.5 16 16.5H4C2.89543 16.5 2 15.6046 2 14.5V5.5Z" fill="currentColor"></path></svg>`
: `<span class="${
icons.getClassWithColor(
getFileExtensionForLang(i.display, true),
) || icons.getClassWithColor('.txt')
} text-left w-4 h-4 file-icon flex items-center flex-shrink-0"></span>`
}<span class="ellipsis">${i.display}</span></div></div>`,
)
.join('') +
'</div>'
);
},
}),
[],
);

const plugins = useMemo(() => {
return [
keymap({
...baseKeymap,
Enter: (state) => {
const key = Object.keys(state).find((k) =>
k.startsWith('autosuggestions'),
);
// @ts-ignore
if (key && state[key]?.active) {
return false;
}
const parts = state.toJSON().doc.content[0]?.content;
// trying to submit with no text
if (!parts) {
return false;
}
onSubmit?.({
parsed:
parts?.map((s: InputEditorContent) =>
s.type === 'mention'
? {
type:
s.attrs.type === 'lang'
? ParsedQueryTypeEnum.LANG
: ParsedQueryTypeEnum.PATH,
text: s.attrs.id,
}
: { type: ParsedQueryTypeEnum.TEXT, text: s.text },
) || [],
plain: parts
?.map((s: InputEditorContent) =>
s.type === 'mention' ? `${s.attrs.type}:${s.attrs.id}` : s.text,
)
.join(''),
});
return true;
},
'Ctrl-Enter': baseKeymap.Enter,
'Cmd-Enter': baseKeymap.Enter,
'Shift-Enter': baseKeymap.Enter,
}),
placeholderPlugin(placeholder),
react(),
mentionPlugin,
];
}, [onSubmit]);

const { nodeViews, renderNodeViews } = useNodeViews(reactNodeViews);
const [mount, setMount] = useState<HTMLDivElement | null>(null);
const [state, setState] = useState(
EditorState.create({
doc: initialValue
? schema.topNodeType.create(null, [schema.nodeFromJSON(initialValue)])
: undefined,
schema,
plugins,
}),
);

useEffect(() => {
if (mount) {
setState(
EditorState.create({
schema,
plugins,
doc: initialValue
? schema.topNodeType.create(null, [
schema.nodeFromJSON(initialValue),
])
: undefined,
}),
);
}
}, [mount, initialValue, plugins]);

const dispatchTransaction = useCallback(
(tr: Transaction) => setState((oldState) => oldState.apply(tr)),
[],
);

useEffect(() => {
const newValue = state.toJSON().doc.content[0]?.content;
onChange(newValue || []);
}, [state]);

return (
<div className="w-full py-4 leading-[24px] overflow-auto bg-transparent rounded-lg outline-none focus:outline-0 resize-none flex-grow-0 flex flex-col justify-center">
<ProseMirror
mount={mount}
state={state}
nodeViews={nodeViews}
dispatchTransaction={dispatchTransaction}
>
<div ref={setMount} autoCorrect="off" />
{renderNodeViews()}
</ProseMirror>
</div>
);
};

export default memo(InputCore);
Loading