feat: refactor chat panel and message components for improved scrolling and message display

- Replaced manual scroll handling in ChatPanel with ConversationMessageScroller for better performance and maintainability.
- Introduced ConversationMessageBubble and ConversationMessageRow components for consistent message styling.
- Updated SupportChatMessageList to utilize new message components and scrolling logic.
- Added utility components for message scroller and message display, enhancing the overall chat experience.
- Updated package dependencies to include @shadcn/react for UI components.
This commit is contained in:
mlogclub
2026-07-29 10:09:17 +08:00
parent 90f5bab456
commit 74b4317578
10 changed files with 839 additions and 552 deletions
@@ -0,0 +1,53 @@
"use client"
import type { ReactNode } from "react"
import { cn } from "@/lib/utils"
export type ConversationMessageVariant =
| "customer"
| "agent"
| "ai"
| "system"
| "recalled"
type ConversationMessageBubbleProps = {
variant: ConversationMessageVariant
children: ReactNode
className?: string
}
function getBubbleClassName(variant: ConversationMessageVariant) {
switch (variant) {
case "customer":
return "border-border/70 bg-muted/60 text-foreground shadow-sm"
case "system":
return "border-dashed border-border bg-muted/60 text-muted-foreground"
case "ai":
return "border-primary/15 bg-primary/5 text-foreground shadow-sm"
case "agent":
return "border-transparent bg-emerald-600 text-white shadow-sm"
case "recalled":
return "border-dashed border-border/70 bg-muted/40 text-muted-foreground"
default:
return "border-border/70 bg-muted/60 text-foreground shadow-sm"
}
}
export function ConversationMessageBubble({
variant,
children,
className,
}: ConversationMessageBubbleProps) {
return (
<div
className={cn(
"w-fit max-w-full rounded-2xl border px-4 py-3 text-sm leading-6",
getBubbleClassName(variant),
className,
)}
>
{children}
</div>
)
}
@@ -0,0 +1,104 @@
"use client"
import type { ReactNode } from "react"
import {
Message,
MessageAvatar,
MessageContent,
MessageFooter,
MessageHeader,
} from "@/components/ui/message"
import { cn } from "@/lib/utils"
type ConversationMessageRowProps = {
align: "start" | "end"
centered?: boolean
header?: ReactNode
footer?: ReactNode
avatar?: ReactNode
children: ReactNode
className?: string
avatarClassName?: string
contentClassName?: string
headerClassName?: string
footerClassName?: string
}
export function ConversationMessageRow({
align,
centered = false,
header,
footer,
avatar,
children,
className,
avatarClassName,
contentClassName,
headerClassName,
footerClassName,
}: ConversationMessageRowProps) {
if (centered) {
return (
<Message
align="start"
className={cn("justify-center", className)}
>
<MessageContent className={cn("w-fit max-w-[85%] items-center", contentClassName)}>
{header ? (
<MessageHeader className={cn("justify-center text-center", headerClassName)}>
{header}
</MessageHeader>
) : null}
{children}
{footer ? (
<MessageFooter className={cn("justify-center text-center", footerClassName)}>
{footer}
</MessageFooter>
) : null}
</MessageContent>
</Message>
)
}
return (
<Message align={align} className={className}>
{avatar ? (
<MessageAvatar className={cn("bg-transparent", avatarClassName)}>
{avatar}
</MessageAvatar>
) : null}
<MessageContent
className={cn(
"max-w-[85%]",
align === "end" ? "items-end" : "items-start",
contentClassName,
)}
>
{header ? (
<MessageHeader
className={cn(
"gap-2 px-0",
align === "end" ? "justify-end text-right" : "justify-start text-left",
headerClassName,
)}
>
{header}
</MessageHeader>
) : null}
{children}
{footer ? (
<MessageFooter
className={cn(
"gap-2 px-0",
align === "end" ? "justify-end text-right" : "justify-start text-left",
footerClassName,
)}
>
{footer}
</MessageFooter>
) : null}
</MessageContent>
</Message>
)
}
@@ -0,0 +1,151 @@
"use client"
import {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useRef,
type ReactNode,
type UIEvent,
} from "react"
import {
MessageScroller,
MessageScrollerButton,
MessageScrollerContent,
MessageScrollerItem,
MessageScrollerProvider,
MessageScrollerViewport,
useMessageScroller,
useMessageScrollerScrollable,
} from "@/components/ui/message-scroller"
import { cn } from "@/lib/utils"
export type ConversationMessageScrollerHandle = {
scrollToBottom: () => void
}
type ConversationMessageScrollerProps = {
children: ReactNode
className?: string
viewportClassName?: string
contentClassName?: string
hasMoreOlder?: boolean
loadingOlder?: boolean
onLoadOlder?: () => void | Promise<void>
onNearBottomChange?: (nearBottom: boolean) => void
onNearBottomVisible?: () => void
topSlot?: ReactNode
scrollThreshold?: number
}
const ConversationMessageScrollerInner = forwardRef<
ConversationMessageScrollerHandle,
ConversationMessageScrollerProps
>(function ConversationMessageScrollerInner(
{
children,
className,
viewportClassName,
contentClassName,
hasMoreOlder = false,
loadingOlder = false,
onLoadOlder,
onNearBottomChange,
onNearBottomVisible,
topSlot,
scrollThreshold = 120,
},
ref,
) {
const { scrollToEnd } = useMessageScroller()
const scrollable = useMessageScrollerScrollable()
const loadingRef = useRef(false)
const nearBottomRef = useRef(false)
const onLoadOlderRef = useRef(onLoadOlder)
const onNearBottomChangeRef = useRef(onNearBottomChange)
const onNearBottomVisibleRef = useRef(onNearBottomVisible)
useEffect(() => {
onLoadOlderRef.current = onLoadOlder
}, [onLoadOlder])
useEffect(() => {
onNearBottomChangeRef.current = onNearBottomChange
}, [onNearBottomChange])
useEffect(() => {
onNearBottomVisibleRef.current = onNearBottomVisible
}, [onNearBottomVisible])
useEffect(() => {
loadingRef.current = loadingOlder
}, [loadingOlder])
useEffect(() => {
const nearBottom = !scrollable.end
nearBottomRef.current = nearBottom
onNearBottomChangeRef.current?.(nearBottom)
if (nearBottom) {
onNearBottomVisibleRef.current?.()
}
}, [scrollable.end])
useImperativeHandle(ref, () => ({
scrollToBottom: () => {
scrollToEnd({ behavior: "auto" })
},
}), [scrollToEnd])
const maybeLoadOlder = useCallback((viewport: HTMLElement) => {
if (!hasMoreOlder || loadingRef.current || !onLoadOlderRef.current) {
return
}
if (viewport.scrollTop > scrollThreshold) {
return
}
loadingRef.current = true
void Promise.resolve(onLoadOlderRef.current()).finally(() => {
loadingRef.current = false
})
}, [hasMoreOlder, scrollThreshold])
const handleScroll = useCallback(
(event: UIEvent<HTMLDivElement>) => {
maybeLoadOlder(event.currentTarget)
},
[maybeLoadOlder],
)
return (
<MessageScroller className={className}>
<MessageScrollerViewport
className={cn("agent-desk-scrollbar bg-muted/10", viewportClassName)}
onScroll={handleScroll}
preserveScrollOnPrepend
>
<MessageScrollerContent
className={cn("gap-4 px-6 py-5", contentClassName)}
>
{topSlot}
{children}
</MessageScrollerContent>
</MessageScrollerViewport>
<MessageScrollerButton />
</MessageScroller>
)
})
export const ConversationMessageScroller = forwardRef<
ConversationMessageScrollerHandle,
ConversationMessageScrollerProps
>(function ConversationMessageScroller(props, ref) {
return (
<MessageScrollerProvider autoScroll defaultScrollPosition="end">
<ConversationMessageScrollerInner {...props} ref={ref} />
</MessageScrollerProvider>
)
})
export { MessageScrollerItem as ConversationMessageScrollerItem }
+85 -172
View File
@@ -6,10 +6,16 @@ import {
useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from "react"
import { ConversationMessageBubble } from "@/components/chat/conversation-message-bubble"
import { ConversationMessageRow } from "@/components/chat/conversation-message-row"
import {
ConversationMessageScroller,
ConversationMessageScrollerItem,
type ConversationMessageScrollerHandle,
} from "@/components/chat/conversation-message-scroller"
import { ImMessageHTML } from "@/components/im-message-html"
import { useImageLightbox } from "@/components/image-lightbox"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
@@ -79,150 +85,52 @@ export const SupportChatMessageList = forwardRef<SupportChatMessageListHandle, S
ref
) {
const t = useI18n()
const containerRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null)
const frameRef = useRef<number | null>(null)
const scrollerRef = useRef<ConversationMessageScrollerHandle | null>(null)
const shouldStickToBottomRef = useRef(true)
const onNearBottomVisibleRef = useRef(onNearBottomVisible)
const safeMessages = Array.isArray(messages) ? messages : []
const lastMessageId = safeMessages.at(-1)?.id
useEffect(() => {
onNearBottomVisibleRef.current = onNearBottomVisible
}, [onNearBottomVisible])
const isNearBottom = useCallback(
(element: HTMLElement, threshold = 80) =>
element.scrollHeight - element.scrollTop - element.clientHeight <= threshold,
[]
)
const scrollToBottom = useCallback(() => {
const container = containerRef.current
if (!container) {
return
}
container.scrollTop = container.scrollHeight
scrollerRef.current?.scrollToBottom()
}, [])
const scheduleScrollToBottom = useCallback(
(attempts = 4) => {
if (frameRef.current !== null) {
cancelAnimationFrame(frameRef.current)
}
const run = (remaining: number, previousHeight = -1) => {
frameRef.current = requestAnimationFrame(() => {
const container = containerRef.current
if (!container) {
frameRef.current = null
return
}
const currentHeight = container.scrollHeight
scrollToBottom()
if (remaining > 1 && currentHeight !== previousHeight) {
run(remaining - 1, currentHeight)
return
}
frameRef.current = null
})
}
run(attempts)
},
[scrollToBottom]
)
const handleImageSettled = useCallback(() => {
if (shouldStickToBottomRef.current) {
scheduleScrollToBottom()
scrollToBottom()
onNearBottomVisibleRef.current?.()
}
}, [scheduleScrollToBottom])
}, [scrollToBottom])
useImperativeHandle(ref, () => ({
scrollToBottom,
}))
useLayoutEffect(() => {
shouldStickToBottomRef.current = true
scheduleScrollToBottom()
return () => {
if (frameRef.current !== null) {
cancelAnimationFrame(frameRef.current)
frameRef.current = null
}
}
}, [lastMessageId, scheduleScrollToBottom])
useEffect(() => {
const container = containerRef.current
const content = contentRef.current
if (!container || !content) {
return
}
const handleScroll = () => {
shouldStickToBottomRef.current = isNearBottom(container)
if (shouldStickToBottomRef.current) {
onNearBottomVisible?.()
}
}
const resizeObserver = new ResizeObserver(() => {
if (shouldStickToBottomRef.current) {
scheduleScrollToBottom()
}
})
handleScroll()
container.addEventListener("scroll", handleScroll)
resizeObserver.observe(container)
resizeObserver.observe(content)
scrollToBottom()
return () => {
container.removeEventListener("scroll", handleScroll)
resizeObserver.disconnect()
}
}, [isNearBottom, onNearBottomVisible, scheduleScrollToBottom, scrollToBottom])
const handleLoadOlder = useCallback(async () => {
if (!onLoadOlder || loadingOlder || !hasMoreOlder) {
return
}
const container = containerRef.current
if (!container) {
return
}
const anchor = {
height: container.scrollHeight,
top: container.scrollTop,
}
try {
await onLoadOlder()
} catch {
return
}
requestAnimationFrame(() => {
requestAnimationFrame(() => {
const current = containerRef.current
if (!current) {
return
}
current.scrollTop = current.scrollHeight - anchor.height + anchor.top
})
})
await onLoadOlder()
}, [hasMoreOlder, loadingOlder, onLoadOlder])
return (
<div
ref={containerRef}
className="agent-desk-scrollbar flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 py-4"
>
<div ref={contentRef} className="flex flex-col gap-4">
{hasMoreOlder && onLoadOlder ? (
<ConversationMessageScroller
ref={scrollerRef}
className="flex min-h-0 flex-1"
viewportClassName="bg-transparent"
contentClassName="gap-4 px-4 py-4"
hasMoreOlder={hasMoreOlder}
loadingOlder={loadingOlder}
onLoadOlder={onLoadOlder}
onNearBottomChange={(nearBottom) => {
shouldStickToBottomRef.current = nearBottom
}}
onNearBottomVisible={onNearBottomVisible}
topSlot={
hasMoreOlder && onLoadOlder ? (
<div className="flex justify-center py-1">
<Button
type="button"
@@ -235,32 +143,36 @@ export const SupportChatMessageList = forwardRef<SupportChatMessageListHandle, S
{loadingOlder ? t("supportChat.loadingOlder") : t("supportChat.loadOlder")}
</Button>
</div>
) : null}
) : null
}
>
{safeMessages.length === 0 ? (
<div className="flex min-h-32 items-center justify-center px-3 py-6 text-center text-sm leading-6 text-muted-foreground">
{t("supportChat.emptyPrompt")}
</div>
) : null}
{safeMessages.length === 0 ? (
<div className="flex min-h-32 items-center justify-center px-3 py-6 text-center text-sm leading-6 text-muted-foreground">
{t("supportChat.emptyPrompt")}
</div>
) : null}
{safeMessages.map((message, index) => {
const previousMessage = index > 0 ? safeMessages[index - 1] : null
const showTimeline =
index === 0 ||
getDayKey(previousMessage?.sentAt) !== getDayKey(message.sentAt)
{safeMessages.map((message, index) => {
const previousMessage = index > 0 ? safeMessages[index - 1] : null
const showTimeline =
index === 0 ||
getDayKey(previousMessage?.sentAt) !== getDayKey(message.sentAt)
return (
return (
<ConversationMessageScrollerItem
key={message.id}
messageId={`${message.id}`}
>
<MessageItem
key={message.id}
message={message}
showTimeline={showTimeline}
onImageSettled={handleImageSettled}
timelineLabel={getTimelineLabel(message.sentAt, t)}
/>
)
})}
</div>
</div>
</ConversationMessageScrollerItem>
)
})}
</ConversationMessageScroller>
)
}
)
@@ -296,50 +208,51 @@ const MessageItem = memo(
</div>
) : null}
<div className={cn("flex gap-2.5", isCustomer ? "justify-end" : "justify-start")}>
{!isCustomer ? (
<Avatar className="mt-5">
{avatarSrc ? <AvatarImage src={avatarSrc} alt="" /> : null}
<AvatarFallback className="bg-muted text-muted-foreground">
{fallbackName || t("supportChat.customerFallback")}
</AvatarFallback>
</Avatar>
) : null}
<div
className={cn(
"flex max-w-[86%] flex-col gap-1.5",
isCustomer ? "items-end" : "items-start"
)}
>
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 px-1 text-[11px] text-muted-foreground">
<ConversationMessageRow
align={isCustomer ? "end" : "start"}
avatar={
!isCustomer ? (
<Avatar>
{avatarSrc ? <AvatarImage src={avatarSrc} alt="" /> : null}
<AvatarFallback className="bg-muted text-muted-foreground">
{fallbackName || t("supportChat.customerFallback")}
</AvatarFallback>
</Avatar>
) : null
}
contentClassName="max-w-[86%] gap-1.5"
headerClassName="flex-wrap gap-x-2 gap-y-1 px-1 text-[11px]"
header={
<>
<span className="font-medium">{senderName}</span>
<span>{formatDateTime(message.sentAt)}</span>
{isCustomer ? (
<span>{message.agentRead ? t("supportChat.agentRead") : t("supportChat.agentUnread")}</span>
) : null}
</div>
<div
</>
}
>
<ConversationMessageBubble
variant={isCustomer ? "customer" : "system"}
className={cn(
"rounded-lg border-0 px-3 py-2 text-sm leading-normal shadow-[0_10px_22px_rgba(15,23,42,0.06)]",
isCustomer
? "bg-[#a9ea7a] text-[#161616] dark:bg-emerald-500 dark:text-emerald-950"
: "border border-border bg-card text-card-foreground dark:bg-background"
)}
>
<ImMessageHTML
html={htmlContent}
className={cn(
"rounded-lg px-3 py-2 text-sm leading-normal shadow-[0_10px_22px_rgba(15,23,42,0.06)]",
isCustomer
? "bg-[#a9ea7a] text-[#161616] dark:bg-emerald-500 dark:text-emerald-950"
: "border border-border bg-card text-card-foreground dark:bg-background"
? "[&_p]:text-[#161616] dark:[&_p]:text-emerald-950 [&_a]:text-[#161616] dark:[&_a]:text-emerald-950 [&_a]:underline [&_img]:cursor-zoom-in"
: "[&_a]:text-card-foreground [&_a]:underline [&_img]:cursor-zoom-in"
)}
>
<ImMessageHTML
html={htmlContent}
className={cn(
isCustomer
? "[&_p]:text-[#161616] dark:[&_p]:text-emerald-950 [&_a]:text-[#161616] dark:[&_a]:text-emerald-950 [&_a]:underline [&_img]:cursor-zoom-in"
: "[&_a]:text-card-foreground [&_a]:underline [&_img]:cursor-zoom-in"
)}
onImageSettled={onImageSettled}
onImageClick={open}
/>
</div>
</div>
</div>
onImageSettled={onImageSettled}
onImageClick={open}
/>
</ConversationMessageBubble>
</ConversationMessageRow>
</div>
)
},
+131
View File
@@ -0,0 +1,131 @@
"use client"
import * as React from "react"
import {
MessageScroller as MessageScrollerPrimitive,
useMessageScroller,
useMessageScrollerScrollable,
useMessageScrollerVisibility,
} from "@shadcn/react/message-scroller"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { ArrowDownIcon } from "lucide-react"
function MessageScrollerProvider(
props: React.ComponentProps<typeof MessageScrollerPrimitive.Provider>
) {
return <MessageScrollerPrimitive.Provider {...props} />
}
function MessageScroller({
className,
...props
}: React.ComponentProps<typeof MessageScrollerPrimitive.Root>) {
return (
<MessageScrollerPrimitive.Root
data-slot="message-scroller"
className={cn(
"group/message-scroller relative flex size-full min-h-0 flex-col overflow-hidden",
className
)}
{...props}
/>
)
}
function MessageScrollerViewport({
className,
...props
}: React.ComponentProps<typeof MessageScrollerPrimitive.Viewport>) {
return (
<MessageScrollerPrimitive.Viewport
data-slot="message-scroller-viewport"
className={cn(
"size-full min-h-0 min-w-0 scroll-fade-b scrollbar-thin scrollbar-gutter-stable overflow-y-auto overscroll-contain contain-content data-autoscrolling:scrollbar-thumb-transparent data-autoscrolling:scrollbar-track-transparent",
className
)}
{...props}
/>
)
}
function MessageScrollerContent({
className,
...props
}: React.ComponentProps<typeof MessageScrollerPrimitive.Content>) {
return (
<MessageScrollerPrimitive.Content
data-slot="message-scroller-content"
className={cn("flex h-max min-h-full flex-col gap-6", className)}
{...props}
/>
)
}
function MessageScrollerItem({
className,
scrollAnchor = false,
...props
}: React.ComponentProps<typeof MessageScrollerPrimitive.Item>) {
return (
<MessageScrollerPrimitive.Item
data-slot="message-scroller-item"
scrollAnchor={scrollAnchor}
className={cn(
"min-w-0 shrink-0 [contain-intrinsic-size:auto_10rem] [content-visibility:auto]",
className
)}
{...props}
/>
)
}
function MessageScrollerButton({
direction = "end",
className,
children,
render,
variant = "secondary",
size = "icon-sm",
...props
}: React.ComponentProps<typeof MessageScrollerPrimitive.Button> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<MessageScrollerPrimitive.Button
data-slot="message-scroller-button"
data-direction={direction}
data-variant={variant}
data-size={size}
direction={direction}
className={cn(
"absolute inset-s-1/2 -translate-x-1/2 border-border bg-background text-foreground transition-[translate,scale,opacity] duration-200 hover:bg-muted hover:text-foreground data-[active=false]:pointer-events-none data-[active=false]:scale-95 data-[active=false]:opacity-0 data-[active=false]:duration-400 data-[active=false]:ease-[cubic-bezier(0.7,0,0.84,0)] data-[active=true]:translate-y-0 data-[active=true]:scale-100 data-[active=true]:opacity-100 data-[active=true]:ease-[cubic-bezier(0.23,1,0.32,1)] data-[direction=end]:bottom-4 data-[direction=end]:data-[active=false]:translate-y-full data-[direction=start]:top-4 data-[direction=start]:data-[active=false]:-translate-y-full rtl:translate-x-1/2 data-[direction=start]:[&_svg]:rotate-180",
className
)}
render={render ?? <Button variant={variant} size={size} />}
{...props}
>
{children ?? (
<>
<ArrowDownIcon
/>
<span className="sr-only">
{direction === "end" ? "Scroll to end" : "Scroll to start"}
</span>
</>
)}
</MessageScrollerPrimitive.Button>
)
}
export {
MessageScrollerProvider,
MessageScroller,
MessageScrollerViewport,
MessageScrollerContent,
MessageScrollerItem,
MessageScrollerButton,
useMessageScroller,
useMessageScrollerScrollable,
useMessageScrollerVisibility,
}
+92
View File
@@ -0,0 +1,92 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function MessageGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="message-group"
className={cn("flex min-w-0 flex-col gap-2", className)}
{...props}
/>
)
}
function Message({
className,
align = "start",
...props
}: React.ComponentProps<"div"> & { align?: "start" | "end" }) {
return (
<div
data-slot="message"
data-align={align}
className={cn(
"group/message relative flex w-full min-w-0 gap-2 text-sm data-[align=end]:flex-row-reverse",
className
)}
{...props}
/>
)
}
function MessageAvatar({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="message-avatar"
className={cn(
"flex w-fit min-w-8 shrink-0 items-center justify-center self-end overflow-hidden rounded-full bg-muted group-has-data-[slot=message-footer]/message:-translate-y-8",
className
)}
{...props}
/>
)
}
function MessageContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="message-content"
className={cn(
"flex w-full min-w-0 flex-col gap-2.5 wrap-break-word group-data-[align=end]/message:*:data-slot:self-end",
className
)}
{...props}
/>
)
}
function MessageHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="message-header"
className={cn(
"flex max-w-full min-w-0 items-center px-3 text-xs font-medium text-muted-foreground group-has-data-[variant=ghost]/message:px-0",
className
)}
{...props}
/>
)
}
function MessageFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="message-footer"
className={cn(
"flex max-w-full min-w-0 items-center px-3 text-xs font-medium text-muted-foreground group-has-data-[variant=ghost]/message:px-0 group-data-[align=end]/message:justify-end",
className
)}
{...props}
/>
)
}
export {
MessageGroup,
Message,
MessageAvatar,
MessageContent,
MessageFooter,
MessageHeader,
}