English
The composer
Step 1. The message box
Why. The composer is the busiest piece of the screen. It sends text, shows the message being replied to or edited, attaches files, grows with the text up to a limit, and behaves like the messengers people know: Enter sends, Shift+Enter starts a new line, Esc cancels a reply or an edit — except on phones, where the on-screen keyboard's Enter key must make a new line.
Attachments are uploaded as soon as they are picked, not when the message is sent: that is the design of topic 11. By the time the user has typed the caption, the files are on the server, and sending is a small JSON request with their ids. The composer must therefore track every upload: its progress, its result or its error, and whether it is still running when the user presses "Send".
The "typing…" notification that the composer sends to the other members comes with the realtime client in topic 20.
Do. Create the composer:
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 { 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 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);
}
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([]);
}
}The state:
replyToandeditingaremodel()inputs: the conversation page binds them two-way ([(replyTo)]="replyTo"), so a "Reply" in the message list sets the page's signal, the composer sees it, and when the composer finishes or cancels, it sets the signal back tonullfor the page.canSubmitiscomputed: in edit mode there must be new, non-empty text; otherwise no upload may still be running, and there must be text or at least one finished upload. The send button binds[disabled]to it.MAX_ATTACHMENTSandMAX_BODYrepeat the server's limits (topic 11) to fail fast;isAllowedFilerepeats the allow-list of media types and, for files the browser does not know a type for, checks the extension. The server still decides.
The effects:
- Starting an edit puts the message's text into the box and focuses it; a reply just focuses it. Both use
untrackedso that onlyeditingorreplyTotrigger the effect, not the signals that the effect writes. - Auto-resize. After each text change,
afterNextRendermeasures the text area'sscrollHeightand sets its height;max-h-40limits the growth, then the area scrolls. TheInjectoris passed becauseafterNextRenderis called inside an effect, outside the constructor's injection context. - Switching chats resets the box and cancels running uploads. The same
Composerinstance stays on screen when the route changes from one chat to another — Angular reuses the component and only changes thechatIdinput — so this reset is necessary.
The actions:
onKeydownsends on Enter unless Shift is held, the user is composing text with an input method (isComposing, for example Japanese), or the device has a coarse pointer (a touch screen).addFiles(files)is public: the conversation page calls it for dropped files, the composer itself for picked and pasted ones. It enforces the limit of ten with a toast, rejects disallowed types with a toast, and starts an upload per file.startUpload(file)subscribes toAttachmentsApi.upload, which emits the request's events (topic 16):UploadProgressupdates the percentage,Responsestores theAttachmentDto, an error stores the message. Each subscription is kept in aMapby a local key, so that removing a chip cancels its upload (unsubscribeaborts the HTTP request).submit()in edit mode callsstore.edit; otherwise it collects the finished uploads, clears the box at once and callsstore.send— the store shows the message as pending.
Upload progress with the fetch backend
In Angular 22, HttpClient uses the browser's fetch API by default, and fetch reports no upload progress. With the default backend the progress bar of a chip therefore stays empty until the upload completes. If you need a moving bar, add withXhr() to provideHttpClient (an exercise of this topic).
Step 2. Testing a component
Why. The composer's rules are in its event handlers, so its tests render it and act like a user: type into the text area, press keys, add files. TestBed.createComponent renders a component into jsdom; the dependencies are replaced with mocks.
Do. Create the spec. The test of the typing notification joins it in topic 20.
ts
import { TestBed } from '@angular/core/testing';
import { NEVER } from 'rxjs';
import { AttachmentsApi } from '../../core/api/chatex-api';
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>;
async function create() {
store = { send: vi.fn(async () => undefined), edit: vi.fn(async () => undefined) };
toast = { error: vi.fn() };
upload = vi.fn(() => NEVER);
TestBed.configureTestingModule({
imports: [Composer],
providers: [
{ provide: MessagesStore, useValue: store },
{ provide: AttachmentsApi, useValue: { upload } },
{ provide: ToastService, useValue: toast },
],
});
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(`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);
});
});imports: [Composer]— a standalone component is imported into the testing module like into another component.fixture.componentRef.setInput('chatId', 'chat-1')sets the required input, as a parent template would.await fixture.whenStable()waits until Angular has rendered and run the pending effects.typeandpressdispatch real DOM events (input,keydown), so the template's event bindings run as in a browser.event.defaultPreventedshows whether the composer took over the Enter key.upload = vi.fn(() => NEVER)—NEVERis an Observable that never emits, so the uploads stay "running" and the test can count the calls.
Check
powershell
npm test -- --watch=false Test Files 8 passed (8)
Tests 38 passed (38)