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';
import {
FC,
memo,
MutableRefObject,
useCallback,
useEffect,
@ -21,6 +22,7 @@ import { ErrorMessageDiv } from './ErrorMessageDiv';
import { ModelSelect } from './ModelSelect';
import { SystemPrompt } from './SystemPrompt';
import { IconSettings } from '@tabler/icons-react';
import { throttle } from '@/utils';
interface Props {
conversation: Conversation;
@ -40,197 +42,203 @@ interface Props {
stopConversationRef: MutableRefObject<boolean>;
}
export const Chat: FC<Props> = ({
conversation,
models,
apiKey,
serverSideApiKeyIsSet,
messageIsStreaming,
modelError,
messageError,
loading,
onSend,
onUpdateConversation,
onEditMessage,
stopConversationRef,
}) => {
const { t } = useTranslation('chat');
const [currentMessage, setCurrentMessage] = useState<Message>();
const [autoScrollEnabled, setAutoScrollEnabled] = useState(true);
const [showSettings, setShowSettings] = useState<boolean>(false);
export const Chat: FC<Props> = memo(
({
conversation,
models,
apiKey,
serverSideApiKeyIsSet,
messageIsStreaming,
modelError,
messageError,
loading,
onSend,
onUpdateConversation,
onEditMessage,
stopConversationRef,
}) => {
const { t } = useTranslation('chat');
const [currentMessage, setCurrentMessage] = useState<Message>();
const [autoScrollEnabled, setAutoScrollEnabled] = useState(true);
const [showSettings, setShowSettings] = useState<boolean>(false);
const messagesEndRef = useRef<HTMLDivElement>(null);
const chatContainerRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const chatContainerRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const scrollToBottom = useCallback(() => {
if (autoScrollEnabled) {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
textareaRef.current?.focus();
}
}, [autoScrollEnabled]);
const handleSettings = () => {
setShowSettings(!showSettings);
};
const handleScroll = () => {
if (chatContainerRef.current) {
const { scrollTop, scrollHeight, clientHeight } =
chatContainerRef.current;
const bottomTolerance = 5;
if (scrollTop + clientHeight < scrollHeight - bottomTolerance) {
setAutoScrollEnabled(false);
} else {
setAutoScrollEnabled(true);
const scrollDown = () => {
if (autoScrollEnabled) {
messagesEndRef.current?.scrollIntoView(true);
}
}
};
};
const throttledScrollDown = throttle(scrollDown, 250);
const handleSettings = () => {
setShowSettings(!showSettings);
};
useEffect(() => {
scrollToBottom();
setCurrentMessage(conversation.messages[conversation.messages.length - 2]);
}, [conversation.messages, scrollToBottom]);
useEffect(() => {
const chatContainer = chatContainerRef.current;
if (chatContainer) {
chatContainer.addEventListener('scroll', handleScroll);
useEffect(() => {
throttledScrollDown();
setCurrentMessage(
conversation.messages[conversation.messages.length - 2],
);
}, [conversation.messages, throttledScrollDown]);
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 () => {
chatContainer.removeEventListener('scroll', handleScroll);
if (messagesEndElement) {
observer.unobserve(messagesEndElement);
}
};
}
}, []);
}, [messagesEndRef]);
return (
<div className="overflow-none relative flex-1 bg-white dark:bg-[#343541]">
{!(apiKey || serverSideApiKeyIsSet) ? (
<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">
{t('OpenAI API Key Required')}
return (
<div className="overflow-none relative flex-1 bg-white dark:bg-[#343541]">
{!(apiKey || serverSideApiKeyIsSet) ? (
<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">
{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 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"
) : modelError ? (
<ErrorMessageDiv error={modelError} />
) : (
<>
<div
className="max-h-full overflow-x-hidden"
ref={chatContainerRef}
>
openai.com
</a>
</div>
</div>
) : modelError ? (
<ErrorMessageDiv error={modelError} />
) : (
<>
<div className="max-h-full overflow-scroll" ref={chatContainerRef}>
{conversation.messages.length === 0 ? (
<>
<div className="mx-auto flex w-[350px] flex-col space-y-10 pt-12 sm:w-[600px]">
<div className="text-center text-3xl font-semibold text-gray-800 dark:text-gray-100">
{models.length === 0 ? t('Loading...') : 'Chatbot UI'}
{conversation.messages.length === 0 ? (
<>
<div className="mx-auto flex w-[350px] flex-col space-y-10 pt-12 sm:w-[600px]">
<div className="text-center text-3xl font-semibold text-gray-800 dark:text-gray-100">
{models.length === 0 ? t('Loading...') : 'Chatbot UI'}
</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
model={conversation.model}
models={models}
onModelChange={(model) =>
onUpdateConversation(conversation, {
key: 'model',
value: model,
})
}
/>
<SystemPrompt
conversation={conversation}
onChangePrompt={(prompt) =>
onUpdateConversation(conversation, {
key: 'prompt',
value: prompt,
})
}
/>
</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
model={conversation.model}
models={models}
onModelChange={(model) =>
onUpdateConversation(conversation, {
key: 'model',
value: model,
})
}
/>
<SystemPrompt
conversation={conversation}
onChangePrompt={(prompt) =>
onUpdateConversation(conversation, {
key: 'prompt',
value: prompt,
})
}
/>
</>
) : (
<>
<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">
{t('Model')}: {conversation.model.name}
<IconSettings
className="ml-2 cursor-pointer hover:opacity-50"
onClick={handleSettings}
size={18}
/>
</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">
<ModelSelect
model={conversation.model}
models={models}
onModelChange={(model) =>
onUpdateConversation(conversation, {
key: 'model',
value: model,
})
}
/>
</div>
</div>
)}
</div>
</>
) : (
<>
<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">
{t('Model')}: {conversation.model.name}
<IconSettings
className="ml-2 cursor-pointer hover:opacity-50"
onClick={handleSettings}
size={18}
{conversation.messages.map((message, index) => (
<ChatMessage
key={index}
message={message}
messageIndex={index}
onEditMessage={onEditMessage}
/>
))}
{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 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>
)}
</>
)}
</div>
{conversation.messages.map((message, index) => (
<ChatMessage
key={index}
message={message}
messageIndex={index}
onEditMessage={onEditMessage}
/>
))}
{loading && <ChatLoader />}
<div
className="h-[162px] bg-white dark:bg-[#343541]"
ref={messagesEndRef}
/>
</>
)}
</div>
<ChatInput
stopConversationRef={stopConversationRef}
textareaRef={textareaRef}
messageIsStreaming={messageIsStreaming}
messages={conversation.messages}
model={conversation.model}
onSend={(message) => {
setCurrentMessage(message);
onSend(message);
}}
onRegenerate={() => {
if (currentMessage) {
onSend(currentMessage, 2);
}
}}
/>
</>
)}
</div>
);
};
<ChatInput
stopConversationRef={stopConversationRef}
textareaRef={textareaRef}
messageIsStreaming={messageIsStreaming}
conversationIsEmpty={conversation.messages.length > 0}
model={conversation.model}
onSend={(message) => {
setCurrentMessage(message);
onSend(message);
}}
onRegenerate={() => {
if (currentMessage) {
onSend(currentMessage, 2);
}
}}
/>
</>
)}
</div>
);
},
);
Chat.displayName = 'Chat';

