Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cloud/ai-service-apps/nextjs-carbon-react-ui/src/hooks/useChatAutoScrollDetector.js
6408 views
1
// Globals -------------------------------------------------------------------->
2
/* global document IntersectionObserver */
3
4
import { useEffect, useRef } from "react";
5
6
const ROOT_MARGIN = "50px";
7
8
function useChatAutoScrollDetector(targetRef, shouldAutoScrollRef) {
9
const observerRef = useRef(null);
10
11
useEffect(() => {
12
const handler = (entries) => {
13
const target = entries[0];
14
15
if (target.isIntersecting) {
16
shouldAutoScrollRef.current = true;
17
} else {
18
shouldAutoScrollRef.current = false;
19
}
20
};
21
22
const options = {
23
root: document.getElementById("chat-messages"),
24
rootMargin: ROOT_MARGIN,
25
threshold: 0,
26
};
27
28
observerRef.current = new IntersectionObserver(handler, options);
29
}, [shouldAutoScrollRef]);
30
31
useEffect(() => {
32
observerRef.current.observe(targetRef.current);
33
34
return () => {
35
observerRef.current.disconnect();
36
};
37
}, [targetRef]);
38
}
39
40
export { useChatAutoScrollDetector };
41
42