Merge branch 'main' into feat/jwt-auth

This commit is contained in:
Siddhant Rai
2025-03-18 18:26:29 +05:30
committed by GitHub
61 changed files with 1721 additions and 1075 deletions

View File

@@ -1,26 +1,17 @@
import { Fragment, useCallback, useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import Hero from '../Hero';
import { useDropzone } from 'react-dropzone';
import DragFileUpload from '../assets/DragFileUpload.svg';
import ArrowDown from '../assets/arrow-down.svg';
import newChatIcon from '../assets/openNewChat.svg';
import Send from '../assets/send.svg';
import SendDark from '../assets/send_dark.svg';
import ShareIcon from '../assets/share.svg';
import SpinnerDark from '../assets/spinner-dark.svg';
import Spinner from '../assets/spinner.svg';
import RetryIcon from '../components/RetryIcon';
import { useDarkTheme, useMediaQuery } from '../hooks';
import { useMediaQuery } from '../hooks';
import { ShareConversationModal } from '../modals/ShareConversationModal';
import {
selectConversationId,
selectToken,
} from '../preferences/preferenceSlice';
import { AppDispatch } from '../store';
import ConversationBubble from './ConversationBubble';
import { handleSendFeedback } from './conversationHandlers';
import { FEEDBACK, Query } from './conversationModels';
import {
@@ -35,20 +26,17 @@ import {
} from './conversationSlice';
import Upload from '../upload/Upload';
import { ActiveState } from '../models/misc';
import ConversationMessages from './ConversationMessages';
import MessageInput from '../components/MessageInput';
export default function Conversation() {
const token = useSelector(selectToken);
const queries = useSelector(selectQueries);
const navigate = useNavigate();
const status = useSelector(selectStatus);
const conversationId = useSelector(selectConversationId);
const dispatch = useDispatch<AppDispatch>();
const conversationRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
const [isDarkTheme] = useDarkTheme();
const [hasScrolledToLast, setHasScrolledToLast] = useState(true);
const [input, setInput] = useState('');
const fetchStream = useRef<any>(null);
const [eventInterrupt, setEventInterrupt] = useState(false);
const [lastQueryReturnedErr, setLastQueryReturnedErr] = useState(false);
const [isShareModalOpen, setShareModalState] = useState<boolean>(false);
const { t } = useTranslation();
@@ -95,23 +83,6 @@ export default function Conversation() {
},
});
const handleUserInterruption = () => {
if (!eventInterrupt && status === 'loading') setEventInterrupt(true);
};
useEffect(() => {
!eventInterrupt && scrollIntoView();
if (queries.length == 0) {
resetConversation();
}
}, [queries.length, queries[queries.length - 1]]);
useEffect(() => {
const element = document.getElementById('inputbox') as HTMLTextAreaElement;
if (element) {
element.focus();
}
}, []);
useEffect(() => {
if (queries.length) {
queries[queries.length - 1].error && setLastQueryReturnedErr(true);
@@ -119,19 +90,6 @@ export default function Conversation() {
}
}, [queries[queries.length - 1]]);
const scrollIntoView = () => {
if (!conversationRef?.current || eventInterrupt) return;
if (status === 'idle' || !queries[queries.length - 1].response) {
conversationRef.current.scrollTo({
behavior: 'smooth',
top: conversationRef.current.scrollHeight,
});
} else {
conversationRef.current.scrollTop = conversationRef.current.scrollHeight;
}
};
const handleQuestion = ({
question,
isRetry = false,
@@ -150,7 +108,6 @@ export default function Conversation() {
} else {
question = question.trim();
if (question === '') return;
setEventInterrupt(false);
!isRetry && dispatch(addQuery({ prompt: question })); //dispatch only new queries
fetchStream.current = dispatch(fetchAnswer({ question }));
}
@@ -187,14 +144,14 @@ export default function Conversation() {
) => {
if (updated === true) {
handleQuestion({ question: updatedQuestion as string, updated, indx });
} else if (inputRef.current?.value && status !== 'loading') {
} else if (input && status !== 'loading') {
if (lastQueryReturnedErr) {
// update last failed query with new prompt
dispatch(
updateQuery({
index: queries.length - 1,
query: {
prompt: inputRef.current.value,
prompt: input,
},
}),
);
@@ -203,10 +160,9 @@ export default function Conversation() {
isRetry: true,
});
} else {
handleQuestion({ question: inputRef.current.value });
handleQuestion({ question: input });
}
inputRef.current.value = '';
handleInput();
setInput('');
}
};
const resetConversation = () => {
@@ -221,98 +177,21 @@ export default function Conversation() {
if (queries && queries.length > 0) resetConversation();
};
const prepResponseView = (query: Query, index: number) => {
let responseView;
if (query.response) {
responseView = (
<ConversationBubble
className={`${index === queries.length - 1 ? 'mb-32' : 'mb-7'}`}
key={`${index}ANSWER`}
message={query.response}
type={'ANSWER'}
sources={query.sources}
toolCalls={query.tool_calls}
feedback={query.feedback}
handleFeedback={(feedback: FEEDBACK) =>
handleFeedback(query, feedback, index)
}
></ConversationBubble>
);
} else if (query.error) {
const retryBtn = (
<button
className="flex items-center justify-center gap-3 self-center rounded-full py-3 px-5 text-lg text-gray-500 transition-colors delay-100 hover:border-gray-500 disabled:cursor-not-allowed dark:text-bright-gray"
disabled={status === 'loading'}
onClick={() => {
handleQuestion({
question: queries[queries.length - 1].prompt,
isRetry: true,
});
}}
>
<RetryIcon
width={isMobile ? 12 : 12} // change the width and height according to device size if necessary
height={isMobile ? 12 : 12}
fill={isDarkTheme ? 'rgb(236 236 241)' : 'rgb(107 114 120)'}
stroke={isDarkTheme ? 'rgb(236 236 241)' : 'rgb(107 114 120)'}
strokeWidth={10}
/>
</button>
);
responseView = (
<ConversationBubble
className={`${index === queries.length - 1 ? 'mb-32' : 'mb-7'} `}
key={`${index}ERROR`}
message={query.error}
type="ERROR"
retryBtn={retryBtn}
></ConversationBubble>
);
}
return responseView;
};
const handleInput = () => {
if (inputRef.current) {
if (window.innerWidth < 350) inputRef.current.style.height = 'auto';
else inputRef.current.style.height = '64px';
inputRef.current.style.height = `${Math.min(
inputRef.current.scrollHeight,
96,
)}px`;
}
};
const checkScroll = () => {
const el = conversationRef.current;
if (!el) return;
const isBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 10;
setHasScrolledToLast(isBottom);
};
useEffect(() => {
handleInput();
window.addEventListener('resize', handleInput);
conversationRef.current?.addEventListener('scroll', checkScroll);
return () => {
window.removeEventListener('resize', handleInput);
conversationRef.current?.removeEventListener('scroll', checkScroll);
};
}, []);
return (
<div className="flex flex-col gap-1 h-full justify-end ">
<div className="flex flex-col gap-1 h-full justify-end">
{conversationId && queries.length > 0 && (
<div className="absolute top-4 right-20 z-10 ">
{' '}
<div className="flex mt-2 items-center gap-4 ">
<div className="absolute top-4 right-20">
<div className="flex mt-2 items-center gap-4">
{isMobile && queries.length > 0 && (
<button
title="Open New Chat"
onClick={() => {
newChat();
}}
className="hover:bg-bright-gray dark:hover:bg-[#28292E]"
className="hover:bg-bright-gray dark:hover:bg-[#28292E] rounded-full p-2"
>
<img
className=" h-5 w-5 filter dark:invert "
className="h-5 w-5 filter dark:invert"
alt="NewChat"
src={newChatIcon}
/>
@@ -324,10 +203,10 @@ export default function Conversation() {
onClick={() => {
setShareModalState(true);
}}
className=" hover:bg-bright-gray dark:hover:bg-[#28292E]"
className="hover:bg-bright-gray dark:hover:bg-[#28292E] rounded-full p-2"
>
<img
className=" h-5 w-5 filter dark:invert"
className="h-5 w-5 filter dark:invert"
alt="share"
src={ShareIcon}
/>
@@ -343,102 +222,33 @@ export default function Conversation() {
)}
</div>
)}
<div
ref={conversationRef}
onWheel={handleUserInterruption}
onTouchMove={handleUserInterruption}
className="flex justify-center w-full overflow-y-auto h-screen sm:mt-12"
>
{queries.length > 0 && !hasScrolledToLast && (
<button
onClick={scrollIntoView}
aria-label="scroll to bottom"
className="fixed bottom-40 right-14 z-10 flex h-7 w-7 items-center justify-center rounded-full border-[0.5px] border-gray-alpha bg-gray-100 bg-opacity-50 dark:bg-purple-taupe md:h-9 md:w-9 md:bg-opacity-100 "
>
<img
src={ArrowDown}
alt="arrow down"
className="h-4 w-4 opacity-50 md:h-5 md:w-5"
/>
</button>
)}
{queries.length > 0 ? (
<div className="w-full md:w-8/12">
{queries.map((query, index) => {
return (
<Fragment key={index}>
<ConversationBubble
className={'first:mt-5'}
key={`${index}QUESTION`}
message={query.prompt}
type="QUESTION"
handleUpdatedQuestionSubmission={handleQuestionSubmission}
questionNumber={index}
sources={query.sources}
></ConversationBubble>
<ConversationMessages
handleQuestion={handleQuestion}
handleQuestionSubmission={handleQuestionSubmission}
handleFeedback={handleFeedback}
queries={queries}
status={status}
/>
{prepResponseView(query, index)}
</Fragment>
);
})}
</div>
) : (
<Hero handleQuestion={handleQuestion} />
)}
</div>
<div className="flex w-11/12 flex-col items-end self-center rounded-2xl bg-opacity-0 z-3 sm:w-[62%] h-auto py-1">
<div className="flex flex-col items-end self-center rounded-2xl bg-opacity-0 z-3 w-full md:w-9/12 lg:w-8/12 xl:w-8/12 2xl:w-6/12 max-w-[1300px] h-auto py-1">
<div
{...getRootProps()}
className="flex w-full items-center rounded-[40px] border border-silver bg-white dark:bg-raisin-black"
className="flex w-full items-center rounded-[40px]"
>
<label htmlFor="file-upload" className="sr-only">
{t('modals.uploadDoc.label')}
</label>
<input {...getInputProps()} id="file-upload" />
<label htmlFor="message-input" className="sr-only">
{t('inputPlaceholder')}
</label>
<textarea
id="message-input"
ref={inputRef}
tabIndex={1}
placeholder={t('inputPlaceholder')}
className={`inputbox-style w-full overflow-y-auto overflow-x-hidden whitespace-pre-wrap rounded-full bg-transparent py-5 text-base leading-tight opacity-100 focus:outline-none dark:bg-transparent dark:text-bright-gray dark:placeholder-bright-gray dark:placeholder-opacity-50`}
onInput={handleInput}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleQuestionSubmission();
}
}}
aria-label={t('inputPlaceholder')}
></textarea>
{status === 'loading' ? (
<img
src={isDarkTheme ? SpinnerDark : Spinner}
className="relative right-[38px] bottom-[24px] -mr-[30px] animate-spin cursor-pointer self-end bg-transparent"
alt={t('loading')}
/>
) : (
<div className="mx-1 cursor-pointer rounded-full p-3 text-center hover:bg-gray-3000 dark:hover:bg-dark-charcoal">
<button
onClick={() => handleQuestionSubmission()}
aria-label={t('send')}
className="flex items-center justify-center"
>
<img
className="ml-[4px] h-6 w-6 text-white"
src={isDarkTheme ? SendDark : Send}
alt={t('send')}
/>
</button>
</div>
)}
<MessageInput
value={input}
onChange={(e) => setInput(e.target.value)}
onSubmit={handleQuestionSubmission}
loading={status === 'loading'}
/>
</div>
<p className="text-gray-595959 hidden w-[100vw] self-center bg-transparent py-2 text-center text-xs dark:text-bright-gray md:inline md:w-full">
<p className="text-gray-4000 hidden w-[100vw] self-center bg-transparent py-2 text-center text-xs dark:text-sonic-silver md:inline md:w-full">
{t('tagline')}
</p>
</div>

View File

@@ -5,10 +5,14 @@ import { useTranslation } from 'react-i18next';
import ReactMarkdown from 'react-markdown';
import { useSelector } from 'react-redux';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/cjs/styles/prism';
import {
vscDarkPlus,
oneLight,
} from 'react-syntax-highlighter/dist/cjs/styles/prism';
import rehypeKatex from 'rehype-katex';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import { useDarkTheme } from '../hooks';
import DocsGPT3 from '../assets/cute_docsgpt3.svg';
import ChevronDown from '../assets/chevron-down.svg';
@@ -18,7 +22,7 @@ import Edit from '../assets/edit.svg';
import Like from '../assets/like.svg?react';
import Link from '../assets/link.svg';
import Sources from '../assets/sources.svg';
import UserIcon from '../assets/user.png';
import UserIcon from '../assets/user.svg';
import Accordion from '../components/Accordion';
import Avatar from '../components/Avatar';
import CopyButton from '../components/CopyButton';
@@ -69,6 +73,7 @@ const ConversationBubble = forwardRef<
ref,
) {
const { t } = useTranslation();
const [isDarkTheme] = useDarkTheme();
// const bubbleRef = useRef<HTMLDivElement | null>(null);
const chunks = useSelector(selectChunks);
const selectedDocs = useSelector(selectSelectedDocs);
@@ -113,7 +118,7 @@ const ConversationBubble = forwardRef<
style={{
wordBreak: 'break-word',
}}
className="text-sm sm:text-base ml-2 mr-2 flex items-center rounded-[28px] bg-purple-30 py-[14px] px-[19px] text-white max-w-full whitespace-pre-wrap leading-normal"
className="text-sm sm:text-base ml-2 mr-2 flex items-center rounded-[28px] bg-gradient-to-b from-medium-purple to-slate-blue py-[14px] px-[19px] text-white max-w-full whitespace-pre-wrap leading-normal"
>
{message}
</div>
@@ -122,7 +127,7 @@ const ConversationBubble = forwardRef<
setIsEditClicked(true);
setEditInputBox(message);
}}
className={`flex-shrink-0 h-fit mt-3 p-2 cursor-pointer rounded-full hover:bg-[#35363B] flex items-center ${isQuestionHovered || isEditClicked ? 'visible' : 'invisible'}`}
className={`flex-shrink-0 h-fit mt-3 p-2 cursor-pointer rounded-full hover:bg-light-silver dark:hover:bg-[#35363B] flex items-center ${isQuestionHovered || isEditClicked ? 'visible' : 'invisible'}`}
>
<img src={Edit} alt="Edit" className="cursor-pointer" />
</button>
@@ -138,29 +143,29 @@ const ConversationBubble = forwardRef<
onChange={(e) => {
setEditInputBox(e.target.value);
}}
onKeyDown={(e) => {
if(e.key === 'Enter' && !e.shiftKey){
e.preventDefault();
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleEditClick();
}
}}
rows={5}
value={editInputBox}
className="w-full resize-none border-2 border-black dark:border-white rounded-3xl px-4 py-3 text-base leading-relaxed text-black dark:bg-raisin-black dark:text-white focus:outline-none focus:ring-2 focus:ring-[#CDB5FF]"
className="w-full resize-none border border-silver dark:border-philippine-grey rounded-3xl px-4 py-3 text-base leading-relaxed text-carbon dark:text-chinese-white dark:bg-raisin-black focus:outline-none"
/>
<div className="flex items-center justify-end gap-2">
<button
className="rounded-full bg-[#CDB5FF] hover:bg-[#E1D3FF] px-4 py-2 text-purple-30 text-sm font-medium"
onClick={handleEditClick}
>
{t('conversation.edit.update')}
</button>
<button
className="px-4 py-2 text-purple-30 text-sm hover:underline"
className="px-4 py-2 text-purple-30 text-sm font-semibold hover:text-chinese-black-2 dark:hover:text-[#B9BCBE] hover:bg-gainsboro dark:hover:bg-onyx-2 transition-colors rounded-full"
onClick={() => setIsEditClicked(false)}
>
{t('conversation.edit.cancel')}
</button>
<button
className="rounded-full bg-purple-30 hover:bg-violets-are-blue dark:hover:bg-royal-purple px-4 py-2 text-white text-sm font-medium transition-colors"
onClick={handleEditClick}
>
{t('conversation.edit.update')}
</button>
</div>
</div>
)}
@@ -341,7 +346,7 @@ const ConversationBubble = forwardRef<
</p>
</div>
<div
className={`fade-in-bubble ml-2 mr-5 flex max-w-[90vw] rounded-[28px] bg-gray-1000 py-[14px] px-7 dark:bg-gun-metal md:max-w-[70vw] lg:max-w-[50vw] ${
className={`fade-in-bubble ml-2 mr-5 flex max-w-[90vw] rounded-[28px] bg-gray-1000 py-[18px] px-7 dark:bg-gun-metal md:max-w-[70vw] lg:max-w-[50vw] ${
type === 'ERROR'
? 'relative flex-row items-center rounded-full border border-transparent bg-[#FFE7E7] p-2 py-5 text-sm font-normal text-red-3000 dark:border-red-2000 dark:text-white'
: 'flex-col rounded-3xl'
@@ -355,25 +360,32 @@ const ConversationBubble = forwardRef<
code(props) {
const { children, className, node, ref, ...rest } = props;
const match = /language-(\w+)/.exec(className || '');
const language = match ? match[1] : '';
return match ? (
<div className="group relative">
<SyntaxHighlighter
{...rest}
PreTag="div"
language={match[1]}
style={vscDarkPlus}
>
{String(children).replace(/\n$/, '')}
</SyntaxHighlighter>
<div
className={`absolute right-3 top-3 lg:invisible
${type !== 'ERROR' ? 'group-hover:lg:visible' : ''} `}
>
<div className="group relative rounded-[14px] overflow-hidden border border-light-silver dark:border-raisin-black">
<div className="flex justify-between items-center px-2 py-1 bg-platinum dark:bg-eerie-black-2">
<span className="text-xs font-medium text-just-black dark:text-chinese-white">
{language}
</span>
<CopyButton
text={String(children).replace(/\n$/, '')}
/>
</div>
<SyntaxHighlighter
{...rest}
PreTag="div"
language={language}
style={isDarkTheme ? vscDarkPlus : oneLight}
className="!mt-0"
customStyle={{
margin: 0,
borderRadius: 0,
scrollbarWidth: 'thin',
}}
>
{String(children).replace(/\n$/, '')}
</SyntaxHighlighter>
</div>
) : (
<code className="whitespace-pre-line rounded-[6px] bg-gray-200 px-[8px] py-[4px] text-xs font-normal dark:bg-independence dark:text-bright-gray">

View File

@@ -0,0 +1,180 @@
import { Fragment, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import ConversationBubble from './ConversationBubble';
import Hero from '../Hero';
import { FEEDBACK, Query, Status } from './conversationModels';
import ArrowDown from '../assets/arrow-down.svg';
import RetryIcon from '../components/RetryIcon';
import { useDarkTheme } from '../hooks';
interface ConversationMessagesProps {
handleQuestion: (params: {
question: string;
isRetry?: boolean;
updated?: boolean | null;
indx?: number;
}) => void;
handleQuestionSubmission: (
updatedQuestion?: string,
updated?: boolean,
indx?: number,
) => void;
handleFeedback?: (query: Query, feedback: FEEDBACK, index: number) => void;
queries: Query[];
status: Status;
}
export default function ConversationMessages({
handleQuestion,
handleQuestionSubmission,
queries,
status,
handleFeedback,
}: ConversationMessagesProps) {
const [isDarkTheme] = useDarkTheme();
const { t } = useTranslation();
const conversationRef = useRef<HTMLDivElement>(null);
const [hasScrolledToLast, setHasScrolledToLast] = useState(true);
const [eventInterrupt, setEventInterrupt] = useState(false);
const handleUserInterruption = () => {
if (!eventInterrupt && status === 'loading') {
setEventInterrupt(true);
}
};
const scrollIntoView = () => {
if (!conversationRef?.current || eventInterrupt) return;
if (status === 'idle' || !queries[queries.length - 1]?.response) {
conversationRef.current.scrollTo({
behavior: 'smooth',
top: conversationRef.current.scrollHeight,
});
} else {
conversationRef.current.scrollTop = conversationRef.current.scrollHeight;
}
};
const checkScroll = () => {
const el = conversationRef.current;
if (!el) return;
const isBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 10;
setHasScrolledToLast(isBottom);
};
useEffect(() => {
!eventInterrupt && scrollIntoView();
}, [queries.length, queries[queries.length - 1]]);
useEffect(() => {
if (status === 'idle') {
setEventInterrupt(false);
}
}, [status]);
useEffect(() => {
conversationRef.current?.addEventListener('scroll', checkScroll);
return () => {
conversationRef.current?.removeEventListener('scroll', checkScroll);
};
}, []);
const prepResponseView = (query: Query, index: number) => {
let responseView;
if (query.response) {
responseView = (
<ConversationBubble
className={`${index === queries.length - 1 ? 'mb-32' : 'mb-7'}`}
key={`${index}ANSWER`}
message={query.response}
type={'ANSWER'}
sources={query.sources}
toolCalls={query.tool_calls}
feedback={query.feedback}
handleFeedback={
handleFeedback
? (feedback) => handleFeedback(query, feedback, index)
: undefined
}
/>
);
} else if (query.error) {
const retryBtn = (
<button
className="flex items-center justify-center gap-3 self-center rounded-full py-3 px-5 text-lg text-gray-500 transition-colors delay-100 hover:border-gray-500 disabled:cursor-not-allowed dark:text-bright-gray"
disabled={status === 'loading'}
onClick={() => {
handleQuestion({
question: queries[queries.length - 1].prompt,
isRetry: true,
});
}}
>
<RetryIcon
width={12}
height={12}
fill={isDarkTheme ? 'rgb(236 236 241)' : 'rgb(107 114 120)'}
stroke={isDarkTheme ? 'rgb(236 236 241)' : 'rgb(107 114 120)'}
strokeWidth={10}
/>
</button>
);
responseView = (
<ConversationBubble
className={`${index === queries.length - 1 ? 'mb-32' : 'mb-7'} `}
key={`${index}ERROR`}
message={query.error}
type="ERROR"
retryBtn={retryBtn}
/>
);
}
return responseView;
};
return (
<div
ref={conversationRef}
onWheel={handleUserInterruption}
onTouchMove={handleUserInterruption}
className="flex justify-center w-full overflow-y-auto h-screen sm:pt-12"
>
{queries.length > 0 && !hasScrolledToLast && (
<button
onClick={scrollIntoView}
aria-label="scroll to bottom"
className="fixed bottom-40 right-14 z-10 flex h-7 w-7 items-center justify-center rounded-full border-[0.5px] border-gray-alpha bg-gray-100 bg-opacity-50 dark:bg-gunmetal md:h-9 md:w-9 md:bg-opacity-100"
>
<img
src={ArrowDown}
alt="arrow down"
className="h-4 w-4 opacity-50 md:h-5 md:w-5 filter dark:invert"
/>
</button>
)}
<div className="w-full md:w-9/12 lg:w-8/12 xl:w-8/12 2xl:w-6/12 max-w-[1300px] px-2">
{queries.length > 0 ? (
queries.map((query, index) => (
<Fragment key={index}>
<ConversationBubble
className={'first:mt-5'}
key={`${index}QUESTION`}
message={query.prompt}
type="QUESTION"
handleUpdatedQuestionSubmission={handleQuestionSubmission}
questionNumber={index}
sources={query.sources}
/>
{prepResponseView(query, index)}
</Fragment>
))
) : (
<Hero handleQuestion={handleQuestion} />
)}
</div>
</div>
);
}

View File

@@ -18,6 +18,9 @@ import { selectConversationId } from '../preferences/preferenceSlice';
import { ActiveState } from '../models/misc';
import { ShareConversationModal } from '../modals/ShareConversationModal';
import { useTranslation } from 'react-i18next';
import ContextMenu from '../components/ContextMenu';
import { MenuOption } from '../components/ContextMenu';
import { useOutsideAlerter } from '../hooks';
interface ConversationProps {
name: string;
@@ -128,6 +131,50 @@ export default function ConversationTile({
}
};
const menuOptions: MenuOption[] = [
{
icon: Share,
label: t('convTile.share'),
onClick: (event: SyntheticEvent) => {
event.stopPropagation();
setShareModalState(true);
setOpen(false);
},
variant: 'primary',
iconWidth: 14,
iconHeight: 14,
},
{
icon: Edit,
label: t('convTile.rename'),
onClick: handleEditConversation,
variant: 'primary',
},
{
icon: Trash,
label: t('convTile.delete'),
onClick: (event: SyntheticEvent) => {
event.stopPropagation();
setDeleteModalState('ACTIVE');
setOpen(false);
},
iconWidth: 18,
iconHeight: 18,
variant: 'danger',
},
];
useOutsideAlerter(
tileRef,
() => {
if (isEdit) {
onClear();
}
},
[isEdit],
true,
);
return (
<>
<div
@@ -136,16 +183,18 @@ export default function ConversationTile({
setIsHovered(true);
}}
onMouseLeave={() => {
setIsHovered(false);
if (!isEdit) {
setIsHovered(false);
}
}}
onClick={() => {
onCoversationClick();
conversationId !== conversation.id &&
selectConversation(conversation.id);
}}
className={`my-auto mx-4 mt-4 flex h-9 cursor-pointer items-center justify-between pl-4 gap-4 rounded-3xl hover:bg-gray-100 dark:hover:bg-[#28292E] ${
conversationId === conversation.id || isOpen || isHovered
? 'bg-gray-100 dark:bg-[#28292E]'
className={`my-auto mx-4 mt-4 flex h-9 cursor-pointer items-center justify-between pl-4 gap-4 rounded-3xl hover:bg-bright-gray dark:hover:bg-dark-charcoal ${
conversationId === conversation.id || isOpen || isHovered || isEdit
? 'bg-bright-gray dark:bg-dark-charcoal'
: ''
}`}
>
@@ -160,13 +209,13 @@ export default function ConversationTile({
onKeyDown={handleRenameKeyDown}
/>
) : (
<p className="my-auto overflow-hidden overflow-ellipsis whitespace-nowrap text-sm font-normal leading-6 text-eerie-black dark:text-white">
<p className="my-auto overflow-hidden overflow-ellipsis whitespace-nowrap text-sm font-normal leading-6 text-eerie-black dark:text-bright-gray">
{conversationName}
</p>
)}
</div>
{(conversationId === conversation.id || isHovered || isOpen) && (
<div className="flex text-white dark:text-[#949494]" ref={menuRef}>
<div className="flex text-white dark:text-sonic-silver" ref={menuRef}>
{isEdit ? (
<div className="flex gap-1">
<img
@@ -204,64 +253,14 @@ export default function ConversationTile({
<img src={threeDots} width={8} />
</button>
)}
{isOpen && (
<div
className="flex-start absolute z-30 flex w-32 translate-x-1 translate-y-5 flex-col rounded-xl bg-stone-100 text-sm text-black shadow-xl dark:bg-chinese-black dark:text-chinese-silver md:w-36"
style={{
top: `${(tileRef.current?.getBoundingClientRect().top ?? 0) + window.scrollY + 8}px`,
}}
>
<button
onClick={(event: SyntheticEvent) => {
event.stopPropagation();
setShareModalState(true);
setOpen(false);
}}
className="flex-start flex items-center gap-4 rounded-t-xl p-3 hover:bg-bright-gray dark:hover:bg-dark-charcoal"
>
<img
src={Share}
alt="Share"
width={14}
height={14}
className="cursor-pointer hover:opacity-50"
id={`img-${conversation.id}`}
/>
<span>{t('convTile.share')}</span>
</button>
<button
onClick={handleEditConversation}
className="flex-start flex items-center gap-4 p-3 hover:bg-bright-gray dark:hover:bg-dark-charcoal"
>
<img
src={Edit}
alt="Edit"
width={16}
height={16}
className="cursor-pointer hover:opacity-50"
id={`img-${conversation.id}`}
/>
<span>{t('convTile.rename')}</span>
</button>
<button
onClick={(event: SyntheticEvent) => {
event.stopPropagation();
setDeleteModalState('ACTIVE');
setOpen(false);
}}
className="flex-start flex items-center gap-3 rounded-b-xl p-2 text-red-700 hover:bg-bright-gray dark:hover:bg-dark-charcoal"
>
<img
src={Trash}
alt="Delete"
width={24}
height={24}
className="cursor-pointer hover:opacity-50"
/>
<span>{t('convTile.delete')}</span>
</button>
</div>
)}
<ContextMenu
isOpen={isOpen}
setIsOpen={setOpen}
options={menuOptions}
anchorRef={tileRef}
position="bottom-right"
offset={{ x: 1, y: 8 }}
/>
</div>
)}
</div>

View File

@@ -1,16 +1,20 @@
import { Fragment, useEffect, useRef, useState } from 'react';
import { Helmet } from 'react-helmet';
import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate, useParams } from 'react-router-dom';
import ConversationMessages from './ConversationMessages';
import MessageInput from '../components/MessageInput';
import conversationService from '../api/services/conversationService';
import Send from '../assets/send.svg';
import Spinner from '../assets/spinner.svg';
import { selectToken } from '../preferences/preferenceSlice';
import { AppDispatch } from '../store';
import ConversationBubble from './ConversationBubble';
import { Query } from './conversationModels';
import {
addQuery,
fetchSharedAnswer,
@@ -24,6 +28,7 @@ import {
setIdentifier,
updateQuery,
} from './sharedConversationSlice';
import { formatDate } from '../utils/dateTimeUtils';
export const SharedConversation = () => {
const navigate = useNavigate();
@@ -36,27 +41,14 @@ export const SharedConversation = () => {
const apiKey = useSelector(selectClientAPIKey);
const status = useSelector(selectStatus);
const inputRef = useRef<HTMLDivElement>(null);
const sharedConversationRef = useRef<HTMLDivElement>(null);
const [input, setInput] = useState('');
const { t } = useTranslation();
const dispatch = useDispatch<AppDispatch>();
const [lastQueryReturnedErr, setLastQueryReturnedErr] = useState(false);
const [eventInterrupt, setEventInterrupt] = useState(false);
const endMessageRef = useRef<HTMLDivElement>(null);
const handleUserInterruption = () => {
if (!eventInterrupt && status === 'loading') setEventInterrupt(true);
};
useEffect(() => {
!eventInterrupt && scrollIntoView();
}, [queries.length, queries[queries.length - 1]]);
useEffect(() => {
identifier && dispatch(setIdentifier(identifier));
const element = document.getElementById('inputbox') as HTMLInputElement;
if (element) {
element.focus();
}
}, []);
useEffect(() => {
@@ -66,20 +58,6 @@ export const SharedConversation = () => {
}
}, [queries[queries.length - 1]]);
const scrollIntoView = () => {
if (!sharedConversationRef?.current || eventInterrupt) return;
if (status === 'idle' || !queries[queries.length - 1].response) {
sharedConversationRef.current.scrollTo({
behavior: 'smooth',
top: sharedConversationRef.current.scrollHeight,
});
} else {
sharedConversationRef.current.scrollTop =
sharedConversationRef.current.scrollHeight;
}
};
const fetchQueries = () => {
identifier &&
conversationService
@@ -95,7 +73,7 @@ export const SharedConversation = () => {
setFetchedData({
queries: data.queries,
title: data.title,
date: data.date,
date: formatDate(data.timestamp),
identifier,
}),
);
@@ -103,47 +81,16 @@ export const SharedConversation = () => {
}
});
};
const handlePaste = (e: React.ClipboardEvent) => {
e.preventDefault();
const text = e.clipboardData.getData('text/plain');
inputRef.current && (inputRef.current.innerText = text);
};
const prepResponseView = (query: Query, index: number) => {
let responseView;
if (query.response) {
responseView = (
<ConversationBubble
ref={endMessageRef}
className={`${index === queries.length - 1 ? 'mb-32' : 'mb-7'}`}
key={`${index}ANSWER`}
message={query.response}
type={'ANSWER'}
sources={query.sources ?? []}
toolCalls={query.tool_calls}
></ConversationBubble>
);
} else if (query.error) {
responseView = (
<ConversationBubble
ref={endMessageRef}
className={`${index === queries.length - 1 ? 'mb-32' : 'mb-7'} `}
key={`${index}ERROR`}
message={query.error}
type="ERROR"
></ConversationBubble>
);
}
return responseView;
};
const handleQuestionSubmission = () => {
if (inputRef.current?.textContent && status !== 'loading') {
if (input && status !== 'loading') {
if (lastQueryReturnedErr) {
// update last failed query with new prompt
dispatch(
updateQuery({
index: queries.length - 1,
query: {
prompt: inputRef.current.textContent,
prompt: input,
},
}),
);
@@ -152,9 +99,9 @@ export const SharedConversation = () => {
isRetry: true,
});
} else {
handleQuestion({ question: inputRef.current.textContent });
handleQuestion({ question: input });
}
inputRef.current.textContent = '';
setInput('');
}
};
@@ -167,7 +114,6 @@ export const SharedConversation = () => {
}) => {
question = question.trim();
if (question === '') return;
setEventInterrupt(false);
!isRetry && dispatch(addQuery({ prompt: question })); //dispatch only new queries
dispatch(fetchSharedAnswer({ question }));
};
@@ -192,93 +138,47 @@ export const SharedConversation = () => {
content="Shared conversations with DocsGPT"
/>
</Helmet>
<div className="flex h-full flex-col items-center justify-between gap-2 overflow-y-hidden dark:bg-raisin-black">
<div
ref={sharedConversationRef}
onWheel={handleUserInterruption}
onTouchMove={handleUserInterruption}
className="flex w-full justify-center overflow-auto"
>
<div className="mt-0 w-11/12 md:w-10/12 lg:w-6/12">
<div className="mb-2 w-full border-b pb-2 dark:border-b-silver">
<h1 className="font-semi-bold text-4xl text-chinese-black dark:text-chinese-silver">
{title}
</h1>
<h2 className="font-semi-bold text-base text-chinese-black dark:text-chinese-silver">
{t('sharedConv.subtitle')}{' '}
<a href="/" className="text-[#007DFF]">
DocsGPT
</a>
</h2>
<h2 className="font-semi-bold text-base text-chinese-black dark:text-chinese-silver">
{date}
</h2>
</div>
<div className="">
{queries?.map((query, index) => {
return (
<Fragment key={index}>
<ConversationBubble
ref={endMessageRef}
className={'mb-1 last:mb-28 md:mb-7'}
key={`${index}QUESTION`}
message={query.prompt}
type="QUESTION"
sources={query.sources}
></ConversationBubble>
{prepResponseView(query, index)}
</Fragment>
);
})}
</div>
</div>
<div className="flex h-full flex-col items-center justify-between gap-2 overflow-y-hidden dark:bg-raisin-black ">
<div className="border-b p-2 dark:border-b-silver w-full md:w-9/12 lg:w-8/12 xl:w-8/12 2xl:w-6/12 max-w-[1200px]">
<h1 className="font-semi-bold text-4xl text-chinese-black dark:text-chinese-silver">
{title}
</h1>
<h2 className="font-semi-bold text-base text-chinese-black dark:text-chinese-silver">
{t('sharedConv.subtitle')}{' '}
<a href="/" className="text-[#007DFF]">
DocsGPT
</a>
</h2>
<h2 className="font-semi-bold text-base text-chinese-black dark:text-chinese-silver">
{date}
</h2>
</div>
<div className="flex w-11/12 flex-col items-center gap-4 pb-2 md:w-10/12 lg:w-6/12">
<ConversationMessages
handleQuestion={handleQuestion}
handleQuestionSubmission={handleQuestionSubmission}
queries={queries}
status={status}
/>
<div className="flex flex-col items-center gap-4 pb-2 w-full md:w-9/12 lg:w-8/12 xl:w-8/12 2xl:w-6/12 max-w-[1200px]">
{apiKey ? (
<div className="flex h-full w-full items-center rounded-[40px] border border-silver bg-white py-1 dark:bg-raisin-black">
<div
id="inputbox"
ref={inputRef}
tabIndex={1}
onPaste={handlePaste}
placeholder={t('inputPlaceholder')}
contentEditable
className={`inputbox-style max-h-24 w-full overflow-y-auto overflow-x-hidden whitespace-pre-wrap rounded-full bg-white pt-5 pb-[22px] text-base leading-tight opacity-100 focus:outline-none dark:bg-raisin-black dark:text-bright-gray`}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleQuestionSubmission();
}
}}
></div>
{status === 'loading' ? (
<img
src={Spinner}
className="relative right-[38px] bottom-[24px] -mr-[30px] animate-spin cursor-pointer self-end bg-transparent filter dark:invert"
></img>
) : (
<div className="mx-1 cursor-pointer rounded-full p-3 text-center hover:bg-gray-3000 dark:hover:bg-dark-charcoal">
<img
onClick={handleQuestionSubmission}
className="ml-[4px] h-6 w-6 text-white filter dark:invert"
src={Send}
></img>
</div>
)}
</div>
<MessageInput
value={input}
onChange={(e) => setInput(e.target.value)}
onSubmit={() => handleQuestionSubmission()}
loading={status === 'loading'}
/>
) : (
<button
onClick={() => navigate('/')}
className="w-fit rounded-full bg-purple-30 p-4 text-white shadow-xl transition-colors duration-200 hover:bg-purple-taupe mb-14 sm:mb-0"
className="w-fit rounded-full bg-purple-30 py-3 px-5 text-white shadow-xl transition-colors duration-200 hover:bg-violets-are-blue mb-14 sm:mb-0"
>
{t('sharedConv.button')}
</button>
)}
<span className="mb-2 hidden text-xs text-dark-charcoal dark:text-silver sm:inline">
<p className="text-gray-4000 hidden w-[100vw] self-center bg-transparent py-2 text-center text-xs dark:text-sonic-silver md:inline md:w-full">
{t('sharedConv.meta')}
</span>
</p>
</div>
</div>
</>

View File

@@ -267,8 +267,7 @@ export const conversationSlice = createSlice({
return state;
}
state.status = 'failed';
state.queries[state.queries.length - 1].error =
'Something went wrong. Please check your internet connection.';
state.queries[state.queries.length - 1].error = 'Something went wrong';
});
},
});

View File

@@ -231,8 +231,7 @@ export const sharedConversationSlice = createSlice({
return state;
}
state.status = 'failed';
state.queries[state.queries.length - 1].error =
'Something went wrong. Please check your internet connection.';
state.queries[state.queries.length - 1].error = 'Something went wrong';
});
},
});