Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ConversationList } from './ConversationList';
import { useAuthContext } from '../../../contexts/AuthContext';
import { getDmTransport } from '../transport';
import { getDirectMessageConversations } from '../graphql';
import type { DirectMessageConversation } from '../graphql';
import type { DmConversation, DmTransport } from '../types';
import { DmMessageStatus } from '../types';

jest.mock('../../../contexts/AuthContext', () => ({
useAuthContext: jest.fn(),
}));
jest.mock('../transport', () => ({
...jest.requireActual('../transport'),
getDmTransport: jest.fn(),
}));
jest.mock('../graphql', () => ({
...jest.requireActual('../graphql'),
getDirectMessageConversations: jest.fn(),
}));

const peer = {
id: 'ada',
name: 'Ada Lovelace',
username: 'ada',
image: '',
permalink: '',
};

const apiRow: DirectMessageConversation = {
id: 'c1',
jid: 'me@chat.daily.dev',
peerJid: 'ada@chat.daily.dev',
requestMessage: null,
createdByViewer: true,
isRequest: false,
unreadCount: 2,
createdAt: '2026-10-01T10:00:00Z',
peer,
};

const renderList = () =>
render(
<QueryClientProvider
client={
new QueryClient({ defaultOptions: { queries: { retry: false } } })
}
>
<ConversationList />
</QueryClientProvider>,
);

let resolveInbox: (conversations: DmConversation[]) => void;

beforeEach(() => {
jest.clearAllMocks();
jest.mocked(useAuthContext).mockReturnValue({
user: { id: 'me' },
} as unknown as ReturnType<typeof useAuthContext>);
jest.mocked(getDirectMessageConversations).mockResolvedValue([apiRow]);
jest.mocked(getDmTransport).mockReturnValue({
listConversations: () =>
new Promise<DmConversation[]>((resolve) => {
resolveInbox = resolve;
}),
} as unknown as DmTransport);
});

describe('ConversationList', () => {
it('shows the conversations from the API while the chat history loads', async () => {
renderList();

const row = await screen.findByRole('link', { name: /Ada Lovelace/ });
expect(row).toHaveAttribute('href', '/messages/ada?origin=inbox');
expect(row).toHaveAttribute('aria-busy', 'true');
expect(screen.getByLabelText('2 unread')).toBeInTheDocument();
});

it('swaps in the last messages once the chat history arrives', async () => {
renderList();
await screen.findByRole('link', { name: /Ada Lovelace/ });

resolveInbox([
{
peer: { ...peer, access: 'open' } as DmConversation['peer'],
unreadCount: 2,
lastMessage: {
id: 'm1',
peerId: 'ada',
senderId: 'ada',
body: 'See you at the meetup',
createdAt: '2026-10-12T09:00:00Z',
status: DmMessageStatus.Sent,
},
},
]);

expect(
await screen.findByText('See you at the meetup'),
).toBeInTheDocument();
expect(
screen.getByRole('link', { name: /Ada Lovelace/ }),
).not.toHaveAttribute('aria-busy');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@ import {
ButtonSize,
ButtonVariant,
} from '../../../components/buttons/Button';
import { dmConversationsQueryOptions } from '../queries';
import {
dmConversationPeersQueryOptions,
dmConversationsQueryOptions,
} from '../queries';
import type { DmConversation } from '../types';
import type { DirectMessageConversation } from '../graphql';
import { getMessagePreview } from '../media';
import { DmOrigin, getMessagesUrl } from '../urls';

Expand Down Expand Up @@ -96,6 +100,51 @@ const ConversationRow = ({
);
};

// A row before its last message has loaded: the person and the unread dot
// are already known, so the conversation can be opened right away.
const PendingConversationRow = ({
conversation: { peer, unreadCount },
isActive,
}: {
conversation: DirectMessageConversation;
isActive: boolean;
}): ReactElement => {
const isUnread = unreadCount > 0 && !isActive;

return (
<Link href={getMessagesUrl(peer.id, { origin: DmOrigin.Inbox })} passHref>
<a
aria-current={isActive ? 'page' : undefined}
aria-busy
className={classNames(
'flex items-center gap-3 rounded-12 px-3 py-2.5 transition-colors hover:bg-surface-hover',
isActive && 'bg-surface-float',
)}
>
<ProfilePicture
user={peer}
size={ProfileImageSize.Large}
nativeLazyLoading
/>
<FlexCol className="min-w-0 flex-1 gap-1.5">
<Typography type={TypographyType.Callout} bold={isUnread} truncate>
{peer.name}
</Typography>
<div className="flex items-center gap-2">
<div className="h-3 w-2/3 animate-pulse rounded-6 bg-surface-float" />
{isUnread && (
<span
aria-label={`${unreadCount} unread`}
className="ml-auto size-2 shrink-0 rounded-full bg-accent-cabbage-default"
/>
)}
</div>
</FlexCol>
</a>
</Link>
);
};

export const ConversationList = ({
activePeerId,
onNewMessage,
Expand All @@ -110,6 +159,12 @@ export const ConversationList = ({
isError,
refetch,
} = useQuery(dmConversationsQueryOptions(user));
const peersQuery = dmConversationPeersQueryOptions(user);
// Only needed until the full inbox lands.
const { data: pendingRows } = useQuery({
...peersQuery,
enabled: isPending && peersQuery.enabled,
});

if (isError) {
return (
Expand All @@ -131,6 +186,20 @@ export const ConversationList = ({
);
}

if (isPending && pendingRows?.length) {
return (
<nav aria-label="Conversations" className="flex flex-col gap-0.5 px-2">
{pendingRows.map((conversation) => (
<PendingConversationRow
key={conversation.peer.id}
conversation={conversation}
isActive={conversation.peer.id === activePeerId}
/>
))}
</nav>
);
}

if (isPending) {
return (
<FlexCol className="gap-2 px-3">
Expand Down
12 changes: 12 additions & 0 deletions packages/shared/src/features/messages/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
DirectMessageAccess,
getDirectMessageAccess,
getDirectMessageConversation,
getDirectMessageConversations,
getDirectMessageRequestCount,
getDirectMessageRequests,
getDirectMessageUnreadCount,
Expand Down Expand Up @@ -107,6 +108,17 @@ export const dmConversationsQueryOptions = (user: QueryUser) =>
enabled: !!user?.id,
});

// The inbox rows as the API knows them: who, and how many unread, but no last
// message. They come back in one request, while the full inbox waits for the
// chat connection and one archive lookup per conversation, so the list can
// show these in the meantime. The mock's conversations aren't in the API.
export const dmConversationPeersQueryOptions = (user: QueryUser) =>
queryOptions({
queryKey: generateQueryKey(RequestKey.DirectMessages, user, 'peers'),
queryFn: getDirectMessageConversations,
enabled: !!user?.id && !isDmMockMode,
});

// Server copies win, but messages that never reached the server only exist
// in the cache, so no refetch may drop them.
export const mergeWithLocalMessages = (
Expand Down
Loading