Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): hold the reader by their message on an older page
Yudhi Armyndharis31aff52cafd0
diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsxindex 9e2d67cd0..3efbeabc5 100644--- a/dashboard/src/components/chats/ChatThread.tsx+++ b/dashboard/src/components/chats/ChatThread.tsx@@ -434,6 +434,7 @@ function ChatThread({key={msg.id}className={`message-bubble-wrapper ${isMe ? 'outgoing' : 'incoming'}`}data-wa-message-id={msg.waMessageId}+ data-scroll-anchor=""><div className="message-bubble-container"><divdiff --git a/dashboard/src/hooks/useChatScrollPosition.render.test.ts b/dashboard/src/hooks/useChatScrollPosition.render.test.tsindex 2267b19bb..d6ea4c8f5 100644--- a/dashboard/src/hooks/useChatScrollPosition.render.test.ts+++ b/dashboard/src/hooks/useChatScrollPosition.render.test.ts@@ -4,7 +4,7 @@import '../test-helpers/register-hooks.ts';import { test, before, after } from 'node:test';import assert from 'node:assert/strict';-import { createElement } from 'react';+import { createElement, useEffect, type MutableRefObject } from 'react';let rtl: typeof import('@testing-library/react');let useChatScrollPosition: (typeof import('./useChatScrollPosition.ts'))['useChatScrollPosition'];@@ -71,3 +71,73 @@ test('switching to a chat that is still loading does not save the clamped top as}}});++// An older page lands above the reader. Previews that swap in BELOW the reader while it is in flight grow+// the thread but move nothing on screen, so holding the reader by the thread's height delta dragged them+// down the thread by those pixels. The reader is held by the message they were on.+test('an older page holds the reader by their message, not by every pixel the thread grew', async () => {+ const { render, screen, cleanup } = rtl;+ cleanup();+ const top = { value: 0 };+ // Content-coordinate tops of the three messages the thread holds; the viewport shows 400px of them.+ const messageTops = new Map<string, number>([+ ['m1', 100],+ ['m2', 500],+ ['m3', 900],+ ]);+ let height = 1300;+ const proto = window.HTMLDivElement.prototype;+ const saved = Object.getOwnPropertyDescriptors(proto);+ const rectSaved = window.Element.prototype.getBoundingClientRect;+ Object.defineProperties(proto, {+ scrollHeight: { configurable: true, get: () => height },+ clientHeight: { configurable: true, get: () => CLIENT_HEIGHT },+ scrollTop: {+ configurable: true,+ get: () => top.value,+ set: (v: number) => {+ top.value = Math.max(0, Math.min(v, height - CLIENT_HEIGHT));+ },+ },+ });+ window.Element.prototype.getBoundingClientRect = function (this: Element) {+ const content = messageTops.get(this.getAttribute('data-id') ?? '');+ const y = content === undefined ? 0 : content - top.value;+ return { top: y, bottom: y + 300, left: 0, right: 0, width: 0, height: 300, x: 0, y } as DOMRect;+ };++ const request: MutableRefObject<(() => void) | null> = { current: null };+ function Older({ fetching }: { fetching: boolean }) {+ const { containerRef, onOlderMessagesRequested } = useChatScrollPosition('A', true, fetching);+ useEffect(() => {+ request.current = onOlderMessagesRequested;+ });+ return createElement(+ 'div',+ { ref: containerRef, 'data-testid': 'thread' },+ ['m1', 'm2', 'm3'].map(id => createElement('div', { key: id, 'data-id': id, 'data-scroll-anchor': '' })),+ );+ }++ try {+ const { rerender } = render(createElement(Older, { fetching: false }));+ const el = screen.getByTestId('thread');+ // The reader is on m2 (500..800 in content, the viewport 400..800), 100px below the container's top.+ top.value = 400;+ request.current?.();+ rerender(createElement(Older, { fetching: true }));++ // The page lands: 2000px of history above, and a 230px preview swapped in below m3 meanwhile.+ for (const [id, y] of [...messageTops]) messageTops.set(id, y + 2000);+ height += 2000 + 230;+ rerender(createElement(Older, { fetching: false }));++ assert.equal(el.scrollTop, 400 + 2000, 'the reader moved by more or less than the history above them');+ } finally {+ 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];+ }+ window.Element.prototype.getBoundingClientRect = rectSaved;+ }+});diff --git a/dashboard/src/hooks/useChatScrollPosition.ts b/dashboard/src/hooks/useChatScrollPosition.tsindex 7f9ce31f6..df452a3a1 100644--- a/dashboard/src/hooks/useChatScrollPosition.ts+++ b/dashboard/src/hooks/useChatScrollPosition.ts@@ -119,6 +119,23 @@ export function correctionForMediaGrowth(return grewAboveReadingPosition(mediaBottom - grew, containerTop) ? grew : null;}+/** Marks the direct children of the scroll container a reader can be held in place by. */+export const SCROLL_ANCHOR_ATTRIBUTE = 'data-scroll-anchor';++/**+ * The first anchor element the reader can see, with its offset from the container's top edge: the+ * thing an older page landing above must hold still, whatever grew elsewhere in the thread meanwhile.+ */+function firstVisibleAnchor(container: HTMLElement): { node: Element; top: number } | null {+ const containerTop = container.getBoundingClientRect().top;+ for (const child of Array.from(container.children)) {+ if (!child.hasAttribute(SCROLL_ANCHOR_ATTRIBUTE)) continue;+ const rect = child.getBoundingClientRect();+ if (rect.bottom > containerTop) return { node: child, top: rect.top - containerTop };+ }+ return null;+}+export function useChatScrollPosition(activeChatId: string | null,isLoaded: boolean,@@ -152,6 +169,8 @@ export function useChatScrollPosition(const prevScrollHeightRef = useRef<number>(0);const awaitingOlderPageRef = useRef<boolean>(false);const wasFetchingOlderRef = useRef<boolean>(false);+ // The element the reader was on when the older page was requested; see the landing effect.+ const olderAnchorRef = useRef<{ node: Element; top: number } | null>(null);// Box height of each mounted media element, recorded at DOM insertion: the one moment a browser// guarantees is before the decode. A WeakMap so entries die with the nodes on a chat switch.const mediaHeights = useRef(new WeakMap<Element, number>());@@ -230,12 +249,12 @@ export function useChatScrollPosition(// was reading is pushed down by however much taller it just got. Left alone the view jumps// backwards at the exact moment they asked for more.//- // The height is read when the page is REQUESTED and the delta applied on the commit where the- // in-flight flag falls — not on the first commit whose height changed, because the older-page- // spinner is an in-flow child of this same container (ChatThread) and its own ~46px arrives one- // commit earlier. Only `scrollHeight` is held; `scrollTop` is read live at apply time, so a- // deliberate reposition made during the fetch survives. The pin/restore machinery above is not- // reused: it writes an ABSOLUTE target, which is unknowable here.+ // The reader's element and its offset are read when the page is REQUESTED and the delta applied on+ // the commit where the in-flight flag falls — not on the first commit whose height changed, because+ // the older-page spinner is an in-flow child of this same container (ChatThread) and its own ~46px+ // arrives one commit earlier. `scrollTop` is read live at apply time, so a deliberate reposition+ // made during the fetch survives. The pin/restore machinery above is not reused: it writes an+ // ABSOLUTE target, which is unknowable here.useLayoutEffect(() => {const el = containerRef.current;const wasFetching = wasFetchingOlderRef.current;@@ -245,10 +264,17 @@ export function useChatScrollPosition(// a media decode, another query resolving — would otherwise consume the pending correction.if (!el || isFetchingOlderMessages || !wasFetching || !awaitingOlderPageRef.current) return;awaitingOlderPageRef.current = false;- // A live message landing mid-fetch is inside this delta too, and it grew the thread at the- // BOTTOM where no correction is wanted — one bubble of overshoot in that race, against a whole- // page of it if the prepend went uncorrected.- const grew = el.scrollHeight - prevScrollHeightRef.current;+ // How far the element the reader was on moved down. Measured on the element, not as a change of the+ // whole thread's height: a preview that swapped in below the reader, or a live message at the+ // bottom, while the page was in flight is inside that height delta and moves nothing on screen, so+ // adding it dragged the reader down the thread. Without a surviving anchor (a chat that had no+ // visible message, or one re-rendered under another key) the height delta is all there is.+ const anchor = olderAnchorRef.current;+ olderAnchorRef.current = null;+ const grew =+ anchor && el.contains(anchor.node)+ ? anchor.node.getBoundingClientRect().top - el.getBoundingClientRect().top - anchor.top+ : el.scrollHeight - prevScrollHeightRef.current;if (grew > 0) {const corrected = el.scrollTop + grew;writeScrollTop(el, corrected);@@ -265,6 +291,7 @@ export function useChatScrollPosition(const el = containerRef.current;if (!el) return;prevScrollHeightRef.current = el.scrollHeight;+ olderAnchorRef.current = firstVisibleAnchor(el);awaitingOlderPageRef.current = true;}, []);