Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): keep a chat left at the bottom at the bottom

Yudhi Armyndharis506334a0af9d
diff --git a/dashboard/src/hooks/useChatScrollPosition.render.test.ts b/dashboard/src/hooks/useChatScrollPosition.render.test.ts
index 26c3ba839..98f6aca2c 100644
--- a/dashboard/src/hooks/useChatScrollPosition.render.test.ts
+++ b/dashboard/src/hooks/useChatScrollPosition.render.test.ts
@@ -219,3 +219,167 @@ for (const scenario of [
}
});
}
+
+// ── Live messages and the per-chat position memory ───────────────────────────
+// One container whose geometry the test drives: `height` is what its content measures and `top` what a
+// browser would report, clamped to the content.
+
+type Geometry = { height: number; top: number };
+
+function installGeometry(state: Geometry): () => void {
+ const maxTop = () => Math.max(0, state.height - CLIENT_HEIGHT);
+ const proto = window.HTMLDivElement.prototype;
+ const saved = Object.getOwnPropertyDescriptors(proto);
+ Object.defineProperties(proto, {
+ scrollHeight: { configurable: true, get: () => state.height },
+ clientHeight: { configurable: true, get: () => CLIENT_HEIGHT },
+ scrollTop: {
+ configurable: true,
+ get: () => Math.min(state.top, maxTop()),
+ set: (v: number) => {
+ state.top = Math.max(0, Math.min(v, maxTop()));
+ },
+ },
+ });
+ return () => {
+ for (const key of ['scrollHeight', 'clientHeight', 'scrollTop'] as const) {
+ if (saved[key]) Object.defineProperty(proto, key, saved[key]);
+ else delete (proto as unknown as Record<string, unknown>)[key];
+ }
+ };
+}
+
+// What the last commit's hook call returned: the callbacks a page would hand to its components.
+const hookRef: MutableRefObject<ReturnType<typeof useChatScrollPosition> | null> = { current: null };
+const hook = (): ReturnType<typeof useChatScrollPosition> =>
+ hookRef.current as ReturnType<typeof useChatScrollPosition>;
+
+function Probe({ chatId }: { chatId: string | null }) {
+ const result = useChatScrollPosition(chatId, chatId !== null, false);
+ useEffect(() => {
+ hookRef.current = result;
+ });
+ return createElement('div', { ref: result.containerRef, 'data-testid': 'thread' });
+}
+
+const nextFrame = () => new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
+
+/** The reader moves the thread: the position changes, then the browser reports it. */
+function readerScrollsTo(el: HTMLElement, top: number): void {
+ el.scrollTop = top;
+ rtl.fireEvent.scroll(el);
+}
+
+/**
+ * A live message of `rowPx` the way the Chats page delivers one: announced to the hook while the thread
+ * still has the height it had, then committed, then a frame.
+ */
+async function liveMessage(
+ state: Geometry,
+ rerender: (ui: ReturnType<typeof createElement>) => void,
+ direction: 'incoming' | 'outgoing',
+ rowPx: number,
+ chatId = 'A',
+): Promise<void> {
+ hook().onMessageAppended(direction);
+ state.height += rowPx;
+ rerender(createElement(Probe, { chatId }));
+ await nextFrame();
+}
+
+test('a chat left at the bottom comes back at its newest message when more arrived while the reader was elsewhere', async () => {
+ const { render, screen, fireEvent, cleanup } = rtl;
+ cleanup();
+ const g: Geometry = { height: 4600, top: 0 };
+ const restore = installGeometry(g);
+ try {
+ const { rerender } = render(createElement(Probe, { chatId: 'A' }));
+ const el = screen.getByTestId('thread');
+ fireEvent.scroll(el);
+ readerScrollsTo(el, 3000);
+ readerScrollsTo(el, g.height - CLIENT_HEIGHT); // the reader leaves A at its bottom
+
+ rerender(createElement(Probe, { chatId: 'B' }));
+ fireEvent.scroll(el);
+ g.height = 5200; // while they read B, two messages reached A's cached thread
+ rerender(createElement(Probe, { chatId: 'A' }));
+ assert.equal(el.scrollTop, g.height - CLIENT_HEIGHT, 'chat A came back above the messages that arrived');
+ } finally {
+ restore();
+ }
+});
+
+test('a chat left at the bottom comes back at the bottom after live messages followed it', async () => {
+ const { render, screen, fireEvent, cleanup } = rtl;
+ cleanup();
+ const g: Geometry = { height: 4600, top: 0 };
+ const restore = installGeometry(g);
+ try {
+ const { rerender } = render(createElement(Probe, { chatId: 'A' }));
+ const el = screen.getByTestId('thread');
+ fireEvent.scroll(el); // the event for the write that opened the chat at its bottom
+ // The reader goes up a little and back down, so the position is remembered by genuine scrolls.
+ readerScrollsTo(el, 3000);
+ readerScrollsTo(el, g.height - CLIENT_HEIGHT);
+
+ await liveMessage(g, rerender, 'incoming', 300);
+ await liveMessage(g, rerender, 'incoming', 300);
+ assert.equal(el.scrollTop, g.height - CLIENT_HEIGHT, 'the thread did not follow the live messages');
+
+ g.height = 4600; // chat B has a thread of its own
+ rerender(createElement(Probe, { chatId: 'B' }));
+ fireEvent.scroll(el);
+ g.height = 5200; // chat A again, its cached thread holding both messages
+ rerender(createElement(Probe, { chatId: 'A' }));
+ assert.equal(el.scrollTop, g.height - CLIENT_HEIGHT, 'chat A came back above its newest messages');
+ } finally {
+ restore();
+ }
+});
+
+// Between the pin threshold (24px) and the follow threshold (100px) the reader is not pinned but a live message
+// still scrolls the thread, and the position remembered for the chat is then the one before the message.
+test('a chat left just above the bottom comes back at the bottom after a live message followed it', async () => {
+ const { render, screen, fireEvent, cleanup } = rtl;
+ cleanup();
+ const g: Geometry = { height: 4600, top: 0 };
+ const restore = installGeometry(g);
+ try {
+ const { rerender } = render(createElement(Probe, { chatId: 'A' }));
+ const el = screen.getByTestId('thread');
+ fireEvent.scroll(el);
+ readerScrollsTo(el, g.height - CLIENT_HEIGHT - 60);
+
+ await liveMessage(g, rerender, 'incoming', 300);
+ assert.equal(el.scrollTop, g.height - CLIENT_HEIGHT, 'the thread did not follow the live message');
+
+ g.height = 4600;
+ rerender(createElement(Probe, { chatId: 'B' }));
+ fireEvent.scroll(el);
+ g.height = 4900;
+ rerender(createElement(Probe, { chatId: 'A' }));
+ assert.equal(el.scrollTop, g.height - CLIENT_HEIGHT, 'chat A came back above its newest message');
+ } finally {
+ restore();
+ }
+});
+
+test('a chat left mid-thread comes back where the reader left it', async () => {
+ const { render, screen, fireEvent, cleanup } = rtl;
+ cleanup();
+ const g: Geometry = { height: 4600, top: 0 };
+ const restore = installGeometry(g);
+ try {
+ const { rerender } = render(createElement(Probe, { chatId: 'A' }));
+ const el = screen.getByTestId('thread');
+ fireEvent.scroll(el);
+ readerScrollsTo(el, 3000);
+
+ rerender(createElement(Probe, { chatId: 'B' }));
+ fireEvent.scroll(el);
+ rerender(createElement(Probe, { chatId: 'A' }));
+ assert.equal(el.scrollTop, 3000);
+ } finally {
+ restore();
+ }
+});
diff --git a/dashboard/src/hooks/useChatScrollPosition.ts b/dashboard/src/hooks/useChatScrollPosition.ts
index fe036e0b6..256f281e8 100644
--- a/dashboard/src/hooks/useChatScrollPosition.ts
+++ b/dashboard/src/hooks/useChatScrollPosition.ts
@@ -65,7 +65,9 @@ export function decideRestoreTarget(
*
* Mount the returned `containerRef` on the scroll container (the `.room-messages`
* div in Chats.tsx). The Map of saved positions lives in a ref so it doesn't
- * trigger renders and is garbage-collected when the host component unmounts.
+ * trigger renders and is garbage-collected when the host component unmounts. A chat the
+ * reader left at the bottom has no entry (it reopens at its newest message), however
+ * much arrived after their last scroll.
*/
/** Distance from the bottom (px) within which the user still counts as "at the bottom". */
@@ -195,6 +197,16 @@ export function useChatScrollPosition(
[writeScrollTop],
);
+ // A pin that follows the thread (a live message, a decoded image) forgets the chat's remembered offset too: the
+ // reader is at the bottom again, and the offset from before the thread grew would bring them back above it.
+ const followBottom = useCallback(
+ (el: HTMLDivElement) => {
+ pinToBottom(el);
+ if (prevChatIdRef.current !== null) scrollMap.current.delete(prevChatIdRef.current);
+ },
+ [pinToBottom],
+ );
+
// Track pin state from scroll geometry: any scroll that lands at the bottom (ours or the user's)
// pins; any scroll away (only ever the user's) unpins. The SAME listener saves the visible
// chat's scrollTop on every genuine user scroll, so the per-chat position map always holds the
@@ -212,9 +224,15 @@ export function useChatScrollPosition(
}
// A genuine user scroll: cancels any pending restore, then updates pin + position map.
pendingRestoreRef.current = null;
- pinnedRef.current = isNearBottom(el.scrollTop, el.scrollHeight, el.clientHeight);
+ const atBottom = isNearBottom(el.scrollTop, el.scrollHeight, el.clientHeight);
+ pinnedRef.current = atBottom;
const visibleChatId = prevChatIdRef.current;
- if (visibleChatId && loadedRef.current) scrollMap.current.set(visibleChatId, el.scrollTop);
+ if (visibleChatId && loadedRef.current) {
+ // At the bottom is a state, not an offset: the thread keeps growing under a reader who follows it, so a
+ // chat left there is opened at its newest message, not at the offset it had when the reader scrolled.
+ if (atBottom) scrollMap.current.delete(visibleChatId);
+ else scrollMap.current.set(visibleChatId, el.scrollTop);
+ }
};
el.addEventListener('scroll', onScroll, { passive: true });
return () => el.removeEventListener('scroll', onScroll);
@@ -311,10 +329,10 @@ export function useChatScrollPosition(
if (action === 'preserve') return;
requestAnimationFrame(() => {
const cur = containerRef.current;
- if (cur) pinToBottom(cur);
+ if (cur) followBottom(cur);
});
},
- [pinToBottom],
+ [followBottom],
);
// Media has no layout box before it decodes. While pinned, each decode re-pins to the bottom;
@@ -346,7 +364,7 @@ export function useChatScrollPosition(
if (pinnedRef.current) {
requestAnimationFrame(() => {
const cur = containerRef.current;
- if (cur && pinnedRef.current) pinToBottom(cur);
+ if (cur && pinnedRef.current) followBottom(cur);
});
return;
}
@@ -382,7 +400,7 @@ export function useChatScrollPosition(
if (activeChatId !== null) scrollMap.current.set(activeChatId, next);
});
},
- [activeChatId, pinToBottom, writeScrollTop],
+ [activeChatId, followBottom, writeScrollTop],
);
return { containerRef, onMessageAppended, onMediaLoad, measureMedia, onOlderMessagesRequested };