Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): reopen a chat on its message after a page landed away
Yudhi Armyndhariscf35377fb330
diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsxindex 3b771125b..94e1ab4f6 100644--- a/dashboard/src/components/chats/ChatThread.tsx+++ b/dashboard/src/components/chats/ChatThread.tsx@@ -650,7 +650,7 @@ function ChatThread({key={msg.id}className={`message-bubble-wrapper ${isMe ? 'outgoing' : 'incoming'}`}data-wa-message-id={msg.waMessageId}- data-scroll-anchor=""+ data-scroll-anchor={msg.id}><divclassName="message-bubble-container"diff --git a/dashboard/src/hooks/useChatScrollPosition.render.test.ts b/dashboard/src/hooks/useChatScrollPosition.render.test.tsindex 8df49fe5a..27d3394d6 100644--- a/dashboard/src/hooks/useChatScrollPosition.render.test.ts+++ b/dashboard/src/hooks/useChatScrollPosition.render.test.ts@@ -1097,7 +1097,7 @@ function RowsProbe({ chatId, rows, fetching = false }: { chatId: string; rows: Rrows.map(r =>createElement('div',- { key: r.id, 'data-id': r.id, ...(r.anchor === false ? {} : { 'data-scroll-anchor': '' }) },+ { key: r.id, 'data-id': r.id, ...(r.anchor === false ? {} : { 'data-scroll-anchor': r.id }) },r.img === undefined ? null : createElement('img', { ref: result.measureMedia, 'data-img': r.id }),),),@@ -1193,6 +1193,101 @@ for (const scenario of [});}+// The page can also land while the reader is still in the other chat, so it is never seen landing: it is above the+// offset saved for the chat when they come back, and so is everything that offset was measured against.+test('an older page that lands while the reader is in another chat reopens the chat on the message they left', async () => {+ const { render, screen, fireEvent, cleanup } = rtl;+ cleanup();+ const t: Thread = { rows: textRows('a', 46), top: 0 };+ const restore = installRows(t);+ try {+ const { rerender } = render(createElement(RowsProbe, { chatId: 'A', rows: t.rows }));+ const el = screen.getByTestId('thread');+ fireEvent.scroll(el);+ readerScrollsTo(el, 50); // near the top: an older page is asked for+ hook().onOlderMessagesRequested();+ rerender(createElement(RowsProbe, { chatId: 'A', rows: t.rows, fetching: true }));++ const rowsOfA = [...textRows('p', 10), ...t.rows]; // the page lands while the reader is in B: 1000px above+ t.rows = textRows('b', 30);+ rerender(createElement(RowsProbe, { chatId: 'B', rows: t.rows }));+ fireEvent.scroll(el);+ t.rows = rowsOfA;+ rerender(createElement(RowsProbe, { chatId: 'A', rows: t.rows }));+ fireEvent.scroll(el);+ assert.equal(el.scrollTop, 50 + 1000, 'A reopened on the page that landed instead of the message the reader left');++ // Out and back again without scrolling: the same message, not the offset from before the page.+ t.rows = textRows('b', 30);+ rerender(createElement(RowsProbe, { chatId: 'B', rows: t.rows }));+ fireEvent.scroll(el);+ t.rows = rowsOfA;+ rerender(createElement(RowsProbe, { chatId: 'A', rows: t.rows }));+ fireEvent.scroll(el);+ assert.equal(el.scrollTop, 50 + 1000, 'the second return went back to the offset from before the page');+ } finally {+ restore();+ }+});++// The rows of that page mount when the chat is shown again, so their images decode after the restore: each one is above+// the reader, and the restore waiting for media holds them through it.+test('an image in a page that landed while the reader was away decodes after they came back without moving them', async () => {+ const { render, screen, fireEvent, cleanup } = rtl;+ cleanup();+ const t: Thread = { rows: textRows('a', 46), top: 0 };+ const restore = installRows(t);+ try {+ const { rerender, container } = render(createElement(RowsProbe, { chatId: 'A', rows: t.rows }));+ const el = screen.getByTestId('thread');+ fireEvent.scroll(el);+ readerScrollsTo(el, 50);+ hook().onOlderMessagesRequested();+ rerender(createElement(RowsProbe, { chatId: 'A', rows: t.rows, fetching: true }));++ const page = textRows('p', 10);+ page[2] = { id: 'p2', h: 100, img: 0 };+ const rowsOfA = [...page, ...t.rows];+ t.rows = textRows('b', 30);+ rerender(createElement(RowsProbe, { chatId: 'B', rows: t.rows }));+ fireEvent.scroll(el);+ t.rows = rowsOfA;+ rerender(createElement(RowsProbe, { chatId: 'A', rows: t.rows }));+ fireEvent.scroll(el);++ t.rows[2] = { id: 'p2', h: 100, img: 300 }; // the page's image decodes+ hook().onMediaLoad({ currentTarget: container.querySelector('img[data-img="p2"]') });+ await nextFrame();+ fireEvent.scroll(el);+ assert.equal(el.scrollTop, 50 + 1000 + 300, 'the image in the page pushed the reader off their message');+ } finally {+ restore();+ }+});++// A saved spot whose first row is gone from the thread (the chat's history was fetched again from its newest page) has+// nothing to be moved by: the offset is written as it was saved.+test('a chat whose first row is gone when the reader comes back reopens at the saved offset', async () => {+ const { render, screen, fireEvent, cleanup } = rtl;+ cleanup();+ const t: Thread = { rows: textRows('a', 46), top: 0 };+ const restore = installRows(t);+ try {+ const { rerender } = render(createElement(RowsProbe, { chatId: 'A', rows: t.rows }));+ const el = screen.getByTestId('thread');+ fireEvent.scroll(el);+ readerScrollsTo(el, 2000);+ t.rows = textRows('b', 30);+ rerender(createElement(RowsProbe, { chatId: 'B', rows: t.rows }));+ fireEvent.scroll(el);+ t.rows = textRows('a', 46).slice(10);+ rerender(createElement(RowsProbe, { chatId: 'A', rows: t.rows }));+ assert.equal(el.scrollTop, 2000);+ } finally {+ restore();+ }+});+// While a page is out, an image that decodes above the reader is left to the landing, which holds them by the message// they were on: a commit in between (a message far below) must not take that measure again from the moved message.test('an image that decodes above the reader while an older page is out is counted when the page lands', async () => {diff --git a/dashboard/src/hooks/useChatScrollPosition.ts b/dashboard/src/hooks/useChatScrollPosition.tsindex 2df7366c7..07e2876db 100644--- a/dashboard/src/hooks/useChatScrollPosition.ts+++ b/dashboard/src/hooks/useChatScrollPosition.ts@@ -144,6 +144,22 @@ function firstVisibleAnchor(container: HTMLElement): { node: Element; top: numbereturn null;}+/**+ * Where a saved spot is in the thread now: its offset, moved down by whatever sits above the row that was first in the+ * thread when it was saved. An older page asked for before the reader left a chat can land while they are in another+ * one, above everything the offset was measured against. With nothing new above that row the shift is zero and the+ * offset is written as saved; it is read live, as the images of such a page decode after the chat is shown again.+ */+function savedSpotTop(container: HTMLElement, spot: { top: number; first: string | null }): number {+ const first = container.querySelector(`[${SCROLL_ANCHOR_ATTRIBUTE}]`);+ const saved =+ spot.first === null+ ? undefined+ : Array.from(container.children).find(row => row.getAttribute(SCROLL_ANCHOR_ATTRIBUTE) === spot.first);+ if (!first || !saved) return spot.top;+ return spot.top + saved.getBoundingClientRect().top - first.getBoundingClientRect().top;+}+export function useChatScrollPosition(activeChatId: string | null,isLoaded: boolean,@@ -159,7 +175,8 @@ export function useChatScrollPosition(onOlderMessagesRequested: () => void;} {const containerRef = useRef<HTMLDivElement | null>(null);- const scrollMap = useRef<Map<string, number>>(new Map());+ // Each chat's saved offset, with the anchor key of the row that was first in its thread then (see savedSpotTop).+ const scrollMap = useRef<Map<string, { top: number; first: string | null }>>(new Map());const prevChatIdRef = useRef<string | null>(null);const pinnedRef = useRef<boolean>(true);// Whether the visible chat's messages have rendered. While a chat loads, the container shows only a@@ -169,7 +186,7 @@ export function useChatScrollPosition(// A 'saved' restore writes scrollTop BEFORE media decodes — the browser clamps the write to the// still-short scrollHeight and the thread lands at the top. The saved value lives here and is// re-applied on every media decode until the user scrolls (any genuine scroll cancels it).- const pendingRestoreRef = useRef<number | null>(null);+ const pendingRestoreRef = useRef<{ top: number; first: string | null } | null>(null);// Where our own last write left the thread, so the scroll listener can skip the event it raised (a genuine// user scroll both updates the pin state / position map AND cancels pendingRestore; our writes must do// neither). That event reports the position by value, and so does the clamp event a content swap queued@@ -228,7 +245,10 @@ export function useChatScrollPosition(// state, not an offset, because the thread keeps growing under a reader who follows it.const rememberPosition = useCallback((chatId: string, el: HTMLDivElement) => {if (isNearBottom(el.scrollTop, el.scrollHeight, el.clientHeight)) scrollMap.current.delete(chatId);- else scrollMap.current.set(chatId, el.scrollTop);+ else {+ const first = el.querySelector(`[${SCROLL_ANCHOR_ATTRIBUTE}]`)?.getAttribute(SCROLL_ANCHOR_ATTRIBUTE) || null;+ scrollMap.current.set(chatId, { top: el.scrollTop, first });+ }}, []);// Track pin state from scroll geometry: any scroll that lands at the bottom (ours or the user's)@@ -269,7 +289,7 @@ export function useChatScrollPosition(// declared before the height tracker, so the flag is gone before the tracker could act on it.if (next !== prevChatIdRef.current) awaitingOlderPageRef.current = false;- const decision = decideRestoreTarget(next, isLoaded, next !== null ? scrollMap.current.get(next) : undefined);+ const decision = decideRestoreTarget(next, isLoaded, next !== null ? scrollMap.current.get(next)?.top : undefined);// A message the reader sent while this chat loaded opens it at that message, the way a send in a loaded chat// scrolls to it. Only in the chat it was sent in: the next restore decision, in whichever chat, forgets it.const sentWhileLoading = sentWhileLoadingRef.current === next;@@ -282,7 +302,7 @@ export function useChatScrollPosition(const saved = scrollMap.current.get(next);if (saved !== undefined) {pendingRestoreRef.current = saved; // re-applied on media loads until the user scrolls- writeScrollTop(el, saved);+ writeScrollTop(el, savedSpotTop(el, saved));pinnedRef.current = false; // a saved spot is (almost always) not the bottom}} else if (decision.restore === 'bottom') {@@ -435,7 +455,7 @@ export function useChatScrollPosition(if (pending !== null) {requestAnimationFrame(() => {const cur = containerRef.current;- if (cur && onScreen() && pendingRestoreRef.current !== null) writeScrollTop(cur, pending);+ if (cur && onScreen() && pendingRestoreRef.current !== null) writeScrollTop(cur, savedSpotTop(cur, pending));});return;}