refactor: Consolidate Message Scrolling & other Logic to Custom Hooks 🔄 (#1257)

* refactor: remove unnecessary drilling/invoking of ScrollToBottom
- feat: useMessageScrolling: consolidates all scrolling logic to hook
- feat: useMessageHelpers: creates message utilities and consolidates logic from UI component

* fix: ensure automatic scrolling is triggered by messagesTree re-render and is throttled
This commit is contained in:
Danny Avila 2023-12-01 19:54:09 -05:00 committed by GitHub
parent ebd23f7295
commit 4674a54c70
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 208 additions and 169 deletions

View file

@ -0,0 +1,83 @@
import { useEffect } from 'react';
import copy from 'copy-to-clipboard';
import type { TMessage } from 'librechat-data-provider';
import type { TMessageProps } from '~/common';
import Icon from '~/components/Endpoints/Icon';
import { useChatContext } from '~/Providers';
export default function useMessageHelpers(props: TMessageProps) {
const { message, currentEditId, setCurrentEditId } = props;
const {
ask,
regenerate,
isSubmitting,
conversation,
latestMessage,
setAbortScroll,
handleContinue,
setLatestMessage,
} = useChatContext();
const { text, children, messageId = null, isCreatedByUser } = message ?? {};
const edit = messageId === currentEditId;
const isLast = !children?.length;
useEffect(() => {
if (!message) {
return;
} else if (isLast) {
setLatestMessage({ ...message });
}
}, [isLast, message, setLatestMessage]);
const enterEdit = (cancel?: boolean) =>
setCurrentEditId && setCurrentEditId(cancel ? -1 : messageId);
const handleScroll = () => {
if (isSubmitting) {
setAbortScroll(true);
} else {
setAbortScroll(false);
}
};
const icon = Icon({
...conversation,
...(message as TMessage),
model: message?.model ?? conversation?.model,
size: 28.8,
});
const regenerateMessage = () => {
if ((isSubmitting && isCreatedByUser) || !message) {
return;
}
regenerate(message);
};
const copyToClipboard = (setIsCopied: React.Dispatch<React.SetStateAction<boolean>>) => {
setIsCopied(true);
copy(text ?? '');
setTimeout(() => {
setIsCopied(false);
}, 3000);
};
return {
ask,
icon,
edit,
isLast,
enterEdit,
conversation,
isSubmitting,
handleScroll,
latestMessage,
handleContinue,
copyToClipboard,
regenerateMessage,
};
}