Skip to content

An AI-powered search engine with a generative UI

Fix auto-scroll behavior and scroll button flickering

Yoshiki Miurada9b08277073
diff --git a/components/chat-messages.tsx b/components/chat-messages.tsx
index 247ae805..870f44c1 100644
--- a/components/chat-messages.tsx
+++ b/components/chat-messages.tsx
@@ -120,7 +120,7 @@ export function ChatMessages({
) : (
<Spinner />
))}
- <div ref={anchorRef} /> {/* Anchor for auto-scroll */}
+ <div ref={anchorRef} />
</div>
)
}
diff --git a/components/chat-panel.tsx b/components/chat-panel.tsx
index 4c12d959..04b61e7e 100644
--- a/components/chat-panel.tsx
+++ b/components/chat-panel.tsx
@@ -90,6 +90,17 @@ export function ChatPanel({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [query])
+ // Add scroll to bottom handler
+ const handleScrollToBottom = () => {
+ const scrollContainer = document.getElementById('scroll-container')
+ if (scrollContainer) {
+ scrollContainer.scrollTo({
+ top: scrollContainer.scrollHeight,
+ behavior: 'smooth'
+ })
+ }
+ }
+
return (
<div
className={cn(
@@ -109,23 +120,20 @@ export function ChatPanel({
onSubmit={handleSubmit}
className={cn('max-w-3xl w-full mx-auto relative')}
>
- {/* Scroll-down button: position relative to the sticky panel */}
+ {/* Add scroll-down button to ChatPanel right top - show when not auto scrolling */}
{!isAutoScroll && messages.length > 0 && (
<Button
type="button"
variant="outline"
size="icon"
- className="absolute -top-10 right-4 z-20 size-8 rounded-full"
- onClick={() =>
- window.scrollTo({
- top: document.documentElement.scrollHeight,
- behavior: 'smooth'
- })
- }
+ className="absolute -top-10 right-4 z-20 size-8 rounded-full shadow-md"
+ onClick={handleScrollToBottom}
+ title="Scroll to bottom"
>
<ChevronDown size={16} />
</Button>
)}
+
<div className="relative flex flex-col w-full gap-2 bg-muted rounded-3xl border border-input">
<Textarea
ref={inputRef}
diff --git a/components/chat.tsx b/components/chat.tsx
index 4c3ad1e6..0196e842 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -7,7 +7,7 @@ import { cn } from '@/lib/utils'
import { useChat } from '@ai-sdk/react'
import { ChatRequestOptions } from 'ai'
import { Message } from 'ai/react'
-import { useEffect } from 'react'
+import { useEffect, useRef } from 'react'
import { toast } from 'sonner'
import { ChatMessages } from './chat-messages'
import { ChatPanel } from './chat-panel'
@@ -23,6 +23,8 @@ export function Chat({
query?: string
models?: Model[]
}) {
+ const scrollContainerRef = useRef<HTMLDivElement>(null)
+
const {
messages,
input,
@@ -54,11 +56,12 @@ export function Chat({
const isLoading = status === 'submitted' || status === 'streaming'
- // Manage auto-scroll and user scroll cancel
const { anchorRef, isAutoScroll } = useAutoScroll({
isLoading,
dependency: messages.length,
- isStreaming: () => status === 'streaming'
+ isStreaming: () => status === 'streaming',
+ scrollContainer: scrollContainerRef,
+ threshold: 10
})
useEffect(() => {
@@ -72,12 +75,10 @@ export function Chat({
})
}
- // Function to update message content and reload the conversation
const handleUpdateAndReloadMessage = async (
messageId: string,
newContent: string
) => {
- // Update the message with new content
setMessages(currentMessages =>
currentMessages.map(msg =>
msg.id === messageId ? { ...msg, content: newContent } : msg
@@ -85,20 +86,15 @@ export function Chat({
)
try {
- // Find the updated message's index
const messageIndex = messages.findIndex(msg => msg.id === messageId)
if (messageIndex === -1) return
- // Keep only messages up to that point
const messagesUpToEdited = messages.slice(0, messageIndex + 1)
- // Update messages to include only up to the edited message
setMessages(messagesUpToEdited)
- // Reset data to clear any tool calls
setData(undefined)
- // Regenerate the conversation using reload
await reload({
body: {
chatId: id,
@@ -111,33 +107,27 @@ export function Chat({
}
}
- // Function to trim messages and reload from a specific message
const handleReloadFrom = async (
messageId: string,
options?: ChatRequestOptions
) => {
- // Find the index of the message with the specified ID
const messageIndex = messages.findIndex(m => m.id === messageId)
if (messageIndex !== -1) {
- // Keep messages up to the specified one (usually the assistant message)
- // and the user message just before it.
const userMessageIndex = messages
.slice(0, messageIndex)
.findLastIndex(m => m.role === 'user')
if (userMessageIndex !== -1) {
const trimmedMessages = messages.slice(0, userMessageIndex + 1)
setMessages(trimmedMessages)
- // Reload the conversation
return await reload(options)
}
}
- // If message or preceding user message not found, perform a normal reload
return await reload(options)
}
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
- setData(undefined) // reset data to clear tool call
+ setData(undefined)
handleSubmit(e)
}
@@ -151,6 +141,7 @@ export function Chat({
>
<div
id="scroll-container"
+ ref={scrollContainerRef}
role="list"
aria-roledescription="chat messages"
className={cn(
diff --git a/lib/hooks/use-auto-scroll.ts b/lib/hooks/use-auto-scroll.ts
index 515b2eb6..bc9535b8 100644
--- a/lib/hooks/use-auto-scroll.ts
+++ b/lib/hooks/use-auto-scroll.ts
@@ -4,6 +4,7 @@ interface UseAutoScrollOptions {
isLoading: boolean
dependency: number
isStreaming: () => boolean
+ scrollContainer?: React.RefObject<HTMLElement>
threshold?: number
intervalMs?: number
}
@@ -20,7 +21,8 @@ export function useAutoScroll({
isLoading,
dependency,
isStreaming,
- threshold = 162,
+ scrollContainer,
+ threshold = 70,
intervalMs = 100
}: UseAutoScrollOptions): UseAutoScrollReturn {
const anchorRef = useRef<HTMLDivElement>(null)
@@ -28,27 +30,51 @@ export function useAutoScroll({
// Detect user scroll to toggle auto-scroll
const handleScroll = useCallback(() => {
- if (typeof window === 'undefined') return
- const scrollHeight = document.documentElement.scrollHeight
- const atBottom =
- window.innerHeight + window.scrollY >= scrollHeight - threshold
- setIsAutoScroll(atBottom)
- }, [threshold])
+ if (scrollContainer?.current) {
+ const element = scrollContainer.current
+ const atBottom =
+ element.scrollHeight - element.scrollTop - element.clientHeight <=
+ threshold
+ setIsAutoScroll(atBottom)
+ } else if (typeof window !== 'undefined') {
+ const scrollHeight = document.documentElement.scrollHeight
+ const atBottom =
+ window.innerHeight + window.scrollY >= scrollHeight - threshold
+ setIsAutoScroll(atBottom)
+ }
+ }, [threshold, scrollContainer])
useEffect(() => {
- if (typeof window === 'undefined') return
- window.addEventListener('scroll', handleScroll, { passive: true })
- return () => {
- window.removeEventListener('scroll', handleScroll)
+ if (scrollContainer?.current) {
+ const element = scrollContainer.current
+ element.addEventListener('scroll', handleScroll, { passive: true })
+ return () => {
+ element.removeEventListener('scroll', handleScroll)
+ }
+ } else if (typeof window !== 'undefined') {
+ window.addEventListener('scroll', handleScroll, { passive: true })
+ return () => {
+ window.removeEventListener('scroll', handleScroll)
+ }
}
- }, [handleScroll])
+ return undefined
+ }, [handleScroll, scrollContainer])
// Scroll to anchor element
const scrollToBottom = useCallback(() => {
- anchorRef.current?.scrollIntoView({
- behavior: dependency > 5 ? 'instant' : 'smooth'
- })
- }, [dependency])
+ if (anchorRef.current) {
+ if (scrollContainer?.current) {
+ anchorRef.current.scrollIntoView({
+ behavior: dependency > 5 ? 'instant' : 'smooth',
+ block: 'end'
+ })
+ } else {
+ anchorRef.current.scrollIntoView({
+ behavior: dependency > 5 ? 'instant' : 'smooth'
+ })
+ }
+ }
+ }, [dependency, scrollContainer])
// Auto-scroll on updates and during streaming
useEffect(() => {