@@ -158,15 +147,13 @@ function renderScrolling({
contextOverrides,
messagesTree,
}: {
- contextOverrides?: Partial
;
+ contextOverrides?: Partial;
messagesTree?: TMessage[] | null;
} = {}) {
return render(
-
-
-
-
- ,
+
+
+ ,
);
}
@@ -393,11 +380,9 @@ describe('useMessageScrolling resize reconciliation', () => {
jest.useFakeTimers();
try {
const view = render(
-
-
-
-
- ,
+
+
+ ,
);
const scrollable = screen.getByTestId('scrollable');
@@ -408,11 +393,9 @@ describe('useMessageScrolling resize reconciliation', () => {
scrollable.scrollTop = 0;
view.rerender(
-
-
-
-
- ,
+
+
+ ,
);
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(
-
-
-
-
- ,
+
+
+ ,
);
const scrollable = screen.getByTestId('scrollable');
@@ -462,26 +443,22 @@ describe('useMessageScrolling resize reconciliation', () => {
fireEvent.wheel(scrollable, { deltaY: -120 });
view.rerender(
-
-
-
-
- ,
+
+
+ ,
);
expect(scrollTo).not.toHaveBeenCalled();
/** The connection opens and lowers the flag. */
view.rerender(
-
-
-
-
- ,
+
+
+ ,
);
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(
-
-
-
-
- ,
+
+
+ ,
);
const scrollable = screen.getByTestId('scrollable');
@@ -504,11 +479,9 @@ describe('useMessageScrolling resize reconciliation', () => {
scrollable.scrollTop = 0;
view.rerender(
-
-
-
-
- ,
+
+
+ ,
);
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(
-
-
-
-
- ,
+
+
+ ,
);
/** 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(
-
-
-
-
- ,
+
+
+ ,
);
const scrollable = screen.getByTestId('scrollable');
@@ -548,11 +517,9 @@ describe('useMessageScrolling resize reconciliation', () => {
scrollable.scrollTop = 0;
view.rerender(
-
-
-
-
- ,
+
+
+ ,
);
/** The whole answer arrives before the glide reports that it landed. */
@@ -597,23 +564,15 @@ describe('useMessageScrolling navigation landing', () => {
];
const harness = (
- store: ReturnType,
+ autoScroll: boolean,
conversationId: string,
messagesTree: TMessage[] | null,
) => (
-
-
-
-
-
-
-
+
+
+
);
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)),
};
}
diff --git a/client/src/hooks/__tests__/useScrollToRef.spec.tsx b/packages/chat/src/react/messages/__tests__/useScrollToRef.spec.tsx
similarity index 79%
rename from client/src/hooks/__tests__/useScrollToRef.spec.tsx
rename to packages/chat/src/react/messages/__tests__/useScrollToRef.spec.tsx
index 5466eb415c..ddb2b52821 100644
--- a/client/src/hooks/__tests__/useScrollToRef.spec.tsx
+++ b/packages/chat/src/react/messages/__tests__/useScrollToRef.spec.tsx
@@ -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(, { 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();
diff --git a/packages/chat/src/react/messages/host.tsx b/packages/chat/src/react/messages/host.tsx
index 3bccafb19b..8603a162c9 100644
--- a/packages/chat/src/react/messages/host.tsx
+++ b/packages/chat/src/react/messages/host.tsx
@@ -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;
- /** The scroll container. */
- scrollableRef: RefObject;
- /** The zero-height marker after the last row. */
- messagesEndRef: RefObject;
- /** Scrolls smoothly to the end, from the scroll-to-bottom control. */
- handleSmoothToRef: (event: MouseEvent) => 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 | 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(null);
- const scrollableRef = useRef(null);
- const messagesEndRef = useRef(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(null),
useAutoScroll: () => false,
useConversationSeen: () => ignoreNearBottom,
diff --git a/client/src/hooks/Messages/messageLayout.ts b/packages/chat/src/react/messages/messageLayout.ts
similarity index 100%
rename from client/src/hooks/Messages/messageLayout.ts
rename to packages/chat/src/react/messages/messageLayout.ts
diff --git a/client/src/hooks/Messages/useMessageScrolling.ts b/packages/chat/src/react/messages/useMessageScrolling.ts
similarity index 90%
rename from client/src/hooks/Messages/useMessageScrolling.ts
rename to packages/chat/src/react/messages/useMessageScrolling.ts
index cd5ae9df63..7d51d86224 100644
--- a/client/src/hooks/Messages/useMessageScrolling.ts
+++ b/packages/chat/src/react/messages/useMessageScrolling.ts
@@ -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>;
+ /** 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;
+ /** The scroll container. */
+ scrollableRef: RefObject;
+ /** The zero-height marker after the last row. */
+ messagesEndRef: RefObject;
+ /** 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) => 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(null);
const contentRef = useRef(null);
const messagesEndRef = useRef(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(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,
diff --git a/packages/chat/src/react/messages/useScrollToRef.ts b/packages/chat/src/react/messages/useScrollToRef.ts
new file mode 100644
index 0000000000..d558e59ece
--- /dev/null
+++ b/packages/chat/src/react/messages/useScrollToRef.ts
@@ -0,0 +1,98 @@
+import { useEffect, useMemo, useRef } from 'react';
+import type { MouseEventHandler, RefObject } from 'react';
+
+type TUseScrollToRef = {
+ targetRef: RefObject;
+ 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;
+};
+
+/** 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 | 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 = (e) => {
+ e.preventDefault();
+ scrollToRefSmooth();
+ };
+
+ return {
+ scrollToRef,
+ handleSmoothToRef,
+ };
+}
diff --git a/packages/chat/test/consumer.spec.tsx b/packages/chat/test/consumer.spec.tsx
index de61ccf649..36f7efc270 100644
--- a/packages/chat/test/consumer.spec.tsx
+++ b/packages/chat/test/consumer.spec.tsx
@@ -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,