Fix rendering performances issues related to scrolling events (#174)

* memoize chat related components

* Avoid re-rendering ChatInput on every message udpate

* change the way the horizontal scrollbar is hidden

* make the scroll event listener passive

* perf(Chat): fix performances issues related to autoscroll

Uses the intersection API to determine autoscroll mode instead of listening for scroll events

* tuning detection of autoscroll
This commit is contained in:
Thomas LÉVEIL 2023-03-27 09:22:38 +02:00 committed by GitHub
parent c3f2dced56
commit 46e1857489
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 401 additions and 366 deletions

View File

@ -7,6 +7,7 @@ import {
} from '@/types'; } from '@/types';
import { import {
FC, FC,
memo,
MutableRefObject, MutableRefObject,
useCallback, useCallback,
useEffect, useEffect,
@ -21,6 +22,7 @@ import { ErrorMessageDiv } from './ErrorMessageDiv';
import { ModelSelect } from './ModelSelect'; import { ModelSelect } from './ModelSelect';
import { SystemPrompt } from './SystemPrompt'; import { SystemPrompt } from './SystemPrompt';
import { IconSettings } from '@tabler/icons-react'; import { IconSettings } from '@tabler/icons-react';
import { throttle } from '@/utils';
interface Props { interface Props {
conversation: Conversation; conversation: Conversation;
@ -40,197 +42,203 @@ interface Props {
stopConversationRef: MutableRefObject<boolean>; stopConversationRef: MutableRefObject<boolean>;
} }
export const Chat: FC<Props> = ({ export const Chat: FC<Props> = memo(
conversation, ({
models, conversation,
apiKey, models,
serverSideApiKeyIsSet, apiKey,
messageIsStreaming, serverSideApiKeyIsSet,
modelError, messageIsStreaming,
messageError, modelError,
loading, messageError,
onSend, loading,
onUpdateConversation, onSend,
onEditMessage, onUpdateConversation,
stopConversationRef, onEditMessage,
}) => { stopConversationRef,
const { t } = useTranslation('chat'); }) => {
const [currentMessage, setCurrentMessage] = useState<Message>(); const { t } = useTranslation('chat');
const [autoScrollEnabled, setAutoScrollEnabled] = useState(true); const [currentMessage, setCurrentMessage] = useState<Message>();
const [showSettings, setShowSettings] = useState<boolean>(false); const [autoScrollEnabled, setAutoScrollEnabled] = useState(true);
const [showSettings, setShowSettings] = useState<boolean>(false);
const messagesEndRef = useRef<HTMLDivElement>(null); const messagesEndRef = useRef<HTMLDivElement>(null);
const chatContainerRef = useRef<HTMLDivElement>(null); const chatContainerRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null); const textareaRef = useRef<HTMLTextAreaElement>(null);
const scrollToBottom = useCallback(() => { const handleSettings = () => {
if (autoScrollEnabled) { setShowSettings(!showSettings);
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); };
textareaRef.current?.focus();
}
}, [autoScrollEnabled]);
const handleScroll = () => { const scrollDown = () => {
if (chatContainerRef.current) { if (autoScrollEnabled) {
const { scrollTop, scrollHeight, clientHeight } = messagesEndRef.current?.scrollIntoView(true);
chatContainerRef.current;
const bottomTolerance = 5;
if (scrollTop + clientHeight < scrollHeight - bottomTolerance) {
setAutoScrollEnabled(false);
} else {
setAutoScrollEnabled(true);
} }
} };
}; const throttledScrollDown = throttle(scrollDown, 250);
const handleSettings = () => { useEffect(() => {
setShowSettings(!showSettings); throttledScrollDown();
}; setCurrentMessage(
conversation.messages[conversation.messages.length - 2],
useEffect(() => { );
scrollToBottom(); }, [conversation.messages, throttledScrollDown]);
setCurrentMessage(conversation.messages[conversation.messages.length - 2]);
}, [conversation.messages, scrollToBottom]);
useEffect(() => {
const chatContainer = chatContainerRef.current;
if (chatContainer) {
chatContainer.addEventListener('scroll', handleScroll);
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
setAutoScrollEnabled(entry.isIntersecting);
if (entry.isIntersecting) {
textareaRef.current?.focus();
}
},
{
root: null,
threshold: 0.5,
},
);
const messagesEndElement = messagesEndRef.current;
if (messagesEndElement) {
observer.observe(messagesEndElement);
}
return () => { return () => {
chatContainer.removeEventListener('scroll', handleScroll); if (messagesEndElement) {
observer.unobserve(messagesEndElement);
}
}; };
} }, [messagesEndRef]);
}, []);
return ( return (
<div className="overflow-none relative flex-1 bg-white dark:bg-[#343541]"> <div className="overflow-none relative flex-1 bg-white dark:bg-[#343541]">
{!(apiKey || serverSideApiKeyIsSet) ? ( {!(apiKey || serverSideApiKeyIsSet) ? (
<div className="mx-auto flex h-full w-[300px] flex-col justify-center space-y-6 sm:w-[500px]"> <div className="mx-auto flex h-full w-[300px] flex-col justify-center space-y-6 sm:w-[500px]">
<div className="text-center text-2xl font-semibold text-gray-800 dark:text-gray-100"> <div className="text-center text-2xl font-semibold text-gray-800 dark:text-gray-100">
{t('OpenAI API Key Required')} {t('OpenAI API Key Required')}
</div>
<div className="text-center text-gray-500 dark:text-gray-400">
{t(
'Please set your OpenAI API key in the bottom left of the sidebar.',
)}
</div>
<div className="text-center text-gray-500 dark:text-gray-400">
{t("If you don't have an OpenAI API key, you can get one here: ")}
<a
href="https://platform.openai.com/account/api-keys"
target="_blank"
rel="noreferrer"
className="text-blue-500 hover:underline"
>
openai.com
</a>
</div>
</div> </div>
<div className="text-center text-gray-500 dark:text-gray-400"> ) : modelError ? (
{t( <ErrorMessageDiv error={modelError} />
'Please set your OpenAI API key in the bottom left of the sidebar.', ) : (
)} <>
</div> <div
<div className="text-center text-gray-500 dark:text-gray-400"> className="max-h-full overflow-x-hidden"
{t("If you don't have an OpenAI API key, you can get one here: ")} ref={chatContainerRef}
<a
href="https://platform.openai.com/account/api-keys"
target="_blank"
rel="noreferrer"
className="text-blue-500 hover:underline"
> >
openai.com {conversation.messages.length === 0 ? (
</a> <>
</div> <div className="mx-auto flex w-[350px] flex-col space-y-10 pt-12 sm:w-[600px]">
</div> <div className="text-center text-3xl font-semibold text-gray-800 dark:text-gray-100">
) : modelError ? ( {models.length === 0 ? t('Loading...') : 'Chatbot UI'}
<ErrorMessageDiv error={modelError} /> </div>
) : (
<> {models.length > 0 && (
<div className="max-h-full overflow-scroll" ref={chatContainerRef}> <div className="flex h-full flex-col space-y-4 rounded border border-neutral-200 p-4 dark:border-neutral-600">
{conversation.messages.length === 0 ? ( <ModelSelect
<> model={conversation.model}
<div className="mx-auto flex w-[350px] flex-col space-y-10 pt-12 sm:w-[600px]"> models={models}
<div className="text-center text-3xl font-semibold text-gray-800 dark:text-gray-100"> onModelChange={(model) =>
{models.length === 0 ? t('Loading...') : 'Chatbot UI'} onUpdateConversation(conversation, {
key: 'model',
value: model,
})
}
/>
<SystemPrompt
conversation={conversation}
onChangePrompt={(prompt) =>
onUpdateConversation(conversation, {
key: 'prompt',
value: prompt,
})
}
/>
</div>
)}
</div> </div>
</>
{models.length > 0 && ( ) : (
<div className="flex h-full flex-col space-y-4 rounded border border-neutral-200 p-4 dark:border-neutral-600"> <>
<ModelSelect <div className="flex justify-center border border-b-neutral-300 bg-neutral-100 py-2 text-sm text-neutral-500 dark:border-none dark:bg-[#444654] dark:text-neutral-200">
model={conversation.model} {t('Model')}: {conversation.model.name}
models={models} <IconSettings
onModelChange={(model) => className="ml-2 cursor-pointer hover:opacity-50"
onUpdateConversation(conversation, { onClick={handleSettings}
key: 'model', size={18}
value: model, />
}) </div>
} {showSettings && (
/> <div className="mx-auto flex w-[200px] flex-col space-y-10 pt-8 sm:w-[300px]">
<div className="flex h-full flex-col space-y-4 rounded border border-neutral-500 p-2">
<SystemPrompt <ModelSelect
conversation={conversation} model={conversation.model}
onChangePrompt={(prompt) => models={models}
onUpdateConversation(conversation, { onModelChange={(model) =>
key: 'prompt', onUpdateConversation(conversation, {
value: prompt, key: 'model',
}) value: model,
} })
/> }
/>
</div>
</div> </div>
)} )}
</div>
</> {conversation.messages.map((message, index) => (
) : ( <ChatMessage
<> key={index}
<div className="flex justify-center border border-b-neutral-300 bg-neutral-100 py-2 text-sm text-neutral-500 dark:border-none dark:bg-[#444654] dark:text-neutral-200"> message={message}
{t('Model')}: {conversation.model.name} messageIndex={index}
<IconSettings onEditMessage={onEditMessage}
className="ml-2 cursor-pointer hover:opacity-50" />
onClick={handleSettings} ))}
size={18}
{loading && <ChatLoader />}
<div
className="h-[162px] bg-white dark:bg-[#343541]"
ref={messagesEndRef}
/> />
</div> </>
{showSettings && ( )}
<div className="mx-auto flex w-[200px] flex-col space-y-10 pt-8 sm:w-[300px]"> </div>
<div className="flex h-full flex-col space-y-4 rounded border border-neutral-500 p-2">
<ModelSelect
model={conversation.model}
models={models}
onModelChange={(model) =>
onUpdateConversation(conversation, {
key: 'model',
value: model,
})
}
/>
</div>
</div>
)}
{conversation.messages.map((message, index) => ( <ChatInput
<ChatMessage stopConversationRef={stopConversationRef}
key={index} textareaRef={textareaRef}
message={message} messageIsStreaming={messageIsStreaming}
messageIndex={index} conversationIsEmpty={conversation.messages.length > 0}
onEditMessage={onEditMessage} model={conversation.model}
/> onSend={(message) => {
))} setCurrentMessage(message);
onSend(message);
{loading && <ChatLoader />} }}
onRegenerate={() => {
<div if (currentMessage) {
className="h-[162px] bg-white dark:bg-[#343541]" onSend(currentMessage, 2);
ref={messagesEndRef} }
/> }}
</> />
)} </>
</div> )}
</div>
<ChatInput );
stopConversationRef={stopConversationRef} },
textareaRef={textareaRef} );
messageIsStreaming={messageIsStreaming} Chat.displayName = 'Chat';
messages={conversation.messages}
model={conversation.model}
onSend={(message) => {
setCurrentMessage(message);
onSend(message);
}}
onRegenerate={() => {
if (currentMessage) {
onSend(currentMessage, 2);
}
}}
/>
</>
)}
</div>
);
};

