Files
vf_react/src/views/AgentChat/hooks/useAutoScroll.ts

39 lines
961 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// src/views/AgentChat/hooks/useAutoScroll.ts
// 自动滚动 Hook - 消息列表自动滚动到底部
import { useEffect, useRef } from 'react';
import type { Message } from '../constants/messageTypes';
/**
* useAutoScroll Hook
*
* 监听消息列表变化,自动滚动到底部
*
* @param messages - 消息列表
* @returns messagesEndRef - 消息列表底部引用(需要绑定到消息列表末尾的 div
*
* @example
* ```tsx
* const { messagesEndRef } = useAutoScroll(messages);
*
* return (
* <VStack>
* {messages.map(msg => <MessageCard key={msg.id} message={msg} />)}
* <div ref={messagesEndRef} />
* </VStack>
* );
* ```
*/
export const useAutoScroll = (messages: Message[]) => {
const messagesEndRef = useRef<HTMLDivElement>(null);
useEffect(() => {
// 平滑滚动到底部
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, [messages]);
return {
messagesEndRef,
};
};