mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-16 21:08:17 +00:00
🛞 refactor: Run Message Scrolling Inside @librechat/chat (#17752)
* refactor: Move Message Scrolling Into @librechat/chat * refactor: Run Message Scrolling in the Package Message List * test: Pin the Scroll Throttle's Coalescing Window
This commit is contained in:
parent
77cb38769b
commit
5ebba27035
19 changed files with 367 additions and 319 deletions
|
|
@ -10,7 +10,6 @@ import type {
|
|||
MessageCopyInput,
|
||||
ForkPreferences,
|
||||
ForkConversation,
|
||||
MessagesScrolling,
|
||||
MessageAudioProps,
|
||||
} from '@librechat/chat/react';
|
||||
import type { TMessage } from 'librechat-data-provider';
|
||||
|
|
@ -21,7 +20,6 @@ import {
|
|||
useCopyMessageToClipboard,
|
||||
} from '~/hooks';
|
||||
import useConversationSeen from '~/hooks/Conversations/useConversationSeen';
|
||||
import useMessageScrolling from '~/hooks/Messages/useMessageScrolling';
|
||||
import { useOptionalMessagesOperations } from './MessagesViewContext';
|
||||
import ThreadMessage from '~/components/Chat/Messages/Thread/Message';
|
||||
import MessageAudio from '~/components/Chat/Messages/MessageAudio';
|
||||
|
|
@ -72,12 +70,6 @@ function useAppForkConversation(): ForkConversation {
|
|||
);
|
||||
}
|
||||
|
||||
/** The app's scrolling hook, as the message list reads it. */
|
||||
function useScrolling(messagesTree: TMessage[] | null | undefined): MessagesScrolling {
|
||||
const { conversation, ...scrolling } = useMessageScrolling(messagesTree);
|
||||
return { ...scrolling, conversationId: conversation?.conversationId };
|
||||
}
|
||||
|
||||
function useAppMessageCopy({ message, searchResults, variant }: MessageCopyInput): MessageCopy {
|
||||
const clipboardSource = useMemo(() => getMessageClipboardSource(message), [message]);
|
||||
const copyToClipboard = useCopyMessageToClipboard({
|
||||
|
|
@ -110,7 +102,7 @@ function AppMessageAudio(props: MessageAudioProps) {
|
|||
}
|
||||
|
||||
/** What the message list reads from the app: the viewer's clock format and fork defaults, the
|
||||
* fork request, the rich-text copy, its scrolling, screenshot and seen reporting, the thread's
|
||||
* fork request, the rich-text copy, its auto-scroll preference, screenshot and seen reporting, the thread's
|
||||
* file map, and the row pieces that still live here: the message body and the subagent activity
|
||||
* group. Registered as the default when this module loads, so rows read it on every route, the
|
||||
* shared view included. */
|
||||
|
|
@ -123,7 +115,6 @@ export const appMessagesHost: MessagesHost = {
|
|||
useGetMessages: useAppGetMessages,
|
||||
useHasPendingTurn: useAppHasPendingTurn,
|
||||
renderMessageAudio: (props) => <AppMessageAudio {...props} />,
|
||||
useScrolling,
|
||||
useScreenshotTarget: () => useScreenshot().screenshotTargetRef,
|
||||
useAutoScroll: () => useAtomValue(autoScrollAtom),
|
||||
useConversationSeen,
|
||||
|
|
|
|||
|
|
@ -93,14 +93,6 @@ const host: MessagesHost = {
|
|||
useGetMessages: () => () => undefined,
|
||||
useHasPendingTurn: () => false,
|
||||
renderMessageAudio: () => null,
|
||||
useScrolling: () => ({
|
||||
contentRef: { current: null },
|
||||
scrollableRef: { current: null },
|
||||
messagesEndRef: { current: null },
|
||||
handleSmoothToRef: () => undefined,
|
||||
debouncedHandleScroll: () => undefined,
|
||||
handleNearBottomChange: () => undefined,
|
||||
}),
|
||||
useScreenshotTarget: () => undefined,
|
||||
useAutoScroll: () => false,
|
||||
useConversationSeen: () => () => undefined,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ export {
|
|||
getRenderedContentMaxScrollTop,
|
||||
reconcileMessageContentLayout,
|
||||
scheduleMessageContentLayoutReconcile,
|
||||
} from './messageLayout';
|
||||
} from '@librechat/chat/react';
|
||||
export { EXPAND_TRANSITION } from './useExpandCollapse';
|
||||
export { default as useAttachments } from './useAttachments';
|
||||
export { default as useSubmitMessage } from './useSubmitMessage';
|
||||
|
|
@ -24,5 +24,4 @@ export {
|
|||
useCopyMessageToClipboard,
|
||||
} from './useCopyToClipboard';
|
||||
export { default as useContentMetadata } from './useContentMetadata';
|
||||
export { default as useMessageScrolling } from './useMessageScrolling';
|
||||
export { default as useSmoothStreaming } from './useSmoothStreaming';
|
||||
|
|
|
|||
|
|
@ -33,7 +33,6 @@ export { default as useFocusTrap } from './useFocusTrap';
|
|||
export { default as useFavorites } from './useFavorites';
|
||||
export { default as useToolFavorites } from './useToolFavorites';
|
||||
export { default as useAdaptiveIcon } from './useAdaptiveIcon';
|
||||
export { default as useScrollToRef } from './useScrollToRef';
|
||||
export { default as useIsActiveItem } from './useIsActiveItem';
|
||||
export { default as useLocalStorage } from './useLocalStorage';
|
||||
export { default as useDocumentTitle } from './useDocumentTitle';
|
||||
|
|
|
|||
|
|
@ -1,74 +0,0 @@
|
|||
import { useEffect, useMemo, useRef } from 'react';
|
||||
import throttle from 'lodash/throttle';
|
||||
import type { RefObject } from 'react';
|
||||
|
||||
type TUseScrollToRef = {
|
||||
targetRef: RefObject<HTMLDivElement>;
|
||||
callback: () => void;
|
||||
smoothCallback: () => void;
|
||||
};
|
||||
|
||||
type ThrottledFunction = (() => void) & {
|
||||
cancel: () => void;
|
||||
flush: () => void;
|
||||
};
|
||||
|
||||
type ScrollToRefReturn = {
|
||||
scrollToRef?: ThrottledFunction;
|
||||
handleSmoothToRef: React.MouseEventHandler<HTMLButtonElement>;
|
||||
};
|
||||
|
||||
export default function useScrollToRef({
|
||||
targetRef,
|
||||
callback,
|
||||
smoothCallback,
|
||||
}: TUseScrollToRef): ScrollToRefReturn {
|
||||
const callbacksRef = useRef({ callback, smoothCallback });
|
||||
useEffect(() => {
|
||||
callbacksRef.current = { callback, smoothCallback };
|
||||
}, [callback, smoothCallback]);
|
||||
|
||||
const scrollToRef = useMemo(
|
||||
() =>
|
||||
throttle(
|
||||
() => {
|
||||
targetRef.current?.scrollIntoView({ behavior: 'instant' });
|
||||
callbacksRef.current.callback();
|
||||
},
|
||||
145,
|
||||
{ leading: true },
|
||||
),
|
||||
[targetRef],
|
||||
);
|
||||
|
||||
const scrollToRefSmooth = useMemo(
|
||||
() =>
|
||||
throttle(
|
||||
() => {
|
||||
targetRef.current?.scrollIntoView({ behavior: 'smooth' });
|
||||
callbacksRef.current.smoothCallback();
|
||||
},
|
||||
750,
|
||||
{ leading: true },
|
||||
),
|
||||
[targetRef],
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
scrollToRef.cancel();
|
||||
scrollToRefSmooth.cancel();
|
||||
},
|
||||
[scrollToRef, scrollToRefSmooth],
|
||||
);
|
||||
|
||||
const handleSmoothToRef: React.MouseEventHandler<HTMLButtonElement> = (e) => {
|
||||
e.preventDefault();
|
||||
scrollToRefSmooth();
|
||||
};
|
||||
|
||||
return {
|
||||
scrollToRef,
|
||||
handleSmoothToRef,
|
||||
};
|
||||
}
|
||||
|
|
@ -6,6 +6,13 @@ import {
|
|||
seedConversations,
|
||||
seedMessages,
|
||||
} from '../db';
|
||||
import {
|
||||
replyText,
|
||||
replyPrompt,
|
||||
sendMessage,
|
||||
MOCK_ENDPOINTS,
|
||||
selectMockEndpoint,
|
||||
} from '../helpers';
|
||||
import { getE2EUser } from '../../../setup/user';
|
||||
|
||||
/** Past the row count at which the thread mounts progressively instead of all at once. */
|
||||
|
|
@ -86,4 +93,41 @@ test.describe('long conversations', () => {
|
|||
await expect(latest).toBeInViewport();
|
||||
await expect(scrollControl).toBeHidden();
|
||||
});
|
||||
|
||||
test('opening a long conversation lands on its latest turn @scenario:long-conversation-opens-at-its-latest-turn', async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto(`/c/${conversationId}`);
|
||||
|
||||
const thread = page.locator(`[data-conversation-id="${conversationId}"]`);
|
||||
await expect(thread.locator('.message-render')).toHaveCount(TURNS);
|
||||
|
||||
await expect(
|
||||
thread.getByText(`Turn ${TURNS} of the long conversation`, { exact: true }),
|
||||
).toBeInViewport();
|
||||
await expect(
|
||||
thread.getByText('Turn 1 of the long conversation', { exact: true }),
|
||||
).not.toBeInViewport();
|
||||
});
|
||||
|
||||
test('a reply sent from the top of a long conversation is followed into view @scenario:sent-reply-is-followed-into-view', async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto(`/c/${conversationId}`);
|
||||
|
||||
const thread = page.locator(`[data-conversation-id="${conversationId}"]`);
|
||||
await expect(thread.locator('.message-render')).toHaveCount(TURNS);
|
||||
await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
|
||||
const first = thread.getByText('Turn 1 of the long conversation', { exact: true });
|
||||
await first.scrollIntoViewIfNeeded();
|
||||
await expect(first).toBeInViewport();
|
||||
|
||||
const label = randomUUID().slice(0, 8);
|
||||
await sendMessage(page, replyPrompt(label));
|
||||
|
||||
const reply = thread.getByText(replyText(label));
|
||||
await expect(reply).toBeVisible({ timeout: 30_000 });
|
||||
await expect(reply).toBeInViewport();
|
||||
await expect(first).not.toBeInViewport();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -19,14 +19,6 @@ export function createMessagesHost(overrides: Partial<MessagesHost> = {}): Messa
|
|||
useGetMessages: () => () => undefined,
|
||||
useHasPendingTurn: () => false,
|
||||
renderMessageAudio: () => null,
|
||||
useScrolling: () => ({
|
||||
contentRef: { current: null },
|
||||
scrollableRef: { current: null },
|
||||
messagesEndRef: { current: null },
|
||||
handleSmoothToRef: () => undefined,
|
||||
debouncedHandleScroll: () => undefined,
|
||||
handleNearBottomChange: () => undefined,
|
||||
}),
|
||||
useScreenshotTarget: () => undefined,
|
||||
useAutoScroll: () => false,
|
||||
useConversationSeen: () => () => undefined,
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import {
|
|||
RowMountProvider,
|
||||
useProgressiveRowMount,
|
||||
} from '../../react/messages/useProgressiveRowMount';
|
||||
import useMessageScrolling from '../../react/messages/useMessageScrolling';
|
||||
import useScrollbarGutter from '../../react/messages/useScrollbarGutter';
|
||||
import { useMessagesHost } from '../../react/messages/host';
|
||||
import { useChatContext } from '../../react/chat/context';
|
||||
|
|
@ -85,25 +86,40 @@ export default function MessagesView({
|
|||
const [currentEditId, setCurrentEditId] = useState<string | number | null>(-1);
|
||||
|
||||
const {
|
||||
conversationId,
|
||||
index,
|
||||
conversation,
|
||||
isSubmitting,
|
||||
abortScroll,
|
||||
setAbortScroll,
|
||||
latestMessageId,
|
||||
latestMessageDepth,
|
||||
messagesKey,
|
||||
} = useChatContext();
|
||||
const conversationId = conversation?.conversationId;
|
||||
const autoScroll = host.useAutoScroll();
|
||||
const {
|
||||
contentRef,
|
||||
scrollableRef,
|
||||
messagesEndRef,
|
||||
handleSmoothToRef,
|
||||
debouncedHandleScroll,
|
||||
handleNearBottomChange,
|
||||
} = host.useScrolling(messagesTree);
|
||||
} = useMessageScrolling({
|
||||
messagesTree,
|
||||
conversationId,
|
||||
isSubmitting,
|
||||
abortScroll,
|
||||
setAbortScroll,
|
||||
autoScroll,
|
||||
});
|
||||
|
||||
useScrollbarGutter(scrollableRef);
|
||||
|
||||
const { index, isSubmitting, latestMessageId, latestMessageDepth, messagesKey } =
|
||||
useChatContext();
|
||||
/** Re-arm from the conversation that owns the RENDERED tree: the app's conversation id lags
|
||||
* the route during warm-cache navigation, and keying off it would first mount the new tree
|
||||
* unwindowed, then narrow it after the fact, visibly unmounting rows the user is already
|
||||
* reading. An empty tree has no message to name its owner, so the route's key stands in. */
|
||||
const treeConversationId = messagesTree?.[0]?.conversationId ?? (messagesKey || conversationId);
|
||||
const autoScroll = host.useAutoScroll();
|
||||
|
||||
/** Direct measurement for the one trigger the observer cannot serve: after a messages
|
||||
* revalidation commits, the end marker may sit where no threshold was crossed, so no
|
||||
|
|
|
|||
|
|
@ -2,10 +2,10 @@
|
|||
* @jest-environment jsdom
|
||||
*/
|
||||
import { useRef } from 'react';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { TMessage } from 'librechat-data-provider';
|
||||
import type { MessagesHost, MessagesScrolling } from '../../../react/messages/host';
|
||||
import type { MessagesScrollButtonProps, MessagesViewProps } from '../MessagesView';
|
||||
import type { MessagesHost } from '../../../react/messages/host';
|
||||
import type { ChatContract } from '../../../react/chat/contract';
|
||||
import type { MessagePartsHost } from '../../../react/host';
|
||||
import { createMessagesHost } from '../../../__fixtures__/messagesHost';
|
||||
|
|
@ -22,42 +22,42 @@ const tree = [{ messageId: 'reply-1', conversationId: 'convo-1' }] as TMessage[]
|
|||
const partsHost = { useFontSize: () => 'text-base' } as unknown as MessagePartsHost;
|
||||
|
||||
function createHost(overrides: Partial<MessagesHost> = {}) {
|
||||
const scrolling: { current?: MessagesScrolling } = {};
|
||||
const reportNearBottom = jest.fn();
|
||||
const useConversationSeen = jest.fn<
|
||||
jest.Mock,
|
||||
[string | undefined, boolean, () => boolean | null, (messageId: string) => boolean]
|
||||
>(() => reportNearBottom);
|
||||
const host = createMessagesHost({
|
||||
useScrolling: () => {
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
const scrollableRef = useRef<HTMLDivElement>(null);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
scrolling.current = {
|
||||
conversationId: 'convo-1',
|
||||
contentRef,
|
||||
scrollableRef,
|
||||
messagesEndRef,
|
||||
handleSmoothToRef: jest.fn(),
|
||||
debouncedHandleScroll: jest.fn(),
|
||||
handleNearBottomChange: jest.fn(),
|
||||
};
|
||||
return scrolling.current;
|
||||
},
|
||||
useScreenshotTarget: () => useRef<HTMLDivElement>(null),
|
||||
useAutoScroll: () => false,
|
||||
useConversationSeen,
|
||||
...overrides,
|
||||
});
|
||||
return { host, scrolling, reportNearBottom, useConversationSeen };
|
||||
return { host, reportNearBottom, useConversationSeen };
|
||||
}
|
||||
|
||||
const contract = {
|
||||
index: 0,
|
||||
isSubmitting: false,
|
||||
latestMessageDepth: 0,
|
||||
messagesKey: 'convo-1',
|
||||
} as ChatContract;
|
||||
/** What the list's scrolling reads from the pane. */
|
||||
const scrollingInputs: Pick<ChatContract, 'conversation' | 'abortScroll' | 'setAbortScroll'> = {
|
||||
abortScroll: false,
|
||||
setAbortScroll: jest.fn(),
|
||||
conversation: {
|
||||
conversationId: 'convo-1',
|
||||
endpoint: null,
|
||||
title: null,
|
||||
createdAt: '2026-11-03T00:00:00.000Z',
|
||||
updatedAt: '2026-11-03T00:00:00.000Z',
|
||||
},
|
||||
};
|
||||
|
||||
const contract: ChatContract = Object.assign(
|
||||
{
|
||||
index: 0,
|
||||
isSubmitting: false,
|
||||
latestMessageDepth: 0,
|
||||
messagesKey: 'convo-1',
|
||||
} as ChatContract,
|
||||
scrollingInputs,
|
||||
);
|
||||
|
||||
function renderView(props: Partial<MessagesViewProps>, host: MessagesHost, chat = contract) {
|
||||
const view = (next: Partial<MessagesViewProps>) => (
|
||||
|
|
@ -144,13 +144,13 @@ describe('MessagesView', () => {
|
|||
});
|
||||
|
||||
it('wires the scroll control to the end marker and to both near-bottom listeners', () => {
|
||||
const { host, scrolling, reportNearBottom } = createHost();
|
||||
const { host, reportNearBottom } = createHost();
|
||||
let button: MessagesScrollButtonProps | undefined;
|
||||
const { container } = renderView(
|
||||
{
|
||||
renderScrollButton: (props) => {
|
||||
button = props;
|
||||
return null;
|
||||
return <button onClick={props.scrollHandler}>Jump</button>;
|
||||
},
|
||||
},
|
||||
host,
|
||||
|
|
@ -159,10 +159,19 @@ describe('MessagesView', () => {
|
|||
expect(button?.enabled).toBe(true);
|
||||
expect(button?.conversationId).toBe('convo-1');
|
||||
expect(button?.messagesEndRef.current).toBe(container.querySelector('#messages-end'));
|
||||
expect(button?.scrollHandler).toBe(scrolling.current?.handleSmoothToRef);
|
||||
expect(button?.scrollableRef.current).toBe(
|
||||
container.querySelector('#messages-end')?.closest('.scrollbar-gutter-stable'),
|
||||
);
|
||||
|
||||
const end = container.querySelector<HTMLElement>('#messages-end');
|
||||
const scrollIntoView = jest.fn();
|
||||
if (end) {
|
||||
end.scrollIntoView = scrollIntoView;
|
||||
}
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Jump' }));
|
||||
expect(scrollIntoView).toHaveBeenCalledWith({ behavior: 'smooth' });
|
||||
|
||||
button?.onNearBottomChange(false);
|
||||
expect(scrolling.current?.handleNearBottomChange).toHaveBeenCalledWith(false);
|
||||
expect(reportNearBottom).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
|
|
@ -192,10 +201,18 @@ describe('MessagesView', () => {
|
|||
});
|
||||
|
||||
it('listens to the scroll container and keeps native scroll anchoring outside a mount window', () => {
|
||||
const { host, scrolling } = createHost();
|
||||
renderView({}, host);
|
||||
let button: MessagesScrollButtonProps | undefined;
|
||||
renderView(
|
||||
{
|
||||
renderScrollButton: (props) => {
|
||||
button = props;
|
||||
return null;
|
||||
},
|
||||
},
|
||||
createHost().host,
|
||||
);
|
||||
|
||||
const scrollable = scrolling.current?.scrollableRef.current;
|
||||
const scrollable = button?.scrollableRef.current;
|
||||
expect(scrollable).toHaveClass('scrollbar-gutter-stable', 'overflow-y-auto');
|
||||
expect(scrollable).not.toHaveClass('[overflow-anchor:none]');
|
||||
});
|
||||
|
|
|
|||
|
|
@ -33,9 +33,6 @@ const host: MessagesHost = {
|
|||
useGetMessages: () => () => undefined,
|
||||
useHasPendingTurn: () => false,
|
||||
renderMessageAudio: () => null,
|
||||
useScrolling: () => {
|
||||
throw new Error('not used by the thread');
|
||||
},
|
||||
useScreenshotTarget: () => undefined,
|
||||
useAutoScroll: () => false,
|
||||
useConversationSeen: () => () => undefined,
|
||||
|
|
|
|||
|
|
@ -130,6 +130,11 @@ export { useComposerOverlay, composerOverlayCountFamily } from './react/overlay'
|
|||
export { default as useTimeTick } from './react/tick';
|
||||
export { default as useGenerationsByLatest } from './react/messages/generations';
|
||||
export type { Generations, TUseGenerations } from './react/messages/generations';
|
||||
export {
|
||||
reconcileMessageContentLayout,
|
||||
getRenderedContentMaxScrollTop,
|
||||
scheduleMessageContentLayoutReconcile,
|
||||
} from './react/messages/messageLayout';
|
||||
export {
|
||||
useMessagesHost,
|
||||
MessagesHostProvider,
|
||||
|
|
@ -145,7 +150,6 @@ export type {
|
|||
ForkPreferences,
|
||||
ForkConversation,
|
||||
ActivitySlotProps,
|
||||
MessagesScrolling,
|
||||
ReportNearBottom,
|
||||
MessageIconData,
|
||||
MessageIconProps,
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import { reconcileMessageContentLayout } from '../messageLayout';
|
||||
|
||||
function setRect(element: HTMLElement, rect: Partial<DOMRect>): void {
|
||||
|
|
@ -1,12 +1,10 @@
|
|||
import React from 'react';
|
||||
import { RecoilRoot } from 'recoil';
|
||||
import { Provider, createStore } from 'jotai';
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import { createContext, useContext } from 'react';
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { TConversation, TMessage } from 'librechat-data-provider';
|
||||
import {
|
||||
MessagesViewContext,
|
||||
type MessagesViewContextValue,
|
||||
} from '~/Providers/MessagesViewContext';
|
||||
import type { TMessage } from 'librechat-data-provider';
|
||||
import type { MessageScrollingInput } from '../useMessageScrolling';
|
||||
|
||||
type MockScrollToBottom = jest.Mock & {
|
||||
cancel: jest.Mock;
|
||||
|
|
@ -19,7 +17,7 @@ mockScrollToBottom.flush = jest.fn();
|
|||
const mockHandleSmoothToRef = jest.fn();
|
||||
let mockScrollCallback: (() => void) | undefined;
|
||||
|
||||
jest.mock('~/hooks/useScrollToRef', () => ({
|
||||
jest.mock('../useScrollToRef', () => ({
|
||||
__esModule: true,
|
||||
default: ({ callback }: { callback: () => void }) => {
|
||||
mockScrollCallback = callback;
|
||||
|
|
@ -36,7 +34,6 @@ jest.mock('../messageLayout', () => ({
|
|||
|
||||
import useMessageScrolling from '../useMessageScrolling';
|
||||
import { reconcileMessageContentLayout } from '../messageLayout';
|
||||
import { autoScrollAtom } from '~/store/autoScroll';
|
||||
|
||||
const mockReconcileMessageContentLayout = reconcileMessageContentLayout as jest.Mock;
|
||||
|
||||
|
|
@ -108,42 +105,34 @@ function setRect(element: HTMLElement, rect: Partial<DOMRect>): void {
|
|||
);
|
||||
}
|
||||
|
||||
const conversation = {
|
||||
conversationId: 'conversation-1',
|
||||
endpoint: 'openAI',
|
||||
model: 'gpt-4',
|
||||
} as TConversation;
|
||||
|
||||
const message = {
|
||||
messageId: 'message-1',
|
||||
conversationId: conversation.conversationId,
|
||||
conversationId: 'conversation-1',
|
||||
isCreatedByUser: false,
|
||||
} as TMessage;
|
||||
|
||||
function createContextValue(
|
||||
overrides: Partial<MessagesViewContextValue> = {},
|
||||
): MessagesViewContextValue {
|
||||
type ScrollingInputs = Omit<MessageScrollingInput, 'messagesTree'>;
|
||||
|
||||
function createContextValue(overrides: Partial<ScrollingInputs> = {}): ScrollingInputs {
|
||||
return {
|
||||
conversation,
|
||||
conversationId: conversation.conversationId,
|
||||
conversationId: 'conversation-1',
|
||||
isSubmitting: true,
|
||||
abortScroll: false,
|
||||
setAbortScroll: jest.fn(),
|
||||
ask: jest.fn(),
|
||||
regenerate: jest.fn(),
|
||||
handleContinue: jest.fn(),
|
||||
index: 0,
|
||||
latestMessageId: message.messageId,
|
||||
latestMessageDepth: 0,
|
||||
getMessages: jest.fn(),
|
||||
setMessages: jest.fn(),
|
||||
autoScroll: true,
|
||||
...overrides,
|
||||
} as MessagesViewContextValue;
|
||||
};
|
||||
}
|
||||
|
||||
/** Stands in for the message list, which feeds the hook from the chat context. */
|
||||
const ScrollingInputsContext = createContext<ScrollingInputs>(createContextValue());
|
||||
|
||||
function ScrollingHarness({ messagesTree }: { messagesTree?: TMessage[] | null }) {
|
||||
const { contentRef, scrollableRef, messagesEndRef, debouncedHandleScroll } =
|
||||
useMessageScrolling(messagesTree);
|
||||
const inputs = useContext(ScrollingInputsContext);
|
||||
const { contentRef, scrollableRef, messagesEndRef, debouncedHandleScroll } = useMessageScrolling({
|
||||
...inputs,
|
||||
messagesTree,
|
||||
});
|
||||
|
||||
return (
|
||||
<div ref={scrollableRef} onScroll={debouncedHandleScroll} data-testid="scrollable">
|
||||
|
|
@ -158,15 +147,13 @@ function renderScrolling({
|
|||
contextOverrides,
|
||||
messagesTree,
|
||||
}: {
|
||||
contextOverrides?: Partial<MessagesViewContextValue>;
|
||||
contextOverrides?: Partial<ScrollingInputs>;
|
||||
messagesTree?: TMessage[] | null;
|
||||
} = {}) {
|
||||
return render(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider value={createContextValue(contextOverrides)}>
|
||||
<ScrollingHarness messagesTree={messagesTree} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
<ScrollingInputsContext.Provider value={createContextValue(contextOverrides)}>
|
||||
<ScrollingHarness messagesTree={messagesTree} />
|
||||
</ScrollingInputsContext.Provider>,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -393,11 +380,9 @@ describe('useMessageScrolling resize reconciliation', () => {
|
|||
jest.useFakeTimers();
|
||||
try {
|
||||
const view = render(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider value={createContextValue({ isSubmitting: false })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
<ScrollingInputsContext.Provider value={createContextValue({ isSubmitting: false })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</ScrollingInputsContext.Provider>,
|
||||
);
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
|
|
@ -408,11 +393,9 @@ describe('useMessageScrolling resize reconciliation', () => {
|
|||
scrollable.scrollTop = 0;
|
||||
|
||||
view.rerender(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider value={createContextValue({ isSubmitting: true })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
<ScrollingInputsContext.Provider value={createContextValue({ isSubmitting: true })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</ScrollingInputsContext.Provider>,
|
||||
);
|
||||
|
||||
expect(scrollTo).toHaveBeenCalledWith({ top: 800, behavior: 'smooth' });
|
||||
|
|
@ -444,11 +427,9 @@ describe('useMessageScrolling resize reconciliation', () => {
|
|||
*/
|
||||
it('starts the turn once a stale abort flag clears', () => {
|
||||
const view = render(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider value={createContextValue({ isSubmitting: false })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
<ScrollingInputsContext.Provider value={createContextValue({ isSubmitting: false })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</ScrollingInputsContext.Provider>,
|
||||
);
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
|
|
@ -462,26 +443,22 @@ describe('useMessageScrolling resize reconciliation', () => {
|
|||
fireEvent.wheel(scrollable, { deltaY: -120 });
|
||||
|
||||
view.rerender(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider
|
||||
value={createContextValue({ isSubmitting: true, abortScroll: true })}
|
||||
>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
<ScrollingInputsContext.Provider
|
||||
value={createContextValue({ isSubmitting: true, abortScroll: true })}
|
||||
>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</ScrollingInputsContext.Provider>,
|
||||
);
|
||||
|
||||
expect(scrollTo).not.toHaveBeenCalled();
|
||||
|
||||
/** The connection opens and lowers the flag. */
|
||||
view.rerender(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider
|
||||
value={createContextValue({ isSubmitting: true, abortScroll: false })}
|
||||
>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
<ScrollingInputsContext.Provider
|
||||
value={createContextValue({ isSubmitting: true, abortScroll: false })}
|
||||
>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</ScrollingInputsContext.Provider>,
|
||||
);
|
||||
|
||||
expect(scrollTo).toHaveBeenCalledWith({ top: 800, behavior: 'smooth' });
|
||||
|
|
@ -489,11 +466,9 @@ describe('useMessageScrolling resize reconciliation', () => {
|
|||
|
||||
it('leaves the send glide alone while the answer streams in', () => {
|
||||
const view = render(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider value={createContextValue({ isSubmitting: false })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
<ScrollingInputsContext.Provider value={createContextValue({ isSubmitting: false })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</ScrollingInputsContext.Provider>,
|
||||
);
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
|
|
@ -504,11 +479,9 @@ describe('useMessageScrolling resize reconciliation', () => {
|
|||
scrollable.scrollTop = 0;
|
||||
|
||||
view.rerender(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider value={createContextValue({ isSubmitting: true })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
<ScrollingInputsContext.Provider value={createContextValue({ isSubmitting: true })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</ScrollingInputsContext.Provider>,
|
||||
);
|
||||
|
||||
expect(scrollTo).toHaveBeenCalledWith({ top: 800, behavior: 'smooth' });
|
||||
|
|
@ -516,11 +489,9 @@ describe('useMessageScrolling resize reconciliation', () => {
|
|||
/** The next delta of the answer arrives while the glide is still travelling. */
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 1100, configurable: true });
|
||||
view.rerender(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider value={createContextValue({ isSubmitting: true })}>
|
||||
<ScrollingHarness messagesTree={[message, message]} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
<ScrollingInputsContext.Provider value={createContextValue({ isSubmitting: true })}>
|
||||
<ScrollingHarness messagesTree={[message, message]} />
|
||||
</ScrollingInputsContext.Provider>,
|
||||
);
|
||||
|
||||
/** A plain follow would have written scrollTop outright and killed the animation. */
|
||||
|
|
@ -534,11 +505,9 @@ describe('useMessageScrolling resize reconciliation', () => {
|
|||
*/
|
||||
it('catches up to the new bottom when the glide lands', () => {
|
||||
const view = render(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider value={createContextValue({ isSubmitting: false })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
<ScrollingInputsContext.Provider value={createContextValue({ isSubmitting: false })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</ScrollingInputsContext.Provider>,
|
||||
);
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
|
|
@ -548,11 +517,9 @@ describe('useMessageScrolling resize reconciliation', () => {
|
|||
scrollable.scrollTop = 0;
|
||||
|
||||
view.rerender(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider value={createContextValue({ isSubmitting: true })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
<ScrollingInputsContext.Provider value={createContextValue({ isSubmitting: true })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</ScrollingInputsContext.Provider>,
|
||||
);
|
||||
|
||||
/** The whole answer arrives before the glide reports that it landed. */
|
||||
|
|
@ -597,23 +564,15 @@ describe('useMessageScrolling navigation landing', () => {
|
|||
];
|
||||
|
||||
const harness = (
|
||||
store: ReturnType<typeof createStore>,
|
||||
autoScroll: boolean,
|
||||
conversationId: string,
|
||||
messagesTree: TMessage[] | null,
|
||||
) => (
|
||||
<RecoilRoot>
|
||||
<Provider store={store}>
|
||||
<MessagesViewContext.Provider
|
||||
value={createContextValue({
|
||||
isSubmitting: false,
|
||||
conversation: { ...conversation, conversationId } as TConversation,
|
||||
conversationId,
|
||||
})}
|
||||
>
|
||||
<ScrollingHarness messagesTree={messagesTree} />
|
||||
</MessagesViewContext.Provider>
|
||||
</Provider>
|
||||
</RecoilRoot>
|
||||
<ScrollingInputsContext.Provider
|
||||
value={createContextValue({ isSubmitting: false, conversationId, autoScroll })}
|
||||
>
|
||||
<ScrollingHarness messagesTree={messagesTree} />
|
||||
</ScrollingInputsContext.Provider>
|
||||
);
|
||||
|
||||
function renderLanding(
|
||||
|
|
@ -621,13 +580,11 @@ describe('useMessageScrolling navigation landing', () => {
|
|||
messagesTree: TMessage[] | null,
|
||||
autoScroll = true,
|
||||
) {
|
||||
const store = createStore();
|
||||
store.set(autoScrollAtom, autoScroll);
|
||||
const view = render(harness(store, conversationId, messagesTree));
|
||||
const view = render(harness(autoScroll, conversationId, messagesTree));
|
||||
return {
|
||||
...view,
|
||||
rerenderWith: (nextId: string, nextTree: TMessage[] | null) =>
|
||||
view.rerender(harness(store, nextId, nextTree)),
|
||||
view.rerender(harness(autoScroll, nextId, nextTree)),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -1,3 +1,6 @@
|
|||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import { StrictMode, createRef, useRef } from 'react';
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { RefObject } from 'react';
|
||||
|
|
@ -98,6 +101,32 @@ describe('useScrollToRef lifecycle', () => {
|
|||
},
|
||||
);
|
||||
|
||||
it.each(scrollActions)(
|
||||
'coalesces a burst of $label calls into one trailing call, as lodash throttle does',
|
||||
({ label, interval }) => {
|
||||
const callback = jest.fn();
|
||||
render(<Harness callback={callback} smoothCallback={callback} />, { wrapper: StrictMode });
|
||||
screen.getByTestId('end').scrollIntoView = jest.fn();
|
||||
|
||||
fireEvent.click(screen.getByText(label));
|
||||
fireEvent.click(screen.getByText(label));
|
||||
fireEvent.click(screen.getByText(label));
|
||||
fireEvent.click(screen.getByText(label));
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
|
||||
act(() => jest.advanceTimersByTime(interval));
|
||||
expect(callback).toHaveBeenCalledTimes(2);
|
||||
|
||||
/** The trailing run opens a window of its own; with nothing queued in it, nothing more runs. */
|
||||
act(() => jest.advanceTimersByTime(interval * 3));
|
||||
expect(callback).toHaveBeenCalledTimes(2);
|
||||
|
||||
/** Once that window closes, the next call is a leading call again. */
|
||||
fireEvent.click(screen.getByText(label));
|
||||
expect(callback).toHaveBeenCalledTimes(3);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(scrollActions)('cancels queued $label work when the target ref changes', ({ label }) => {
|
||||
const callback = jest.fn();
|
||||
const previousRef = createRef<HTMLDivElement>();
|
||||
|
|
@ -10,24 +10,6 @@ import type {
|
|||
} from 'librechat-data-provider';
|
||||
import type { Dispatch, ReactNode, MouseEvent, RefObject, SetStateAction } from 'react';
|
||||
|
||||
/** The scroll machinery of the message list, as the app's scrolling hook drives it. */
|
||||
export type MessagesScrolling = {
|
||||
/** The conversation the scrolling follows. */
|
||||
conversationId?: string | null;
|
||||
/** Wraps the rendered thread. */
|
||||
contentRef: RefObject<HTMLDivElement>;
|
||||
/** The scroll container. */
|
||||
scrollableRef: RefObject<HTMLDivElement>;
|
||||
/** The zero-height marker after the last row. */
|
||||
messagesEndRef: RefObject<HTMLDivElement>;
|
||||
/** Scrolls smoothly to the end, from the scroll-to-bottom control. */
|
||||
handleSmoothToRef: (event: MouseEvent<HTMLButtonElement>) => void;
|
||||
/** The container's scroll listener. */
|
||||
debouncedHandleScroll: () => void;
|
||||
/** Reports whether the end marker is in view. */
|
||||
handleNearBottomChange: (isNearBottom: boolean) => void;
|
||||
};
|
||||
|
||||
/** What the message slot renders one visible row of the thread from. */
|
||||
export type MessageRowSlotProps = {
|
||||
message: TMessage;
|
||||
|
|
@ -152,14 +134,6 @@ export interface MessagesHost {
|
|||
useHasPendingTurn: (conversationId: string) => boolean;
|
||||
/** Renders the app's read-aloud control, or `null` while read-aloud is off. */
|
||||
renderMessageAudio: (props: MessageAudioProps) => ReactNode;
|
||||
/**
|
||||
* Drives the list's scrolling: follows the stream, lands on a conversation's end and keeps
|
||||
* the reader's position.
|
||||
*
|
||||
* @deprecated On arrival: a bridge to the app's `useMessageScrolling`, which reads the app's
|
||||
* messages providers, until it moves into this package and the list runs it itself.
|
||||
*/
|
||||
useScrolling: (messagesTree: TMessage[] | null | undefined) => MessagesScrolling;
|
||||
/** The element the app's conversation screenshot captures; none outside a screenshot provider. */
|
||||
useScreenshotTarget: () => RefObject<HTMLDivElement> | undefined;
|
||||
/** Whether the viewer asked the thread to follow new content to the bottom. */
|
||||
|
|
@ -196,27 +170,12 @@ const fallbackForkPreferences: ForkPreferences = {
|
|||
setRememberOption: noop,
|
||||
};
|
||||
|
||||
/** Scrolling with nothing behind it: live refs, inert handlers. */
|
||||
function useInertScrolling(): MessagesScrolling {
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
const scrollableRef = useRef<HTMLDivElement>(null);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
return {
|
||||
contentRef,
|
||||
scrollableRef,
|
||||
messagesEndRef,
|
||||
handleSmoothToRef: () => undefined,
|
||||
debouncedHandleScroll: () => undefined,
|
||||
handleNearBottomChange: () => undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const ignoreNearBottom: ReportNearBottom = () => undefined;
|
||||
|
||||
const noMessages = (): TMessage[] | undefined => undefined;
|
||||
|
||||
/** The host rows read outside any provider before an app registers one: locale clock, no slots,
|
||||
* no forking, no copying, no thread, no queued turn, no read-aloud, inert scrolling. */
|
||||
* no forking, no copying, no thread, no queued turn, no read-aloud. */
|
||||
const fallbackHost: MessagesHost = {
|
||||
useHour12: () => undefined,
|
||||
renderFiles: () => null,
|
||||
|
|
@ -226,7 +185,6 @@ const fallbackHost: MessagesHost = {
|
|||
useGetMessages: () => noMessages,
|
||||
useHasPendingTurn: () => false,
|
||||
renderMessageAudio: () => null,
|
||||
useScrolling: useInertScrolling,
|
||||
useScreenshotTarget: () => useRef<HTMLDivElement>(null),
|
||||
useAutoScroll: () => false,
|
||||
useConversationSeen: () => ignoreNearBottom,
|
||||
|
|
|
|||
|
|
@ -1,11 +1,41 @@
|
|||
import { useRef, useCallback, useEffect } from 'react';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { Constants } from 'librechat-data-provider';
|
||||
import type { Dispatch, MouseEvent, RefObject, SetStateAction } from 'react';
|
||||
import type { TMessage } from 'librechat-data-provider';
|
||||
import { useMessagesConversation, useMessagesSubmission } from '~/Providers';
|
||||
import type { ThrottledFunction } from './useScrollToRef';
|
||||
import { reconcileMessageContentLayout } from './messageLayout';
|
||||
import useScrollToRef from '~/hooks/useScrollToRef';
|
||||
import { autoScrollAtom } from '~/store/autoScroll';
|
||||
import useScrollToRef from './useScrollToRef';
|
||||
|
||||
/** What the list's scrolling follows: the rendered thread, its conversation, the pane's
|
||||
* submission state and the viewer's auto-scroll preference. */
|
||||
export type MessageScrollingInput = {
|
||||
messagesTree?: TMessage[] | null;
|
||||
conversationId?: string | null;
|
||||
isSubmitting: boolean;
|
||||
/** Whether the reader vetoed riding the stream for the current turn. */
|
||||
abortScroll: boolean;
|
||||
setAbortScroll: Dispatch<SetStateAction<boolean>>;
|
||||
/** Whether opening a conversation lands the reader on its newest message. */
|
||||
autoScroll: boolean;
|
||||
};
|
||||
|
||||
/** The scroll machinery of the message list. */
|
||||
export type MessageScrolling = {
|
||||
/** Wraps the rendered thread. */
|
||||
contentRef: RefObject<HTMLDivElement>;
|
||||
/** The scroll container. */
|
||||
scrollableRef: RefObject<HTMLDivElement>;
|
||||
/** The zero-height marker after the last row. */
|
||||
messagesEndRef: RefObject<HTMLDivElement>;
|
||||
/** Jumps to the end marker; absent until the target ref exists. */
|
||||
scrollToBottom?: ThrottledFunction;
|
||||
/** Scrolls smoothly to the end, from the scroll-to-bottom control. */
|
||||
handleSmoothToRef: (event: MouseEvent<HTMLButtonElement>) => void;
|
||||
/** The container's scroll listener. */
|
||||
debouncedHandleScroll: () => void;
|
||||
/** Reports whether the end marker is in view. */
|
||||
handleNearBottomChange: (isNearBottom: boolean) => void;
|
||||
};
|
||||
|
||||
const resizeFollowThreshold = 120;
|
||||
|
||||
|
|
@ -25,9 +55,16 @@ const prefersReducedMotion = () =>
|
|||
typeof window.matchMedia === 'function' &&
|
||||
window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
export default function useMessageScrolling(messagesTree?: TMessage[] | null) {
|
||||
const autoScroll = useAtomValue(autoScrollAtom);
|
||||
|
||||
/** Follows the stream, lands on a conversation's end once its rows mount, and keeps the
|
||||
* reader's position when they scroll away. */
|
||||
export default function useMessageScrolling({
|
||||
messagesTree,
|
||||
conversationId,
|
||||
isSubmitting,
|
||||
abortScroll,
|
||||
setAbortScroll,
|
||||
autoScroll,
|
||||
}: MessageScrollingInput): MessageScrolling {
|
||||
const scrollableRef = useRef<HTMLDivElement | null>(null);
|
||||
const contentRef = useRef<HTMLDivElement | null>(null);
|
||||
const messagesEndRef = useRef<HTMLDivElement | null>(null);
|
||||
|
|
@ -51,8 +88,6 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) {
|
|||
/** The conversation whose newest message has already been landed on, so the
|
||||
* stream deltas that follow cannot re-take a reader who scrolled away. */
|
||||
const landedConversationRef = useRef<string | null>(null);
|
||||
const { conversation, conversationId } = useMessagesConversation();
|
||||
const { setAbortScroll, isSubmitting, abortScroll } = useMessagesSubmission();
|
||||
|
||||
const getIsNearBottom = useCallback(() => {
|
||||
const scrollEl = scrollableRef.current;
|
||||
|
|
@ -134,7 +169,7 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) {
|
|||
* `Message` raises this on every wheel tick, downward ones included, so
|
||||
* it is set again on the way here; and the value this closure can see is
|
||||
* a render behind, so a conditional clear loses the race and leaves the
|
||||
* ride vetoed for the rest of the answer. Recoil no-ops an unchanged
|
||||
* ride vetoed for the rest of the answer. The setter no-ops an unchanged
|
||||
* write, so repeating it costs nothing. */
|
||||
setAbortScroll(false);
|
||||
}
|
||||
|
|
@ -409,7 +444,7 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) {
|
|||
|
||||
return () => {
|
||||
if (abortScroll === true) {
|
||||
scrollToBottom && scrollToBottom.cancel();
|
||||
scrollToBottom?.cancel();
|
||||
}
|
||||
};
|
||||
}, [isSubmitting, messagesTree, scrollToBottom, abortScroll, followBottom]);
|
||||
|
|
@ -420,7 +455,7 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) {
|
|||
* Keyed on the conversation whose rows are actually MOUNTED, not on the id
|
||||
* alone. The id reaches this hook a commit or more before the tree does, and
|
||||
* firing on it scrolled the outgoing thread to its end and then never ran
|
||||
* again — the reader was left wherever that put them, which on a long thread
|
||||
* again: the reader was left wherever that put them, which on a long thread
|
||||
* is the top. Waiting for the rendered tree to name the same conversation
|
||||
* costs nothing and is the only moment `messages-end` is where the reader
|
||||
* expects it.
|
||||
|
|
@ -469,7 +504,6 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) {
|
|||
}, [autoScroll, conversationId, messagesTree, scrollToBottom]);
|
||||
|
||||
return {
|
||||
conversation,
|
||||
contentRef,
|
||||
scrollableRef,
|
||||
messagesEndRef,
|
||||
98
packages/chat/src/react/messages/useScrollToRef.ts
Normal file
98
packages/chat/src/react/messages/useScrollToRef.ts
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
import { useEffect, useMemo, useRef } from 'react';
|
||||
import type { MouseEventHandler, RefObject } from 'react';
|
||||
|
||||
type TUseScrollToRef = {
|
||||
targetRef: RefObject<HTMLDivElement>;
|
||||
callback: () => void;
|
||||
smoothCallback: () => void;
|
||||
};
|
||||
|
||||
/** A throttled call that runs on the leading edge and once more on the trailing edge. */
|
||||
export type ThrottledFunction = (() => void) & {
|
||||
/** Drops the pending trailing call. */
|
||||
cancel: () => void;
|
||||
};
|
||||
|
||||
type ScrollToRefReturn = {
|
||||
scrollToRef?: ThrottledFunction;
|
||||
handleSmoothToRef: MouseEventHandler<HTMLButtonElement>;
|
||||
};
|
||||
|
||||
/** Runs `run` at once, then at most once per `wait` ms while calls keep arriving: a call
|
||||
* inside the window is deferred to the window's end, and that run opens the next window. */
|
||||
function throttle(run: () => void, wait: number): ThrottledFunction {
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pending = false;
|
||||
const closeWindow = () => {
|
||||
if (!pending) {
|
||||
timer = null;
|
||||
return;
|
||||
}
|
||||
pending = false;
|
||||
run();
|
||||
timer = setTimeout(closeWindow, wait);
|
||||
};
|
||||
const throttled = () => {
|
||||
if (timer != null) {
|
||||
pending = true;
|
||||
return;
|
||||
}
|
||||
run();
|
||||
timer = setTimeout(closeWindow, wait);
|
||||
};
|
||||
throttled.cancel = () => {
|
||||
if (timer != null) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
timer = null;
|
||||
pending = false;
|
||||
};
|
||||
return throttled;
|
||||
}
|
||||
|
||||
export default function useScrollToRef({
|
||||
targetRef,
|
||||
callback,
|
||||
smoothCallback,
|
||||
}: TUseScrollToRef): ScrollToRefReturn {
|
||||
const callbacksRef = useRef({ callback, smoothCallback });
|
||||
useEffect(() => {
|
||||
callbacksRef.current = { callback, smoothCallback };
|
||||
}, [callback, smoothCallback]);
|
||||
|
||||
const scrollToRef = useMemo(
|
||||
() =>
|
||||
throttle(() => {
|
||||
targetRef.current?.scrollIntoView({ behavior: 'instant' });
|
||||
callbacksRef.current.callback();
|
||||
}, 145),
|
||||
[targetRef],
|
||||
);
|
||||
|
||||
const scrollToRefSmooth = useMemo(
|
||||
() =>
|
||||
throttle(() => {
|
||||
targetRef.current?.scrollIntoView({ behavior: 'smooth' });
|
||||
callbacksRef.current.smoothCallback();
|
||||
}, 750),
|
||||
[targetRef],
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
scrollToRef.cancel();
|
||||
scrollToRefSmooth.cancel();
|
||||
},
|
||||
[scrollToRef, scrollToRefSmooth],
|
||||
);
|
||||
|
||||
const handleSmoothToRef: MouseEventHandler<HTMLButtonElement> = (e) => {
|
||||
e.preventDefault();
|
||||
scrollToRefSmooth();
|
||||
};
|
||||
|
||||
return {
|
||||
scrollToRef,
|
||||
handleSmoothToRef,
|
||||
};
|
||||
}
|
||||
|
|
@ -228,14 +228,6 @@ const messagesHost: MessagesHost = {
|
|||
useGetMessages: () => () => undefined,
|
||||
useHasPendingTurn: () => false,
|
||||
renderMessageAudio: () => null,
|
||||
useScrolling: () => ({
|
||||
contentRef: { current: null },
|
||||
scrollableRef: { current: null },
|
||||
messagesEndRef: { current: null },
|
||||
handleSmoothToRef: () => undefined,
|
||||
debouncedHandleScroll: () => undefined,
|
||||
handleNearBottomChange: () => undefined,
|
||||
}),
|
||||
useScreenshotTarget: () => undefined,
|
||||
useAutoScroll: () => false,
|
||||
useConversationSeen: () => () => undefined,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue