Path: blob/master/cloud/ai-service-apps/nextjs-carbon-react-ui/src/hooks/useChatAutoScrollDetector.js
6408 views
// Globals -------------------------------------------------------------------->1/* global document IntersectionObserver */23import { useEffect, useRef } from "react";45const ROOT_MARGIN = "50px";67function useChatAutoScrollDetector(targetRef, shouldAutoScrollRef) {8const observerRef = useRef(null);910useEffect(() => {11const handler = (entries) => {12const target = entries[0];1314if (target.isIntersecting) {15shouldAutoScrollRef.current = true;16} else {17shouldAutoScrollRef.current = false;18}19};2021const options = {22root: document.getElementById("chat-messages"),23rootMargin: ROOT_MARGIN,24threshold: 0,25};2627observerRef.current = new IntersectionObserver(handler, options);28}, [shouldAutoScrollRef]);2930useEffect(() => {31observerRef.current.observe(targetRef.current);3233return () => {34observerRef.current.disconnect();35};36}, [targetRef]);37}3839export { useChatAutoScrollDetector };404142