Skip to content

Commit

Permalink
Fix: Chat scrolls down then up on mobile browsers
Browse files Browse the repository at this point in the history
  • Loading branch information
duogenesis committed Oct 25, 2023
1 parent a366449 commit 40c58fe
Showing 1 changed file with 18 additions and 5 deletions.
23 changes: 18 additions & 5 deletions components/conversation-screen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,15 @@ const ConversationScreen = ({navigation, route}) => {
>(null);
const hasScrolled = useRef(false);
const hasFetchedAll = useRef(false);
const hasFinishedFirstLoad = useRef(false);
const isFetchingNextPage = useRef(false);

const personId: number = route?.params?.personId;
const name: string = route?.params?.name;
const imageUuid: number = route?.params?.imageUuid;
const isDeletedUser: boolean = route?.params?.isDeletedUser;

const listRef = useRef<any>(null)
const listRef = useRef<ScrollView>(null)

const lastMamId = (() => {
if (!messages) return '';
Expand Down Expand Up @@ -121,11 +122,12 @@ const ConversationScreen = ({navigation, route}) => {
if (hasFetchedAll.current) {
return;
}

if (isFetchingNextPage.current) {
return;
}

isFetchingNextPage.current = true;

const fetchedMessages = await fetchConversation(personId, lastMamId);

isFetchingNextPage.current = false;
Expand All @@ -134,7 +136,7 @@ const ConversationScreen = ({navigation, route}) => {
if (fetchedMessages !== 'timeout') {
// Prevents the list from moving up to the newly added speech bubbles and
// triggering another fetch
if (listRef.current) listRef.current.scrollTo({y: 1});
if (listRef.current) listRef.current.scrollTo({y: 1, animated: false});

setMessages([...(fetchedMessages ?? []), ...(messages ?? [])]);

Expand All @@ -147,12 +149,20 @@ const ConversationScreen = ({navigation, route}) => {
setMessages(msgs => [...(msgs ?? []), msg]);
}, []);

const isCloseToTop = ({contentOffset}) => contentOffset.y < 20;
const isCloseToTop = ({contentOffset}) => contentOffset.y === 0;
const isCloseToBottom = ({layoutMeasurement, contentOffset, contentSize}) => {
const paddingToBottom = 20;
return layoutMeasurement.height + contentOffset.y >=
contentSize.height - paddingToBottom;
};

const onScroll = useCallback(({nativeEvent}) => {
if (isCloseToTop(nativeEvent)) {
if (isCloseToTop(nativeEvent) && hasFinishedFirstLoad.current) {
maybeLoadNextPage();
}
if (isCloseToBottom(nativeEvent)) {
hasFinishedFirstLoad.current = true;
}
}, [maybeLoadNextPage]);

useEffect(() => {
Expand Down Expand Up @@ -286,6 +296,9 @@ const ConversationScreen = ({navigation, route}) => {
onContentSizeChange={scrollToEnd}
onScroll={onScroll}
scrollEventThrottle={0}
maintainVisibleContentPosition={{
minIndexForVisible: 0
}}
contentContainerStyle={{
paddingTop: 10,
paddingBottom: 20,
Expand Down

0 comments on commit 40c58fe

Please sign in to comment.