import { Component, ElementRef, ViewChild, effect, inject } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import { ChatStore } from './chat.store'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-chat', standalone: true, imports: [CommonModule, ReactiveFormsModule], templateUrl: './chat.html', styleUrl: './chat.css', }) export class Chat { readonly chatStore = inject(ChatStore); private route = inject(ActivatedRoute); @ViewChild('scrollContainer') private scrollContainer!: ElementRef; messageControl = new FormControl(''); constructor() { // Scroll to bottom when messages change effect(() => { // Accessing messages will trigger effect on change const msgs = this.chatStore.messages(); const loading = this.chatStore.isLoading(); setTimeout(() => { this.scrollToBottom(); }, 50); }); } ngOnInit() { this.route.paramMap.subscribe((params) => { const urlId = params.get('id'); if (urlId) { // If an ID exists in the URL, populate it in the store this.chatStore.setChatId(urlId); this.chatStore.fetchChatHistory(); } }); } errorMessage = ''; sendMessage() { const value = this.messageControl.value; if (value && value.trim() && !this.chatStore.isLoading()) { const words = value.trim().split(/\s+/).length; if (words > 400) { this.errorMessage = `Input must be under 400 words (currently ${words} words).`; return; } this.errorMessage = ''; this.chatStore.sendMessage(value.trim()); this.messageControl.setValue(''); } } private scrollToBottom(): void { try { const el = this.scrollContainer.nativeElement; el.scrollTop = el.scrollHeight; } catch (err) {} } }