Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed autoscroll on hovering messaged + update messages #638

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 33 additions & 10 deletions components/use-scroll-to-bottom.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,52 @@
import { useEffect, useRef, type RefObject } from 'react';
import { useEffect, useRef, type RefObject } from "react";

export function useScrollToBottom<T extends HTMLElement>(): [
RefObject<T>,
RefObject<T>,
RefObject<T | null>,
RefObject<T | null>,
] {
const containerRef = useRef<T>(null);
const endRef = useRef<T>(null);
const containerRef = useRef<T | null>(null);
const endRef = useRef<T | null>(null);
const shouldScrollRef = useRef(true);

useEffect(() => {
const container = containerRef.current;
const end = endRef.current;

if (container && end) {
// Initial scroll
end.scrollIntoView({ behavior: "instant", block: "end" });

// Check if user has scrolled up
const handleScroll = () => {
if (!container) return;

const isAtBottom = Math.abs(
(container.scrollHeight - container.scrollTop) - container.clientHeight
) < 10;

shouldScrollRef.current = isAtBottom;
};

const observer = new MutationObserver(() => {
end.scrollIntoView({ behavior: 'instant', block: 'end' });
// Only scroll if we're at the bottom or it's a new message
if (shouldScrollRef.current) {
end.scrollIntoView({ behavior: "instant", block: "end" });
}
});

observer.observe(container, {
childList: true,
subtree: true,
attributes: true,
characterData: true,
subtree: true, // Watch nested changes
characterData: true, // Watch text changes
});

return () => observer.disconnect();
// Add scroll listener
container.addEventListener('scroll', handleScroll);

return () => {
observer.disconnect();
container.removeEventListener('scroll', handleScroll);
};
}
}, []);

Expand Down