import { Injectable, inject, signal } from '@angular/core'; import { LiveAnnouncer } from '@angular/cdk/a11y'; export interface Toast { id: number; text: string; kind: 'ok' | 'error'; } /** Short messages in the corner; also read out by screen readers. */ @Injectable({ providedIn: 'root' }) export class ToastService { private announcer = inject(LiveAnnouncer); private next = 1; readonly toasts = signal([]); ok(text: string): void { this.show(text, 'ok', 4000); } error(text: string): void { this.show(text, 'error', 8000); } dismiss(id: number): void { this.toasts.update(list => list.filter(t => t.id !== id)); } private show(text: string, kind: Toast['kind'], ms: number): void { const id = this.next++; this.toasts.update(list => [...list.slice(-3), { id, text, kind }]); this.announcer.announce(text, kind === 'error' ? 'assertive' : 'polite'); setTimeout(() => this.dismiss(id), ms); } }