Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(Chat): scrollToMessage lands a message at the page's top (#10781)

Christopher Chedeaue633aab2b278
diff --git a/.changeset/chat-stream-scroll-to-message-page.md b/.changeset/chat-stream-scroll-to-message-page.md
new file mode 100644
index 0000000000..6b277959a6
--- /dev/null
+++ b/.changeset/chat-stream-scroll-to-message-page.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `useChatStreamScroll`'s `scrollToMessage` now puts the message at the top of the viewport when the scroller is the page itself. It landed off by the page's own scroll.
+@vjeux
diff --git a/packages/core/src/Chat/ChatLayout.test.tsx b/packages/core/src/Chat/ChatLayout.test.tsx
index d7f90cfe25..0d5cb1ea12 100644
--- a/packages/core/src/Chat/ChatLayout.test.tsx
+++ b/packages/core/src/Chat/ChatLayout.test.tsx
@@ -131,17 +131,6 @@ describe('ChatLayout — default scroll button keyboard reachability', () => {
});
});
-// ---------------------------------------------------------------------------
-// Self-scroll layout contract (#2573)
-//
-// jsdom has no layout, so these assert the class-level CSS intent: the root
-// must be a flex column whose message area flexes (grow, no shrink) instead
-// of forcing minHeight: 100%. With minHeight: 100% the in-flow sticky dock
-// added its full height on top of the message area, so the root always
-// overflowed by exactly the dock height (phantom scrollbar). Real-layout
-// geometry was verified in a browser; see the PR for measurements.
-// ---------------------------------------------------------------------------
-
describe('ChatLayout — a page that scrolls the document', () => {
// The page's root element scrolls, and the browser raises the scroll at the
// document. The root's offsetHeight is the page's height; its clientHeight
@@ -190,6 +179,17 @@ describe('ChatLayout — a page that scrolls the document', () => {
});
});
+// ---------------------------------------------------------------------------
+// Self-scroll layout contract (#2573)
+//
+// jsdom has no layout, so these assert the class-level CSS intent: the root
+// must be a flex column whose message area flexes (grow, no shrink) instead
+// of forcing minHeight: 100%. With minHeight: 100% the in-flow sticky dock
+// added its full height on top of the message area, so the root always
+// overflowed by exactly the dock height (phantom scrollbar). Real-layout
+// geometry was verified in a browser; see the PR for measurements.
+// ---------------------------------------------------------------------------
+
describe('ChatLayout — self-scroll layout contract (#2573)', () => {
it('root is a flex column so the dock height is part of the 100%', () => {
render(
diff --git a/packages/core/src/Chat/__tests__/useChatStreamScrollPage.a11y.browser.spec.ts b/packages/core/src/Chat/__tests__/useChatStreamScrollPage.a11y.browser.spec.ts
index cfcb6247df..b313e0f5fc 100644
--- a/packages/core/src/Chat/__tests__/useChatStreamScrollPage.a11y.browser.spec.ts
+++ b/packages/core/src/Chat/__tests__/useChatStreamScrollPage.a11y.browser.spec.ts
@@ -105,9 +105,9 @@ async function restingTop(page: Page) {
return last;
}
-async function scrollPageUp(page: Page) {
+async function scrollPageUp(page: Page, distance = 600) {
await page.mouse.move(200, 200);
- await page.mouse.wheel(0, -600);
+ await page.mouse.wheel(0, -distance);
await expect
.poll(async () => pageGap(page), {timeout: SETTLE_TIMEOUT_MS})
.toBeGreaterThan(100);
@@ -154,3 +154,21 @@ test('leaves a reader who scrolled up in place when messages arrive', async ({
const after = await page.evaluate(() => document.documentElement.scrollTop);
expect(Math.abs(after - before)).toBeLessThanOrEqual(1);
});
+
+test('puts a message at the top of the viewport with scrollToMessage', async ({
+ page,
+}) => {
+ // A reader's scroll, not a script's. A script's scroll can land between two
+ // frames of the opening follow, which then takes the page back to its end.
+ await scrollPageUp(page, 1300);
+ await page.getByRole('button', {name: 'Scroll to the message'}).click();
+ await expect
+ .poll(
+ async () =>
+ page
+ .locator('[data-message]')
+ .evaluate(element => Math.round(element.getBoundingClientRect().top)),
+ {timeout: SETTLE_TIMEOUT_MS},
+ )
+ .toBe(0);
+});
diff --git a/packages/core/src/Chat/__tests__/useChatStreamScrollPage.fixture.tsx b/packages/core/src/Chat/__tests__/useChatStreamScrollPage.fixture.tsx
index a6c6440c75..188c615e7d 100644
--- a/packages/core/src/Chat/__tests__/useChatStreamScrollPage.fixture.tsx
+++ b/packages/core/src/Chat/__tests__/useChatStreamScrollPage.fixture.tsx
@@ -15,20 +15,32 @@ import {useChatStreamScroll} from '../useChatStreamScroll';
function App() {
const scrollRef = useRef<HTMLElement>(document.documentElement);
- const {scrollIfLocked, isLocked, isScrolledUp} = useChatStreamScroll({
- scrollRef,
- });
+ const {scrollIfLocked, scrollToMessage, isLocked, isScrolledUp} =
+ useChatStreamScroll({scrollRef});
+ const messageRef = useRef<HTMLDivElement>(null);
const [extra, setExtra] = useState(0);
useEffect(() => scrollIfLocked(), [extra, scrollIfLocked]);
return (
<main style={{paddingBlockEnd: 64}}>
- <div style={{height: 2400}}>Earlier messages</div>
+ <div style={{height: 1200}}>Earlier messages</div>
+ <div ref={messageRef} data-message style={{height: 1200}}>
+ A message to scroll to
+ </div>
<div>Latest message</div>
{extra > 0 && <div style={{height: extra}}>New messages</div>}
<div style={{position: 'fixed', insetInline: 0, bottom: 0}}>
<button type="button" onClick={() => setExtra(value => value + 400)}>
Append messages
</button>
+ <button
+ type="button"
+ onClick={() => {
+ if (messageRef.current) {
+ scrollToMessage(messageRef.current);
+ }
+ }}>
+ Scroll to the message
+ </button>
<output
data-locked={String(isLocked)}
data-scrolled-up={String(isScrolledUp)}
diff --git a/packages/core/src/Chat/useChatStreamScroll.test.tsx b/packages/core/src/Chat/useChatStreamScroll.test.tsx
index 8fd76a7219..4315bfc4f9 100644
--- a/packages/core/src/Chat/useChatStreamScroll.test.tsx
+++ b/packages/core/src/Chat/useChatStreamScroll.test.tsx
@@ -465,6 +465,30 @@ describe('useChatStreamScroll — the page as the scroller', () => {
expect(api.current!.isLocked).toBe(true);
});
+ it('puts a message at the top of the viewport with scrollToMessage', () => {
+ const {api} = renderPage();
+ root.scrollTop = 1000;
+ const scrollTo = vi.fn();
+ Object.defineProperty(root, 'scrollTo', {
+ value: scrollTo,
+ configurable: true,
+ });
+ vi.spyOn(root, 'getBoundingClientRect').mockReturnValue({
+ top: -1000,
+ } as DOMRect);
+ const message = document.createElement('div');
+ vi.spyOn(message, 'getBoundingClientRect').mockReturnValue({
+ top: 300,
+ } as DOMRect);
+ try {
+ api.current!.scrollToMessage(message);
+ expect(scrollTo).toHaveBeenCalledWith({top: 1300, behavior: 'instant'});
+ } finally {
+ Reflect.deleteProperty(root, 'scrollTo');
+ vi.restoreAllMocks();
+ }
+ });
+
it('ignores the scroll of an element inside the page', () => {
const {api} = renderPage();
const panel = document.createElement('div');
@@ -478,3 +502,25 @@ describe('useChatStreamScroll — the page as the scroller', () => {
}
});
});
+
+describe('useChatStreamScroll — scrollToMessage in a scrolling element', () => {
+ it('puts a message at the top of the element\u2019s visible area', () => {
+ const {api, el} = renderHook();
+ el.scrollTop = 50;
+ const scrollTo = vi.fn();
+ Object.defineProperty(el, 'scrollTo', {
+ value: scrollTo,
+ configurable: true,
+ });
+ vi.spyOn(el, 'getBoundingClientRect').mockReturnValue({
+ top: 100,
+ } as DOMRect);
+ const message = document.createElement('div');
+ vi.spyOn(message, 'getBoundingClientRect').mockReturnValue({
+ top: 400,
+ } as DOMRect);
+ api.current!.scrollToMessage(message);
+ expect(scrollTo).toHaveBeenCalledWith({top: 350, behavior: 'instant'});
+ vi.restoreAllMocks();
+ });
+});
diff --git a/packages/core/src/Chat/useChatStreamScroll.ts b/packages/core/src/Chat/useChatStreamScroll.ts
index e20a2ff001..a850fdad8e 100644
--- a/packages/core/src/Chat/useChatStreamScroll.ts
+++ b/packages/core/src/Chat/useChatStreamScroll.ts
@@ -154,6 +154,13 @@ function markFollowing(el: Element, locked: boolean): void {
}
}
+// The page's scroll fires at the document. The root's box moves up by that
+// scroll.
+function scrollsPage(el: HTMLElement): boolean {
+ const doc = el.ownerDocument;
+ return el === doc.scrollingElement || el === doc.documentElement;
+}
+
export function useChatStreamScroll({
scrollRef,
enabled = true,
@@ -307,9 +314,12 @@ export function useChatStreamScroll({
if (!container) {
return;
}
- const containerRect = container.getBoundingClientRect();
- const elRect = el.getBoundingClientRect();
- const offset = elRect.top - containerRect.top + container.scrollTop;
+ // The page's visible area starts at the viewport's top, not at the
+ // root's box.
+ const top = scrollsPage(container)
+ ? 0
+ : container.getBoundingClientRect().top;
+ const offset = el.getBoundingClientRect().top - top + container.scrollTop;
container.scrollTo({top: offset, behavior: 'instant'});
lastScrollTopRef.current = container.scrollTop;
},
@@ -376,11 +386,10 @@ export function useChatStreamScroll({
lastScrollTopRef.current = el.scrollTop;
markFollowing(el, lockedRef.current);
const doc = el.ownerDocument;
- const scrollsPage =
- el === doc.scrollingElement || el === doc.documentElement;
+ const isPage = scrollsPage(el);
// The root's offsetHeight is the page's height. Its clientHeight is the
// viewport's, which is what the reader sees.
- const shownHeight = () => (scrollsPage ? el.clientHeight : el.offsetHeight);
+ const shownHeight = () => (isPage ? el.clientHeight : el.offsetHeight);
const onScroll = () => {
const {scrollTop, scrollHeight} = el;
@@ -412,7 +421,7 @@ export function useChatStreamScroll({
};
// A scroll of the page fires at the document, not at its root element.
- const view = scrollsPage ? doc.defaultView : null;
+ const view = isPage ? doc.defaultView : null;
const stopPageListeners: (() => void)[] = [];
if (view != null) {
const atDocument = (listener: () => void) => (event: Event) => {