English
The conversation page
Step 1. The page
Why. The page connects the parts: it reads :chatId from the route, provides and opens the MessagesStore, loads the chat's details into ChatsStore, shows the header, the list and — depending on the user's role — the composer, a "Join" button or a "Only admins can post" bar, and decides when messages count as read.
Presence ("online", "last seen") and typing indicators in the header come in topic 20, the profile dialog in topic 21; three lines differ until then (yellow).
Do. Create 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 { 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"
[size]="40"
/>
<span class="min-w-0">
<span class="block truncate font-semibold">{{ title() }}</span>
<span class="block truncate text-xs">
{{ 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);
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 subtitle = computed(() => {
const chat = this.chat();
if (!chat) return '';
if (chat.type === 'direct') {
const seen = 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']);
});
});
});
// 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);
}
}
}The data:
providers: [MessagesStore]creates the page's own store (chapter 1), injected by the page and by theComposerinside it.chatId = input.required<string>()receives the route parameter throughwithComponentInputBinding()(topic 16). When the user clicks another chat, the router reuses the page and only changes the input.chatiscomputedfromChatsStore.details, so every update of the details — a rename, a new avatar, a role change — appears in the header at once.titlefalls back to the list row while the details are loading.allowPostusescanPostfrommodels.ts: members of groups and direct chats, and owners and admins of channels.peeris aresourcethat loads the direct-chat partner's profile for "last seen".paramsreturnsundefinedfor groups and channels, so nothing is loaded for them.
The effects:
- Opening a chat. An effect reads only
chatId(); everything insideuntracked(...)runs without becoming a dependency. It marks the chat as active inChatsStore(its new messages will not count as unread — topic 20), clears reply and edit, opens the store and loads the details. If the chat cannot be loaded — it was deleted, or the user lost access — a toast explains it and the page goes back to/chats. - Marking as read. Another effect watches the newest confirmed message,
atBottomfrom the list and the chat. After 400 ms of calm it callsstore.markRead()— but only if the newest message is in view, the browser tab is visible and the user is a member. Thevisibilitychangelistener re-checks when the user returns to the tab: a message that arrived in a background tab stays unread until the user actually sees it. - Losing access.
chats.removedemits when the chat is deleted or the user is removed (topic 20 sends these events);takeUntilDestroyed()ends the subscription with the page. - Cleaning up.
DestroyRef.onDestroyclears the timer, removes the document listener and unsets the active chat.
The actions:
deleteMessageasks with the confirmation dialog of topic 17, then deletes.retryresends a failed message; errors become toasts.joinis offered when the user previews a public chat without being a member (myRoleis null — the API lets anybody read a public chat, topic 10). After joining, the store is opened again so the composer appears.toggleMutelets channel subscribers mute or unmute the channel.- Drag and drop.
dragoverchecks that files are dragged (dataTransfer.typescontains'Files') and that the user may post, and callspreventDefault(), which tells the browser that a drop is allowed here. A dashed overlay shows the drop target, anddrophands the files to the composer throughviewChild(Composer). <router-outlet />after the section is the place for the chat info panel (topic 21), a child route of the conversation. Until that route exists, the header and the info button lead tochats/…/info, which no route matches, so the wildcard route returns to/chats.
Step 2. The route
Do. Add the conversation route:
ts
import { Routes } from '@angular/router';
import { authGuard, guestGuard } from './core/auth/guards';
export const routes: Routes = [
{
path: 'login',
canActivate: [guestGuard],
title: 'Sign in · Chatex',
loadComponent: () => import('./features/auth/login.page').then((m) => m.LoginPage),
},
{
path: 'register',
canActivate: [guestGuard],
title: 'Create account · Chatex',
loadComponent: () => import('./features/auth/register.page').then((m) => m.RegisterPage),
},
{
path: '',
canActivate: [authGuard],
loadComponent: () => import('./features/shell/shell').then((m) => m.Shell),
children: [
{ path: '', pathMatch: 'full', redirectTo: 'chats' },
{
path: 'chats',
loadComponent: () => import('./features/shell/no-chat.page').then((m) => m.NoChatPage),
},
{
path: 'chats/:chatId',
loadComponent: () =>
import('./features/conversation/conversation.page').then((m) => m.ConversationPage),
},
{
path: 'discover',
loadComponent: () =>
import('./features/discover/discover.page').then((m) => m.DiscoverPage),
},
],
},
{ path: '**', redirectTo: 'chats' },
];The route chats/:chatId stands after chats: both are tried in order, and chats matches only the exact path. In the shell, inConversation (topic 17) now becomes true on these URLs and hides the bottom tab bar on phones.
Check
Start the API and the client, sign in as Alice in one window and as Bob in a private window.
- Click "Course team" in Alice's list: the URL becomes
/chats/…, the header shows the title and "2 members · @course_team", and the empty list says "No messages yet. Say hello!". - Type "Hello from topic 19" and press Enter: the message appears at once on the right, the list row shows "You: Hello from topic 19" and moves to the top. Press Shift+Enter in the box: a new line, nothing sent.
- Send a message as Bob. Alice does not see it until she opens the chat again: the client still has no realtime connection. Topic 20 changes that.
- As Alice, open the "⋮" menu of Bob's message: Reply shows the quote bar above the box; send the reply, then click the quote in the bubble: the original is highlighted. Edit your own message: the text appears in the box and the bubble gets "edited" after saving. Delete asks for confirmation and leaves "Message deleted".
- Click the paperclip and pick a text file, or drop one onto the conversation: a chip appears, shows the size when the upload is done, and the send button turns active. Send it; the file chip in the bubble downloads it. Try a
.exe: the toast says its type can't be sent. - Send enough messages to fill more than a screen (or use a chat with more than 50 messages), reload, and scroll up: older messages load without the view jumping.
- Stop the API (Ctrl+C) and send a message: it shows a warning icon and "Not sent. Retry Delete". Start the API again and click Retry.