Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): hold a reader through decodes while a page loads

Yudhi Armyndharis6d0283da27b2
diff --git a/dashboard/src/hooks/useChatScrollPosition.render.test.ts b/dashboard/src/hooks/useChatScrollPosition.render.test.ts
index 27d3394d6..18c165727 100644
--- a/dashboard/src/hooks/useChatScrollPosition.render.test.ts
+++ b/dashboard/src/hooks/useChatScrollPosition.render.test.ts
@@ -1041,9 +1041,10 @@ test('a decode after an older page landed does not apply the saved spot from bef
// ── A thread of message rows ─────────────────────────────────────────────────
// Rows laid out top to bottom in the container, each an anchor; a row may hold an image, which the test grows as it
-// decodes. Positions are what a browser would report for them at the current scrollTop.
+// decodes, under its text or (imgFirst) above it. Positions are what a browser would report for them at the current
+// scrollTop.
-type Row = { id: string; h: number; img?: number; anchor?: false };
+type Row = { id: string; h: number; img?: number; anchor?: false; imgFirst?: true };
type Thread = { rows: Row[]; top: number };
const rowsHeight = (t: Thread) => t.rows.reduce((sum, r) => sum + r.h + (r.img ?? 0), 0);
@@ -1072,7 +1073,8 @@ function installRows(t: Thread): () => void {
const id = this.getAttribute('data-id') ?? this.getAttribute('data-img');
let y = -Math.min(t.top, rowsMax(t));
for (const r of t.rows) {
- if (r.id === id) return this.hasAttribute('data-img') ? box(y + r.h, r.img ?? 0) : box(y, r.h + (r.img ?? 0));
+ if (r.id === id)
+ return this.hasAttribute('data-img') ? box(y + (r.imgFirst ? 0 : r.h), r.img ?? 0) : box(y, r.h + (r.img ?? 0));
y += r.h + (r.img ?? 0);
}
return box(0, CLIENT_HEIGHT); // the container
@@ -1346,6 +1348,68 @@ test('an image that decodes above where the reader scrolled while an older page
}
});
+// An image above the reader that decodes while a page is out holds them in its frame, as it does with no page out, and
+// the landing then counts it once: whichever comes first of its load, the request, a scroll of the reader, the frame
+// and the landing. The reader is on a4, 50px under the top edge; the page is 1000px. The image grows by 30px, so the row
+// the reader is on stays below it however the thread is read.
+for (const scenario of [
+ { name: 'in its frame', order: ['request', 'decode', 'frame', 'land'] },
+ { name: 'when its load came just before the page was asked for', order: ['decode', 'request', 'frame', 'land'] },
+ { name: 'when the page lands before its frame', order: ['request', 'decode', 'land', 'frame'] },
+ { name: 'when the reader scrolls before its frame', order: ['request', 'decode', 'scroll', 'frame', 'land'] },
+ { name: 'when the image is in the row the reader is on', order: ['request', 'decode', 'frame', 'land'], inRow: true },
+ { name: 'when no message row is in view', order: ['request', 'decode', 'frame', 'land'], noAnchors: true },
+]) {
+ test(`an image that decodes above the reader while an older page is out holds them ${scenario.name}`, async () => {
+ const { render, screen, fireEvent, cleanup } = rtl;
+ cleanup();
+ const t: Thread = { rows: textRows('a', 46), top: 0 };
+ // In the row the reader is on, the image is above its text and above the top edge: a4 is still the first row.
+ const imageRow = scenario.inRow ? 4 : 2;
+ t.rows[imageRow] = { id: `a${imageRow}`, h: 100, img: 0, ...(scenario.inRow ? { imgFirst: true as const } : {}) };
+ if (scenario.noAnchors) t.rows = t.rows.map(r => ({ ...r, anchor: false as const }));
+ const restore = installRows(t);
+ try {
+ const { rerender, container } = render(createElement(RowsProbe, { chatId: 'A', rows: t.rows }));
+ const el = screen.getByTestId('thread');
+ fireEvent.scroll(el);
+ const start = scenario.inRow ? 420 : 450;
+ readerScrollsTo(el, start);
+ let fetching = false;
+ let scrolled = 0;
+ for (const step of scenario.order) {
+ if (step === 'request') {
+ hook().onOlderMessagesRequested();
+ fetching = true;
+ rerender(createElement(RowsProbe, { chatId: 'A', rows: t.rows, fetching }));
+ } else if (step === 'decode') {
+ t.rows[imageRow] = { ...t.rows[imageRow], img: 30 };
+ hook().onMediaLoad({ currentTarget: container.querySelector(`img[data-img="a${imageRow}"]`) });
+ } else if (step === 'scroll') {
+ scrolled = 10; // the reader moves on by 10px from where they saw the thread
+ readerScrollsTo(el, start + scrolled);
+ } else if (step === 'frame') {
+ await nextFrame();
+ if (scenario.order.indexOf('land') > scenario.order.indexOf('frame'))
+ assert.equal(el.scrollTop, start + scrolled + 30, 'the image moved the reader while the page was out');
+ } else {
+ t.rows = [
+ ...(scenario.noAnchors
+ ? textRows('p', 10).map(r => ({ ...r, anchor: false as const }))
+ : textRows('p', 10)),
+ ...t.rows,
+ ];
+ fetching = false;
+ rerender(createElement(RowsProbe, { chatId: 'A', rows: t.rows, fetching }));
+ }
+ }
+ assert.equal(el.scrollTop, start + scrolled + 30 + 1000, 'the image was counted more or less than once');
+ } finally {
+ restore();
+ }
+ });
+}
+
// A reader can stop where no row is in view (a tall element that is not a message): the landing then holds them by the
// row they were on before, not by every pixel the thread grew, growth below them included.
test('a reader who scrolls to where no message is in view while an older page is out is held by the row before', async () => {
diff --git a/dashboard/src/hooks/useChatScrollPosition.ts b/dashboard/src/hooks/useChatScrollPosition.ts
index 07e2876db..53baf9060 100644
--- a/dashboard/src/hooks/useChatScrollPosition.ts
+++ b/dashboard/src/hooks/useChatScrollPosition.ts
@@ -251,6 +251,39 @@ export function useChatScrollPosition(
}
}, []);
+ // Holds the reader through the media whose load arrived since this last ran (see onMediaLoad's third branch): sorted by
+ // document order, each element is read, re-seeded and corrected for before the next, so every one is classified
+ // against a layout in which the growth above it is already corrected. With an older page out, a correction for an
+ // element above the landing's anchor row moves that row's recorded offset by as much, so the landing does not count
+ // the same pixels again; this runs before the anchor is taken and before the landing measures it, so each growth is
+ // in either the recorded offset or a correction, never both.
+ const applyMediaGrowth = useCallback(() => {
+ const batch = decodedMediaRef.current
+ .splice(0)
+ .sort((a, b) => (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1));
+ const cur = containerRef.current;
+ if (!cur || batch.length === 0) return;
+ const containerTop = cur.getBoundingClientRect().top;
+ let moved = false;
+ for (const grown of batch) {
+ const seeded = mediaHeights.current.get(grown);
+ if (seeded === undefined) continue;
+ const rect = grown.getBoundingClientRect();
+ // 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(grown, rect.height);
+ const grew = correctionForMediaGrowth(seeded, rect.height, rect.bottom, containerTop);
+ if (grew === null) continue;
+ // Added to the LIVE scrollTop, so each correction stacks on the ones applied above it.
+ writeScrollTop(cur, cur.scrollTop + grew);
+ moved = true;
+ const anchor = olderAnchorRef.current;
+ if (anchor && anchor.node.compareDocumentPosition(grown) & Node.DOCUMENT_POSITION_PRECEDING) anchor.top += grew;
+ prevScrollHeightRef.current += grew;
+ }
+ if (moved && prevChatIdRef.current !== null) rememberPosition(prevChatIdRef.current, cur);
+ }, [rememberPosition, writeScrollTop]);
+
// 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
@@ -272,9 +305,11 @@ export function useChatScrollPosition(
pinnedRef.current = atBottom;
const visibleChatId = prevChatIdRef.current;
if (visibleChatId && loadedRef.current) rememberPosition(visibleChatId, el);
- // With an older page out, media decoding above the reader is left to the landing (see onMediaLoad), and the
- // landing can only count it against the row the reader is on now, not the one they asked for the page on.
- if (awaitingOlderPageRef.current) olderAnchorRef.current = firstVisibleAnchor(el) ?? olderAnchorRef.current;
+ // With an older page out, the landing holds the row the reader is on now, not the one they asked for the page on.
+ if (awaitingOlderPageRef.current) {
+ applyMediaGrowth();
+ olderAnchorRef.current = firstVisibleAnchor(el) ?? olderAnchorRef.current;
+ }
};
el.addEventListener('scroll', onScroll, { passive: true });
return () => el.removeEventListener('scroll', onScroll);
@@ -317,10 +352,11 @@ export function useChatScrollPosition(
const onOlderMessagesRequested = useCallback(() => {
const el = containerRef.current;
if (!el) return;
+ applyMediaGrowth();
prevScrollHeightRef.current = el.scrollHeight;
olderAnchorRef.current = firstVisibleAnchor(el);
awaitingOlderPageRef.current = true;
- }, []);
+ }, [applyMediaGrowth]);
// Older messages are prepended ABOVE the viewport, so the thread grows upward and what the user
// was reading is pushed down by however much taller it just got. Left alone the view jumps
@@ -344,6 +380,7 @@ export function useChatScrollPosition(
// query only reports itself in flight a turn later, so any commit in between — a live message,
// a media decode, another query resolving — would otherwise consume the pending correction.
if (!el || isFetchingOlderMessages || !wasFetching || !awaitingOlderPageRef.current) return;
+ applyMediaGrowth(); // a decode whose frame has not run yet is counted there, not in the anchor's move
awaitingOlderPageRef.current = false;
// A follow still armed belongs to a message announced before the reader went back for history; the page that
// lands is not its row, and consuming it here would take the reader from the message they were held on to the
@@ -466,12 +503,7 @@ export function useChatScrollPosition(
});
return;
}
- const el = containerRef.current;
- if (!el) return;
- // An older page in flight already owns this growth: the landing effect diffs against a
- // 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;
+ if (!containerRef.current) return;
// Which element grew, and by how much, decides whether the reader moved at all.
const media = event?.currentTarget ?? null;
if (!media || !mediaHeights.current.has(media)) return;
@@ -482,30 +514,11 @@ export function useChatScrollPosition(
decoded.push(media);
if (decoded.length > 1) return;
requestAnimationFrame(() => {
- const batch = decoded
- .splice(0)
- .sort((a, b) => (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1));
- const cur = containerRef.current;
- if (!cur || !onScreen()) return;
- const containerTop = cur.getBoundingClientRect().top;
- let moved = false;
- for (const grown of batch) {
- const seeded = mediaHeights.current.get(grown);
- if (seeded === undefined) continue;
- const rect = grown.getBoundingClientRect();
- // 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(grown, rect.height);
- const grew = correctionForMediaGrowth(seeded, rect.height, rect.bottom, containerTop);
- if (grew === null) continue;
- // Added to the LIVE scrollTop, so each correction stacks on the ones applied above it.
- writeScrollTop(cur, cur.scrollTop + grew);
- moved = true;
- }
- if (moved && activeChatId !== null) rememberPosition(activeChatId, cur);
+ if (onScreen()) applyMediaGrowth();
+ else decoded.length = 0;
});
},
- [activeChatId, followBottom, rememberPosition, writeScrollTop],
+ [activeChatId, applyMediaGrowth, followBottom, writeScrollTop],
);
return { containerRef, onMessageAppended, onMediaLoad, measureMedia, onOlderMessagesRequested };