Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(dashboard): extract the three conversation-tab filters

Yudhi Armyndharis655ceb6d983e
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 69ab0adc0..a72d42f68 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -3,6 +3,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Trans, useTranslation } from 'react-i18next';
import { nextReconnectState } from '../utils/reconnectState';
import { applyIncomingToChatList, promoteChatWithSnippet } from '../utils/chatList';
+import { filterChats, filterChannels, groupStatusesByContact } from '../utils/chatFilters';
import {
Search,
Send,
@@ -1190,46 +1191,14 @@ export function Chats() {
[t],
);
- const searchMatch = (c: Chat) =>
- c.name?.toLowerCase().includes(searchQuery.toLowerCase()) || c.id.toLowerCase().includes(searchQuery.toLowerCase());
-
- // Chats tab: real conversations. Channel/status-kind rows are hidden here and surfaced on their
- // own tabs instead.
- const filteredChats = chats.filter(c => c.kind !== 'channel' && c.kind !== 'status' && searchMatch(c));
-
- // Channels tab: same search box, filtered client-side like the other two tabs. The zero-state
- // ("not subscribed to any channels") stays keyed on the unfiltered list below, so a non-matching
- // search just renders an empty list instead of claiming there are no subscriptions at all.
- const searchQueryLower = searchQuery.toLowerCase();
- const filteredChannels = (channelsQuery.data ?? []).filter(
- ch => ch.name.toLowerCase().includes(searchQueryLower) || ch.id.toLowerCase().includes(searchQueryLower),
- );
-
- // Status tab: group the flat status list by contact (one row per contact), newest-contact-first
- // across groups, filtered by the same search box. The store returns statuses newest-first
- // (postedAt DESC); each group's items are flipped to oldest-first so the viewer reads like a
- // WhatsApp story — newest at the bottom, where the viewer's open-at-newest scroll lands.
- // A plain const (not useMemo) mirrors filteredChats/filteredChannels above — statusesQuery.data
- // is already a stable, query-cached reference, so re-grouping on every render is cheap.
- const byStatusContact = new Map<string, ContactStatusGroup>();
- for (const item of statusesQuery.data ?? []) {
- const existing = byStatusContact.get(item.contact.id);
- if (existing) {
- existing.items.push(item);
- if (item.timestamp > existing.latest) existing.latest = item.timestamp;
- } else {
- byStatusContact.set(item.contact.id, { contact: item.contact, items: [item], latest: item.timestamp });
- }
- }
- for (const group of byStatusContact.values()) group.items.reverse();
- const groupedStatuses = Array.from(byStatusContact.values())
- .filter(
- g =>
- (g.contact.name ?? '').toLowerCase().includes(searchQueryLower) ||
- (g.contact.pushName ?? '').toLowerCase().includes(searchQueryLower) ||
- g.contact.id.toLowerCase().includes(searchQueryLower),
- )
- .sort((a, b) => (a.latest < b.latest ? 1 : a.latest > b.latest ? -1 : 0));
+ // One search box drives all three tabs; each matches on its own fields. Plain consts (not useMemo)
+ // because chats/channelsQuery.data/statusesQuery.data are already stable, query-cached references,
+ // so re-filtering on every render is cheap. See utils/chatFilters for the two status orderings.
+ const filteredChats = filterChats(chats, searchQuery);
+ // The channels zero-state ("not subscribed to any channels") stays keyed on the UNFILTERED list
+ // below, so a non-matching search renders an empty list rather than claiming there are none.
+ const filteredChannels = filterChannels(channelsQuery.data ?? [], searchQuery);
+ const groupedStatuses: ContactStatusGroup[] = groupStatusesByContact(statusesQuery.data ?? [], searchQuery);
// The open status group, derived — see the activeStatusContactId declaration.
const activeStatusGroup = activeStatusContactId
diff --git a/dashboard/src/utils/chatFilters.test.ts b/dashboard/src/utils/chatFilters.test.ts
new file mode 100644
index 000000000..e9f5d83c8
--- /dev/null
+++ b/dashboard/src/utils/chatFilters.test.ts
@@ -0,0 +1,105 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { filterChats, filterChannels, groupStatusesByContact } from './chatFilters.ts';
+
+const chat = (id: string, name?: string, kind?: string) => ({ id, name, kind });
+
+test('the chats tab hides channel and status rows, which have their own tabs', () => {
+ const all = [chat('[email protected]', 'Alice'), chat('n@newsletter', 'News', 'channel'), chat('s@broadcast', 'S', 'status')];
+
+ assert.deepEqual(
+ filterChats(all, '').map(c => c.id),
+ );
+});
+
+test('search matches name or id, case-insensitively, and an absent name never throws', () => {
+ const all = [chat('[email protected]', 'Alice'), chat('[email protected]'), chat('[email protected]', 'Bob')];
+
+ assert.deepEqual(
+ filterChats(all, 'ALI').map(c => c.id),
+ );
+ assert.deepEqual(
+ filterChats(all, '628222').map(c => c.id),
+ );
+ assert.deepEqual(
+ filterChats(all, 'zzz').map(c => c.id),
+ [],
+ );
+});
+
+test('channels match on their own name and id', () => {
+ const channels = [
+ { id: '111@newsletter', name: 'OpenWA News' },
+ { id: '222@newsletter', name: 'Other' },
+ ];
+
+ assert.deepEqual(
+ filterChannels(channels, 'openwa').map(c => c.id),
+ ['111@newsletter'],
+ );
+ assert.deepEqual(
+ filterChannels(channels, '222').map(c => c.id),
+ ['222@newsletter'],
+ );
+});
+
+const item = (contactId: string, timestamp: string, name?: string) => ({
+ contact: { id: contactId, name },
+ timestamp,
+});
+
+test('statuses collapse to one row per contact, newest contact first', () => {
+ // Store order is newest-first overall.
+ const statuses = [
+ item('b', '2026-08-01T03:00:00Z', 'Bob'),
+ item('a', '2026-08-01T02:00:00Z', 'Alice'),
+ item('a', '2026-08-01T01:00:00Z', 'Alice'),
+ ];
+
+ const groups = groupStatusesByContact(statuses, '');
+
+ assert.deepEqual(
+ groups.map(g => g.contact.id),
+ ['b', 'a'],
+ 'group order is newest-contact-first',
+ );
+ assert.equal(groups[1].items.length, 2, 'one row per contact, items kept together');
+ assert.equal(groups[1].latest, '2026-08-01T02:00:00Z', 'latest is the newest timestamp in the group');
+});
+
+test("a group's items run oldest-first, opposite to the group ordering", () => {
+ // The viewer opens at the newest and reads like a story: newest at the bottom, where the scroll
+ // lands. The store hands them over newest-first, so the group must flip them.
+ const groups = groupStatusesByContact(
+ [item('a', '2026-08-01T03:00:00Z'), item('a', '2026-08-01T02:00:00Z'), item('a', '2026-08-01T01:00:00Z')],
+ '',
+ );
+
+ assert.deepEqual(
+ groups[0].items.map(i => i.timestamp),
+ ['2026-08-01T01:00:00Z', '2026-08-01T02:00:00Z', '2026-08-01T03:00:00Z'],
+ );
+});
+
+test('status search matches name, pushName or id', () => {
+ const statuses = [
+ { contact: { id: '[email protected]', name: 'Alice', pushName: 'Ali' }, timestamp: '2026-08-01T01:00:00Z' },
+ { contact: { id: '[email protected]', name: undefined, pushName: 'Bobby' }, timestamp: '2026-08-01T02:00:00Z' },
+ ];
+
+ assert.deepEqual(
+ groupStatusesByContact(statuses, 'alice').map(g => g.contact.id),
+ );
+ assert.deepEqual(
+ groupStatusesByContact(statuses, 'bobby').map(g => g.contact.id),
+ );
+ assert.deepEqual(
+ groupStatusesByContact(statuses, '628111').map(g => g.contact.id),
+ );
+});
diff --git a/dashboard/src/utils/chatFilters.ts b/dashboard/src/utils/chatFilters.ts
new file mode 100644
index 000000000..6fac35e19
--- /dev/null
+++ b/dashboard/src/utils/chatFilters.ts
@@ -0,0 +1,71 @@
+/**
+ * Search filtering and status grouping for the three conversation tabs.
+ *
+ * One search box drives Chats, Channels and Status, but each tab matches on different fields, and the
+ * Status tab additionally collapses a flat list into one row per contact with a two-axis ordering.
+ * As inline consts inside the page these were three unrelated rules reading one piece of state; as
+ * functions they take the query as an argument and can be tested.
+ */
+
+/** Case-insensitive "does any of these fields contain the query". Absent fields never match. */
+const matches = (query: string, ...fields: (string | undefined)[]): boolean => {
+ const needle = query.toLowerCase();
+ return fields.some(f => (f ?? '').toLowerCase().includes(needle));
+};
+
+interface ChatLike {
+ id: string;
+ name?: string;
+ kind?: string;
+}
+
+/**
+ * Chats tab: real conversations only. Channel- and status-kind rows are hidden here and surfaced on
+ * their own tabs instead, so a channel never appears twice.
+ */
+export function filterChats<T extends ChatLike>(chats: T[], query: string): T[] {
+ return chats.filter(c => c.kind !== 'channel' && c.kind !== 'status' && matches(query, c.name, c.id));
+}
+
+/** Channels tab: same search box, matched on the channel's own name/id. */
+export function filterChannels<T extends { id: string; name: string }>(channels: T[], query: string): T[] {
+ return channels.filter(ch => matches(query, ch.name, ch.id));
+}
+
+interface StatusItemLike<C> {
+ contact: C;
+ /** ISO-8601. Compared lexically, which orders ISO strings correctly — the store hands them over as
+ * strings and never as epoch numbers. */
+ timestamp: string;
+}
+
+/**
+ * Status tab: collapse the flat status list to one row per contact.
+ *
+ * Two orderings, and they run in opposite directions on purpose. Groups are sorted newest-contact
+ * first, so the most recently active contact heads the list. Within a group the items are flipped to
+ * oldest-first, because the store returns statuses newest-first (postedAt DESC) and the viewer opens
+ * at the newest — reading like a WhatsApp story, newest at the bottom where the scroll lands.
+ *
+ * Getting either direction wrong is invisible in a screenshot and obvious to a user, which is why it
+ * is pinned by a test rather than left inline.
+ */
+export function groupStatusesByContact<
+ C extends { id: string; name?: string; pushName?: string },
+ T extends StatusItemLike<C>,
+>(statuses: T[], query: string): { contact: C; items: T[]; latest: string }[] {
+ const byContact = new Map<string, { contact: C; items: T[]; latest: string }>();
+ for (const item of statuses) {
+ const existing = byContact.get(item.contact.id);
+ if (existing) {
+ existing.items.push(item);
+ if (item.timestamp > existing.latest) existing.latest = item.timestamp;
+ } else {
+ byContact.set(item.contact.id, { contact: item.contact, items: [item], latest: item.timestamp });
+ }
+ }
+ for (const group of byContact.values()) group.items.reverse();
+ return Array.from(byContact.values())
+ .filter(g => matches(query, g.contact.name, g.contact.pushName, g.contact.id))
+ .sort((a, b) => (a.latest < b.latest ? 1 : a.latest > b.latest ? -1 : 0));
+}