fix: scroll issue playground

This commit is contained in:
n4ze3m
2024-07-14 23:13:48 +05:30
parent 15f29de34c
commit f5f0157260
8 changed files with 165 additions and 130 deletions

View File

@@ -0,0 +1,35 @@
import { useRef, useEffect, useState } from 'react';
export const useSmartScroll = (messages: any[], streaming: boolean) => {
const containerRef = useRef<HTMLDivElement>(null);
const [isAtBottom, setIsAtBottom] = useState(true);
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const handleScroll = () => {
const { scrollTop, scrollHeight, clientHeight } = container;
setIsAtBottom(scrollHeight - scrollTop - clientHeight < 50);
};
container.addEventListener('scroll', handleScroll);
return () => container.removeEventListener('scroll', handleScroll);
}, []);
useEffect(() => {
if (isAtBottom && containerRef.current) {
const scrollOptions: ScrollIntoViewOptions = streaming
? { behavior: 'smooth', block: 'end' }
: { behavior: 'auto', block: 'end' };
containerRef.current.lastElementChild?.scrollIntoView(scrollOptions);
}
}, [messages, streaming, isAtBottom]);
const scrollToBottom = () => {
containerRef.current?.lastElementChild?.scrollIntoView({ behavior: 'smooth', block: 'end' });
};
return { containerRef, isAtBottom, scrollToBottom };
};