Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): keep actions off a clicked bubble, focus in the thread
Yudhi Armyndharis72b17854794a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c14b18ea3..4862547ea 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -71,7 +71,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Stop a request left over from before logout from reloading the dashboard login form.- Stop a dashboard Logs export from downloading rows after sign-out when its last page was throttled.- Stop reopening a just-saved dashboard template from loading its old values, which a second save wrote back.-- Reach a chat message's reply, react and delete actions from the keyboard in the dashboard: the thread is one tab stop, the arrow keys move between messages, and the actions show while focus is inside the bubble.+- Reach a chat message's reply, react and delete actions from the keyboard in the dashboard: the message bubbles are one tab stop, the arrow keys move between them, and the actions show while keyboard focus is inside a bubble.- Stop an operator ingress dead-letter redrive at its next row on shutdown, leaving the rows it did not reach unchanged.- Run a plugin's `onDisable` once when shutdown, uninstall or an update overlaps a disable already in progress.- Answer `503` and keep the previous version when shutdown begins before an update of a plugin the operator switched on has applied.diff --git a/dashboard/src/components/chats/ChatThread.test.ts b/dashboard/src/components/chats/ChatThread.test.tsindex de75eec13..cf9051288 100644--- a/dashboard/src/components/chats/ChatThread.test.ts+++ b/dashboard/src/components/chats/ChatThread.test.ts@@ -4,6 +4,7 @@import '../../test-helpers/register-hooks.ts';import { test, before, afterEach } from 'node:test';import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';import { createElement, createRef } from 'react';import type { Chat } from '../../services/api.ts';import type { ChatMessageView } from '../../utils/chatMessages.ts';@@ -60,21 +61,22 @@ function renderThread(role: string,messages: ChatMessageView[] = [PROMPT],activeChat: Chat = CHAT,-): { clicks: string[]; container: HTMLElement } {+): { clicks: string[]; container: HTMLElement; rerenderWith: (next: ChatMessageView[]) => void } {window.sessionStorage.setItem('openwa_user_role', role);const clicks: string[] = [];const noop = () => {};- const { container } = rtl.render(+ const containerRef = createRef<HTMLDivElement>();+ const tree = (list: ChatMessageView[]) =>createElement(RoleProvider,null,createElement(ChatThread, {sessionId: 's1',activeChat,- messages,+ messages: list,loadingMessages: false,messagesError: false,- messagesContainerRef: createRef<HTMLDivElement>(),+ messagesContainerRef: containerRef,hasMoreMessages: false,loadingOlderMessages: false,onLoadOlderMessages: noop,@@ -88,9 +90,9 @@ function renderThread(clicks.push(button.id);},}),- ),- );- return { clicks, container };+ );+ const { container, rerender } = rtl.render(tree(messages));+ return { clicks, container, rerenderWith: next => rerender(tree(next)) };}test('a read-only key sees prompt choices disabled and no reply, react or delete actions', () => {@@ -448,3 +450,115 @@ test('a key pressed inside a message action keeps its own meaning', () => {rtl.fireEvent.keyDown(reply, { key: 'ArrowUp' });assert.equal(document.activeElement, reply);});++const bubblesOf = (container: HTMLElement): HTMLElement[] => [+ ...container.querySelectorAll<HTMLElement>('[data-roving-message]'),+];++// A bubble is the one tab stop of the thread; what is inside it (a link, a preview, a button) is a stop+// of its own, and landing on it must not make its bubble the stop as well, or Shift+Tab visits both.+test('focus on a link inside a message does not move the thread tab stop', () => {+ const linked: ChatMessageView = { ...PROMPT, id: 'db-0', waMessageId: 'wamid.0', body: 'see https://example.org/a' };+ const newest: ChatMessageView = {+ ...PROMPT,+ id: 'db-9',+ waMessageId: 'wamid.9',+ body: 'Newest',+ metadata: undefined,+ };+ const { container } = renderThread('operator', [linked, newest]);+ const stops = (): Array<string | null> => bubblesOf(container).map(el => el.getAttribute('tabindex'));+ assert.deepEqual(stops(), ['-1', '0']);++ const link = container.querySelector<HTMLElement>('[data-wa-message-id="wamid.0"] a[href]');+ assert.ok(link, 'the body links its URL');+ rtl.act(() => link.focus());++ assert.deepEqual(stops(), ['-1', '0']);+});++test('arrow keys, Home and End are consumed and reach the stops from the middle of three', () => {+ const messages = ['a', 'b', 'c'].map((id): ChatMessageView => ({+ ...PROMPT,+ id: `db-${id}`,+ waMessageId: `wamid.${id}`,+ metadata: undefined,+ }));+ const { container } = renderThread('operator', messages);+ const bubbles = bubblesOf(container);+ bubbles[1].focus();++ // fireEvent returns false when the handler called preventDefault.+ assert.equal(rtl.fireEvent.keyDown(bubbles[1], { key: 'Home' }), false);+ assert.equal(document.activeElement, bubbles[0]);+ bubbles[1].focus();+ assert.equal(rtl.fireEvent.keyDown(bubbles[1], { key: 'End' }), false);+ assert.equal(document.activeElement, bubbles[2]);+ bubbles[1].focus();+ assert.equal(rtl.fireEvent.keyDown(bubbles[1], { key: 'ArrowUp' }), false);+ assert.equal(document.activeElement, bubbles[0]);+ bubbles[1].focus();+ assert.equal(rtl.fireEvent.keyDown(bubbles[1], { key: 'ArrowDown' }), false);+ assert.equal(document.activeElement, bubbles[2]);+ // A key the thread does not use is left alone.+ assert.equal(rtl.fireEvent.keyDown(bubbles[1], { key: 'a' }), true);+});++// Deleting removes the buttons that hold focus, so focus would fall to the page and the next Tab would+// land in the composer.+test('keyboard focus stays in the thread when the focused message is deleted', () => {+ const first: ChatMessageView = { ...PROMPT, id: 'db-1', waMessageId: 'wamid.1', metadata: undefined };+ const second: ChatMessageView = { ...PROMPT, id: 'db-2', waMessageId: 'wamid.2', metadata: undefined };+ const { container, rerenderWith } = renderThread('operator', [first, second]);+ const bubbles = bubblesOf(container);+ const del = bubbles[1].querySelector<HTMLElement>('[aria-label][class*="action"], .action-btn:last-of-type');+ assert.ok(del, 'the newest message offers its actions');+ del.focus();+ assert.equal(document.activeElement, del);++ rerenderWith([first, { ...second, type: 'revoked', body: '' }]);++ const active = document.activeElement;+ assert.ok(active && active !== document.body, 'focus fell to the page');+ assert.ok(container.contains(active), 'focus left the thread');+});++test('focus does not return to the thread when it was moved elsewhere before a message was deleted', () => {+ const first: ChatMessageView = { ...PROMPT, id: 'db-1', waMessageId: 'wamid.1', metadata: undefined };+ const second: ChatMessageView = { ...PROMPT, id: 'db-2', waMessageId: 'wamid.2', metadata: undefined };+ const { container, rerenderWith } = renderThread('operator', [first, second]);+ const outside = document.createElement('input');+ document.body.appendChild(outside);+ try {+ bubblesOf(container)[1].focus();+ outside.focus();+ rerenderWith([first, { ...second, type: 'revoked', body: '' }]);+ assert.equal(document.activeElement, outside);+ } finally {+ outside.remove();+ }+});++// 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.+test('a click marks pointer use, a key press clears it, and the stylesheet reveals on keyboard focus only', () => {+ const { container } = renderThread('operator', [PROMPT, { ...PROMPT, id: 'db-2', waMessageId: 'wamid.2' }]);+ const thread = container.querySelector<HTMLElement>('.room-messages');+ assert.ok(thread);+ assert.equal(thread.hasAttribute('data-pointer'), false);+ rtl.fireEvent.pointerDown(bubblesOf(container)[0]);+ assert.equal(thread.hasAttribute('data-pointer'), true);+ rtl.fireEvent.keyDown(bubblesOf(container)[0], { key: 'Tab' });+ assert.equal(thread.hasAttribute('data-pointer'), false);++ const css = readFileSync(new URL('../../pages/Chats.css', import.meta.url), 'utf8');+ for (const target of [+ '.message-bubble-container:focus-within .message-actions-menu',+ '.reaction-trigger-wrapper:focus-within .reaction-quick-popover',+ ]) {+ const rule = css.split('\n').find(line => line.includes(target));+ assert.ok(rule, `${target} reveals the menu on focus`);+ assert.ok(rule.includes('.room-messages:not([data-pointer])'), `${target} is gated on keyboard modality`);+ }+});diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsxindex 88b6f58ad..ced9e45c9 100644--- a/dashboard/src/components/chats/ChatThread.tsx+++ b/dashboard/src/components/chats/ChatThread.tsx@@ -1,4 +1,13 @@-import { useCallback, useEffect, useMemo, useState, type KeyboardEvent, type RefObject } from 'react';+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ type FocusEvent,+ type KeyboardEvent,+ type RefObject,+} from 'react';import { useTranslation } from 'react-i18next';import { AlertCircle, ChevronDown, CornerUpLeft, Loader2, MessageSquare, Smile, Trash2 } from 'lucide-react';import { useRole } from '../../hooks/useRole';@@ -76,8 +85,9 @@ function ChatThread({const { canWrite } = useRole();// The message actions sit behind hover, so a keyboard user reaches them through the bubble that carries- // them: the thread is one tab stop (the focused message, else the newest), the arrow keys move between- // messages, and the actions show while focus is inside the bubble (Chats.css).+ // them: the bubbles are one tab stop (the focused message, else the newest), the arrow keys move between+ // them, and the actions show while keyboard focus is inside a bubble (Chats.css). Links, previews and+ // buttons inside a message stay stops of their own.const hasActions = useCallback((message: ChatMessageView) => canWrite && message.type !== 'revoked' && Boolean(message.waMessageId),[canWrite],@@ -111,6 +121,15 @@ function ChatThread({target.focus();};+ // Whether focus was last inside the thread. When the focused message turns revoked its bubble loses its+ // tab stop and its action buttons unmount, which drops focus to the page; no blur event is fired for a+ // removed element, so this stays true and tells that case from a click elsewhere.+ const focusInThreadRef = useRef(false);+ useEffect(() => {+ if (!focusInThreadRef.current || document.activeElement !== document.body) return;+ messagesContainerRef.current?.querySelector<HTMLElement>('[data-roving-message][tabindex="0"]')?.focus();+ }, [messages, hasActions, messagesContainerRef]);+// "@<digits>" in a message body only ever means something once resolved against a participant// this thread has already seen post (see buildMentionNameMap) — recomputed only when the message// list itself changes, not per-render.@@ -250,7 +269,21 @@ function ChatThread({// position:relative so the scroll-to-bottom button can float inside.return (- <div className="room-messages" ref={messagesContainerRef}>+ <div+ className="room-messages"+ ref={messagesContainerRef}+ // The actions show while focus is inside a bubble, but only for keyboard focus: a click also focuses+ // the bubble, and its menu would stay drawn over the message after the pointer left. The marker is+ // read by Chats.css.+ onPointerDown={event => event.currentTarget.setAttribute('data-pointer', '')}+ onKeyDown={event => event.currentTarget.removeAttribute('data-pointer')}+ onFocus={() => {+ focusInThreadRef.current = true;+ }}+ onBlur={event => {+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) focusInThreadRef.current = false;+ }}+ >{/* Floating scroll-to-bottom button. Hidden while loading (no height to measure yet)and when the user is already at/near the bottom. */}{showJumpToBottom && !loadingMessages && (@@ -478,7 +511,11 @@ function ChatThread({? {'data-roving-message': '',tabIndex: tabStopId === msg.id ? 0 : -1,- onFocus: () => setFocusedMessageId(msg.id),+ // Only focus on the bubble itself: a link or a button inside it is a stop of its own and+ // must not turn the bubble into the thread's tab stop as well.+ onFocus: (event: FocusEvent<HTMLDivElement>) => {+ if (event.target === event.currentTarget) setFocusedMessageId(msg.id);+ },onKeyDown: onBubbleKeyDown,}: {})}diff --git a/dashboard/src/pages/Chats.css b/dashboard/src/pages/Chats.cssindex 642574203..0d8aa5602 100644--- a/dashboard/src/pages/Chats.css+++ b/dashboard/src/pages/Chats.css@@ -1114,7 +1114,7 @@}.chats-page .message-bubble-container:hover .message-actions-menu,-.chats-page .message-bubble-container:focus-within .message-actions-menu {+.chats-page .room-messages:not([data-pointer]) .message-bubble-container:focus-within .message-actions-menu {display: flex;}@@ -1180,7 +1180,7 @@}.chats-page .reaction-trigger-wrapper:hover .reaction-quick-popover,-.chats-page .reaction-trigger-wrapper:focus-within .reaction-quick-popover {+.chats-page .room-messages:not([data-pointer]) .reaction-trigger-wrapper:focus-within .reaction-quick-popover {display: flex;}