English
The chat store
Step 1. Why a store
Why. Several parts of the screen show the same chats at the same time: the list pane, the unread badge in the rail and the tab bar, the browser tab's title "(3) Chatex", the conversation header (topic 19), the chat info panel (topic 21). If each component loaded its own copy, they would disagree after the first change. A store is a service that owns this state: components read its signals and call its methods, and nobody else changes the data.
This is the same separation as between an ASP.NET Core endpoint and a service: the component is thin, the store holds the rules. Chatex writes its stores by hand with signals rather than using a state library such as NgRx: the state is small, and plain classes with signal and computed are easy to read and test.
Step 2. ChatsStore
Why. The store keeps the list of the user's chats, most recently active first, as the API's GET /api/chats returns it in keyset pages (topic 11), and the full details of chats that have been opened. In topic 20 hub events will update both; this topic builds the parts that HTTP needs.
Do. Create the store:
ts
import { Injectable, computed, effect, inject, signal } from '@angular/core';
import { Subject, firstValueFrom } from 'rxjs';
import { ChatsApi, avatarUrl } from '../core/api/chatex-api';
import { ChatDto, ChatListItemDto, LastMessageDto, MessageDto } from '../core/api/models';
import { AuthService } from '../core/auth/auth.service';
import { BlobUrlService } from '../core/media/blob-url.service';
/** A chat list row; `lastMessage.deleted` is set locally when the last message gets deleted. */
export type ChatListItem = ChatListItemDto & {
lastMessage?: (LastMessageDto & { deleted?: boolean; hasAttachments?: boolean }) | null;
};
const byActivity = (a: ChatListItem, b: ChatListItem) =>
a.lastActivityAt < b.lastActivityAt ? 1 : a.lastActivityAt > b.lastActivityAt ? -1 : 0;
/** The user's chats (most recently active first), kept current by hub events. */
@Injectable({ providedIn: 'root' })
export class ChatsStore {
private readonly api = inject(ChatsApi);
private readonly auth = inject(AuthService);
private readonly blobs = inject(BlobUrlService);
private nextCursor: string | null = null;
private reloadTimer: ReturnType<typeof setTimeout> | undefined;
readonly items = signal<ChatListItem[]>([]);
readonly loaded = signal(false);
readonly loading = signal(false);
readonly loadingMore = signal(false);
readonly hasMore = signal(false);
/** Full details of chats that were opened, by id. */
readonly details = signal<Readonly<Record<string, ChatDto>>>({});
/** The chat on screen; its new messages don't count as unread. */
readonly activeChatId = signal<string | null>(null);
/** Fires when the user loses access to a chat (deleted, removed, left). */
readonly removed = new Subject<string>();
readonly totalUnread = computed(() =>
this.items().reduce((sum, chat) => sum + (chat.isMuted ? 0 : chat.unreadCount), 0),
);
constructor() {
effect(() => {
this.auth.sessionEpoch();
this.reset();
});
}
async loadFirst(): Promise<void> {
this.loading.set(true);
try {
const page = await firstValueFrom(this.api.list());
this.items.set([...page.items].sort(byActivity));
this.nextCursor = page.nextCursor ?? null;
this.hasMore.set(!!this.nextCursor);
this.loaded.set(true);
} finally {
this.loading.set(false);
}
}
async loadMore(): Promise<void> {
if (!this.nextCursor || this.loadingMore()) {
return;
}
this.loadingMore.set(true);
try {
const page = await firstValueFrom(this.api.list(this.nextCursor));
const known = new Set(this.items().map((c) => c.id));
this.items.update((list) => [...list, ...page.items.filter((c) => !known.has(c.id))]);
this.nextCursor = page.nextCursor ?? null;
this.hasMore.set(!!this.nextCursor);
} finally {
this.loadingMore.set(false);
}
}
/** Loads (or reloads) a chat's details and syncs its list row. */
async loadChat(chatId: string): Promise<ChatDto> {
const chat = await firstValueFrom(this.api.get(chatId));
this.setDetails(chat);
return chat;
}
/** Stores fresh chat details (from any API response) and patches the list row. */
setDetails(chat: ChatDto): void {
const previous = this.details()[chat.id];
if (previous && previous.hasAvatar !== chat.hasAvatar) {
this.blobs.invalidate(avatarUrl.chat(chat.id));
}
this.details.update((all) => ({ ...all, [chat.id]: chat }));
if (!chat.myRole) {
this.items.update((list) => list.filter((c) => c.id !== chat.id));
return;
}
const role = chat.myRole;
const exists = this.items().some((c) => c.id === chat.id);
if (exists) {
this.patch(chat.id, (c) => ({
...c,
title: chat.title,
hasAvatar: chat.hasAvatar,
isMuted: chat.isMuted,
myRole: role,
peer: chat.peer,
}));
} else {
const item: ChatListItem = {
id: chat.id,
type: chat.type,
title: chat.title,
hasAvatar: chat.hasAvatar,
lastActivityAt: new Date().toISOString(),
myRole: role,
isMuted: chat.isMuted,
lastMessage: null,
unreadCount: 0,
peer: chat.peer,
};
this.items.update((list) => [item, ...list]);
}
}
/**
* Forget a chat the user can no longer see. `notify` announces it on `removed` (the open
* conversation then closes with a notice); pass false when the user left or deleted it here.
*/
remove(chatId: string, notify = true): void {
this.items.update((list) => list.filter((c) => c.id !== chatId));
this.details.update((all) => {
const next = { ...all };
delete next[chatId];
return next;
});
if (notify) {
this.removed.next(chatId);
}
}
markReadLocally(chatId: string): void {
this.patch(chatId, (c) => (c.unreadCount ? { ...c, unreadCount: 0 } : c));
}
setMuted(chatId: string, muted: boolean): void {
this.patch(chatId, (c) => ({ ...c, isMuted: muted }));
const chat = this.details()[chatId];
if (chat) {
this.details.update((all) => ({ ...all, [chatId]: { ...chat, isMuted: muted } }));
}
}
/** Keeps the list in step with a message the user just sent. */
noteOwnMessage(message: MessageDto): void {
this.applyMessageCreated(message);
}
private applyMessageCreated(message: MessageDto): void {
const chat = this.items().find((c) => c.id === message.chatId);
if (!chat) {
// A chat we don't have yet (e.g. someone started a direct chat with us).
this.scheduleReload();
return;
}
if (chat.lastMessage && chat.lastMessage.id >= message.id) {
return;
}
const mine = message.sender.id === this.auth.user()?.id;
const visible =
this.activeChatId() === message.chatId && document.visibilityState === 'visible';
this.items.update((list) =>
list
.map((c) =>
c.id === message.chatId
? {
...c,
lastActivityAt: message.createdAt,
lastMessage: {
id: message.id,
senderId: message.sender.id,
body: (message.body ?? '').slice(0, 100),
createdAt: message.createdAt,
hasAttachments: message.attachments.length > 0,
},
unreadCount: mine || visible ? c.unreadCount : c.unreadCount + 1,
}
: c,
)
.sort(byActivity),
);
}
private patch(chatId: string, change: (chat: ChatListItem) => ChatListItem): void {
this.items.update((list) => list.map((c) => (c.id === chatId ? change(c) : c)));
}
private scheduleReload(): void {
clearTimeout(this.reloadTimer);
this.reloadTimer = setTimeout(() => void this.loadFirst().catch(() => undefined), 300);
}
private reset(): void {
clearTimeout(this.reloadTimer);
this.items.set([]);
this.details.set({});
this.loaded.set(false);
this.hasMore.set(false);
this.nextCursor = null;
this.activeChatId.set(null);
}
}ChatListItemextends the DTO with two client-side flags on the last message —deletedandhasAttachments— with an intersection type (A & B): an object that has the members of both.- The state is a set of signals:
items(the list),loaded,loading,loadingMore,hasMore,details(a dictionary from chat id toChatDto), andactiveChatId, the chat on screen. They arereadonlyfields: other code can callitems()and, by convention, does not callset— only the store's methods change the state. totalUnreadiscomputedfromitems: the sum of the unread counts, without muted chats. The rail and the tab title read it, and it is recomputed only when the list changes.loadFirst()andloadMore()load the first page and the following ones with the opaquenextCursor.loadMoreskips chats that are already known, because a chat can move between pages while the user scrolls.byActivitysorts bylastActivityAt; ISO timestamps sort correctly as strings.setDetails(chat)is the single entry point for fresh chat details from any API response — creating a chat, joining, renaming. It stores the details, patches the list row, and adds the chat to the top of the list if it is new. If the user is no longer a member (myRoleis null), the row is removed. IfhasAvatarchanged, it invalidates the cached avatar.remove(chatId, notify)forgets a chat and, unless told otherwise, announces it onremoved, an RxJSSubject— an event without state, which the open conversation listens to (topic 19). ASubjectfits better than a signal here: "this chat was removed" is something that happens, not a value that is.markReadLocally,setMuted,noteOwnMessageare used by the conversation (topic 19).noteOwnMessagemoves the chat to the top with the new last message after the user sends one; the same private method will apply incoming messages in topic 20.- The effect on
sessionEpochresets everything when the user signs out (topic 16), so the next user starts with an empty list.
Step 3. Testing the store
Why. The store is plain logic around signals, and its dependencies are services we can replace: the API with a stub that returns fixed pages, AuthService with the fake of topic 16, BlobUrlService with an object that has an invalidate mock.
Do. Create the spec. The import line in yellow becomes longer in topic 20, when the tests of hub events join it.
ts
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { fakeAuth } from '../../testing/fakes';
import { ChatsApi } from '../core/api/chatex-api';
import { ChatListItemDto } from '../core/api/models';
import { AuthService } from '../core/auth/auth.service';
import { BlobUrlService } from '../core/media/blob-url.service';
import { ChatsStore } from './chats.store';
function item(
id: string,
lastActivityAt: string,
overrides: Partial<ChatListItemDto> = {},
): ChatListItemDto {
return {
id,
type: 'group',
title: id,
hasAvatar: false,
lastActivityAt,
myRole: 'member',
isMuted: false,
lastMessage: null,
unreadCount: 0,
peer: null,
...overrides,
};
}
describe('ChatsStore', () => {
let store: ChatsStore;
beforeEach(async () => {
Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true });
const api = {
list: vi.fn(() =>
of({
items: [
item('chat-old', '2026-11-01T00:00:00Z'),
item('chat-1', '2026-11-05T00:00:00Z'),
item('chat-muted', '2026-11-03T00:00:00Z', { isMuted: true, unreadCount: 4 }),
],
nextCursor: null,
}),
),
};
TestBed.configureTestingModule({
providers: [
{ provide: ChatsApi, useValue: api },
{ provide: AuthService, useValue: fakeAuth() },
{ provide: BlobUrlService, useValue: { invalidate: vi.fn() } },
],
});
store = TestBed.inject(ChatsStore);
TestBed.tick();
await store.loadFirst();
});
const order = () => store.items().map((c) => c.id);
const get = (id: string) => store.items().find((c) => c.id === id)!;
it('lists chats by latest activity', () => {
expect(order()).toEqual(['chat-1', 'chat-muted', 'chat-old']);
});
it('clears unread counts locally', () => {
store.markReadLocally('chat-muted');
expect(get('chat-muted').unreadCount).toBe(0);
});
});{ provide: ChatsApi, useValue: api }replaces a service with an object, like registering a fake in anIServiceCollection. TypeScript's structural typing makes it easy: the object needs only the members the store calls.vi.fn(() => of({ … }))is a mock function that returns an Observable of one page;of(value)emits one value and completes, like a fulfilled HTTP call.TestBed.tick()runs the store's pending effect — the reset — before the test loads data, so every test starts from the state that a real application is in after start-up.Object.defineProperty(document, 'visibilityState', …)makes jsdom report a visible tab; the unread rules of topic 20 depend on it.
Check
powershell
npm test -- --watch=false Test Files 5 passed (5)
Tests 21 passed (21)