useChatScroll.tsx 994 B

12345678910111213141516171819202122232425262728293031323334
  1. import React, { useEffect } from 'react';
  2. import { throttle } from '../utils/misc';
  3. export const scrollToBottom = (requiresNearBottom: boolean, delay?: number) => {
  4. const mainScrollElem = document.getElementById('main-scroll');
  5. if (!mainScrollElem) return;
  6. const spaceToBottom =
  7. mainScrollElem.scrollHeight -
  8. mainScrollElem.scrollTop -
  9. mainScrollElem.clientHeight;
  10. if (!requiresNearBottom || spaceToBottom < 100) {
  11. setTimeout(
  12. () => mainScrollElem.scrollTo({ top: mainScrollElem.scrollHeight }),
  13. delay ?? 80
  14. );
  15. }
  16. };
  17. const scrollToBottomThrottled = throttle(scrollToBottom, 80);
  18. export function useChatScroll(msgListRef: React.RefObject<HTMLDivElement>) {
  19. useEffect(() => {
  20. if (!msgListRef.current) return;
  21. const resizeObserver = new ResizeObserver((_) => {
  22. scrollToBottomThrottled(true, 10);
  23. });
  24. resizeObserver.observe(msgListRef.current);
  25. return () => {
  26. resizeObserver.disconnect();
  27. };
  28. }, [msgListRef]);
  29. }