Skip to content

refactor: dont use useEffect anymore to control thread scroll #35818

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

Merged
merged 18 commits into from
Apr 16, 2025
Merged
Show file tree
Hide file tree
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
17 changes: 1 addition & 16 deletions apps/meteor/app/ui-utils/client/lib/RoomHistoryManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,6 @@ export function upsertMessageBulk(

const defaultLimit = parseInt(getConfig('roomListLimit') ?? '50') || 50;

const waitAfterFlush = (fn: () => void) => setTimeout(() => Tracker.afterFlush(fn), 10);

class RoomHistoryManagerClass extends Emitter {
private lastRequest?: Date;

Expand Down Expand Up @@ -156,8 +154,6 @@ class RoomHistoryManagerClass extends Emitter {

this.unqueue();

let previousHeight: number | undefined;
let scroll: number | undefined;
const { messages = [] } = result;
room.unreadNotLoaded.set(result.unreadNotLoaded);
room.firstUnread.set(result.firstUnread);
Expand All @@ -166,12 +162,7 @@ class RoomHistoryManagerClass extends Emitter {
room.oldestTs = messages[messages.length - 1].ts;
}

const wrapper = await waitForElement('.messages-box .wrapper [data-overlayscrollbars-viewport]');

if (wrapper) {
previousHeight = wrapper.scrollHeight;
scroll = wrapper.scrollTop;
}
await waitForElement('.messages-box .wrapper [data-overlayscrollbars-viewport]');

upsertMessageBulk({
msgs: messages.filter((msg) => msg.t !== 'command'),
Expand All @@ -194,12 +185,6 @@ class RoomHistoryManagerClass extends Emitter {
return this.getMore(rid);
}

waitAfterFlush(() => {
this.emit('loaded-messages');
const heightDiff = wrapper.scrollHeight - (previousHeight ?? NaN);
wrapper.scrollTop = (scroll ?? NaN) + heightDiff;
});

room.isLoading.set(false);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { IMessage } from '@rocket.chat/core-typings';
import type { KeyboardEvent, MouseEvent, RefObject } from 'react';
import type { KeyboardEvent, MouseEvent, MutableRefObject } from 'react';
import { createContext, useContext } from 'react';

export type MessageListContextValue = {
Expand All @@ -25,7 +25,7 @@ export type MessageListContextValue = {
showColors: boolean;
jumpToMessageParam?: string;
username: string | undefined;
messageListRef?: RefObject<HTMLElement>;
messageListRef?: MutableRefObject<HTMLElement | undefined>;
};

export const MessageListContext = createContext<MessageListContextValue>({
Expand All @@ -43,7 +43,7 @@ export const MessageListContext = createContext<MessageListContextValue>({
showUsername: false,
showColors: false,
username: undefined,
messageListRef: { current: null },
messageListRef: { current: undefined },
});

export const useShowTranslated: MessageListContextValue['useShowTranslated'] = (...args) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,48 +3,69 @@ import { useRouter } from '@rocket.chat/ui-contexts';
import { useCallback } from 'react';

import { useMessageListJumpToMessageParam, useMessageListRef } from '../../../../components/message/list/MessageListContext';
import { useSafeRefCallback } from '../../../../hooks/useSafeRefCallback';
import { setHighlightMessage, clearHighlightMessage } from '../providers/messageHighlightSubscription';

// this is an arbitrary value so that there's a gap between the header and the message;
const SCROLL_EXTRA_OFFSET = 60;

export const useJumpToMessage = (messageId: IMessage['_id']) => {
const jumpToMessageParam = useMessageListJumpToMessageParam();
const listRef = useMessageListRef();
const router = useRouter();

const ref = useCallback(
(node: HTMLElement | null) => {
if (!node || !scroll) {
return;
}
setTimeout(() => {
if (listRef?.current) {
const wrapper = listRef.current;
const containerRect = wrapper.getBoundingClientRect();
const messageRect = node.getBoundingClientRect();

const offset = messageRect.top - containerRect.top;
const scrollPosition = wrapper.scrollTop;
const newScrollPosition = scrollPosition + offset - SCROLL_EXTRA_OFFSET;

wrapper.scrollTo({ top: newScrollPosition, behavior: 'smooth' });
const ref = useSafeRefCallback(
useCallback(
(node: HTMLElement | null) => {
if (!node || !scroll) {
return;
}

const { msg: _, ...search } = router.getSearchParameters();
router.navigate(
if (listRef) {
listRef.current = node;
}

node.scrollIntoView({
behavior: 'smooth',
block: 'center',
});
const handleScroll = () => {
const { msg: _, ...search } = router.getSearchParameters();
router.navigate(
{
pathname: router.getLocationPathname(),
search,
},
{ replace: true },
);
setTimeout(clearHighlightMessage, 2000);
};

const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
handleScroll();
}
});
},
{
pathname: router.getLocationPathname(),
search,
threshold: 0.1,
},
{ replace: true },
);

observer.observe(node);

setHighlightMessage(messageId);
setTimeout(clearHighlightMessage, 2000);
}, 500);
},
[listRef, messageId, router],

return () => {
observer.disconnect();
if (listRef) {
listRef.current = undefined;
}
};
},
[listRef, messageId, router],
),
);

if (jumpToMessageParam !== messageId) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { isThreadMainMessage } from '@rocket.chat/core-typings';
import { useLayout, useUser, useUserPreference, useSetting, useEndpoint, useSearchParameter } from '@rocket.chat/ui-contexts';
import type { ReactNode, RefObject } from 'react';
import type { MutableRefObject, ReactNode } from 'react';
import { useMemo, memo } from 'react';

import { getRegexHighlight, getRegexHighlightUrl } from '../../../../../app/highlight-words/client/helper';
Expand All @@ -15,7 +15,7 @@ import { useLoadSurroundingMessages } from '../hooks/useLoadSurroundingMessages'

type MessageListProviderProps = {
children: ReactNode;
messageListRef?: RefObject<HTMLElement>;
messageListRef?: MutableRefObject<HTMLElement | undefined>;
attachmentDimension?: {
width?: number;
height?: number;
Expand Down
9 changes: 3 additions & 6 deletions apps/meteor/client/views/room/body/RoomBody.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Box } from '@rocket.chat/fuselage';
import { useMergedRefs } from '@rocket.chat/fuselage-hooks';
import { usePermission, useRole, useSetting, useTranslation, useUser, useUserPreference } from '@rocket.chat/ui-contexts';
import type { MouseEvent, ReactElement } from 'react';
import { memo, useCallback, useMemo, useRef } from 'react';
import { memo, useCallback, useMemo } from 'react';

import DropTargetOverlay from './DropTargetOverlay';
import JumpToRecentMessageButton from './JumpToRecentMessageButton';
Expand Down Expand Up @@ -81,8 +81,6 @@ const RoomBody = (): ReactElement => {
return subscribed;
}, [allowAnonymousRead, canPreviewChannelRoom, room, subscribed]);

const innerBoxRef = useRef<HTMLDivElement | null>(null);

const {
wrapperRef: unreadBarWrapperRef,
innerRef: unreadBarInnerRef,
Expand All @@ -93,7 +91,7 @@ const RoomBody = (): ReactElement => {

const { innerRef: dateScrollInnerRef, bubbleRef, listStyle, ...bubbleDate } = useDateScroll();

const { innerRef: isAtBottomInnerRef, atBottomRef, sendToBottom, sendToBottomIfNecessary, isAtBottom } = useListIsAtBottom();
const { innerRef: isAtBottomInnerRef, atBottomRef, sendToBottom, sendToBottomIfNecessary, isAtBottom, jumpToRef } = useListIsAtBottom();

const { innerRef: getMoreInnerRef } = useGetMore(room._id, atBottomRef);

Expand All @@ -118,7 +116,6 @@ const RoomBody = (): ReactElement => {

const innerRef = useMergedRefs(
dateScrollInnerRef,
innerBoxRef,
restoreScrollPositionInnerRef,
isAtBottomInnerRef,
newMessagesScrollRef,
Expand Down Expand Up @@ -245,7 +242,7 @@ const RoomBody = (): ReactElement => {
)}
</>
) : null}
<MessageList rid={room._id} messageListRef={innerBoxRef} />
<MessageList rid={room._id} messageListRef={jumpToRef} />
{hasMoreNextMessages ? (
<li className='load-more'>{isLoadingMoreMessages ? <LoadingMessagesIndicator /> : null}</li>
) : null}
Expand Down
9 changes: 3 additions & 6 deletions apps/meteor/client/views/room/body/RoomBodyV2.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Box } from '@rocket.chat/fuselage';
import { useMergedRefs } from '@rocket.chat/fuselage-hooks';
import { usePermission, useRole, useSetting, useTranslation, useUser, useUserPreference } from '@rocket.chat/ui-contexts';
import type { MouseEvent, ReactElement } from 'react';
import { memo, useCallback, useMemo, useRef } from 'react';
import { memo, useCallback, useMemo } from 'react';

import { isTruthy } from '../../../../lib/isTruthy';
import { CustomScrollbars } from '../../../components/CustomScrollbars';
Expand Down Expand Up @@ -81,8 +81,6 @@ const RoomBody = (): ReactElement => {
return subscribed;
}, [allowAnonymousRead, canPreviewChannelRoom, room, subscribed]);

const innerBoxRef = useRef<HTMLDivElement | null>(null);

const {
wrapperRef,
innerRef: unreadBarInnerRef,
Expand All @@ -93,7 +91,7 @@ const RoomBody = (): ReactElement => {

const { innerRef: dateScrollInnerRef, bubbleRef, listStyle, ...bubbleDate } = useDateScroll();

const { innerRef: isAtBottomInnerRef, atBottomRef, sendToBottom, sendToBottomIfNecessary, isAtBottom } = useListIsAtBottom();
const { innerRef: isAtBottomInnerRef, atBottomRef, sendToBottom, sendToBottomIfNecessary, isAtBottom, jumpToRef } = useListIsAtBottom();

const { innerRef: getMoreInnerRef } = useGetMore(room._id, atBottomRef);

Expand All @@ -118,7 +116,6 @@ const RoomBody = (): ReactElement => {

const innerRef = useMergedRefs(
dateScrollInnerRef,
innerBoxRef,
restoreScrollPositionInnerRef,
isAtBottomInnerRef,
newMessagesScrollRef,
Expand Down Expand Up @@ -248,7 +245,7 @@ const RoomBody = (): ReactElement => {
)}
</>
) : null}
<MessageList rid={room._id} messageListRef={innerBoxRef} />
<MessageList rid={room._id} messageListRef={jumpToRef} />
{hasMoreNextMessages ? (
<li className='load-more'>{isLoadingMoreMessages ? <LoadingMessagesIndicator /> : null}</li>
) : null}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,18 @@ import { useSafeRefCallback } from '../../../../hooks/useSafeRefCallback';
export const useListIsAtBottom = () => {
const atBottomRef = useRef(true);

const jumpToRef = useRef<HTMLElement>(undefined);

const innerBoxRef = useRef<HTMLDivElement | null>(null);

const sendToBottom = useCallback(() => {
innerBoxRef.current?.scrollTo({ left: 30, top: innerBoxRef.current?.scrollHeight });
}, []);

const sendToBottomIfNecessary = useCallback(() => {
if (jumpToRef.current) {
atBottomRef.current = false;
}
if (atBottomRef.current === true) {
sendToBottom();
}
Expand All @@ -42,6 +47,9 @@ export const useListIsAtBottom = () => {
}

const observer = new ResizeObserver(() => {
if (jumpToRef.current) {
atBottomRef.current = false;
}
if (atBottomRef.current === true) {
node.scrollTo({ left: 30, top: node.scrollHeight });
}
Expand Down Expand Up @@ -72,5 +80,6 @@ export const useListIsAtBottom = () => {
sendToBottom,
sendToBottomIfNecessary,
isAtBottom,
jumpToRef,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,22 @@ describe('useRestoreScrollPosition', () => {
expect(mockElement.removeEventListener).toHaveBeenCalledWith('scroll', expect.any(Function));
});

it('should not restore scroll position if already at bottom', () => {
(RoomManager.getStore as jest.Mock).mockReturnValue({ scroll: 100, atBottom: true });
it('should do nothing if no previous scroll position is stored', () => {
(RoomManager.getStore as jest.Mock).mockReturnValue({ atBottom: true });

const mockElement = {
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
scrollHeight: 800,
scrollTop: 123,
};

const useRefSpy = jest.spyOn(React, 'useRef').mockReturnValueOnce({ current: mockElement });

const { unmount } = renderHook(() => useRestoreScrollPosition());

expect(useRefSpy).toHaveBeenCalledWith(null);
expect(mockElement).toHaveProperty('scrollTop', 800);
expect(mockElement).toHaveProperty('scrollTop', 123);
expect(mockElement).not.toHaveProperty('scrollLeft');

unmount();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,9 @@ export function useRestoreScrollPosition() {

const store = RoomManager.getStore(roomId);

if (store?.scroll && !store.atBottom) {
if (store?.scroll !== undefined && !store.atBottom) {
ref.current.scrollTop = store.scroll;
ref.current.scrollLeft = 30;
} else {
ref.current.scrollTop = ref.current.scrollHeight;
}
}, [roomId]);

Expand Down
Loading
Loading