English
Avatars and pipes
Step 1. Pipes
Why. The chat list shows "14:05" for a message of today, "Yesterday", a weekday within the last week and a short date for older ones; the conversation shows day separators and clock times; attachments show sizes like "1.4 MB". A pipe formats a value inside a template: the template writes the value, a vertical bar and the pipe's name, like a filter. The formatting functions themselves are exported too, so that code and tests can call them.
Do. Create the pipes:
ts
import { Pipe, PipeTransform } from '@angular/core';
const DAY_MS = 86_400_000;
function startOfDay(date: Date): number {
return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
}
/** "14:05" today, "Yesterday", a weekday within a week, otherwise a short date. For chat lists. */
export function shortWhen(iso: string, now = new Date()): string {
const date = new Date(iso);
const days = Math.round((startOfDay(now) - startOfDay(date)) / DAY_MS);
if (days <= 0) {
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
if (days === 1) {
return 'Yesterday';
}
if (days < 7) {
return date.toLocaleDateString([], { weekday: 'short' });
}
return date.toLocaleDateString([], {
day: 'numeric',
month: 'short',
year: date.getFullYear() === now.getFullYear() ? undefined : 'numeric',
});
}
/** "Today", "Yesterday" or a full date. For the separators in the message list. */
export function dayLabel(iso: string, now = new Date()): string {
const date = new Date(iso);
const days = Math.round((startOfDay(now) - startOfDay(date)) / DAY_MS);
if (days === 0) {
return 'Today';
}
if (days === 1) {
return 'Yesterday';
}
return date.toLocaleDateString([], {
weekday: 'long',
day: 'numeric',
month: 'long',
year: date.getFullYear() === now.getFullYear() ? undefined : 'numeric',
});
}
/** "just now", "5 minutes ago", "yesterday", ... */
export function timeAgo(iso: string, now = Date.now()): string {
const seconds = Math.round((Date.parse(iso) - now) / 1000);
const format = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto' });
const units: [Intl.RelativeTimeFormatUnit, number][] = [
['year', 31_536_000],
['month', 2_592_000],
['week', 604_800],
['day', 86_400],
['hour', 3_600],
['minute', 60],
];
for (const [unit, size] of units) {
if (Math.abs(seconds) >= size) {
return format.format(Math.round(seconds / size), unit);
}
}
return 'just now';
}
export function fileSize(bytes: number): string {
if (bytes < 1024) {
return `${bytes} B`;
}
const units = ['KB', 'MB', 'GB'];
let value = bytes / 1024;
let unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
unit++;
}
return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;
}
@Pipe({ name: 'shortWhen' })
export class ShortWhenPipe implements PipeTransform {
transform(value: string | null | undefined): string {
return value ? shortWhen(value) : '';
}
}
@Pipe({ name: 'timeAgo' })
export class TimeAgoPipe implements PipeTransform {
transform(value: string | null | undefined): string {
return value ? timeAgo(value) : '';
}
}
@Pipe({ name: 'clock' })
export class ClockPipe implements PipeTransform {
transform(value: string | null | undefined): string {
return value
? new Date(value).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
: '';
}
}
@Pipe({ name: 'fileSize' })
export class FileSizePipe implements PipeTransform {
transform(value: number | null | undefined): string {
return value == null ? '' : fileSize(value);
}
}toLocaleTimeString([], { … })andIntl.RelativeTimeFormatformat in the browser's language and conventions — 24-hour clocks in Ukraine, AM/PM in the US — with no translation tables in the app.[]means "the user's default locale".- Days are counted between midnights (
startOfDay), not as 24-hour periods: a message from 23:50 is "Yesterday" at 00:10. @Pipe({ name: 'shortWhen' })withPipeTransformwraps a function as a pipe. Angular pipes are pure by default: Angular callstransformagain only when the input value changes, so a list of 100 chats does not re-format 100 dates on every render.timeAgo("5 minutes ago", "yesterday") is used for "last seen" in topics 19–21;fileSizeandFileSizePipefor attachments in topic 19.
Step 2. Protected images as blob URLs
Why. Avatars and attachments are served by the API only to users who may see them (topic 13): the requests need the bearer token. A plain <img src="/api/users/…/avatar"> cannot send it — the browser loads images by itself, without our interceptor and without an Authorization header. Putting the token into the URL would leak it into logs and the browser history.
The solution is to download the image with HttpClient, which goes through the interceptor, and give the <img> a blob URL: URL.createObjectURL(blob) returns a short-lived URL such as blob:http://localhost:4200/0d3f… that points to data in the page's memory. The production Content-Security-Policy allows exactly this with img-src 'self' blob: data: (topic 24).
Do. Create the service:
ts
import { HttpClient } from '@angular/common/http';
import { Injectable, effect, inject, signal } from '@angular/core';
import { firstValueFrom } from 'rxjs';
import { AuthService } from '../auth/auth.service';
/**
* Avatars and attachments need the bearer token, so `<img src="/api/...">` can't load them.
* This fetches them with HttpClient (through the auth interceptor) and hands out object URLs,
* cached per URL until invalidated.
*/
@Injectable({ providedIn: 'root' })
export class BlobUrlService {
private readonly http = inject(HttpClient);
private readonly cache = new Map<string, Promise<string | null>>();
/** Bumped when an avatar changes, so components re-request it. */
private readonly versions = signal<Readonly<Record<string, number>>>({});
constructor() {
const auth = inject(AuthService);
effect(() => {
auth.sessionEpoch();
this.clear();
});
}
/** An object URL for the resource, or null if it doesn't exist. */
get(url: string): Promise<string | null> {
let entry = this.cache.get(url);
if (!entry) {
entry = firstValueFrom(this.http.get(url, { responseType: 'blob' })).then(
(blob) => URL.createObjectURL(blob),
() => {
this.cache.delete(url);
return null;
},
);
this.cache.set(url, entry);
}
return entry;
}
/** Version counter for a URL; read it in a computed/resource to reload after `invalidate`. */
version(url: string): number {
return this.versions()[url] ?? 0;
}
/** Forget a cached resource (e.g. an avatar that was replaced). */
invalidate(url: string): void {
const entry = this.cache.get(url);
this.cache.delete(url);
void entry?.then((objectUrl) => objectUrl && URL.revokeObjectURL(objectUrl));
this.versions.update((v) => ({ ...v, [url]: (v[url] ?? 0) + 1 }));
}
/** Downloads a protected file and saves it under its original name. */
async download(url: string, fileName: string): Promise<void> {
const blob = await firstValueFrom(this.http.get(url, { responseType: 'blob' }));
const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = objectUrl;
anchor.download = fileName;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
setTimeout(() => URL.revokeObjectURL(objectUrl), 10_000);
}
private clear(): void {
for (const entry of this.cache.values()) {
void entry.then((objectUrl) => objectUrl && URL.revokeObjectURL(objectUrl));
}
this.cache.clear();
}
}- The cache stores promises, not URLs. Fifty messages from the same sender ask for the same avatar during one render; the first call starts the download and stores its promise, and the other 49 get that promise — the same single-flight idea as the token refresh of topic 16. A failed download is removed from the cache, so the next render can try again, and resolves to
null. responseType: 'blob'makesHttpClientreturn the body as binary data instead of parsing JSON.versionsis a signal of counters per URL.invalidate(url)— called when a user changes their avatar — drops the cached entry, frees the old blob URL withURL.revokeObjectURLand increments the counter. Components that readversion(url)inside a signal-based loader load the image again (the next step).- On sign-out the effect that reads
sessionEpochclears the whole cache. The images of one user must not be shown to the next user of the same tab, and blob URLs hold memory until revoked. download(url, fileName)saves a protected attachment (topic 19): it creates a temporary<a download>element, clicks it and revokes the URL ten seconds later.
Step 3. The avatar component
Why. Avatars appear everywhere — in the rail, the chat list, the conversation header, member lists and dialogs. A component shows the uploaded image if there is one, and coloured initials otherwise, so that every user and chat is recognisable even without a photo; it can also show a green dot for users who are online (topic 20).
Do. Create the component:
angular-ts
import {
ChangeDetectionStrategy,
Component,
computed,
inject,
input,
resource,
} from '@angular/core';
import { avatarUrl } from '../../core/api/chatex-api';
import { BlobUrlService } from '../../core/media/blob-url.service';
const COLORS = [
'bg-rose-500',
'bg-orange-500',
'bg-amber-500',
'bg-emerald-500',
'bg-teal-500',
'bg-sky-500',
'bg-blue-500',
'bg-violet-500',
'bg-fuchsia-500',
];
/** A round avatar: the uploaded image (loaded as a blob) or coloured initials, plus an online dot. */
@Component({
selector: 'app-avatar',
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
class: 'relative inline-flex shrink-0',
'[style.width.px]': 'size()',
'[style.height.px]': 'size()',
},
template: `
@if (image.value(); as src) {
<img [src]="src" alt="" class="size-full rounded-full object-cover" />
} @else {
<span
aria-hidden="true"
class="flex size-full items-center justify-center rounded-full font-semibold text-white select-none"
[class]="color()"
[style.font-size.px]="size() * 0.4"
>{{ initials() }}</span
>
}
@if (online()) {
<span
class="absolute right-0 bottom-0 block rounded-full bg-emerald-500 ring-2 ring-surface"
[style.width.px]="dot()"
[style.height.px]="dot()"
title="Online"
></span>
}
`,
})
export class Avatar {
private readonly blobs = inject(BlobUrlService);
readonly kind = input<'user' | 'chat'>('user');
readonly id = input<string | null | undefined>(null);
readonly name = input('');
readonly hasAvatar = input(false);
readonly size = input(40);
readonly online = input(false);
protected readonly dot = computed(() => Math.max(8, Math.round(this.size() * 0.28)));
protected readonly initials = computed(() => {
const words = this.name().trim().split(/\s+/).filter(Boolean);
const letters = words.length > 1 ? words[0][0] + words[1][0] : (words[0] ?? '?').slice(0, 2);
return letters.toUpperCase();
});
protected readonly color = computed(() => {
const key = this.id() ?? this.name();
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash * 31 + key.charCodeAt(i)) | 0;
}
return COLORS[Math.abs(hash) % COLORS.length];
});
protected readonly image = resource({
params: () => {
const id = this.id();
if (!id || !this.hasAvatar()) {
return undefined;
}
const url = avatarUrl[this.kind()](id);
return { url, version: this.blobs.version(url) };
},
loader: ({ params }) => this.blobs.get(params.url),
});
}- Inputs describe what to show:
kind(a user's or a chat's avatar),id,namefor the initials,hasAvatarfrom the DTO,sizein pixels andonline. The DTOs carryhasAvatar, so the component never requests an image that does not exist. hostbinds the component element's own width and height tosize():'[style.width.px]': 'size()'.initialstakes the first letters of the first two words ("Course team" → "CT"), or the first two letters of a single word.colorhashes the id (or the name) into one of nine colours, so the same user always gets the same colour on every screen.| 0keeps the hash a 32-bit integer.resource({ params, loader })is Angular's signal-based way to load data.paramsis a computation likecomputed: it readsid,hasAvatar,kindandblobs.version(url). Whenever its result changes,resourcecallsloaderwith the new parameters and exposes the result as signals:value(),isLoading(),error(). Ifparamsreturnsundefined, nothing is loaded andvalue()isundefined— here, a chat without a photo. Readingversion(url)inparamsis what makes an invalidated avatar reload.@if (image.value(); as src)shows the image once it has loaded and the initials until then (or forever if there is no image).alt=""marks the image as decorative: the name is always written next to it.
resource compared with an Observable
The same could be written with an Observable pipeline and switchMap. resource is shorter for the common case "load something whenever these signals change, show the latest result", and it cancels outdated loads by itself: if the inputs change while a load is running, the result of the old load is ignored.
Check
npm run build succeeds. The avatar appears on screen in the next chapters.