mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-21 07:23:11 +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,
|
||||
|
|
|
|||
|
|
@ -1,42 +0,0 @@
|
|||
import { reconcileMessageContentLayout } from '../messageLayout';
|
||||
|
||||
function setRect(element: HTMLElement, rect: Partial<DOMRect>): void {
|
||||
element.getBoundingClientRect = jest.fn(
|
||||
() =>
|
||||
({
|
||||
x: rect.x ?? 0,
|
||||
y: rect.y ?? 0,
|
||||
top: rect.top ?? 0,
|
||||
left: rect.left ?? 0,
|
||||
right: rect.right ?? 0,
|
||||
bottom: rect.bottom ?? 0,
|
||||
width: rect.width ?? 0,
|
||||
height: rect.height ?? 0,
|
||||
toJSON: () => ({}),
|
||||
}) as DOMRect,
|
||||
);
|
||||
}
|
||||
|
||||
describe('message layout reconciliation', () => {
|
||||
it('clamps to the rendered content bottom when the scroll container is still oversized', () => {
|
||||
const scrollable = document.createElement('div');
|
||||
const content = document.createElement('div');
|
||||
const target = document.createElement('button');
|
||||
|
||||
scrollable.className = 'scrollbar-gutter-stable';
|
||||
content.append(target);
|
||||
scrollable.append(content);
|
||||
document.body.append(scrollable);
|
||||
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });
|
||||
Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });
|
||||
scrollable.scrollTop = 700;
|
||||
setRect(scrollable, { top: 0, bottom: 200, height: 200 });
|
||||
setRect(content, { top: -700, bottom: -200, height: 500 });
|
||||
|
||||
expect(reconcileMessageContentLayout(target)).toBe(true);
|
||||
expect(scrollable.scrollTop).toBe(300);
|
||||
|
||||
document.body.removeChild(scrollable);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,700 +0,0 @@
|
|||
import React from 'react';
|
||||
import { RecoilRoot } from 'recoil';
|
||||
import { Provider, createStore } from 'jotai';
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { TConversation, TMessage } from 'librechat-data-provider';
|
||||
import {
|
||||
MessagesViewContext,
|
||||
type MessagesViewContextValue,
|
||||
} from '~/Providers/MessagesViewContext';
|
||||
|
||||
type MockScrollToBottom = jest.Mock & {
|
||||
cancel: jest.Mock;
|
||||
flush: jest.Mock;
|
||||
};
|
||||
|
||||
const mockScrollToBottom = jest.fn() as MockScrollToBottom;
|
||||
mockScrollToBottom.cancel = jest.fn();
|
||||
mockScrollToBottom.flush = jest.fn();
|
||||
const mockHandleSmoothToRef = jest.fn();
|
||||
let mockScrollCallback: (() => void) | undefined;
|
||||
|
||||
jest.mock('~/hooks/useScrollToRef', () => ({
|
||||
__esModule: true,
|
||||
default: ({ callback }: { callback: () => void }) => {
|
||||
mockScrollCallback = callback;
|
||||
return {
|
||||
scrollToRef: mockScrollToBottom,
|
||||
handleSmoothToRef: mockHandleSmoothToRef,
|
||||
};
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock('../messageLayout', () => ({
|
||||
reconcileMessageContentLayout: jest.fn(),
|
||||
}));
|
||||
|
||||
import useMessageScrolling from '../useMessageScrolling';
|
||||
import { reconcileMessageContentLayout } from '../messageLayout';
|
||||
import { autoScrollAtom } from '~/store/autoScroll';
|
||||
|
||||
const mockReconcileMessageContentLayout = reconcileMessageContentLayout as jest.Mock;
|
||||
|
||||
class MockResizeObserver {
|
||||
static instances: MockResizeObserver[] = [];
|
||||
|
||||
static reset() {
|
||||
MockResizeObserver.instances = [];
|
||||
}
|
||||
|
||||
static last(): MockResizeObserver | undefined {
|
||||
return MockResizeObserver.instances[MockResizeObserver.instances.length - 1];
|
||||
}
|
||||
|
||||
readonly callback: ResizeObserverCallback;
|
||||
observe = jest.fn();
|
||||
unobserve = jest.fn();
|
||||
disconnect = jest.fn();
|
||||
|
||||
constructor(callback: ResizeObserverCallback) {
|
||||
this.callback = callback;
|
||||
MockResizeObserver.instances.push(this);
|
||||
}
|
||||
|
||||
trigger() {
|
||||
this.callback([], this as unknown as ResizeObserver);
|
||||
}
|
||||
}
|
||||
|
||||
class MockIntersectionObserver {
|
||||
static instances: MockIntersectionObserver[] = [];
|
||||
|
||||
static reset() {
|
||||
MockIntersectionObserver.instances = [];
|
||||
}
|
||||
|
||||
readonly callback: IntersectionObserverCallback;
|
||||
observe = jest.fn();
|
||||
unobserve = jest.fn();
|
||||
disconnect = jest.fn();
|
||||
takeRecords = jest.fn(() => []);
|
||||
|
||||
constructor(callback: IntersectionObserverCallback) {
|
||||
this.callback = callback;
|
||||
MockIntersectionObserver.instances.push(this);
|
||||
}
|
||||
}
|
||||
|
||||
/** Matches the hook's glide fallback, the window in which a landing is still pending. */
|
||||
const glideWindow = 700;
|
||||
|
||||
const originalResizeObserver = global.ResizeObserver;
|
||||
const originalIntersectionObserver = global.IntersectionObserver;
|
||||
|
||||
function setRect(element: HTMLElement, rect: Partial<DOMRect>): void {
|
||||
element.getBoundingClientRect = jest.fn(
|
||||
() =>
|
||||
({
|
||||
x: rect.x ?? 0,
|
||||
y: rect.y ?? 0,
|
||||
top: rect.top ?? 0,
|
||||
left: rect.left ?? 0,
|
||||
right: rect.right ?? 0,
|
||||
bottom: rect.bottom ?? 0,
|
||||
width: rect.width ?? 0,
|
||||
height: rect.height ?? 0,
|
||||
toJSON: () => ({}),
|
||||
}) as DOMRect,
|
||||
);
|
||||
}
|
||||
|
||||
const conversation = {
|
||||
conversationId: 'conversation-1',
|
||||
endpoint: 'openAI',
|
||||
model: 'gpt-4',
|
||||
} as TConversation;
|
||||
|
||||
const message = {
|
||||
messageId: 'message-1',
|
||||
conversationId: conversation.conversationId,
|
||||
isCreatedByUser: false,
|
||||
} as TMessage;
|
||||
|
||||
function createContextValue(
|
||||
overrides: Partial<MessagesViewContextValue> = {},
|
||||
): MessagesViewContextValue {
|
||||
return {
|
||||
conversation,
|
||||
conversationId: conversation.conversationId,
|
||||
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(),
|
||||
...overrides,
|
||||
} as MessagesViewContextValue;
|
||||
}
|
||||
|
||||
function ScrollingHarness({ messagesTree }: { messagesTree?: TMessage[] | null }) {
|
||||
const { contentRef, scrollableRef, messagesEndRef, debouncedHandleScroll } =
|
||||
useMessageScrolling(messagesTree);
|
||||
|
||||
return (
|
||||
<div ref={scrollableRef} onScroll={debouncedHandleScroll} data-testid="scrollable">
|
||||
<div ref={contentRef} data-testid="content">
|
||||
<div ref={messagesEndRef} data-testid="end" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function renderScrolling({
|
||||
contextOverrides,
|
||||
messagesTree,
|
||||
}: {
|
||||
contextOverrides?: Partial<MessagesViewContextValue>;
|
||||
messagesTree?: TMessage[] | null;
|
||||
} = {}) {
|
||||
return render(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider value={createContextValue(contextOverrides)}>
|
||||
<ScrollingHarness messagesTree={messagesTree} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('useMessageScrolling resize reconciliation', () => {
|
||||
beforeEach(() => {
|
||||
MockResizeObserver.reset();
|
||||
MockIntersectionObserver.reset();
|
||||
mockScrollToBottom.mockClear();
|
||||
mockScrollToBottom.cancel.mockClear();
|
||||
mockScrollToBottom.flush.mockClear();
|
||||
mockHandleSmoothToRef.mockClear();
|
||||
mockReconcileMessageContentLayout.mockClear();
|
||||
mockScrollCallback = undefined;
|
||||
(global as unknown as { ResizeObserver: typeof MockResizeObserver }).ResizeObserver =
|
||||
MockResizeObserver;
|
||||
(
|
||||
global as unknown as { IntersectionObserver: typeof MockIntersectionObserver }
|
||||
).IntersectionObserver = MockIntersectionObserver;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(global as unknown as { ResizeObserver: typeof ResizeObserver | undefined }).ResizeObserver =
|
||||
originalResizeObserver;
|
||||
(
|
||||
global as unknown as { IntersectionObserver: typeof IntersectionObserver | undefined }
|
||||
).IntersectionObserver = originalIntersectionObserver;
|
||||
});
|
||||
|
||||
it('rides the bottom when streaming content resizes and auto-scroll is active', () => {
|
||||
renderScrolling();
|
||||
|
||||
const observer = MockResizeObserver.last();
|
||||
expect(observer?.observe).toHaveBeenCalledWith(screen.getByTestId('content'));
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });
|
||||
Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });
|
||||
scrollable.scrollTop = 700;
|
||||
|
||||
act(() => {
|
||||
observer?.trigger();
|
||||
});
|
||||
|
||||
/** Written straight to the element rather than routed through the throttled
|
||||
* scrollIntoView helper, so an answer arriving a few pixels at a time flows
|
||||
* instead of lurching once every throttle window. */
|
||||
expect(scrollable.scrollTop).toBe(800);
|
||||
});
|
||||
|
||||
it('reconciles message layout after an explicit scroll to bottom', () => {
|
||||
renderScrolling();
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
act(() => {
|
||||
mockScrollCallback?.();
|
||||
});
|
||||
|
||||
expect(mockReconcileMessageContentLayout).toHaveBeenCalledWith(scrollable);
|
||||
});
|
||||
|
||||
/**
|
||||
* `useMessageProcess` raises the abort flag on any wheel at all, downward ones
|
||||
* included, through a throttle whose trailing call lands after the gesture has
|
||||
* ended. Gating on it meant scrolling down to the newest word could never resume
|
||||
* the ride, while the scroll-to-bottom button, which touches no wheel, always
|
||||
* could. Position and direction answer that question instead.
|
||||
*/
|
||||
it('rides the bottom for a reader who is on it, even with the abort flag raised', () => {
|
||||
renderScrolling({ contextOverrides: { abortScroll: true } });
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });
|
||||
Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });
|
||||
scrollable.scrollTop = 700;
|
||||
|
||||
act(() => {
|
||||
MockResizeObserver.last()?.trigger();
|
||||
});
|
||||
|
||||
expect(scrollable.scrollTop).toBe(800);
|
||||
});
|
||||
|
||||
it('does not follow resizes after the user scrolls away from the bottom', () => {
|
||||
renderScrolling();
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });
|
||||
Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });
|
||||
scrollable.scrollTop = 100;
|
||||
|
||||
fireEvent.scroll(scrollable);
|
||||
|
||||
act(() => {
|
||||
MockResizeObserver.last()?.trigger();
|
||||
});
|
||||
|
||||
expect(mockScrollToBottom).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('judges the first scroll against a real previous position, not against the top', () => {
|
||||
const setAbortScroll = jest.fn();
|
||||
renderScrolling({ contextOverrides: { setAbortScroll } });
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });
|
||||
Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });
|
||||
|
||||
/** A thread opens at its end, so the reader's first gesture carries a large
|
||||
* positive scrollTop. Measured from 0 it read as a jump down onto the end, and
|
||||
* the reader was re-pinned to the stream they were trying to leave. */
|
||||
setAbortScroll.mockClear();
|
||||
scrollable.scrollTop = 700;
|
||||
fireEvent.scroll(scrollable);
|
||||
|
||||
expect(setAbortScroll).not.toHaveBeenCalled();
|
||||
|
||||
/** With a baseline taken, the same gesture is judged on its real delta. */
|
||||
scrollable.scrollTop = 500;
|
||||
fireEvent.scroll(scrollable);
|
||||
|
||||
act(() => {
|
||||
MockResizeObserver.last()?.trigger();
|
||||
});
|
||||
|
||||
expect(scrollable.scrollTop).toBe(500);
|
||||
});
|
||||
|
||||
it('obeys the first scroll away from a thread that was placed at its end', () => {
|
||||
renderScrolling();
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });
|
||||
Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });
|
||||
|
||||
/** The thread opens at its end without the reader touching it, so the position
|
||||
* it was placed at is what their first gesture has to be judged against. */
|
||||
scrollable.scrollTop = 800;
|
||||
act(() => {
|
||||
mockScrollCallback?.();
|
||||
});
|
||||
|
||||
/** One PageUp, and it is the first event the handler sees. A key press buys a
|
||||
* single resize of grace and clears no flag of its own, so if the gesture is
|
||||
* spent taking a baseline the reader is ridden straight back to the end. */
|
||||
fireEvent.keyDown(screen.getByTestId('content'), { key: 'PageUp' });
|
||||
scrollable.scrollTop = 300;
|
||||
fireEvent.scroll(scrollable);
|
||||
|
||||
act(() => {
|
||||
MockResizeObserver.last()?.trigger();
|
||||
MockResizeObserver.last()?.trigger();
|
||||
});
|
||||
|
||||
expect(scrollable.scrollTop).toBe(300);
|
||||
});
|
||||
|
||||
it('does not follow the next resize after user interaction inside message content', () => {
|
||||
renderScrolling();
|
||||
|
||||
fireEvent.pointerDown(screen.getByTestId('content'));
|
||||
|
||||
act(() => {
|
||||
MockResizeObserver.last()?.trigger();
|
||||
});
|
||||
|
||||
expect(mockScrollToBottom).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
/**
|
||||
* One interaction rarely settles in a single frame: expanding a tool result renders
|
||||
* the container, then its contents arrive and grow it again. Only the first resize
|
||||
* was credited to the interaction, so the second read the reader as still riding the
|
||||
* stream and put them back on the bottom they had just deliberately left.
|
||||
*/
|
||||
it('keeps an interaction that settles over several resizes from re-pinning the reader', () => {
|
||||
renderScrolling();
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });
|
||||
Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });
|
||||
scrollable.scrollTop = 800;
|
||||
|
||||
fireEvent.pointerDown(screen.getByTestId('content'));
|
||||
|
||||
/** The expansion renders, which is the resize the interaction is credited with. */
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 2000, configurable: true });
|
||||
act(() => {
|
||||
MockResizeObserver.last()?.trigger();
|
||||
});
|
||||
expect(scrollable.scrollTop).toBe(800);
|
||||
|
||||
/** Its contents then load. This belongs to the same interaction, not to the stream. */
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 2600, configurable: true });
|
||||
act(() => {
|
||||
MockResizeObserver.last()?.trigger();
|
||||
});
|
||||
|
||||
expect(scrollable.scrollTop).toBe(800);
|
||||
});
|
||||
|
||||
it('clamps the scroll position back to content after a resize shrink', () => {
|
||||
renderScrolling({ contextOverrides: { abortScroll: true } });
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 500, configurable: true });
|
||||
Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });
|
||||
scrollable.scrollTop = 450;
|
||||
|
||||
act(() => {
|
||||
MockResizeObserver.last()?.trigger();
|
||||
});
|
||||
|
||||
expect(scrollable.scrollTop).toBe(300);
|
||||
expect(mockScrollToBottom).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
/**
|
||||
* Sending arms a smooth glide down to the newest word, and the landing re-pins the
|
||||
* thread to the bottom. The landing is scheduled for the whole glide window, so a
|
||||
* reader who changes their mind and heads up mid-flight was pinned again anyway and
|
||||
* dragged back on the next streaming resize.
|
||||
*/
|
||||
it('lets an upward gesture during the send glide beat the pending landing', () => {
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const view = render(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider value={createContextValue({ isSubmitting: false })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
);
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
const scrollTo = jest.fn();
|
||||
(scrollable as unknown as { scrollTo: jest.Mock }).scrollTo = scrollTo;
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });
|
||||
Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });
|
||||
scrollable.scrollTop = 0;
|
||||
|
||||
view.rerender(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider value={createContextValue({ isSubmitting: true })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
);
|
||||
|
||||
expect(scrollTo).toHaveBeenCalledWith({ top: 800, behavior: 'smooth' });
|
||||
|
||||
/** The reader heads up while the glide is still in flight. */
|
||||
scrollable.scrollTop = 400;
|
||||
fireEvent.wheel(scrollable, { deltaY: -120 });
|
||||
|
||||
act(() => {
|
||||
jest.advanceTimersByTime(glideWindow);
|
||||
});
|
||||
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 1200, configurable: true });
|
||||
act(() => {
|
||||
MockResizeObserver.last()?.trigger();
|
||||
});
|
||||
|
||||
expect(scrollable.scrollTop).toBe(400);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* A reader who scrolls away during one answer leaves the abort flag raised, and
|
||||
* nothing lowers it until the next connection opens, which is after the send has
|
||||
* already been seen. Spending the start of the turn on that first pass left the
|
||||
* answer the reader had just asked for streaming offscreen.
|
||||
*/
|
||||
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>,
|
||||
);
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
const scrollTo = jest.fn();
|
||||
(scrollable as unknown as { scrollTo: jest.Mock }).scrollTo = scrollTo;
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });
|
||||
Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });
|
||||
scrollable.scrollTop = 0;
|
||||
|
||||
/** They left the bottom during the previous answer, which is what raised it. */
|
||||
fireEvent.wheel(scrollable, { deltaY: -120 });
|
||||
|
||||
view.rerender(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider
|
||||
value={createContextValue({ isSubmitting: true, abortScroll: true })}
|
||||
>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
);
|
||||
|
||||
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>,
|
||||
);
|
||||
|
||||
expect(scrollTo).toHaveBeenCalledWith({ top: 800, behavior: 'smooth' });
|
||||
});
|
||||
|
||||
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>,
|
||||
);
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
const scrollTo = jest.fn();
|
||||
(scrollable as unknown as { scrollTo: jest.Mock }).scrollTo = scrollTo;
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });
|
||||
Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });
|
||||
scrollable.scrollTop = 0;
|
||||
|
||||
view.rerender(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider value={createContextValue({ isSubmitting: true })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
);
|
||||
|
||||
expect(scrollTo).toHaveBeenCalledWith({ top: 800, behavior: 'smooth' });
|
||||
|
||||
/** 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>,
|
||||
);
|
||||
|
||||
/** A plain follow would have written scrollTop outright and killed the animation. */
|
||||
expect(scrollable.scrollTop).toBe(0);
|
||||
});
|
||||
|
||||
/**
|
||||
* Following stands down for the length of the glide, so an answer that arrives
|
||||
* while it travels moves the bottom past the target the glide aimed at. Landing
|
||||
* has to close that gap, or a short response settles short of its own end.
|
||||
*/
|
||||
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>,
|
||||
);
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
(scrollable as unknown as { scrollTo: jest.Mock }).scrollTo = jest.fn();
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });
|
||||
Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });
|
||||
scrollable.scrollTop = 0;
|
||||
|
||||
view.rerender(
|
||||
<RecoilRoot>
|
||||
<MessagesViewContext.Provider value={createContextValue({ isSubmitting: true })}>
|
||||
<ScrollingHarness messagesTree={[message]} />
|
||||
</MessagesViewContext.Provider>
|
||||
</RecoilRoot>,
|
||||
);
|
||||
|
||||
/** The whole answer arrives before the glide reports that it landed. */
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 1400, configurable: true });
|
||||
act(() => {
|
||||
fireEvent(scrollable, new Event('scrollend'));
|
||||
});
|
||||
|
||||
expect(scrollable.scrollTop).toBe(1200);
|
||||
});
|
||||
|
||||
it('does not clamp to rendered content bottom during general resize reconciliation', () => {
|
||||
renderScrolling();
|
||||
|
||||
const scrollable = screen.getByTestId('scrollable');
|
||||
const content = screen.getByTestId('content');
|
||||
Object.defineProperty(scrollable, 'scrollHeight', { value: 1000, configurable: true });
|
||||
Object.defineProperty(scrollable, 'clientHeight', { value: 200, configurable: true });
|
||||
|
||||
/** Move away from the end so the reader is left alone, which is the state this
|
||||
* is about: reconciliation must not drag them to the rendered content bottom. */
|
||||
scrollable.scrollTop = 900;
|
||||
fireEvent.scroll(scrollable);
|
||||
scrollable.scrollTop = 700;
|
||||
fireEvent.scroll(scrollable);
|
||||
|
||||
setRect(scrollable, { top: 0, bottom: 200, height: 200 });
|
||||
setRect(content, { top: -700, bottom: -200, height: 500 });
|
||||
|
||||
act(() => {
|
||||
MockResizeObserver.last()?.trigger();
|
||||
});
|
||||
|
||||
expect(scrollable.scrollTop).toBe(700);
|
||||
expect(mockScrollToBottom).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('useMessageScrolling navigation landing', () => {
|
||||
const treeFor = (conversationId: string): TMessage[] => [
|
||||
{ ...message, conversationId } as TMessage,
|
||||
];
|
||||
|
||||
const harness = (
|
||||
store: ReturnType<typeof createStore>,
|
||||
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>
|
||||
);
|
||||
|
||||
function renderLanding(
|
||||
conversationId: string,
|
||||
messagesTree: TMessage[] | null,
|
||||
autoScroll = true,
|
||||
) {
|
||||
const store = createStore();
|
||||
store.set(autoScrollAtom, autoScroll);
|
||||
const view = render(harness(store, conversationId, messagesTree));
|
||||
return {
|
||||
...view,
|
||||
rerenderWith: (nextId: string, nextTree: TMessage[] | null) =>
|
||||
view.rerender(harness(store, nextId, nextTree)),
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
MockResizeObserver.reset();
|
||||
MockIntersectionObserver.reset();
|
||||
mockScrollToBottom.mockClear();
|
||||
mockScrollToBottom.cancel.mockClear();
|
||||
(global as unknown as { ResizeObserver: typeof MockResizeObserver }).ResizeObserver =
|
||||
MockResizeObserver;
|
||||
(
|
||||
global as unknown as { IntersectionObserver: typeof MockIntersectionObserver }
|
||||
).IntersectionObserver = MockIntersectionObserver;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(global as unknown as { ResizeObserver: typeof ResizeObserver | undefined }).ResizeObserver =
|
||||
originalResizeObserver;
|
||||
(
|
||||
global as unknown as { IntersectionObserver: typeof IntersectionObserver | undefined }
|
||||
).IntersectionObserver = originalIntersectionObserver;
|
||||
});
|
||||
|
||||
it('waits for the opened conversation to own the rendered rows', () => {
|
||||
/** The id reaches the hook commits before the tree does. Landing on the
|
||||
* outgoing thread spends the one scroll this navigation gets, and leaves
|
||||
* the reader at the top of the thread they actually asked for. */
|
||||
renderLanding('conversation-2', treeFor('conversation-1'));
|
||||
|
||||
expect(mockScrollToBottom).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('lands once the rendered tree names the opened conversation', () => {
|
||||
const { rerenderWith } = renderLanding('conversation-2', treeFor('conversation-1'));
|
||||
expect(mockScrollToBottom).not.toHaveBeenCalled();
|
||||
|
||||
rerenderWith('conversation-2', treeFor('conversation-2'));
|
||||
|
||||
expect(mockScrollToBottom).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not re-land on the tree identities a stream mints', () => {
|
||||
const { rerenderWith } = renderLanding('conversation-2', treeFor('conversation-2'));
|
||||
expect(mockScrollToBottom).toHaveBeenCalledTimes(1);
|
||||
|
||||
/** Every delta writes a fresh array; re-landing on those would haul back a
|
||||
* reader who deliberately scrolled up. */
|
||||
rerenderWith('conversation-2', treeFor('conversation-2'));
|
||||
rerenderWith('conversation-2', treeFor('conversation-2'));
|
||||
|
||||
expect(mockScrollToBottom).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('lands again for the next conversation opened', () => {
|
||||
const { rerenderWith } = renderLanding('conversation-2', treeFor('conversation-2'));
|
||||
expect(mockScrollToBottom).toHaveBeenCalledTimes(1);
|
||||
|
||||
rerenderWith('conversation-3', treeFor('conversation-2'));
|
||||
expect(mockScrollToBottom).toHaveBeenCalledTimes(1);
|
||||
|
||||
rerenderWith('conversation-3', treeFor('conversation-3'));
|
||||
expect(mockScrollToBottom).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('stays put when the setting is off', () => {
|
||||
renderLanding('conversation-2', treeFor('conversation-2'), false);
|
||||
|
||||
expect(mockScrollToBottom).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -1,73 +0,0 @@
|
|||
const MESSAGE_SCROLL_CONTAINER_SELECTOR = '.scrollbar-gutter-stable';
|
||||
const MESSAGE_LAYOUT_RECONCILE_DURATION_MS = 350;
|
||||
|
||||
function getNow(): number {
|
||||
return typeof performance !== 'undefined' ? performance.now() : Date.now();
|
||||
}
|
||||
|
||||
function getContentElement(scrollEl: HTMLElement): HTMLElement | null {
|
||||
return scrollEl.firstElementChild instanceof HTMLElement ? scrollEl.firstElementChild : null;
|
||||
}
|
||||
|
||||
export function getRenderedContentMaxScrollTop(scrollEl: HTMLElement): number {
|
||||
const scrollHeightMax = Math.max(0, scrollEl.scrollHeight - scrollEl.clientHeight);
|
||||
const contentEl = getContentElement(scrollEl);
|
||||
if (!contentEl) {
|
||||
return scrollHeightMax;
|
||||
}
|
||||
|
||||
const scrollRect = scrollEl.getBoundingClientRect();
|
||||
const contentRect = contentEl.getBoundingClientRect();
|
||||
if (scrollRect.height === 0 && contentRect.height === 0 && scrollEl.clientHeight > 0) {
|
||||
return scrollHeightMax;
|
||||
}
|
||||
|
||||
const contentBottom = contentRect.bottom - scrollRect.top + scrollEl.scrollTop;
|
||||
const renderedMax = Math.max(0, Math.ceil(contentBottom - scrollEl.clientHeight));
|
||||
|
||||
return Math.min(scrollHeightMax, renderedMax);
|
||||
}
|
||||
|
||||
export function reconcileMessageContentLayout(target: HTMLElement | null): boolean {
|
||||
const scrollEl = target?.closest<HTMLElement>(MESSAGE_SCROLL_CONTAINER_SELECTOR) ?? null;
|
||||
if (!scrollEl) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const maxScrollTop = getRenderedContentMaxScrollTop(scrollEl);
|
||||
if (scrollEl.scrollTop <= maxScrollTop) {
|
||||
return false;
|
||||
}
|
||||
|
||||
scrollEl.scrollTop = maxScrollTop;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function scheduleMessageContentLayoutReconcile(target: HTMLElement | null): () => void {
|
||||
reconcileMessageContentLayout(target);
|
||||
if (
|
||||
!target ||
|
||||
typeof window === 'undefined' ||
|
||||
typeof window.requestAnimationFrame !== 'function'
|
||||
) {
|
||||
return () => {};
|
||||
}
|
||||
|
||||
const startedAt = getNow();
|
||||
let animationFrameId: number | undefined;
|
||||
const reconcile = () => {
|
||||
reconcileMessageContentLayout(target);
|
||||
if (getNow() - startedAt >= MESSAGE_LAYOUT_RECONCILE_DURATION_MS) {
|
||||
animationFrameId = undefined;
|
||||
return;
|
||||
}
|
||||
animationFrameId = window.requestAnimationFrame(reconcile);
|
||||
};
|
||||
|
||||
animationFrameId = window.requestAnimationFrame(reconcile);
|
||||
return () => {
|
||||
if (animationFrameId !== undefined) {
|
||||
window.cancelAnimationFrame(animationFrameId);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
@ -1,481 +0,0 @@
|
|||
import { useRef, useCallback, useEffect } from 'react';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { Constants } from 'librechat-data-provider';
|
||||
import type { TMessage } from 'librechat-data-provider';
|
||||
import { useMessagesConversation, useMessagesSubmission } from '~/Providers';
|
||||
import { reconcileMessageContentLayout } from './messageLayout';
|
||||
import useScrollToRef from '~/hooks/useScrollToRef';
|
||||
import { autoScrollAtom } from '~/store/autoScroll';
|
||||
|
||||
const resizeFollowThreshold = 120;
|
||||
|
||||
/** How long a glide is given to land before per-frame following resumes. */
|
||||
const glideTimeout = 700;
|
||||
|
||||
/** Arriving counts from further out than leaving does, because while an answer
|
||||
* streams the end is a moving target: it recedes between the reader's last
|
||||
* wheel tick and the frame that measures it, so someone scrolling all the way
|
||||
* down still lands tens of pixels short. Judging arrival as tightly as
|
||||
* departure means they can never quite catch it. */
|
||||
const attachThreshold = 150;
|
||||
const detachThreshold = 24;
|
||||
|
||||
const prefersReducedMotion = () =>
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.matchMedia === 'function' &&
|
||||
window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
export default function useMessageScrolling(messagesTree?: TMessage[] | null) {
|
||||
const autoScroll = useAtomValue(autoScrollAtom);
|
||||
|
||||
const scrollableRef = useRef<HTMLDivElement | null>(null);
|
||||
const contentRef = useRef<HTMLDivElement | null>(null);
|
||||
const messagesEndRef = useRef<HTMLDivElement | null>(null);
|
||||
const isNearBottomRef = useRef(true);
|
||||
/** The single authority for whether the thread is riding the stream. Driven only
|
||||
* by what the reader does, never by the observer, whose zero-height sentinel
|
||||
* flickers as content grows and was the source of the attach/detach churn. */
|
||||
const isStuckRef = useRef(true);
|
||||
const isGlidingRef = useRef(false);
|
||||
/** Raised wherever a reader gesture lets go of the bottom, so a glide already in
|
||||
* flight knows not to re-pin them when it lands. */
|
||||
const glideInterruptedRef = useRef(false);
|
||||
const glideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
/** Seeded below zero rather than at 0 so the first event after mount is read as
|
||||
* "no previous sample" instead of as a jump down from the top. Every
|
||||
* programmatic move writes the position it left the thread at, so this stands
|
||||
* only until something has actually placed the thread. */
|
||||
const lastScrollTopRef = useRef(-1);
|
||||
const wasSubmittingRef = useRef(false);
|
||||
const suppressNextResizeFollowRef = useRef(false);
|
||||
/** 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;
|
||||
if (!scrollEl) {
|
||||
return true;
|
||||
}
|
||||
const distance = scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight;
|
||||
return distance <= resizeFollowThreshold;
|
||||
}, []);
|
||||
|
||||
/** The scroll-to-bottom button owns the IntersectionObserver (so its visibility
|
||||
* state never re-renders the message tree host) and reports intersection back
|
||||
* through this callback.
|
||||
*
|
||||
* It reports only. The sentinel it watches has no height and is observed at a
|
||||
* 0.85 threshold, a ratio a zero-area box cannot reach, so it flickers while an
|
||||
* answer streams. Letting it decide whether to ride the stream is what made the
|
||||
* thread attach and detach on its own.
|
||||
*/
|
||||
const handleNearBottomChange = useCallback((isNearBottom: boolean) => {
|
||||
isNearBottomRef.current = isNearBottom;
|
||||
}, []);
|
||||
|
||||
const distanceFromEnd = useCallback(() => {
|
||||
const scrollEl = scrollableRef.current;
|
||||
if (!scrollEl) {
|
||||
return 0;
|
||||
}
|
||||
return scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight;
|
||||
}, []);
|
||||
|
||||
/** Direction is judged against the last sample, so anything that moves the thread
|
||||
* on the reader's behalf has to leave one behind. A thread opening at its end, or
|
||||
* ridden down by the stream, is placed without the reader touching it; with no
|
||||
* record of where it was put, their first gesture is spent taking the baseline
|
||||
* instead of being obeyed, and a keyboard scroll away from the end is lost. */
|
||||
const rememberScrollPosition = useCallback(() => {
|
||||
const scrollEl = scrollableRef.current;
|
||||
if (!scrollEl) {
|
||||
return;
|
||||
}
|
||||
lastScrollTopRef.current = scrollEl.scrollTop;
|
||||
}, []);
|
||||
|
||||
const debouncedHandleScroll = useCallback(() => {
|
||||
const scrollEl = scrollableRef.current;
|
||||
isNearBottomRef.current = getIsNearBottom();
|
||||
if (!scrollEl) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** Direction comes from where the thread actually moved, which covers the
|
||||
* wheel, a trackpad and a dragged scrollbar alike. */
|
||||
const top = scrollEl.scrollTop;
|
||||
const previousTop = lastScrollTopRef.current;
|
||||
lastScrollTopRef.current = top;
|
||||
|
||||
/** A thread opens already scrolled to its end, so the first event carries a
|
||||
* large positive `scrollTop` with nothing to compare it against. Measuring it
|
||||
* from 0 calls it downward, and the gesture that produced it, a reader pushing
|
||||
* up and away from the stream, is swallowed: a single PageUp reads as an
|
||||
* arrival and leaves the thread riding the answer. Take this one as the
|
||||
* baseline and judge direction from the next. */
|
||||
if (previousTop < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const movingDown = top >= previousTop;
|
||||
const distance = distanceFromEnd();
|
||||
|
||||
/** Arriving is judged here rather than on the wheel tick that started it: the
|
||||
* browser animates wheel scrolling, so at tick time the thread is still far
|
||||
* short of where that tick is taking it, and reading the distance then calls
|
||||
* a gesture that lands on the end a miss. */
|
||||
if (movingDown) {
|
||||
if (distance <= attachThreshold) {
|
||||
isStuckRef.current = true;
|
||||
/** Cleared unconditionally rather than on a read of the current value.
|
||||
* `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
|
||||
* write, so repeating it costs nothing. */
|
||||
setAbortScroll(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (distance > detachThreshold) {
|
||||
isStuckRef.current = false;
|
||||
glideInterruptedRef.current = true;
|
||||
}
|
||||
}, [distanceFromEnd, getIsNearBottom, setAbortScroll]);
|
||||
|
||||
const scrollCallback = () => {
|
||||
reconcileMessageContentLayout(scrollableRef.current);
|
||||
isNearBottomRef.current = true;
|
||||
isStuckRef.current = true;
|
||||
rememberScrollPosition();
|
||||
};
|
||||
|
||||
const { scrollToRef: scrollToBottom, handleSmoothToRef } = useScrollToRef({
|
||||
targetRef: messagesEndRef,
|
||||
callback: scrollCallback,
|
||||
smoothCallback: () => {
|
||||
scrollCallback();
|
||||
setAbortScroll(false);
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Ride the bottom of the thread.
|
||||
*
|
||||
* Written straight to `scrollTop` rather than routed through the throttled
|
||||
* `scrollIntoView` helper: an answer arrives a few pixels at a time, so
|
||||
* correcting on every frame reads as the text simply flowing upward, while
|
||||
* correcting every 145ms reads as a thread that lurches.
|
||||
*
|
||||
* The glide is for distance only, when a send has to travel from wherever the
|
||||
* reader was down to the newest word. Following while one is in flight would
|
||||
* cancel it on the first frame.
|
||||
*/
|
||||
const followBottom = useCallback((behavior: ScrollBehavior = 'auto') => {
|
||||
const scrollEl = scrollableRef.current;
|
||||
if (!scrollEl) {
|
||||
return;
|
||||
}
|
||||
const target = Math.max(0, scrollEl.scrollHeight - scrollEl.clientHeight);
|
||||
if (Math.abs(scrollEl.scrollTop - target) < 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (behavior !== 'smooth' || prefersReducedMotion()) {
|
||||
scrollEl.scrollTop = target;
|
||||
/** Riding the bottom re-affirms that we are on it. The throttled helper this
|
||||
* replaced did the same through its callback, and without it a single
|
||||
* under-reported intersection ends the ride for the rest of the turn. */
|
||||
isNearBottomRef.current = true;
|
||||
isStuckRef.current = true;
|
||||
lastScrollTopRef.current = target;
|
||||
return;
|
||||
}
|
||||
|
||||
isGlidingRef.current = true;
|
||||
glideInterruptedRef.current = false;
|
||||
if (glideTimerRef.current != null) {
|
||||
clearTimeout(glideTimerRef.current);
|
||||
}
|
||||
const land = () => {
|
||||
isGlidingRef.current = false;
|
||||
scrollEl.removeEventListener('scrollend', land);
|
||||
if (glideTimerRef.current != null) {
|
||||
clearTimeout(glideTimerRef.current);
|
||||
glideTimerRef.current = null;
|
||||
}
|
||||
/** Scrolling up during the glide is the reader taking over. Re-pinning them
|
||||
* here would hand the thread straight back to the stream on the next resize,
|
||||
* and the timeout fires for the whole glide window even once the animation
|
||||
* has visibly settled, so the gesture has to win outright. */
|
||||
if (glideInterruptedRef.current) {
|
||||
return;
|
||||
}
|
||||
isNearBottomRef.current = true;
|
||||
isStuckRef.current = true;
|
||||
/** Following stands down for the whole trip, so anything that streamed in
|
||||
* meanwhile moved the bottom past the target this glide aimed at. Close that
|
||||
* gap on arrival, or a short answer settles a few lines short of its end. */
|
||||
const settled = Math.max(0, scrollEl.scrollHeight - scrollEl.clientHeight);
|
||||
if (Math.abs(scrollEl.scrollTop - settled) >= 1) {
|
||||
scrollEl.scrollTop = settled;
|
||||
}
|
||||
lastScrollTopRef.current = scrollEl.scrollTop;
|
||||
};
|
||||
scrollEl.addEventListener('scrollend', land, { once: true });
|
||||
glideTimerRef.current = setTimeout(land, glideTimeout);
|
||||
scrollEl.scrollTo({ top: target, behavior: 'smooth' });
|
||||
}, []);
|
||||
|
||||
const clampScrollToContent = useCallback(() => {
|
||||
const scrollEl = scrollableRef.current;
|
||||
if (!scrollEl) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const maxScrollTop = Math.max(0, scrollEl.scrollHeight - scrollEl.clientHeight);
|
||||
if (scrollEl.scrollTop <= maxScrollTop) {
|
||||
return false;
|
||||
}
|
||||
|
||||
scrollEl.scrollTop = maxScrollTop;
|
||||
isNearBottomRef.current = getIsNearBottom();
|
||||
return true;
|
||||
}, [getIsNearBottom]);
|
||||
|
||||
const reconcileContentResize = useCallback(
|
||||
(shouldFollowResize = true) => {
|
||||
if (clampScrollToContent()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (suppressNextResizeFollowRef.current) {
|
||||
suppressNextResizeFollowRef.current = false;
|
||||
isNearBottomRef.current = getIsNearBottom();
|
||||
/** An interaction rarely settles in one frame: a tool result expands, then its
|
||||
* contents arrive and grow it again. Only the first resize is credited to the
|
||||
* gesture, so letting go of the ride has to happen here. Leaving it to the
|
||||
* resize that follows means reading a reader who has just been pushed far up
|
||||
* their own thread as still riding the stream, and handing them back to the
|
||||
* bottom they deliberately left. Where the interaction actually left them
|
||||
* decides it, so one that kept them on the end keeps streaming. */
|
||||
isStuckRef.current = isNearBottomRef.current;
|
||||
return;
|
||||
}
|
||||
|
||||
/** A glide already on its way to the bottom is heading exactly where this
|
||||
* would put us, and touching the position would cancel it. */
|
||||
if (isGlidingRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** Deliberately not gated on `abortScroll`. `useMessageProcess` raises that on
|
||||
* any wheel at all, downward ones included, through a 500ms throttle whose
|
||||
* trailing call lands after the gesture has ended: no clear timed to the
|
||||
* gesture can outlive it, which is why scrolling down to the newest word
|
||||
* could never resume the ride while the button, which touches no wheel,
|
||||
* always could. Whether the reader is riding the stream is answered here by
|
||||
* where they actually are and which way they were going. */
|
||||
if (shouldFollowResize && isSubmitting && isStuckRef.current) {
|
||||
followBottom();
|
||||
}
|
||||
},
|
||||
[clampScrollToContent, followBottom, getIsNearBottom, isSubmitting],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const contentEl = contentRef.current;
|
||||
if (!contentEl || typeof ResizeObserver === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
const observer = new ResizeObserver(() => reconcileContentResize());
|
||||
observer.observe(contentEl);
|
||||
return () => observer.disconnect();
|
||||
}, [reconcileContentResize]);
|
||||
|
||||
useEffect(() => {
|
||||
const contentEl = contentRef.current;
|
||||
if (!contentEl) {
|
||||
return;
|
||||
}
|
||||
|
||||
const suppressNextResizeFollow = () => {
|
||||
suppressNextResizeFollowRef.current = true;
|
||||
};
|
||||
|
||||
contentEl.addEventListener('pointerdown', suppressNextResizeFollow, true);
|
||||
contentEl.addEventListener('keydown', suppressNextResizeFollow, true);
|
||||
return () => {
|
||||
contentEl.removeEventListener('pointerdown', suppressNextResizeFollow, true);
|
||||
contentEl.removeEventListener('keydown', suppressNextResizeFollow, true);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const scrollEl = scrollableRef.current;
|
||||
if (!scrollEl || typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
/** Direction decides, not position. Heading up lets go at once and stays let
|
||||
* go, however close to the end the reader still is; anything position-based
|
||||
* drags them back before they have cleared the band, which reads as the
|
||||
* thread refusing to be scrolled.
|
||||
*
|
||||
* Heading down only re-attaches on arrival at the end.
|
||||
*
|
||||
* `Message` aborts auto-scroll on `wheel` alone, and a tick against the end
|
||||
* moves nothing and so fires no `scroll`, leaving that flag set with nothing
|
||||
* to clear it. Clearing it on arrival is what lets the ride resume; the
|
||||
* button escaped the problem only by never touching the wheel. */
|
||||
/** An upward tick releases immediately, without waiting to see where it lands.
|
||||
* Re-attaching is left entirely to arrival, handled on scroll.
|
||||
*
|
||||
* A downward tick clears the abort flag outright. `Message` raises it on any
|
||||
* wheel at all, and a tick against the end moves nothing, so it fires no
|
||||
* `scroll` for the arrival handler to answer: the last tick of scrolling down
|
||||
* to the newest word leaves the ride vetoed with nothing left to lift it.
|
||||
* Scrolling down is never an intent to abandon the stream. */
|
||||
const onWheel = (event: WheelEvent) => {
|
||||
if (event.deltaY < 0) {
|
||||
isStuckRef.current = false;
|
||||
glideInterruptedRef.current = true;
|
||||
return;
|
||||
}
|
||||
/** Next frame, not now: React binds `Message`'s handler at the root, above
|
||||
* this container, so it runs after this one and would put the flag straight
|
||||
* back. Clearing once the event has finished dispatching is what makes it
|
||||
* stick. */
|
||||
window.requestAnimationFrame(() => setAbortScroll(false));
|
||||
};
|
||||
|
||||
scrollEl.addEventListener('wheel', onWheel, { passive: true });
|
||||
return () => {
|
||||
scrollEl.removeEventListener('wheel', onWheel);
|
||||
};
|
||||
}, [setAbortScroll]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (glideTimerRef.current != null) {
|
||||
clearTimeout(glideTimerRef.current);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!messagesTree || messagesTree.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!messagesEndRef.current || !scrollableRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const startedSubmitting = isSubmitting && !wasSubmittingRef.current;
|
||||
|
||||
if (!isSubmitting) {
|
||||
wasSubmittingRef.current = false;
|
||||
}
|
||||
|
||||
/** The start of a turn is spent only once it can be acted on. A reader who
|
||||
* scrolled away during the last answer leaves the abort flag raised, and
|
||||
* nothing lowers it until the next connection opens, which is after this effect
|
||||
* has already seen the send. Marking the turn as started on that first pass
|
||||
* spent it against a closed gate: by the time the flag cleared there was no
|
||||
* start left to honour and the reader was still detached, so the answer they
|
||||
* had just asked for streamed on offscreen. */
|
||||
if (isSubmitting && abortScroll !== true) {
|
||||
wasSubmittingRef.current = true;
|
||||
/** Sending re-attaches: the reader asked for this answer, so take them to it.
|
||||
* The one long trip of a turn, and the only one worth animating. */
|
||||
if (startedSubmitting) {
|
||||
isNearBottomRef.current = true;
|
||||
isStuckRef.current = true;
|
||||
followBottom('smooth');
|
||||
} else if (isStuckRef.current && !isGlidingRef.current) {
|
||||
/** Every delta of the answer reruns this effect, and a plain follow writes
|
||||
* scrollTop outright, which cancels an animation on its first frame. The
|
||||
* glide is left to finish the trip it started. */
|
||||
followBottom();
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (abortScroll === true) {
|
||||
scrollToBottom && scrollToBottom.cancel();
|
||||
}
|
||||
};
|
||||
}, [isSubmitting, messagesTree, scrollToBottom, abortScroll, followBottom]);
|
||||
|
||||
/**
|
||||
* Land on the newest message when a conversation is opened.
|
||||
*
|
||||
* 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
|
||||
* 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.
|
||||
*
|
||||
* One landing per conversation: the tree's identity changes on every stream
|
||||
* delta and cache reconcile, and re-running on those would drag a reader who
|
||||
* has scrolled away back to the bottom.
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!autoScroll) {
|
||||
/** Switching the setting off releases the landing, so switching it back
|
||||
* on while the same conversation is open honours it again. */
|
||||
landedConversationRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (conversationId == null || conversationId === Constants.NEW_CONVO) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!scrollToBottom || !messagesEndRef.current || !scrollableRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** Rows are gated by the progressive mount window during a first commit,
|
||||
* but that window only ever grows UPWARD from the newest row, so the end
|
||||
* of the mounted content is already the end of the thread. */
|
||||
if (!messagesTree?.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** Same fallback `MessagesView` uses to key the mount window: a tree whose
|
||||
* rows carry no conversation id is taken to be this conversation's, so a
|
||||
* locally-built thread still lands instead of waiting forever. */
|
||||
const renderedConversationId = messagesTree[0]?.conversationId ?? conversationId;
|
||||
if (renderedConversationId !== conversationId) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (landedConversationRef.current === conversationId) {
|
||||
return;
|
||||
}
|
||||
|
||||
landedConversationRef.current = conversationId;
|
||||
scrollToBottom();
|
||||
}, [autoScroll, conversationId, messagesTree, scrollToBottom]);
|
||||
|
||||
return {
|
||||
conversation,
|
||||
contentRef,
|
||||
scrollableRef,
|
||||
messagesEndRef,
|
||||
scrollToBottom,
|
||||
handleSmoothToRef,
|
||||
debouncedHandleScroll,
|
||||
handleNearBottomChange,
|
||||
};
|
||||
}
|
||||
|
|
@ -1,123 +0,0 @@
|
|||
import { StrictMode, createRef, useRef } from 'react';
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { RefObject } from 'react';
|
||||
import useScrollToRef from '../useScrollToRef';
|
||||
|
||||
const followLabel = 'Follow';
|
||||
const jumpLabel = 'Jump';
|
||||
const scrollActions = [
|
||||
{ label: followLabel, behavior: 'instant', interval: 145 },
|
||||
{ label: jumpLabel, behavior: 'smooth', interval: 750 },
|
||||
];
|
||||
|
||||
function Harness({
|
||||
callback,
|
||||
smoothCallback,
|
||||
targetRef: suppliedRef,
|
||||
}: {
|
||||
callback: () => void;
|
||||
smoothCallback: () => void;
|
||||
targetRef?: RefObject<HTMLDivElement>;
|
||||
}) {
|
||||
const localRef = useRef<HTMLDivElement>(null);
|
||||
const targetRef = suppliedRef ?? localRef;
|
||||
const { scrollToRef, handleSmoothToRef } = useScrollToRef({
|
||||
targetRef,
|
||||
callback,
|
||||
smoothCallback,
|
||||
});
|
||||
return (
|
||||
<div>
|
||||
<button onClick={() => scrollToRef?.()}>{followLabel}</button>
|
||||
<button onClick={handleSmoothToRef}>{jumpLabel}</button>
|
||||
<div ref={targetRef} data-testid="end" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
describe('useScrollToRef lifecycle', () => {
|
||||
beforeEach(() => jest.useFakeTimers());
|
||||
afterEach(() => {
|
||||
jest.clearAllTimers();
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it.each(['Follow', 'Jump'])('cancels trailing %s work when the chat unmounts', (button) => {
|
||||
const callback = jest.fn();
|
||||
const smoothCallback = jest.fn();
|
||||
const { unmount } = render(<Harness callback={callback} smoothCallback={smoothCallback} />, {
|
||||
wrapper: StrictMode,
|
||||
});
|
||||
const scroll = jest.fn();
|
||||
screen.getByTestId('end').scrollIntoView = scroll;
|
||||
fireEvent.click(screen.getByText(button));
|
||||
fireEvent.click(screen.getByText(button));
|
||||
expect(callback.mock.calls.length + smoothCallback.mock.calls.length).toBe(1);
|
||||
|
||||
unmount();
|
||||
act(() => jest.advanceTimersByTime(1000));
|
||||
expect(callback.mock.calls.length + smoothCallback.mock.calls.length).toBe(1);
|
||||
expect(scroll).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each(['Follow', 'Jump'])('uses the latest callback for pending %s work', (button) => {
|
||||
const previous = jest.fn();
|
||||
const latest = jest.fn();
|
||||
const { rerender } = render(<Harness callback={previous} smoothCallback={previous} />, {
|
||||
wrapper: StrictMode,
|
||||
});
|
||||
const scroll = jest.fn();
|
||||
screen.getByTestId('end').scrollIntoView = scroll;
|
||||
fireEvent.click(screen.getByText(button));
|
||||
fireEvent.click(screen.getByText(button));
|
||||
rerender(<Harness callback={latest} smoothCallback={latest} />);
|
||||
act(() => jest.advanceTimersByTime(1000));
|
||||
|
||||
expect(previous).toHaveBeenCalledTimes(1);
|
||||
expect(latest).toHaveBeenCalledTimes(1);
|
||||
expect(scroll).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it.each(scrollActions)(
|
||||
'preserves leading and trailing $label timing',
|
||||
({ label, behavior, interval }) => {
|
||||
const callback = jest.fn();
|
||||
render(<Harness callback={callback} smoothCallback={callback} />, { wrapper: StrictMode });
|
||||
const scroll = jest.fn();
|
||||
screen.getByTestId('end').scrollIntoView = scroll;
|
||||
|
||||
fireEvent.click(screen.getByText(label));
|
||||
expect(scroll).toHaveBeenLastCalledWith({ behavior });
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
fireEvent.click(screen.getByText(label));
|
||||
act(() => jest.advanceTimersByTime(interval - 1));
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
act(() => jest.advanceTimersByTime(1));
|
||||
expect(callback).toHaveBeenCalledTimes(2);
|
||||
expect(scroll).toHaveBeenLastCalledWith({ behavior });
|
||||
},
|
||||
);
|
||||
|
||||
it.each(scrollActions)('cancels queued $label work when the target ref changes', ({ label }) => {
|
||||
const callback = jest.fn();
|
||||
const previousRef = createRef<HTMLDivElement>();
|
||||
const nextRef = createRef<HTMLDivElement>();
|
||||
const { rerender } = render(
|
||||
<Harness callback={callback} smoothCallback={callback} targetRef={previousRef} />,
|
||||
{ wrapper: StrictMode },
|
||||
);
|
||||
const scroll = jest.fn();
|
||||
screen.getByTestId('end').scrollIntoView = scroll;
|
||||
fireEvent.click(screen.getByText(label));
|
||||
fireEvent.click(screen.getByText(label));
|
||||
|
||||
rerender(<Harness callback={callback} smoothCallback={callback} targetRef={nextRef} />);
|
||||
act(() => jest.advanceTimersByTime(1000));
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
expect(scroll).toHaveBeenCalledTimes(1);
|
||||
|
||||
fireEvent.click(screen.getByText(label));
|
||||
expect(callback).toHaveBeenCalledTimes(2);
|
||||
expect(scroll).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
|
@ -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,
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue