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

Adds functionality to scroll to bottom of messages container on submi… #250

Merged
Merged
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
25 changes: 19 additions & 6 deletions apps/www/src/components/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ const ChatMessage: React.FC<{
};

export const Chat = () => {
const messagesDivRef = React.useRef<HTMLInputElement>(null);
const storage = !IS_SERVER ? window.localStorage : null;
const [currentApiKey, setCurrentApiKey] = React.useState<string>(
storage?.getItem(CHAT_OPENAI_API_KEY) ?? "",
Expand All @@ -75,6 +76,12 @@ export const Chat = () => {
},
});

const scrollToBottom = () => {
if (messagesDivRef.current) {
messagesDivRef.current.scrollTop = messagesDivRef.current.scrollHeight;
}
};

const handleUpdateApiKey = (e: React.ChangeEvent<HTMLInputElement>) => {
const newApiKey = e.target.value;
setCurrentApiKey(newApiKey);
Expand All @@ -84,6 +91,12 @@ export const Chat = () => {
setSelectedChatGptModel(value);
};

const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
storage?.setItem(CHAT_OPENAI_API_KEY, currentApiKey);
scrollToBottom();
handleSubmit(e);
};

const messagesWithoutSystem = messages.slice(1);
const reversedMessagesWithoutSystem = R.reverse(messagesWithoutSystem);
return (
Expand Down Expand Up @@ -114,14 +127,14 @@ export const Chat = () => {
</div>
<form
autoComplete="off"
onSubmit={(e) => {
storage?.setItem(CHAT_OPENAI_API_KEY, currentApiKey);
handleSubmit(e);
}}
onSubmit={onSubmit}
className="flex flex-col flex-1"
>
{/* Col-reverse is used to enable automatic scrolling as content populates the div */}
<div className="flex flex-1 flex-col-reverse overflow-y-auto pt-4 pb-3">
<div
ref={messagesDivRef}
className="flex flex-1 flex-col-reverse overflow-y-auto pt-4 pb-3"
>
{/* This div takes up all the remaining space so the messages start at the top */}
<div className="flex flex-1" />
{reversedMessagesWithoutSystem.map((message, index) => {
Expand Down Expand Up @@ -173,7 +186,7 @@ export const Chat = () => {
}
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSubmit(e as unknown as React.FormEvent<HTMLFormElement>);
onSubmit(e as unknown as React.FormEvent<HTMLFormElement>);
}
}}
placeholder="Message ChatGPT"
Expand Down
Loading