English
Presence and typing
Step 1. Who is online
Why. A green dot on an avatar and "online" or "last seen 5 minutes ago" under a name make a messenger feel alive. The hub tells a client when a user who shares a chat with it comes online or goes offline (UserOnline, UserOffline, topic 14), but a client that has just connected does not know who is online now. It asks with GetOnlineUsers(ids) for the users it shows — the partners of direct chats in the list, the members in the chat info panel — and keeps the answers current with the events.
Do. Create the presence store:
ts
import { Injectable, effect, inject, signal } from '@angular/core';
import { AuthService } from '../auth/auth.service';
import { RealtimeService } from './realtime.service';
/** Who is online, from UserOnline/UserOffline events plus GetOnlineUsers for the users on screen. */
@Injectable({ providedIn: 'root' })
export class PresenceStore {
private readonly realtime = inject(RealtimeService);
private readonly online = signal<ReadonlySet<string>>(new Set());
private readonly lastSeen = signal<Readonly<Record<string, string>>>({});
private readonly watched = new Set<string>();
constructor() {
this.realtime.events.subscribe((event) => {
if (event.type === 'userOnline') {
this.setOnline([event.userId], true);
} else if (event.type === 'userOffline') {
this.setOnline([event.userId], false);
this.lastSeen.update((map) => ({ ...map, [event.userId]: event.lastSeenAt }));
}
});
// Presence may have changed while disconnected: ask again for everyone shown.
this.realtime.connected.subscribe(() => void this.query([...this.watched]));
const auth = inject(AuthService);
effect(() => {
auth.sessionEpoch();
this.watched.clear();
this.online.set(new Set());
this.lastSeen.set({});
});
}
isOnline(userId: string | null | undefined): boolean {
return !!userId && this.online().has(userId);
}
/** A live "last seen" time, newer than what the API returned when the user went offline here. */
lastSeenAt(userId: string): string | undefined {
return this.lastSeen()[userId];
}
/** Start showing presence for these users. */
watch(userIds: readonly string[]): void {
const fresh = userIds.filter((id) => !this.watched.has(id));
fresh.forEach((id) => this.watched.add(id));
void this.query(fresh);
}
private async query(userIds: string[]): Promise<void> {
for (let i = 0; i < userIds.length; i += 100) {
const batch = userIds.slice(i, i + 100);
const online = new Set(await this.realtime.getOnlineUsers(batch));
this.online.update((current) => {
const next = new Set(current);
batch.forEach((id) => (online.has(id) ? next.add(id) : next.delete(id)));
return next;
});
}
}
private setOnline(userIds: string[], online: boolean): void {
this.online.update((current) => {
const next = new Set(current);
userIds.forEach((id) => (online ? next.add(id) : next.delete(id)));
return next;
});
}
}onlineis a signal holding aReadonlySetof user ids;isOnline(id)reads it, so a template or acomputedthat calls it re-renders when the set changes. Each change builds a newSet— the immutability rule of signals.lastSeenkeeps thelastSeenAtofUserOfflineevents. It is newer than thelastSeenAtthat the API returned when a profile was loaded, so "last seen" is correct without reloading the profile.watch(ids)remembers the users on screen and asks the hub about those not asked before, in batches of 100.- After every (re)connect it asks again for everyone watched, because presence may have changed while the client was offline; on sign-out it forgets everything.
Step 2. Who is typing
Why. The hub forwards Typing(chatId, userId) to the other members whenever someone types, at most every three seconds (the throttle of RealtimeService.sendTyping). The server stores nothing: a typing indicator is a fleeting signal, and the receivers expire it after about five seconds without news (Docs/Realtime.md).
Do. Create the typing store:
ts
import { Injectable, inject, signal } from '@angular/core';
import { AuthService } from '../auth/auth.service';
import { RealtimeService } from './realtime.service';
/** Typing indicators expire this long after the last Typing event. */
export const TYPING_TTL_MS = 5_000;
/** Who is typing in which chat. Typing is never stored on the server. */
@Injectable({ providedIn: 'root' })
export class TypingStore {
private readonly auth = inject(AuthService);
/** chatId → userId → expiry timestamp. */
private readonly typing = signal<Readonly<Record<string, Readonly<Record<string, number>>>>>({});
private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
constructor() {
inject(RealtimeService).events.subscribe((event) => {
if (event.type === 'typing' && event.userId !== this.auth.user()?.id) {
this.set(event.chatId, event.userId);
} else if (event.type === 'messageCreated') {
this.clear(event.message.chatId, event.message.sender.id);
}
});
}
/** Ids of the users typing in the chat. Reads a signal, so it works inside computed(). */
usersTyping(chatId: string): string[] {
return Object.keys(this.typing()[chatId] ?? {});
}
private set(chatId: string, userId: string): void {
this.typing.update((all) => ({
...all,
[chatId]: { ...all[chatId], [userId]: Date.now() + TYPING_TTL_MS },
}));
const key = `${chatId}:${userId}`;
clearTimeout(this.timers.get(key));
this.timers.set(
key,
setTimeout(() => this.clear(chatId, userId), TYPING_TTL_MS),
);
}
private clear(chatId: string, userId: string): void {
const key = `${chatId}:${userId}`;
clearTimeout(this.timers.get(key));
this.timers.delete(key);
if (!this.typing()[chatId]?.[userId]) {
return;
}
this.typing.update((all) => {
const chat = { ...all[chatId] };
delete chat[userId];
return { ...all, [chatId]: chat };
});
}
}typingmaps chat ids to users and their expiry times;usersTyping(chatId)reads the signal, socomputeds that call it update.- Each
Typingevent (from somebody else) sets or extends the user's entry and restarts a five-second timer per chat and user; the timer removes the entry. - A
messageCreatedevent clears the sender's entry at once: when the message arrives, the "typing…" must disappear without waiting five seconds.
Step 3. The composer announces typing
Do. Complete the composer and its spec (new lines in green). Both are now final:
angular-ts
import { HttpEventType } from '@angular/common/http';
import {
ChangeDetectionStrategy,
Component,
DestroyRef,
ElementRef,
Injector,
afterNextRender,
computed,
effect,
inject,
input,
model,
signal,
untracked,
viewChild,
} from '@angular/core';
import { Subscription } from 'rxjs';
import { AttachmentsApi } from '../../core/api/chatex-api';
import { AttachmentDto } from '../../core/api/models';
import { problemMessage } from '../../core/api/problem';
import { RealtimeService } from '../../core/realtime/realtime.service';
import { ToastService } from '../../core/ui/toast.service';
import { ChatMessage, MessagesStore } from '../../state/messages.store';
import { ICONS } from '../../shared/ui/icons';
import { FileSizePipe } from '../../shared/ui/pipes';
export const MAX_ATTACHMENTS = 10;
export const MAX_BODY = 4000;
/** What the server accepts; checked here only to fail fast. */
const ALLOWED_TYPES = new Set([
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'application/pdf',
'text/plain',
'application/zip',
'application/x-zip-compressed',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-powerpoint',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'audio/mpeg',
'audio/ogg',
'video/ogg',
'video/mp4',
'video/mpeg',
]);
const ALLOWED_EXTENSIONS =
/\.(jpe?g|png|gif|webp|pdf|txt|zip|docx?|xlsx?|pptx?|mp3|mpeg|ogg|oga|ogv|mp4)$/i;
export function isAllowedFile(file: File): boolean {
return ALLOWED_TYPES.has(file.type) || (!file.type && ALLOWED_EXTENSIONS.test(file.name));
}
interface Upload {
key: number;
file: File;
progress: number;
attachment?: AttachmentDto;
error?: string;
}
let uploadKeys = 0;
/** The message box: text, reply/edit bar, and attachments uploaded as soon as they're picked. */
@Component({
selector: 'app-composer',
imports: [FileSizePipe, ICONS],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: 'block border-t border-line bg-surface pb-safe' },
template: `
@if (editing(); as m) {
<div class="flex items-center gap-3 border-b border-line px-4 py-2 text-sm">
<svg lucidePencil class="size-4 shrink-0 text-brand-600"></svg>
<div class="min-w-0 flex-1">
<p class="font-medium text-brand-600 dark:text-brand-400">Editing message</p>
<p class="truncate text-muted">{{ m.body }}</p>
</div>
<button
type="button"
class="icon-btn size-8"
aria-label="Cancel editing"
(click)="cancel()"
>
<svg lucideX class="size-4"></svg>
</button>
</div>
} @else if (replyTo(); as m) {
<div class="flex items-center gap-3 border-b border-line px-4 py-2 text-sm">
<svg lucideReply class="size-4 shrink-0 text-brand-600"></svg>
<div class="min-w-0 flex-1">
<p class="font-medium text-brand-600 dark:text-brand-400">
Reply to {{ m.sender.displayName }}
</p>
<p class="truncate text-muted">{{ m.body || '📎 Attachment' }}</p>
</div>
<button type="button" class="icon-btn size-8" aria-label="Cancel reply" (click)="cancel()">
<svg lucideX class="size-4"></svg>
</button>
</div>
}
@if (uploads().length) {
<ul class="flex gap-2 overflow-x-auto px-3 pt-3" aria-label="Attachments">
@for (u of uploads(); track u.key) {
<li
class="relative flex w-44 shrink-0 items-center gap-2 rounded-xl border border-line bg-subtle p-2 pr-7"
[class.border-red-400]="u.error"
>
<svg lucideFile class="size-5 shrink-0 text-muted"></svg>
<div class="min-w-0 flex-1">
<p class="truncate text-xs font-medium">{{ u.file.name }}</p>
@if (u.error) {
<p class="truncate text-[11px] text-red-600 dark:text-red-400" [title]="u.error">
{{ u.error }}
</p>
} @else if (!u.attachment) {
<div class="mt-1 h-1 overflow-hidden rounded bg-line">
<div
class="h-full bg-brand-500 transition-[width]"
[style.width.%]="u.progress"
></div>
</div>
} @else {
<p class="text-[11px] text-muted">{{ u.file.size | fileSize }}</p>
}
</div>
<button
type="button"
class="absolute top-1 right-1 rounded-full p-1 text-muted hover:bg-line hover:text-fg"
[attr.aria-label]="'Remove ' + u.file.name"
(click)="removeUpload(u.key)"
>
<svg lucideX class="size-3.5"></svg>
</button>
</li>
}
</ul>
}
<form
class="flex items-end gap-1 px-2 py-2 sm:px-3"
(submit)="$event.preventDefault(); submit()"
>
@if (!editing()) {
<button
type="button"
class="icon-btn"
aria-label="Attach files"
title="Attach files"
(click)="fileInput.click()"
>
<svg lucidePaperclip class="size-5"></svg>
</button>
<input #fileInput type="file" multiple class="hidden" (change)="onFilesPicked(fileInput)" />
}
<div class="min-w-0 flex-1">
<textarea
#textarea
rows="1"
class="input max-h-40 resize-none overflow-y-auto rounded-3xl border-transparent bg-subtle px-4 py-2.5 leading-5"
[placeholder]="placeholder()"
aria-label="Message"
[maxLength]="maxBody"
[value]="text()"
(input)="onInput($any($event.target).value)"
(keydown)="onKeydown($event)"
(paste)="onPaste($event)"
></textarea>
@if (text().length > maxBody - 300) {
<p class="px-4 pt-1 text-right text-[11px] text-muted">
{{ text().length }} / {{ maxBody }}
</p>
}
</div>
<button
type="submit"
class="flex size-10 shrink-0 items-center justify-center rounded-full bg-brand-600 text-white transition-colors hover:bg-brand-700 disabled:bg-zinc-300 disabled:text-zinc-500 dark:disabled:bg-zinc-700 dark:disabled:text-zinc-400"
[disabled]="!canSubmit()"
[attr.aria-label]="editing() ? 'Save' : 'Send'"
>
@if (editing()) {
<svg lucideCheck class="size-5"></svg>
} @else {
<svg lucideSend class="size-5"></svg>
}
</button>
</form>
`,
})
export class Composer {
private readonly store = inject(MessagesStore);
private readonly attachmentsApi = inject(AttachmentsApi);
private readonly realtime = inject(RealtimeService);
private readonly toast = inject(ToastService);
private readonly injector = inject(Injector);
private readonly subscriptions = new Map<number, Subscription>();
private readonly coarsePointer =
typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches;
readonly chatId = input.required<string>();
readonly placeholder = input('Message');
readonly replyTo = model<ChatMessage | null>(null);
readonly editing = model<ChatMessage | null>(null);
protected readonly maxBody = MAX_BODY;
protected readonly text = signal('');
protected readonly uploads = signal<Upload[]>([]);
private readonly textarea = viewChild.required<ElementRef<HTMLTextAreaElement>>('textarea');
protected readonly canSubmit = computed(() => {
const body = this.text().trim();
if (this.editing()) {
return body.length > 0 && body !== this.editing()?.body;
}
const uploads = this.uploads();
const uploading = uploads.some((u) => !u.attachment && !u.error);
const ready = uploads.some((u) => u.attachment);
return !uploading && (body.length > 0 || ready);
});
constructor() {
// Starting an edit puts the message text into the box; a reply just focuses it.
effect(() => {
const editing = this.editing();
untracked(() => {
this.text.set(editing?.body ?? '');
if (editing) this.focus();
});
});
effect(() => {
if (this.replyTo()) untracked(() => this.focus());
});
// Grow with the text, up to max-h-40 (then it scrolls).
effect(() => {
this.text();
afterNextRender(() => this.autoResize(), { injector: this.injector });
});
// Switching chats starts with an empty box.
effect(() => {
this.chatId();
untracked(() => this.reset());
});
inject(DestroyRef).onDestroy(() => this.subscriptions.forEach((s) => s.unsubscribe()));
}
private autoResize(): void {
const element = this.textarea().nativeElement;
element.style.height = 'auto';
const border = element.offsetHeight - element.clientHeight;
element.style.height = `${element.scrollHeight + border}px`;
}
focus(): void {
setTimeout(() => this.textarea().nativeElement.focus());
}
/** Adds files from the picker, a paste or a drop. */
addFiles(files: File[]): void {
if (this.editing() || !files.length) {
return;
}
const room = MAX_ATTACHMENTS - this.uploads().length;
if (files.length > room) {
this.toast.error(`You can attach up to ${MAX_ATTACHMENTS} files per message.`);
files = files.slice(0, Math.max(0, room));
}
for (const file of files) {
if (!isAllowedFile(file)) {
this.toast.error(`“${file.name}” has a file type that can't be sent.`);
continue;
}
this.startUpload(file);
}
}
protected onInput(value: string): void {
this.text.set(value);
if (value.trim() && !this.editing()) {
this.realtime.sendTyping(this.chatId());
}
}
protected onKeydown(event: KeyboardEvent): void {
if (event.key === 'Escape' && (this.editing() || this.replyTo())) {
event.preventDefault();
this.cancel();
return;
}
// On touch keyboards Enter makes a new line; elsewhere Enter sends and Shift+Enter breaks the line.
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing && !this.coarsePointer) {
event.preventDefault();
this.submit();
}
}
protected onPaste(event: ClipboardEvent): void {
const files = Array.from(event.clipboardData?.files ?? []);
if (files.length) {
event.preventDefault();
this.addFiles(files);
}
}
protected onFilesPicked(input: HTMLInputElement): void {
this.addFiles(Array.from(input.files ?? []));
input.value = '';
}
protected cancel(): void {
if (this.editing()) {
this.editing.set(null);
this.text.set('');
}
this.replyTo.set(null);
}
protected removeUpload(key: number): void {
this.subscriptions.get(key)?.unsubscribe();
this.subscriptions.delete(key);
this.uploads.update((list) => list.filter((u) => u.key !== key));
}
submit(): void {
if (!this.canSubmit()) {
return;
}
const body = this.text().trim();
const editing = this.editing();
if (editing) {
this.editing.set(null);
this.text.set('');
this.store.edit(editing.id, body).catch((error) => this.toast.error(error));
return;
}
const attachments = this.uploads()
.map((u) => u.attachment)
.filter((a): a is AttachmentDto => !!a);
const replyTo = this.replyTo()?.id ?? null;
this.text.set('');
this.uploads.set([]);
this.replyTo.set(null);
this.focus();
this.store.send(body, attachments, replyTo).catch((error) => this.toast.error(error));
}
private startUpload(file: File): void {
const key = ++uploadKeys;
this.uploads.update((list) => [...list, { key, file, progress: 0 }]);
const patch = (change: Partial<Upload>) =>
this.uploads.update((list) => list.map((u) => (u.key === key ? { ...u, ...change } : u)));
const subscription = this.attachmentsApi.upload(file).subscribe({
next: (event) => {
if (event.type === HttpEventType.UploadProgress && event.total) {
patch({ progress: Math.round((event.loaded / event.total) * 100) });
} else if (event.type === HttpEventType.Response && event.body) {
patch({ progress: 100, attachment: event.body });
}
},
error: (error) => patch({ error: problemMessage(error) }),
});
this.subscriptions.set(key, subscription);
}
private reset(): void {
this.subscriptions.forEach((s) => s.unsubscribe());
this.subscriptions.clear();
this.text.set('');
this.uploads.set([]);
}
}ts
import { TestBed } from '@angular/core/testing';
import { NEVER } from 'rxjs';
import { fakeRealtime } from '../../../testing/fakes';
import { AttachmentsApi } from '../../core/api/chatex-api';
import { RealtimeService } from '../../core/realtime/realtime.service';
import { ToastService } from '../../core/ui/toast.service';
import { MessagesStore } from '../../state/messages.store';
import { Composer, MAX_ATTACHMENTS, isAllowedFile } from './composer';
describe('Composer', () => {
let store: { send: ReturnType<typeof vi.fn>; edit: ReturnType<typeof vi.fn> };
let toast: { error: ReturnType<typeof vi.fn> };
let upload: ReturnType<typeof vi.fn>;
let realtime: ReturnType<typeof fakeRealtime>;
async function create() {
store = { send: vi.fn(async () => undefined), edit: vi.fn(async () => undefined) };
toast = { error: vi.fn() };
upload = vi.fn(() => NEVER);
realtime = fakeRealtime();
TestBed.configureTestingModule({
imports: [Composer],
providers: [
{ provide: MessagesStore, useValue: store },
{ provide: AttachmentsApi, useValue: { upload } },
{ provide: ToastService, useValue: toast },
{ provide: RealtimeService, useValue: realtime },
],
});
const fixture = TestBed.createComponent(Composer);
fixture.componentRef.setInput('chatId', 'chat-1');
await fixture.whenStable();
const textarea = fixture.nativeElement.querySelector('textarea') as HTMLTextAreaElement;
return { fixture, textarea };
}
function type(textarea: HTMLTextAreaElement, value: string) {
textarea.value = value;
textarea.dispatchEvent(new Event('input'));
}
function press(textarea: HTMLTextAreaElement, init: KeyboardEventInit) {
const event = new KeyboardEvent('keydown', { key: 'Enter', cancelable: true, ...init });
textarea.dispatchEvent(event);
return event;
}
it('sends on Enter and clears the box', async () => {
const { fixture, textarea } = await create();
type(textarea, ' hello ');
await fixture.whenStable();
const event = press(textarea, {});
await fixture.whenStable();
expect(event.defaultPrevented).toBe(true);
expect(store.send).toHaveBeenCalledWith('hello', [], null);
expect(textarea.value).toBe('');
});
it('keeps Shift+Enter for a new line', async () => {
const { fixture, textarea } = await create();
type(textarea, 'line one');
await fixture.whenStable();
const event = press(textarea, { shiftKey: true });
expect(event.defaultPrevented).toBe(false);
expect(store.send).not.toHaveBeenCalled();
});
it("doesn't send an empty message", async () => {
const { textarea } = await create();
type(textarea, ' ');
press(textarea, {});
expect(store.send).not.toHaveBeenCalled();
});
it('tells the others the user is typing', async () => {
const { textarea } = await create();
type(textarea, 'h');
expect(realtime.sendTyping).toHaveBeenCalledWith('chat-1');
});
it(`uploads at most ${MAX_ATTACHMENTS} files per message`, async () => {
const { fixture } = await create();
const files = Array.from(
{ length: MAX_ATTACHMENTS + 2 },
(_, i) => new File(['x'], `f${i}.txt`, { type: 'text/plain' }),
);
fixture.componentInstance.addFiles(files);
expect(upload).toHaveBeenCalledTimes(MAX_ATTACHMENTS);
expect(toast.error).toHaveBeenCalled();
});
it('rejects file types the server does not accept', async () => {
const { fixture } = await create();
fixture.componentInstance.addFiles([
new File(['x'], 'run.exe', { type: 'application/x-msdownload' }),
]);
expect(upload).not.toHaveBeenCalled();
expect(toast.error).toHaveBeenCalled();
});
});
describe('isAllowedFile', () => {
it('accepts allowed types, or allowed extensions when the type is unknown', () => {
expect(isAllowedFile(new File([''], 'a.png', { type: 'image/png' }))).toBe(true);
expect(isAllowedFile(new File([''], 'notes.docx', { type: '' }))).toBe(true);
expect(isAllowedFile(new File([''], 'a.svg', { type: 'image/svg+xml' }))).toBe(false);
});
});onInput calls sendTyping for non-empty text, but not while editing an old message — editing is not "typing a message" for the others. The new test checks that the first keystroke reaches the realtime service.
Step 4. Presence and typing on screen
Do. Complete the chat list (new lines in green). It is now final:
angular-ts
import {
ChangeDetectionStrategy,
Component,
ElementRef,
computed,
effect,
inject,
signal,
viewChild,
} from '@angular/core';
import { RouterLink, RouterLinkActive } from '@angular/router';
import { chatTitle } from '../../core/api/models';
import { AuthService } from '../../core/auth/auth.service';
import { PresenceStore } from '../../core/realtime/presence.store';
import { TypingStore } from '../../core/realtime/typing.store';
import { ChatListItem, ChatsStore } from '../../state/chats.store';
import { Avatar } from '../../shared/ui/avatar';
import { Dialogs } from '../../shared/ui/dialogs';
import { ICONS } from '../../shared/ui/icons';
import { ShortWhenPipe } from '../../shared/ui/pipes';
import { NewChatDialog } from '../new-chat/new-chat-dialog';
@Component({
selector: 'app-chat-list-pane',
imports: [RouterLink, RouterLinkActive, Avatar, ShortWhenPipe, ICONS],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<header class="pt-safe flex items-center gap-2 px-4">
<h1 class="flex-1 py-4 text-xl font-bold tracking-tight">Chats</h1>
<button
type="button"
class="icon-btn"
aria-label="New chat"
title="New chat"
(click)="newChat()"
>
<svg lucideSquarePen class="size-5"></svg>
</button>
</header>
<div class="px-4 pb-3">
<label class="relative block">
<span class="sr-only">Filter chats</span>
<svg
lucideSearch
class="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted"
></svg>
<input
class="input border-transparent bg-subtle pl-9"
type="search"
placeholder="Search chats"
[value]="filter()"
(input)="filter.set($any($event.target).value)"
/>
</label>
</div>
<div class="min-h-0 flex-1 overflow-y-auto pb-20 md:pb-2">
@if (!store.loaded() && store.loading()) {
<ul aria-hidden="true">
@for (i of skeleton; track i) {
<li class="flex animate-pulse items-center gap-3 px-4 py-3">
<span class="size-12 rounded-full bg-subtle"></span>
<span class="flex-1 space-y-2">
<span class="block h-3 w-1/2 rounded bg-subtle"></span>
<span class="block h-3 w-3/4 rounded bg-subtle"></span>
</span>
</li>
}
</ul>
} @else if (store.loaded() && !store.items().length) {
<div class="flex flex-col items-center gap-3 px-6 py-16 text-center">
<span
class="flex size-14 items-center justify-center rounded-full bg-brand-50 text-brand-600 dark:bg-brand-950 dark:text-brand-300"
>
<svg lucideMessagesSquare class="size-7"></svg>
</span>
<p class="font-medium">No chats yet</p>
<p class="text-sm text-muted">Start a conversation or find a public group.</p>
<div class="mt-2 flex gap-2">
<button type="button" class="btn-primary" (click)="newChat()">New chat</button>
<a routerLink="/discover" class="btn-secondary">Discover</a>
</div>
</div>
} @else if (!visible().length) {
<p class="px-4 py-10 text-center text-sm text-muted">No chats match “{{ filter() }}”.</p>
}
<ul>
@for (chat of visible(); track chat.id) {
<li>
<a
[routerLink]="['/chats', chat.id]"
routerLinkActive="!bg-brand-50 dark:!bg-brand-950/60"
class="flex items-center gap-3 px-4 py-2.5 transition-colors hover:bg-subtle"
>
<app-avatar
[kind]="chat.type === 'direct' ? 'user' : 'chat'"
[id]="chat.type === 'direct' ? chat.peer?.id : chat.id"
[name]="title(chat)"
[hasAvatar]="chat.type === 'direct' ? !!chat.peer?.hasAvatar : chat.hasAvatar"
[online]="chat.type === 'direct' && presence.isOnline(chat.peer?.id)"
[size]="48"
/>
<span class="min-w-0 flex-1">
<span class="flex items-center gap-1.5">
@if (chat.type === 'channel') {
<svg lucideMegaphone class="size-3.5 shrink-0 text-muted"></svg>
} @else if (chat.type === 'group') {
<svg lucideUsers class="size-3.5 shrink-0 text-muted"></svg>
}
<span class="truncate font-medium">{{ title(chat) }}</span>
@if (chat.isMuted) {
<svg
lucideBellOff
class="size-3.5 shrink-0 text-muted"
aria-label="Muted"
></svg>
}
<span class="ml-auto shrink-0 pl-2 text-xs text-muted">{{
chat.lastMessage?.createdAt ?? chat.lastActivityAt | shortWhen
}}</span>
</span>
<span class="mt-0.5 flex items-center gap-2">
<span class="min-w-0 flex-1 truncate text-sm text-muted">
@if (typingIn(chat.id); as typing) {
<span class="text-brand-600 dark:text-brand-400">{{ typing }}</span>
} @else {
{{ preview(chat) }}
}
</span>
@if (chat.unreadCount) {
<span
class="badge"
[class]="
chat.isMuted
? 'bg-zinc-400 text-white dark:bg-zinc-600'
: 'bg-brand-600 text-white'
"
>
{{ chat.unreadCount > 99 ? '99+' : chat.unreadCount }}
</span>
}
</span>
</span>
</a>
</li>
}
</ul>
@if (store.hasMore() && !filter()) {
<div #sentinel class="flex justify-center py-4 text-muted">
@if (store.loadingMore()) {
<svg lucideLoaderCircle class="size-5 animate-spin"></svg>
}
</div>
}
</div>
`,
})
export class ChatListPane {
protected readonly store = inject(ChatsStore);
protected readonly presence = inject(PresenceStore);
private readonly typing = inject(TypingStore);
private readonly me = inject(AuthService).user;
private readonly dialogs = inject(Dialogs);
protected readonly skeleton = [1, 2, 3, 4, 5, 6];
protected readonly filter = signal('');
protected readonly visible = computed(() => {
const q = this.filter().trim().toLowerCase();
const items = this.store.items();
return q ? items.filter((c) => this.title(c).toLowerCase().includes(q)) : items;
});
private readonly sentinel = viewChild<ElementRef<HTMLElement>>('sentinel');
constructor() {
// Infinite scroll: load the next page when the bottom sentinel comes into view.
effect((onCleanup) => {
const element = this.sentinel()?.nativeElement;
if (!element) {
return;
}
const observer = new IntersectionObserver((entries) => {
if (entries.some((e) => e.isIntersecting)) {
void this.store.loadMore();
}
});
observer.observe(element);
onCleanup(() => observer.disconnect());
});
// Show presence dots for direct-chat partners.
effect(() => {
const peers = this.store
.items()
.map((c) => c.peer?.id)
.filter((id): id is string => !!id);
this.presence.watch(peers);
});
}
protected title(chat: ChatListItem): string {
return chatTitle(chat);
}
protected preview(chat: ChatListItem): string {
const last = chat.lastMessage;
if (!last) {
return chat.type === 'channel' ? 'Channel created' : 'No messages yet';
}
const prefix = last.senderId === this.me()?.id && chat.type !== 'channel' ? 'You: ' : '';
if (last.deleted) {
return `${prefix}Message deleted`;
}
return prefix + (last.body || (last.hasAttachments !== false ? '📎 Attachment' : ''));
}
protected typingIn(chatId: string): string | null {
const count = this.typing.usersTyping(chatId).length;
return count ? (count === 1 ? 'typing…' : `${count} people typing…`) : null;
}
protected newChat(): void {
this.dialogs.open(NewChatDialog);
}
}- The avatar of a direct chat gets
[online]="chat.type === 'direct' && presence.isOnline(chat.peer?.id)", the green dot. (The attribute is inside an existing element, so it cannot be highlighted in the listing.) - The preview line shows "typing…" or "3 people typing…" instead of the last message while someone types.
- An effect asks the presence store to watch the partners of all direct chats in the list; it runs again when the list changes.
The conversation header shows presence and typing too. Only the profile dialog of topic 21 is still missing in the page:
angular-ts
import {
ChangeDetectionStrategy,
Component,
DestroyRef,
computed,
effect,
inject,
input,
resource,
signal,
untracked,
viewChild,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Router, RouterLink, RouterOutlet } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import { ChatsApi, UsersApi } from '../../core/api/chatex-api';
import { canPost, chatTitle } from '../../core/api/models';
import { toProblem } from '../../core/api/problem';
import { AuthService } from '../../core/auth/auth.service';
import { PresenceStore } from '../../core/realtime/presence.store';
import { TypingStore } from '../../core/realtime/typing.store';
import { ToastService } from '../../core/ui/toast.service';
import { ChatsStore } from '../../state/chats.store';
import { ChatMessage, MessagesStore } from '../../state/messages.store';
import { Avatar } from '../../shared/ui/avatar';
import { Dialogs } from '../../shared/ui/dialogs';
import { ICONS } from '../../shared/ui/icons';
import { timeAgo } from '../../shared/ui/pipes';
import { Composer } from './composer';
import { MessageList } from './message-list';
@Component({
selector: 'app-conversation-page',
imports: [RouterLink, RouterOutlet, Avatar, MessageList, Composer, ICONS],
providers: [MessagesStore],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: 'flex min-h-0 flex-1' },
template: `
<section
class="relative flex min-w-0 flex-1 flex-col bg-canvas"
(dragover)="onDragOver($event)"
(dragleave)="dragging.set(false)"
(drop)="onDrop($event)"
>
<header
class="pt-safe flex items-center gap-1 border-b border-line bg-surface/95 px-2 backdrop-blur sm:px-3"
>
<a routerLink="/chats" class="icon-btn md:hidden" aria-label="Back to chats">
<svg lucideArrowLeft class="size-5"></svg>
</a>
<a
[routerLink]="['/chats', chatId(), 'info']"
class="flex min-w-0 flex-1 items-center gap-3 rounded-lg py-2 pr-2 pl-1 hover:bg-subtle/60"
>
<app-avatar
[kind]="isDirect() ? 'user' : 'chat'"
[id]="isDirect() ? chat()?.peer?.id : chatId()"
[name]="title()"
[hasAvatar]="isDirect() ? !!chat()?.peer?.hasAvatar : !!chat()?.hasAvatar"
[online]="isDirect() && presence.isOnline(chat()?.peer?.id)"
[size]="40"
/>
<span class="min-w-0">
<span class="block truncate font-semibold">{{ title() }}</span>
<span
class="block truncate text-xs"
[class]="typingText() ? 'text-brand-600 dark:text-brand-400' : 'text-muted'"
>
{{ typingText() ?? subtitle() }}
</span>
</span>
</a>
<a
[routerLink]="['/chats', chatId(), 'info']"
class="icon-btn"
aria-label="Chat info"
title="Chat info"
>
<svg lucideInfo class="size-5"></svg>
</a>
</header>
@if (store.error() && !store.messages().length) {
<div class="flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center">
<p class="text-sm text-muted">
{{
chat() && !chat()!.myRole
? 'Join this chat to read its messages.'
: "Messages couldn't be loaded."
}}
</p>
@if (!chat() || chat()!.myRole) {
<button type="button" class="btn-secondary" (click)="store.loadInitial()">
<svg lucideRotateCw class="size-4"></svg>Try again
</button>
}
</div>
} @else {
<app-message-list
[messages]="store.messages()"
[chat]="chat()"
[meId]="me()?.id"
[peerReadUpTo]="store.peerReadUpTo()"
[loading]="store.loading()"
[loadingOlder]="store.loadingOlder()"
[hasOlder]="store.hasOlder()"
(loadOlder)="store.loadOlder()"
(reply)="replyTo.set($event); editing.set(null)"
(edit)="editing.set($event); replyTo.set(null)"
(remove)="deleteMessage($event)"
(retry)="retry($event)"
(discard)="store.discard($event.id)"
(atBottom)="atBottom.set($event)"
/>
}
@if (chat(); as c) {
@if (!c.myRole) {
<div class="pb-safe border-t border-line bg-surface p-3 text-center">
<button
type="button"
class="btn-primary w-full sm:w-auto"
[disabled]="joining()"
(click)="join()"
>
<svg lucideUserPlus class="size-4"></svg> Join {{ c.type }}
</button>
</div>
} @else if (allowPost()) {
<app-composer
[chatId]="chatId()"
[placeholder]="c.type === 'channel' ? 'Broadcast a post' : 'Message'"
[(replyTo)]="replyTo"
[(editing)]="editing"
/>
} @else {
<div
class="pb-safe flex items-center justify-center gap-2 border-t border-line bg-surface p-3 text-sm text-muted"
>
<svg lucideMegaphone class="size-4"></svg> Only admins can post in this channel
<button
type="button"
class="ml-2 font-medium text-brand-600 hover:underline dark:text-brand-400"
(click)="toggleMute()"
>
{{ c.isMuted ? 'Unmute' : 'Mute' }}
</button>
</div>
}
}
@if (dragging()) {
<div
class="pointer-events-none absolute inset-2 z-20 flex items-center justify-center rounded-2xl border-2 border-dashed border-brand-500 bg-brand-50/90 text-brand-700 dark:bg-brand-950/90 dark:text-brand-200"
>
<span class="flex items-center gap-2 font-medium"
><svg lucidePaperclip class="size-5"></svg> Drop files to attach</span
>
</div>
}
</section>
<router-outlet />
`,
})
export class ConversationPage {
protected readonly store = inject(MessagesStore);
private readonly chats = inject(ChatsStore);
private readonly chatsApi = inject(ChatsApi);
private readonly usersApi = inject(UsersApi);
protected readonly presence = inject(PresenceStore);
private readonly typing = inject(TypingStore);
private readonly toast = inject(ToastService);
private readonly dialogs = inject(Dialogs);
private readonly router = inject(Router);
protected readonly me = inject(AuthService).user;
/** Route parameter (bound with withComponentInputBinding). */
readonly chatId = input.required<string>();
protected readonly chat = computed(() => this.chats.details()[this.chatId()]);
protected readonly isDirect = computed(() => this.chat()?.type === 'direct');
protected readonly title = computed(() => {
const chat = this.chat() ?? this.chats.items().find((c) => c.id === this.chatId());
return chat ? chatTitle(chat) : '';
});
protected readonly allowPost = computed(() => {
const chat = this.chat();
return !!chat && canPost(chat.type, chat.myRole);
});
protected readonly replyTo = signal<ChatMessage | null>(null);
protected readonly editing = signal<ChatMessage | null>(null);
protected readonly atBottom = signal(true);
protected readonly dragging = signal(false);
protected readonly joining = signal(false);
private readonly composer = viewChild(Composer);
/** The direct-chat partner's profile, for "last seen". */
private readonly peer = resource({
params: () => (this.isDirect() ? this.chat()?.peer?.id : undefined),
loader: ({ params }) => firstValueFrom(this.usersApi.get(params)),
});
protected readonly typingText = computed(() => {
const ids = this.typing.usersTyping(this.chatId());
if (!ids.length) return null;
if (this.isDirect()) return 'typing…';
return ids.length === 1 ? 'Someone is typing…' : `${ids.length} people are typing…`;
});
protected readonly subtitle = computed(() => {
const chat = this.chat();
if (!chat) return '';
if (chat.type === 'direct') {
const peerId = chat.peer?.id;
if (this.presence.isOnline(peerId)) return 'online';
const seen = (peerId && this.presence.lastSeenAt(peerId)) || this.peer.value()?.lastSeenAt;
return seen ? `last seen ${timeAgo(seen)}` : `@${chat.peer?.userName ?? ''}`;
}
const noun = chat.type === 'channel' ? 'subscriber' : 'member';
const handle = chat.publicHandle ? ` · @${chat.publicHandle}` : '';
return `${chat.memberCount} ${noun}${chat.memberCount === 1 ? '' : 's'}${handle}`;
});
constructor() {
effect(() => {
const chatId = this.chatId();
untracked(() => {
this.chats.activeChatId.set(chatId);
this.replyTo.set(null);
this.editing.set(null);
void this.store.open(chatId);
this.chats.loadChat(chatId).catch((error) => {
this.toast.error(toProblem(error).status === 404 ? 'This chat no longer exists.' : error);
void this.router.navigate(['/chats']);
});
});
});
effect(() => {
const peerId = this.chat()?.peer?.id;
if (peerId) untracked(() => this.presence.watch([peerId]));
});
// Mark messages read while the newest one is on screen and the tab is visible.
let readTimer: ReturnType<typeof setTimeout> | undefined;
const scheduleRead = () => {
clearTimeout(readTimer);
readTimer = setTimeout(() => {
if (this.atBottom() && document.visibilityState === 'visible' && this.chat()?.myRole) {
void this.store.markRead();
}
}, 400);
};
effect(() => {
this.store.lastConfirmed();
this.atBottom();
this.chat();
untracked(scheduleRead);
});
document.addEventListener('visibilitychange', scheduleRead);
this.chats.removed.pipe(takeUntilDestroyed()).subscribe((chatId) => {
if (chatId === this.chatId()) {
this.toast.info('You no longer have access to this chat.');
void this.router.navigate(['/chats']);
}
});
inject(DestroyRef).onDestroy(() => {
clearTimeout(readTimer);
document.removeEventListener('visibilitychange', scheduleRead);
if (this.chats.activeChatId() === this.chatId()) {
this.chats.activeChatId.set(null);
}
});
}
protected async deleteMessage(message: ChatMessage): Promise<void> {
const ok = await this.dialogs.confirm({
title: 'Delete message?',
message: 'It will be removed for everyone in this chat.',
confirmText: 'Delete',
danger: true,
});
if (ok) {
this.store.delete(message.id).catch((error) => this.toast.error(error));
}
}
protected retry(message: ChatMessage): void {
this.store.retry(message.id).catch((error) => this.toast.error(error));
}
protected async join(): Promise<void> {
this.joining.set(true);
try {
const chat = await firstValueFrom(this.chatsApi.join(this.chatId()));
this.chats.setDetails(chat);
await this.store.open(chat.id);
} catch (error) {
this.toast.error(error);
} finally {
this.joining.set(false);
}
}
protected async toggleMute(): Promise<void> {
const chat = this.chat();
if (!chat) return;
try {
await firstValueFrom(this.chatsApi.mute(chat.id, !chat.isMuted));
this.chats.setMuted(chat.id, !chat.isMuted);
} catch (error) {
this.toast.error(error);
}
}
protected onDragOver(event: DragEvent): void {
if (this.allowPost() && event.dataTransfer?.types.includes('Files')) {
event.preventDefault();
this.dragging.set(true);
}
}
protected onDrop(event: DragEvent): void {
this.dragging.set(false);
const files = Array.from(event.dataTransfer?.files ?? []);
if (files.length && this.allowPost()) {
event.preventDefault();
this.composer()?.addFiles(files);
}
}
}typingTextiscomputedfrom the typing store: "typing…" in a direct chat, "Someone is typing…" or "N people are typing…" in groups. It replaces the subtitle and colours it in the brand colour while it lasts.subtitleof a direct chat is "online", or "last seen …" from the live presence store, falling back to the profile'slastSeenAt, or the user name.- The header's avatar gets the online dot (
[online], inside the<app-avatar>element, again without highlighting), and an effect watches the partner.
Step 5. The connection banner
Why. When the connection is down, the screen silently stops updating. Users should know that what they see may be outdated.
Do. Complete the shell (new lines in green). It is now final:
angular-ts
import { ChangeDetectionStrategy, Component, computed, effect, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { NavigationEnd, Router, RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
import { filter, map } from 'rxjs';
import { AuthService } from '../../core/auth/auth.service';
import { RealtimeService } from '../../core/realtime/realtime.service';
import { ThemeService } from '../../core/ui/theme.service';
import { ChatsStore } from '../../state/chats.store';
import { Avatar } from '../../shared/ui/avatar';
import { ICONS } from '../../shared/ui/icons';
import { ChatListPane } from '../chat-list/chat-list-pane';
/**
* The signed-in layout.
* - Phone (< md): one pane at a time. /chats shows the list, a chat fills the screen, and a bottom
* tab bar switches between Chats, Discover and Settings (hidden inside a conversation).
* - Tablet (md–xl): nav rail + chat list + main pane.
* - Desktop (≥ xl): the same with a wider list; chat info docks on the right of the conversation.
*/
@Component({
selector: 'app-shell',
imports: [RouterOutlet, RouterLink, RouterLinkActive, ChatListPane, Avatar, ICONS],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="flex h-dvh overflow-hidden">
<!-- Nav rail (tablet and desktop) -->
<nav
class="hidden w-18 shrink-0 flex-col items-center gap-2 border-r border-line bg-surface py-4 md:flex"
aria-label="Main"
>
<a
routerLink="/chats"
class="mb-4 flex size-11 items-center justify-center rounded-xl bg-brand-600 text-white"
aria-label="Chatex home"
>
<svg lucideMessagesSquare class="size-6"></svg>
</a>
@for (item of nav; track item.path) {
<a
[routerLink]="item.path"
routerLinkActive="!bg-brand-50 !text-brand-700 dark:!bg-brand-950 dark:!text-brand-300"
class="relative flex size-11 items-center justify-center rounded-xl text-muted transition-colors hover:bg-subtle hover:text-fg"
[attr.aria-label]="item.label"
[title]="item.label"
>
@switch (item.icon) {
@case ('chats') {
<svg lucideMessagesSquare class="size-5"></svg>
}
@case ('discover') {
<svg lucideCompass class="size-5"></svg>
}
@case ('settings') {
<svg lucideSettings class="size-5"></svg>
}
}
@if (item.icon === 'chats' && unread()) {
<span class="absolute -top-1 -right-1 badge bg-brand-600 text-white">{{
unreadLabel()
}}</span>
}
</a>
}
<div class="mt-auto flex flex-col items-center gap-2">
<button
type="button"
class="icon-btn"
(click)="toggleTheme()"
[attr.aria-label]="theme.isDark() ? 'Switch to light theme' : 'Switch to dark theme'"
[title]="theme.isDark() ? 'Light theme' : 'Dark theme'"
>
@if (theme.isDark()) {
<svg lucideSun class="size-5"></svg>
} @else {
<svg lucideMoon class="size-5"></svg>
}
</button>
@if (auth.user(); as me) {
<a
routerLink="/settings"
class="rounded-full"
[title]="me.displayName"
aria-label="Your profile"
>
<app-avatar
[id]="me.id"
[name]="me.displayName"
[hasAvatar]="me.hasAvatar"
[size]="36"
/>
</a>
}
</div>
</nav>
<!-- Chat list: always visible from md up; on phones only on /chats -->
<app-chat-list-pane
class="w-full shrink-0 flex-col border-r border-line bg-surface md:flex md:w-80 xl:w-96"
[class.hidden]="!onChatsRoot()"
[class.flex]="onChatsRoot()"
/>
<!-- Main pane -->
<main
class="min-w-0 flex-1 flex-col md:flex"
[class.hidden]="onChatsRoot()"
[class.flex]="!onChatsRoot()"
>
@if (
realtime.state() === 'reconnecting' ||
(realtime.state() === 'disconnected' && auth.isAuthenticated())
) {
<div
class="flex items-center justify-center gap-2 bg-amber-100 px-3 py-1.5 text-xs text-amber-900 dark:bg-amber-900/40 dark:text-amber-200"
role="status"
>
<svg lucideWifiOff class="size-3.5"></svg>
Connecting… live updates are paused
</div>
}
<div class="flex min-h-0 flex-1 flex-col">
<router-outlet />
</div>
</main>
</div>
<!-- Bottom tab bar (phones), hidden inside a conversation -->
@if (!inConversation()) {
<nav
class="pb-safe fixed inset-x-0 bottom-0 z-30 flex border-t border-line bg-surface/95 backdrop-blur md:hidden"
aria-label="Main"
>
@for (item of nav; track item.path) {
<a
[routerLink]="item.path"
routerLinkActive="!text-brand-600 dark:!text-brand-400"
[routerLinkActiveOptions]="{
exact: item.path !== '/settings' && item.path !== '/discover',
}"
class="relative flex min-h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] text-muted"
>
@switch (item.icon) {
@case ('chats') {
<svg lucideMessagesSquare class="size-5"></svg>
}
@case ('discover') {
<svg lucideCompass class="size-5"></svg>
}
@case ('settings') {
<svg lucideSettings class="size-5"></svg>
}
}
{{ item.label }}
@if (item.icon === 'chats' && unread()) {
<span class="absolute top-1.5 left-1/2 ml-1.5 badge bg-brand-600 text-white">{{
unreadLabel()
}}</span>
}
</a>
}
</nav>
}
`,
})
export class Shell {
protected readonly auth = inject(AuthService);
protected readonly realtime = inject(RealtimeService);
protected readonly theme = inject(ThemeService);
private readonly chats = inject(ChatsStore);
private readonly router = inject(Router);
protected readonly nav = [
{ path: '/chats', label: 'Chats', icon: 'chats' },
{ path: '/discover', label: 'Discover', icon: 'discover' },
{ path: '/settings', label: 'Settings', icon: 'settings' },
] as const;
private readonly url = toSignal(
this.router.events.pipe(
filter((e) => e instanceof NavigationEnd),
map(() => this.router.url),
),
{ initialValue: this.router.url },
);
private readonly path = computed(() => this.url().split(/[?#]/)[0]);
protected readonly onChatsRoot = computed(() => this.path() === '/chats');
protected readonly inConversation = computed(() => /^\/chats\/[^/]+/.test(this.path()));
protected readonly unread = this.chats.totalUnread;
protected readonly unreadLabel = computed(() =>
this.unread() > 99 ? '99+' : String(this.unread()),
);
constructor() {
void this.chats.loadFirst().catch(() => undefined);
effect(() => {
const count = this.unread();
document.title = count ? `(${count}) Chatex` : 'Chatex';
});
}
protected toggleTheme(): void {
this.theme.set(this.theme.isDark() ? 'light' : 'dark');
}
}The banner "Connecting… live updates are paused" appears above the main pane while the state is reconnecting, or disconnected while the user is signed in. Injecting RealtimeService in the shell also guarantees that the service exists — and connects — as soon as the signed-in layout appears.
Check
powershell
npm test -- --watch=false Test Files 8 passed (8)
Tests 49 passed (49)Start the API and the client; sign in as Alice and as Bob in two windows with a direct chat between them.
- In the Network tab (filter "hubs"),
POST /hubs/chat/negotiate?negotiateVersion=1answers200, and a WebSocket connection to/hubs/chatstays open. - Alice's list shows a green dot on Bob's avatar, and the header of their chat says "online". Close Bob's window: after the grace period of topic 14 the dot disappears and the header says "last seen just now".
- Type in Bob's composer: Alice sees "typing…" in the list row and the header; it disappears when Bob sends the message, or about five seconds after he stops.
- Stop the API: the amber banner "Connecting… live updates are paused" appears in Alice's window. Send a message as Bob after starting the API again, before Alice's client has reconnected: once it reconnects, the banner disappears and the message appears — fetched with
GET /api/chats/…/messages?after=…&limit=100, visible in the Network tab.