File size: 1,201 Bytes
f0743f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// hooks/useAutoScroll.ts
import { useEffect, useState } from 'react';

interface UseAutoScrollProps {
  ref: React.RefObject<HTMLElement>;
  content: string;
  isSubmitting: boolean;
}

export const useAutoScroll = ({ ref, content, isSubmitting }: UseAutoScrollProps) => {
  const [userScrolled, setUserScrolled] = useState(false);

  useEffect(() => {
    const scrollContainer = ref.current;
    if (!scrollContainer) {
      return;
    }

    const handleScroll = () => {
      const { scrollTop, scrollHeight, clientHeight } = scrollContainer;
      const isNearBottom = scrollHeight - scrollTop - clientHeight < 50;

      if (!isNearBottom) {
        setUserScrolled(true);
      } else {
        setUserScrolled(false);
      }
    };

    scrollContainer.addEventListener('scroll', handleScroll);

    return () => {
      scrollContainer.removeEventListener('scroll', handleScroll);
    };
  }, [ref]);

  useEffect(() => {
    const scrollContainer = ref.current;
    if (!scrollContainer || !isSubmitting || userScrolled) {
      return;
    }

    scrollContainer.scrollTop = scrollContainer.scrollHeight;
  }, [content, isSubmitting, userScrolled, ref]);

  return { userScrolled };
};