Skip to content

An AI-powered search engine with a generative UI

Improve chat scrolling with section-based UI

Yoshiki Miuracaf75065c9f2
diff --git a/components/chat-messages.tsx b/components/chat-messages.tsx
index 97823174..40e47abd 100644
--- a/components/chat-messages.tsx
+++ b/components/chat-messages.tsx
@@ -7,15 +7,20 @@ import { RenderMessage } from './render-message'
import { ToolSection } from './tool-section'
import { Spinner } from './ui/spinner'
+// Import section structure interface
+interface ChatSection {
+ id: string
+ userMessage: Message
+ assistantMessages: Message[]
+}
+
interface ChatMessagesProps {
- messages: Message[]
+ sections: ChatSection[] // Changed from messages to sections
data: JSONValue[] | undefined
onQuerySelect: (query: string) => void
isLoading: boolean
chatId?: string
addToolResult?: (params: { toolCallId: string; result: any }) => void
- /** Ref for anchoring auto-scroll position */
- anchorRef: React.RefObject<HTMLDivElement>
/** Ref for the scroll container */
scrollContainerRef: React.RefObject<HTMLDivElement>
onUpdateMessage?: (messageId: string, newContent: string) => Promise<void>
@@ -23,35 +28,31 @@ 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({
- messages,
+ sections,
data,
onQuerySelect,
isLoading,
chatId,
addToolResult,
- anchorRef,
scrollContainerRef,
onUpdateMessage,
reload
-}: // isAutoScroll, // No longer needed
-// enableAutoScroll // No longer needed
-ChatMessagesProps) {
+}: ChatMessagesProps) {
const [openStates, setOpenStates] = useState<Record<string, boolean>>({})
const manualToolCallId = 'manual-tool-call'
useEffect(() => {
- const lastMessage = messages[messages.length - 1]
- if (lastMessage?.role === 'user') {
- setOpenStates({ [manualToolCallId]: true })
+ // Open manual tool call when the last section is a user message
+ if (sections.length > 0) {
+ const lastSection = sections[sections.length - 1]
+ if (lastSection.userMessage.role === 'user') {
+ setOpenStates({ [manualToolCallId]: true })
+ }
}
- }, [messages])
+ }, [sections])
// get last tool data for manual tool call
const lastToolData = useMemo(() => {
@@ -78,21 +79,31 @@ ChatMessagesProps) {
}
}, [data])
- if (!messages.length) return null
+ if (!sections.length) return null
+
+ // Get all messages as a flattened array
+ const allMessages = sections.flatMap(section => [
+ section.userMessage,
+ ...section.assistantMessages
+ ])
const lastUserIndex =
- messages.length -
+ allMessages.length -
1 -
- [...messages].reverse().findIndex(msg => msg.role === 'user')
+ [...allMessages].reverse().findIndex(msg => msg.role === 'user')
- const showLoading = isLoading && messages[messages.length - 1].role === 'user'
+ // Check if loading indicator should be shown
+ const showLoading =
+ isLoading &&
+ sections.length > 0 &&
+ sections[sections.length - 1].assistantMessages.length === 0
const getIsOpen = (id: string) => {
if (id.includes('call')) {
return openStates[id] ?? true
}
const baseId = id.endsWith('-related') ? id.slice(0, -8) : id
- const index = messages.findIndex(msg => msg.id === baseId)
+ const index = allMessages.findIndex(msg => msg.id === baseId)
return openStates[id] ?? index >= lastUserIndex
}
@@ -111,41 +122,66 @@ ChatMessagesProps) {
aria-roledescription="chat messages"
className={cn(
'relative size-full pt-14',
- messages.length > 0 ? 'flex-1 overflow-y-auto' : ''
+ sections.length > 0 ? 'flex-1 overflow-y-auto' : ''
)}
- // style={{ contain: 'strict' }}
>
<div className="relative mx-auto w-full max-w-3xl px-4">
- {messages.map(message => (
- <div key={message.id} className="mb-4 flex flex-col gap-4">
- <RenderMessage
- message={message}
- messageId={message.id}
- getIsOpen={getIsOpen}
- onOpenChange={handleOpenChange}
- onQuerySelect={onQuerySelect}
- chatId={chatId}
- addToolResult={addToolResult}
- onUpdateMessage={onUpdateMessage}
- reload={reload}
- />
+ {sections.map((section, sectionIndex) => (
+ <div
+ key={section.id}
+ id={`section-${section.id}`}
+ className="chat-section mb-8"
+ style={
+ sectionIndex === sections.length - 1
+ ? { minHeight: 'calc(-228px + 100dvh)' }
+ : {}
+ }
+ >
+ {/* User message */}
+ <div className="flex flex-col gap-4">
+ <RenderMessage
+ message={section.userMessage}
+ messageId={section.userMessage.id}
+ getIsOpen={getIsOpen}
+ onOpenChange={handleOpenChange}
+ onQuerySelect={onQuerySelect}
+ chatId={chatId}
+ addToolResult={addToolResult}
+ onUpdateMessage={onUpdateMessage}
+ reload={reload}
+ />
+ {showLoading && <Spinner />}
+ </div>
+
+ {/* Assistant messages */}
+ {section.assistantMessages.map(assistantMessage => (
+ <div key={assistantMessage.id} className="mt-4">
+ <RenderMessage
+ message={assistantMessage}
+ messageId={assistantMessage.id}
+ getIsOpen={getIsOpen}
+ onOpenChange={handleOpenChange}
+ onQuerySelect={onQuerySelect}
+ chatId={chatId}
+ addToolResult={addToolResult}
+ onUpdateMessage={onUpdateMessage}
+ reload={reload}
+ />
+ </div>
+ ))}
</div>
))}
- {showLoading &&
- (lastToolData ? (
- <ToolSection
- key={manualToolCallId}
- tool={lastToolData}
- isOpen={getIsOpen(manualToolCallId)}
- onOpenChange={open => handleOpenChange(manualToolCallId, open)}
- addToolResult={addToolResult}
- />
- ) : (
- <Spinner />
- ))}
- <div ref={anchorRef} />
+
+ {showLoading && lastToolData && (
+ <ToolSection
+ key={manualToolCallId}
+ tool={lastToolData}
+ isOpen={getIsOpen(manualToolCallId)}
+ onOpenChange={open => handleOpenChange(manualToolCallId, open)}
+ addToolResult={addToolResult}
+ />
+ )}
</div>
- {/* Scroll to bottom button has been removed from here */}
</div>
)
}
diff --git a/components/chat-panel.tsx b/components/chat-panel.tsx
index ed85017a..57d4c040 100644
--- a/components/chat-panel.tsx
+++ b/components/chat-panel.tsx
@@ -25,8 +25,10 @@ interface ChatPanelProps {
stop: () => void
append: (message: any) => void
models?: Model[]
- /** Whether auto-scroll is currently active (at bottom) */
- isAutoScroll: boolean
+ /** Whether to show the scroll to bottom button */
+ showScrollToBottomButton: boolean
+ /** Reference to the scroll container */
+ scrollContainerRef: React.RefObject<HTMLDivElement>
}
export function ChatPanel({
@@ -40,7 +42,8 @@ export function ChatPanel({
stop,
append,
models,
- isAutoScroll
+ showScrollToBottomButton,
+ scrollContainerRef
}: ChatPanelProps) {
const [showEmptyScreen, setShowEmptyScreen] = useState(false)
const router = useRouter()
@@ -93,9 +96,9 @@ export function ChatPanel({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [query])
- // Add scroll to bottom handler
+ // Scroll to the bottom of the container
const handleScrollToBottom = () => {
- const scrollContainer = document.getElementById('scroll-container')
+ const scrollContainer = scrollContainerRef.current
if (scrollContainer) {
scrollContainer.scrollTo({
top: scrollContainer.scrollHeight,
@@ -123,8 +126,8 @@ export function ChatPanel({
onSubmit={handleSubmit}
className={cn('max-w-3xl w-full mx-auto relative')}
>
- {/* Add scroll-down button to ChatPanel right top - show when not auto scrolling */}
- {!isAutoScroll && messages.length > 0 && (
+ {/* Scroll to bottom button - only shown when showScrollToBottomButton is true */}
+ {showScrollToBottomButton && messages.length > 0 && (
<Button
type="button"
variant="outline"
diff --git a/components/chat.tsx b/components/chat.tsx
index c95173d3..4ab2f821 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -1,18 +1,23 @@
'use client'
import { CHAT_ID } from '@/lib/constants'
-import { useAutoScroll } from '@/lib/hooks/use-auto-scroll'
import { Model } from '@/lib/types/models'
import { cn } from '@/lib/utils'
import { useChat } from '@ai-sdk/react'
import { ChatRequestOptions } from 'ai'
import { Message } from 'ai/react'
-import { useRouter } from 'next/navigation'
-import { useEffect, useRef, useTransition } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
import { toast } from 'sonner'
import { ChatMessages } from './chat-messages'
import { ChatPanel } from './chat-panel'
+// Define section structure
+interface ChatSection {
+ id: string // User message ID
+ userMessage: Message
+ assistantMessages: Message[]
+}
+
export function Chat({
id,
savedMessages = [],
@@ -25,8 +30,7 @@ export function Chat({
models?: Model[]
}) {
const scrollContainerRef = useRef<HTMLDivElement>(null)
- const router = useRouter()
- const [isPending, startTransition] = useTransition()
+ const [isAtBottom, setIsAtBottom] = useState(true)
const {
messages,
@@ -60,17 +64,72 @@ export function Chat({
const isLoading = status === 'submitted' || status === 'streaming'
- const {
- anchorRef,
- isAutoScroll,
- enable: enableAutoScroll
- } = useAutoScroll({
- isLoading,
- dependency: messages.length,
- isStreaming: status === 'streaming',
- scrollContainer: scrollContainerRef,
- threshold: 70
- })
+ // Convert messages array to sections array
+ const sections = useMemo<ChatSection[]>(() => {
+ const result: ChatSection[] = []
+ let currentSection: ChatSection | null = null
+
+ for (const message of messages) {
+ if (message.role === 'user') {
+ // Start a new section when a user message is found
+ if (currentSection) {
+ result.push(currentSection)
+ }
+ currentSection = {
+ id: message.id,
+ userMessage: message,
+ assistantMessages: []
+ }
+ } else if (currentSection && message.role === 'assistant') {
+ // Add assistant message to the current section
+ currentSection.assistantMessages.push(message)
+ }
+ // Ignore other role types like 'system' for now
+ }
+
+ // Add the last section if exists
+ if (currentSection) {
+ result.push(currentSection)
+ }
+
+ return result
+ }, [messages])
+
+ // Detect if scroll container is at the bottom
+ useEffect(() => {
+ const container = scrollContainerRef.current
+ if (!container) return
+
+ const handleScroll = () => {
+ const { scrollTop, scrollHeight, clientHeight } = container
+ const threshold = 50 // threshold in pixels
+ if (scrollHeight - scrollTop - clientHeight < threshold) {
+ setIsAtBottom(true)
+ } else {
+ setIsAtBottom(false)
+ }
+ }
+
+ container.addEventListener('scroll', handleScroll, { passive: true })
+ handleScroll() // Set initial state
+
+ return () => container.removeEventListener('scroll', handleScroll)
+ }, [scrollContainerRef.current])
+
+ // Scroll to the section when a new user message is sent
+ useEffect(() => {
+ if (sections.length > 0) {
+ const lastMessage = messages[messages.length - 1]
+ if (lastMessage && lastMessage.role === 'user') {
+ // If the last message is from user, find the corresponding section
+ const sectionId = lastMessage.id
+ requestAnimationFrame(() => {
+ const sectionElement = document.getElementById(`section-${sectionId}`)
+ sectionElement?.scrollIntoView({ behavior: 'smooth', block: 'start' })
+ })
+ }
+ }
+ }, [sections, messages])
useEffect(() => {
setMessages(savedMessages)
@@ -148,13 +207,12 @@ export function Chat({
data-testid="full-chat"
>
<ChatMessages
- messages={messages}
+ sections={sections}
data={data}
onQuerySelect={onQuerySelect}
isLoading={isLoading}
chatId={id}
addToolResult={addToolResult}
- anchorRef={anchorRef}
scrollContainerRef={scrollContainerRef}
onUpdateMessage={handleUpdateAndReloadMessage}
reload={handleReloadFrom}
@@ -170,7 +228,8 @@ export function Chat({
query={query}
append={append}
models={models}
- isAutoScroll={isAutoScroll}
+ showScrollToBottomButton={!isAtBottom}
+ scrollContainerRef={scrollContainerRef}
/>
</div>
)