Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): give the media correction a baseline it can measure
Yudhi Armyndharis640d630b15d7
diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsxindex 338ba30db..77ad5ef44 100644--- a/dashboard/src/components/chats/ChatThread.tsx+++ b/dashboard/src/components/chats/ChatThread.tsx@@ -29,6 +29,8 @@ interface ChatThreadProps {loadingOlderMessages: boolean;onLoadOlderMessages: () => void;onMediaLoad: (event?: { currentTarget: Element | null }) => void;+ /** Seeds each media element's pre-decode height; see useChatScrollPosition.measureMedia. */+ measureMedia: (el: Element | null) => void;onOpenImage: (messageId: string) => void;onReply: (message: ChatMessageView) => void;onReact: (message: ChatMessageView, emoji: string) => void;@@ -50,6 +52,7 @@ function ChatThread({loadingOlderMessages,onLoadOlderMessages,onMediaLoad,+ measureMedia,onOpenImage,onReply,onReact,@@ -227,7 +230,9 @@ function ChatThread({const thumb = msg.body && msg.body.length > 100 ? `data:image/jpeg;base64,${msg.body}` : '';return (<div className="message-location">- {thumb && <img src={thumb} alt="" onLoad={onMediaLoad} className="chat-location-media" />}+ {thumb && (+ <img ref={measureMedia} src={thumb} alt="" onLoad={onMediaLoad} className="chat-location-media" />+ )}<span className="message-media-omitted">π {t('chats.media.location')}</span></div>);@@ -279,6 +284,7 @@ function ChatThread({src={mediaSrc}alt={mediaInfo.filename || t('chats.media.image')}className="chat-image-media"+ ref={measureMedia}onLoad={onMediaLoad}onClick={() => onOpenImage(msg.id)}/>@@ -287,7 +293,13 @@ function ChatThread({case 'video':return (<div className="message-media-video">- <video src={mediaSrc} controls className="chat-video-media" onLoadedData={onMediaLoad} />+ <video+ ref={measureMedia}+ src={mediaSrc}+ controls+ className="chat-video-media"+ onLoadedData={onMediaLoad}+ /></div>);case 'audio':diff --git a/dashboard/src/hooks/useChatMessages.ts b/dashboard/src/hooks/useChatMessages.tsindex e85d027f9..751b1a609 100644--- a/dashboard/src/hooks/useChatMessages.ts+++ b/dashboard/src/hooks/useChatMessages.ts@@ -101,11 +101,15 @@ export function useChatMessages(// remount would stomp that newer write with the stale queued one. This effect stays as a second// chance for the same key in case the fetch had already settled before any write ever queued for// it β a normal case, and a no-op here since the queue is empty by then.- const { isFetching } = query;+ // Gated on `idle`, not on `isFetching`. A fetch the browser parks when it goes offline reports+ // fetchStatus 'paused', which makes `isFetching` false while the request is still going to land:+ // draining here would hand the resumed page a queue that no longer exists to replay. The writer+ // and the settle subscription key on the same value for the same reason.+ const { fetchStatus } = query;useEffect(() => {- if (isFetching) return;+ if (fetchStatus !== 'idle') return;replayWritesLostToFetch(queryClient, messagesQueryKey(sessionId, chatId ?? ''));- }, [queryClient, isFetching, sessionId, chatId]);+ }, [queryClient, fetchStatus, sessionId, chatId]);return query;}diff --git a/dashboard/src/hooks/useChatScrollPosition.test.ts b/dashboard/src/hooks/useChatScrollPosition.test.tsindex e407c931d..31e7df5a4 100644--- a/dashboard/src/hooks/useChatScrollPosition.test.ts+++ b/dashboard/src/hooks/useChatScrollPosition.test.ts@@ -1,6 +1,11 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { decideRestoreTarget, grewAboveReadingPosition, isNearBottom } from './useChatScrollPosition.ts';+import {+ correctionForMediaGrowth,+ decideRestoreTarget,+ grewAboveReadingPosition,+ isNearBottom,+} from './useChatScrollPosition.ts';test('isNearBottom: exactly at the bottom counts as near', () => {assert.equal(isNearBottom(1000, 2000, 1000), true); // 2000-1000-1000 = 0@@ -68,3 +73,44 @@ test('media straddling the top edge is left uncorrected rather than over-correct// would overshoot. Answering false drifts with the reader rather than against them.assert.equal(grewAboveReadingPosition(160, CONTAINER_TOP), false);});++// --- correctionForMediaGrowth -------------------------------------------------------------------+//+// The reading position is the container's top edge (CONTAINER_TOP, declared above). A media element+// that decodes above it pushes everything below down, so scrollTop has to grow by the same amount to+// keep the same content on screen.++test('an element that decoded above the reader is corrected by exactly its growth', () => {+ // Seeded 0px at mount, now 300px, and its post-decode bottom sits at 90: before it grew, its+ // bottom was at -210, well above the reading position.+ assert.equal(correctionForMediaGrowth(1000, 0, 300, 90, CONTAINER_TOP), 1300);+});++/**+ * The case a baseline taken in the load handler could never see. By then the decoded height is+ * already in layout, so seeded === current, the growth reads as zero, and nothing is corrected+ * while the reader has in fact been displaced.+ */+test('a baseline equal to the current height yields no correction, which is why it is seeded at mount', () => {+ assert.equal(correctionForMediaGrowth(1000, 300, 300, 90, CONTAINER_TOP), null);+});++test('an element that decoded below the reader is left alone', () => {+ // Grew 300, and even before growing its bottom was at 500: far below the top edge, so nothing+ // the reader can see moved. Correcting here would drag them toward the newest messages.+ assert.equal(correctionForMediaGrowth(1000, 0, 300, 800, CONTAINER_TOP), null);+});++/**+ * The subtraction is what makes the question answerable. Post-decode this element measures BELOW+ * the top edge (bottom 150 > 100), but it only got there by growing: before the decode its bottom+ * was at 50, above the reader, so it did displace them.+ */+test('the above/below question is asked against the pre-decode layout', () => {+ assert.equal(correctionForMediaGrowth(1000, 0, 100, 150, CONTAINER_TOP), 1100);+});++test('a shrink or an unchanged box corrects nothing', () => {+ assert.equal(correctionForMediaGrowth(1000, 300, 300, 50, CONTAINER_TOP), null);+ assert.equal(correctionForMediaGrowth(1000, 300, 120, 50, CONTAINER_TOP), null);+});diff --git a/dashboard/src/hooks/useChatScrollPosition.ts b/dashboard/src/hooks/useChatScrollPosition.tsindex 42d9c7860..25a5dd662 100644--- a/dashboard/src/hooks/useChatScrollPosition.ts+++ b/dashboard/src/hooks/useChatScrollPosition.ts@@ -57,10 +57,11 @@ export function decideRestoreTarget(* they scroll back), so late-decoding media never yanks a reading user.* - Reading further back: the same late-decode growth, above a viewport that is* NOT pinned to the bottom, holds the user's position instead of re-pinning.- * That is `onMediaLoad`'s third branch. It snapshots the height at the load- * event, since a decode has no requesting call to hang one on the way- * `onOlderMessagesRequested` does, and it corrects only for media sitting- * above the reading position: growth below it moves nothing on screen.+ * That is `onMediaLoad`'s third branch. The baseline comes from+ * `measureMedia`, a ref callback that records each element's box height at+ * DOM insertion, because a height read inside the load handler is already+ * post-decode and would measure the growth as zero. It corrects only for+ * media above the reading position: growth below it moves nothing on screen.** 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@@ -91,6 +92,31 @@ export function grewAboveReadingPosition(mediaBottom: number, containerTop: numbreturn mediaBottom <= containerTop;}+/**+ * The scrollTop that holds the reader still after a media element finished decoding, or null when+ * nothing on screen moved.+ *+ * `seededHeight` is the element's box height recorded when it MOUNTED. That matters: by the time a+ * `load` handler runs, the decoded size is already in layout, and every geometry read there flushes+ * it, so a baseline taken in the handler measures the growth as zero and the correction never+ * fires. DOM insertion is the one moment a browser guarantees is pre-decode.+ *+ * The growth is subtracted from the bottom edge before the above/below question is asked, because+ * `mediaBottom` is read post-decode: an element that displaced the reader can already measure below+ * the container's top edge by exactly the amount it grew.+ */+export function correctionForMediaGrowth(+ scrollTop: number,+ seededHeight: number,+ currentHeight: number,+ mediaBottom: number,+ containerTop: number,+): number | null {+ const grew = currentHeight - seededHeight;+ if (grew <= 0) return null;+ return grewAboveReadingPosition(mediaBottom - grew, containerTop) ? scrollTop + grew : null;+}+export function useChatScrollPosition(activeChatId: string | null,isLoaded: boolean,@@ -100,6 +126,8 @@ export function useChatScrollPosition(onMessageAppended: (direction: ScrollDirection) => void;/** Pass the load event through: which element grew decides whether the reader moved at all. */onMediaLoad: (event?: { currentTarget: Element | null }) => void;+ /** Ref callback for every inline media element; seeds the pre-decode height onMediaLoad needs. */+ measureMedia: (el: Element | null) => void;/** Call when an older page is requested; the reading position is held once it lands. */onOlderMessagesRequested: () => void;} {@@ -118,6 +146,9 @@ export function useChatScrollPosition(const prevScrollHeightRef = useRef<number>(0);const awaitingOlderPageRef = useRef<boolean>(false);const wasFetchingOlderRef = useRef<boolean>(false);+ // 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>());const writeScrollTop = useCallback((el: HTMLDivElement, top: number) => {const before = el.scrollTop;@@ -259,6 +290,11 @@ export function useChatScrollPosition(// reading down exactly like an unabsorbed older-page prepend, and it is held the same way. The// decode has no request event to hang a snapshot on, so the baseline is taken here, from the// load event itself, and the element that fired it says whether the reader moved at all.+ /** Attach to every inline media element: seeds its pre-decode height for onMediaLoad. */+ const measureMedia = useCallback((el: Element | null) => {+ if (el) mediaHeights.current.set(el, el.getBoundingClientRect().height);+ }, []);+const onMediaLoad = useCallback((event?: { currentTarget: Element | null }) => {const pending = pendingRestoreRef.current;@@ -282,26 +318,30 @@ export function useChatScrollPosition(// request-time snapshot that spans every commit until the page lands, decodes included.// Correcting here as well would count the same pixels twice and overshoot by the decode.if (awaitingOlderPageRef.current) return;- // Which element grew decides whether the reader moved at all; see grewAboveReadingPosition.+ // Which element grew, and by how much, decides whether the reader moved at all.const media = event?.currentTarget ?? null;if (!media) return;- if (!grewAboveReadingPosition(media.getBoundingClientRect().bottom, el.getBoundingClientRect().top)) {- return;- }- // Snapshot locally rather than from a ref any other commit can refresh: a render landing- // between this event and the frame below would otherwise consume the pending correction and- // leave the reader displaced with nothing to catch it.- const before = el.scrollHeight;+ const seeded = mediaHeights.current.get(media);+ if (seeded === undefined) return;+ const rect = media.getBoundingClientRect();+ // Re-seed before the frame: the element has finished growing, so its current box is the+ // baseline for any later change (a re-decode on a src swap, a lazy dimension arriving).+ mediaHeights.current.set(media, rect.height);+ const corrected = correctionForMediaGrowth(+ el.scrollTop,+ seeded,+ rect.height,+ rect.bottom,+ el.getBoundingClientRect().top,+ );+ if (corrected === null) return;requestAnimationFrame(() => {const cur = containerRef.current;if (!cur) return;// The container is reused across chats, so a switch between the event and this frame would- // measure the new thread and save the result under the old chat's id. prevChatIdRef holds- // whichever chat is actually on screen, set by the restore effect above.+ // apply the correction to a different thread and save it under the outgoing chat's id.+ // prevChatIdRef holds whichever chat is actually on screen, set by the restore effect above.if (prevChatIdRef.current !== activeChatId) return;- const grew = cur.scrollHeight - before;- if (grew <= 0) return;- const corrected = cur.scrollTop + grew;writeScrollTop(cur, corrected);if (activeChatId !== null) scrollMap.current.set(activeChatId, corrected);});@@ -309,5 +349,5 @@ export function useChatScrollPosition([activeChatId, pinToBottom, writeScrollTop],);- return { containerRef, onMessageAppended, onMediaLoad, onOlderMessagesRequested };+ return { containerRef, onMessageAppended, onMediaLoad, measureMedia, onOlderMessagesRequested };}diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex d9ecb30f7..1b933d44c 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -235,6 +235,7 @@ export function Chats() {containerRef: messagesContainerRef,onMessageAppended,onMediaLoad,+ measureMedia,onOlderMessagesRequested,} = useChatScrollPosition(activeChat?.id ?? null, messages.length > 0, loadingOlderMessages);@@ -927,6 +928,7 @@ export function Chats() {loadingOlderMessages={loadingOlderMessages}onLoadOlderMessages={handleLoadOlderMessages}onMediaLoad={onMediaLoad}+ measureMedia={measureMedia}onOpenImage={messageId => {const idx = imageMedia.findIndex(x => x.id === messageId);if (idx >= 0) setLightboxIndex(idx);