ChatMessageList: fix initial scroll position

This commit is contained in:
Alex Gleason 2022-06-17 16:50:18 -05:00
parent a7e5281098
commit bf01c42397
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
1 changed files with 34 additions and 23 deletions

View File

@ -6,7 +6,7 @@ import {
} from 'immutable';
import escape from 'lodash/escape';
import throttle from 'lodash/throttle';
import React, { useState, useEffect, useRef } from 'react';
import React, { useState, useEffect, useRef, useLayoutEffect, useMemo } from 'react';
import { useIntl, defineMessages } from 'react-intl';
import { createSelector } from 'reselect';
@ -78,7 +78,10 @@ const ChatMessageList: React.FC<IChatMessageList> = ({ chatId, chatMessageIds })
const node = useRef<HTMLDivElement>(null);
const messagesEnd = useRef<HTMLDivElement>(null);
const lastComputedScroll = useRef<number>(0);
const lastComputedScroll = useRef<number | undefined>(undefined);
const scrollBottom = useRef<number | undefined>(undefined);
const initialCount = useMemo(() => chatMessages.count(), []);
const scrollToBottom = () => {
messagesEnd.current?.scrollIntoView(false);
@ -141,37 +144,45 @@ const ChatMessageList: React.FC<IChatMessageList> = ({ chatId, chatMessageIds })
};
}, []);
// const getScrollBottom = (): number | undefined => {
// if (node.current) {
// const { scrollHeight, scrollTop } = node.current;
// return scrollHeight - scrollTop;
// }
//
// return undefined;
// };
useLayoutEffect(() => {
if (node.current) {
const { scrollHeight, scrollTop } = node.current;
scrollBottom.current = scrollHeight - scrollTop;
}
});
// const restoreScrollPosition = (scrollBottom: number) => {
// if (node.current) {
// lastComputedScroll.current = node.current.scrollHeight - scrollBottom;
// node.current.scrollTop = lastComputedScroll.current;
// }
// };
const restoreScrollPosition = () => {
if (node.current && scrollBottom.current) {
lastComputedScroll.current = node.current.scrollHeight - scrollBottom.current;
node.current.scrollTop = lastComputedScroll.current;
}
};
// Stick scrollbar to bottom.
useEffect(() => {
if (isNearBottom() || initialLoad) {
if (isNearBottom()) {
scrollToBottom();
}
// First load.
if (chatMessages.count() !== initialCount) {
setInitialLoad(false);
setIsLoading(false);
scrollToBottom();
}
}, [chatMessages.count()]);
useEffect(() => {
scrollToBottom();
}, [messagesEnd.current]);
// History added.
useEffect(() => {
// Retain scroll bar position when loading old messages
// restoreScrollPosition(scrollBottom);
setIsLoading(false);
setInitialLoad(false);
}, [chatMessages.getIn([0, 'id'])]);
// Retain scroll bar position when loading old messages.
if (!initialLoad) {
restoreScrollPosition();
}
}, [chatMessageIds.first()]);
const handleLoadMore = () => {
const maxId = chatMessages.getIn([0, 'id']) as string;