View File

@ -12,7 +12,7 @@ import { useTranslation } from 'next-i18next';
interface Props {
messageIsStreaming: boolean;
model: OpenAIModel;
messages: Message[];
conversationIsEmpty: boolean;
onSend: (message: Message) => void;
onRegenerate: () => void;
stopConversationRef: MutableRefObject<boolean>;
@ -22,7 +22,7 @@ interface Props {
export const ChatInput: FC<Props> = ({
messageIsStreaming,
model,
messages,
conversationIsEmpty,
onSend,
onRegenerate,
stopConversationRef,
@ -102,11 +102,11 @@ export const ChatInput: FC<Props> = ({
}
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">
{messageIsStreaming && (
<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}
>
<IconPlayerStop size={16} className="mb-[2px] inline-block" />{' '}
@ -114,9 +114,9 @@ export const ChatInput: FC<Props> = ({
</button>
)}
{!messageIsStreaming && messages.length > 0 && (
{!messageIsStreaming && !conversationIsEmpty && (
<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}
>
<IconRepeat size={16} className="mb-[2px] inline-block" />{' '}

View File

@ -1,12 +1,12 @@
import { Message } from '@/types';
import { IconEdit } from '@tabler/icons-react';
import { useTranslation } from 'next-i18next';
import { FC, useEffect, useRef, useState } from 'react';
import ReactMarkdown from 'react-markdown';
import { FC, useEffect, useRef, useState, memo } from 'react';
import rehypeMathjax from 'rehype-mathjax';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import { CodeBlock } from '../Markdown/CodeBlock';
import { MemoizedReactMarkdown } from '../Markdown/MemoizedReactMarkdown';
import { CopyButton } from './CopyButton';
interface Props {
@ -15,198 +15,201 @@ interface Props {
onEditMessage: (message: Message, messageIndex: number) => void;
}
export const ChatMessage: FC<Props> = ({
message,
messageIndex,
onEditMessage,
}) => {
const { t } = useTranslation('chat');
const [isEditing, setIsEditing] = useState<boolean>(false);
const [isHovering, setIsHovering] = useState<boolean>(false);
const [messageContent, setMessageContent] = useState(message.content);
const [messagedCopied, setMessageCopied] = useState(false);
export const ChatMessage: FC<Props> = memo(
({ message, messageIndex, onEditMessage }) => {
const { t } = useTranslation('chat');
const [isEditing, setIsEditing] = useState<boolean>(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 = () => {
setIsEditing(!isEditing);
};
const toggleEditing = () => {
setIsEditing(!isEditing);
};
const handleInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
setMessageContent(event.target.value);
if (textareaRef.current) {
textareaRef.current.style.height = 'inherit';
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
}
};
const handleInputChange = (
event: React.ChangeEvent<HTMLTextAreaElement>,
) => {
setMessageContent(event.target.value);
if (textareaRef.current) {
textareaRef.current.style.height = 'inherit';
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
}
};
const handleEditMessage = () => {
if (message.content != messageContent) {
onEditMessage({ ...message, content: messageContent }, messageIndex);
}
setIsEditing(false);
};
const handleEditMessage = () => {
if (message.content != messageContent) {
onEditMessage({ ...message, content: messageContent }, messageIndex);
}
setIsEditing(false);
};
const handlePressEnter = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleEditMessage();
}
};
const handlePressEnter = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleEditMessage();
}
};
const copyOnClick = () => {
if (!navigator.clipboard) return;
const copyOnClick = () => {
if (!navigator.clipboard) return;
navigator.clipboard.writeText(message.content).then(() => {
setMessageCopied(true);
setTimeout(() => {
setMessageCopied(false);
}, 2000);
});
};
navigator.clipboard.writeText(message.content).then(() => {
setMessageCopied(true);
setTimeout(() => {
setMessageCopied(false);
}, 2000);
});
};
useEffect(() => {
if (textareaRef.current) {
textareaRef.current.style.height = 'inherit';
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
}
}, [isEditing]);
useEffect(() => {
if (textareaRef.current) {
textareaRef.current.style.height = 'inherit';
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
}
}, [isEditing]);
return (
<div
className={`group ${message.role === 'assistant'
? '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'
return (
<div
className={`group ${
message.role === 'assistant'
? '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' }}
onMouseEnter={() => setIsHovering(true)}
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="min-w-[40px] font-bold">
{message.role === 'assistant' ? t('AI') : t('You')}:
</div>
style={{ overflowWrap: 'anywhere' }}
onMouseEnter={() => setIsHovering(true)}
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="min-w-[40px] font-bold">
{message.role === 'assistant' ? t('AI') : t('You')}:
</div>
<div className="prose mt-[-2px] w-full dark:prose-invert">
{message.role === 'user' ? (
<div className="flex w-full">
{isEditing ? (
<div className="flex w-full flex-col">
<textarea
ref={textareaRef}
className="w-full resize-none whitespace-pre-wrap border-none outline-none dark:bg-[#343541]"
value={messageContent}
onChange={handleInputChange}
onKeyDown={handlePressEnter}
style={{
fontFamily: 'inherit',
fontSize: 'inherit',
lineHeight: 'inherit',
padding: '0',
margin: '0',
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);
<div className="prose mt-[-2px] w-full dark:prose-invert">
{message.role === 'user' ? (
<div className="flex w-full">
{isEditing ? (
<div className="flex w-full flex-col">
<textarea
ref={textareaRef}
className="w-full resize-none whitespace-pre-wrap border-none outline-none dark:bg-[#343541]"
value={messageContent}
onChange={handleInputChange}
onKeyDown={handlePressEnter}
style={{
fontFamily: 'inherit',
fontSize: 'inherit',
lineHeight: 'inherit',
padding: '0',
margin: '0',
overflow: 'hidden',
}}
>
{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 className="prose whitespace-pre-wrap dark:prose-invert">
{message.content}
</div>
)}
) : (
<div className="prose whitespace-pre-wrap dark:prose-invert">
{message.content}
</div>
)}
{(isHovering || window.innerWidth < 640) && !isEditing && (
<button
className={`absolute ${window.innerWidth < 640
? 'right-3 bottom-1'
: 'right-[-20px] top-[26px]'
{(isHovering || window.innerWidth < 640) && !isEditing && (
<button
className={`absolute ${
window.innerWidth < 640
? '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>
) : (
<>
<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>
>
<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 || '');
{(isHovering || window.innerWidth < 640) && (
<CopyButton
messagedCopied={messagedCopied}
copyOnClick={copyOnClick}
/>
)}
</>
)}
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}
</MemoizedReactMarkdown>
{(isHovering || window.innerWidth < 640) && (
<CopyButton
messagedCopied={messagedCopied}
copyOnClick={copyOnClick}
/>
)}
</>
)}
</div>
</div>
</div>
</div>
);
};
);
},
);
ChatMessage.displayName = 'ChatMessage';

View File

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