English
New chats and discovery
Step 1. User search
Why. Starting a direct chat, adding members to a group (here and in topic 21) — all need "find a person by name". The API's GET /api/users?query= (topic 12) needs at least two characters. Sending a request on every keystroke would flood the API and, worse, show results out of order: the answer for "al" may arrive after the answer for "alice". RxJS solves both problems in four operators.
Do. Create the reusable search component:
angular-ts
import {
ChangeDetectionStrategy,
Component,
DestroyRef,
computed,
inject,
input,
model,
output,
signal,
} from '@angular/core';
import { Subject, debounceTime, distinctUntilChanged, switchMap, of, catchError, map } from 'rxjs';
import { UsersApi } from '../../core/api/chatex-api';
import { UserSummaryDto } from '../../core/api/models';
import { AuthService } from '../../core/auth/auth.service';
import { Avatar } from './avatar';
import { ICONS } from './icons';
/**
* Searches users by name. In `multiple` mode it keeps a selection (shown as removable chips);
* otherwise clicking a result emits `picked`.
*/
@Component({
selector: 'app-user-search',
imports: [Avatar, ICONS],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
@if (multiple() && selected().length) {
<ul class="mb-3 flex flex-wrap gap-2" aria-label="Selected users">
@for (user of selected(); track user.id) {
<li
class="flex items-center gap-1.5 rounded-full bg-brand-50 py-1 pr-1 pl-1 text-sm text-brand-800 dark:bg-brand-950 dark:text-brand-200"
>
<app-avatar
[id]="user.id"
[name]="user.displayName"
[hasAvatar]="user.hasAvatar"
[size]="22"
/>
<span class="max-w-32 truncate">{{ user.displayName }}</span>
<button
type="button"
class="rounded-full p-0.5 hover:bg-brand-100 dark:hover:bg-brand-900"
[attr.aria-label]="'Remove ' + user.displayName"
(click)="toggle(user)"
>
<svg lucideX class="size-3.5"></svg>
</button>
</li>
}
</ul>
}
<label class="relative block">
<span class="sr-only">Search people</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 pl-9"
type="search"
placeholder="Search by name or @username"
autocomplete="off"
[value]="query()"
(input)="onQuery($any($event.target).value)"
/>
</label>
<ul
class="mt-2 max-h-72 overflow-y-auto"
role="listbox"
[attr.aria-multiselectable]="multiple()"
>
@if (searching()) {
<li class="flex justify-center py-4 text-muted">
<svg lucideLoaderCircle class="size-5 animate-spin"></svg>
</li>
} @else if (query().trim().length >= 2 && !results().length) {
<li class="py-4 text-center text-sm text-muted">No people found</li>
}
@for (user of results(); track user.id) {
<li role="option" [attr.aria-selected]="isSelected(user.id)">
<button
type="button"
class="flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left hover:bg-subtle"
(click)="multiple() ? toggle(user) : picked.emit(user)"
>
<app-avatar
[id]="user.id"
[name]="user.displayName"
[hasAvatar]="user.hasAvatar"
[size]="36"
/>
<span class="min-w-0 flex-1">
<span class="block truncate text-sm font-medium">{{ user.displayName }}</span>
<span class="block truncate text-xs text-muted">@{{ user.userName }}</span>
</span>
@if (multiple()) {
<span
class="flex size-5 items-center justify-center rounded-full border"
[class]="
isSelected(user.id) ? 'border-brand-600 bg-brand-600 text-white' : 'border-line'
"
>
@if (isSelected(user.id)) {
<svg lucideCheck class="size-3.5"></svg>
}
</span>
}
</button>
</li>
}
</ul>
`,
})
export class UserSearch {
private readonly api = inject(UsersApi);
private readonly me = inject(AuthService).user;
private readonly queries = new Subject<string>();
readonly multiple = input(false);
/** Users to leave out of the results (e.g. existing members). */
readonly exclude = input<readonly string[]>([]);
readonly selected = model<UserSummaryDto[]>([]);
readonly picked = output<UserSummaryDto>();
protected readonly query = signal('');
protected readonly searching = signal(false);
private readonly found = signal<UserSummaryDto[]>([]);
protected readonly results = computed(() => {
const hidden = new Set([...this.exclude(), this.me()?.id ?? '']);
return this.found().filter((u) => !hidden.has(u.id));
});
constructor() {
const subscription = this.queries
.pipe(
map((q) => q.trim()),
debounceTime(250),
distinctUntilChanged(),
switchMap((q) => {
if (q.length < 2) {
this.searching.set(false);
return of([]);
}
this.searching.set(true);
return this.api.search(q).pipe(catchError(() => of([])));
}),
)
.subscribe((users) => {
this.searching.set(false);
this.found.set(users);
});
inject(DestroyRef).onDestroy(() => subscription.unsubscribe());
}
protected onQuery(value: string): void {
this.query.set(value);
this.queries.next(value);
}
protected isSelected(id: string): boolean {
return this.selected().some((u) => u.id === id);
}
protected toggle(user: UserSummaryDto): void {
this.selected.update((list) =>
list.some((u) => u.id === user.id) ? list.filter((u) => u.id !== user.id) : [...list, user],
);
}
}queriesis aSubject<string>: every keystroke pushes the input's value into it (onQuery).- The pipeline —
maptrims the text;debounceTime(250)waits until the user pauses for 250 ms;distinctUntilChanged()drops a query equal to the previous one (typing a letter and deleting it);switchMapstarts the HTTP request and cancels the previous one if a new query arrives first. Results can therefore never arrive out of order.catchError(() => of([]))turns a failed search into an empty result instead of ending the stream. inject(DestroyRef).onDestroy(...)unsubscribes when the component is destroyed — the counterpart ofIDisposable. Without it, the subscription would keep the component alive.- Two modes. With
multiplefalse a click on a user emitspicked, an output (output<UserSummaryDto>()): the parent listens with(picked)="startDirect($event)". Withmultipletrue a click toggles the user inselected, and the selection shows as removable chips. selected = model<UserSummaryDto[]>([])is a two-way input: the parent binds it with the "banana in a box" syntax[(selected)]="members", and changes made inside the component flow back into the parent's signal.resultshides the signed-in user and the ids inexclude(existing members, topic 21) with acomputedover the found users.$any($event.target).valuereads the input's value;$anytells the template compiler not to type-check$event.target, which TypeScript knows only as anEventTarget.- Accessibility. The list is a
listboxwithoptions andaria-selected; the search field has a visually hidden label (sr-only).
Step 2. The new-chat dialog
Why. One dialog creates all three kinds of chat (topic 3): a direct chat with one person, a group where everyone writes, a channel where only admins post. Groups and channels have a title, an optional description, an optional public handle that makes them discoverable, and initial members.
Do. Create the dialog:
angular-ts
import { DialogRef } from '@angular/cdk/dialog';
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import { ChatsApi } from '../../core/api/chatex-api';
import { UserSummaryDto } from '../../core/api/models';
import { fieldErrors, problemMessage, toProblem } from '../../core/api/problem';
import { ChatsStore } from '../../state/chats.store';
import { ICONS } from '../../shared/ui/icons';
import { UserSearch } from '../../shared/ui/user-search';
type Tab = 'direct' | 'group' | 'channel';
/** Public handles: 5–32 characters, a letter first, then letters, digits or _. */
export const HANDLE_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]{4,31}$/;
@Component({
selector: 'app-new-chat-dialog',
imports: [ReactiveFormsModule, UserSearch, ICONS],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="flex dialog-card flex-col" role="dialog" aria-labelledby="new-chat-title">
<header class="flex items-center gap-2 border-b border-line px-5 py-3">
<h2 id="new-chat-title" class="flex-1 text-lg font-semibold">New chat</h2>
<button type="button" class="-mr-2 icon-btn" aria-label="Close" (click)="ref.close()">
<svg lucideX class="size-5"></svg>
</button>
</header>
<div class="px-5 pt-4">
<div class="grid grid-cols-3 gap-1 rounded-xl bg-subtle p-1" role="tablist">
@for (t of tabs; track t.id) {
<button
type="button"
role="tab"
class="flex items-center justify-center gap-1.5 rounded-lg px-2 py-2 text-sm font-medium transition-colors"
[class]="tab() === t.id ? 'bg-surface text-fg shadow-sm' : 'text-muted hover:text-fg'"
[attr.aria-selected]="tab() === t.id"
(click)="tab.set(t.id)"
>
@switch (t.id) {
@case ('direct') {
<svg lucideUser class="size-4"></svg>
}
@case ('group') {
<svg lucideUsers class="size-4"></svg>
}
@case ('channel') {
<svg lucideMegaphone class="size-4"></svg>
}
}
{{ t.label }}
</button>
}
</div>
</div>
<div class="px-5 py-4">
@if (tab() === 'direct') {
@if (error()) {
<p
class="mb-3 rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700 dark:bg-red-950 dark:text-red-300"
role="alert"
>
{{ error() }}
</p>
}
<p class="mb-3 text-sm text-muted">Find someone to message directly.</p>
<app-user-search (picked)="startDirect($event)" />
} @else {
<form [formGroup]="form" (ngSubmit)="create()" class="space-y-4" novalidate>
@if (error()) {
<p
class="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700 dark:bg-red-950 dark:text-red-300"
role="alert"
>
{{ error() }}
</p>
}
<div>
<label class="label" for="chat-title">{{
tab() === 'channel' ? 'Channel name' : 'Group name'
}}</label>
<input
id="chat-title"
class="input"
formControlName="title"
maxlength="128"
[class.input-invalid]="titleInvalid()"
/>
@if (titleInvalid()) {
<p class="field-error">A name is required.</p>
}
</div>
<div>
<label class="label" for="chat-description"
>Description <span class="font-normal text-muted">(optional)</span></label
>
<textarea
id="chat-description"
class="input min-h-20"
formControlName="description"
maxlength="1000"
></textarea>
</div>
<div>
<label class="label" for="chat-handle"
>Public handle <span class="font-normal text-muted">(optional)</span></label
>
<div class="relative">
<span
class="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-muted"
>@</span
>
<input
id="chat-handle"
class="input pl-7"
formControlName="publicHandle"
autocapitalize="none"
maxlength="32"
[class.input-invalid]="handleError()"
/>
</div>
@if (handleError(); as m) {
<p class="field-error">{{ m }}</p>
} @else {
<p class="mt-1 text-xs text-muted">
With a handle the {{ tab() }} is public: anyone can find and join it.
</p>
}
</div>
<div>
<span class="label">Add members</span>
<app-user-search [multiple]="true" [(selected)]="members" />
</div>
<div class="flex flex-col-reverse gap-2 pt-2 sm:flex-row sm:justify-end">
<button type="button" class="btn-secondary" (click)="ref.close()">Cancel</button>
<button type="submit" class="btn-primary" [disabled]="busy()">
@if (busy()) {
<svg lucideLoaderCircle class="size-4 animate-spin"></svg>
}
Create {{ tab() }}
</button>
</div>
</form>
}
</div>
</div>
`,
})
export class NewChatDialog {
protected readonly ref = inject(DialogRef);
private readonly api = inject(ChatsApi);
private readonly store = inject(ChatsStore);
private readonly router = inject(Router);
protected readonly tabs: { id: Tab; label: string }[] = [
{ id: 'direct', label: 'Direct' },
{ id: 'group', label: 'Group' },
{ id: 'channel', label: 'Channel' },
];
protected readonly tab = signal<Tab>('direct');
protected readonly busy = signal(false);
protected readonly error = signal<string | null>(null);
private readonly serverHandleError = signal<string | null>(null);
protected readonly members = signal<UserSummaryDto[]>([]);
protected readonly form = inject(NonNullableFormBuilder).group({
title: ['', [Validators.required, Validators.maxLength(128)]],
description: ['', Validators.maxLength(1000)],
publicHandle: ['', Validators.pattern(HANDLE_PATTERN)],
});
constructor() {
this.form.controls.publicHandle.valueChanges.subscribe(() => this.serverHandleError.set(null));
}
protected titleInvalid(): boolean {
const c = this.form.controls.title;
return c.invalid && c.touched;
}
protected handleError(): string | null {
const c = this.form.controls.publicHandle;
if (this.serverHandleError()) {
return this.serverHandleError();
}
return c.invalid && c.touched
? '5–32 characters: letters, digits and _, starting with a letter.'
: null;
}
protected async startDirect(user: UserSummaryDto): Promise<void> {
try {
const chat = await firstValueFrom(this.api.direct(user.id));
this.store.setDetails(chat);
this.ref.close();
await this.router.navigate(['/chats', chat.id]);
} catch (error) {
this.error.set(problemMessage(error));
}
}
protected async create(): Promise<void> {
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
this.busy.set(true);
this.error.set(null);
const value = this.form.getRawValue();
try {
const chat = await firstValueFrom(
this.api.create({
type: this.tab() === 'channel' ? 'channel' : 'group',
title: value.title.trim(),
description: value.description.trim() || null,
publicHandle: value.publicHandle.trim() || null,
memberIds: this.members().map((m) => m.id),
}),
);
this.store.setDetails(chat);
this.ref.close();
await this.router.navigate(['/chats', chat.id]);
} catch (error) {
const problem = toProblem(error);
if (problem.code === 'handle_taken') {
this.serverHandleError.set(problemMessage(error));
} else {
this.serverHandleError.set(fieldErrors(error, 'publicHandle')[0] ?? null);
this.error.set(problemMessage(error));
}
} finally {
this.busy.set(false);
}
}
}- Tabs are three buttons with
role="tab"andaria-selected; thetabsignal decides which part of the template is shown. - Direct. Picking a user calls
POST /api/chats/direct. The API returns the existing direct chat if there is one (topic 10), so the dialog never creates duplicates.store.setDetails(chat)puts the chat into the list at once, then the dialog closes and navigates to it. - Group or channel. A Reactive Form with the server's limits;
HANDLE_PATTERNmirrors the handle rule (5–32 characters, a letter first) and is exported for the chat info panel of topic 21. Empty optional fields are sent asnull. - Errors.
handle_takenappears under the handle field; any other field error of the handle too; everything else above the form. inject(DialogRef)gives the dialog its own handle, whichref.close()uses. The dialog has noDialogsparameter: whoever opens it (the chat list, the no-chat page) callsdialogs.open(NewChatDialog).
Step 3. The discover page
Why. A group or channel with a public handle can be found and joined by anyone (topic 10). The discover page searches them with GET /api/chats/search, shows a preview with the member count and joins with one click.
Do. Create the page:
angular-ts
import { ChangeDetectionStrategy, Component, DestroyRef, inject, signal } from '@angular/core';
import { Router } from '@angular/router';
import {
Subject,
catchError,
debounceTime,
distinctUntilChanged,
firstValueFrom,
map,
of,
switchMap,
} from 'rxjs';
import { ChatsApi } from '../../core/api/chatex-api';
import { ChatDto, ChatSummaryDto } from '../../core/api/models';
import { ToastService } from '../../core/ui/toast.service';
import { ChatsStore } from '../../state/chats.store';
import { Avatar } from '../../shared/ui/avatar';
import { ICONS } from '../../shared/ui/icons';
/** Search public groups and channels, preview one and join it. */
@Component({
selector: 'app-discover-page',
imports: [Avatar, ICONS],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: 'flex min-h-0 flex-1 flex-col overflow-y-auto' },
template: `
<div class="pt-safe mx-auto w-full max-w-3xl px-4 pb-24 md:px-8 md:pb-10">
<header class="py-6">
<h1 class="text-2xl font-bold tracking-tight">Discover</h1>
<p class="mt-1 text-sm text-muted">Find public groups and channels by name or handle.</p>
</header>
<label class="relative block">
<span class="sr-only">Search public chats</span>
<svg
lucideSearch
class="pointer-events-none absolute top-1/2 left-3 size-5 -translate-y-1/2 text-muted"
></svg>
<input
class="input py-3 pl-11"
type="search"
placeholder="Search public chats"
(input)="search($any($event.target).value)"
/>
</label>
<div class="mt-6 grid gap-6 lg:grid-cols-[1fr_20rem]">
<ul class="space-y-2">
@if (searching()) {
<li class="flex justify-center py-8 text-muted">
<svg lucideLoaderCircle class="size-6 animate-spin"></svg>
</li>
} @else if (searched() && !results().length) {
<li class="card px-4 py-10 text-center text-sm text-muted">
Nothing found. Try another name.
</li>
} @else if (!searched()) {
<li class="flex flex-col items-center gap-3 card px-4 py-12 text-center">
<svg lucideCompass class="size-10 text-brand-500"></svg>
<p class="text-sm text-muted">Type at least 2 characters to search.</p>
</li>
}
@for (chat of results(); track chat.id) {
<li>
<button
type="button"
class="flex w-full items-center gap-3 card p-3 text-left transition-colors hover:border-brand-300 dark:hover:border-brand-700"
[class.!border-brand-500]="preview()?.id === chat.id"
(click)="select(chat)"
>
<app-avatar
kind="chat"
[id]="chat.id"
[name]="chat.title ?? ''"
[hasAvatar]="chat.hasAvatar"
[size]="48"
/>
<span class="min-w-0 flex-1">
<span class="flex items-center gap-1.5 font-medium">
@if (chat.type === 'channel') {
<svg lucideMegaphone class="size-4 text-muted"></svg>
} @else {
<svg lucideUsers class="size-4 text-muted"></svg>
}
<span class="truncate">{{ chat.title }}</span>
</span>
<span class="block truncate text-sm text-muted"
>@{{ chat.publicHandle }}
@if (chat.description) {
· {{ chat.description }}
}
</span>
</span>
</button>
</li>
}
</ul>
@if (preview(); as c) {
<aside class="h-fit card p-5 text-center lg:sticky lg:top-6">
<app-avatar
class="mx-auto"
kind="chat"
[id]="c.id"
[name]="c.title ?? ''"
[hasAvatar]="c.hasAvatar"
[size]="80"
/>
<h2 class="mt-3 text-lg font-semibold">{{ c.title }}</h2>
<p class="text-sm text-muted">
@{{ c.publicHandle }} · {{ c.memberCount }}
{{ c.type === 'channel' ? 'subscribers' : 'members' }}
</p>
@if (c.description) {
<p class="mt-3 text-sm whitespace-pre-wrap">{{ c.description }}</p>
}
<button
type="button"
class="mt-5 btn-primary w-full"
[disabled]="busy()"
(click)="joinOrOpen(c)"
>
@if (busy()) {
<svg lucideLoaderCircle class="size-4 animate-spin"></svg>
}
{{ c.myRole ? 'Open' : 'Join ' + c.type }}
</button>
</aside>
}
</div>
</div>
`,
})
export class DiscoverPage {
private readonly api = inject(ChatsApi);
private readonly chats = inject(ChatsStore);
private readonly router = inject(Router);
private readonly toast = inject(ToastService);
private readonly queries = new Subject<string>();
protected readonly results = signal<ChatSummaryDto[]>([]);
protected readonly searching = signal(false);
protected readonly searched = signal(false);
protected readonly preview = signal<ChatDto | null>(null);
protected readonly busy = signal(false);
constructor() {
const subscription = this.queries
.pipe(
map((q) => q.trim()),
debounceTime(300),
distinctUntilChanged(),
switchMap((q) => {
if (q.length < 2) {
this.searched.set(false);
this.searching.set(false);
return of([]);
}
this.searching.set(true);
return this.api.search(q).pipe(
map((list) => {
this.searched.set(true);
return list;
}),
catchError((error) => {
this.toast.error(error);
return of([]);
}),
);
}),
)
.subscribe((list) => {
this.searching.set(false);
this.results.set(list);
});
inject(DestroyRef).onDestroy(() => subscription.unsubscribe());
}
protected search(value: string): void {
this.queries.next(value);
}
protected async select(chat: ChatSummaryDto): Promise<void> {
try {
const details = await firstValueFrom(this.api.get(chat.id));
this.preview.set(details);
// On narrow screens the preview sits below the list; bring it into view.
if (window.innerWidth < 1024) {
setTimeout(() =>
document.querySelector('aside.card')?.scrollIntoView({ behavior: 'smooth' }),
);
}
} catch (error) {
this.toast.error(error);
}
}
protected async joinOrOpen(chat: ChatDto): Promise<void> {
if (chat.myRole) {
this.chats.setDetails(chat);
await this.router.navigate(['/chats', chat.id]);
return;
}
this.busy.set(true);
try {
const joined = await firstValueFrom(this.api.join(chat.id));
this.chats.setDetails(joined);
this.toast.success(`Joined ${joined.title ?? 'chat'}`);
await this.router.navigate(['/chats', joined.id]);
} catch (error) {
this.toast.error(error);
} finally {
this.busy.set(false);
}
}
}- The search pipeline is the one of the user search, with 300 ms of debounce and a toast for errors.
searcheddistinguishes "nothing found" from "nothing searched yet". select(chat)loads the fullChatDto— the search result has no member count and no role. On narrow screens the preview sits below the list, so the page scrolls it into view.joinOrOpen(chat)opens a chat the user is already a member of (myRoleset), otherwise joins it withPOST /api/chats/{id}/join, adds it to the store withsetDetails, shows a success toast and navigates to it.[class.!border-brand-500]— a class binding with Tailwind's important modifier highlights the selected result.
Check
npm run build succeeds. The dialog and the page become reachable in the next chapter.