An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
Refactor: Consolidate scroll to bottom button into ChatPanel
Yoshiki Miuradf9fcb509889
diff --git a/components/chat-messages.tsx b/components/chat-messages.tsxindex 07d56d9e..97823174 100644--- a/components/chat-messages.tsx+++ b/components/chat-messages.tsx@@ -1,3 +1,5 @@+'use client'+import { cn } from '@/lib/utils'import { ChatRequestOptions, JSONValue, Message } from 'ai'import { useEffect, useMemo, useState } from 'react'@@ -21,6 +23,10 @@ interface ChatMessagesProps {messageId: string,options?: ChatRequestOptions) => Promise<string | null | undefined>+ /** Whether auto-scroll is enabled (used by the button, now removed) */+ // isAutoScroll?: boolean // No longer needed+ /** Function to enable auto-scroll (used by the button, now removed) */+ // enableAutoScroll?: () => void // No longer needed}export function ChatMessages({@@ -34,7 +40,9 @@ export function ChatMessages({scrollContainerRef,onUpdateMessage,reload-}: ChatMessagesProps) {+}: // isAutoScroll, // No longer needed+// enableAutoScroll // No longer needed+ChatMessagesProps) {const [openStates, setOpenStates] = useState<Record<string, boolean>>({})const manualToolCallId = 'manual-tool-call'@@ -105,7 +113,7 @@ export function ChatMessages({'relative size-full pt-14',messages.length > 0 ? 'flex-1 overflow-y-auto' : '')}- style={{ contain: 'strict' }}+ // style={{ contain: 'strict' }}><div className="relative mx-auto w-full max-w-3xl px-4">{messages.map(message => (@@ -137,6 +145,7 @@ export function ChatMessages({))}<div ref={anchorRef} /></div>+ {/* Scroll to bottom button has been removed from here */}</div>)}diff --git a/components/chat.tsx b/components/chat.tsxindex 20dedbb4..f52731df 100644--- a/components/chat.tsx+++ b/components/chat.tsx@@ -62,10 +62,14 @@ export function Chat({const isLoading = status === 'submitted' || status === 'streaming'- const { anchorRef, isAutoScroll } = useAutoScroll({+ const {+ anchorRef,+ isAutoScroll,+ enable: enableAutoScroll+ } = useAutoScroll({isLoading,dependency: messages.length,- isStreaming: () => status === 'streaming',+ isStreaming: status === 'streaming',scrollContainer: scrollContainerRef,threshold: 50})diff --git a/lib/hooks/use-auto-scroll.ts b/lib/hooks/use-auto-scroll.tsindex bc9535b8..3549d9bd 100644--- a/lib/hooks/use-auto-scroll.ts+++ b/lib/hooks/use-auto-scroll.ts@@ -1,100 +1,181 @@-import { useCallback, useEffect, useRef, useState } from 'react'+import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useRef,+ useState+} from 'react'interface UseAutoScrollOptions {- isLoading: boolean+ /** Value that changes when the content updates (e.g. messages.length) */dependency: number- isStreaming: () => boolean+ /** Whether content is currently loading */+ isLoading: boolean+ /** Whether content is currently streaming */+ isStreaming: boolean+ /** The container element to scroll (window if undefined) */scrollContainer?: React.RefObject<HTMLElement>+ /** Threshold in pixels from bottom to consider "at bottom" (default: 60) */threshold?: number- intervalMs?: number}interface UseAutoScrollReturn {+ /** Reference to place at the bottom of your content for scroll targeting */anchorRef: React.RefObject<HTMLDivElement>+ /** Whether auto-scrolling is currently enabled */isAutoScroll: boolean+ /** Function to manually enable auto-scrolling */+ enable: () => void}/**- * Custom hook to auto-scroll to a target element and pause when the user scrolls away.+ * Hook that provides auto-scrolling functionality with user override detection.*/export function useAutoScroll({- isLoading,dependency,+ isLoading,isStreaming,scrollContainer,- threshold = 70,- intervalMs = 100+ threshold = 60}: UseAutoScrollOptions): UseAutoScrollReturn {const anchorRef = useRef<HTMLDivElement>(null)const [isAutoScroll, setIsAutoScroll] = useState(true)+ const autoScrollIsEnabledRef = useRef(true) // Ref to mirror isAutoScroll for sync checks+ const intervalRef = useRef<NodeJS.Timeout | undefined>() // Ref to hold the interval ID++ // Sync ref with state+ useEffect(() => {+ autoScrollIsEnabledRef.current = isAutoScroll+ }, [isAutoScroll])- // Detect user scroll to toggle auto-scroll+ // Detect when user scrolls away from bottomconst handleScroll = useCallback(() => {+ // Calculate distance from bottom of scroll container (synchronously)+ let pixelsFromBottom = 0if (scrollContainer?.current) {const element = scrollContainer.current- const atBottom =- element.scrollHeight - element.scrollTop - element.clientHeight <=- threshold- setIsAutoScroll(atBottom)+ pixelsFromBottom =+ element.scrollHeight - element.scrollTop - element.clientHeight} else if (typeof window !== 'undefined') {- const scrollHeight = document.documentElement.scrollHeight- const atBottom =- window.innerHeight + window.scrollY >= scrollHeight - threshold- setIsAutoScroll(atBottom)+ pixelsFromBottom =+ document.documentElement.scrollHeight -+ (window.innerHeight + window.scrollY)}- }, [threshold, scrollContainer])- useEffect(() => {- if (scrollContainer?.current) {- const element = scrollContainer.current- element.addEventListener('scroll', handleScroll, { passive: true })- return () => {- element.removeEventListener('scroll', handleScroll)+ // If user scrolled up beyond threshold AND auto-scroll was previously enabled via ref+ if (autoScrollIsEnabledRef.current && pixelsFromBottom > threshold) {+ autoScrollIsEnabledRef.current = false // Set ref immediately+ setIsAutoScroll(false) // Set state++ // Clear interval immediately if it's running+ if (intervalRef.current) {+ clearInterval(intervalRef.current)+ intervalRef.current = undefined}- } else if (typeof window !== 'undefined') {- window.addEventListener('scroll', handleScroll, { passive: true })+ }+ }, [scrollContainer, threshold]) // Depends only on these props++ // Add scroll event listener+ useEffect(() => {+ const options = { passive: true }+ const currentScrollElement = scrollContainer?.current++ if (currentScrollElement) {+ currentScrollElement.addEventListener('scroll', handleScroll, options)return () => {- window.removeEventListener('scroll', handleScroll)+ currentScrollElement.removeEventListener('scroll', handleScroll)}}+ // No window fallback, listener is only for the specified containerreturn undefined- }, [handleScroll, scrollContainer])+ }, [handleScroll, scrollContainer, scrollContainer?.current]) // Re-run when .current changes- // Scroll to anchor element+ // Setup intersection observer for auto re-enabling+ useEffect(() => {+ if (+ !anchorRef.current ||+ isAutoScroll || // Observer is active only when auto-scroll is off+ typeof IntersectionObserver === 'undefined'+ ) {+ return undefined+ }++ const observer = new IntersectionObserver(+ entries => {+ const [entry] = entries+ if (entry.isIntersecting && entry.intersectionRatio >= 0.95) {+ autoScrollIsEnabledRef.current = true+ setIsAutoScroll(true)+ }+ },+ {+ root: scrollContainer?.current ?? null,+ threshold: 0.95,+ rootMargin: '0px 0px 5px 0px'+ }+ )+ observer.observe(anchorRef.current)+ return () => {+ observer.disconnect()+ }+ }, [anchorRef, isAutoScroll, scrollContainer])++ // Function to manually scroll to bottomconst scrollToBottom = useCallback(() => {- if (anchorRef.current) {- if (scrollContainer?.current) {+ if (!autoScrollIsEnabledRef.current) {+ return+ }+ if (!anchorRef.current) return++ try {+ requestAnimationFrame(() => {+ if (!anchorRef.current || !autoScrollIsEnabledRef.current) return // Double check ref inside rAFanchorRef.current.scrollIntoView({behavior: dependency > 5 ? 'instant' : 'smooth',block: 'end'})- } else {- anchorRef.current.scrollIntoView({- behavior: dependency > 5 ? 'instant' : 'smooth'- })- }+ })+ } catch (error) {+ console.error('[useAutoScroll] Error scrolling:', error)+ }+ }, [dependency]) // dependency is the main driver for scroll content change++ // Function to enable auto-scrolling+ const enable = useCallback(() => {+ autoScrollIsEnabledRef.current = true // Set ref first+ setIsAutoScroll(true) // Then set state+ setTimeout(scrollToBottom, 0) // scrollToBottom will respect the ref+ }, [scrollToBottom])++ // Perform auto-scroll when content changes or state allows+ useLayoutEffect(() => {+ if (!autoScrollIsEnabledRef.current) {+ return}- }, [dependency, scrollContainer])- // Auto-scroll on updates and during streaming- useEffect(() => {- if (!isAutoScroll) returnscrollToBottom()- let intervalId: ReturnType<typeof setInterval> | undefined- if (isAutoScroll && isStreaming() && isLoading) {- intervalId = setInterval(scrollToBottom, intervalMs)++ // Clear any existing interval before potentially starting a new one+ if (intervalRef.current) {+ clearInterval(intervalRef.current)+ intervalRef.current = undefined+ }++ if (autoScrollIsEnabledRef.current && isStreaming && isLoading) {+ intervalRef.current = setInterval(scrollToBottom, 150)}+return () => {- if (intervalId) clearInterval(intervalId)+ if (intervalRef.current) {+ clearInterval(intervalRef.current)+ intervalRef.current = undefined+ }}- }, [- dependency,- isLoading,- isAutoScroll,- isStreaming,- intervalMs,- scrollToBottom- ])+ }, [dependency, isLoading, isStreaming, isAutoScroll, scrollToBottom]) // isAutoScroll is needed to re-trigger effect when it changes state- return { anchorRef, isAutoScroll }+ return {+ anchorRef,+ isAutoScroll,+ enable+ }}