View File

@ -12,7 +12,7 @@ import { useTranslation } from 'next-i18next';
interface Props { interface Props {
messageIsStreaming: boolean; messageIsStreaming: boolean;
model: OpenAIModel; model: OpenAIModel;
messages: Message[]; conversationIsEmpty: boolean;
onSend: (message: Message) => void; onSend: (message: Message) => void;
onRegenerate: () => void; onRegenerate: () => void;
stopConversationRef: MutableRefObject<boolean>; stopConversationRef: MutableRefObject<boolean>;
@ -22,7 +22,7 @@ interface Props {
export const ChatInput: FC<Props> = ({ export const ChatInput: FC<Props> = ({
messageIsStreaming, messageIsStreaming,
model, model,
messages, conversationIsEmpty,
onSend, onSend,
onRegenerate, onRegenerate,
stopConversationRef, stopConversationRef,
@ -102,11 +102,11 @@ export const ChatInput: FC<Props> = ({
} }
return ( return (
<div className="absolute bottom-0 left-0 w-full border-transparent pt-6 dark:border-white/20 bg-gradient-to-b from-transparent via-white to-white dark:via-[#343541] dark:to-[#343541] md:pt-2"> <div className="absolute bottom-0 left-0 w-full border-transparent bg-gradient-to-b from-transparent via-white to-white pt-6 dark:border-white/20 dark:via-[#343541] dark:to-[#343541] md:pt-2">
<div className="stretch mx-2 mt-4 flex flex-row gap-3 last:mb-2 md:mx-4 md:mt-[52px] md:last:mb-6 lg:mx-auto lg:max-w-3xl"> <div className="stretch mx-2 mt-4 flex flex-row gap-3 last:mb-2 md:mx-4 md:mt-[52px] md:last:mb-6 lg:mx-auto lg:max-w-3xl">
{messageIsStreaming && ( {messageIsStreaming && (
<button <button
className="absolute -top-2 left-0 right-0 mx-auto w-fit rounded border border-neutral-200 dark:border-neutral-600 py-2 px-4 text-black bg-white dark:bg-[#343541] dark:text-white md:top-0" className="absolute -top-2 left-0 right-0 mx-auto w-fit rounded border border-neutral-200 bg-white py-2 px-4 text-black dark:border-neutral-600 dark:bg-[#343541] dark:text-white md:top-0"
onClick={handleStopConversation} onClick={handleStopConversation}
> >
<IconPlayerStop size={16} className="mb-[2px] inline-block" />{' '} <IconPlayerStop size={16} className="mb-[2px] inline-block" />{' '}
@ -114,9 +114,9 @@ export const ChatInput: FC<Props> = ({
</button> </button>
)} )}
{!messageIsStreaming && messages.length > 0 && ( {!messageIsStreaming && !conversationIsEmpty && (
<button <button
className="absolute -top-2 left-0 right-0 mx-auto w-fit rounded border border-neutral-200 dark:border-neutral-600 py-2 px-4 text-black bg-white dark:bg-[#343541] dark:text-white md:top-0" className="absolute -top-2 left-0 right-0 mx-auto w-fit rounded border border-neutral-200 bg-white py-2 px-4 text-black dark:border-neutral-600 dark:bg-[#343541] dark:text-white md:top-0"
onClick={onRegenerate} onClick={onRegenerate}
> >
<IconRepeat size={16} className="mb-[2px] inline-block" />{' '} <IconRepeat size={16} className="mb-[2px] inline-block" />{' '}

View File

@ -1,12 +1,12 @@
import { Message } from '@/types'; import { Message } from '@/types';
import { IconEdit } from '@tabler/icons-react'; import { IconEdit } from '@tabler/icons-react';
import { useTranslation } from 'next-i18next'; import { useTranslation } from 'next-i18next';
import { FC, useEffect, useRef, useState } from 'react'; import { FC, useEffect, useRef, useState, memo } from 'react';
import ReactMarkdown from 'react-markdown';
import rehypeMathjax from 'rehype-mathjax'; import rehypeMathjax from 'rehype-mathjax';
import remarkGfm from 'remark-gfm'; import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math'; import remarkMath from 'remark-math';
import { CodeBlock } from '../Markdown/CodeBlock'; import { CodeBlock } from '../Markdown/CodeBlock';
import { MemoizedReactMarkdown } from '../Markdown/MemoizedReactMarkdown';
import { CopyButton } from './CopyButton'; import { CopyButton } from './CopyButton';
interface Props { interface Props {
@ -15,198 +15,201 @@ interface Props {
onEditMessage: (message: Message, messageIndex: number) => void; onEditMessage: (message: Message, messageIndex: number) => void;
} }
export const ChatMessage: FC<Props> = ({ export const ChatMessage: FC<Props> = memo(
message, ({ message, messageIndex, onEditMessage }) => {
messageIndex, const { t } = useTranslation('chat');
onEditMessage, const [isEditing, setIsEditing] = useState<boolean>(false);
}) => { const [isHovering, setIsHovering] = useState<boolean>(false);
const { t } = useTranslation('chat'); const [messageContent, setMessageContent] = useState(message.content);
const [isEditing, setIsEditing] = useState<boolean>(false); const [messagedCopied, setMessageCopied] = useState(false);
const [isHovering, setIsHovering] = useState<boolean>(false);
const [messageContent, setMessageContent] = useState(message.content);
const [messagedCopied, setMessageCopied] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null); const textareaRef = useRef<HTMLTextAreaElement>(null);
const toggleEditing = () => { const toggleEditing = () => {
setIsEditing(!isEditing); setIsEditing(!isEditing);
}; };
const handleInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => { const handleInputChange = (
setMessageContent(event.target.value); event: React.ChangeEvent<HTMLTextAreaElement>,
if (textareaRef.current) { ) => {
textareaRef.current.style.height = 'inherit'; setMessageContent(event.target.value);
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`; if (textareaRef.current) {
} textareaRef.current.style.height = 'inherit';
}; textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
}
};
const handleEditMessage = () => { const handleEditMessage = () => {
if (message.content != messageContent) { if (message.content != messageContent) {
onEditMessage({ ...message, content: messageContent }, messageIndex); onEditMessage({ ...message, content: messageContent }, messageIndex);
} }
setIsEditing(false); setIsEditing(false);
}; };
const handlePressEnter = (e: React.KeyboardEvent<HTMLTextAreaElement>) => { const handlePressEnter = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) { if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault(); e.preventDefault();
handleEditMessage(); handleEditMessage();
} }
}; };
const copyOnClick = () => { const copyOnClick = () => {
if (!navigator.clipboard) return; if (!navigator.clipboard) return;
navigator.clipboard.writeText(message.content).then(() => { navigator.clipboard.writeText(message.content).then(() => {
setMessageCopied(true); setMessageCopied(true);
setTimeout(() => { setTimeout(() => {
setMessageCopied(false); setMessageCopied(false);
}, 2000); }, 2000);
}); });
}; };
useEffect(() => { useEffect(() => {
if (textareaRef.current) { if (textareaRef.current) {
textareaRef.current.style.height = 'inherit'; textareaRef.current.style.height = 'inherit';
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`; textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
} }
}, [isEditing]); }, [isEditing]);
return ( return (
<div <div
className={`group ${message.role === 'assistant' className={`group ${
? 'border-b border-black/10 bg-gray-50 text-gray-800 dark:border-gray-900/50 dark:bg-[#444654] dark:text-gray-100' message.role === 'assistant'
: 'border-b border-black/10 bg-white text-gray-800 dark:border-gray-900/50 dark:bg-[#343541] dark:text-gray-100' ? 'border-b border-black/10 bg-gray-50 text-gray-800 dark:border-gray-900/50 dark:bg-[#444654] dark:text-gray-100'
: 'border-b border-black/10 bg-white text-gray-800 dark:border-gray-900/50 dark:bg-[#343541] dark:text-gray-100'
}`} }`}
style={{ overflowWrap: 'anywhere' }} style={{ overflowWrap: 'anywhere' }}
onMouseEnter={() => setIsHovering(true)} onMouseEnter={() => setIsHovering(true)}
onMouseLeave={() => setIsHovering(false)} onMouseLeave={() => setIsHovering(false)}
> >
<div className="relative m-auto flex gap-4 p-4 text-base md:max-w-2xl md:gap-6 md:py-6 lg:max-w-2xl lg:px-0 xl:max-w-3xl"> <div className="relative m-auto flex gap-4 p-4 text-base md:max-w-2xl md:gap-6 md:py-6 lg:max-w-2xl lg:px-0 xl:max-w-3xl">
<div className="min-w-[40px] font-bold"> <div className="min-w-[40px] font-bold">
{message.role === 'assistant' ? t('AI') : t('You')}: {message.role === 'assistant' ? t('AI') : t('You')}:
</div> </div>
<div className="prose mt-[-2px] w-full dark:prose-invert"> <div className="prose mt-[-2px] w-full dark:prose-invert">
{message.role === 'user' ? ( {message.role === 'user' ? (
<div className="flex w-full"> <div className="flex w-full">
{isEditing ? ( {isEditing ? (
<div className="flex w-full flex-col"> <div className="flex w-full flex-col">
<textarea <textarea
ref={textareaRef} ref={textareaRef}
className="w-full resize-none whitespace-pre-wrap border-none outline-none dark:bg-[#343541]" className="w-full resize-none whitespace-pre-wrap border-none outline-none dark:bg-[#343541]"
value={messageContent} value={messageContent}
onChange={handleInputChange} onChange={handleInputChange}
onKeyDown={handlePressEnter} onKeyDown={handlePressEnter}
style={{ style={{
fontFamily: 'inherit', fontFamily: 'inherit',
fontSize: 'inherit', fontSize: 'inherit',
lineHeight: 'inherit', lineHeight: 'inherit',
padding: '0', padding: '0',
margin: '0', margin: '0',
overflow: 'hidden', overflow: 'hidden',
}}
/>
<div className="mt-10 flex justify-center space-x-4">
<button
className="h-[40px] rounded-md bg-blue-500 px-4 py-1 text-sm font-medium text-white enabled:hover:bg-blue-600 disabled:opacity-50"
onClick={handleEditMessage}
disabled={messageContent.trim().length <= 0}
>
{t('Save & Submit')}
</button>
<button
className="h-[40px] rounded-md border border-neutral-300 px-4 py-1 text-sm font-medium text-neutral-700 hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-800"
onClick={() => {
setMessageContent(message.content);
setIsEditing(false);
}} }}
> />
{t('Cancel')}
</button> <div className="mt-10 flex justify-center space-x-4">
<button
className="h-[40px] rounded-md bg-blue-500 px-4 py-1 text-sm font-medium text-white enabled:hover:bg-blue-600 disabled:opacity-50"
onClick={handleEditMessage}
disabled={messageContent.trim().length <= 0}
>
{t('Save & Submit')}
</button>
<button
className="h-[40px] rounded-md border border-neutral-300 px-4 py-1 text-sm font-medium text-neutral-700 hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-800"
onClick={() => {
setMessageContent(message.content);
setIsEditing(false);
}}
>
{t('Cancel')}
</button>
</div>
</div> </div>
</div> ) : (
) : ( <div className="prose whitespace-pre-wrap dark:prose-invert">
<div className="prose whitespace-pre-wrap dark:prose-invert"> {message.content}
{message.content} </div>
</div> )}
)}
{(isHovering || window.innerWidth < 640) && !isEditing && ( {(isHovering || window.innerWidth < 640) && !isEditing && (
<button <button
className={`absolute ${window.innerWidth < 640 className={`absolute ${
? 'right-3 bottom-1' window.innerWidth < 640
: 'right-[-20px] top-[26px]' ? 'right-3 bottom-1'
: 'right-[-20px] top-[26px]'
}`} }`}
>
<IconEdit
size={20}
className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
onClick={toggleEditing}
/>
</button>
)}
</div>
) : (
<>
<MemoizedReactMarkdown
className="prose dark:prose-invert"
remarkPlugins={[remarkGfm, remarkMath]}
rehypePlugins={[rehypeMathjax]}
components={{
code({ node, inline, className, children, ...props }) {
const match = /language-(\w+)/.exec(className || '');
return !inline && match ? (
<CodeBlock
key={Math.random()}
language={match[1]}
value={String(children).replace(/\n$/, '')}
{...props}
/>
) : (
<code className={className} {...props}>
{children}
</code>
);
},
table({ children }) {
return (
<table className="border-collapse border border-black py-1 px-3 dark:border-white">
{children}
</table>
);
},
th({ children }) {
return (
<th className="break-words border border-black bg-gray-500 py-1 px-3 text-white dark:border-white">
{children}
</th>
);
},
td({ children }) {
return (
<td className="break-words border border-black py-1 px-3 dark:border-white">
{children}
</td>
);
},
}}
> >
<IconEdit {message.content}
size={20} </MemoizedReactMarkdown>
className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
onClick={toggleEditing} {(isHovering || window.innerWidth < 640) && (
<CopyButton
messagedCopied={messagedCopied}
copyOnClick={copyOnClick}
/> />
</button> )}
)} </>
</div> )}
) : ( </div>
<>
<ReactMarkdown
className="prose dark:prose-invert"
remarkPlugins={[remarkGfm, remarkMath]}
rehypePlugins={[rehypeMathjax]}
components={{
code({ node, inline, className, children, ...props }) {
const match = /language-(\w+)/.exec(className || '');
return !inline && match ? (
<CodeBlock
key={Math.random()}
language={match[1]}
value={String(children).replace(/\n$/, '')}
{...props}
/>
) : (
<code className={className} {...props}>
{children}
</code>
);
},
table({ children }) {
return (
<table className="border-collapse border border-black py-1 px-3 dark:border-white">
{children}
</table>
);
},
th({ children }) {
return (
<th className="break-words border border-black bg-gray-500 py-1 px-3 text-white dark:border-white">
{children}
</th>
);
},
td({ children }) {
return (
<td className="break-words border border-black py-1 px-3 dark:border-white">
{children}
</td>
);
},
}}
>
{message.content}
</ReactMarkdown>
{(isHovering || window.innerWidth < 640) && (
<CopyButton
messagedCopied={messagedCopied}
copyOnClick={copyOnClick}
/>
)}
</>
)}
</div> </div>
</div> </div>
</div> );
); },
}; );
ChatMessage.displayName = 'ChatMessage';

View File

@ -3,7 +3,7 @@ import {
programmingLanguages, programmingLanguages,
} from '@/utils/app/codeblock'; } from '@/utils/app/codeblock';
import { IconCheck, IconClipboard, IconDownload } from '@tabler/icons-react'; import { IconCheck, IconClipboard, IconDownload } from '@tabler/icons-react';
import { FC, useState } from 'react'; import { FC, useState, memo } from 'react';
import { useTranslation } from 'next-i18next'; import { useTranslation } from 'next-i18next';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'; import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneDark } from 'react-syntax-highlighter/dist/cjs/styles/prism'; import { oneDark } from 'react-syntax-highlighter/dist/cjs/styles/prism';
@ -13,7 +13,7 @@ interface Props {
value: string; value: string;
} }
export const CodeBlock: FC<Props> = ({ language, value }) => { export const CodeBlock: FC<Props> = memo(({ language, value }) => {
const { t } = useTranslation('markdown'); const { t } = useTranslation('markdown');
const [isCopied, setIsCopied] = useState<Boolean>(false); const [isCopied, setIsCopied] = useState<Boolean>(false);
@ -92,4 +92,5 @@ export const CodeBlock: FC<Props> = ({ language, value }) => {
</SyntaxHighlighter> </SyntaxHighlighter>
</div> </div>
); );
}; });
CodeBlock.displayName = 'CodeBlock';

View File

@ -0,0 +1,4 @@
import { FC, memo } from 'react';
import ReactMarkdown, { Options } from 'react-markdown';
export const MemoizedReactMarkdown: FC<Options> = memo(ReactMarkdown);

19
utils/index.ts Normal file
View File

@ -0,0 +1,19 @@
export function throttle<T extends (...args: any[]) => any>(func: T, limit: number): T {
let lastFunc: ReturnType<typeof setTimeout>;
let lastRan: number;
return ((...args) => {
if (!lastRan) {
func(...args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
if (Date.now() - lastRan >= limit) {
func(...args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
}) as T;
}