Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): let the Chats search popup own Escape and its focus

Yudhi Armyndharisf744c98ba810
diff --git a/dashboard/src/components/GlobalSearch.test.ts b/dashboard/src/components/GlobalSearch.test.ts
index f69190e5b..8e0e0c8ed 100644
--- a/dashboard/src/components/GlobalSearch.test.ts
+++ b/dashboard/src/components/GlobalSearch.test.ts
@@ -6,7 +6,9 @@ import { test, before, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { createElement } from 'react';
-const pending = new Map<string, (hits: string[]) => void>();
+const pending = new Map<string, (hits: string[], total?: number) => void>();
+const offsets: string[] = [];
+const scopes: string[] = [];
function installFetchStub(): void {
globalThis.fetch = ((input: RequestInfo | URL): Promise<Response> => {
@@ -15,19 +17,22 @@ function installFetchStub(): void {
'http://localhost',
);
const q = url.searchParams.get('q') ?? '';
+ const offset = url.searchParams.get('offset') ?? '0';
+ offsets.push(offset);
+ scopes.push(url.searchParams.get('sessionId') ?? '');
return new Promise(resolve => {
- pending.set(q, texts =>
+ pending.set(q, (texts, total = texts.length) =>
resolve(
new Response(
JSON.stringify({
hits: texts.map((text, i) => ({
- messageId: `${q}-${i}`,
+ messageId: `${q}-${offset}-${i}`,
sessionId: 'sess-1',
chatId: '[email protected]',
timestamp: 1_767_225_600,
snippet: text,
})),
- total: texts.length,
+ total,
}),
{ headers: { 'Content-Type': 'application/json' } },
),
@@ -53,6 +58,8 @@ before(async () => {
afterEach(() => {
rtl.cleanup();
pending.clear();
+ offsets.length = 0;
+ scopes.length = 0;
});
async function typeAndWaitForRequest(input: HTMLElement, value: string): Promise<void> {
@@ -90,3 +97,215 @@ test('a response for a query the user cleared does not fill the list', async ()
await new Promise(resolve => setTimeout(resolve, 20));
assert.equal(rtl.screen.queryByText('refund issued') === null, true, 'the cleared query filled the list');
});
+
+test('Escape during a pending keystroke keeps the dismissed results closed', async () => {
+ rtl.render(createElement(GlobalSearch, { onHit: () => undefined }));
+ const input = rtl.screen.getByRole('textbox');
+
+ await typeAndWaitForRequest(input, 'refund');
+ await rtl.act(async () => pending.get('refund')!(['refund issued']));
+ await rtl.screen.findByRole('listbox');
+
+ rtl.fireEvent.change(input, { target: { value: 'refunds' } });
+ rtl.fireEvent.keyDown(input, { key: 'Escape' });
+ assert.ok(!rtl.screen.queryByRole('listbox'), 'Escape left the results open');
+ // Past the debounce: the keystroke typed before Escape must not reopen them.
+ await new Promise(resolve => setTimeout(resolve, 400));
+ assert.ok(!rtl.screen.queryByRole('listbox'), 'the pending debounce reopened the dismissed results');
+});
+
+test('Escape that cancels a search before any results opened is consumed', async () => {
+ const { screen, fireEvent } = rtl;
+ rtl.render(createElement(GlobalSearch, { onHit: () => undefined }));
+ const input = screen.getByRole('textbox');
+
+ fireEvent.change(input, { target: { value: 'refund' } });
+ // Inside the debounce window: nothing has opened yet, but the key cancels the pending search, so a
+ // page-level Escape handler (the Chats page closes the open conversation) must leave it alone.
+ assert.equal(fireEvent.keyDown(input, { key: 'Escape' }), false, 'the cancelling Escape was not consumed');
+ await new Promise(resolve => setTimeout(resolve, 400));
+ assert.ok(!pending.has('refund'), 'the cancelled search still ran');
+ assert.ok(!screen.queryByRole('listbox'), 'the cancelled search opened results');
+ // With nothing pending and nothing open, Escape is not the widget's to keep.
+ assert.equal(fireEvent.keyDown(input, { key: 'Escape' }), true, 'an idle Escape was swallowed');
+});
+
+test("refocusing after Escape cancelled a search does not show the previous query's results", async () => {
+ rtl.render(createElement(GlobalSearch, { onHit: () => undefined }));
+ const input = rtl.screen.getByRole('textbox');
+
+ await typeAndWaitForRequest(input, 'refund');
+ await rtl.act(async () => pending.get('refund')!(['refund issued']));
+ await rtl.screen.findByRole('listbox');
+
+ rtl.fireEvent.change(input, { target: { value: 'refunds' } });
+ rtl.fireEvent.keyDown(input, { key: 'Escape' });
+ rtl.fireEvent.focus(input);
+ assert.ok(!rtl.screen.queryByText('refund issued'), 'refocus showed results for the old query');
+ await rtl.waitFor(() => assert.ok(pending.has('refunds'), 'refocus did not search the query the input shows'));
+ await rtl.act(async () => pending.get('refunds')!(['refunds batch']));
+ await rtl.screen.findByText('refunds batch');
+});
+
+const page = (from: number): string[] => Array.from({ length: 20 }, (_, i) => `refund ${from + i}`);
+
+test('a mouse click on "more" keeps the results open and appends the next page', async () => {
+ const { screen, fireEvent, act, waitFor } = rtl;
+ rtl.render(createElement(GlobalSearch, { onHit: () => undefined }));
+ const input = screen.getByRole('textbox');
+ input.focus();
+ await typeAndWaitForRequest(input, 'refund');
+ await act(async () => pending.get('refund')!(page(0), 40));
+ const more = await screen.findByRole('button', { name: '40 results' });
+
+ // A real mousedown moves focus off the input; cancelling it is what keeps the input focused.
+ assert.equal(fireEvent.mouseDown(more), false, 'mousedown on "more" was not cancelled');
+ fireEvent.click(more);
+ await waitFor(() => assert.deepEqual(offsets, ['0', '20']));
+ await act(async () => pending.get('refund')!(page(20), 40));
+ await new Promise(resolve => setTimeout(resolve, 200));
+ assert.ok(screen.queryByRole('listbox'), 'the results closed after "more"');
+ assert.equal(screen.getAllByRole('option').length, 40);
+});
+
+test('Tab then Enter on "more" keeps the results open and returns focus to the input', async () => {
+ const { screen, fireEvent, act, waitFor } = rtl;
+ rtl.render(createElement(GlobalSearch, { onHit: () => undefined }));
+ const input = screen.getByRole('textbox');
+ input.focus();
+ await typeAndWaitForRequest(input, 'refund');
+ await act(async () => pending.get('refund')!(page(0), 40));
+ const more = await screen.findByRole('button', { name: '40 results' });
+
+ // Tabbing moves focus from the input to the button; the results must outlive the close timer.
+ act(() => more.focus());
+ await new Promise(resolve => setTimeout(resolve, 200));
+ assert.ok(screen.queryByRole('listbox'), 'moving focus to "more" closed the results');
+
+ // Enter and Space activate a focused button through click.
+ fireEvent.click(more);
+ await waitFor(() => assert.deepEqual(offsets, ['0', '20']));
+ assert.equal(document.activeElement, input, 'focus was left on the replaced button');
+ await act(async () => pending.get('refund')!(page(20), 40));
+ await new Promise(resolve => setTimeout(resolve, 200));
+ assert.ok(screen.queryByRole('listbox'), 'the results closed after "more"');
+ assert.equal(screen.getAllByRole('option').length, 40);
+});
+
+test('focus leaving the widget still closes the results', async () => {
+ const { screen, act } = rtl;
+ const outside = document.createElement('button');
+ document.body.appendChild(outside);
+ try {
+ rtl.render(createElement(GlobalSearch, { onHit: () => undefined }));
+ const input = screen.getByRole('textbox');
+ input.focus();
+ await typeAndWaitForRequest(input, 'refund');
+ await act(async () => pending.get('refund')!(['refund issued']));
+ await screen.findByRole('listbox');
+ act(() => outside.focus());
+ await new Promise(resolve => setTimeout(resolve, 200));
+ assert.ok(!screen.queryByRole('listbox'), 'the results stayed open after focus left');
+ } finally {
+ outside.remove();
+ }
+});
+
+test('picking a hit with the mouse closes the results', async () => {
+ const { screen, act, fireEvent } = rtl;
+ const picked: string[] = [];
+ rtl.render(createElement(GlobalSearch, { onHit: (h: { messageId: string }) => picked.push(h.messageId) }));
+ const input = screen.getByRole('textbox');
+ input.focus();
+ await typeAndWaitForRequest(input, 'refund');
+ await act(async () => pending.get('refund')!(['refund issued']));
+ const hit = await screen.findByRole('option');
+ // A browser moves focus to the pressed button on mousedown, then fires click.
+ act(() => {
+ fireEvent.mouseDown(hit);
+ hit.focus();
+ });
+ fireEvent.click(hit);
+ await new Promise(resolve => setTimeout(resolve, 200));
+ assert.equal(picked.length, 1);
+ assert.ok(!screen.queryByRole('listbox'), 'the results stayed open after picking a hit');
+});
+
+test('clicking the input after a pick or Escape shows the results again', async () => {
+ const { screen, act, fireEvent } = rtl;
+ rtl.render(createElement(GlobalSearch, { onHit: () => undefined }));
+ const input = screen.getByRole('textbox');
+ input.focus();
+ await typeAndWaitForRequest(input, 'refund');
+ await act(async () => pending.get('refund')!(['refund issued']));
+ // A mouse pick keeps focus in the input, so the click back fires no focus event.
+ const hit = await screen.findByRole('option');
+ fireEvent.mouseDown(hit);
+ fireEvent.click(hit);
+ assert.ok(!screen.queryByRole('listbox'), 'picking a hit left the results open');
+ fireEvent.click(input);
+ assert.ok(await screen.findByRole('listbox'), 'clicking the input after a pick did not reopen the results');
+
+ fireEvent.keyDown(input, { key: 'Escape' });
+ assert.ok(!screen.queryByRole('listbox'), 'Escape left the results open');
+ fireEvent.click(input);
+ assert.ok(await screen.findByRole('listbox'), 'clicking the input after Escape did not reopen the results');
+});
+
+test('a click on the input while a keystroke search is pending sends that search once', async () => {
+ const { screen, fireEvent } = rtl;
+ rtl.render(createElement(GlobalSearch, { onHit: () => undefined }));
+ const input = screen.getByRole('textbox');
+ input.focus();
+ fireEvent.change(input, { target: { value: 'refund' } });
+ fireEvent.click(input); // before the 300 ms debounce fires
+ await new Promise(resolve => setTimeout(resolve, 400));
+ assert.deepEqual(offsets, ['0'], 'the same search went out twice');
+});
+
+test('clicking the input after Escape cancelled a scope change searches the scope shown', async () => {
+ const { screen, act, fireEvent, waitFor } = rtl;
+ rtl.render(createElement(GlobalSearch, { onHit: () => undefined, currentSessionId: 'sess-1' }));
+ const input = screen.getByRole('textbox');
+ input.focus();
+ await typeAndWaitForRequest(input, 'refund');
+ await act(async () => pending.get('refund')!(['refund issued']));
+ await screen.findByRole('listbox');
+
+ const scope = screen.getByRole('checkbox');
+ fireEvent.click(scope);
+ fireEvent.keyDown(scope, { key: 'Escape' }); // cancels the scoped search before it goes out
+ fireEvent.click(input);
+ await waitFor(() => assert.deepEqual(scopes, ['', 'sess-1']));
+});
+
+test('a hit reached with Tab is picked with Enter or Space', async () => {
+ const { screen, act, fireEvent } = rtl;
+ const picked: string[] = [];
+ rtl.render(createElement(GlobalSearch, { onHit: (h: { messageId: string }) => picked.push(h.messageId) }));
+ const input = screen.getByRole('textbox');
+ input.focus();
+ await typeAndWaitForRequest(input, 'refund');
+ await act(async () => pending.get('refund')!(['refund issued']));
+ const hit = await screen.findByRole('option');
+ act(() => hit.focus());
+ // Enter and Space activate a focused button through click, with no mousedown.
+ fireEvent.click(hit);
+ await new Promise(resolve => setTimeout(resolve, 200));
+ assert.equal(picked.length, 1);
+ assert.ok(!screen.queryByRole('listbox'), 'the results stayed open after picking a hit');
+});
+
+test('Escape with focus on "more" closes the results and is consumed', async () => {
+ const { screen, act, fireEvent } = rtl;
+ rtl.render(createElement(GlobalSearch, { onHit: () => undefined }));
+ const input = screen.getByRole('textbox');
+ input.focus();
+ await typeAndWaitForRequest(input, 'refund');
+ await act(async () => pending.get('refund')!(page(0), 40));
+ const more = await screen.findByRole('button', { name: '40 results' });
+ act(() => more.focus());
+ // Unconsumed, the key would reach the Chats page handler and close the open conversation instead.
+ assert.equal(fireEvent.keyDown(more, { key: 'Escape' }), false, 'Escape on "more" was not consumed');
+ assert.ok(!screen.queryByRole('listbox'), 'Escape on "more" left the results open');
+});
diff --git a/dashboard/src/components/GlobalSearch.tsx b/dashboard/src/components/GlobalSearch.tsx
index 846c1ab0b..dc955b979 100644
--- a/dashboard/src/components/GlobalSearch.tsx
+++ b/dashboard/src/components/GlobalSearch.tsx
@@ -25,18 +25,23 @@ export function GlobalSearch({ onHit, currentSessionId }: GlobalSearchProps) {
const [open, setOpen] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const blurTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const inputRef = useRef<HTMLInputElement>(null);
// Bumped by every search and by clearing the input: a response whose id is no longer current belongs
// to a query the user has moved past, and a slower earlier one must not overwrite the latest results.
const requestId = useRef(0);
+ // The query and scope the list was last searched for; Escape can cancel a pending search (a keystroke or
+ // a scope toggle), leaving the list behind what the input shows.
+ const searchedKey = useRef('');
+ const scopeKey = scopeCurrent && currentSessionId ? currentSessionId : '';
const run = useCallback(
async (query: string, offset: number, append: boolean) => {
const id = ++requestId.current;
- const params = buildSearchParams(
- query,
- scopeCurrent && currentSessionId ? { sessionId: currentSessionId } : undefined,
- { limit: PAGE_SIZE, offset },
- );
+ searchedKey.current = `${scopeKey}|${query}`;
+ const params = buildSearchParams(query, scopeKey ? { sessionId: scopeKey } : undefined, {
+ limit: PAGE_SIZE,
+ offset,
+ });
if (!params) {
setHits([]);
setTotal(0);
@@ -63,7 +68,7 @@ export function GlobalSearch({ onHit, currentSessionId }: GlobalSearchProps) {
if (id === requestId.current) setLoading(false);
}
},
- [scopeCurrent, currentSessionId, t],
+ [scopeKey, t],
);
// Debounce on input change.
@@ -77,12 +82,15 @@ export function GlobalSearch({ onHit, currentSessionId }: GlobalSearchProps) {
setLoading(false);
return;
}
+ // timer.current is non-null exactly while a search is pending, which the Escape handler reads.
timer.current = setTimeout(() => {
+ timer.current = null;
setOpen(true);
void run(q, 0, false);
}, DEBOUNCE_MS);
return () => {
if (timer.current) clearTimeout(timer.current);
+ timer.current = null;
};
}, [q, run]);
@@ -93,20 +101,58 @@ export function GlobalSearch({ onHit, currentSessionId }: GlobalSearchProps) {
};
}, []);
- const loadMore = () => void run(q, hits.length, true);
+ const reopen = () => {
+ if (!q.trim()) return;
+ if (searchedKey.current !== `${scopeKey}|${q}`) {
+ // Searched now, so the keystroke debounce still pending for the same text would only repeat it.
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = null;
+ void run(q, 0, false);
+ }
+ setOpen(true);
+ };
+
+ // Focus returns to the input so a keyboard user can keep going (Escape, Tab) once the button is
+ // replaced by the loading row, which would otherwise leave focus on nothing.
+ const loadMore = () => {
+ inputRef.current?.focus();
+ void run(q, hits.length, true);
+ };
return (
- <div className="global-search">
+ <div
+ className="global-search"
+ // Close only when focus leaves the whole widget: tabbing from the input to the scope toggle or
+ // the "more" button must keep the results open, or the button unmounts before it can be used.
+ onBlur={e => {
+ if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;
+ blurTimer.current = setTimeout(() => setOpen(false), 150);
+ }}
+ // Escape dismisses the open results from anywhere in the widget (input, scope toggle, a hit,
+ // "more") and is consumed, so a page-level Escape handler (the Chats page closes the open
+ // conversation) leaves it alone.
+ onKeyDown={e => {
+ if (e.key !== 'Escape' || e.nativeEvent.isComposing) return;
+ // A pending debounce would reopen the results the user just dismissed. Cancelling it is the
+ // key's whole effect, so it is consumed too, even before any results have opened.
+ const cancelledSearch = timer.current !== null;
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = null;
+ if (!cancelledSearch && (!open || !q.trim())) return;
+ e.preventDefault();
+ setOpen(false);
+ }}
+ >
<input
+ ref={inputRef}
className="global-search-input"
type="text"
placeholder={t('search.placeholder')}
value={q}
onChange={e => setQ(e.target.value)}
- onFocus={() => q.trim() && setOpen(true)}
- onBlur={() => {
- blurTimer.current = setTimeout(() => setOpen(false), 150);
- }}
+ onFocus={reopen}
+ // A pick or Escape closes the results with focus still in the input, where a click fires no focus.
+ onClick={reopen}
aria-label={t('search.placeholder')}
/>
{currentSessionId && (
@@ -123,7 +169,18 @@ export function GlobalSearch({ onHit, currentSessionId }: GlobalSearchProps) {
{!loading &&
!error &&
hits.map(h => (
- <button key={h.messageId} className="global-search-hit" role="option" onMouseDown={() => onHit(h)}>
+ <button
+ key={h.messageId}
+ className="global-search-hit"
+ role="option"
+ // preventDefault on mousedown keeps focus in the input, as on "more"; click fires for the
+ // mouse and for Enter/Space on a hit reached with Tab. Picking a hit closes the results.
+ onMouseDown={e => e.preventDefault()}
+ onClick={() => {
+ setOpen(false);
+ onHit(h);
+ }}
+ >
<div className="global-search-hit-meta">
{h.chatId} · {new Date(h.timestamp * 1000).toLocaleString()}
</div>
@@ -135,7 +192,9 @@ export function GlobalSearch({ onHit, currentSessionId }: GlobalSearchProps) {
</button>
))}
{!loading && !error && hits.length < total && (
- <button className="global-search-more" onClick={loadMore}>
+ // preventDefault on mousedown keeps focus in the input, so a mouse click does not start the
+ // close timer; click still fires for the mouse and for Enter/Space.
+ <button className="global-search-more" onMouseDown={e => e.preventDefault()} onClick={loadMore}>
{t('search.results', { count: total })}
</button>
)}
diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.ts
index 284093756..a3d67bdd4 100644
--- a/dashboard/src/pages/Chats.test.ts
+++ b/dashboard/src/pages/Chats.test.ts
@@ -303,6 +303,9 @@ function installFetchStub(): void {
const send = () => jsonResponse({ messageId: 'wamid.out.1', timestamp: 1_700_000_100 });
return sendGate ? sendGate.then(send) : Promise.resolve(send());
}
+ if (method === 'GET' && path.startsWith('/api/search?')) {
+ return Promise.resolve(jsonResponse({ hits: [], total: 0 }));
+ }
if (method === 'POST' && path === `/api/sessions/${SESSION.id}/status/send-text`) {
return Promise.resolve(jsonResponse({ success: true }));
}
@@ -585,6 +588,29 @@ test('Escape closes the open room, and is left alone while a dialog owns it', as
);
});
+test('Escape dismisses the message search results instead of the conversation behind them', async () => {
+ const { screen, fireEvent, within, waitFor } = rtl;
+ resetFetchCalls();
+ const { container } = renderChats();
+
+ await screen.findByText('Main (15551234567)');
+ fireEvent.click(await screen.findByText('Alice'));
+ await within(container.querySelector('.room-messages') as HTMLElement).findByText('hello from alice');
+
+ const search = container.querySelector('.global-search-input') as HTMLInputElement;
+ search.focus();
+ fireEvent.change(search, { target: { value: 'invoice' } });
+ await screen.findByRole('listbox');
+
+ fireEvent.keyDown(search, { key: 'Escape' });
+ // assert.ok, not assert.equal(node, null): formatting a live jsdom node into the failure message spins.
+ assert.ok(!screen.queryByRole('listbox'), 'Escape left the search results open');
+ assert.ok(screen.queryByRole('button', { name: 'Back' }), 'Escape closed the room while the results owned it');
+
+ fireEvent.keyDown(search, { key: 'Escape' });
+ await waitFor(() => assert.ok(!screen.queryByRole('button', { name: 'Back' }), 'Escape did not close the room'));
+});
+
// Stage a file in the open room and wait for the preview banner. A non-image type is used on
// purpose: the image branch calls URL.createObjectURL, which JSDOM does not implement.
//