An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
Fix auto-scroll behavior and scroll button flickering
Yoshiki Miurada9b08277073
diff --git a/components/chat-messages.tsx b/components/chat-messages.tsxindex 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.tsxindex 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 (<divclassName={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 && (<Buttontype="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"><Textarearef={inputRef}diff --git a/components/chat.tsx b/components/chat.tsxindex 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?: stringmodels?: 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 cancelconst { 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 conversationconst handleUpdateAndReloadMessage = async (messageId: string,newContent: string) => {- // Update the message with new contentsetMessages(currentMessages =>currentMessages.map(msg =>msg.id === messageId ? { ...msg, content: newContent } : msg@@ -85,20 +86,15 @@ export function Chat({)try {- // Find the updated message's indexconst messageIndex = messages.findIndex(msg => msg.id === messageId)if (messageIndex === -1) return- // Keep only messages up to that pointconst messagesUpToEdited = messages.slice(0, messageIndex + 1)- // Update messages to include only up to the edited messagesetMessages(messagesUpToEdited)- // Reset data to clear any tool callssetData(undefined)- // Regenerate the conversation using reloadawait reload({body: {chatId: id,@@ -111,33 +107,27 @@ export function Chat({}}- // Function to trim messages and reload from a specific messageconst handleReloadFrom = async (messageId: string,options?: ChatRequestOptions) => {- // Find the index of the message with the specified IDconst 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 conversationreturn await reload(options)}}- // If message or preceding user message not found, perform a normal reloadreturn 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({><divid="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.tsindex 515b2eb6..bc9535b8 100644--- a/lib/hooks/use-auto-scroll.ts+++ b/lib/hooks/use-auto-scroll.ts@@ -4,6 +4,7 @@ interface UseAutoScrollOptions {isLoading: booleandependency: numberisStreaming: () => boolean+ scrollContainer?: React.RefObject<HTMLElement>threshold?: numberintervalMs?: 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-scrollconst 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 elementconst 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 streaminguseEffect(() => {