77 lines
2.2 KiB
TypeScript
77 lines
2.2 KiB
TypeScript
import { Component, ElementRef, ViewChild, effect, inject } from '@angular/core';
|
|
import { CommonModule } from '@angular/common';
|
|
import { FormControl, ReactiveFormsModule } from '@angular/forms';
|
|
import { ChatStore, MessageStore } from './chat.store';
|
|
import { ActivatedRoute } from '@angular/router';
|
|
import { Sidebar } from '../core/layout/sidebar/sidebar';
|
|
import { Loader } from '../shared/loader/loader';
|
|
import { InfiniteScroll } from '../core/directives/infinite-scroll';
|
|
import { environment } from '../../environments/environment.development';
|
|
|
|
@Component({
|
|
selector: 'app-chat',
|
|
standalone: true,
|
|
imports: [CommonModule, ReactiveFormsModule, Sidebar, Loader, InfiniteScroll],
|
|
templateUrl: './chat.html',
|
|
styleUrl: './chat.css',
|
|
})
|
|
export class Chat {
|
|
protected readonly messageStore = inject(MessageStore);
|
|
private readonly route = inject(ActivatedRoute);
|
|
|
|
@ViewChild('scrollContainer') private scrollContainer!: ElementRef;
|
|
|
|
messageControl = new FormControl('');
|
|
|
|
constructor() {
|
|
// Scroll to bottom when messages change
|
|
effect(() => {
|
|
const loading = this.messageStore.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.messageStore.setChatId(urlId);
|
|
this.messageStore.fetchChatHistory();
|
|
}
|
|
});
|
|
}
|
|
|
|
errorMessage = '';
|
|
|
|
sendMessage() {
|
|
const value = this.messageControl.value;
|
|
if (value && value.trim() && !this.messageStore.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.messageStore.sendMessage(value.trim());
|
|
this.messageControl.setValue('');
|
|
}
|
|
}
|
|
|
|
private scrollToBottom(): void {
|
|
try {
|
|
const el = this.scrollContainer.nativeElement;
|
|
el.scrollTop = el.scrollHeight;
|
|
} catch (err) {
|
|
if (!environment.production) console.log(err);
|
|
}
|
|
}
|
|
|
|
protected loadMoreChats() {
|
|
this.messageStore.loadOlderMessages();
|
|
}
|
|
}
|