fix(ai): fix auto-scroll logic and improve some ui

- Updated the ChatInterface component to improve scrolling behavior and UI elements.
- Replaced the scroll-to-bottom button with a more visually appealing design and added functionality to reset scroll state.
- Enhanced the AIChatWaitingIndicator with animations for better user feedback during processing.
- Refactored the useAutoScroll hook to improve performance and user interaction handling, ensuring smoother scrolling experience.
- Filtered out empty message parts before persisting to the database, improving data integrity.

These changes collectively enhance the user experience in the AI chat interface.

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2025-08-11 22:44:47 +08:00
parent e844a68b28
commit dba2461de7
4 changed files with 70 additions and 86 deletions
@@ -1,14 +1,13 @@
import { ScrollArea } from "@follow/components/ui/scroll-area/ScrollArea.js"
import { tracker } from "@follow/tracker"
import { clsx, cn, nextFrame } from "@follow/utils"
import { springScrollTo } from "@follow/utils/scroller"
import type { BizUIMessage } from "@folo-services/ai-tools"
import { ErrorBoundary } from "@sentry/react"
import type { EditorState, LexicalEditor } from "lexical"
import { AnimatePresence } from "motion/react"
import { nanoid } from "nanoid"
import type { FC } from "react"
import { Suspense, useCallback, useEffect, useState } from "react"
import { Suspense, useEffect, useState } from "react"
import { useEventCallback } from "usehooks-ts"
import {
@@ -34,7 +33,7 @@ import { ChatInput } from "./ChatInput"
import { CollapsibleError } from "./CollapsibleError"
import { WelcomeScreen } from "./WelcomeScreen"
const SCROLL_BOTTOM_THRESHOLD = window.innerHeight / 2
const SCROLL_BOTTOM_THRESHOLD = 100
const ChatInterfaceContent = () => {
const hasMessages = useHasMessages()
@@ -97,13 +96,6 @@ const ChatInterfaceContent = () => {
}
}, [scrollAreaRef])
const scrollToBottom = useCallback(() => {
const scrollElement = scrollAreaRef
if (!scrollElement) return
springScrollTo(scrollElement.scrollHeight, scrollElement)
}, [scrollAreaRef])
const blockActions = useBlockActions()
const handleSendMessage = useEventCallback(
(message: string | EditorState, editor: LexicalEditor | null) => {
@@ -175,6 +167,7 @@ const ChatInterfaceContent = () => {
<WelcomeScreen onSend={handleSendMessage} />
) : (
<ScrollArea
scrollbarClassName="mb-40 mt-12"
ref={setScrollAreaRef}
rootClassName="flex-1"
viewportClassName={cn("pt-12 pb-32", error && "pb-48")}
@@ -186,7 +179,8 @@ const ChatInterfaceContent = () => {
) : (
<div className="mx-auto max-w-4xl px-6 py-8">
<Messages />
{status === "submitted" && <AIChatWaitingIndicator />}
{(status === "submitted" || status === "streaming") && <AIChatWaitingIndicator />}
</div>
)}
</ScrollArea>
@@ -195,24 +189,19 @@ const ChatInterfaceContent = () => {
</div>
{shouldShowScrollToBottom && (
<div className="absolute inset-x-0 bottom-32 z-10">
<div className="mx-auto max-w-[300px] p-6 pb-3">
<button
type="button"
onClick={scrollToBottom}
className="bg-accent/10 border-accent/20 shadow-accent/5 dark:shadow-accent/10 hover:bg-accent/15 backdrop-blur-background group relative w-full overflow-hidden rounded-xl border shadow-lg transition-colors"
>
{/* Glass effect overlay */}
<div className="from-accent/5 absolute inset-0 bg-gradient-to-r to-transparent" />
{/* Content */}
<div className="relative z-10 flex items-center justify-center gap-2 p-3">
<i className="i-mingcute-arrow-down-circle-fill text-accent size-3" />
<span className="text-accent text-sm font-medium">Scroll to Bottom</span>
</div>
</button>
</div>
<div className={clsx("absolute right-1/2 z-40 translate-x-1/2", "bottom-44")}>
<button
type="button"
onClick={() => resetScrollState()}
className={cn(
"backdrop-blur-background group flex items-center gap-2 rounded-full border px-3.5 py-2 transition-all",
"border-border/40 bg-material-ultra-thin/70 shadow-[0_1px_2px_rgba(0,0,0,0.06),0_8px_24px_rgba(0,0,0,0.08)]",
"hover:bg-material-thin/70 hover:border-border/60 active:scale-[0.98]",
)}
>
<i className="i-mingcute-arrow-down-line text-text/90 size-3" />
<span className="text-text/90 text-[13px] font-medium">Scroll to Bottom</span>
</button>
</div>
)}
@@ -247,8 +247,17 @@ export const AIChatMessage: React.FC<AIChatMessageProps> = React.memo(({ message
export const AIChatWaitingIndicator: React.FC = () => {
return (
<span className="text-text-tertiary text-xs">
<i className="i-mgc-loading-3-cute-re size-3 animate-spin" />
</span>
<m.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 8 }}
transition={{ duration: 0.2, ease: [0.25, 0.46, 0.45, 0.94] }}
className="sticky bottom-4 z-10 flex w-full justify-center pb-2"
>
<div className="backdrop-blur-background border-border/50 bg-material-ultra-thin/70 text-text-secondary hover:bg-material-thin/70 flex items-center gap-2 rounded-full border px-3.5 py-1.5 text-xs shadow-[0_1px_2px_rgba(0,0,0,0.06),0_8px_24px_rgba(0,0,0,0.08)] transition-colors">
<i className="i-mgc-loading-3-cute-re size-3 animate-spin" />
<span className="font-medium">Thinking…</span>
</div>
</m.div>
)
}
@@ -1,26 +1,22 @@
import { springScrollTo } from "@follow/utils/scroller"
import { debounce } from "es-toolkit/compat"
import { debounce, throttle } from "es-toolkit/compat"
import { useCallback, useEffect, useRef, useState } from "react"
const BOTTOM_THRESHOLD = 50
export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) => {
const [isAtBottom, setIsAtBottom] = useState(true)
const [isUserInteracting, setIsUserInteracting] = useState(false)
const scrollAnimationRef = useRef<{ stop: () => void } | null>(null)
const interactionTimeoutRef = useRef<number | null>(null)
const isAutoScrollingRef = useRef(false)
const isUserInteractingRef = useRef(isUserInteracting)
useEffect(() => {
isUserInteractingRef.current = isUserInteracting
}, [isUserInteracting])
const isAutoScrollCancelledRef = useRef(false)
const isAtBottomRef = useRef(isAtBottom)
useEffect(() => {
isAtBottomRef.current = isAtBottom
}, [isAtBottom])
// cancellation is tracked purely via ref to avoid re-renders while user interacts
const scrollToBottom = useCallback(
(force = false) => {
if (!viewport) return
@@ -29,7 +25,7 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) =>
scrollAnimationRef.current.stop()
}
if (force || (!isUserInteractingRef.current && isAtBottomRef.current)) {
if (force || (isAtBottomRef.current && !isAutoScrollCancelledRef.current)) {
isAutoScrollingRef.current = true
const targetScrollTop = viewport.scrollHeight - viewport.clientHeight
const animation = springScrollTo(targetScrollTop, viewport)
@@ -52,55 +48,43 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) =>
useEffect(() => {
if (!viewport) return
if (!enabled) return
if (!enabled) {
return
}
const handleScroll = () => {
const handleScroll = throttle(() => {
if (isAutoScrollingRef.current) {
return
}
}, 100)
const { scrollTop, scrollHeight, clientHeight } = viewport
const atBottom = scrollHeight - scrollTop - clientHeight <= BOTTOM_THRESHOLD
if (!isUserInteractingRef.current) {
setIsAtBottom(atBottom)
}
}
const handleWheel = () => {
const cancelAutoScroll = () => {
isAutoScrollingRef.current = false
setIsUserInteracting(true)
if (scrollAnimationRef.current) {
scrollAnimationRef.current.stop()
}
if (interactionTimeoutRef.current) {
window.clearTimeout(interactionTimeoutRef.current)
}
interactionTimeoutRef.current = window.setTimeout(() => {
setIsUserInteracting(false)
handleScroll() // Re-check position after interaction ends
}, 150)
isAutoScrollCancelledRef.current = true
handleScroll()
}
const handleWheel = throttle(cancelAutoScroll, 100)
const handleTouchStart = handleWheel
const handleTouchMove = handleWheel
viewport.addEventListener("scroll", handleScroll, { passive: true })
viewport.addEventListener("wheel", handleWheel, { passive: true })
viewport.addEventListener("touchstart", handleTouchStart, { passive: true })
viewport.addEventListener("touchmove", handleTouchMove, { passive: true })
return () => {
viewport.removeEventListener("scroll", handleScroll)
viewport.removeEventListener("wheel", handleWheel)
if (interactionTimeoutRef.current) {
window.clearTimeout(interactionTimeoutRef.current)
}
viewport.removeEventListener("touchstart", handleTouchStart)
viewport.removeEventListener("touchmove", handleTouchMove)
if (scrollAnimationRef.current) {
scrollAnimationRef.current.stop()
}
}
}, [viewport])
}, [viewport, enabled])
useEffect(() => {
if (!viewport || !enabled) return
@@ -110,7 +94,7 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) =>
const resizeObserver = new ResizeObserver(
debounce(() => {
if (!isUserInteractingRef.current && isAtBottomRef.current) {
if (isAtBottomRef.current && !isAutoScrollCancelledRef.current) {
requestAnimationFrame(() => {
scrollToBottom()
})
@@ -126,7 +110,7 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) =>
}, [viewport, enabled, scrollToBottom])
const resetScrollState = useCallback(() => {
setIsUserInteracting(false)
isAutoScrollCancelledRef.current = false
setIsAtBottom(true)
scrollToBottom(true)
}, [scrollToBottom])
@@ -154,23 +154,25 @@ class AIPersistServiceStatic {
await db
.insert(aiChatMessagesTable)
.values(
messages.map((message) => {
const convertedParts = message.parts as any[]
messages
.filter((message) => message.parts.length > 0)
.map((message) => {
const convertedParts = message.parts as any[]
return {
id: message.id,
chatId,
role: message.role,
contentFormat: "plaintext" as const,
createdAt: new Date(),
status: "completed" as const,
finishedAt: message.metadata?.finishTime
? new Date(message.metadata.finishTime)
: undefined,
messageParts: convertedParts,
metadata: message.metadata,
} as typeof aiChatMessagesTable.$inferInsert
}),
return {
id: message.id,
chatId,
role: message.role,
contentFormat: "plaintext" as const,
createdAt: new Date(),
status: "completed" as const,
finishedAt: message.metadata?.finishTime
? new Date(message.metadata.finishTime)
: undefined,
messageParts: convertedParts,
metadata: message.metadata,
} as typeof aiChatMessagesTable.$inferInsert
}),
)
.onConflictDoUpdate({
target: [aiChatMessagesTable.id],