Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): keep chat thread focus through a page blur
Yudhi Armyndharis95b6fa7def17
diff --git a/dashboard/src/components/chats/ChatThread.test.ts b/dashboard/src/components/chats/ChatThread.test.tsindex 8f84d2491..7f01790ec 100644--- a/dashboard/src/components/chats/ChatThread.test.ts+++ b/dashboard/src/components/chats/ChatThread.test.ts@@ -12,6 +12,8 @@ import type { ChatMessageView } from '../../utils/chatMessages.ts';type RTL = typeof import('@testing-library/react');let rtl: RTL;+// Set by a test that needs the engine's answer for a focus it did not give by key press, which jsdom cannot.+let focusVisibleOverride: boolean | null = null;let matchesOriginal: typeof Element.prototype.matches;let ChatThread: typeof import('./ChatThread.tsx').default;let RoleProvider: typeof import('../RoleProvider.tsx').RoleProvider;@@ -30,7 +32,8 @@ before(async () => {// the focus of a click.matchesOriginal = window.Element.prototype.matches;window.Element.prototype.matches = function (this: Element, selector: string): boolean {- return selector === ':focus-visible' ? this === document.activeElement : matchesOriginal.call(this, selector);+ if (selector !== ':focus-visible') return matchesOriginal.call(this, selector);+ return focusVisibleOverride ?? this === document.activeElement;} as typeof Element.prototype.matches;});@@ -39,6 +42,7 @@ after(() => {});afterEach(() => {+ focusVisibleOverride = null;rtl.cleanup();window.sessionStorage.removeItem('openwa_user_role');});@@ -818,6 +822,111 @@ test('focus that left the thread and was then lost is not taken back into it', (}});+/** Runs `fn` with `document.hasFocus()` answering `false`, as it does while another window or a dialog has focus. */+function whilePageUnfocused(fn: () => void): void {+ Object.defineProperty(document, 'hasFocus', { configurable: true, value: () => false });+ try {+ fn();+ } finally {+ delete (document as { hasFocus?: unknown }).hasFocus;+ }+}++// A native dialog (the delete confirmation) or another window takes the page's focus: the focused control gets+// a blur with no relatedTarget while the document reports no focus, and it is the active element again when+// the page is. What was held for it must survive that, or the delete that follows finds nothing to give back+// and the next Tab lands in the composer.+test('focus held for a control survives the page losing focus, and is given back when the list changes', () => {+ const [a, b, c]: ChatMessageView[] = ['1', '2', '3'].map(n => ({+ ...PROMPT,+ id: `db-${n}`,+ waMessageId: `wamid.${n}`,+ metadata: undefined,+ }));+ const { container, rerenderWith } = renderThread('operator', [a, b, c]);+ const del = bubblesOf(container)[1].querySelector<HTMLElement>('.action-btn:last-of-type');+ assert.ok(del);+ del.focus();++ whilePageUnfocused(() => rtl.fireEvent.focusOut(del));+ rerenderWith([a, { ...b, type: 'revoked', body: '' }, c]);++ assert.equal(focusedMessage(), 'wamid.3');+});++// What it got back with the page is not a new focus to classify: an engine that does not call it+// :focus-visible would otherwise make it one a pointer brought, and the place held for the keyboard is dropped.+test('focus given back with the page keeps what was held, whatever :focus-visible says', () => {+ const [a, b, c]: ChatMessageView[] = ['1', '2', '3'].map(n => ({+ ...PROMPT,+ id: `db-${n}`,+ waMessageId: `wamid.${n}`,+ metadata: undefined,+ }));+ const { container, rerenderWith } = renderThread('operator', [a, b, c]);+ const thread = container.querySelector<HTMLElement>('.room-messages');+ assert.ok(thread);+ const del = bubblesOf(container)[1].querySelector<HTMLElement>('.action-btn:last-of-type');+ assert.ok(del);+ del.focus();++ whilePageUnfocused(() => rtl.fireEvent.focusOut(del));+ focusVisibleOverride = false;+ rtl.fireEvent.focusIn(del);+ focusVisibleOverride = null;+ rerenderWith([a, { ...b, type: 'revoked', body: '' }, c]);++ assert.equal(focusedMessage(), 'wamid.3');+ assert.equal(thread.hasAttribute('data-pointer'), false);+});++// The element the page took focus from is only forgiven for the round trip: if focus left the thread by+// another route and the element is focused again later, that is a new focus and is classified as one.+test('a later focus on a control the page once took focus from is classified again', () => {+ const [a, b, c]: ChatMessageView[] = ['1', '2', '3'].map(n => ({+ ...PROMPT,+ id: `db-${n}`,+ waMessageId: `wamid.${n}`,+ metadata: undefined,+ }));+ const { container, rerenderWith } = renderThread('operator', [a, b, c]);+ const del = bubblesOf(container)[1].querySelector<HTMLElement>('.action-btn:last-of-type');+ assert.ok(del);+ const outside = document.createElement('input');+ document.body.appendChild(outside);+ try {+ del.focus();+ whilePageUnfocused(() => rtl.fireEvent.focusOut(del));+ // The page never gave focus back to it; the reader moved on to a control outside the thread and returned.+ outside.focus();+ del.focus();+ rerenderWith([a, { ...b, type: 'revoked', body: '' }, c]);++ assert.equal(focusedMessage(), 'wamid.3');+ } finally {+ outside.remove();+ }+});++// Only the page's own loss is forgiven: the same blur while the page has focus is the focus going nowhere.+test('focus that went nowhere while the page has focus is not held', () => {+ const [a, b, c]: ChatMessageView[] = ['1', '2', '3'].map(n => ({+ ...PROMPT,+ id: `db-${n}`,+ waMessageId: `wamid.${n}`,+ metadata: undefined,+ }));+ const { container, rerenderWith } = renderThread('operator', [a, b, c]);+ const del = bubblesOf(container)[1].querySelector<HTMLElement>('.action-btn:last-of-type');+ assert.ok(del);+ del.focus();++ rtl.fireEvent.focusOut(del);+ rerenderWith([a, { ...b, type: 'revoked', body: '' }, c]);++ assert.equal(focusedMessage(), 'body');+});+// Chats.css shows the actions while focus is inside a bubble, but a click focuses the bubble too, and// its menu would stay drawn over the message after the pointer left. The thread marks pointer use and the// stylesheet reveals on focus only without the mark. jsdom has no layout, so the selectors are pinned.diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsxindex 9c0c6a55f..7d9420bfa 100644--- a/dashboard/src/components/chats/ChatThread.tsx+++ b/dashboard/src/components/chats/ChatThread.tsx@@ -133,13 +133,20 @@ function ChatThread({// element is checked after the commit, and only once: a later change of the list never moves focus, and// the position of a reader who scrolled away is never touched (preventScroll). Focus a pointer brought// in is not recorded, so a mouse click on Delete moves nothing. The place is found from the bubble in the- // document, not from an index taken at focus time, which an older page landing since would have moved.+ // document, not from an index taken at focus time, which an older page landing since would have moved. The+ // page itself losing focus (the delete confirmation, another window) ends nothing: see deactivatedRef.const keyboardFocusRef = useRef<{element: HTMLElement;bubble: HTMLElement;wa: string | null;neighbors: Array<{ element: HTMLElement; wa: string | null }>;} | null>(null);+ // The element that lost focus because the page did: another window took over, or a native dialog (the+ // delete confirmation) opened. It stays the active element and is given focus back with the page, with no+ // relatedTarget and, in some engines, without :focus-visible, so the round trip neither drops what is held+ // above nor re-classifies the focus that comes back. The blur arrives after confirm() has returned, so the+ // handler that opened the dialog cannot put the place back itself.+ const deactivatedRef = useRef<EventTarget | null>(null);useEffect(() => {const held = keyboardFocusRef.current;if (!held) return;@@ -353,6 +360,11 @@ function ChatThread({onKeyDown={event => event.currentTarget.removeAttribute('data-pointer')}onFocus={event => {const target = event.target;+ // The page gave focus back to the element it took it from: pointer mode and the held place stand as+ // they were left.+ const resumed = deactivatedRef.current === target;+ deactivatedRef.current = null;+ if (resumed) return;const bubble = target.closest<HTMLElement>('[data-roving-message]');const keyboard = target.matches(':focus-visible');if (keyboard) event.currentTarget.removeAttribute('data-pointer');@@ -369,7 +381,11 @@ function ChatThread({keyboardFocusRef.current = { element: target, bubble, wa: waIdOf(bubble), neighbors };}}onBlur={event => {- if (!event.currentTarget.contains(event.relatedTarget as Node | null)) keyboardFocusRef.current = null;+ if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;+ // The page lost focus, not the element: it is still the active one and what it held is still true.+ const pageLostFocus = event.relatedTarget === null && !document.hasFocus();+ deactivatedRef.current = pageLostFocus ? event.target : null;+ if (!pageLostFocus) keyboardFocusRef.current = null;}}>{/* Older-page spinner, or the failure in its place. An in-flow sibling before the thread, not